aws-durable-execution-sdk 1.0.0

Rust SDK for AWS Lambda Durable Functions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
//! Plugin frames reach the handler, `.spawn()`ed operations, combinator
//! inputs and map items through the SDK's spawn paths (#126).

#![cfg(feature = "test-util")]
#![expect(clippy::expect_used)] // reason: test assertions

use std::cell::Cell;
use std::future::IntoFuture as _;

use aws_durable_execution_sdk as durable;
use durable::plugin::{InvocationInfo, Plugin, PluginFactory};
use durable::test_util::LocalRunner;
use durable::{BoxError, DurableContext, Options};

thread_local! {
    /// Set while a `wrap_invocation` of this thread's plugin is entered.
    static IN_INVOCATION: Cell<bool> = const { Cell::new(false) };
}

fn in_invocation() -> bool {
    IN_INVOCATION.with(Cell::get)
}

/// The current frames as the wraps entered on this thread show them: `I`
/// for the invocation, then the name of each user function, outermost
/// first. Every test plugin below that has wraps pushes onto [`IN_FN`].
fn frames() -> Vec<String> {
    IN_FN.with(|f| f.borrow().clone())
}

/// `[I, rest..]` as owned strings.
fn path(rest: &[&str]) -> Vec<String> {
    std::iter::once("I")
        .chain(rest.iter().copied())
        .map(str::to_owned)
        .collect()
}

fn enter_invocation(next: &mut dyn FnMut()) {
    IN_FN.with(|f| f.borrow_mut().push("I".to_owned()));
    next();
    IN_FN.with(|f| f.borrow_mut().pop());
}

fn enter_user_function(info: &durable::plugin::OperationInfo, next: &mut dyn FnMut()) {
    IN_FN.with(|f| {
        f.borrow_mut()
            .push(info.name().unwrap_or_default().to_owned());
    });
    next();
    IN_FN.with(|f| f.borrow_mut().pop());
}

/// One user-function wrap: the operation's name and whether its info is
/// virtual.
type WrapSeen = (String, bool);

/// A plugin whose wraps make the frames readable with [`frames`], and which
/// logs every user-function wrap it enters.
#[derive(Clone, Default)]
struct Wraps(std::sync::Arc<std::sync::Mutex<Vec<WrapSeen>>>);

impl Plugin for Wraps {
    fn wrap_invocation(&self, _info: &InvocationInfo, next: &mut dyn FnMut()) {
        enter_invocation(next);
    }

    fn wrap_user_function(&self, info: &durable::plugin::OperationInfo, next: &mut dyn FnMut()) {
        self.0.lock().expect("not poisoned").push((
            info.name().unwrap_or_default().to_owned(),
            info.is_virtual(),
        ));
        enter_user_function(info, next);
    }
}

/// Creates a clone of one plugin for every invocation.
struct Each<P>(P);

impl<P: Plugin + Clone + 'static> PluginFactory for Each<P> {
    fn create_plugin(&self, _info: &InvocationInfo) -> Result<Option<Box<dyn Plugin>>, BoxError> {
        Ok(Some(Box::new(self.0.clone())))
    }
}

/// Runs `handler` through a [`LocalRunner`] with `plugin` registered.
async fn run_with<P, F, Fut, O>(plugin: P, handler: F) -> durable::test_util::TestResult<O>
where
    P: Plugin + Clone + 'static,
    F: Fn((), DurableContext) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<O, BoxError>> + Send + 'static,
    O: serde::Serialize + serde::de::DeserializeOwned + Send + 'static,
{
    LocalRunner::new()
        .options(
            Options::builder()
                .plugin(Each(plugin))
                .build()
                .expect("valid options"),
        )
        .run(handler, ())
        .await
        .expect("runner")
}

/// Polls `fut` once with a no-op waker.
fn poll_once<F: Future + Unpin>(fut: &mut F) -> bool {
    let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
    std::pin::Pin::new(fut).poll(&mut cx).is_ready()
}

/// What the handler gives the [`Poker`] plugin to poll.
enum Given {
    /// A step future the handler claimed with `.future()`.
    Claimed(durable::DurableFuture<u32>),
    /// The conversion of an unclaimed `try_join_all` builder to its future.
    Unclaimed(Box<dyn FnOnce() -> durable::DurableFuture<Vec<u32>> + Send>),
}

type GivenSlot = std::sync::Arc<std::sync::Mutex<Option<Given>>>;

/// Takes what the slot holds, polls it once, and puts a claimed future
/// back so the handler can await it.
fn poke(slot: &GivenSlot) {
    let given = slot.lock().expect("not poisoned").take();
    match given {
        Some(Given::Claimed(mut fut)) => {
            poll_once(&mut fut);
            *slot.lock().expect("not poisoned") = Some(Given::Claimed(fut));
        }
        Some(Given::Unclaimed(convert)) => {
            let mut fut = convert();
            poll_once(&mut fut);
        }
        None => {}
    }
}

/// Pokes the slot in the synchronous part of the user-function start hook
/// of step `trigger`.
#[derive(Clone, Default)]
struct Poker(GivenSlot);

impl Plugin for Poker {
    fn on_user_function_start(
        &self,
        info: &durable::plugin::OperationInfo,
    ) -> durable::plugin::HookWork {
        if info.name() == Some("trigger") {
            poke(&self.0);
        }
        Ok(None)
    }
}

/// Where [`guard_reach_matches_step_body_check`] polls what the handler gave.
#[derive(Debug, Clone, Copy)]
enum Reach {
    /// A claimed step future, in a synchronous start hook.
    ClaimedInHook,
    /// A claimed step future, in a step body.
    ClaimedInBody,
    /// An unclaimed `try_join_all` builder, converted and polled in a
    /// synchronous start hook.
    UnclaimedInHook,
}

/// #126 rule 8.3: the plugin guard reaches what the step-body check
/// reaches. Polling a future the handler already claimed, from a start
/// hook or a step body, claims nothing and records no error. Polling an
/// unclaimed combinator from a start hook claims its ID under the guard
/// and fails the execution with the context usage error naming plugin
/// code. Every poll runs synchronously on the SDK task that runs the hook
/// or body, never on a hook-work task, where the task-ownership check
/// would fail first.
#[tokio::test]
async fn guard_reach_matches_step_body_check() {
    for reach in [
        Reach::ClaimedInHook,
        Reach::ClaimedInBody,
        Reach::UnclaimedInHook,
    ] {
        let poker = Poker::default();
        let slot = std::sync::Arc::clone(&poker.0);
        let result = run_with(poker, move |_event: (), ctx: DurableContext| {
            let slot = std::sync::Arc::clone(&slot);
            async move {
                let given = match reach {
                    Reach::ClaimedInHook | Reach::ClaimedInBody => {
                        Given::Claimed(ctx.step(|_| async { Ok(7_u32) }).name("given").future())
                    }
                    Reach::UnclaimedInHook => {
                        let input = ctx.step(|_| async { Ok(7_u32) }).name("input").future();
                        let join = ctx.try_join_all([input]).name("j");
                        Given::Unclaimed(Box::new(move || join.future()))
                    }
                };
                *slot.lock().expect("not poisoned") = Some(given);
                let body_slot = std::sync::Arc::clone(&slot);
                ctx.step(move |_| async move {
                    if matches!(reach, Reach::ClaimedInBody) {
                        poke(&body_slot);
                    }
                    Ok(0_u32)
                })
                .name("trigger")
                .await?;
                let given = slot.lock().expect("not poisoned").take();
                match given {
                    Some(Given::Claimed(fut)) => Ok(fut.await?),
                    _ => Ok(0_u32),
                }
            }
        })
        .await;
        let message = result
            .error()
            .and_then(durable::WireError::error_message)
            .unwrap_or_default()
            .to_owned();
        match reach {
            Reach::ClaimedInHook | Reach::ClaimedInBody => {
                assert_eq!(result.output(), Some(&7), "{reach:?}: {message}");
            }
            Reach::UnclaimedInHook => {
                assert_eq!(result.output(), None, "{reach:?}");
                assert!(message.contains("plugin code"), "{reach:?}: {message}");
            }
        }
    }
}

/// Which callback of the step's SDK span [`PanicsInSpan`] panics in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SpanCallback {
    Enter,
    Exit,
}

/// A layer that panics once, in the first `on_enter` or `on_exit` of a
/// `durable_operation` span.
struct PanicsInSpan {
    at: SpanCallback,
    armed: std::sync::atomic::AtomicBool,
}

impl PanicsInSpan {
    fn hit<S>(&self, id: &tracing::span::Id, ctx: &tracing_subscriber::layer::Context<'_, S>)
    where
        S: tracing::Subscriber + for<'l> tracing_subscriber::registry::LookupSpan<'l>,
    {
        let operation = ctx
            .span(id)
            .is_some_and(|span| span.name() == "durable_operation");
        // The subscriber panic under test, once.
        let fire = operation && self.armed.swap(false, std::sync::atomic::Ordering::SeqCst);
        assert!(!fire, "span subscriber panics");
    }
}

impl<S> tracing_subscriber::Layer<S> for PanicsInSpan
where
    S: tracing::Subscriber + for<'l> tracing_subscriber::registry::LookupSpan<'l>,
{
    fn on_enter(&self, id: &tracing::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
        if self.at == SpanCallback::Enter {
            self.hit(id, &ctx);
        }
    }

    fn on_exit(&self, id: &tracing::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
        if self.at == SpanCallback::Exit {
            self.hit(id, &ctx);
        }
    }
}

/// #126 rule 6.2: the gateway enters a task's span inside its
/// `catch_unwind`, so a subscriber panic while the SDK span of a
/// `.spawn()`ed step is entered or exited is a task panic, and the
/// invocation fails with it. Current-thread, so the thread-local subscriber
/// sees the spawned step's task.
#[tokio::test]
async fn span_subscriber_panic_caught_by_gateway() {
    use tracing_subscriber::layer::SubscriberExt as _;

    for at in [SpanCallback::Enter, SpanCallback::Exit] {
        let _guard = test_tracing::install_test_subscriber(tracing_subscriber::registry().with(
            PanicsInSpan {
                at,
                armed: std::sync::atomic::AtomicBool::new(true),
            },
        ));
        #[expect(clippy::disallowed_methods)]
        // reason: the test observes the panic the run resumes, which only a
        // task's JoinHandle reports.
        let joined = tokio::spawn(async {
            LocalRunner::new()
                .run(
                    |_event: (), ctx: DurableContext| async move {
                        let handle = ctx.step(|_| async { Ok(1_u32) }).name("s").spawn();
                        Ok::<_, BoxError>(handle.await?)
                    },
                    (),
                )
                .await
        })
        .await;
        let payload = joined.expect_err("the invocation fails").into_panic();
        let message = payload
            .downcast_ref::<&str>()
            .map(|s| (*s).to_owned())
            .or_else(|| payload.downcast_ref::<String>().cloned())
            .unwrap_or_default();
        assert_eq!(message, "span subscriber panics", "{at:?}");
    }
}

/// #126 rules 5.2 and 6.2: a `.spawn()`ed step in child `c` captures the
/// frames current at `.spawn()`, and its task's gateway enters them at
/// every poll, on whichever worker polls it: the body reads `[I, c, step]`
/// before and after each of its awaits.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn spawned_task_captures_creating_frames() {
    let result = run_with(
        Wraps::default(),
        |_event: (), ctx: DurableContext| async move {
            Ok(ctx
                .run_in_child_context(|child| async move {
                    let handle = child
                        .step(|_| async {
                            let mut seen = vec![frames()];
                            for _ in 0..8 {
                                tokio::time::sleep(std::time::Duration::from_millis(1)).await;
                                seen.push(frames());
                            }
                            Ok(seen)
                        })
                        .name("step")
                        .spawn();
                    Ok(handle.await?)
                })
                .name("c")
                .await?)
        },
    )
    .await;
    let seen = result.output().expect("the run succeeded");
    assert_eq!(seen.len(), 9, "{seen:?}");
    for frames in seen {
        assert_eq!(*frames, path(&["c", "step"]), "{seen:?}");
    }
}

/// #126 rule 5.2: a `.spawn()`ed step's handle that child `a` hands to a
/// `race` in child `b` keeps the frames the step captured at `.spawn()`:
/// the body reads `[I, a, step]`, never `b`'s.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn spawned_handle_into_combinator_keeps_frames() {
    let result = run_with(
        Wraps::default(),
        |_event: (), ctx: DurableContext| async move {
            let (handle_tx, handle_rx) = tokio::sync::oneshot::channel();
            let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
            let a = ctx
                .run_in_child_context(move |child| async move {
                    let go = std::sync::Arc::new(tokio::sync::Notify::new());
                    let body_go = std::sync::Arc::clone(&go);
                    let handle = child
                        .step(move |_| async move {
                            body_go.notified().await;
                            Ok(frames())
                        })
                        .name("step")
                        .spawn();
                    if handle_tx.send((handle, go)).is_err() {
                        return Err::<u32, BoxError>("b stopped".into());
                    }
                    // Child `a` stays open until `b` raced the handle.
                    done_rx.await?;
                    Ok(0_u32)
                })
                .name("a")
                .spawn();
            let b = ctx
                .run_in_child_context(move |child| async move {
                    let (handle, go) = handle_rx.await?;
                    go.notify_one();
                    let won = child.race([handle]).name("r").await?;
                    let _done = done_tx.send(());
                    Ok::<_, BoxError>(won)
                })
                .name("b")
                .spawn();
            let (a, b) = tokio::join!(a, b);
            a?;
            Ok::<_, BoxError>(b?)
        },
    )
    .await;
    assert_eq!(result.output(), Some(&path(&["a", "step"])));
}

/// The frames each item or branch body of one container read.
type Container = Vec<Vec<String>>;

/// #126 rule 5.3: items of a `map` and branches of a `parallel` and a
/// `parallel_mixed` capture their task context at dispatch inside the
/// container's poll, so each body reads `[I, container, item]`, in both
/// nesting modes. A flat item's info is virtual; a normal item's is not.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn map_items_and_branches_capture_container_frames() {
    for mode in [
        durable::builders::map_parallel::NestingMode::Normal,
        durable::builders::map_parallel::NestingMode::Flat,
    ] {
        let wraps = Wraps::default();
        let log = std::sync::Arc::clone(&wraps.0);
        let result = run_with(wraps, move |_event: (), ctx: DurableContext| async move {
            let map = ctx
                .map(vec![1_u32, 2], |_child, _item, _index| async move {
                    Ok(frames())
                })
                .name("m")
                .item_namer(|_item, index| format!("m{index}"))
                .nesting(mode)
                .await?;
            let parallel = ctx
                .parallel(vec![
                    durable::Branch::new("p0", |_child| async move { Ok(frames()) }),
                    durable::Branch::new("p1", |_child| async move { Ok(frames()) }),
                ])
                .name("p")
                .nesting(mode)
                .await?;
            let mut branches = durable::BranchSet::new();
            let x0 = branches.add("x0", |_child| async move { Ok(frames()) });
            let x1 = branches.add("x1", |_child| async move { Ok(frames()) });
            ctx.parallel_mixed(branches).name("x").nesting(mode).await?;
            let mixed = vec![x0.into_result()?, x1.into_result()?];
            Ok::<(Container, Container, Container), BoxError>((map, parallel, mixed))
        })
        .await;
        let (map, parallel, mixed) = result.output().expect("the run succeeded");
        assert_eq!(*map, [path(&["m", "m0"]), path(&["m", "m1"])], "{mode:?}");
        assert_eq!(
            *parallel,
            [path(&["p", "p0"]), path(&["p", "p1"])],
            "{mode:?}"
        );
        assert_eq!(*mixed, [path(&["x", "x0"]), path(&["x", "x1"])], "{mode:?}");
        let flat = matches!(mode, durable::builders::map_parallel::NestingMode::Flat);
        let seen = log.lock().expect("not poisoned").clone();
        for item in ["m0", "m1", "p0", "p1", "x0", "x1"] {
            let virtual_flags: Vec<bool> = seen
                .iter()
                .filter(|(name, _)| name == item)
                .map(|(_, is_virtual)| *is_virtual)
                .collect();
            assert!(!virtual_flags.is_empty(), "{mode:?} {item}: {seen:?}");
            assert!(
                virtual_flags.iter().all(|v| *v == flat),
                "{mode:?} {item}: {seen:?}"
            );
        }
        for container in ["m", "p", "x"] {
            assert!(
                seen.iter().any(|(name, v)| name == container && !v),
                "{mode:?} {container}: {seen:?}"
            );
        }
    }
}

/// #126 rule 5.3: the root task captures its task context at `spawn_root`
/// dispatch, so the handler runs in the invocation frame only.
#[tokio::test]
async fn root_task_captures_invocation_frame() {
    let result = run_with(
        Wraps::default(),
        |_event: (), _ctx: DurableContext| async move { Ok::<_, BoxError>(frames()) },
    )
    .await;
    assert_eq!(result.output(), Some(&path(&[])));
}

/// Where a hook ran, and the frames it read.
type HookSeen = (&'static str, Vec<String>);

/// Wraps as [`Wraps`] does, and records, for step `step`, the frames of
/// its user-function start hook's synchronous part and of its returned
/// future.
#[derive(Clone, Default)]
struct WorkProbe(std::sync::Arc<std::sync::Mutex<Vec<HookSeen>>>);

impl Plugin for WorkProbe {
    fn wrap_invocation(&self, _info: &InvocationInfo, next: &mut dyn FnMut()) {
        enter_invocation(next);
    }

    fn wrap_user_function(&self, info: &durable::plugin::OperationInfo, next: &mut dyn FnMut()) {
        enter_user_function(info, next);
    }

    fn on_user_function_start(
        &self,
        info: &durable::plugin::OperationInfo,
    ) -> durable::plugin::HookWork {
        if info.name() != Some("step") {
            return Ok(None);
        }
        self.0
            .lock()
            .expect("not poisoned")
            .push(("sync", frames()));
        let log = std::sync::Arc::clone(&self.0);
        Ok(Some(Box::pin(async move {
            log.lock().expect("not poisoned").push(("future", frames()));
            Ok(())
        })))
    }
}

/// #126 rules 5.5 and 14: a hook future runs on its own plugin-work task,
/// which carries no task context. In child `c`, the start hook's
/// synchronous part runs in the poller's frames `[I, c]`, and its future
/// reads no frame at all.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn plugin_work_task_carries_no_frames() {
    let probe = WorkProbe::default();
    let log = std::sync::Arc::clone(&probe.0);
    let result = run_with(probe, |_event: (), ctx: DurableContext| async move {
        Ok(ctx
            .run_in_child_context(|child| async move {
                Ok(child.step(|_| async { Ok(1_u32) }).name("step").await?)
            })
            .name("c")
            .await?)
    })
    .await;
    assert_eq!(result.output(), Some(&1));
    let seen = log.lock().expect("not poisoned").clone();
    assert_eq!(
        seen,
        [("sync", path(&["c"])), ("future", Vec::new())],
        "{seen:?}"
    );
}

/// #126 rules 6.2 and #151: in child `c`, a `.spawn()`ed step whose handle
/// is dropped keeps running in the frames it captured. Its body waits 1 s,
/// then reads `[I, c, step]`, while `c` awaits a 2 s durable wait; the step
/// settles.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn dropped_handle_task_keeps_frames() {
    let read = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let handler_read = std::sync::Arc::clone(&read);
    let run = run_with(Wraps::default(), move |_event: (), ctx: DurableContext| {
        let read = std::sync::Arc::clone(&handler_read);
        async move {
            Ok(ctx
                .run_in_child_context(move |child| async move {
                    drop(
                        child
                            .step(move |_| async move {
                                tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                                read.lock().expect("not poisoned").push(frames());
                                Ok(1_u32)
                            })
                            .name("step")
                            .spawn(),
                    );
                    child
                        .wait(std::time::Duration::from_secs(2))
                        .name("w")
                        .await?;
                    Ok(0_u32)
                })
                .name("c")
                .await?)
        }
    });
    let result = tokio::time::timeout(std::time::Duration::from_secs(5), run)
        .await
        .expect("the run ends within 5 s");
    assert_eq!(result.output(), Some(&0));
    let step = result.operation("step").expect("the step recorded");
    assert_eq!(step.status(), durable::OperationStatus::Succeeded);
    let read = read.lock().expect("not poisoned").clone();
    assert_eq!(read, [path(&["c", "step"])]);
}

/// Emits a `probe` event when dropped.
struct EmitsOnDrop;

impl Drop for EmitsOnDrop {
    fn drop(&mut self) {
        tracing::info!(target: "probe", "drop");
    }
}

/// #126 rules 5.1 and 6.2, without plugins: a `.spawn()`ed step's task
/// enters the span current at `.spawn()` on every poll and on its drop. Its
/// body emits an event, then holds a guard that emits one when dropped and
/// stays pending; the enclosing scope closes, which aborts the task. Both
/// events are inside `outer`.
///
/// A child body's scope closing is what aborts the task, so `outer`
/// instruments the child body, where the step is spawned, rather than the
/// handler.
/// Current-thread, so the thread-local subscriber sees every event.
#[tokio::test]
async fn span_entered_on_poll_and_on_drop() {
    use tracing::Instrument as _;
    use tracing_subscriber::layer::SubscriberExt as _;

    let names = ScopeNames::default();
    let _guard =
        test_tracing::install_test_subscriber(tracing_subscriber::registry().with(names.clone()));
    let runner = LocalRunner::new();
    let run = runner.run(
        |_event: (), ctx: DurableContext| async move {
            Ok::<_, BoxError>(
                ctx.run_in_child_context(|child| {
                    async move {
                        let ran = std::sync::Arc::new(tokio::sync::Notify::new());
                        let body_ran = std::sync::Arc::clone(&ran);
                        drop(
                            child
                                .step(move |_| async move {
                                    tracing::info!(target: "probe", "body");
                                    let _guard = EmitsOnDrop;
                                    body_ran.notify_one();
                                    std::future::pending::<()>().await;
                                    Ok(0_u32)
                                })
                                .name("s")
                                .spawn(),
                        );
                        ran.notified().await;
                        Ok(1_u32)
                    }
                    .instrument(tracing::info_span!("outer"))
                })
                .name("c")
                .await?,
            )
        },
        (),
    );
    let result = tokio::time::timeout(std::time::Duration::from_secs(5), run)
        .await
        .expect("the run ends within 5 s")
        .expect("runner");
    assert_eq!(result.output(), Some(&1));
    let seen = names.0.lock().expect("not poisoned").clone();
    assert_eq!(seen.len(), 2, "a body and a drop event: {seen:?}");
    for scope in &seen {
        assert!(scope.contains(&"outer"), "{seen:?}");
    }
}

/// Reads the frames into its log when dropped.
struct ReadsOnDrop(std::sync::Arc<std::sync::Mutex<Vec<Vec<String>>>>);

impl Drop for ReadsOnDrop {
    fn drop(&mut self) {
        self.0.lock().expect("not poisoned").push(frames());
    }
}

/// #126 rules 3 and 4.5: when a scope closes, a pending body is dropped
/// inside the current frames and the wraps of the plugins that started it.
/// A `.spawn()`ed step `op` in child `c` holds a guard and stays pending on
/// `std::future::pending()`; `c` returns, its scope closes, and the guard
/// reads `[I, c, op]` in its `Drop`.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn dropped_body_drops_inside_frames() {
    let read = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let handler_read = std::sync::Arc::clone(&read);
    let run = run_with(Wraps::default(), move |_event: (), ctx: DurableContext| {
        let read = std::sync::Arc::clone(&handler_read);
        async move {
            Ok(ctx
                .run_in_child_context(move |child| async move {
                    let ran = std::sync::Arc::new(tokio::sync::Notify::new());
                    let body_ran = std::sync::Arc::clone(&ran);
                    drop(
                        child
                            .step(move |_| async move {
                                let _guard = ReadsOnDrop(read);
                                body_ran.notify_one();
                                std::future::pending::<()>().await;
                                Ok(0_u32)
                            })
                            .name("op")
                            .spawn(),
                    );
                    ran.notified().await;
                    Ok(1_u32)
                })
                .name("c")
                .await?)
        }
    });
    let result = tokio::time::timeout(std::time::Duration::from_secs(5), run)
        .await
        .expect("the run ends within 5 s");
    assert_eq!(result.output(), Some(&1));
    let read = read.lock().expect("not poisoned").clone();
    assert_eq!(read, [path(&["c", "op"])]);
}

/// Without plugins, no code runs in a frame: the handler, a `.spawn()`ed
/// step and a map item read no frame.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn without_plugins_no_code_is_wrapped() {
    let result = LocalRunner::new()
        .run(
            |_event: (), ctx: DurableContext| async move {
                let in_handler = frames();
                let spawned = ctx.step(|_| async { Ok(frames()) }).name("spawned").spawn();
                let items = ctx
                    .map(
                        vec![1_u32],
                        |_child, _item, _index| async move { Ok(frames()) },
                    )
                    .name("m")
                    .await?;
                let mut seen = vec![in_handler, spawned.await?];
                seen.extend(items);
                Ok::<_, BoxError>(seen)
            },
            (),
        )
        .await
        .expect("runner");
    assert_eq!(result.output(), Some(&vec![Vec::<String>::new(); 3]));
}

/// Records, at the synchronous call of `on_invocation_end`, whether the
/// invocation wrap was entered.
struct EndProbe(std::sync::Arc<std::sync::Mutex<Vec<bool>>>);

impl Plugin for EndProbe {
    fn wrap_invocation(&self, _info: &InvocationInfo, next: &mut dyn FnMut()) {
        let outer = IN_INVOCATION.with(|flag| flag.replace(true));
        next();
        IN_INVOCATION.with(|flag| flag.set(outer));
    }

    fn on_invocation_end<'a>(
        &'a self,
        _info: &'a durable::plugin::InvocationEndInfo,
    ) -> durable::plugin::HookFuture<'a> {
        self.0.lock().expect("not poisoned").push(in_invocation());
        Box::pin(std::future::ready(Ok(())))
    }
}

struct EndFactory(std::sync::Arc<std::sync::Mutex<Vec<bool>>>);

impl PluginFactory for EndFactory {
    fn create_plugin(&self, _info: &InvocationInfo) -> Result<Option<Box<dyn Plugin>>, BoxError> {
        Ok(Some(Box::new(EndProbe(std::sync::Arc::clone(&self.0)))))
    }
}

/// `wrap_invocation` is active while `on_invocation_end` runs, on every
/// invocation, the suspending one and the final one.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_invocation_wrap_is_active_during_on_invocation_end() {
    let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let result = LocalRunner::new()
        .options(
            Options::builder()
                .plugin(EndFactory(std::sync::Arc::clone(&seen)))
                .build()
                .expect("valid options"),
        )
        .run(
            |_event: (), ctx: DurableContext| async move {
                ctx.wait(std::time::Duration::from_secs(1))
                    .name("w")
                    .await?;
                Ok::<_, BoxError>(1_u32)
            },
            (),
        )
        .await
        .expect("runner");
    assert_eq!(result.output(), Some(&1));
    let seen = seen.lock().expect("not poisoned").clone();
    assert_eq!(
        seen,
        [true, true],
        "one end hook per invocation, each inside the wrap"
    );
}

/// The names of the spans in scope of each `probe` event.
#[derive(Clone, Default)]
struct ScopeNames(std::sync::Arc<std::sync::Mutex<Vec<Vec<&'static str>>>>);

impl<S> tracing_subscriber::Layer<S> for ScopeNames
where
    S: tracing::Subscriber + for<'l> tracing_subscriber::registry::LookupSpan<'l>,
{
    fn on_event(&self, event: &tracing::Event<'_>, ctx: tracing_subscriber::layer::Context<'_, S>) {
        if event.metadata().target() != "probe" {
            return;
        }
        let names = ctx
            .event_scope(event)
            .map(|scope| scope.from_root().map(|span| span.name()).collect())
            .unwrap_or_default();
        self.0.lock().expect("not poisoned").push(names);
    }
}

/// A step created with `.future()` inside span `created` and joined inside
/// span `joined` runs its body inside `created`, the span current where
/// the user created the operation, not inside `joined`.
#[tokio::test]
async fn a_future_step_runs_inside_the_span_of_its_creation() {
    use tracing::Instrument as _;
    use tracing_subscriber::layer::SubscriberExt as _;

    let names = ScopeNames::default();
    let _guard =
        test_tracing::install_test_subscriber(tracing_subscriber::registry().with(names.clone()));
    let result = LocalRunner::new()
        .run(
            |_event: (), ctx: DurableContext| async move {
                let step = {
                    let _created = tracing::info_span!("created").entered();
                    ctx.step(|_| async {
                        tracing::info!(target: "probe", "in body");
                        Ok(1_u32)
                    })
                    .name("s")
                    .future()
                };
                let joined = ctx
                    .try_join_all([step])
                    .name("j")
                    .into_future()
                    .instrument(tracing::info_span!("joined"))
                    .await?;
                Ok::<_, BoxError>(joined)
            },
            (),
        )
        .await
        .expect("runner");
    assert_eq!(result.output(), Some(&vec![1]));
    let seen = names.0.lock().expect("not poisoned").clone();
    assert!(!seen.is_empty(), "the body ran");
    for scope in &seen {
        assert!(scope.contains(&"created"), "{scope:?}");
        assert!(!scope.contains(&"joined"), "{scope:?}");
    }
}

/// Records the user-function hooks of parallel branches, and the active
/// user-function wraps when a step's start hook runs.
struct FnHooks(std::sync::Arc<std::sync::Mutex<Vec<String>>>);

thread_local! {
    /// The user functions whose wrap is entered on this thread.
    static IN_FN: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
}

impl Plugin for FnHooks {
    fn wrap_user_function(&self, info: &durable::plugin::OperationInfo, next: &mut dyn FnMut()) {
        IN_FN.with(|f| {
            f.borrow_mut()
                .push(info.name().unwrap_or_default().to_owned());
        });
        next();
        IN_FN.with(|f| f.borrow_mut().pop());
    }

    fn on_user_function_start(
        &self,
        info: &durable::plugin::OperationInfo,
    ) -> durable::plugin::HookWork {
        let name = info.name().unwrap_or_default();
        let line = match info.sub_type() {
            Some("ParallelBranch") => {
                format!(
                    "fn-start {name} parent={}",
                    info.parent_id().unwrap_or_default()
                )
            }
            Some("Step") => format!(
                "step-start {name} in {:?}",
                IN_FN.with(|f| f.borrow().clone())
            ),
            _ => return Ok(None),
        };
        self.0.lock().expect("not poisoned").push(line);
        Ok(None)
    }

    fn on_user_function_end(
        &self,
        info: &durable::plugin::OperationInfo,
        outcome: Result<(), &durable::WireError>,
    ) -> durable::plugin::HookWork {
        if info.sub_type() == Some("ParallelBranch") {
            let status = if outcome.is_ok() {
                "SUCCEEDED"
            } else {
                "FAILED"
            };
            self.0.lock().expect("not poisoned").push(format!(
                "fn-end {} {status} parent={}",
                info.name().unwrap_or_default(),
                info.parent_id().unwrap_or_default()
            ));
        }
        Ok(None)
    }
}

struct FnFactory(std::sync::Arc<std::sync::Mutex<Vec<String>>>);

impl PluginFactory for FnFactory {
    fn create_plugin(&self, _info: &InvocationInfo) -> Result<Option<Box<dyn Plugin>>, BoxError> {
        Ok(Some(Box::new(FnHooks(std::sync::Arc::clone(&self.0)))))
    }
}

async fn run_fn_hooks<F, Fut>(
    handler: F,
) -> (durable::test_util::TestResult<Vec<String>>, Vec<String>)
where
    F: Fn((), DurableContext) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<Vec<String>, BoxError>> + Send + 'static,
{
    let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let result = LocalRunner::new()
        .options(
            Options::builder()
                .plugin(FnFactory(std::sync::Arc::clone(&log)))
                .build()
                .expect("valid options"),
        )
        .run(handler, ())
        .await
        .expect("runner");
    let lines = log.lock().expect("not poisoned").clone();
    (result, lines)
}

/// Shaped like conformance 10-12: two parallel branches at concurrency 1
/// get one user-function start and end each, in order, each with the
/// parallel as its parent.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn parallel_branches_get_user_function_hooks_in_order() {
    let (result, lines) = run_fn_hooks(|_event: (), ctx: DurableContext| async move {
        let branches = vec![
            durable::Branch::new("0", |_child| async move { Ok("task-1".to_owned()) }),
            durable::Branch::new("1", |_child| async move { Ok("task-2".to_owned()) }),
        ];
        Ok(ctx
            .parallel(branches)
            .name("parallel")
            .max_concurrency(1)
            .await?)
    })
    .await;
    assert_eq!(
        result.output(),
        Some(&vec!["task-1".to_owned(), "task-2".to_owned()])
    );
    let parallel = result.operation("parallel").expect("the parallel ran");
    let id = parallel.id();
    assert_eq!(
        lines,
        [
            format!("fn-start 0 parent={id}"),
            format!("fn-end 0 SUCCEEDED parent={id}"),
            format!("fn-start 1 parent={id}"),
            format!("fn-end 1 SUCCEEDED parent={id}"),
        ]
    );
}

/// Re-entry: a step inside a parallel branch fires its user-function start
/// hook while the container's and the branch's wraps are active, because
/// the step's runner runs inside the branch body's poll, which runs inside
/// the container's frames.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_step_in_a_branch_starts_inside_the_branch_wrap() {
    let (_result, lines) = run_fn_hooks(|_event: (), ctx: DurableContext| async move {
        let branches = vec![durable::Branch::new(
            "0",
            |child: DurableContext| async move {
                Ok(child
                    .step(|_| async { Ok("inner".to_owned()) })
                    .name("inner")
                    .await?)
            },
        )];
        Ok(ctx.parallel(branches).name("parallel").await?)
    })
    .await;
    assert!(
        lines.contains(&"step-start inner in [\"parallel\", \"0\"]".to_owned()),
        "{lines:?}"
    );
}

/// Records every user-function hook and the attempt start, with the info
/// fields the tests below check, and a `probe` event in each start.
struct Rec(std::sync::Arc<std::sync::Mutex<Vec<String>>>);

impl Rec {
    fn line(&self, line: String) {
        self.0.lock().expect("not poisoned").push(line);
    }
}

fn describe(info: &durable::plugin::OperationInfo) -> String {
    format!(
        "{} attempt={:?} status={:?} replay={} start={:?}",
        info.name().unwrap_or_default(),
        info.attempt(),
        info.status(),
        info.is_replay(),
        info.start_timestamp()
    )
}

impl Plugin for Rec {
    fn wrap_user_function(&self, info: &durable::plugin::OperationInfo, next: &mut dyn FnMut()) {
        self.line(format!("wrap {}", describe(info)));
        IN_FN.with(|f| {
            f.borrow_mut()
                .push(info.name().unwrap_or_default().to_owned());
        });
        next();
        IN_FN.with(|f| f.borrow_mut().pop());
    }

    fn on_attempt_start(&self, info: &durable::plugin::AttemptInfo) -> durable::plugin::HookWork {
        self.line(format!("attempt-start {}", describe(info.operation())));
        Ok(None)
    }

    fn on_operation_start(
        &self,
        info: &durable::plugin::OperationInfo,
    ) -> durable::plugin::HookWork {
        self.line(format!("op-start {}", describe(info)));
        Ok(None)
    }

    fn on_user_function_start(
        &self,
        info: &durable::plugin::OperationInfo,
    ) -> durable::plugin::HookWork {
        tracing::info!(target: "probe", "start");
        self.line(format!("fn-start {}", describe(info)));
        Ok(None)
    }

    fn on_user_function_end(
        &self,
        info: &durable::plugin::OperationInfo,
        outcome: Result<(), &durable::WireError>,
    ) -> durable::plugin::HookWork {
        if let Err(wire) = outcome {
            self.line(format!("fn-end-error {:?}", wire.error_message()));
        }
        self.line(format!("fn-end {}", describe(info)));
        Ok(None)
    }
}

struct RecFactory(std::sync::Arc<std::sync::Mutex<Vec<String>>>);

impl PluginFactory for RecFactory {
    fn create_plugin(&self, _info: &InvocationInfo) -> Result<Option<Box<dyn Plugin>>, BoxError> {
        Ok(Some(Box::new(Rec(std::sync::Arc::clone(&self.0)))))
    }
}

async fn run_rec<F, Fut, O>(handler: F) -> (durable::test_util::TestResult<O>, Vec<String>)
where
    F: Fn((), DurableContext) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<O, BoxError>> + Send + 'static,
    O: serde::Serialize + serde::de::DeserializeOwned + Send + 'static,
{
    let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let result = LocalRunner::new()
        .options(
            Options::builder()
                .plugin(RecFactory(std::sync::Arc::clone(&log)))
                .build()
                .expect("valid options"),
        )
        .run(handler, ())
        .await
        .expect("runner");
    let lines = log.lock().expect("not poisoned").clone();
    (result, lines)
}

/// The user-function hooks and the wrap of a step attempt see
/// the attempt's info: attempt 1, status `Started`, `is_replay` false, and
/// the start timestamp `on_attempt_start` saw.
#[tokio::test]
async fn a_step_attempts_user_function_hooks_see_the_started_attempt() {
    let (result, lines) = run_rec(|_event: (), ctx: DurableContext| async move {
        Ok(ctx.step(|_| async { Ok(1_u32) }).name("s").await?)
    })
    .await;
    assert_eq!(result.output(), Some(&1));
    let attempt = lines
        .iter()
        .find_map(|l| l.strip_prefix("attempt-start "))
        .expect("the attempt started")
        .to_owned();
    assert!(
        attempt.contains("attempt=Some(1) status=Some(Started) replay=false start=Some("),
        "{attempt}"
    );
    for hook in ["fn-start", "wrap", "fn-end"] {
        let line = format!("{hook} {attempt}");
        assert!(lines.contains(&line), "{line} in {lines:?}");
    }
}

/// A plugin's start hook and the body's event both run inside the SDK's
/// step span.
#[tokio::test]
async fn a_start_hook_and_the_body_run_inside_the_step_span() {
    use tracing_subscriber::layer::SubscriberExt as _;

    let names = ScopeNames::default();
    let _guard =
        test_tracing::install_test_subscriber(tracing_subscriber::registry().with(names.clone()));
    let (result, _lines) = run_rec(|_event: (), ctx: DurableContext| async move {
        Ok(ctx
            .step(|_| async {
                tracing::info!(target: "probe", "body");
                Ok(1_u32)
            })
            .name("s")
            .await?)
    })
    .await;
    assert_eq!(result.output(), Some(&1));
    let seen = names.0.lock().expect("not poisoned").clone();
    // The start hook's event comes first, the body's second.
    assert_eq!(seen.len(), 2, "one start and one body event: {seen:?}");
    let start = seen.first().expect("a start event");
    let body = seen.get(1).expect("a body event");
    assert!(start.contains(&"durable_operation"), "{start:?}");
    assert!(body.contains(&"durable_operation"), "{body:?}");
}

/// A `with_retry` that fails once and succeeds has
/// user-function hooks only for the outer block; its attempt-1 and
/// attempt-2 children have none, and their bodies run inside the outer
/// block's wrap.
#[tokio::test]
async fn with_retry_attempts_are_not_user_functions() {
    let calls = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
    let (result, lines) = run_rec(move |_event: (), ctx: DurableContext| {
        let calls = std::sync::Arc::clone(&calls);
        async move {
            Ok(ctx
                .with_retry(move |_child, _attempt| {
                    let calls = std::sync::Arc::clone(&calls);
                    async move {
                        let wraps = IN_FN.with(|f| f.borrow().clone());
                        assert_eq!(wraps, ["block"], "the attempt runs inside the block's wrap");
                        if calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 {
                            return Err::<u32, BoxError>("once".into());
                        }
                        Ok(5)
                    }
                })
                .name("block")
                .retry_strategy(|_err, attempt| {
                    if attempt >= 2 {
                        durable::RetryDecision::Stop
                    } else {
                        durable::RetryDecision::retry(std::time::Duration::from_secs(1))
                    }
                })
                .await?)
        }
    })
    .await;
    assert_eq!(result.output(), Some(&5));
    let hooks: Vec<&String> = lines
        .iter()
        .filter(|l| l.starts_with("fn-start") || l.starts_with("fn-end"))
        .collect();
    let names: Vec<String> = hooks
        .iter()
        .map(|l| l.split(" attempt=").next().unwrap_or_default().to_owned())
        .collect();
    // The retry delay suspends the first invocation with the block
    // pending, so the second invocation runs the block again: one start
    // per invocation, and one end, in the invocation that finished it.
    assert_eq!(
        names,
        ["fn-start block", "fn-start block", "fn-end block"],
        "{lines:?}"
    );
    assert_eq!(result.invocations().len(), 2);
}

/// A child's user-function start receives the info its
/// `on_operation_start` received, with `is_replay` the child context's
/// `is_replaying()` at the body's start: false for a new child, true for a
/// STARTED child whose body has an inner record (the wait `w`).
#[tokio::test]
async fn a_childs_user_function_start_replays_as_its_context_does() {
    let (result, lines) = run_rec(|_event: (), ctx: DurableContext| async move {
        Ok(ctx
            .run_in_child_context(|child| async move {
                child
                    .wait(std::time::Duration::from_secs(1))
                    .name("w")
                    .await?;
                Ok(2_u32)
            })
            .name("c")
            .await?)
    })
    .await;
    assert_eq!(result.output(), Some(&2));
    assert_eq!(result.invocations().len(), 2);
    let resumed: Vec<&str> = lines
        .iter()
        .filter_map(|l| l.strip_prefix("op-start "))
        .filter(|l| l.starts_with("c ") && l.contains("replay=true"))
        .collect();
    assert_eq!(resumed.len(), 1, "{lines:?}");
    let start = format!("fn-start {}", resumed.first().expect("one"));
    assert!(lines.contains(&start), "{start} in {lines:?}");
    let starts: Vec<bool> = lines
        .iter()
        .filter_map(|l| l.strip_prefix("fn-start c "))
        .map(|l| l.contains("replay=true"))
        .collect();
    assert_eq!(starts, [false, true], "{lines:?}");
}

/// An error whose `Display` counts its calls and, at the first, polls an
/// operation the child created and never awaited. The SDK displays the
/// error to derive the wire, before the end hooks, so a closed scope
/// keeps that operation pending and its body never runs.
struct Counting {
    calls: std::sync::Arc<std::sync::atomic::AtomicU32>,
    pending: std::sync::Mutex<Option<durable::DurableFuture<u32>>>,
}

impl std::fmt::Debug for Counting {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Counting")
    }
}

impl std::fmt::Display for Counting {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        let pending = self.pending.lock().expect("not poisoned").take();
        if let Some(mut fut) = pending {
            let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
            let polled = std::pin::Pin::new(&mut fut).poll(&mut cx);
            assert!(polled.is_pending(), "the child's scope is closed");
        }
        f.write_str("counted")
    }
}

impl std::error::Error for Counting {}

/// A child body's error is displayed once; the recorded FAIL
/// error is the end hook's; an operation the child started is refused
/// before the end hook runs (its admission is closed, so it stays pending).
#[tokio::test]
async fn a_child_body_error_is_displayed_once_and_its_scope_closes_first() {
    let calls = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
    let ran = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let (handler_calls, handler_ran) = (std::sync::Arc::clone(&calls), std::sync::Arc::clone(&ran));
    let (result, lines) = run_rec(move |_event: (), ctx: DurableContext| {
        let (calls, ran) = (
            std::sync::Arc::clone(&handler_calls),
            std::sync::Arc::clone(&handler_ran),
        );
        async move {
            let outcome = ctx
                .run_in_child_context(move |child| async move {
                    let step_ran = ran;
                    let late = child
                        .step(move |_| async move {
                            step_ran.store(true, std::sync::atomic::Ordering::SeqCst);
                            Ok(1_u32)
                        })
                        .name("late")
                        .future();
                    Err::<u32, BoxError>(Box::new(Counting {
                        calls,
                        pending: std::sync::Mutex::new(Some(late)),
                    }))
                })
                .name("c")
                .await;
            Ok(outcome.is_err())
        }
    })
    .await;
    assert_eq!(result.output(), Some(&true));
    assert_eq!(
        calls.load(std::sync::atomic::Ordering::SeqCst),
        1,
        "{lines:?}"
    );
    assert!(
        !ran.load(std::sync::atomic::Ordering::SeqCst),
        "the abandoned step never ran"
    );
    let recorded = result
        .operation("c")
        .and_then(|op| op.error())
        .and_then(durable::WireError::error_message)
        .map(str::to_owned);
    let ended = format!("fn-end-error {recorded:?}");
    assert!(lines.contains(&ended), "{ended} in {lines:?}");
    assert!(
        result.operation("late").is_none(),
        "the abandoned step recorded nothing"
    );
}

/// A child-like site whose body returns a [`Counting`] error.
#[derive(Clone, Copy, Debug)]
enum ScopeSite {
    MapItem,
    Branch,
    MixedBranch,
}

/// #126 rule 7.9: a map item, a `parallel` branch and a `parallel_mixed`
/// branch close their scope inside the body, as a child context does, so
/// the error's `Display`, which the SDK calls before the end hooks, sees a
/// closed scope: the operation the body started and did not await stays
/// pending, never runs and records nothing.
#[tokio::test]
async fn an_item_or_branch_body_closes_its_scope_before_the_end_hooks() {
    for site in [
        ScopeSite::MapItem,
        ScopeSite::Branch,
        ScopeSite::MixedBranch,
    ] {
        let calls = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let ran = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let (handler_calls, handler_ran) =
            (std::sync::Arc::clone(&calls), std::sync::Arc::clone(&ran));
        let (result, lines) = run_rec(move |_event: (), ctx: DurableContext| {
            let (calls, ran) = (
                std::sync::Arc::clone(&handler_calls),
                std::sync::Arc::clone(&handler_ran),
            );
            let body = move |child: DurableContext| async move {
                let step_ran = ran;
                let late = child
                    .step(move |_| async move {
                        step_ran.store(true, std::sync::atomic::Ordering::SeqCst);
                        Ok(1_u32)
                    })
                    .name("late")
                    .future();
                Err::<u32, BoxError>(Box::new(Counting {
                    calls,
                    pending: std::sync::Mutex::new(Some(late)),
                }))
            };
            async move {
                let failed = match site {
                    ScopeSite::MapItem => ctx
                        .map(vec![1_u32], move |child, _item, _idx| body.clone()(child))
                        .name("b")
                        .await
                        .is_err(),
                    ScopeSite::Branch => ctx
                        .parallel(vec![durable::Branch::new("b", body)])
                        .name("p")
                        .await
                        .is_err(),
                    ScopeSite::MixedBranch => {
                        let mut branches = durable::BranchSet::new();
                        let handle = branches.add("b", body);
                        let batch = ctx.parallel_mixed(branches).name("p").await;
                        batch.is_err() || handle.into_result().is_err()
                    }
                };
                Ok(failed)
            }
        })
        .await;
        assert_eq!(result.output(), Some(&true), "{site:?}: {lines:?}");
        assert!(
            calls.load(std::sync::atomic::Ordering::SeqCst) >= 1,
            "{site:?}: the error was displayed"
        );
        assert!(
            !ran.load(std::sync::atomic::Ordering::SeqCst),
            "{site:?}: the abandoned step never ran"
        );
        assert!(
            result.operation("late").is_none(),
            "{site:?}: the abandoned step recorded nothing"
        );
    }
}

/// A resumed child with no inner record. Its operation start
/// reports `is_replay` true; its user-function start, wrap and end report
/// the child context's `is_replaying()`, false.
#[tokio::test]
async fn a_resumed_child_without_an_inner_record_runs_its_user_function_live() {
    let (result, lines) = run_rec(|_event: (), ctx: DurableContext| async move {
        let resumed = ctx.is_replaying();
        let child = ctx
            .run_in_child_context(move |_child| async move {
                if !resumed {
                    // The first invocation suspends on the wait below with
                    // this body pending and no record inside the child.
                    std::future::pending::<()>().await;
                }
                Ok(5_u32)
            })
            .name("c")
            .into_future();
        let wait = ctx
            .wait(std::time::Duration::from_secs(1))
            .name("w")
            .into_future();
        let (child, wait) = tokio::join!(child, wait);
        wait?;
        Ok(child?)
    })
    .await;
    assert_eq!(result.output(), Some(&5));
    assert_eq!(result.invocations().len(), 2, "{lines:?}");
    let flags = |prefix: &str| -> Vec<bool> {
        lines
            .iter()
            .filter_map(|l| l.strip_prefix(prefix))
            .map(|l| l.contains("replay=true"))
            .collect()
    };
    assert_eq!(flags("op-start c "), [false, true], "{lines:?}");
    assert_eq!(flags("fn-start c "), [false, false], "{lines:?}");
    // A wrap runs at every poll of the body, so only the values count.
    let wraps = flags("wrap c ");
    assert!(!wraps.is_empty() && wraps.iter().all(|r| !r), "{lines:?}");
    assert_eq!(flags("fn-end c "), [false], "{lines:?}");
}

/// An error whose `Display` calls a durable operation on the context it
/// captured: the body's own child context.
struct CallsInDisplay(DurableContext);

impl std::fmt::Debug for CallsInDisplay {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("CallsInDisplay")
    }
}

impl std::fmt::Display for CallsInDisplay {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        drop(
            self.0
                .wait(std::time::Duration::from_secs(1))
                .name("in-display"),
        );
        f.write_str("calls in display")
    }
}

impl std::error::Error for CallsInDisplay {}

/// Which user function returns the [`CallsInDisplay`] error.
#[derive(Clone, Copy, Debug)]
enum OutcomeSite {
    Child,
    MapItem,
    Branch,
}

/// #126 rule 8.2: a child body, a map item and a parallel branch whose error's
/// `Display` calls the captured context fail the execution with the
/// outcome context usage message.
#[tokio::test]
async fn an_error_display_calling_an_operation_fails_the_execution() {
    for site in [
        OutcomeSite::Child,
        OutcomeSite::MapItem,
        OutcomeSite::Branch,
    ] {
        let result = LocalRunner::new()
            .run(
                move |_event: (), ctx: DurableContext| async move {
                    let failed = match site {
                        OutcomeSite::Child => ctx
                            .run_in_child_context(|child| async move {
                                Err::<u32, BoxError>(Box::new(CallsInDisplay(child)))
                            })
                            .name("c")
                            .await
                            .is_err(),
                        OutcomeSite::MapItem => ctx
                            .map(vec![1_u32], |child, _item, _idx| async move {
                                Err::<u32, BoxError>(Box::new(CallsInDisplay(child)))
                            })
                            .name("m")
                            .await
                            .is_err(),
                        OutcomeSite::Branch => ctx
                            .parallel(vec![durable::Branch::new("b", |child| async move {
                                Err::<u32, BoxError>(Box::new(CallsInDisplay(child)))
                            })])
                            .name("p")
                            .await
                            .is_err(),
                    };
                    Ok::<_, BoxError>(failed)
                },
                (),
            )
            .await
            .expect("runner");
        assert_eq!(result.output(), None, "{site:?}");
        let message = result
            .error()
            .and_then(durable::WireError::error_message)
            .unwrap_or_default();
        assert!(
            message.contains("called while the SDK records the outcome of operation"),
            "{site:?}: {message}"
        );
        assert!(
            result.operation("in-display").is_none(),
            "{site:?}: nothing recorded"
        );
    }
}

/// One observation of a `.spawn()`ed step: the hook or body, its tokio task,
/// and the user-function wraps entered on its thread.
type SpawnSeen = (String, Option<tokio::task::Id>, Vec<String>);

/// Records where a step's start hooks run: their task and the entered
/// user-function wraps, and emits a `probe` event for the span scope.
struct SpawnProbe(std::sync::Arc<std::sync::Mutex<Vec<SpawnSeen>>>);

fn spawn_seen(log: &std::sync::Mutex<Vec<SpawnSeen>>, what: &str) {
    log.lock().expect("not poisoned").push((
        what.to_owned(),
        tokio::task::try_id(),
        IN_FN.with(|f| f.borrow().clone()),
    ));
    tracing::info!(target: "probe", "{what}");
}

impl Plugin for SpawnProbe {
    fn wrap_user_function(&self, info: &durable::plugin::OperationInfo, next: &mut dyn FnMut()) {
        IN_FN.with(|f| {
            f.borrow_mut()
                .push(info.name().unwrap_or_default().to_owned());
        });
        next();
        IN_FN.with(|f| f.borrow_mut().pop());
    }

    fn on_operation_start(
        &self,
        info: &durable::plugin::OperationInfo,
    ) -> durable::plugin::HookWork {
        if info.name() == Some("s") {
            spawn_seen(&self.0, "op-start");
        }
        Ok(None)
    }

    fn on_attempt_start(&self, info: &durable::plugin::AttemptInfo) -> durable::plugin::HookWork {
        if info.operation().name() == Some("s") {
            spawn_seen(&self.0, "attempt-start");
        }
        Ok(None)
    }
}

struct SpawnProbeFactory(std::sync::Arc<std::sync::Mutex<Vec<SpawnSeen>>>);

impl PluginFactory for SpawnProbeFactory {
    fn create_plugin(&self, _info: &InvocationInfo) -> Result<Option<Box<dyn Plugin>>, BoxError> {
        Ok(Some(Box::new(SpawnProbe(std::sync::Arc::clone(&self.0)))))
    }
}

/// Runs a child `outer` that, inside span `caller`, records itself and
/// `.spawn()`s step `s` with `semantics`, then awaits it. Returns the
/// observations and the span scope of each, in order.
async fn run_spawned_step(
    semantics: durable::StepSemantics,
) -> (Vec<SpawnSeen>, Vec<Vec<&'static str>>) {
    use tracing_subscriber::layer::SubscriberExt as _;

    let names = ScopeNames::default();
    let _guard =
        test_tracing::install_test_subscriber(tracing_subscriber::registry().with(names.clone()));
    let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let body_log = std::sync::Arc::clone(&log);
    let result = LocalRunner::new()
        .options(
            Options::builder()
                .plugin(SpawnProbeFactory(std::sync::Arc::clone(&log)))
                .build()
                .expect("valid options"),
        )
        .run(
            move |_event: (), ctx: DurableContext| {
                let body_log = std::sync::Arc::clone(&body_log);
                async move {
                    Ok::<_, BoxError>(
                        ctx.run_in_child_context(move |child| async move {
                            let handle = {
                                let _caller = tracing::info_span!("caller").entered();
                                spawn_seen(&body_log, "caller");
                                let step_log = std::sync::Arc::clone(&body_log);
                                let handle = child
                                    .step(move |_| async move {
                                        spawn_seen(&step_log, "body");
                                        Ok(1_u32)
                                    })
                                    .name("s")
                                    .semantics(semantics)
                                    .spawn();
                                spawn_seen(&body_log, "spawned");
                                handle
                            };
                            Ok(handle.await?)
                        })
                        .name("outer")
                        .await?,
                    )
                }
            },
            (),
        )
        .await
        .expect("runner");
    assert_eq!(result.output(), Some(&1));
    let seen = log.lock().expect("not poisoned").clone();
    let scopes = names.0.lock().expect("not poisoned").clone();
    (seen, scopes)
}

/// #126 rules 5.2 and 11 (#153): a `.spawn()`ed
/// `AtLeastOncePerRetry` step fires `on_operation_start` on the caller's
/// task before `.spawn()` returns, inside the caller's frames and span, and
/// `on_attempt_start` and the body on the step's own task, inside the frames
/// and span the step captured, which equal the caller's.
/// Current-thread, so the thread-local subscriber sees every event.
#[tokio::test]
async fn a_spawned_step_starts_on_the_caller_in_the_callers_frames_and_span() {
    let (seen, scopes) = run_spawned_step(durable::StepSemantics::AtLeastOncePerRetry).await;
    let order: Vec<&str> = seen.iter().map(|(what, _, _)| what.as_str()).collect();
    assert_eq!(
        order,
        ["caller", "op-start", "spawned", "attempt-start", "body"],
        "{seen:?}"
    );
    let caller = seen.first().expect("the caller").1;
    assert!(caller.is_some());
    for (what, task, frames) in &seen {
        let on_caller = matches!(what.as_str(), "caller" | "op-start" | "spawned");
        assert_eq!(*task == caller, on_caller, "{what} task: {seen:?}");
        let expected: &[&str] = if what == "body" {
            &["outer", "s"]
        } else {
            &["outer"]
        };
        assert_eq!(frames, expected, "{what} frames: {seen:?}");
    }
    assert_eq!(scopes.len(), seen.len(), "{scopes:?}");
    for ((what, _, _), scope) in seen.iter().zip(&scopes) {
        assert!(scope.contains(&"caller"), "{what} span: {scope:?}");
    }
}

/// #126 rule 11: a `.spawn()`ed `AtMostOncePerRetry` step fires both start
/// hooks on its own task after the START response, in the captured frames
/// and span.
/// Current-thread, so the thread-local subscriber sees every event.
#[tokio::test]
async fn a_spawned_at_most_once_step_starts_on_its_own_task() {
    let (seen, scopes) = run_spawned_step(durable::StepSemantics::AtMostOncePerRetry).await;
    let order: Vec<&str> = seen.iter().map(|(what, _, _)| what.as_str()).collect();
    assert_eq!(
        order,
        ["caller", "spawned", "op-start", "attempt-start", "body"],
        "{seen:?}"
    );
    let caller = seen.first().expect("the caller").1;
    for (what, task, frames) in &seen {
        let on_caller = matches!(what.as_str(), "caller" | "spawned");
        assert_eq!(*task == caller, on_caller, "{what} task: {seen:?}");
        let expected: &[&str] = if what == "body" {
            &["outer", "s"]
        } else {
            &["outer"]
        };
        assert_eq!(frames, expected, "{what} frames: {seen:?}");
    }
    assert_eq!(scopes.len(), seen.len(), "{scopes:?}");
    for ((what, _, _), scope) in seen.iter().zip(&scopes) {
        assert!(scope.contains(&"caller"), "{what} span: {scope:?}");
    }
}

/// One observation of [`future_input_keeps_creator_frames`]: the hook or
/// body, and the invocation and user-function wraps entered on its thread.
type FrameSeen = (String, Vec<String>);

/// Records the frames `on_operation_start` of operation `in` runs in, with
/// `I` for the invocation wrap and each user-function wrap's name, and
/// emits a `probe` event for the span scope.
struct FrameProbe(std::sync::Arc<std::sync::Mutex<Vec<FrameSeen>>>);

fn frame_seen(log: &std::sync::Mutex<Vec<FrameSeen>>, what: &str) {
    log.lock()
        .expect("not poisoned")
        .push((what.to_owned(), IN_FN.with(|f| f.borrow().clone())));
    tracing::info!(target: "probe", "{what}");
}

impl Plugin for FrameProbe {
    fn wrap_invocation(&self, _info: &InvocationInfo, next: &mut dyn FnMut()) {
        IN_FN.with(|f| f.borrow_mut().push("I".to_owned()));
        next();
        IN_FN.with(|f| f.borrow_mut().pop());
    }

    fn wrap_user_function(&self, info: &durable::plugin::OperationInfo, next: &mut dyn FnMut()) {
        IN_FN.with(|f| {
            f.borrow_mut()
                .push(info.name().unwrap_or_default().to_owned());
        });
        next();
        IN_FN.with(|f| f.borrow_mut().pop());
    }

    fn on_operation_start(
        &self,
        info: &durable::plugin::OperationInfo,
    ) -> durable::plugin::HookWork {
        if info.name() == Some("in") {
            frame_seen(&self.0, "op-start");
        }
        Ok(None)
    }
}

struct FrameProbeFactory(std::sync::Arc<std::sync::Mutex<Vec<FrameSeen>>>);

impl PluginFactory for FrameProbeFactory {
    fn create_plugin(&self, _info: &InvocationInfo) -> Result<Option<Box<dyn Plugin>>, BoxError> {
        Ok(Some(Box::new(FrameProbe(std::sync::Arc::clone(&self.0)))))
    }
}

/// Which lazy input [`future_input_keeps_creator_frames`] creates.
#[derive(Debug, Clone, Copy)]
enum LazyInput {
    /// A step, whose start step a combinator runs on its own task.
    Step,
    /// A `wait_for_condition`, which a combinator polls once on a task it
    /// spawns.
    WaitForCondition,
}

/// How child `b` of [`run_cross_child`] awaits the input child `a` made.
#[derive(Debug, Clone, Copy)]
enum AwaitIn {
    /// Inside a `try_join_all` `j`, which begins the input.
    Combinator,
    /// Directly, so the first poll begins it.
    Direct,
}

/// Runs a handler in which child `a`, inside span `A`, creates a lazy
/// input `in` of `kind` with `.future()`, and child `b`, inside span `B`,
/// awaits it as `how` says. Returns the observations of a [`FrameProbe`]
/// and the span scope of each. Child `a` stays open until `b` awaited the
/// input, so the input's context is still open while it runs.
async fn run_cross_child(
    kind: LazyInput,
    how: AwaitIn,
) -> (Vec<FrameSeen>, Vec<Vec<&'static str>>) {
    use tracing::Instrument as _;
    use tracing_subscriber::layer::SubscriberExt as _;

    let names = ScopeNames::default();
    let _guard =
        test_tracing::install_test_subscriber(tracing_subscriber::registry().with(names.clone()));
    let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let body_log = std::sync::Arc::clone(&log);
    let result = LocalRunner::new()
        .options(
            Options::builder()
                .plugin(FrameProbeFactory(std::sync::Arc::clone(&log)))
                .build()
                .expect("valid options"),
        )
        .run(
            move |_event: (), ctx: DurableContext| {
                let body_log = std::sync::Arc::clone(&body_log);
                async move {
                    let (input_tx, input_rx) = tokio::sync::oneshot::channel();
                    let (done_tx, done_rx) = tokio::sync::oneshot::channel::<()>();
                    let a = ctx
                        .run_in_child_context(move |child| async move {
                            let input = {
                                let _a = tracing::info_span!("A").entered();
                                lazy_input(&child, kind, &body_log)
                            };
                            if input_tx.send(input).is_err() {
                                return Err::<u32, BoxError>("b stopped".into());
                            }
                            // Child `a` stays open until `b` awaited the input.
                            done_rx.await?;
                            Ok(0_u32)
                        })
                        .name("a")
                        .spawn();
                    let b = ctx
                        .run_in_child_context(move |child| async move {
                            let input = input_rx.await?;
                            let values = match how {
                                AwaitIn::Combinator => {
                                    child
                                        .try_join_all([input])
                                        .name("j")
                                        .into_future()
                                        .instrument(tracing::info_span!("B"))
                                        .await?
                                }
                                AwaitIn::Direct => {
                                    vec![input.instrument(tracing::info_span!("B")).await?]
                                }
                            };
                            let _done = done_tx.send(());
                            Ok::<_, BoxError>(values)
                        })
                        .name("b")
                        .spawn();
                    let (a, b) = tokio::join!(a, b);
                    a?;
                    Ok::<_, BoxError>(b?)
                }
            },
            (),
        )
        .await
        .expect("runner");
    assert_eq!(result.output(), Some(&vec![1]), "{kind:?} {how:?}");
    let seen = log.lock().expect("not poisoned").clone();
    let scopes = names.0.lock().expect("not poisoned").clone();
    (seen, scopes)
}

/// Creates the lazy input `in` of `kind` on `child`: a step returning 1, or
/// a `wait_for_condition` from 0 whose single check returns 1. The body or
/// check records itself as `body`.
fn lazy_input(
    child: &DurableContext,
    kind: LazyInput,
    log: &std::sync::Arc<std::sync::Mutex<Vec<FrameSeen>>>,
) -> durable::DurableFuture<u32> {
    let log = std::sync::Arc::clone(log);
    match kind {
        LazyInput::Step => child
            .step(move |_| async move {
                frame_seen(&log, "body");
                Ok(1_u32)
            })
            .name("in")
            .future(),
        LazyInput::WaitForCondition => child
            .wait_for_condition(
                move |_ctx, state: u32| {
                    let log = std::sync::Arc::clone(&log);
                    async move {
                        frame_seen(&log, "body");
                        Ok(state + 1)
                    }
                },
                0_u32,
            )
            .wait_strategy_fn(|_state, _attempt| {
                durable::builders::wait_for_condition::WaitDecision::complete()
            })
            .name("in")
            .future(),
    }
}

/// #126 rule 5.2: a lazy combinator input runs its
/// start phase inside the task context it captured at `.future()`. The
/// input is created in child `a` inside span `A`, and a `try_join_all` in
/// child `b` inside span `B` polls it. `on_operation_start` sees `[I, a]`
/// and span `A`; the step body and the condition check see `[I, a, in]`,
/// both in span `A`; none sees `B`, and none has `b` innermost.
/// Current-thread, so the thread-local subscriber sees every event.
#[tokio::test]
async fn future_input_keeps_creator_frames() {
    for kind in [LazyInput::Step, LazyInput::WaitForCondition] {
        let (seen, scopes) = run_cross_child(kind, AwaitIn::Combinator).await;
        assert_frames(kind, &seen, &scopes, ("a", "A"), "B");
    }
}

/// #126 rules 4.6 and 5.2: only a gateway or a combinator
/// enters a future's captured context. A `.future()` created in child `a`
/// inside span `A` and awaited directly in child `b` inside span `B` runs
/// in its awaiter's context, both phases: `on_operation_start` sees
/// `[I, b]` and span `B`; the step body and the condition check see
/// `[I, b, in]`, both in span `B`; none sees `A`.
/// Current-thread, so the thread-local subscriber sees every event.
#[tokio::test]
async fn a_directly_awaited_future_runs_in_its_awaiters_context() {
    for kind in [LazyInput::Step, LazyInput::WaitForCondition] {
        let (seen, scopes) = run_cross_child(kind, AwaitIn::Direct).await;
        assert_frames(kind, &seen, &scopes, ("b", "B"), "A");
    }
}

/// The assertions of [`future_input_keeps_creator_frames`] and
/// [`a_directly_awaited_future_runs_in_its_awaiters_context`] for one row:
/// the hook and the body run in child `child` and span `span`, and never in
/// span `other`.
fn assert_frames(
    kind: LazyInput,
    seen: &[FrameSeen],
    scopes: &[Vec<&'static str>],
    (child, span): (&str, &str),
    other: &str,
) {
    let order: Vec<&str> = seen.iter().map(|(what, _)| what.as_str()).collect();
    assert_eq!(order, ["op-start", "body"], "{kind:?}: {seen:?}");
    for (what, frames) in seen {
        // The body or check runs in its own frame, above the frames of
        // the child that created it; the start hook runs below it.
        let expected: Vec<&str> = match what.as_str() {
            "body" => vec!["I", child, "in"],
            _ => vec!["I", child],
        };
        // The frames entered innermost, from the last invocation wrap:
        // the combinator runs a step input's start step in its own
        // poll, so the poller's wraps `[I, b]` are still on the stack
        // below the entered `[I, a]`, and a context plugin's innermost
        // wrap sets the current context (#126 rule 4.4).
        let innermost = frames
            .iter()
            .rposition(|frame| frame == "I")
            .and_then(|at| frames.get(at..))
            .unwrap_or(frames);
        assert_eq!(innermost, expected, "{kind:?} {what} frames: {seen:?}");
    }
    assert_eq!(scopes.len(), seen.len(), "{kind:?}: {scopes:?}");
    for ((what, _), scope) in seen.iter().zip(scopes) {
        assert!(scope.contains(&span), "{kind:?} {what} span: {scope:?}");
        assert!(!scope.contains(&other), "{kind:?} {what} span: {scope:?}");
    }
}

/// The log [`PanicsAtCaptured`] and [`CapturedFrames`] share.
type Log = std::sync::Arc<std::sync::Mutex<Vec<String>>>;

fn log(log: &Log, line: &str) {
    log.lock().expect("not poisoned").push(line.to_owned());
}

type Flag = std::sync::Arc<std::sync::atomic::AtomicBool>;

thread_local! {
    /// The spans entered on this thread.
    static DEPTH: Cell<usize> = const { Cell::new(0) };
}

/// A layer that, once `armed` is set, panics `"span subscriber panics"`
/// at the next outermost enter or exit of a `captured` span, once, and
/// logs `panic` first. It sets `started` at the step's `START` lifecycle
/// event, which the checkpoint path emits inside `captured` too.
struct PanicsAtCaptured {
    at: SpanCallback,
    armed: Flag,
    started: Flag,
    log: Log,
}

impl PanicsAtCaptured {
    fn hit<S>(&self, id: &tracing::span::Id, ctx: &tracing_subscriber::layer::Context<'_, S>)
    where
        S: tracing::Subscriber + for<'l> tracing_subscriber::registry::LookupSpan<'l>,
    {
        let captured = ctx.span(id).is_some_and(|span| span.name() == "captured");
        // Outermost: the gateway's own enter or exit, not one nested in a
        // poll.
        let outermost = DEPTH.with(Cell::get) == 0;
        if !captured || !outermost || !self.armed.swap(false, std::sync::atomic::Ordering::SeqCst) {
            return;
        }
        log(&self.log, "panic");
        #[expect(clippy::panic, reason = "the subscriber panic under test")]
        {
            panic!("span subscriber panics");
        }
    }
}

impl<S> tracing_subscriber::Layer<S> for PanicsAtCaptured
where
    S: tracing::Subscriber + for<'l> tracing_subscriber::registry::LookupSpan<'l>,
{
    fn on_enter(&self, id: &tracing::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
        if self.at == SpanCallback::Enter {
            self.hit(id, &ctx);
        }
        DEPTH.with(|depth| depth.set(depth.get() + 1));
    }

    fn on_exit(&self, id: &tracing::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
        DEPTH.with(|depth| depth.set(depth.get().saturating_sub(1)));
        if self.at == SpanCallback::Exit {
            self.hit(id, &ctx);
        }
    }

    fn on_event(&self, event: &tracing::Event<'_>, ctx: tracing_subscriber::layer::Context<'_, S>) {
        let in_captured = ctx
            .event_span(event)
            .is_some_and(|span| span.name() == "captured");
        if in_captured && event.metadata().target() == durable::observability::TARGET {
            self.started
                .store(true, std::sync::atomic::Ordering::SeqCst);
        }
    }
}

/// A plugin whose invocation wrap logs, for a frame entered inside a
/// `captured` span, `enter` before `next()`, and after it whether the
/// thread panics.
#[derive(Clone)]
struct CapturedFrames(Log);

impl Plugin for CapturedFrames {
    fn wrap_invocation(&self, _info: &InvocationInfo, next: &mut dyn FnMut()) {
        let captured = tracing::Span::current()
            .metadata()
            .is_some_and(|meta| meta.name() == "captured");
        if captured {
            log(&self.0, "enter");
        }
        next();
        if captured {
            log(
                &self.0,
                &format!("after panicking={}", std::thread::panicking()),
            );
        }
    }
}

/// The message of a panic payload.
fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
    payload
        .downcast_ref::<&str>()
        .map(|s| (*s).to_owned())
        .or_else(|| payload.downcast_ref::<String>().cloned())
        .unwrap_or_default()
}

/// Runs a handler that `.spawn()`s, inside a `captured` span, the step `s`
/// running `body`, with a [`PanicsAtCaptured`] at `at` installed and
/// [`CapturedFrames`] registered. `body` gets the layer's `armed` and
/// `started` flags and a `ready` flag. The handler awaits the step when
/// `await_step`; otherwise, once the body set `ready`, it arms the layer
/// and returns, which stops the step. Returns the message of the panic the invocation fails with, and
/// the log.
async fn failing_run<B, Fut>(at: SpanCallback, await_step: bool, body: B) -> (String, Vec<String>)
where
    B: Fn(Flag, Flag, Flag) -> Fut + Clone + Send + Sync + 'static,
    Fut: Future<Output = Result<u32, BoxError>> + Send + 'static,
{
    use tracing_subscriber::layer::SubscriberExt as _;
    let log = Log::default();
    let layer = PanicsAtCaptured {
        at,
        armed: Flag::default(),
        started: Flag::default(),
        log: std::sync::Arc::clone(&log),
    };
    let flags = (
        std::sync::Arc::clone(&layer.armed),
        std::sync::Arc::clone(&layer.started),
        Flag::default(),
    );
    let plugin = CapturedFrames(std::sync::Arc::clone(&log));
    let _guard = test_tracing::install_test_subscriber(tracing_subscriber::registry().with(layer));
    #[expect(clippy::disallowed_methods)]
    // reason: the test observes the panic the run resumes, which only a
    // task's JoinHandle reports.
    let joined = tokio::spawn(async move {
        LocalRunner::new()
            .options(
                Options::builder()
                    .plugin(Each(plugin))
                    .build()
                    .expect("valid options"),
            )
            .run(
                move |_event: (), ctx: DurableContext| {
                    let (body, flags) = (body.clone(), flags.clone());
                    async move {
                        let (armed, ready) = (
                            std::sync::Arc::clone(&flags.0),
                            std::sync::Arc::clone(&flags.2),
                        );
                        let handle = tracing::info_span!("captured").in_scope(|| {
                            ctx.step(move |_| {
                                body(flags.0.clone(), flags.1.clone(), flags.2.clone())
                            })
                            .name("s")
                            .spawn()
                        });
                        if await_step {
                            handle.await?;
                        } else {
                            while !ready.load(std::sync::atomic::Ordering::SeqCst) {
                                tokio::task::yield_now().await;
                            }
                            // The step's poll that set `ready` has ended:
                            // its drop is the next enter and exit.
                            armed.store(true, std::sync::atomic::Ordering::SeqCst);
                            drop(handle);
                        }
                        Ok::<_, BoxError>(())
                    }
                },
                (),
            )
            .await
    })
    .await;
    let message = panic_message(&*joined.expect_err("the invocation fails").into_panic());
    let seen = log.lock().expect("not poisoned").clone();
    (message, seen)
}

/// Yields until the step's `START` event was emitted inside `captured`,
/// so the next outermost enter or exit of `captured` is the gateway's.
async fn after_start(started: &Flag) {
    while !started.load(std::sync::atomic::Ordering::SeqCst) {
        tokio::task::yield_now().await;
    }
}

/// The gateway catches a subscriber panic at its captured span's enter
/// before it enters any captured frame, and one at its exit after every
/// frame returned normally. A step body's panic is caught inside the
/// frames, whose wraps then run with no panic in flight, and it wins over
/// the later exit panic.
#[tokio::test]
async fn captured_span_panic_is_caught_outside_plugin_frames() {
    use std::sync::atomic::Ordering::SeqCst;
    let after_frame = ["enter", "after panicking=false", "panic"];
    for (at, body_panics, expected, message) in [
        (
            SpanCallback::Enter,
            false,
            &["panic"][..],
            "span subscriber panics",
        ),
        (
            SpanCallback::Exit,
            false,
            &after_frame[..],
            "span subscriber panics",
        ),
        (SpanCallback::Exit, true, &after_frame[..], "body panics"),
    ] {
        let (reported, seen) = failing_run(at, true, move |armed, started, _ready| async move {
            after_start(&started).await;
            armed.store(true, SeqCst);
            if at == SpanCallback::Enter {
                // The gateway's next poll enters `captured` and panics.
                tokio::task::yield_now().await;
            }
            assert!(!body_panics, "body panics");
            Ok(1_u32)
        })
        .await;
        let case = format!("{at:?} body_panics={body_panics}");
        assert_eq!(reported, message, "{case}");
        let seen: Vec<&str> = seen.iter().map(String::as_str).collect();
        let panic = seen.iter().position(|l| *l == "panic").expect("the panic");
        // The last frame before the panic, and its end.
        let start = (panic + 1).saturating_sub(expected.len());
        let before = seen.get(start..=panic);
        assert_eq!(before, Some(expected), "{case}: {seen:?}");
        if at == SpanCallback::Enter {
            // The panicking poll entered no frame: the frame before the
            // panic is the previous poll's, which ended.
            assert_eq!(
                seen.get(panic.saturating_sub(1)),
                Some(&"after panicking=false"),
                "{case}: {seen:?}"
            );
        }
        assert!(!seen.contains(&"after panicking=true"), "{case}: {seen:?}");
    }
}

/// A subscriber panic entering or exiting the captured span while the
/// gateway drops an aborted pending task fails the invocation, and no
/// panic unwinds through the task's captured frames.
#[tokio::test]
async fn captured_span_panic_during_aborted_task_drop_is_recorded() {
    use std::sync::atomic::Ordering::SeqCst;
    for at in [SpanCallback::Enter, SpanCallback::Exit] {
        let (reported, seen) = failing_run(at, false, |_armed, started, ready| async move {
            after_start(&started).await;
            ready.store(true, SeqCst);
            std::future::pending::<Result<u32, BoxError>>().await
        })
        .await;
        assert_eq!(reported, "span subscriber panics", "{at:?}");
        let seen: Vec<&str> = seen.iter().map(String::as_str).collect();
        let panic = seen.iter().position(|l| *l == "panic").expect("the panic");
        let expected: &[&str] = match at {
            // The drop never enters the frames: the frame before the panic
            // is the last poll's, which ended.
            SpanCallback::Enter => &["after panicking=false", "panic"],
            // The drop ran inside the frames, which returned normally.
            SpanCallback::Exit => &["enter", "after panicking=false", "panic"],
        };
        let start = (panic + 1).saturating_sub(expected.len());
        assert_eq!(seen.get(start..=panic), Some(expected), "{at:?}: {seen:?}");
        assert!(!seen.contains(&"after panicking=true"), "{at:?}: {seen:?}");
    }
}

/// What the runs of a combinator winner's body saw: the names of the spans
/// in scope of each run's `probe` event, and the frames each run read.
type BodyContext = (Vec<Vec<&'static str>>, Vec<Vec<String>>);

/// Runs `race`, or `select_ok` when `select_ok` is true, over two inputs
/// and then waits 1 s, so invocation 2 replays the recorded winner. The
/// body of the virtual child `a` makes the winner `in` with `.future()`
/// inside span `created`: a child context that returns 300 KiB, so its
/// record and the combinator's carry `ReplayChildren`, and replay runs its
/// body again. The loser is a step that never finishes. The handler awaits
/// the combinator inside span `joined`. Returns what each run of `in`'s
/// body saw, its frames counted from the last invocation wrap.
async fn oversized_winner_body_context(select_ok: bool) -> BodyContext {
    use tracing::Instrument as _;
    use tracing_subscriber::layer::SubscriberExt as _;

    let names = ScopeNames::default();
    let _guard =
        test_tracing::install_test_subscriber(tracing_subscriber::registry().with(names.clone()));
    let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
    let body_seen = std::sync::Arc::clone(&seen);
    let result = run_with(Wraps::default(), move |_event: (), ctx: DurableContext| {
        let body_seen = std::sync::Arc::clone(&body_seen);
        async move {
            let slot: std::sync::Arc<std::sync::Mutex<Option<durable::DurableFuture<String>>>> =
                std::sync::Arc::default();
            let fill = std::sync::Arc::clone(&slot);
            ctx.run_in_child_context(move |a| async move {
                let winner = {
                    let _created = tracing::info_span!("created").entered();
                    a.run_in_child_context(move |_in| async move {
                        let stack = frames();
                        let at = stack.iter().rposition(|frame| frame == "I");
                        let innermost = at.and_then(|at| stack.get(at..)).unwrap_or(&stack);
                        body_seen
                            .lock()
                            .expect("not poisoned")
                            .push(innermost.to_vec());
                        tracing::info!(target: "probe", "winner body");
                        Ok("w".repeat(300 * 1024))
                    })
                    .name("in")
                    .future()
                };
                *fill.lock().expect("not poisoned") = Some(winner);
                Ok(0_u32)
            })
            .name("a")
            .virtual_context()
            .await?;
            let winner = slot
                .lock()
                .expect("not poisoned")
                .take()
                .ok_or("`a` made no input")?;
            let loser = ctx
                .step(|_| async {
                    std::future::pending::<()>().await;
                    Ok(String::new())
                })
                .name("loser")
                .future();
            let joined = tracing::info_span!("joined");
            let value = if select_ok {
                ctx.select_ok([winner, loser])
                    .name("first")
                    .into_future()
                    .instrument(joined)
                    .await?
            } else {
                ctx.race([winner, loser])
                    .name("first")
                    .into_future()
                    .instrument(joined)
                    .await?
            };
            ctx.wait(std::time::Duration::from_secs(1))
                .name("pause")
                .await?;
            Ok::<_, BoxError>(value.len())
        }
    })
    .await;
    assert_eq!(result.output(), Some(&307_200));
    assert_eq!(result.invocation_count(), 2);
    let scopes = names.0.lock().expect("not poisoned").clone();
    let frames = seen.lock().expect("not poisoned").clone();
    (scopes, frames)
}

/// Asserts that the winner's body ran live and on replay, and that both
/// runs ran inside span `created`, not span `joined`, and inside the wraps
/// of `a`: the live run inside its own frame `in` too, and the replay,
/// which rebuilds the value, inside no frame of its own.
fn assert_ran_in_creation_context((scopes, frames): &BodyContext) {
    assert_eq!(
        scopes.len(),
        2,
        "the body ran live and on replay: {scopes:?}"
    );
    for scope in scopes {
        assert!(scope.contains(&"created"), "{scope:?}");
        assert!(!scope.contains(&"joined"), "{scope:?}");
    }
    assert_eq!(frames, &[path(&["a", "in"]), path(&["a"])]);
}

/// The replay of a `race` whose winner was over 256 KiB runs the winner's
/// body in the span and wraps current where the winner became a future, as
/// the first run does.
#[tokio::test]
async fn a_replayed_oversized_race_winner_runs_in_its_creation_context() {
    assert_ran_in_creation_context(&oversized_winner_body_context(false).await);
}

/// As [`a_replayed_oversized_race_winner_runs_in_its_creation_context`],
/// for `select_ok`.
#[tokio::test]
async fn a_replayed_oversized_select_ok_winner_runs_in_its_creation_context() {
    assert_ran_in_creation_context(&oversized_winner_body_context(true).await);
}