obeli-sk-wasm-workers 0.37.0

Internal package of obelisk
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
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
use super::activity_ctx::{self, ActivityCtx};
use super::activity_ctx_process::process_support_outer::v1_0_0::obelisk::activity::process as process_support;
use crate::activity::activity_ctx::ActivityPreopenIoError;
use crate::activity::cancel_registry::CancelRegistry;
use crate::component_logger::{LogStrageConfig, log_activities};
use crate::envvar::EnvVar;
use crate::http_hooks::ConfigSectionHint;
use crate::std_output_stream::{StdOutputConfig, StdOutputConfigWithSender};
use crate::{RunnableComponent, WasmFileError};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use concepts::storage::http_client_trace::HttpClientTrace;
use concepts::storage::{LogInfoAppendRow, LogStreamType, Version};
use concepts::time::{ClockFn, Sleep, now_tokio_instant};
use concepts::{
    ComponentId, FunctionFqn, PackageIfcFns, Params, StrVariant, SupportedFunctionReturnValue,
    TrapKind,
};
use concepts::{FunctionMetadata, ResultParsingError};
use executor::worker::{FatalError, WorkerContext, WorkerResult, WorkerResultOk};
use executor::worker::{Worker, WorkerError};
use itertools::Itertools;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use tracing::{error, info, trace};
use utils::wasm_tools::ExIm;
use wasmtime::component::{ComponentExportIndex, InstancePre, Type};
use wasmtime::{Engine, component::Val};
use wasmtime::{Store, UpdateDeadline};

#[derive(Clone, Debug)]
pub struct ActivityConfig {
    pub component_id: ComponentId,
    pub forward_stdout: Option<StdOutputConfig>,
    pub forward_stderr: Option<StdOutputConfig>,
    pub env_vars: Arc<[EnvVar]>,
    pub directories_config: Option<ActivityDirectoriesConfig>,
    pub fuel: Option<u64>,
    pub allowed_hosts: Arc<[crate::http_request_policy::AllowedHostConfig]>,
    /// The TOML config section type for error messages
    pub config_section_hint: ConfigSectionHint,
}

#[derive(Clone, Debug)]
pub struct ActivityDirectoriesConfig {
    pub parent_preopen_dir: Arc<Path>,
    pub reuse_on_retry: bool,
    pub process_provider: Option<ProcessProvider>,
}

#[derive(Clone, Copy, Debug)]
pub enum ProcessProvider {
    Native,
}

#[derive(derive_more::Debug)]
pub struct ActivityWorkerCompiled {
    #[debug(skip)]
    engine: Arc<Engine>,
    #[debug(skip)]
    instance_pre: InstancePre<ActivityCtx>,
    exim: ExIm,
    #[debug(skip)]
    clock_fn: Box<dyn ClockFn>,
    #[debug(skip)]
    sleep: Arc<dyn Sleep>,
    exported_ffqn_to_index: hashbrown::HashMap<FunctionFqn, ComponentExportIndex>,
    config: ActivityConfig,
}
impl ActivityWorkerCompiled {
    pub fn new_with_config(
        runnable_component: RunnableComponent,
        config: ActivityConfig,
        engine: Arc<Engine>,
        clock_fn: Box<dyn ClockFn>,
        sleep: Arc<dyn Sleep>,
    ) -> Result<Self, WasmFileError> {
        let mut linker = wasmtime::component::Linker::new(&engine);
        // wasi
        wasmtime_wasi::p2::add_to_linker_async(&mut linker)
            .map_err(|err| WasmFileError::linking_error("cannot link wasi", err))?;
        // wasi-http
        wasmtime_wasi_http::p2::add_only_http_to_linker_async(&mut linker)
            .map_err(|err| WasmFileError::linking_error("cannot link wasi-http", err))?;
        // obelisk:log
        log_activities::obelisk::log::log::add_to_linker::<_, ActivityCtx>(&mut linker, |x| x)
            .map_err(|err| WasmFileError::linking_error("cannot link obelisk:log", err))?;
        // obelisk:activity/process
        match config
            .directories_config
            .as_ref()
            .and_then(|dir| dir.process_provider.as_ref())
        {
            Some(ProcessProvider::Native) => {
                process_support::add_to_linker::<_, ActivityCtx>(&mut linker, |x| x).map_err(
                    |err| WasmFileError::linking_error("cannot link process support", err),
                )?;
            }
            None => {}
        }
        // Attempt to pre-instantiate to catch missing imports
        let instance_pre = linker
            .instantiate_pre(&runnable_component.wasmtime_component)
            .map_err(|err| {
                let reason = if err.to_string()
                    == "component imports instance `obelisk:activity/process@1.0.0`, but a matching implementation was not found in the linker"
                {
                    "activity comopnent imports Process API, but it is not enabled. Use e.g. `directories  = { enabled = true, process_provider = \"native\"}`".to_string().into()
                } else {
                    StrVariant::Static("cannot link activity")
                };
                WasmFileError::linking_error(reason, err)}
            )?;

        let exported_ffqn_to_index = RunnableComponent::index_exported_functions(
            &runnable_component.wasmtime_component,
            &runnable_component.wasm_component.exim,
        )
        .map_err(WasmFileError::DecodeError)?;
        Ok(Self {
            engine,
            exim: runnable_component.wasm_component.exim,
            clock_fn,
            sleep,
            exported_ffqn_to_index,
            config,
            instance_pre,
        })
    }

    #[must_use]
    pub fn exported_functions_ext(&self) -> &[FunctionMetadata] {
        self.exim.get_exports(true)
    }

    #[must_use]
    pub fn exports_hierarchy_ext(&self) -> &[PackageIfcFns] {
        self.exim.get_exports_hierarchy_ext()
    }

    #[must_use]
    pub fn imported_functions(&self) -> &[FunctionMetadata] {
        &self.exim.imports_flat
    }

    #[must_use]
    pub fn into_worker(
        self,
        cancel_registry: CancelRegistry,
        log_forwarder_sender: &mpsc::Sender<LogInfoAppendRow>,
        logs_storage_config: Option<LogStrageConfig>,
    ) -> ActivityWorker {
        let stdout = StdOutputConfigWithSender::new(
            self.config.forward_stdout,
            log_forwarder_sender,
            LogStreamType::StdOut,
        );
        let stderr = StdOutputConfigWithSender::new(
            self.config.forward_stderr,
            log_forwarder_sender,
            LogStreamType::StdErr,
        );
        ActivityWorker {
            engine: self.engine,
            instance_pre: self.instance_pre,
            exim: self.exim,
            clock_fn: self.clock_fn,
            sleep: self.sleep,
            exported_ffqn_to_index: self.exported_ffqn_to_index,
            config: self.config,
            cancel_registry,
            stdout,
            stderr,
            logs_storage_config,
        }
    }
}

pub struct ActivityWorker {
    engine: Arc<Engine>,
    instance_pre: InstancePre<ActivityCtx>,
    exim: ExIm,
    clock_fn: Box<dyn ClockFn>,
    sleep: Arc<dyn Sleep>,
    exported_ffqn_to_index: hashbrown::HashMap<FunctionFqn, ComponentExportIndex>,
    config: ActivityConfig,
    cancel_registry: CancelRegistry,
    stdout: Option<StdOutputConfigWithSender>,
    stderr: Option<StdOutputConfigWithSender>,
    logs_storage_config: Option<LogStrageConfig>,
}

impl ActivityWorker {
    #[must_use]
    pub fn exported_functions_ext(&self) -> &[FunctionMetadata] {
        self.exim.get_exports(true)
    }

    #[must_use]
    pub fn exports_hierarchy_ext(&self) -> &[PackageIfcFns] {
        self.exim.get_exports_hierarchy_ext()
    }

    #[must_use]
    pub fn imported_functions(&self) -> &[FunctionMetadata] {
        &self.exim.imports_flat
    }
}

#[async_trait]
impl Worker for ActivityWorker {
    fn exported_functions_noext(&self) -> &[FunctionMetadata] {
        self.exim.get_exports(false)
    }

    async fn run(&self, ctx: WorkerContext) -> WorkerResult {
        trace!("Context: {ctx:?}");
        assert!(ctx.event_history.is_empty());
        let cancelation_token = self
            .cancel_registry
            .obtain_cancellation_token(ctx.execution_id.clone());

        let started_at = self.clock_fn.now();
        ctx.worker_span.record(
            "execution_deadline",
            tracing::field::display(&ctx.locked_event.lock_expires_at),
        );

        let ffqn = ctx.ffqn.clone();
        let params = ctx.params.clone();
        let version = ctx.version.clone();
        let worker_span = ctx.worker_span.clone();

        let (mut store, deadline_duration) = match self.create_store(ctx, started_at).await {
            Ok(store) => store,
            Err(err) => return WorkerResult::Err(err),
        };

        let stopwatch_for_reporting = now_tokio_instant(); // Not using `clock_fn` here is ok, value is only used for log reporting.

        let call_function = {
            let call_func_params = match self
                .call_func_params(&ffqn, &params, &version, &mut store)
                .await
            {
                Ok(ok) => ok,
                Err(err) => return WorkerResult::Err(err),
            };
            self.call_func(&mut store, call_func_params)
        };

        tokio::select! { // future's liveness: Dropping the loser immediately.
            res = call_function => {
                let activity_ctx = store.into_data();
                let res = self.process_res(res, &version, activity_ctx);
                worker_span.in_scope(|| {
                    match &res {
                        Ok(worker_res_ok) => {
                            info!(duration = ?stopwatch_for_reporting.elapsed(), "Run finished: {worker_res_ok}");
                        }
                        Err(WorkerError::ExecutorClosing(_)) => {
                            info!("Executor closing");
                        }
                        Err(err) => {
                            info!(%err, duration = ?stopwatch_for_reporting.elapsed(), "Run finished with an error");
                        }
                    }
                });
                return res;
            },
            ()  = self.sleep.sleep(deadline_duration) => {
                let activity_ctx = store.into_data();
                worker_span.in_scope(||
                        info!(duration = ?stopwatch_for_reporting.elapsed(), %started_at,
                        now = %self.clock_fn.now(),
                        "Run timed out")
                    );
                let http_client_traces = Some(activity_ctx.http_hooks.http_client_traces
                    .into_iter()
                        .map(|(req, mut resp)| HttpClientTrace {
                            req,
                            resp: resp.try_recv().ok(),
                        })
                        .collect_vec());
                return WorkerResult::Err(WorkerError::TemporaryTimeout{
                    http_client_traces,
                    version,
                });
            }
            cancel_res = cancelation_token => {
                // TODO: Add http traces
                info!("Activity cancelled");
                assert!(cancel_res.is_ok(), "only closed channels are dropped");
                return WorkerResult::Err(WorkerError::FatalError(FatalError::Cancelled, version));
            }
        }
    }
}

struct CallFuncParams {
    func: wasmtime::component::Func,
    params: Arc<[Val]>,
    result_type: Type,
}

impl ActivityWorker {
    async fn create_store(
        &self,
        ctx: WorkerContext,
        started_at: DateTime<Utc>,
    ) -> Result<(Store<ActivityCtx>, Duration /* deadline duration*/), WorkerError> {
        let preopened_dir = if let Some(directories_config) = &self.config.directories_config {
            let preopened_dir = directories_config
                .parent_preopen_dir
                .join(ctx.execution_id.to_string());
            if !directories_config.reuse_on_retry {
                // Attempt to `rm -rf` before (re)creating the directory.
                match tokio::fs::remove_dir_all(&preopened_dir).await {
                    Ok(()) => {}
                    Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
                    Err(err) => {
                        error!(
                            "Cannot remove old preopened directory that is in the way - {err:?}"
                        );
                        return Err(WorkerError::ActivityPreopenedDirError {
                            reason: format!(
                                "cannot remove old preopened directory that is in the way - {err}"
                            ),
                            detail: format!("{err:?}"),
                            version: ctx.version.clone(),
                        });
                    }
                }
            }
            let res = tokio::fs::create_dir_all(&preopened_dir).await;
            if let Err(err) = res {
                error!("cannot create preopened directory - {err:?}");
                return Err(WorkerError::ActivityPreopenedDirError {
                    reason: format!("cannot create preopened directory - {err}"),
                    detail: format!("{err:?}"),
                    version: ctx.version.clone(),
                });
            }
            Some(preopened_dir)
        } else {
            None
        };
        let lock_expires_at = ctx.locked_event.lock_expires_at;
        let worker_span = ctx.worker_span.clone();
        let version = ctx.version.clone();

        let stdout = self
            .stdout
            .as_ref()
            .map(|it| it.build(&ctx.execution_id, ctx.locked_event.run_id));
        let stderr = self
            .stderr
            .as_ref()
            .map(|it| it.build(&ctx.execution_id, ctx.locked_event.run_id));

        let mut store = match activity_ctx::store(
            &self.engine,
            ctx,
            &self.config,
            self.clock_fn.clone_box(),
            preopened_dir,
            stdout,
            stderr,
            self.logs_storage_config.clone(),
        ) {
            Ok(store) => store,
            Err(ActivityPreopenIoError { err }) => {
                return Err(WorkerError::ActivityPreopenedDirError {
                    reason: format!(
                        "not found although preopened directory was just created - {err}"
                    ),
                    detail: format!("{err:?}"),
                    version,
                });
            }
        };

        // Set fuel.
        if let Some(fuel) = self.config.fuel {
            store
                .set_fuel(fuel)
                .expect("engine must have `consume_fuel` enabled");
        }

        // Configure epoch callback before running the initialization to avoid interruption
        store.epoch_deadline_callback(|store_ctx| {
            let executor_closing = *store_ctx.data().executor_close_watcher.borrow();
            if executor_closing {
                info!("Executor closing");
                Ok(UpdateDeadline::Interrupt) // Interpreted as executor closing in `process_res`
            } else {
                Ok(UpdateDeadline::YieldCustom(
                    1,
                    Box::pin(tokio::task::yield_now()),
                ))
            }
        });

        let deadline_delta = lock_expires_at - started_at;
        let Ok(deadline_duration) = deadline_delta.to_std() else {
            worker_span.in_scope(|| {
                info!(execution_deadline = %lock_expires_at, %started_at,
                    "Timed out - started_at later than execution_deadline");
            });
            return Err(WorkerError::TemporaryTimeout {
                http_client_traces: None,
                version,
            });
        };
        worker_span.record(
            "deadline_duration",
            tracing::field::debug(&deadline_duration),
        );
        Ok((store, deadline_duration))
    }

    async fn call_func_params(
        &self,
        ffqn: &FunctionFqn,
        params: &Params,
        version: &Version,
        store: &mut Store<ActivityCtx>,
    ) -> Result<CallFuncParams, WorkerError> {
        let instance = match self.instance_pre.instantiate_async(&mut *store).await {
            Ok(instance) => instance,
            Err(err) => {
                let reason = err.to_string();
                if reason.starts_with("maximum concurrent") {
                    return Err(WorkerError::LimitReached {
                        reason,
                        version: version.clone(),
                    });
                }
                return Err(WorkerError::FatalError(
                    FatalError::CannotInstantiate {
                        reason: format!("cannot instantiate: {err}"),
                        detail: Some(format!("{err:?}")),
                    },
                    version.clone(),
                ));
            }
        };
        let func = {
            let fn_export_index = self
                .exported_ffqn_to_index
                .get(ffqn)
                .expect("executor only calls `run` with ffqns that are exported");
            instance
                .get_func(&mut *store, fn_export_index)
                .expect("exported function found with wit-parser but not with wasmtime")
        };

        let component_func = func.ty(store);
        let params = match params.as_vals(component_func.params()) {
            Ok(params) => params,
            Err(err) => {
                return Err(WorkerError::FatalError(
                    FatalError::ParamsParsingError(err),
                    version.clone(),
                ));
            }
        };

        let result_types = component_func.results().collect::<Vec<_>>(); // TODO: investigate using the iterator directly.
        assert!(
            result_types.len() == 1,
            "multi-value and void results are not supported, must have been checked in function registry"
        );

        Ok(CallFuncParams {
            func,
            params,
            result_type: result_types
                .into_iter()
                .next()
                .expect("just checked that size == 1"),
        })
    }

    async fn call_func(
        &self,
        store: &mut Store<ActivityCtx>,
        CallFuncParams {
            func,
            params,
            result_type,
        }: CallFuncParams,
    ) -> Result<Result<SupportedFunctionReturnValue, ResultParsingError>, wasmtime::Error> {
        let mut results = vec![Val::Bool(false)];
        let res = func
            .call_async(&mut *store, &params, &mut results)
            .await
            .map(|()| {
                (
                    results.into_iter().next().expect("results size is 1"),
                    result_type,
                )
            });
        res.map(|(val, r#type)| SupportedFunctionReturnValue::new(val, r#type))
    }

    fn process_res(
        &self,
        res: Result<Result<SupportedFunctionReturnValue, ResultParsingError>, wasmtime::Error>,
        version: &Version,
        activity_ctx: ActivityCtx,
    ) -> WorkerResult {
        let http_client_traces = Some(
            activity_ctx
                .http_hooks
                .http_client_traces
                .into_iter()
                .map(|(req, mut resp)| HttpClientTrace {
                    req,
                    resp: resp.try_recv().ok(),
                })
                .collect_vec(),
        );
        match res {
            Ok(Ok(result)) => WorkerResult::Ok(WorkerResultOk::RunFinished {
                retval: result,
                version: version.clone(),
                http_client_traces,
            }),
            Ok(Err(result_parsing_err)) => WorkerResult::Err(WorkerError::FatalError(
                FatalError::ResultParsingError(result_parsing_err),
                version.clone(),
            )),
            Err(err) => WorkerResult::Err(
                if let Some(trap) = err
                    .source()
                    .and_then(|source| source.downcast_ref::<wasmtime::Trap>())
                {
                    if *trap == wasmtime::Trap::OutOfFuel {
                        WorkerError::ActivityTrap {
                            reason: format!(
                                "total fuel consumed: {}",
                                self.config
                                    .fuel
                                    .expect("must have been set as it was the reason of trap")
                            ),
                            detail: None,
                            trap_kind: TrapKind::OutOfFuel,
                            version: version.clone(),
                            http_client_traces,
                        }
                    } else if *trap == wasmtime::Trap::Interrupt {
                        WorkerError::ExecutorClosing(version.clone())
                    } else {
                        WorkerError::ActivityTrap {
                            reason: trap.to_string(),
                            detail: Some(format!("{err:?}")),
                            trap_kind: TrapKind::Trap,
                            version: version.clone(),
                            http_client_traces,
                        }
                    }
                } else {
                    WorkerError::ActivityTrap {
                        reason: err.to_string(),
                        trap_kind: TrapKind::HostFunctionError,
                        detail: Some(format!("{err:?}")),
                        version: version.clone(),
                        http_client_traces,
                    }
                },
            ),
        }
    }
}

#[cfg(any(test, feature = "test"))]
pub mod test {
    use concepts::{ComponentId, ComponentType, StrVariant, component_id::ComponentDigest};
    use utils::sha256sum::calculate_sha256_file;
    use wasmtime::Engine;

    use crate::{
        RunnableComponent,
        engines::{EngineConfig, Engines},
    };

    pub async fn compile_activity(wasm_path: &str) -> (RunnableComponent, ComponentId) {
        let engine = Engines::get_activity_engine_test(EngineConfig::on_demand_testing()).unwrap();
        compile_activity_with_engine(wasm_path, &engine, ComponentType::Activity).await
    }

    #[allow(dead_code)] // falsly positive
    pub(crate) async fn compile_activity_stub(wasm_path: &str) -> (RunnableComponent, ComponentId) {
        let engine = Engines::get_activity_engine_test(EngineConfig::on_demand_testing()).unwrap();
        compile_activity_with_engine(wasm_path, &engine, ComponentType::ActivityStub).await
    }

    pub(crate) async fn compile_activity_with_engine(
        wasm_path: &str,
        engine: &Engine,
        component_type: ComponentType,
    ) -> (RunnableComponent, ComponentId) {
        assert!(component_type.is_activity());
        let file_digest = calculate_sha256_file(wasm_path).await.unwrap();
        let component_id = ComponentId::new(
            component_type,
            StrVariant::empty(),
            ComponentDigest(file_digest.0),
        )
        .unwrap();
        (
            RunnableComponent::new(wasm_path, engine, component_type).unwrap(),
            component_id,
        )
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::activity::activity_worker::test::compile_activity_with_engine;
    use crate::engines::PoolingOptions;
    use crate::engines::{EngineConfig, Engines};
    use crate::http_hooks::ConfigSectionHint;
    use crate::http_request_policy::{AllowedHostConfig, HostPattern, MethodsPattern};
    use assert_matches::assert_matches;
    use concepts::prefixed_ulid::{DEPLOYMENT_ID_DUMMY, RunId};
    use concepts::storage::http_client_trace::{RequestTrace, ResponseTrace};
    use concepts::storage::{DbPool, TimeoutOutcome};
    use concepts::storage::{ExecutionRequest, Version};
    use concepts::storage::{Locked, LockedBy, PendingState, PendingStatePendingAt};
    use concepts::time::Now;
    use concepts::time::TokioSleep;
    use concepts::{ComponentRetryConfig, ComponentType};
    use concepts::{ExecutionFailureKind, FinishedExecutionError, SUPPORTED_RETURN_VALUE_OK_EMPTY};
    use concepts::{
        ExecutionId, FunctionFqn, Params, SupportedFunctionReturnValue, prefixed_ulid::ExecutorId,
        storage::CreateRequest, storage::DbPoolCloseable,
    };
    use db_tests::Database;
    use executor::executor::LockingStrategy;
    use executor::executor::{ExecConfig, ExecTask};
    use insta::assert_json_snapshot;
    use rstest::rstest;
    use serde_json::json;
    use std::future;
    use std::time::Duration;
    use test_utils::env_or_default;
    use test_utils::sim_clock::SimClock;
    use tracing::{debug, info, info_span};
    use val_json::{
        type_wrapper::TypeWrapper,
        wast_val::{WastVal, WastValWithType},
    };

    pub const SLEEP_LOOP_ACTIVITY_FFQN: FunctionFqn = FunctionFqn::new_static_tuple(
        test_programs_sleep_activity_builder::exports::testing::sleep::sleep::SLEEP_LOOP,
    ); // sleep-loop: func(millis: u64, iterations: u32);
    pub const HTTP_GET_SUCCESSFUL_ACTIVITY: FunctionFqn = FunctionFqn::new_static_tuple(
        test_programs_http_get_activity_builder::exports::testing::http::http_get::GET_SUCCESSFUL,
    );

    pub const FIBO_ACTIVITY_FFQN: FunctionFqn = FunctionFqn::new_static_tuple(
        test_programs_fibo_activity_builder::exports::testing::fibo::fibo::FIBO,
    ); // func(n: u8) -> u64;
    pub const FIBO_10_INPUT: u8 = 10;
    pub const FIBO_10_OUTPUT: u64 = 55;

    fn activity_config(component_id: ComponentId) -> ActivityConfig {
        ActivityConfig {
            component_id,
            forward_stdout: None,
            forward_stderr: None,
            env_vars: Arc::from([]),
            directories_config: None,
            fuel: None,
            allowed_hosts: Arc::from([]),
            config_section_hint: ConfigSectionHint::ActivityWasm,
        }
    }

    pub(crate) fn activity_config_allowed_host(
        component_id: ComponentId,
        allowed_host: &str,
    ) -> ActivityConfig {
        ActivityConfig {
            component_id,
            forward_stdout: None,
            forward_stderr: None,
            env_vars: Arc::from([]),
            directories_config: None,
            fuel: None,
            allowed_hosts: Arc::from(vec![AllowedHostConfig {
                pattern: HostPattern::parse_with_methods(allowed_host, MethodsPattern::AllMethods)
                    .unwrap(),
                secret_env_mappings: Vec::new(),
                replace_in: hashbrown::HashSet::new(),
            }]),
            config_section_hint: ConfigSectionHint::ActivityWasm,
        }
    }

    pub(crate) async fn new_activity_worker(
        wasm_path: &str,
        engine: Arc<Engine>,
        clock_fn: Box<dyn ClockFn>,
        sleep: impl Sleep + 'static,
    ) -> (Arc<dyn Worker>, ComponentId) {
        new_activity_worker_with_config(wasm_path, engine, clock_fn, sleep, activity_config).await
    }

    async fn new_activity_worker_with_config(
        wasm_path: &str,
        engine: Arc<Engine>,
        clock_fn: Box<dyn ClockFn>,
        sleep: impl Sleep + 'static,
        config_fn: impl FnOnce(ComponentId) -> ActivityConfig,
    ) -> (Arc<dyn Worker>, ComponentId) {
        let cancel_registry = CancelRegistry::new();
        let (wasm_component, component_id) =
            compile_activity_with_engine(wasm_path, &engine, ComponentType::Activity).await;
        let (db_forwarder_sender, _) = mpsc::channel(1);
        (
            Arc::new(
                ActivityWorkerCompiled::new_with_config(
                    wasm_component,
                    config_fn(component_id.clone()),
                    engine,
                    clock_fn,
                    Arc::new(sleep),
                )
                .unwrap()
                .into_worker(cancel_registry, &db_forwarder_sender, None),
            ),
            component_id,
        )
    }

    pub(crate) async fn new_activity(
        db_pool: Arc<dyn DbPool>,
        wasm_path: &'static str,
        clock_fn: Box<dyn ClockFn>,
        sleep: impl Sleep + 'static,
        retry_config: ComponentRetryConfig,
        locking_strategy: LockingStrategy,
    ) -> ExecTask {
        new_activity_with_config(
            db_pool,
            wasm_path,
            clock_fn,
            sleep,
            activity_config,
            retry_config,
            locking_strategy,
        )
        .await
    }

    pub(crate) async fn new_activity_with_config(
        db_pool: Arc<dyn DbPool>,
        wasm_path: &'static str,
        clock_fn: Box<dyn ClockFn>,
        sleep: impl Sleep + 'static,
        config_fn: impl FnOnce(ComponentId) -> ActivityConfig,
        retry_config: ComponentRetryConfig,
        locking_strategy: LockingStrategy,
    ) -> ExecTask {
        let engine = Engines::get_activity_engine_test(EngineConfig::on_demand_testing()).unwrap();
        let (worker, component_id) = new_activity_worker_with_config(
            wasm_path,
            engine,
            clock_fn.clone_box(),
            sleep,
            config_fn,
        )
        .await;
        let exec_config = ExecConfig {
            batch_size: 1,
            lock_expiry: Duration::from_secs(1),
            tick_sleep: Duration::ZERO,
            component_id,
            task_limiter: None,
            executor_id: ExecutorId::generate(),
            retry_config,
            locking_strategy,
        };
        ExecTask::new_all_ffqns_test(worker, exec_config, clock_fn, db_pool)
    }

    pub(crate) async fn new_activity_fibo(
        db_pool: Arc<dyn DbPool>,
        clock_fn: Box<dyn ClockFn>,
        sleep: impl Sleep + 'static,
        locking_strategy: LockingStrategy,
    ) -> ExecTask {
        new_activity(
            db_pool,
            test_programs_fibo_activity_builder::TEST_PROGRAMS_FIBO_ACTIVITY,
            clock_fn,
            sleep,
            ComponentRetryConfig::ZERO,
            locking_strategy,
        )
        .await
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) enum TestRetryBehavior {
        SucceedOnRetry,
        Fail { expected_retry_err: &'static str },
    }

    /// Common test helper for testing HTTP GET retry behavior on fallible errors.
    ///
    /// This function tests that:
    /// 1. An activity that returns an error (from a 500 response) triggers a temporary failure with backoff
    /// 2. After the backoff expires, the activity is retried
    /// 3. On retry, either succeeds (if `succeed_eventually` is true) or fails permanently
    pub(crate) async fn run_http_get_retry_test(
        listener: std::net::TcpListener,
        worker: Arc<dyn Worker>,
        ffqn: FunctionFqn,
        make_params: impl FnOnce(&str) -> Params,
        locking_strategy: LockingStrategy,
        expected_err_contains: &str,
        test_retry_behavior: TestRetryBehavior,
    ) {
        use std::ops::Deref;
        use wiremock::{
            Mock, MockServer, ResponseTemplate,
            matchers::{method, path},
        };

        const BODY: &str = "ok";
        const RETRY_EXP_BACKOFF: Duration = Duration::from_millis(10);

        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;

        let server_address = listener
            .local_addr()
            .expect("Failed to get server address.");
        let uri = format!("http://127.0.0.1:{port}", port = server_address.port());

        let retry_config = ComponentRetryConfig {
            max_retries: Some(1),
            retry_exp_backoff: RETRY_EXP_BACKOFF,
        };
        let exec_config = ExecConfig {
            batch_size: 1,
            lock_expiry: Duration::from_secs(1),
            tick_sleep: Duration::ZERO,
            component_id: ComponentId::dummy_activity(),
            task_limiter: None,
            executor_id: ExecutorId::generate(),
            retry_config,
            locking_strategy,
        };
        let ffqns = Arc::from([ffqn.clone()]);
        let exec_task = ExecTask::new_test(
            exec_config,
            worker,
            sim_clock.clone_box(),
            db_pool.clone(),
            ffqns,
        );

        let params = make_params(&uri);
        let execution_id = ExecutionId::generate();
        let created_at = sim_clock.now();
        let db_connection = db_pool.connection_test().await.unwrap();
        db_connection
            .create(CreateRequest {
                created_at,
                execution_id: execution_id.clone(),
                ffqn: ffqn.clone(),
                params,
                parent: None,
                metadata: concepts::ExecutionMetadata::empty(),
                scheduled_at: created_at,
                component_id: ComponentId::dummy_activity(),
                deployment_id: DEPLOYMENT_ID_DUMMY,
                scheduled_by: None,
            })
            .await
            .unwrap();

        let server = MockServer::builder().listener(listener).start().await;
        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(500).set_body_string(BODY))
            .expect(1)
            .mount(&server)
            .await;
        debug!("started mock server on {}", server.address());

        {
            // Expect error result to be interpreted as a temporary failure
            assert_eq!(
                1,
                exec_task
                    .tick_test(sim_clock.now(), RunId::generate())
                    .await
                    .wait_for_tasks()
                    .await
                    .len()
            );
            let exec_log = db_connection.get(&execution_id).await.unwrap();

            let (reason, detail, found_expires_at, http_client_traces) = assert_matches!(
                &exec_log.last_event().event,
                ExecutionRequest::TemporarilyFailed {
                    backoff_expires_at,
                    reason,
                    detail: Some(detail),
                    http_client_traces: Some(http_client_traces)
                }
                => (reason, detail, *backoff_expires_at, http_client_traces)
            );
            assert_eq!(sim_clock.now() + RETRY_EXP_BACKOFF, found_expires_at);
            assert_eq!("activity returned error", reason.deref());
            assert!(
                detail.contains(expected_err_contains),
                "Unexpected detail: {detail}, expected to contain: {expected_err_contains}"
            );

            assert_eq!(1, http_client_traces.len());
            let http_client_trace = http_client_traces.iter().next().unwrap();
            let (method_actual, uri_actual) = assert_matches!(
                http_client_trace,
                HttpClientTrace {
                    req: RequestTrace {
                        method,
                        sent_at: _,
                        uri
                    },
                    resp: Some(ResponseTrace {
                        status: Ok(500),
                        finished_at: _
                    })
                }
                => (method, uri)
            );
            assert_eq!("GET", method_actual);
            assert_eq!(format!("{uri}/"), *uri_actual);
            server.verify().await;
        }

        // Noop until the timeout expires
        assert_eq!(
            0,
            exec_task
                .tick_test(sim_clock.now(), RunId::generate())
                .await
                .wait_for_tasks()
                .await
                .len()
        );
        sim_clock.move_time_forward(RETRY_EXP_BACKOFF);

        server.reset().await;

        if test_retry_behavior == TestRetryBehavior::SucceedOnRetry {
            // Reconfigure the server, return 200
            Mock::given(method("GET"))
                .and(path("/"))
                .respond_with(ResponseTemplate::new(200).set_body_string(BODY))
                .expect(1)
                .mount(&server)
                .await;
            debug!("Reconfigured the server");
        } // otherwise return 404

        assert_eq!(
            1,
            exec_task
                .tick_test(sim_clock.now(), RunId::generate())
                .await
                .wait_for_tasks()
                .await
                .len()
        );
        let exec_log = db_connection.get(&execution_id).await.unwrap();
        let res = assert_matches!(exec_log.last_event().event.clone(), ExecutionRequest::Finished { retval, .. } => retval);
        let wast_val_with_type = match test_retry_behavior {
            TestRetryBehavior::SucceedOnRetry => {
                let wast_val_with_type = assert_matches!(res, SupportedFunctionReturnValue::Ok(Some(wast_val_with_type)) => wast_val_with_type);
                let val = assert_matches!(&wast_val_with_type.value, WastVal::String(val) => val);
                assert_eq!(BODY, val.deref());
                wast_val_with_type
            }
            TestRetryBehavior::Fail { expected_retry_err } => {
                let wast_val_with_type = assert_matches!(res, SupportedFunctionReturnValue::Err(Some(wast_val_with_type)) => wast_val_with_type);
                let val = assert_matches!(&wast_val_with_type.value, WastVal::String(val) => val);
                assert_eq!(expected_retry_err, val.deref());
                wast_val_with_type
            }
        };
        // check types
        assert_matches!(wast_val_with_type.r#type, TypeWrapper::String); // in both cases
        drop(db_connection);
        drop(exec_task);
        db_close.close().await;
    }

    /// Creates an activity worker with allowed host configuration.
    /// Returns the worker and the URI for the allowed host.
    pub(crate) async fn create_activity_worker_with_allowed_host(
        wasm_path: &str,
        listener: &std::net::TcpListener,
    ) -> Arc<dyn Worker> {
        let engine = Engines::get_activity_engine_test(EngineConfig::on_demand_testing()).unwrap();
        let sim_clock = SimClock::default();
        let server_address = listener
            .local_addr()
            .expect("Failed to get server address.");
        let uri = format!("http://127.0.0.1:{port}", port = server_address.port());

        let (worker, _) = new_activity_worker_with_config(
            wasm_path,
            engine,
            sim_clock.clone_box(),
            TokioSleep,
            {
                let uri = uri.clone();
                move |component_id| activity_config_allowed_host(component_id, &uri)
            },
        )
        .await;
        worker
    }

    #[rstest]
    #[tokio::test]
    async fn fibo_once(
        #[values(LockingStrategy::ByFfqns, LockingStrategy::ByComponentDigest)]
        locking_strategy: LockingStrategy,
    ) {
        test_utils::set_up();
        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;
        let db_connection = db_pool.connection().await.unwrap();
        let exec = new_activity_fibo(
            db_pool.clone(),
            sim_clock.clone_box(),
            TokioSleep,
            locking_strategy,
        )
        .await;
        // Create an execution.
        let execution_id = ExecutionId::generate();
        let created_at = sim_clock.now();
        let params = Params::from_json_values_test(vec![json!(FIBO_10_INPUT)]);
        db_connection
            .create(CreateRequest {
                created_at,
                execution_id: execution_id.clone(),
                ffqn: FIBO_ACTIVITY_FFQN,
                params,
                parent: None,
                metadata: concepts::ExecutionMetadata::empty(),
                scheduled_at: created_at,
                component_id: exec.config.component_id.clone(),

                deployment_id: DEPLOYMENT_ID_DUMMY,
                scheduled_by: None,
            })
            .await
            .unwrap();
        // tick
        let executed = exec
            .tick_test_await(sim_clock.now(), RunId::generate())
            .await;
        assert_eq!(vec![execution_id.clone()], executed);
        // Check the result.
        let res = db_connection
            .wait_for_finished_result(
                &execution_id,
                Some(Box::pin(future::ready(TimeoutOutcome::Cancel))),
            )
            .await
            .unwrap();
        let res = assert_matches!(res, SupportedFunctionReturnValue::Ok(ok) => ok);
        let fibo = assert_matches!(res,
            Some(WastValWithType {value: WastVal::U64(val), r#type: TypeWrapper::U64 }) => val);
        assert_eq!(FIBO_10_OUTPUT, fibo);
        drop(db_connection);
        db_close.close().await;
    }

    #[tokio::test]
    async fn limit_reached() {
        const FIBO_INPUT: u8 = 10;
        const LOCK_EXPIRY_MILLIS: u64 = 1100;
        const TASKS: u32 = 10;
        const MAX_INSTANCES: u32 = 1;

        test_utils::set_up();
        let fibo_input = env_or_default("FIBO_INPUT", FIBO_INPUT);
        let lock_expiry =
            Duration::from_millis(env_or_default("LOCK_EXPIRY_MILLIS", LOCK_EXPIRY_MILLIS));
        let tasks = env_or_default("TASKS", TASKS);
        let max_instances = env_or_default("MAX_INSTANCES", MAX_INSTANCES);

        let pool_opts = PoolingOptions {
            pooling_total_component_instances: Some(max_instances),
            pooling_total_stacks: Some(max_instances),
            pooling_total_core_instances: Some(max_instances),
            pooling_total_memories: Some(max_instances),
            pooling_total_tables: Some(max_instances),
            ..Default::default()
        };

        let engine =
            Engines::get_activity_engine_test(EngineConfig::pooling_nocache_testing(pool_opts))
                .unwrap();

        let (fibo_worker, _) = new_activity_worker(
            test_programs_fibo_activity_builder::TEST_PROGRAMS_FIBO_ACTIVITY,
            engine,
            Now.clone_box(),
            TokioSleep,
        )
        .await;
        // create executions
        let join_handles = (0..tasks)
            .map(|_| {
                let fibo_worker = fibo_worker.clone();
                let execution_id = ExecutionId::generate();
                let ctx = WorkerContext {
                    execution_id: execution_id.clone(),
                    metadata: concepts::ExecutionMetadata::empty(),
                    ffqn: FIBO_ACTIVITY_FFQN,
                    params: Params::from_json_values_test(vec![json!(fibo_input)]),
                    event_history: Vec::new(),
                    responses: Vec::new(),
                    version: Version::new(0),
                    can_be_retried: false,
                    worker_span: info_span!("worker-test"),
                    locked_event: Locked {
                        component_id: ComponentId::dummy_activity(),
                        executor_id: ExecutorId::generate(),
                        deployment_id: DEPLOYMENT_ID_DUMMY,
                        run_id: RunId::generate(),
                        lock_expires_at: Now.now() + lock_expiry,
                        retry_config: ComponentRetryConfig::ZERO,
                    },
                    executor_close_watcher: tokio::sync::watch::channel(false).1,
                };
                tokio::spawn(async move { fibo_worker.run(ctx).await })
            })
            .collect::<Vec<_>>();
        let mut limit_reached = 0;
        for jh in join_handles {
            if matches!(
                jh.await.unwrap(),
                WorkerResult::Err(WorkerError::LimitReached { .. })
            ) {
                limit_reached += 1;
            }
        }
        assert!(limit_reached > 0, "Limit was not reached");
    }

    #[rstest::rstest]
    #[case(
            10,
            100,
            SupportedFunctionReturnValue::ExecutionError(FinishedExecutionError{
                kind: ExecutionFailureKind::TimedOut,
                reason: None, detail: None
            })
        )] // 1s -> timeout
    #[case(10, 10, SUPPORTED_RETURN_VALUE_OK_EMPTY)] // 0.1s -> Ok
    #[case(
            1500,
            1,
            SupportedFunctionReturnValue::ExecutionError(FinishedExecutionError{
                kind: ExecutionFailureKind::TimedOut,
                reason: None, detail: None
            })
        )] // 1s -> timeout
    #[tokio::test]
    async fn sleep_should_produce_temporary_timeout(
        #[case] sleep_millis: u32,
        #[case] sleep_iterations: u32,
        #[case] expected: concepts::SupportedFunctionReturnValue,
        #[values(LockingStrategy::ByFfqns, LockingStrategy::ByComponentDigest)]
        locking_strategy: LockingStrategy,
    ) {
        const LOCK_EXPIRY: Duration = Duration::from_millis(500);
        test_utils::set_up();
        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;
        let engine = Engines::get_activity_engine_test(EngineConfig::on_demand_testing()).unwrap();
        let (worker, _) = new_activity_worker(
            test_programs_sleep_activity_builder::TEST_PROGRAMS_SLEEP_ACTIVITY,
            engine,
            sim_clock.clone_box(),
            TokioSleep,
        )
        .await;

        let exec_config = ExecConfig {
            batch_size: 1,
            lock_expiry: LOCK_EXPIRY,
            tick_sleep: Duration::ZERO,
            component_id: ComponentId::dummy_activity(),
            task_limiter: None,
            executor_id: ExecutorId::generate(),
            retry_config: ComponentRetryConfig::ZERO,
            locking_strategy,
        };
        let ffqns = Arc::from([SLEEP_LOOP_ACTIVITY_FFQN]);
        let exec_task = ExecTask::new_test(
            exec_config,
            worker,
            sim_clock.clone_box(),
            db_pool.clone(),
            ffqns,
        );

        // Create an execution.
        let execution_id = ExecutionId::generate();
        info!("Testing {execution_id}");
        let created_at = sim_clock.now();
        let db_connection = db_pool.connection().await.unwrap();
        db_connection
            .create(CreateRequest {
                created_at,
                execution_id: execution_id.clone(),
                ffqn: SLEEP_LOOP_ACTIVITY_FFQN,
                params: Params::from_json_values_test(vec![
                    json!(
                        {"milliseconds": sleep_millis}),
                    json!(sleep_iterations),
                ]),
                parent: None,
                metadata: concepts::ExecutionMetadata::empty(),
                scheduled_at: created_at,
                component_id: ComponentId::dummy_activity(),
                deployment_id: DEPLOYMENT_ID_DUMMY,
                scheduled_by: None,
            })
            .await
            .unwrap();

        // Run the execution via tick.
        assert_eq!(
            1,
            exec_task
                .tick_test(sim_clock.now(), RunId::generate())
                .await
                .wait_for_tasks()
                .await
                .len()
        );

        // Check the result.
        let exec_log = db_connection.get(&execution_id).await.unwrap();
        let retval = assert_matches!(
            exec_log.last_event().event.clone(),
            ExecutionRequest::Finished { retval, .. } => retval
        );
        assert_eq!(expected, retval);

        drop(exec_task);
        db_close.close().await;
    }

    #[rstest::rstest]
    #[case(1, 2_000)] // 1ms * 2000 iterations
    #[case(2_000, 1)] // 2s * 1 iteration
    #[tokio::test]
    async fn long_running_execution_should_timeout(
        #[case] sleep_millis: u64,
        #[case] sleep_iterations: u32,
    ) {
        const TIMEOUT: Duration = Duration::from_millis(200);
        test_utils::set_up();

        let engine = Engines::get_activity_engine_test(EngineConfig::on_demand_testing()).unwrap();

        let sim_clock = SimClock::epoch();
        let (worker, _) = new_activity_worker(
            test_programs_sleep_activity_builder::TEST_PROGRAMS_SLEEP_ACTIVITY,
            engine,
            sim_clock.clone_box(),
            TokioSleep,
        )
        .await;

        let executed_at = sim_clock.now();
        let version = Version::new(10);
        let ctx = WorkerContext {
            execution_id: ExecutionId::generate(),
            metadata: concepts::ExecutionMetadata::empty(),
            ffqn: SLEEP_LOOP_ACTIVITY_FFQN,
            params: Params::from_json_values_test(vec![
                json!(
                    {"milliseconds": sleep_millis}),
                json!(sleep_iterations),
            ]),
            event_history: Vec::new(),
            responses: Vec::new(),
            version: version.clone(),
            can_be_retried: false,
            worker_span: info_span!("worker-test"),
            locked_event: Locked {
                component_id: ComponentId::dummy_activity(),
                executor_id: ExecutorId::generate(),
                deployment_id: DEPLOYMENT_ID_DUMMY,
                run_id: RunId::generate(),
                lock_expires_at: executed_at + TIMEOUT,
                retry_config: ComponentRetryConfig::ZERO,
            },
            executor_close_watcher: tokio::sync::watch::channel(false).1,
        };
        let WorkerResult::Err(err) = worker.run(ctx).await else {
            panic!()
        };
        let actual_version = assert_matches!(
            err,
            WorkerError::TemporaryTimeout {
                http_client_traces:_,
                version
            }
            => version
        );
        assert_eq!(version, actual_version);
    }

    #[tokio::test]
    async fn execution_deadline_before_now_should_timeout() {
        test_utils::set_up();

        let engine = Engines::get_activity_engine_test(EngineConfig::on_demand_testing()).unwrap();
        let sim_clock = SimClock::epoch();
        let (worker, _) = new_activity_worker(
            test_programs_sleep_activity_builder::TEST_PROGRAMS_SLEEP_ACTIVITY,
            engine,
            sim_clock.clone_box(),
            TokioSleep,
        )
        .await;
        // simulate a scheduling problem where deadline < now
        let execution_deadline = sim_clock.now();
        sim_clock.move_time_forward(Duration::from_millis(100));
        let version = Version::new(10);
        let ctx = WorkerContext {
            execution_id: ExecutionId::generate(),
            metadata: concepts::ExecutionMetadata::empty(),
            ffqn: SLEEP_LOOP_ACTIVITY_FFQN,
            params: Params::from_json_values_test(vec![
                json!(
                    {"milliseconds": 1}),
                json!(1),
            ]),
            event_history: Vec::new(),
            responses: Vec::new(),
            version: version.clone(),
            can_be_retried: false,
            worker_span: info_span!("worker-test"),
            locked_event: Locked {
                component_id: ComponentId::dummy_activity(),
                executor_id: ExecutorId::generate(),
                deployment_id: DEPLOYMENT_ID_DUMMY,
                run_id: RunId::generate(),
                lock_expires_at: execution_deadline,
                retry_config: ComponentRetryConfig::ZERO,
            },
            executor_close_watcher: tokio::sync::watch::channel(false).1,
        };
        let WorkerResult::Err(err) = worker.run(ctx).await else {
            panic!()
        };
        let actual_version = assert_matches!(
            err,
            WorkerError::TemporaryTimeout {
                http_client_traces: None,
                version: actual_version,
            }
            => actual_version
        );
        assert_eq!(version, actual_version);
    }

    #[rstest]
    #[tokio::test]
    async fn http_get_simple(
        #[values(LockingStrategy::ByFfqns, LockingStrategy::ByComponentDigest)]
        locking_strategy: LockingStrategy,
    ) {
        use std::ops::Deref;
        use wiremock::{
            Mock, MockServer, ResponseTemplate,
            matchers::{method, path},
        };
        const BODY: &str = "ok";
        test_utils::set_up();
        info!("All set up");
        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;
        let engine = Engines::get_activity_engine_test(EngineConfig::on_demand_testing()).unwrap();

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let server_address = listener
            .local_addr()
            .expect("Failed to get server address.");
        let uri = format!("http://127.0.0.1:{port}", port = server_address.port());

        let (worker, _) = new_activity_worker_with_config(
            test_programs_http_get_activity_builder::TEST_PROGRAMS_HTTP_GET_ACTIVITY,
            engine,
            sim_clock.clone_box(),
            TokioSleep,
            {
                let uri = uri.clone();
                move |component_id| activity_config_allowed_host(component_id, &uri)
            },
        )
        .await;

        let exec_config = ExecConfig {
            batch_size: 1,
            lock_expiry: Duration::from_secs(1),
            tick_sleep: Duration::ZERO,
            component_id: ComponentId::dummy_activity(),
            task_limiter: None,
            executor_id: ExecutorId::generate(),
            retry_config: ComponentRetryConfig::ZERO,
            locking_strategy,
        };
        let ffqns = Arc::from([HTTP_GET_SUCCESSFUL_ACTIVITY]);
        let exec_task = ExecTask::new_test(
            exec_config,
            worker,
            sim_clock.clone_box(),
            db_pool.clone(),
            ffqns,
        );

        let params = Params::from_json_values_test(vec![json!(uri.clone())]);
        let execution_id = ExecutionId::generate();
        let created_at = sim_clock.now();
        let db_connection = db_pool.connection_test().await.unwrap();
        info!("Creating execution");
        let stopwatch = std::time::Instant::now();
        db_connection
            .create(CreateRequest {
                created_at,
                execution_id: execution_id.clone(),
                ffqn: HTTP_GET_SUCCESSFUL_ACTIVITY,
                params,
                parent: None,
                metadata: concepts::ExecutionMetadata::empty(),
                scheduled_at: created_at,
                component_id: ComponentId::dummy_activity(),

                deployment_id: DEPLOYMENT_ID_DUMMY,
                scheduled_by: None,
            })
            .await
            .unwrap();

        let server = MockServer::builder().listener(listener).start().await;
        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(200).set_body_string(BODY))
            .expect(1)
            .mount(&server)
            .await;

        assert_eq!(
            1,
            exec_task
                .tick_test(sim_clock.now(), RunId::generate())
                .await
                .wait_for_tasks()
                .await
                .len()
        );
        let exec_log = db_connection.get(&execution_id).await.unwrap();
        let stopwatch = stopwatch.elapsed();
        info!("Finished in {stopwatch:?}");
        let (res, http_client_traces) = assert_matches!(
                exec_log.last_event().event.clone(),
                ExecutionRequest::Finished { retval, http_client_traces: Some(http_client_traces) }
                => (retval, http_client_traces));
        let wast_val_with_type = assert_matches!(res, SupportedFunctionReturnValue::Ok(Some(wast_val_with_type)) => wast_val_with_type);
        let val = assert_matches!(wast_val_with_type.value, WastVal::String(val) => val);
        assert_eq!(BODY, val.deref());
        // check types
        assert_matches!(wast_val_with_type.r#type, TypeWrapper::String);
        assert_eq!(1, http_client_traces.len());
        let http_client_trace = http_client_traces.into_iter().next().unwrap();
        let (method, uri_actual) = assert_matches!(
            http_client_trace,
            HttpClientTrace {
                req: RequestTrace {
                    method,
                    sent_at: _,
                    uri
                },
                resp: Some(ResponseTrace {
                    status: Ok(200),
                    finished_at: _
                })
            }
            => (method, uri)
        );
        assert_eq!("GET", method);
        assert_eq!(format!("{uri}/"), *uri_actual);
        drop(db_connection);
        drop(exec_task);
        db_close.close().await;
    }

    #[rstest]
    #[tokio::test]
    async fn http_get_activity_trap_should_be_turned_into_finished_execution_error_permanent_failure(
        #[values(LockingStrategy::ByFfqns, LockingStrategy::ByComponentDigest)]
        locking_strategy: LockingStrategy,
    ) {
        use wiremock::{
            Mock, MockServer, ResponseTemplate,
            matchers::{method, path},
        };
        const STATUS: u16 = 418; // I'm a teapot causes trap
        test_utils::set_up();
        info!("All set up");
        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;
        let engine = Engines::get_activity_engine_test(EngineConfig::on_demand_testing()).unwrap();

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let server_address = listener
            .local_addr()
            .expect("Failed to get server address.");
        let uri = format!("http://127.0.0.1:{port}", port = server_address.port());

        let (worker, _) = new_activity_worker_with_config(
            test_programs_http_get_activity_builder::TEST_PROGRAMS_HTTP_GET_ACTIVITY,
            engine,
            sim_clock.clone_box(),
            TokioSleep,
            {
                let uri = uri.clone();
                move |component_id| activity_config_allowed_host(component_id, &uri)
            },
        )
        .await;

        let exec_config = ExecConfig {
            batch_size: 1,
            lock_expiry: Duration::from_secs(1),
            tick_sleep: Duration::ZERO,
            component_id: ComponentId::dummy_activity(),
            task_limiter: None,
            executor_id: ExecutorId::generate(),
            retry_config: ComponentRetryConfig::ZERO,
            locking_strategy,
        };
        let ffqns = Arc::from([HTTP_GET_SUCCESSFUL_ACTIVITY]);
        let exec_task = ExecTask::new_test(
            exec_config,
            worker,
            sim_clock.clone_box(),
            db_pool.clone(),
            ffqns,
        );

        let params = Params::from_json_values_test(vec![json!(uri.clone())]);
        let execution_id = ExecutionId::generate();
        let created_at = sim_clock.now();
        let db_connection = db_pool.connection_test().await.unwrap();
        info!("Creating execution");
        let stopwatch = std::time::Instant::now();
        db_connection
            .create(CreateRequest {
                created_at,
                execution_id: execution_id.clone(),
                ffqn: HTTP_GET_SUCCESSFUL_ACTIVITY,
                params,
                parent: None,
                metadata: concepts::ExecutionMetadata::empty(),
                scheduled_at: created_at,
                component_id: ComponentId::dummy_activity(),

                deployment_id: DEPLOYMENT_ID_DUMMY,
                scheduled_by: None,
            })
            .await
            .unwrap();

        let server = MockServer::builder().listener(listener).start().await;
        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(STATUS).set_body_string(""))
            .expect(1)
            .mount(&server)
            .await;

        assert_eq!(
            1,
            exec_task
                .tick_test(sim_clock.now(), RunId::generate())
                .await
                .wait_for_tasks()
                .await
                .len()
        );
        let exec_log = db_connection.get(&execution_id).await.unwrap();
        let stopwatch = stopwatch.elapsed();
        info!("Finished in {stopwatch:?}");
        let (res, http_client_traces) = assert_matches!(
                exec_log.last_event().event.clone(),
                ExecutionRequest::Finished { retval, http_client_traces: Some(http_client_traces) }
                => (retval, http_client_traces));
        let res = assert_matches!(res, SupportedFunctionReturnValue::ExecutionError(err) => err);
        let reason = assert_matches!(
            res,
            FinishedExecutionError {
                kind: ExecutionFailureKind::Uncategorized,
                reason: Some(reason), // activity trap
                detail: _
            } => reason
        );
        assert!(reason.starts_with("activity trap"), "{reason}");

        assert_eq!(1, http_client_traces.len());
        let http_client_trace = http_client_traces.into_iter().next().unwrap();
        let (method, uri_actual) = assert_matches!(
            http_client_trace,
            HttpClientTrace {
                req: RequestTrace {
                    method,
                    sent_at: _,
                    uri
                },
                resp: Some(ResponseTrace {
                    status: Ok(STATUS),
                    finished_at: _
                })
            }
            => (method, uri)
        );
        assert_eq!("GET", method);
        assert_eq!(format!("{uri}/"), *uri_actual);
        drop(db_connection);
        drop(exec_task);
        db_close.close().await;
    }

    #[rstest::rstest]
    #[tokio::test]
    async fn http_get_retry_on_fallible_err(
        #[values(TestRetryBehavior::SucceedOnRetry,TestRetryBehavior::Fail { expected_retry_err: "wrong status code: 404" })]
        test_retry_behavior: TestRetryBehavior,
        #[values(LockingStrategy::ByFfqns, LockingStrategy::ByComponentDigest)]
        locking_strategy: LockingStrategy,
    ) {
        test_utils::set_up();

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let worker = create_activity_worker_with_allowed_host(
            test_programs_http_get_activity_builder::TEST_PROGRAMS_HTTP_GET_ACTIVITY,
            &listener,
        )
        .await;

        run_http_get_retry_test(
            listener,
            worker,
            HTTP_GET_SUCCESSFUL_ACTIVITY,
            |uri| Params::from_json_values_test(vec![json!(uri)]),
            locking_strategy,
            "wrong status code: 500",
            test_retry_behavior,
        )
        .await;
    }

    #[tokio::test]
    async fn http_get_denied_host() {
        use wiremock::{
            Mock, MockServer, ResponseTemplate,
            matchers::{method, path},
        };
        test_utils::set_up();
        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;
        let engine = Engines::get_activity_engine_test(EngineConfig::on_demand_testing()).unwrap();

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let server_address = listener.local_addr().unwrap();
        let uri = format!("http://127.0.0.1:{port}", port = server_address.port());

        // Create worker with NO allowed hosts - the request should be denied
        let (worker, _) = new_activity_worker_with_config(
            test_programs_http_get_activity_builder::TEST_PROGRAMS_HTTP_GET_ACTIVITY,
            engine,
            sim_clock.clone_box(),
            TokioSleep,
            activity_config, // no allowed hosts
        )
        .await;

        let exec_config = ExecConfig {
            batch_size: 1,
            lock_expiry: Duration::from_secs(1),
            tick_sleep: Duration::ZERO,
            component_id: ComponentId::dummy_activity(),
            task_limiter: None,
            executor_id: ExecutorId::generate(),
            retry_config: ComponentRetryConfig::ZERO,
            locking_strategy: LockingStrategy::ByComponentDigest,
        };
        let ffqns = Arc::from([HTTP_GET_SUCCESSFUL_ACTIVITY]);
        let exec_task = ExecTask::new_test(
            exec_config,
            worker,
            sim_clock.clone_box(),
            db_pool.clone(),
            ffqns,
        );

        let params = Params::from_json_values_test(vec![json!(uri.clone())]);
        let execution_id = ExecutionId::generate();
        let created_at = sim_clock.now();
        let db_connection = db_pool.connection_test().await.unwrap();
        db_connection
            .create(CreateRequest {
                created_at,
                execution_id: execution_id.clone(),
                ffqn: HTTP_GET_SUCCESSFUL_ACTIVITY,
                params,
                parent: None,
                metadata: concepts::ExecutionMetadata::empty(),
                scheduled_at: created_at,
                component_id: ComponentId::dummy_activity(),
                deployment_id: DEPLOYMENT_ID_DUMMY,
                scheduled_by: None,
            })
            .await
            .unwrap();

        let server = MockServer::builder().listener(listener).start().await;
        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(ResponseTemplate::new(200).set_body_string("should not reach"))
            .expect(0) // Should NOT be called since host is denied
            .mount(&server)
            .await;

        assert_eq!(
            1,
            exec_task
                .tick_test(sim_clock.now(), RunId::generate())
                .await
                .wait_for_tasks()
                .await
                .len()
        );
        let exec_log = db_connection.get(&execution_id).await.unwrap();
        let retval = assert_matches!(
            exec_log.last_event().event.clone(),
            ExecutionRequest::Finished { retval, .. } => retval
        );
        // The execution should fail with an ExecutionError when the WASM traps.
        // The trap happens because the HTTP request is denied and the WASM unwraps the error.
        let err = assert_matches!(retval, SupportedFunctionReturnValue::Err(Some(err)) => err);
        let err = assert_matches!(err.value, WastVal::String(err) => err);
        assert_eq!("ErrorCode::HttpRequestDenied", err);
        // Verify the mock server was not called (request was blocked before reaching it)
        server.verify().await;
        drop(db_connection);
        drop(exec_task);
        db_close.close().await;
    }

    #[rstest]
    #[tokio::test]
    async fn http_get_with_secret(
        #[values(LockingStrategy::ByFfqns, LockingStrategy::ByComponentDigest)]
        locking_strategy: LockingStrategy,
    ) {
        use crate::http_request_policy::{AllowedHostConfig, MethodsPattern, ReplacementLocation};
        use hashbrown::HashSet;
        use secrecy::SecretString;
        use wiremock::{
            Mock, MockServer, ResponseTemplate,
            matchers::{header, method, path, query_param},
        };
        const SECRET_VALUE: &str = "my-secret-api-key-12345";
        const SECRET_ENV_VAR: &str = "TEST_API_KEY";
        test_utils::set_up();
        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;
        let engine = Engines::get_activity_engine_test(EngineConfig::on_demand_testing()).unwrap();

        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let server_address = listener.local_addr().unwrap();
        let allowed_host = format!("http://127.0.0.1:{port}", port = server_address.port());
        let host_pattern =
            HostPattern::parse_with_methods(&allowed_host, MethodsPattern::AllMethods).unwrap();

        // Create worker with secret configuration
        let (worker, component_id) = new_activity_worker_with_config(
            test_programs_http_get_activity_builder::TEST_PROGRAMS_HTTP_GET_ACTIVITY,
            engine,
            sim_clock.clone_box(),
            TokioSleep,
            {
                let host_pattern = host_pattern.clone();
                move |component_id| ActivityConfig {
                    component_id,
                    forward_stdout: None,
                    forward_stderr: None,
                    env_vars: Arc::from([]),
                    directories_config: None,
                    fuel: None,
                    allowed_hosts: Arc::from(vec![AllowedHostConfig {
                        pattern: host_pattern,
                        secret_env_mappings: vec![(
                            SECRET_ENV_VAR.to_string(),
                            SecretString::from(SECRET_VALUE.to_string()),
                        )],
                        replace_in: HashSet::from_iter([
                            ReplacementLocation::Headers,
                            ReplacementLocation::Params,
                            ReplacementLocation::Body,
                        ]),
                    }]),
                    config_section_hint: ConfigSectionHint::ActivityWasm,
                }
            },
        )
        .await;

        let exec_config = ExecConfig {
            batch_size: 1,
            lock_expiry: Duration::from_secs(1),
            tick_sleep: Duration::ZERO,
            component_id: component_id.clone(),
            task_limiter: None,
            executor_id: ExecutorId::generate(),
            retry_config: ComponentRetryConfig::ZERO,
            locking_strategy,
        };
        let secret_get_ffqn: FunctionFqn =
            FunctionFqn::new_static("testing:http/http-get", "secret-get");
        let ffqns = Arc::from([secret_get_ffqn.clone()]);
        let exec_task = ExecTask::new_test(
            exec_config,
            worker,
            sim_clock.clone_box(),
            db_pool.clone(),
            ffqns,
        );

        // secret-get takes: url, env_var, header (optional)
        // The url contains the placeholder which gets replaced with the secret
        let url_with_placeholder = format!("{allowed_host}/?secret={SECRET_ENV_VAR}");
        let header_with_placeholder =
            Some(("X-API-Key".to_string(), format!("Bearer {SECRET_ENV_VAR}")));
        let params = Params::from_json_values_test(vec![
            json!(url_with_placeholder),
            json!(SECRET_ENV_VAR),
            json!(header_with_placeholder),
        ]);
        let execution_id = ExecutionId::generate();
        let created_at = sim_clock.now();
        let db_connection = db_pool.connection_test().await.unwrap();
        db_connection
            .create(CreateRequest {
                created_at,
                execution_id: execution_id.clone(),
                ffqn: secret_get_ffqn.clone(),
                params,
                parent: None,
                metadata: concepts::ExecutionMetadata::empty(),
                scheduled_at: created_at,
                component_id,
                deployment_id: DEPLOYMENT_ID_DUMMY,
                scheduled_by: None,
            })
            .await
            .unwrap();

        let server = MockServer::builder().listener(listener).start().await;
        // Verify the secret was replaced in both query params and headers
        Mock::given(method("GET"))
            .and(path("/"))
            .and(query_param("secret", SECRET_VALUE))
            .and(header("X-API-Key", format!("Bearer {SECRET_VALUE}")))
            .respond_with(ResponseTemplate::new(200).set_body_string("secret-received"))
            .expect(1)
            .mount(&server)
            .await;

        assert_eq!(
            1,
            exec_task
                .tick_test(sim_clock.now(), RunId::generate())
                .await
                .wait_for_tasks()
                .await
                .len()
        );
        let exec_log = db_connection.get(&execution_id).await.unwrap();
        let retval = assert_matches!(
            exec_log.last_event().event.clone(),
            ExecutionRequest::Finished { retval, .. } => retval
        );
        // Should succeed with the secret replaced
        assert_matches!(retval, SupportedFunctionReturnValue::Ok(..));
        server.verify().await;
        drop(db_connection);
        drop(exec_task);
        db_close.close().await;
    }

    #[rstest]
    #[tokio::test]
    async fn preopened_dir_sanity(
        #[values(LockingStrategy::ByFfqns, LockingStrategy::ByComponentDigest)]
        locking_strategy: LockingStrategy,
    ) {
        test_utils::set_up();
        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;
        let db_connection = db_pool.connection().await.unwrap();
        let parent_preopen_tempdir = tempfile::tempdir().unwrap();
        let parent_preopen_dir = Arc::from(parent_preopen_tempdir.path());
        let retry_config = ComponentRetryConfig {
            max_retries: Some(1), // should fail in first try
            retry_exp_backoff: Duration::ZERO,
        };
        let exec = new_activity_with_config(
            db_pool.clone(),
            test_programs_dir_activity_builder::TEST_PROGRAMS_DIR_ACTIVITY,
            sim_clock.clone_box(),
            TokioSleep,
            move |component_id| ActivityConfig {
                component_id,
                forward_stdout: None,
                forward_stderr: None,
                env_vars: Arc::default(),
                directories_config: Some(ActivityDirectoriesConfig {
                    parent_preopen_dir,
                    reuse_on_retry: true, // relies on continuing in the same folder
                    process_provider: None,
                }),
                fuel: None,
                allowed_hosts: Arc::from([]),
                config_section_hint: ConfigSectionHint::ActivityWasm,
            },
            retry_config,
            locking_strategy,
        )
        .await;
        // Create an execution.
        let execution_id = ExecutionId::generate();
        let created_at = sim_clock.now();
        db_connection
            .create(CreateRequest {
                created_at,
                execution_id: execution_id.clone(),
                ffqn: FunctionFqn::new_static_tuple(
                    test_programs_dir_activity_builder::exports::testing::dir::dir::IO,
                ),
                params: Params::empty(),
                parent: None,
                metadata: concepts::ExecutionMetadata::empty(),
                scheduled_at: created_at,
                component_id: exec.config.component_id.clone(),

                deployment_id: DEPLOYMENT_ID_DUMMY,
                scheduled_by: None,
            })
            .await
            .unwrap();
        let run_id = RunId::generate();
        let executed = exec.tick_test_await(sim_clock.now(), run_id).await;
        assert_eq!(vec![execution_id.clone()], executed);
        // First execution should have failed
        let pending_state = db_connection
            .get_pending_state(&execution_id)
            .await
            .unwrap()
            .pending_state;
        let (scheduled_at, found_run_id) = assert_matches!(pending_state,
                PendingState::PendingAt(PendingStatePendingAt {
                    scheduled_at,
                    last_lock: Some(LockedBy { executor_id: _, run_id }),
                })
            => (scheduled_at, run_id));
        // retry_exp_backoff is 0
        assert_eq!(sim_clock.now(), scheduled_at);
        assert_eq!(run_id, found_run_id);

        let executed = exec
            .tick_test_await(sim_clock.now(), RunId::generate())
            .await;
        assert_eq!(vec![execution_id.clone()], executed);

        // Check the result.
        let res = db_connection
            .wait_for_finished_result(
                &execution_id,
                Some(Box::pin(future::ready(TimeoutOutcome::Cancel))),
            )
            .await
            .unwrap();
        assert_matches!(res, SupportedFunctionReturnValue::Ok(..));

        db_close.close().await;
    }

    #[rstest::rstest(
            ffqn => [FunctionFqn::new_static_tuple(
                    test_programs_process_activity_builder::exports::testing::process::process::TOUCH,
                ), FunctionFqn::new_static_tuple(
                    test_programs_process_activity_builder::exports::testing::process::process::KILL,
                ),
                FunctionFqn::new_static_tuple(
                    test_programs_process_activity_builder::exports::testing::process::process::STDIO,
                )],
        )]
    #[tokio::test]
    async fn process_sanity(
        ffqn: FunctionFqn,
        #[values(LockingStrategy::ByFfqns, LockingStrategy::ByComponentDigest)]
        locking_strategy: LockingStrategy,
    ) {
        test_utils::set_up();
        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;
        let db_connection = db_pool.connection().await.unwrap();
        let parent_preopen_tempdir = tempfile::tempdir().unwrap();
        let parent_preopen_dir = Arc::from(parent_preopen_tempdir.path());
        let exec = new_activity_with_config(
            db_pool.clone(),
            test_programs_process_activity_builder::TEST_PROGRAMS_PROCESS_ACTIVITY,
            sim_clock.clone_box(),
            TokioSleep,
            move |component_id| ActivityConfig {
                component_id,
                forward_stdout: Some(StdOutputConfig::Stderr),
                forward_stderr: Some(StdOutputConfig::Stderr),
                env_vars: Arc::default(),
                directories_config: Some(ActivityDirectoriesConfig {
                    parent_preopen_dir,
                    reuse_on_retry: false,
                    process_provider: Some(ProcessProvider::Native),
                }),
                fuel: None,
                allowed_hosts: Arc::from([]),
                config_section_hint: ConfigSectionHint::ActivityWasm,
            },
            ComponentRetryConfig::ZERO,
            locking_strategy,
        )
        .await;
        // Create an execution.
        let execution_id = ExecutionId::generate();
        let created_at = sim_clock.now();
        db_connection
            .create(CreateRequest {
                created_at,
                execution_id: execution_id.clone(),
                ffqn,
                params: Params::empty(),
                parent: None,
                metadata: concepts::ExecutionMetadata::empty(),
                scheduled_at: created_at,
                component_id: exec.config.component_id.clone(),

                deployment_id: DEPLOYMENT_ID_DUMMY,
                scheduled_by: None,
            })
            .await
            .unwrap();
        let executed = exec
            .tick_test_await(sim_clock.now(), RunId::generate())
            .await;
        assert_eq!(vec![execution_id.clone()], executed);
        // Check the result.
        let res = db_connection
            .wait_for_finished_result(
                &execution_id,
                Some(Box::pin(future::ready(TimeoutOutcome::Cancel))),
            )
            .await
            .unwrap();
        assert_matches!(res, SupportedFunctionReturnValue::Ok(..));
        db_close.close().await;
    }

    #[tokio::test]
    async fn process_api_not_enabled_should_produce_meaningful_error() {
        test_utils::set_up();
        let sim_clock = SimClock::default();

        let engine = Engines::get_activity_engine_test(EngineConfig::on_demand_testing()).unwrap();

        let (wasm_component, component_id) = compile_activity_with_engine(
            test_programs_process_activity_builder::TEST_PROGRAMS_PROCESS_ACTIVITY,
            &engine,
            ComponentType::Activity,
        )
        .await;

        let err = ActivityWorkerCompiled::new_with_config(
            wasm_component,
            ActivityConfig {
                component_id,
                forward_stdout: Some(StdOutputConfig::Stderr),
                forward_stderr: Some(StdOutputConfig::Stderr),
                env_vars: Arc::default(),
                directories_config: None,
                fuel: None,
                allowed_hosts: Arc::from([]),
                config_section_hint: ConfigSectionHint::ActivityWasm,
            },
            engine,
            sim_clock.clone_box(),
            Arc::new(TokioSleep),
        )
        .unwrap_err();
        let reason = assert_matches!(err, WasmFileError::LinkingError { reason, .. } => reason);
        assert_eq!(
            r#"activity comopnent imports Process API, but it is not enabled. Use e.g. `directories  = { enabled = true, process_provider = "native"}`"#,
            reason.to_string()
        );
    }

    #[cfg(unix)]
    async fn is_process_running(pid: u32) -> bool {
        let output = tokio::process::Command::new("ps")
            .arg("a")
            .output()
            .await
            .unwrap();
        let stdout = String::from_utf8(output.stdout).unwrap();
        stdout.lines().any(|line| {
            line.split_whitespace()
                .next()
                .is_some_and(|field| field == pid.to_string())
        })
    }

    #[cfg(unix)]
    #[rstest]
    #[tokio::test]
    async fn process_group_cleanup(
        #[values(LockingStrategy::ByFfqns, LockingStrategy::ByComponentDigest)]
        locking_strategy: LockingStrategy,
    ) {
        test_utils::set_up();
        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;
        let db_connection = db_pool.connection().await.unwrap();
        let parent_preopen_tempdir = tempfile::tempdir().unwrap();
        let parent_preopen_dir = Arc::from(parent_preopen_tempdir.path());
        let exec = new_activity_with_config(
            db_pool.clone(),
            test_programs_process_activity_builder::TEST_PROGRAMS_PROCESS_ACTIVITY,
            sim_clock.clone_box(),
            TokioSleep,
            move |component_id| ActivityConfig {
                component_id,
                forward_stdout: None,
                forward_stderr: None,
                env_vars: Arc::from([EnvVar {
                    key: "PATH".to_string(),
                    val: std::env::var("PATH").unwrap(),
                }]),
                directories_config: Some(ActivityDirectoriesConfig {
                    parent_preopen_dir,
                    reuse_on_retry: false,
                    process_provider: Some(ProcessProvider::Native),
                }),
                fuel: None,
                allowed_hosts: Arc::from([]),
                config_section_hint: ConfigSectionHint::ActivityWasm,
            },
            ComponentRetryConfig::ZERO,
            locking_strategy,
        )
        .await;
        // Create an execution.
        let execution_id = ExecutionId::generate();
        let created_at = sim_clock.now();
        db_connection
                .create(CreateRequest {
                    created_at,
                    execution_id: execution_id.clone(),
                    ffqn: FunctionFqn::new_static_tuple(
                        test_programs_process_activity_builder::exports::testing::process::process::EXEC_SLEEP,
                    ),
                    params: Params::empty(),
                    parent: None,
                    metadata: concepts::ExecutionMetadata::empty(),
                    scheduled_at: created_at,
                    component_id: exec.config.component_id.clone(),

                    deployment_id: DEPLOYMENT_ID_DUMMY,
                    scheduled_by: None,
                })
                .await
                .unwrap();
        let executed = exec
            .tick_test_await(sim_clock.now(), RunId::generate())
            .await;
        assert_eq!(vec![execution_id.clone()], executed);
        // Check the result.
        let res = db_connection
            .wait_for_finished_result(
                &execution_id,
                Some(Box::pin(future::ready(TimeoutOutcome::Cancel))),
            )
            .await
            .unwrap();
        let sleep_pid = assert_matches!(res,
                SupportedFunctionReturnValue::Ok(Some(WastValWithType {value,
                    r#type: _})) => value);
        let sleep_pid = assert_matches!(sleep_pid, WastVal::U32(val) => val);
        debug!("Sleep pid: {sleep_pid}");

        // Test that the process was killed
        let mut attempt = 0;
        while is_process_running(sleep_pid).await {
            assert!(attempt < 5, "failed after 5 attemtps");
            attempt += 1;
            tokio::time::sleep(Duration::from_secs(1)).await;
        }

        db_close.close().await;
    }

    #[rstest::rstest(
            param => [
                r#"{"image": "foo", "a": false, "b":false}"#,
                r#"{"b": false, "a":false, "image": "foo"}"#,
                ])]
    #[tokio::test]
    async fn record_field_ordering(
        param: &str,
        #[values(LockingStrategy::ByFfqns, LockingStrategy::ByComponentDigest)]
        locking_strategy: LockingStrategy,
    ) {
        test_utils::set_up();
        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;
        let db_connection = db_pool.connection().await.unwrap();
        let exec = new_activity_with_config(
            db_pool.clone(),
            test_programs_serde_activity_builder::TEST_PROGRAMS_SERDE_ACTIVITY,
            sim_clock.clone_box(),
            TokioSleep,
            move |component_id| ActivityConfig {
                component_id,
                forward_stdout: Some(StdOutputConfig::Stderr),
                forward_stderr: Some(StdOutputConfig::Stderr),
                env_vars: Arc::default(),
                directories_config: None,
                fuel: None,
                allowed_hosts: Arc::from([]),
                config_section_hint: ConfigSectionHint::ActivityWasm,
            },
            ComponentRetryConfig::ZERO,
            locking_strategy,
        )
        .await;
        // Create an execution.
        let ffqn = FunctionFqn::new_static_tuple(
            test_programs_serde_activity_builder::exports::testing::serde::serde::REC,
        );
        let execution_id = ExecutionId::generate();
        let created_at = sim_clock.now();
        db_connection
            .create(CreateRequest {
                created_at,
                execution_id: execution_id.clone(),
                ffqn,
                params: Params::from_json_values_test(vec![serde_json::from_str(param).unwrap()]),
                parent: None,
                metadata: concepts::ExecutionMetadata::empty(),
                scheduled_at: created_at,
                component_id: exec.config.component_id.clone(),

                deployment_id: DEPLOYMENT_ID_DUMMY,
                scheduled_by: None,
            })
            .await
            .unwrap();
        let executed = exec
            .tick_test_await(sim_clock.now(), RunId::generate())
            .await;
        assert_eq!(vec![execution_id.clone()], executed);
        // Check the result.
        let res = db_connection
            .wait_for_finished_result(
                &execution_id,
                Some(Box::pin(future::ready(TimeoutOutcome::Cancel))),
            )
            .await
            .unwrap();
        let record = assert_matches!(res, SupportedFunctionReturnValue::Ok(record) => record);
        assert_json_snapshot!(record);
        db_close.close().await;
    }

    #[rstest]
    #[tokio::test]
    async fn variant_with_optional_none(
        #[values(LockingStrategy::ByFfqns, LockingStrategy::ByComponentDigest)]
        locking_strategy: LockingStrategy,
    ) {
        test_utils::set_up();
        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;
        let db_connection = db_pool.connection().await.unwrap();
        let exec = new_activity_with_config(
            db_pool.clone(),
            test_programs_serde_activity_builder::TEST_PROGRAMS_SERDE_ACTIVITY,
            sim_clock.clone_box(),
            TokioSleep,
            move |component_id| ActivityConfig {
                component_id,
                forward_stdout: Some(StdOutputConfig::Stderr),
                forward_stderr: Some(StdOutputConfig::Stderr),
                env_vars: Arc::default(),
                directories_config: None,
                fuel: None,
                allowed_hosts: Arc::from([]),
                config_section_hint: ConfigSectionHint::ActivityWasm,
            },
            ComponentRetryConfig::ZERO,
            locking_strategy,
        )
        .await;
        // Create an execution.
        let ffqn = FunctionFqn::new_static_tuple(
            test_programs_serde_activity_builder::exports::testing::serde::serde::VAR,
        );
        let execution_id = ExecutionId::generate();
        let created_at = sim_clock.now();
        db_connection
            .create(CreateRequest {
                created_at,
                execution_id: execution_id.clone(),
                ffqn,
                params: Params::from_json_values_test(vec![json!({"var1":null})]),
                parent: None,
                metadata: concepts::ExecutionMetadata::empty(),
                scheduled_at: created_at,
                component_id: exec.config.component_id.clone(),

                deployment_id: DEPLOYMENT_ID_DUMMY,
                scheduled_by: None,
            })
            .await
            .unwrap();
        let executed = exec
            .tick_test_await(sim_clock.now(), RunId::generate())
            .await;
        assert_eq!(vec![execution_id.clone()], executed);
        // Check the result.
        let res = db_connection
            .wait_for_finished_result(
                &execution_id,
                Some(Box::pin(future::ready(TimeoutOutcome::Cancel))),
            )
            .await
            .unwrap();
        let variant = assert_matches!(res, SupportedFunctionReturnValue::Ok(variant) => variant);
        assert_json_snapshot!(variant);
        db_close.close().await;
    }

    #[rstest]
    #[tokio::test]
    async fn permanent_error_variant_should_not_retry(
        #[values(LockingStrategy::ByFfqns, LockingStrategy::ByComponentDigest)]
        locking_strategy: LockingStrategy,
    ) {
        test_utils::set_up();
        let sim_clock = SimClock::default();
        let (_guard, db_pool, db_close) = Database::Memory.set_up().await;
        let db_connection = db_pool.connection().await.unwrap();
        // max_retries > 0, so it would retry if error wasn't permanent
        let retry_config = ComponentRetryConfig {
            max_retries: Some(1),
            retry_exp_backoff: Duration::from_millis(10),
        };
        let exec = new_activity_with_config(
            db_pool.clone(),
            test_programs_serde_activity_builder::TEST_PROGRAMS_SERDE_ACTIVITY,
            sim_clock.clone_box(),
            TokioSleep,
            move |component_id| ActivityConfig {
                component_id,
                forward_stdout: Some(StdOutputConfig::Stderr),
                forward_stderr: Some(StdOutputConfig::Stderr),
                env_vars: Arc::default(),
                directories_config: None,
                fuel: None,
                allowed_hosts: Arc::from([]),
                config_section_hint: ConfigSectionHint::ActivityWasm,
            },
            retry_config,
            locking_strategy,
        )
        .await;
        // Create an execution.
        let ffqn = FunctionFqn::new_static_tuple(
            test_programs_serde_activity_builder::exports::testing::serde::serde::PERMANENT_ERR,
        );
        let execution_id = ExecutionId::generate();
        let created_at = sim_clock.now();
        db_connection
            .create(CreateRequest {
                created_at,
                execution_id: execution_id.clone(),
                ffqn,
                params: Params::empty(),
                parent: None,
                metadata: concepts::ExecutionMetadata::empty(),
                scheduled_at: created_at,
                component_id: exec.config.component_id.clone(),

                deployment_id: DEPLOYMENT_ID_DUMMY,
                scheduled_by: None,
            })
            .await
            .unwrap();
        let executed = exec
            .tick_test_await(sim_clock.now(), RunId::generate())
            .await;
        assert_eq!(vec![execution_id.clone()], executed);
        // Check the result - should be Finished with Err, not TemporarilyFailed
        let res = db_connection
            .wait_for_finished_result(
                &execution_id,
                Some(Box::pin(future::ready(TimeoutOutcome::Cancel))),
            )
            .await
            .unwrap();
        // The permanent-failure variant should prevent retry and finish with Err
        let err = assert_matches!(res, SupportedFunctionReturnValue::Err(err) => err);
        let (key, _) = assert_matches!(
            err,
            Some(WastValWithType {
                value: WastVal::Variant(key, payload),
                ..
            }) => (key, payload)
        );
        assert_eq!("permanent_failure", key.as_snake_str());
        db_close.close().await;
    }
}