hermit-run 0.4.0

Hermit: a deterministic Linux execution engine for reproducible runs, record and replay, and concurrency-race search.
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
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

#[macro_use]
mod macros;

mod fs;
mod mmap;
mod network;
mod random;
mod time;

use std::collections::BTreeMap;
use std::fs::File;
use std::io;
use std::io::Seek;
use std::io::SeekFrom;
use std::ops::Deref;
use std::ops::DerefMut;
use std::os::fd::AsRawFd;
use std::os::fd::FromRawFd;
use std::os::fd::OwnedFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::ffi::OsStringExt;
use std::os::unix::fs::MetadataExt;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Mutex;
use std::sync::OnceLock;

use reverie::Errno;
use reverie::Error;
use reverie::GlobalTool;
use reverie::Guest;
use reverie::Pid;
use reverie::Rdtsc;
use reverie::RdtscResult;
use reverie::Stack;
use reverie::Subscription;
use reverie::Tid;
use reverie::Tool;
use reverie::syscalls::AddrMut;
use reverie::syscalls::Chdir;
use reverie::syscalls::Close;
use reverie::syscalls::Dup3;
use reverie::syscalls::EfdFlags;
use reverie::syscalls::Eventfd2;
use reverie::syscalls::Fcntl;
use reverie::syscalls::FcntlCmd;
use reverie::syscalls::Flock;
use reverie::syscalls::FromToRaw;
use reverie::syscalls::Lseek;
use reverie::syscalls::MemoryAccess;
use reverie::syscalls::OFlag;
use reverie::syscalls::Openat;
use reverie::syscalls::PathPtr;
use reverie::syscalls::ReadAddr;
use reverie::syscalls::Syscall;
use reverie::syscalls::Sysno;
use reverie::syscalls::Unlinkat;
use reverie::syscalls::Whence;
use serde::Deserialize;
use serde::Serialize;
fn capture_guest_fd(pid: Pid, fd: libc::c_int) -> (Option<std::os::fd::OwnedFd>, Option<String>) {
    match crate::fd::duplicate_guest_fd(pid, fd) {
        Ok(duplicate) => (Some(duplicate), None),
        Err(error) if error.raw_os_error() == Some(libc::EBADF) => (None, None),
        Err(error) => (None, Some(error.to_string())),
    }
}

fn same_guest_open_file_description(
    pid: Pid,
    left: libc::c_int,
    right: libc::c_int,
) -> io::Result<bool> {
    const KCMP_FILE: libc::c_int = 0;
    let comparison = unsafe {
        libc::syscall(
            libc::SYS_kcmp,
            pid.as_raw(),
            pid.as_raw(),
            KCMP_FILE,
            left,
            right,
        )
    };
    if comparison == -1 {
        Err(io::Error::last_os_error())
    } else {
        Ok(comparison == 0)
    }
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
struct ReplayFileIdentity {
    device: u64,
    inode: u64,
}

impl ReplayFileIdentity {
    fn from_metadata(metadata: &std::fs::Metadata) -> Self {
        Self {
            device: metadata.dev(),
            inode: metadata.ino(),
        }
    }
}

type MaterializedFiles = BTreeMap<ReplayFileIdentity, BTreeMap<ReplayFileIdentity, OwnedFd>>;

static MATERIALIZED_FILES: OnceLock<Mutex<MaterializedFiles>> = OnceLock::new();

fn materialized_files() -> &'static Mutex<MaterializedFiles> {
    MATERIALIZED_FILES.get_or_init(|| Mutex::new(BTreeMap::new()))
}

fn identity_for_fd(fd: libc::c_int) -> io::Result<ReplayFileIdentity> {
    Ok(ReplayFileIdentity::from_metadata(&std::fs::metadata(
        format!("/proc/self/fd/{fd}"),
    )?))
}

fn replay_root_identity(pid: Pid) -> io::Result<ReplayFileIdentity> {
    Ok(ReplayFileIdentity::from_metadata(&std::fs::metadata(
        format!("/proc/{}/root", pid.as_raw()),
    )?))
}

pub(crate) struct ReplayMaterializationScope {
    identity: ReplayFileIdentity,
    _root: OwnedFd,
}

impl ReplayMaterializationScope {
    pub(crate) fn new(root_fd: libc::c_int) -> io::Result<Self> {
        let root = duplicate_controller_fd(root_fd)?;
        Ok(Self {
            identity: identity_for_fd(root.as_raw_fd())?,
            _root: root,
        })
    }
}

impl Drop for ReplayMaterializationScope {
    fn drop(&mut self) {
        materialized_files()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
            .remove(&self.identity);
    }
}

fn duplicate_controller_fd(fd: libc::c_int) -> io::Result<OwnedFd> {
    let duplicate = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 3) };
    if duplicate < 0 {
        Err(io::Error::last_os_error())
    } else {
        // SAFETY: F_DUPFD_CLOEXEC returned a new descriptor owned by this process.
        Ok(unsafe { OwnedFd::from_raw_fd(duplicate) })
    }
}

fn register_materialized(root: ReplayFileIdentity, object: OwnedFd) -> io::Result<()> {
    let identity = identity_for_fd(object.as_raw_fd())?;
    materialized_files()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .entry(root)
        .or_default()
        .entry(identity)
        .or_insert(object);
    Ok(())
}

fn materialized_file_is_registered(pid: Pid, metadata: &std::fs::Metadata) -> bool {
    let Ok(root) = replay_root_identity(pid) else {
        return false;
    };
    materialized_files()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .get(&root)
        .is_some_and(|files| files.contains_key(&ReplayFileIdentity::from_metadata(metadata)))
}

fn unexpected_pidfd_getfd_fd(
    recorded: &Result<i64, Errno>,
    actual: &Result<i64, Errno>,
) -> Option<libc::c_int> {
    if recorded == actual {
        None
    } else {
        actual.as_ref().ok().map(|fd| *fd as libc::c_int)
    }
}

fn remember_materialized_file(pid: Pid, fd: libc::c_int) {
    let Ok(metadata) = std::fs::metadata(format!("/proc/{}/fd/{fd}", pid.as_raw())) else {
        return;
    };
    if metadata.file_type().is_file() {
        let Ok(root) = replay_root_identity(pid) else {
            return;
        };
        let Ok(object) = crate::record_replay_path::open_process_fd(pid, fd) else {
            return;
        };
        let _ = register_materialized(root, object);
    }
}

pub(crate) fn remember_materialized_object(
    root_fd: libc::c_int,
    fd: libc::c_int,
) -> io::Result<()> {
    let metadata = std::fs::metadata(format!("/proc/self/fd/{fd}"))?;
    if !metadata.file_type().is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "exec materialization did not resolve to a regular file",
        ));
    }
    register_materialized(identity_for_fd(root_fd)?, duplicate_controller_fd(fd)?)
}

#[cfg(test)]
pub(crate) fn registered_materialized_count(root_fd: libc::c_int) -> usize {
    let Ok(root) = identity_for_fd(root_fd) else {
        return 0;
    };
    materialized_files()
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .get(&root)
        .map_or(0, BTreeMap::len)
}

fn remember_materialized_path(
    root: &std::os::fd::OwnedFd,
    start: &std::os::fd::OwnedFd,
    path: &Path,
) -> io::Result<()> {
    let resolved = crate::record_replay_path::resolve_existing_path(root, start, path, false)?;
    remember_materialized_object(root.as_raw_fd(), resolved.object.as_raw_fd())
}

use crate::desync::DesyncError;
use crate::event::OpenMaterialization;
use crate::event_stream::ChildEventStreamIds;
use crate::event_stream::DebugEvent;
use crate::event_stream::EventReader;
use crate::event_stream::EventStreamId;
use crate::event_stream::normalize_unused_args;

#[derive(Serialize, Deserialize)]
pub struct ReplayerThreadState {
    events: EventReader,
    stream_id: EventStreamId,
    child_stream_ids: ChildEventStreamIds,
    bootstrapped: bool,
}

impl Deref for ReplayerThreadState {
    type Target = EventReader;

    fn deref(&self) -> &Self::Target {
        &self.events
    }
}

impl DerefMut for ReplayerThreadState {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.events
    }
}

impl Default for ReplayerThreadState {
    fn default() -> Self {
        panic!("thread state should be explicitly initialized in init_thread_state")
    }
}

/// A Reverie tool that replays syscalls. Note that only syscalls that cannot be
/// made deterministic are forwarded to this tool.
#[derive(Serialize, Deserialize)]
pub struct Replayer {
    // Keep track of the data directory. Each thread uses this path to open its
    // event stream.
    data: PathBuf,
    /// Duplicates of this guest process's captured output endpoints.
    #[serde(skip)]
    stdout: Option<std::os::fd::OwnedFd>,
    #[serde(skip)]
    stderr: Option<std::os::fd::OwnedFd>,
    /// Preserve replayed write ordering independently for each captured stream.
    #[serde(skip)]
    stdout_output_lock: tokio::sync::Mutex<()>,
    #[serde(skip)]
    stderr_output_lock: tokio::sync::Mutex<()>,
    #[serde(skip)]
    stdout_error: Option<String>,
    #[serde(skip)]
    stderr_error: Option<String>,
}

impl Default for Replayer {
    fn default() -> Self {
        Self {
            data: PathBuf::new(),
            stdout: None,
            stderr: None,
            stdout_output_lock: tokio::sync::Mutex::new(()),
            stderr_output_lock: tokio::sync::Mutex::new(()),
            stdout_error: None,
            stderr_error: None,
        }
    }
}

#[reverie::tool]
impl Tool for Replayer {
    type GlobalState = detcore::GlobalState;
    type ThreadState = ReplayerThreadState;

    fn new(pid: Pid, cfg: &<Self::GlobalState as GlobalTool>::Config) -> Self {
        let (stdout, stdout_error) = capture_guest_fd(pid, libc::STDOUT_FILENO);
        let (stderr, stderr_error) = capture_guest_fd(pid, libc::STDERR_FILENO);
        Self {
            data: cfg.replay_data.as_ref().unwrap().clone(),
            stdout,
            stderr,
            stdout_output_lock: tokio::sync::Mutex::new(()),
            stderr_output_lock: tokio::sync::Mutex::new(()),
            stdout_error,
            stderr_error,
        }
    }

    fn init_thread_state(
        &self,
        child: Tid,
        parent: Option<(Tid, &Self::ThreadState)>,
    ) -> Self::ThreadState {
        let stream_id = match parent {
            None => EventStreamId::root(),
            Some((_, state)) => state.child_stream_ids.next(&state.stream_id),
        };
        // We have to unwrap because there is no way to handle errors here.
        ReplayerThreadState {
            events: EventReader::open(&self.data, &stream_id).unwrap_or_else(|err| {
                panic!(
                    "Failed to open {:?} for replay thread {} (physical {}): {}",
                    self.data, stream_id, child, err
                )
            }),
            stream_id,
            child_stream_ids: ChildEventStreamIds::default(),
            bootstrapped: parent.is_some_and(|(_, state)| state.bootstrapped),
        }
    }

    fn subscriptions(config: &<Self::GlobalState as GlobalTool>::Config) -> Subscription {
        // Subscribe to the exact same events as the recorder does.
        crate::recorder::Recorder::subscriptions(config)
    }

    async fn handle_syscall_event<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Error> {
        self.expect_syscall(guest, syscall);

        // NOTE: This match statement should be identical to the one in the
        // recorder. Otherwise, our recorder and replayer will disagree about
        // how syscalls should be handled.
        //
        // FIXME: Figure out a way to avoid duplicate code. (Merge record/replay
        // into a single tool?)
        Ok(match syscall {
            // AUTONOMOUS-BOT-IMPLEMENTED
            Syscall::Execve(_) | Syscall::Execveat(_) => self.handle_exec(guest, syscall).await,
            Syscall::Brk(_) => self.let_through(guest, syscall).await,
            Syscall::Mprotect(_) => self.let_through(guest, syscall).await,
            Syscall::ArchPrctl(_) => {
                // To properly handle arch_prctl, we should prevent calls from
                // using ARCH_SET_CPUID since we already do that for the
                // tracees. However, it is rare for programs to use
                // ARCH_SET_CPUID. For all other arch_prctl subfunctions, we
                // should let it through.
                self.let_through(guest, syscall).await
            }
            Syscall::Read(syscall) => Ok(self.handle_read(guest, syscall).await?),
            Syscall::Pread64(syscall) => self.handle_pread64(guest, syscall).await,
            Syscall::Readv(syscall) => Ok(self
                .handle_readv_family(
                    guest,
                    syscall.iov().map(|a| a.as_raw()),
                    syscall.len(),
                    syscall.into(),
                )
                .await?),
            Syscall::Preadv(syscall) => Ok(self
                .handle_readv_family(
                    guest,
                    syscall.iov().map(|a| a.as_raw()),
                    syscall.iov_len(),
                    syscall.into(),
                )
                .await?),
            Syscall::Preadv2(syscall) => Ok(self
                .handle_readv_family(
                    guest,
                    syscall.iov().map(|a| a.as_raw()),
                    syscall.iov_len() as usize,
                    syscall.into(),
                )
                .await?),
            Syscall::Recvfrom(syscall) => self.handle_recvfrom(guest, syscall).await,
            Syscall::Recvmsg(syscall) => self.handle_recvmsg(guest, syscall).await,
            Syscall::Write(syscall) => Ok(self.handle_write_family(guest, syscall.into()).await?),
            Syscall::Pwrite64(syscall) => {
                Ok(self.handle_write_family(guest, syscall.into()).await?)
            }
            Syscall::Writev(syscall) => Ok(self.handle_write_family(guest, syscall.into()).await?),
            Syscall::Pwritev(syscall) => {
                Ok(self.handle_write_family(guest, syscall.into()).await?)
            }
            Syscall::Pwritev2(syscall) => {
                Ok(self.handle_write_family(guest, syscall.into()).await?)
            }
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(#3598)
            Syscall::Access(_) | Syscall::Faccessat(_) | Syscall::Other(Sysno::faccessat2, _) => {
                self.handle_simple(guest, syscall).await
            }
            Syscall::Lseek(_) => self.handle_optional_fd_position(guest, syscall).await,
            Syscall::Stat(syscall) => self.handle_stat_family(guest, syscall.into()).await,
            Syscall::Fstat(syscall) => self.handle_stat_family(guest, syscall.into()).await,
            Syscall::Lstat(syscall) => self.handle_stat_family(guest, syscall.into()).await,
            Syscall::Newfstatat(syscall) => self.handle_stat_family(guest, syscall.into()).await,
            Syscall::Statfs(syscall) => self.handle_statfs(guest, syscall.buf()).await,
            Syscall::Fstatfs(syscall) => self.handle_statfs(guest, syscall.buf()).await,
            Syscall::Statx(syscall) => self.handle_statx(guest, syscall).await,
            Syscall::Getdents(syscall) => self.handle_getdents(guest, syscall).await,
            Syscall::Getdents64(syscall) => self.handle_getdents64(guest, syscall).await,
            Syscall::Mmap(syscall) => self.handle_mmap(guest, syscall).await,
            // AUTONOMOUS-BOT-IMPLEMENTED
            Syscall::Madvise(syscall) => self.handle_madvise(guest, syscall).await,
            Syscall::Munmap(_) => self.let_through(guest, syscall).await,
            Syscall::Open(_) | Syscall::Openat(_) => {
                self.handle_virtual_fd_create(guest, syscall).await
            }
            Syscall::Openat2(call) => self.handle_openat2(guest, call).await,
            Syscall::Close(_) => self.handle_close(guest, syscall).await,
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(#3598)
            Syscall::Chdir(_) | Syscall::Fchdir(_) => {
                self.handle_working_directory_change(guest, syscall).await
            }
            // AUTONOMOUS-BOT-IMPLEMENTED
            Syscall::Getcwd(call) => self.handle_getcwd(guest, call).await,
            Syscall::Fadvise64(_) => self.handle_simple(guest, syscall).await,
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(PR-3601): the descriptor may be a placeholder,
            // so the recorded result is returned without running the call.
            Syscall::Fsync(_) | Syscall::Fdatasync(_) | Syscall::Syncfs(_) => {
                self.handle_simple(guest, syscall).await
            }
            // AUTONOMOUS-BOT-IMPLEMENTED
            Syscall::Fchmod(_) | Syscall::Fchown(_) => {
                self.handle_descriptor_metadata_change(guest, syscall).await
            }
            // AUTONOMOUS-BOT-IMPLEMENTED
            Syscall::Fsetxattr(_)
            | Syscall::Fremovexattr(_)
            | Syscall::Setxattr(_)
            | Syscall::Lsetxattr(_)
            | Syscall::Removexattr(_)
            | Syscall::Lremovexattr(_) => self.handle_xattr_change(guest, syscall).await,
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(PR-3601)
            Syscall::Getxattr(_)
            | Syscall::Lgetxattr(_)
            | Syscall::Fgetxattr(_)
            | Syscall::Listxattr(_)
            | Syscall::Llistxattr(_)
            | Syscall::Flistxattr(_) => self.handle_xattr_query(guest, syscall).await,
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(#2373)
            Syscall::Flock(call) => self.handle_flock(guest, call).await,
            Syscall::Ftruncate(syscall) => Ok(self.handle_ftruncate(guest, syscall).await?),
            Syscall::Dup(_) => {
                self.handle_replayed_side_effect(guest, syscall, "dup")
                    .await
            }
            Syscall::Dup2(_) => self.handle_dup2(guest, syscall).await,
            Syscall::Dup3(_) => {
                self.handle_replayed_side_effect(guest, syscall, "dup3")
                    .await
            }
            Syscall::Ioctl(syscall) => self.handle_ioctl(guest, syscall).await,
            Syscall::Socket(_) => {
                self.handle_replayed_side_effect(guest, syscall, "socket")
                    .await
            }
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(PR-979): recreate and validate the pidfd on
            // replay. pidfd_open returns a real kernel fd that later modeled
            // descriptor ops (fcntl/poll/waitid/close) act on, so we re-inject
            // it and assert the fd matches the recorded value, catching
            // fd-allocation or target-lifetime drift rather than blindly
            // substituting the recorded number.
            Syscall::PidfdOpen(_) => {
                self.handle_replayed_side_effect(guest, syscall, "pidfd_open")
                    .await
            }
            Syscall::ClockGettime(syscall) => self.handle_clock_gettime(guest, syscall).await,
            Syscall::ClockGetres(syscall) => self.handle_clock_getres(guest, syscall).await,
            Syscall::Gettimeofday(syscall) => self.handle_gettimeofday(guest, syscall).await,
            Syscall::Settimeofday(_) => self.handle_simple(guest, syscall).await,
            Syscall::Time(syscall) => self.handle_time(guest, syscall).await,
            Syscall::Setsockopt(_) => {
                self.handle_replayed_side_effect(guest, syscall, "setsockopt")
                    .await
            }
            Syscall::Fcntl(call)
                if matches!(
                    call.cmd(),
                    FcntlCmd::F_DUPFD(_) | FcntlCmd::F_DUPFD_CLOEXEC(_)
                ) =>
            {
                self.handle_replayed_side_effect(guest, syscall, "fcntl_dupfd")
                    .await
            }
            Syscall::Fcntl(call) if matches!(call.cmd(), FcntlCmd::F_SETFD(_)) => {
                self.handle_replayed_side_effect(guest, syscall, "fcntl_setfd")
                    .await
            }
            Syscall::Fcntl(_) => self.handle_simple(guest, syscall).await,
            Syscall::Connect(_) => self.handle_simple(guest, syscall).await,
            Syscall::Sendto(_) => self.handle_simple(guest, syscall).await,
            Syscall::Sendmsg(_) => self.handle_simple(guest, syscall).await,
            Syscall::Poll(syscall) => self.handle_poll(guest, syscall).await,
            Syscall::Ppoll(syscall) => self.handle_ppoll(guest, syscall).await,
            Syscall::Select(syscall) => self.handle_select(guest, syscall).await,
            Syscall::Pselect6(syscall) => self.handle_pselect6(guest, syscall).await,
            Syscall::EpollWait(syscall) => self.handle_epoll_wait(guest, syscall).await,
            Syscall::Getsockopt(syscall) => self.handle_sockopt_family(guest, syscall.into()).await,
            Syscall::Getpeername(syscall) => {
                self.handle_sockopt_family(guest, syscall.into()).await
            }
            Syscall::Getsockname(syscall) => {
                self.handle_sockopt_family(guest, syscall.into()).await
            }
            Syscall::Getrandom(syscall) => self.handle_getrandom(guest, syscall).await,
            Syscall::Readlink(syscall) => self.handle_readlink(guest, syscall).await,
            // AUTONOMOUS-BOT-IMPLEMENTED
            Syscall::Mkdir(_) => self.handle_mkdir(guest, syscall, false).await,
            Syscall::Unlink(_) => self.handle_optional_path_removal(guest, syscall).await,
            Syscall::Unlinkat(call) => self.handle_unlinkat(guest, call).await,
            // AUTONOMOUS-BOT-IMPLEMENTED
            Syscall::Mkdirat(_) => self.handle_mkdir(guest, syscall, true).await,
            Syscall::Mknodat(_)
            | Syscall::Fchownat(_)
            | Syscall::Linkat(_)
            | Syscall::Renameat(_)
            | Syscall::Renameat2(_)
            | Syscall::Symlinkat(_)
            | Syscall::Fchmodat(_)
            | Syscall::Utimensat(_) => self.handle_confined_path_mutation(guest, syscall).await,
            // AUTONOMOUS-BOT-IMPLEMENTED
            Syscall::Rename(_)
            | Syscall::Link(_)
            | Syscall::Symlink(_)
            | Syscall::Chmod(_)
            | Syscall::Chown(_)
            | Syscall::Lchown(_)
            | Syscall::Mknod(_) => self.handle_confined_path_mutation(guest, syscall).await,
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(#3598): rmdir shares unlink's optional removal.
            Syscall::Rmdir(_) => self.handle_optional_path_removal(guest, syscall).await,
            // AUTONOMOUS-BOT-IMPLEMENTED
            Syscall::Other(Sysno::close_range, _) => self.handle_close_range(guest, syscall).await,
            // AUTONOMOUS-BOT-IMPLEMENTED
            // TODO-HUMAN-REVIEW(#2407): pidfd_getfd is raw in the pinned
            // Reverie. Replay must materialize its real OFD alias and validate
            // both successful fd allocation and failure errno.
            Syscall::Other(Sysno::pidfd_getfd, _) => self.handle_pidfd_getfd(guest, syscall).await,
            unsupported => return Ok(guest.inject_with_retry(unsupported).await?),
        }?)
    }

    // TODO-HUMAN-REVIEW(#2370)
    async fn handle_post_exec<G: Guest<Self>>(&self, guest: &mut G) -> Result<(), Errno> {
        guest.thread_state_mut().bootstrapped = true;
        Ok(())
    }

    async fn handle_rdtsc_event<G: Guest<Self>>(
        &self,
        guest: &mut G,
        _request: Rdtsc,
    ) -> Result<RdtscResult, Errno> {
        next_event!(guest, Rdtsc)
    }
}

impl Replayer {
    // TODO-HUMAN-REVIEW(#2370)
    async fn handle_exec<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        let event = match next_event!(guest, Exec) {
            Ok(event) => event,
            Err(error) => return Err(error),
        };
        let actual_request = self
            .read_exec_request(guest, syscall)
            .unwrap_or_else(|error| {
                panic!("could not read replay exec request after recorded success: {error}")
            });
        assert_eq!(
            actual_request.dirfd, event.request.dirfd,
            "replay exec directory context differs from recording"
        );
        assert_eq!(
            actual_request.flags, event.request.flags,
            "replay exec flags differ from recording"
        );
        let bootstrap_path = if actual_request.path == event.request.path {
            None
        } else {
            let valid_bootstrap_substitution = guest.is_root_thread()
                && !guest.thread_state().bootstrapped
                && matches!(
                    &event.target,
                    crate::event::ExecTarget::Materialize(materialization)
                        if matches!(
                            materialization.base,
                            crate::event::ExecMaterializationBase::Root
                        ) && materialization.path == event.request.path
                );
            assert!(
                valid_bootstrap_substitution,
                "replay exec pathname differs from recording outside the root bootstrap"
            );
            assert!(
                actual_request.path.len() >= event.request.path.len(),
                "private replay bootstrap pathname is shorter than the recorded pathname"
            );
            Some(event.request.path.clone())
        };

        let root = crate::record_replay_path::open_process_root(guest.pid())
            .unwrap_or_else(|error| panic!("could not pin replay root for exec: {error}"));
        for dependency in &event.dependencies {
            let path = PathBuf::from(std::ffi::OsString::from_vec(dependency.path.clone()));
            let start = match dependency.base {
                crate::event::ExecMaterializationBase::Root => {
                    crate::record_replay_path::open_process_root(guest.pid())
                }
                crate::event::ExecMaterializationBase::Cwd => {
                    crate::record_replay_path::open_process_cwd(guest.pid())
                }
                crate::event::ExecMaterializationBase::DirectoryFd(fd) => {
                    crate::record_replay_path::open_process_directory_fd(guest.pid(), fd)
                }
            }
            .unwrap_or_else(|error| panic!("could not pin replay exec dependency base: {error}"));
            let mut snapshot = self
                .open_exec_snapshot(&dependency.image)
                .unwrap_or_else(|error| {
                    panic!("could not open recorded exec dependency snapshot: {error}")
                });
            crate::record_replay_path::materialize_regular_file(
                &root,
                &start,
                &path,
                &dependency.symlinks,
                &mut snapshot,
                dependency.image.digest,
                dependency.image.mode,
            )
            .unwrap_or_else(|error| {
                panic!("could not materialize recorded exec dependency {path:?}: {error}")
            });
            remember_materialized_path(&root, &start, &path).unwrap_or_else(|error| {
                panic!("could not register recorded exec dependency {path:?}: {error}")
            });
        }

        if let crate::event::ExecTarget::Materialize(materialization) = &event.target {
            let path = PathBuf::from(std::ffi::OsString::from_vec(materialization.path.clone()));
            let start = match materialization.base {
                crate::event::ExecMaterializationBase::Root => {
                    crate::record_replay_path::open_process_root(guest.pid())
                }
                crate::event::ExecMaterializationBase::Cwd => {
                    crate::record_replay_path::open_process_cwd(guest.pid())
                }
                crate::event::ExecMaterializationBase::DirectoryFd(fd) => {
                    crate::record_replay_path::open_process_directory_fd(guest.pid(), fd)
                }
            }
            .unwrap_or_else(|error| {
                panic!("could not pin replay exec materialization base: {error}")
            });
            let mut snapshot = self
                .open_exec_snapshot(&event.executable)
                .unwrap_or_else(|error| panic!("could not open recorded exec snapshot: {error}"));
            crate::record_replay_path::materialize_regular_file(
                &root,
                &start,
                &path,
                &materialization.symlinks,
                &mut snapshot,
                event.executable.digest,
                event.executable.mode,
            )
            .and_then(|()| remember_materialized_path(&root, &start, &path))
            .unwrap_or_else(|error| {
                panic!("could not materialize recorded exec target {path:?}: {error}")
            });
        }

        if let crate::event::ExecTarget::RestoreDescriptor(descriptor) = &event.target {
            self.restore_exec_descriptor(guest, descriptor, &event.executable)
                .await
                .unwrap_or_else(|error| {
                    panic!(
                        "could not restore recorded executable descriptor {}: {error}",
                        descriptor.target_fd
                    )
                });
        }

        self.verify_live_exec_target(guest, syscall, &event.executable)
            .await
            .unwrap_or_else(|error| {
                panic!(
                    "replay exec target {:?} (dirfd {}, flags {:#x}) does not match recorded image: {error}",
                    std::ffi::OsString::from_vec(event.request.path.clone()),
                    event.request.dirfd,
                    event.request.flags,
                )
            });

        if let Some(path) = bootstrap_path {
            return self
                .inject_successful_exec_at_path(guest, syscall, &path)
                .await;
        }

        match guest.inject(syscall).await {
            Err(error) => panic!(
                "replayed exec returned {error} after recording successfully replaced the image"
            ),
            Ok(value) => panic!(
                "replayed exec returned {value} after recording successfully replaced the image"
            ),
        }
    }

    async fn inject_successful_exec_at_path<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
        path: &[u8],
    ) -> Result<i64, Errno> {
        let address = match syscall {
            Syscall::Execve(call) => <Option<PathPtr<'_>> as FromToRaw>::into_raw(call.path()),
            Syscall::Execveat(call) => <Option<PathPtr<'_>> as FromToRaw>::into_raw(call.path()),
            _ => unreachable!("bootstrap path rewrite requested for {syscall:?}"),
        };
        assert_ne!(
            address, 0,
            "successful bootstrap exec has a non-null pathname"
        );
        let mut replacement = path.to_vec();
        replacement.push(0);
        guest.memory().write_exact(
            AddrMut::<u8>::from_raw(address).expect("bootstrap pathname address is non-null"),
            &replacement,
        )?;
        match guest.inject(syscall).await {
            Err(error) => panic!(
                "replayed bootstrap exec returned {error} after recording successfully replaced the image"
            ),
            Ok(value) => panic!(
                "replayed bootstrap exec returned {value} after recording successfully replaced the image"
            ),
        }
    }

    // TODO-HUMAN-REVIEW(#2370)
    async fn preserve_materialized_exec_descriptor<G: Guest<Self>>(
        &self,
        guest: &mut G,
        descriptor: &crate::event::ExecDescriptor,
        image: &crate::event::ExecImage,
    ) -> io::Result<bool> {
        let target_path = format!("/proc/{}/fd/{}", guest.pid().as_raw(), descriptor.target_fd);
        let target_metadata = match std::fs::metadata(&target_path) {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
            Err(error) => return Err(error),
        };
        if !target_metadata.file_type().is_file()
            || !materialized_file_is_registered(guest.pid(), &target_metadata)
        {
            return Ok(false);
        }

        let mut actual_status = guest
            .inject_with_retry(
                Fcntl::new()
                    .with_fd(descriptor.target_fd)
                    .with_cmd(FcntlCmd::F_GETFL),
            )
            .await
            .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?
            as libc::c_int;
        const SETTABLE_STATUS_FLAGS: libc::c_int =
            libc::O_APPEND | libc::O_ASYNC | libc::O_DIRECT | libc::O_NOATIME | libc::O_NONBLOCK;
        if actual_status & !SETTABLE_STATUS_FLAGS
            != descriptor.status_flags & !SETTABLE_STATUS_FLAGS
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "materialized exec descriptor immutable status flags differ: expected {:#x}, found {actual_status:#x}",
                    descriptor.status_flags
                ),
            ));
        }
        if actual_status != descriptor.status_flags {
            let normalized = (actual_status & !SETTABLE_STATUS_FLAGS)
                | (descriptor.status_flags & SETTABLE_STATUS_FLAGS);
            let result = guest
                .inject_with_retry(
                    Fcntl::new()
                        .with_fd(descriptor.target_fd)
                        .with_cmd(FcntlCmd::F_SETFL(normalized)),
                )
                .await;
            if result != Ok(0) {
                return Err(io::Error::other(format!(
                    "could not restore materialized exec descriptor status flags: {result:?}"
                )));
            }
            actual_status = guest
                .inject_with_retry(
                    Fcntl::new()
                        .with_fd(descriptor.target_fd)
                        .with_cmd(FcntlCmd::F_GETFL),
                )
                .await
                .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?
                as libc::c_int;
            if actual_status != descriptor.status_flags {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!(
                        "materialized exec descriptor status flags differ after F_SETFL: expected {:#x}, found {actual_status:#x}",
                        descriptor.status_flags
                    ),
                ));
            }
        }

        let actual_offset = guest
            .inject_with_retry(
                Lseek::new()
                    .with_fd(descriptor.target_fd)
                    .with_offset(0)
                    .with_whence(Whence::SEEK_CUR),
            )
            .await;
        match (descriptor.offset, actual_offset) {
            (Some(expected), Ok(actual)) if actual == expected => {}
            (Some(expected), Ok(actual)) => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!(
                        "materialized exec descriptor offset differs: expected {expected}, found {actual}"
                    ),
                ));
            }
            (Some(_), Err(error)) => {
                return Err(io::Error::from_raw_os_error(error.into_raw()));
            }
            (None, Err(Errno::EBADF | Errno::ESPIPE)) => {}
            (None, Err(error)) => {
                return Err(io::Error::from_raw_os_error(error.into_raw()));
            }
            (None, Ok(actual)) => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!(
                        "materialized exec descriptor unexpectedly has seekable offset {actual}"
                    ),
                ));
            }
        }

        let pinned = crate::record_replay_path::open_process_fd(guest.pid(), descriptor.target_fd)?;
        let identity = crate::record_replay_path::file_identity(pinned.as_raw_fd())?;
        if !crate::record_replay_path::is_regular_file(identity) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "materialized exec descriptor is not a regular file",
            ));
        }
        if identity.mode & 0o7777 != image.mode {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "materialized exec descriptor mode differs: expected {:o}, found {:o}",
                    image.mode,
                    identity.mode & 0o7777
                ),
            ));
        }
        let actual_digest = detcore::Digest::digest_reader(
            crate::record_replay_path::open_readable_fd(pinned.as_raw_fd())?,
        )?;
        if actual_digest != image.digest {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "materialized exec descriptor digest differs: expected {}, found {}",
                    image.digest, actual_digest
                ),
            ));
        }

        let mut expected_aliases = descriptor
            .aliases
            .iter()
            .map(|alias| (alias.fd, alias.descriptor_flags))
            .collect::<Vec<_>>();
        expected_aliases.sort_unstable();
        let original_count = expected_aliases.len();
        expected_aliases.dedup_by_key(|alias| alias.0);
        if expected_aliases.len() != original_count {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "recorded exec descriptor contains duplicate aliases",
            ));
        }

        let target_identity = ReplayFileIdentity::from_metadata(&target_metadata);
        let mut actual_aliases = Vec::new();
        for entry in std::fs::read_dir(format!("/proc/{}/fd", guest.pid().as_raw()))? {
            let entry = entry?;
            let Some(fd) = entry
                .file_name()
                .to_str()
                .and_then(|name| name.parse::<libc::c_int>().ok())
            else {
                continue;
            };
            let metadata = match std::fs::metadata(entry.path()) {
                Ok(metadata) => metadata,
                Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
                Err(error) => return Err(error),
            };
            if ReplayFileIdentity::from_metadata(&metadata) != target_identity {
                continue;
            }
            if same_guest_open_file_description(guest.pid(), descriptor.target_fd, fd)? {
                let descriptor_flags = guest
                    .inject_with_retry(Fcntl::new().with_fd(fd).with_cmd(FcntlCmd::F_GETFD))
                    .await
                    .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?
                    as libc::c_int;
                actual_aliases.push((fd, descriptor_flags));
            }
        }
        actual_aliases.sort_unstable();
        if actual_aliases != expected_aliases {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "materialized exec descriptor aliases differ: expected {expected_aliases:?}, found {actual_aliases:?}"
                ),
            ));
        }

        Ok(true)
    }

    // TODO-HUMAN-REVIEW(#2370)
    async fn restore_exec_descriptor<G: Guest<Self>>(
        &self,
        guest: &mut G,
        descriptor: &crate::event::ExecDescriptor,
        image: &crate::event::ExecImage,
    ) -> io::Result<()> {
        if descriptor.aliases.is_empty()
            || !descriptor
                .aliases
                .iter()
                .any(|alias| alias.fd == descriptor.target_fd)
        {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "recorded exec descriptor has no target alias",
            ));
        }
        for alias in &descriptor.aliases {
            let actual = guest
                .inject_with_retry(Fcntl::new().with_fd(alias.fd).with_cmd(FcntlCmd::F_GETFD))
                .await
                .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?
                as libc::c_int;
            if actual != alias.descriptor_flags {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!(
                        "replay descriptor {} flags differ before exec restore: expected {:#x}, found {actual:#x}",
                        alias.fd, alias.descriptor_flags
                    ),
                ));
            }
        }
        if self
            .preserve_materialized_exec_descriptor(guest, descriptor, image)
            .await?
        {
            return Ok(());
        }

        let root = crate::record_replay_path::open_process_root(guest.pid())?;
        let mut snapshot = self.open_exec_snapshot(image)?;
        let private_name = crate::record_replay_path::create_root_temporary_regular_file(
            &root,
            &mut snapshot,
            image.digest,
            image.mode,
        )?;
        let private_path = Path::new("/").join(&private_name);
        let path_bytes = private_path.as_os_str().as_bytes();
        if path_bytes.len() + 1 > 128 {
            let _ = crate::record_replay_path::unlink_root_entry(&root, &private_name);
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "temporary executable pathname is too long",
            ));
        }
        let mut path = [0_u8; 128];
        path[..path_bytes.len()].copy_from_slice(path_bytes);
        let mut stack = guest.stack().await;
        let path_addr = stack.push(path);
        let path_ptr =
            PathPtr::from_ptr(unsafe { path_addr.cast::<u8>().as_ptr().cast::<libc::c_char>() })
                .expect("guest stack address is non-null");
        let _path_guard = stack
            .commit()
            .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?;
        let reopen_flags = OFlag::from_bits_truncate(descriptor.status_flags) | OFlag::O_CLOEXEC;
        let source_fd = match guest
            .inject_with_retry(
                Openat::new()
                    .with_dirfd(libc::AT_FDCWD)
                    .with_path(Some(path_ptr))
                    .with_flags(reopen_flags),
            )
            .await
        {
            Ok(fd) => fd as libc::c_int,
            Err(error) => {
                let _ = crate::record_replay_path::unlink_root_entry(&root, &private_name);
                return Err(io::Error::from_raw_os_error(error.into_raw()));
            }
        };
        drop(_path_guard);
        crate::record_replay_path::unlink_root_entry(&root, &private_name)?;

        let result = async {
            let actual_status = guest
                .inject_with_retry(Fcntl::new().with_fd(source_fd).with_cmd(FcntlCmd::F_GETFL))
                .await
                .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?
                as libc::c_int;
            if actual_status != descriptor.status_flags {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!(
                        "restored exec descriptor status flags differ: expected {:#x}, found {actual_status:#x}",
                        descriptor.status_flags
                    ),
                ));
            }
            if let Some(offset) = descriptor.offset {
                let actual = guest
                    .inject_with_retry(
                        Lseek::new()
                            .with_fd(source_fd)
                            .with_offset(offset)
                            .with_whence(Whence::SEEK_SET),
                    )
                    .await
                    .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?;
                if actual != offset {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!(
                            "restored exec descriptor offset differs: expected {offset}, found {actual}"
                        ),
                    ));
                }
            }

            for alias in &descriptor.aliases {
                let flags = if alias.descriptor_flags & libc::FD_CLOEXEC != 0 {
                    OFlag::O_CLOEXEC
                } else {
                    OFlag::empty()
                };
                let actual = guest
                    .inject_with_retry(
                        Dup3::new()
                            .with_oldfd(source_fd)
                            .with_newfd(alias.fd)
                            .with_flags(flags),
                    )
                    .await
                    .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?;
                if actual != i64::from(alias.fd) {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!(
                            "restored exec descriptor alias returned {actual}, expected {}",
                            alias.fd
                        ),
                    ));
                }
                remember_materialized_file(guest.pid(), alias.fd);
            }
            Ok(())
        }
        .await;
        let close_source = guest
            .inject_with_retry(Close::new().with_fd(source_fd))
            .await;
        if close_source != Ok(0) && result.is_ok() {
            return Err(io::Error::other(format!(
                "could not close executable staging descriptor: {close_source:?}"
            )));
        }
        result
    }

    fn read_exec_request<G: Guest<Self>>(
        &self,
        guest: &G,
        syscall: Syscall,
    ) -> io::Result<crate::event::ExecRequest> {
        let call = match syscall {
            Syscall::Execve(call) => call.into(),
            Syscall::Execveat(call) => call,
            _ => unreachable!("exec request read for {syscall:?}"),
        };
        let path = call
            .path()
            .ok_or_else(|| io::Error::from_raw_os_error(libc::EFAULT))?
            .read(&guest.memory())
            .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?;
        Ok(crate::event::ExecRequest {
            dirfd: call.dirfd(),
            path: path.as_os_str().as_bytes().to_vec(),
            flags: call.flags(),
        })
    }

    fn open_exec_snapshot(&self, image: &crate::event::ExecImage) -> io::Result<File> {
        let path = self
            .data
            .join(crate::consts::EXEC_FILES_NAME)
            .join(image.digest.to_string());
        let metadata = std::fs::symlink_metadata(&path)?;
        if !metadata.file_type().is_file() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("recorded exec snapshot is not a regular file: {path:?}"),
            ));
        }
        let mut file = File::open(&path)?;
        let actual = detcore::Digest::digest_reader(&mut file)?;
        if actual != image.digest {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "recorded exec snapshot digest mismatch at {path:?}: expected {}, found {}",
                    image.digest, actual
                ),
            ));
        }
        file.seek(SeekFrom::Start(0))?;
        Ok(file)
    }

    async fn verify_live_exec_target<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
        expected: &crate::event::ExecImage,
    ) -> io::Result<()> {
        let call = match syscall {
            Syscall::Execve(call) => call.into(),
            Syscall::Execveat(call) => call,
            _ => unreachable!("exec target verification for {syscall:?}"),
        };
        let path_ptr = call
            .path()
            .ok_or_else(|| io::Error::from_raw_os_error(libc::EFAULT))?;
        let path = path_ptr
            .read(&guest.memory())
            .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?;
        let pinned = if path.as_os_str().is_empty() {
            if call.flags() & libc::AT_EMPTY_PATH == 0 {
                return Err(io::Error::from_raw_os_error(libc::ENOENT));
            }
            crate::record_replay_path::open_process_fd(guest.pid(), call.dirfd())?
        } else {
            let mut flags = OFlag::O_PATH | OFlag::O_CLOEXEC;
            if call.flags() & libc::AT_SYMLINK_NOFOLLOW != 0 {
                flags |= OFlag::O_NOFOLLOW;
            }
            let temporary = guest
                .inject_with_retry(
                    reverie::syscalls::Openat::new()
                        .with_dirfd(call.dirfd())
                        .with_path(Some(path_ptr))
                        .with_flags(flags),
                )
                .await
                .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?;
            let pinned =
                crate::record_replay_path::open_process_fd(guest.pid(), temporary as libc::c_int);
            let close = guest
                .inject_with_retry(Close::new().with_fd(temporary as libc::c_int))
                .await;
            if close != Ok(0) {
                return Err(io::Error::other(format!(
                    "could not close temporary replay exec descriptor: {close:?}"
                )));
            }
            pinned?
        };
        let identity = crate::record_replay_path::file_identity(pinned.as_raw_fd())?;
        if !crate::record_replay_path::is_regular_file(identity) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "replay exec target is not a regular file",
            ));
        }
        if identity.mode & 0o7777 != expected.mode {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "replay exec mode differs: expected {:o}, found {:o}",
                    expected.mode,
                    identity.mode & 0o7777
                ),
            ));
        }
        let actual = detcore::Digest::digest_reader(crate::record_replay_path::open_readable_fd(
            pinned.as_raw_fd(),
        )?)?;
        if actual != expected.digest {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "replay exec digest differs: expected {}, found {}",
                    expected.digest, actual
                ),
            ));
        }
        Ok(())
    }

    pub(super) async fn reserve_replay_fd<G: Guest<Self>>(
        &self,
        guest: &mut G,
        fd: i32,
        cloexec: bool,
    ) {
        let flags = if cloexec {
            EfdFlags::EFD_CLOEXEC
        } else {
            EfdFlags::empty()
        };
        let placeholder = guest
            .inject_with_retry(Eventfd2::new().with_count(0).with_flags(flags))
            .await
            .unwrap_or_else(|error| {
                panic!("could not reserve replay FD {fd} with an eventfd: {error}")
            });
        if placeholder != i64::from(fd) {
            let _ = guest.inject(Close::new().with_fd(placeholder as i32)).await;
            panic!(
                "replay FD namespace diverged: expected slot {fd}, placeholder returned {placeholder}"
            );
        }
    }
    pub(super) fn fd_is_in_replay_root(&self, pid: Pid, fd: libc::c_int) -> bool {
        let path = format!("/proc/{}/fd/{fd}", pid.as_raw());
        let Ok(metadata) = std::fs::metadata(&path) else {
            return false;
        };
        if metadata.file_type().is_file() {
            return materialized_file_is_registered(pid, &metadata);
        }
        if !metadata.file_type().is_dir() {
            return false;
        }
        // Compare directory objects, not procfs link text. The guest may live in
        // a mount namespace the replayer cannot name, such as a private tmpfs at
        // `/test`, where the two link texts never share a prefix.
        let (Ok(root), Ok(directory)) = (
            crate::record_replay_path::open_process_root(pid),
            crate::record_replay_path::open_process_directory_fd(pid, fd),
        ) else {
            return false;
        };
        crate::record_replay_path::directory_is_beneath(&root, &directory).unwrap_or(false)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#662): Audit replay path confinement.
    fn open_request<G: Guest<Self>>(
        &self,
        guest: &G,
        syscall: Syscall,
    ) -> io::Result<(libc::c_int, PathBuf, OFlag)> {
        let request = match syscall {
            Syscall::Open(call) => (
                libc::AT_FDCWD,
                call.path()
                    .ok_or_else(|| io::Error::from_raw_os_error(libc::EFAULT))?
                    .read(&guest.memory())
                    .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?,
                call.flags(),
            ),
            Syscall::Openat(call) => (
                call.dirfd(),
                call.path()
                    .ok_or_else(|| io::Error::from_raw_os_error(libc::EFAULT))?
                    .read(&guest.memory())
                    .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?,
                call.flags(),
            ),
            _ => unreachable!("open replay path requested for {syscall:?}"),
        };
        Ok(request)
    }

    /// Decides whether a recorded regular-file open names a file replay may
    /// open for real: a file replay itself materialized, a file the open creates,
    /// or, for `O_TMPFILE`, a directory. Resolution starts from descriptors for
    /// the guest's root and base directory, so it sees the guest's mounts and
    /// symlinks rather than the replayer's. An `O_CREAT` open first creates the
    /// missing parent directories inside the replay root.
    ///
    /// A path that crosses a procfs symlink (`/proc/<pid>/root`,
    /// `/proc/self/fd/<n>`, or `/dev/fd/<n>` through `/proc/self/fd`) is
    /// refused before any directory is created. Its text names a path inside
    /// the replay root, but the guest's kernel follows the link to the linked
    /// object, which may be a host file outside it.
    fn open_materializes_in_replay_root<G: Guest<Self>>(
        &self,
        guest: &G,
        dirfd: libc::c_int,
        path: &Path,
        flags: OFlag,
    ) -> bool {
        let pid = guest.pid();
        let Ok(root) = crate::record_replay_path::open_process_root(pid) else {
            return false;
        };
        let start = if path.is_absolute() {
            crate::record_replay_path::open_process_root(pid)
        } else if dirfd == libc::AT_FDCWD {
            crate::record_replay_path::open_process_cwd(pid)
        } else {
            crate::record_replay_path::open_process_directory_fd(pid, dirfd)
        };
        let Ok(start) = start else {
            return false;
        };
        if !crate::record_replay_path::directory_is_beneath(&root, &start).unwrap_or(false) {
            return false;
        }
        let parent = path
            .parent()
            .filter(|parent| !parent.as_os_str().is_empty());
        if flags.contains(OFlag::O_CREAT)
            && let Some(parent) = parent
            && let Err(error) =
                crate::record_replay_path::ensure_directory_path_follow_final_without_procfs_symlinks(
                    &root, &start, parent,
                )
            && error.raw_os_error() == Some(libc::ELOOP)
        {
            return false;
        }
        let metadata =
            |object: &OwnedFd| std::fs::metadata(format!("/proc/self/fd/{}", object.as_raw_fd()));
        match crate::record_replay_path::resolve_existing_path_without_procfs_symlinks(
            &root, &start, path,
        ) {
            Ok(resolved) => match metadata(&resolved.object) {
                Ok(found) if flags.contains(OFlag::O_TMPFILE) => found.is_dir(),
                Ok(found) if found.file_type().is_file() => {
                    materialized_file_is_registered(pid, &found)
                }
                _ => false,
            },
            Err(error)
                if error.raw_os_error() == Some(libc::ENOENT)
                    && flags.contains(OFlag::O_CREAT)
                    && !flags.contains(OFlag::O_TMPFILE) =>
            {
                // Only the final component may be missing.
                match parent {
                    None => true,
                    Some(parent) => {
                        crate::record_replay_path::resolve_existing_path_without_procfs_symlinks(
                            &root, &start, parent,
                        )
                    }
                    .and_then(|resolved| metadata(&resolved.object))
                    .is_ok_and(|found| found.is_dir()),
                }
            }
            Err(_) => false,
        }
    }

    fn materialize_recorded_directory<G: Guest<Self>>(
        &self,
        guest: &G,
        syscall: Syscall,
        dirfd: libc::c_int,
        path: &Path,
        flags: OFlag,
    ) -> io::Result<bool> {
        let root = crate::record_replay_path::open_process_root(guest.pid())?;
        let start = if path.is_absolute() {
            crate::record_replay_path::open_process_root(guest.pid())?
        } else if dirfd == libc::AT_FDCWD {
            crate::record_replay_path::open_process_cwd(guest.pid())?
        } else {
            let start =
                match crate::record_replay_path::open_process_directory_fd(guest.pid(), dirfd) {
                    Ok(start) => start,
                    Err(error) if error.raw_os_error() == Some(libc::ENOTDIR) => {
                        tracing::debug!(
                            ?syscall,
                            "recorded open directory base is a virtual replay descriptor"
                        );
                        return Ok(false);
                    }
                    Err(error) => return Err(error),
                };
            match crate::record_replay_path::directory_is_beneath(&root, &start)? {
                true => {}
                false => {
                    tracing::debug!(
                        ?syscall,
                        "recorded open directory base is not confined to replay root"
                    );
                    return Ok(false);
                }
            }
            start
        };
        if flags.contains(OFlag::O_NOFOLLOW) {
            crate::record_replay_path::ensure_directory_path(&root, &start, path)?;
        } else {
            crate::record_replay_path::ensure_directory_path_follow_final(&root, &start, path)?;
        }
        Ok(true)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#662): Audit replay-root file and directory materialization.
    async fn handle_virtual_fd_create<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        let event = next_event!(guest, Open)?;
        let recorded = event.result;
        if let Ok(fd) = recorded {
            let (dirfd, path, flags) = self.open_request(guest, syscall).unwrap_or_else(|error| {
                panic!("could not decode successful recorded open: {error}")
            });
            let materialize = match event.materialize {
                OpenMaterialization::Directory => self
                    .materialize_recorded_directory(guest, syscall, dirfd, &path, flags)
                    .unwrap_or_else(|error| {
                        panic!("failed to materialize recorded open directory: {error}")
                    }),
                OpenMaterialization::RegularFile => {
                    self.open_materializes_in_replay_root(guest, dirfd, &path, flags)
                }
                OpenMaterialization::None => false,
            };
            if materialize {
                match guest.inject_with_retry(syscall).await {
                    Ok(actual) => {
                        assert_eq!(
                            actual, fd,
                            "replay materialized open returned a different descriptor"
                        );
                        remember_materialized_file(guest.pid(), actual as libc::c_int);
                    }
                    Err(error) => {
                        tracing::debug!(
                            ?syscall,
                            %error,
                            "replay path unavailable; reserving a virtual descriptor"
                        );
                        self.reserve_replay_fd(guest, fd as i32, flags.contains(OFlag::O_CLOEXEC))
                            .await;
                    }
                }
            } else {
                self.reserve_replay_fd(guest, fd as i32, flags.contains(OFlag::O_CLOEXEC))
                    .await;
            }
        }
        recorded
    }

    fn mkdir_request<G: Guest<Self>>(
        &self,
        guest: &G,
        syscall: Syscall,
    ) -> io::Result<(libc::c_int, PathBuf)> {
        let (dirfd, path) = match syscall {
            Syscall::Mkdir(call) => (
                libc::AT_FDCWD,
                call.path()
                    .ok_or_else(|| io::Error::from_raw_os_error(libc::EFAULT))?
                    .read(&guest.memory())
                    .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?,
            ),
            Syscall::Mkdirat(call) => (
                call.dirfd(),
                call.path()
                    .ok_or_else(|| io::Error::from_raw_os_error(libc::EFAULT))?
                    .read(&guest.memory())
                    .map_err(|error| io::Error::from_raw_os_error(error.into_raw()))?,
            ),
            _ => unreachable!("mkdir replay path requested for {syscall:?}"),
        };
        Ok((dirfd, path))
    }

    fn materialize_recorded_mkdir<G: Guest<Self>>(
        &self,
        guest: &G,
        syscall: Syscall,
    ) -> io::Result<bool> {
        let (dirfd, path) = self.mkdir_request(guest, syscall)?;
        let root = crate::record_replay_path::open_process_root(guest.pid())?;
        if path.is_absolute() {
            crate::record_replay_path::ensure_directory_path(&root, &root, &path)?;
            return Ok(true);
        }

        let start = if dirfd == libc::AT_FDCWD {
            crate::record_replay_path::open_process_cwd(guest.pid())?
        } else {
            match crate::record_replay_path::open_process_directory_fd(guest.pid(), dirfd) {
                Ok(start) => start,
                Err(error) if error.raw_os_error() == Some(libc::ENOTDIR) => {
                    tracing::debug!(
                        ?syscall,
                        "recorded mkdir directory base is a virtual replay descriptor"
                    );
                    return Ok(false);
                }
                Err(error) => return Err(error),
            }
        };
        match crate::record_replay_path::directory_is_beneath(&root, &start)? {
            true => {}
            false => {
                tracing::debug!(
                    ?syscall,
                    "recorded mkdir directory base is not confined to replay root"
                );
                return Ok(false);
            }
        }
        crate::record_replay_path::ensure_directory_path(&root, &start, &path)?;
        Ok(true)
    }

    // TODO-HUMAN-REVIEW(#2370)
    /// Replays successful mkdir side effects exactly as before. For a recorded
    /// `EEXIST` caused by a directory, it reconstructs that directory in the
    /// fresh chroot while still returning the recorded error to the guest.
    async fn handle_mkdir<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
        confined_dirfd: bool,
    ) -> Result<i64, Errno> {
        let event = next_event!(guest, Mkdir)?;
        if event.result == Err(Errno::EEXIST) && event.existing_directory {
            self.materialize_recorded_mkdir(guest, syscall)
                .unwrap_or_else(|error| {
                    panic!("failed to materialize recorded mkdir directory: {error}")
                });
        } else if let Ok(expected) = event.result {
            if !confined_dirfd {
                let actual = guest.inject_with_retry(syscall).await;
                assert_eq!(actual, Ok(expected), "mkdir side effects diverged");
            } else if self.path_mutation_dirfds_are_confined(guest.pid(), syscall) {
                match guest.inject_with_retry(syscall).await {
                    Ok(actual) => assert_eq!(
                        actual, expected,
                        "replayed mkdirat returned a different result"
                    ),
                    Err(error @ (Errno::ENOENT | Errno::ENOTDIR | Errno::EROFS)) => {
                        tracing::debug!(?syscall, %error, "replay mkdirat kept virtual");
                    }
                    Err(error) => {
                        panic!(
                            "replayed mkdirat {syscall:?} failed after recording returned {expected}: {error}"
                        );
                    }
                }
            }
        }
        event.result
    }

    fn dirfd_is_confined(&self, pid: Pid, fd: libc::c_int) -> bool {
        fd == libc::AT_FDCWD || self.fd_is_in_replay_root(pid, fd)
    }

    fn path_mutation_dirfds_are_confined(&self, pid: Pid, syscall: Syscall) -> bool {
        match syscall {
            Syscall::Mkdirat(call) => self.dirfd_is_confined(pid, call.dirfd()),
            Syscall::Mknodat(call) => self.dirfd_is_confined(pid, call.dirfd()),
            Syscall::Fchownat(call) => self.dirfd_is_confined(pid, call.dirfd()),
            Syscall::Fchmodat(call) => self.dirfd_is_confined(pid, call.dirfd()),
            // TODO-HUMAN-REVIEW(#3598): the legacy forms resolve relative
            // paths against the working directory, like AT_FDCWD.
            Syscall::Rename(_)
            | Syscall::Link(_)
            | Syscall::Symlink(_)
            | Syscall::Chmod(_)
            | Syscall::Chown(_)
            | Syscall::Lchown(_)
            | Syscall::Mknod(_) => true,
            Syscall::Utimensat(call) => self.dirfd_is_confined(pid, call.dirfd()),
            Syscall::Symlinkat(call) => self.dirfd_is_confined(pid, call.newdirfd()),
            Syscall::Linkat(call) => {
                self.dirfd_is_confined(pid, call.olddirfd())
                    && self.dirfd_is_confined(pid, call.newdirfd())
            }
            Syscall::Renameat(call) => {
                self.dirfd_is_confined(pid, call.olddirfd())
                    && self.dirfd_is_confined(pid, call.newdirfd())
            }
            Syscall::Renameat2(call) => {
                self.dirfd_is_confined(pid, call.olddirfd())
                    && self.dirfd_is_confined(pid, call.newdirfd())
            }
            _ => false,
        }
    }

    async fn handle_openat2<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: reverie::syscalls::Openat2,
    ) -> Result<i64, Errno> {
        let recorded = next_event!(guest, Return);
        if let Ok(fd) = recorded {
            if self.dirfd_is_confined(guest.pid(), syscall.dirfd()) {
                match guest.inject_with_retry(syscall).await {
                    Ok(actual) => {
                        assert_eq!(actual, fd, "replayed openat2 returned a different fd")
                    }
                    Err(error) => {
                        tracing::debug!(%error, "replay openat2 path unavailable");
                        self.reserve_replay_fd(guest, fd as i32, false).await;
                    }
                }
            } else {
                self.reserve_replay_fd(guest, fd as i32, false).await;
            }
        }
        recorded
    }

    async fn handle_confined_path_mutation<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        let recorded = next_event!(guest, Return);
        if let Ok(expected) = recorded
            && self.path_mutation_dirfds_are_confined(guest.pid(), syscall)
        {
            match guest.inject_with_retry(syscall).await {
                Ok(actual) => assert_eq!(
                    actual, expected,
                    "replayed path mutation returned a different result"
                ),
                Err(error @ (Errno::ENOENT | Errno::ENOTDIR | Errno::EROFS)) => {
                    tracing::debug!(?syscall, %error, "replay path mutation kept virtual");
                }
                Err(error) => {
                    panic!(
                        "replayed path mutation {syscall:?} failed after recording returned {expected}: {error}"
                    );
                }
            }
        }
        recorded
    }

    // TODO-HUMAN-REVIEW(PR-3601)
    /// Replays a metadata change made through a descriptor: fchmod or fchown.
    /// A placeholder descriptor has no metadata to change, so the recorded
    /// result stands alone. A file in the replay root gets the change
    /// reapplied, because later path calls such as chmod run there and must
    /// find what the recording found.
    async fn handle_descriptor_metadata_change<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        let fd = match syscall {
            Syscall::Fchmod(call) => call.fd(),
            Syscall::Fchown(call) => call.fd(),
            _ => unreachable!("descriptor metadata handler received {syscall:?}"),
        };
        let recorded = next_event!(guest, Return);
        if let Ok(expected) = recorded
            && self.fd_is_in_replay_root(guest.pid(), fd)
        {
            match guest.inject_with_retry(syscall).await {
                Ok(actual) => assert_eq!(
                    actual, expected,
                    "replayed descriptor metadata change returned a different result"
                ),
                Err(error) => {
                    panic!(
                        "replayed descriptor metadata change {syscall:?} failed after recording returned {expected}: {error}"
                    );
                }
            }
        }
        recorded
    }

    // TODO-HUMAN-REVIEW(PR-3601)
    /// Replays an xattr change from its recorded result. Every xattr query
    /// also replays from the recording, so the guest never reads the replay
    /// root's attributes directly. The kernel and filesystems do, for every
    /// namespace but `user.`: `system.` holds POSIX and NFSv4 ACLs, which
    /// govern access and later creations; `security.` holds file capabilities
    /// and the labels security modules (SELinux, Smack, IMA, EVM) consult on
    /// access and exec; `trusted.` is read by filesystems such as overlayfs.
    /// Those govern calls replay runs live, so a change to one of them that
    /// the recording saw succeed on a file in the replay root must establish
    /// its end state there, even a read-only one (EROFS), or replay refuses to
    /// continue. A `user.` change is carried over where the replay root can
    /// take it and otherwise kept virtual: nothing that replay runs live can
    /// observe it.
    ///
    /// The replay root is built without the host's attributes, so its starting
    /// state may differ from the recording's. A set therefore runs without
    /// XATTR_CREATE or XATTR_REPLACE: whatever was there, the attribute ends up
    /// holding the recorded value. A removal that finds no attribute (ENODATA)
    /// ends in the recorded state too.
    ///
    /// A file the replay root lacks (a placeholder descriptor, ENOENT or
    /// ENOTDIR) keeps the change virtual, whatever the name, as other path
    /// mutations do. No live call can reach such a file:
    /// tools that copy a file's ACL to their output, such as strip, and
    /// installs that set a capability on a staged binary both change files
    /// outside the recorded tree.
    async fn handle_xattr_change<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        let pid = guest.pid();
        // The path calls take no dirfd; a relative path resolves against the
        // working directory, which replay keeps inside the root.
        let (in_replay_root, name, live_call, is_removal) = {
            let memory = guest.memory();
            let read = |name: Option<reverie::syscalls::CStrPtr<'_>>| {
                name.ok_or(Errno::EFAULT)
                    .and_then(|name| name.read(&memory))
            };
            match syscall {
                Syscall::Fsetxattr(call) => (
                    self.fd_is_in_replay_root(pid, call.fd()),
                    read(call.name()),
                    Syscall::Fsetxattr(call.with_flags(0)),
                    false,
                ),
                Syscall::Setxattr(call) => (
                    true,
                    read(call.name()),
                    Syscall::Setxattr(call.with_flags(0)),
                    false,
                ),
                Syscall::Lsetxattr(call) => (
                    true,
                    read(call.name()),
                    Syscall::Lsetxattr(call.with_flags(0)),
                    false,
                ),
                Syscall::Fremovexattr(call) => (
                    self.fd_is_in_replay_root(pid, call.fd()),
                    read(call.name()),
                    syscall,
                    true,
                ),
                Syscall::Removexattr(call) => (true, read(call.name()), syscall, true),
                Syscall::Lremovexattr(call) => (true, read(call.name()), syscall, true),
                _ => unreachable!("xattr change handler received {syscall:?}"),
            }
        };
        let recorded = next_event!(guest, Return)?;
        let name = name.unwrap_or_else(|error| {
            panic!("could not read the name of recorded xattr change {syscall:?}: {error}")
        });
        let governs_live_calls = !name.to_bytes().starts_with(b"user.");
        // A placeholder descriptor names a file the replay root lacks.
        let outcome = if in_replay_root {
            guest.inject_with_retry(live_call).await.map(drop)
        } else {
            Err(Errno::ENOENT)
        };
        match outcome {
            Ok(()) => {}
            Err(Errno::ENODATA) if is_removal => {}
            Err(error @ (Errno::ENOENT | Errno::ENOTDIR)) => {
                tracing::debug!(?syscall, %error, "replay xattr change kept virtual");
            }
            Err(error) if !governs_live_calls => {
                tracing::debug!(?syscall, %error, "replay xattr change kept virtual");
            }
            Err(error) => panic!(
                "replay root could not take recorded change to {name:?} {syscall:?}: {error}"
            ),
        }
        Ok(recorded)
    }

    // TODO-HUMAN-REVIEW(#3598)
    /// Replay `chdir(2)` or `fchdir(2)` from its recorded result and move the
    /// replay process's working directory with it. A successful recording
    /// carries the directory the call actually entered; that directory is
    /// created inside the replay root, as for a recorded `O_DIRECTORY` open,
    /// and entered by that resolved name. Neither the spelled path nor the
    /// descriptor is reused: the path may cross a host symlink or `..` that the
    /// replay root lacks, and the descriptor may be a replay placeholder. Every
    /// later `AT_FDCWD`-relative or legacy relative-path replay mutation trusts
    /// `/proc/<pid>/cwd`, so a stale or wrong directory would land them
    /// elsewhere; the resulting cwd is checked against the recording.
    async fn handle_working_directory_change<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        let entered = PathBuf::from(std::ffi::OsString::from_vec(next_event!(guest, Bytes)?));
        assert!(
            entered.is_absolute(),
            "recorded {syscall:?} entered a relative directory {entered:?}"
        );
        self.materialize_recorded_directory(
            guest,
            syscall,
            libc::AT_FDCWD,
            &entered,
            OFlag::empty(),
        )
        .unwrap_or_else(|error| {
            panic!("failed to materialize recorded working directory {entered:?}: {error}")
        });
        // The injection stack holds well under PATH_MAX, so enter the directory
        // in pieces: the root first, then runs of components, each of which
        // fits the buffer. A single component is at most NAME_MAX bytes.
        let mut path = [0_u8; 512];
        let mut pieces = vec![b"/".to_vec()];
        for component in entered.components().skip(1) {
            let component = component.as_os_str().as_bytes();
            let last = pieces.last_mut().expect("pieces starts non-empty");
            let separator = usize::from(!last.ends_with(b"/"));
            if last.len() + separator + component.len() < path.len() {
                if separator == 1 {
                    last.push(b'/');
                }
                last.extend_from_slice(component);
            } else {
                pieces.push(component.to_vec());
            }
        }
        for piece in pieces {
            assert!(
                piece.len() < path.len(),
                "path component of {entered:?} exceeds NAME_MAX"
            );
            path.fill(0);
            path[..piece.len()].copy_from_slice(&piece);
            let mut stack = guest.stack().await;
            let path_addr = stack.push(path);
            let path_ptr = PathPtr::from_ptr(unsafe {
                path_addr.cast::<u8>().as_ptr().cast::<libc::c_char>()
            })
            .expect("guest stack address is non-null");
            let _path_guard = stack.commit()?;
            if let Err(error) = guest
                .inject_with_retry(Chdir::new().with_path(Some(path_ptr)))
                .await
            {
                panic!("replayed {syscall:?} into recorded {entered:?} failed: {error}");
            }
        }
        let actual = crate::record_replay_path::process_cwd_path(guest.tid())
            .unwrap_or_else(|error| panic!("could not read replayed working directory: {error}"));
        assert_eq!(
            actual, entered,
            "replayed {syscall:?} entered a different directory than the recording"
        );
        Ok(0)
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#2373)
    /// Replay `flock(2)` by taking the lock again, not by consuming its recorded
    /// return value.
    ///
    /// `handle_simple` is only valid when nothing beyond the return value depends
    /// on a call. `flock` is the opposite case: its entire product is kernel state
    /// that a contender observes -- another process, or any other open file
    /// description in the same lock domain. Consuming the recorded `Return`
    /// without re-issuing the call makes a replayed run a program that merely
    /// *claims* to hold locks, so replaying a lockfile-based workload excludes
    /// nothing and a concurrent writer can corrupt what the recording protected.
    ///
    /// Only a descriptor that materialized in the replay root is a real kernel
    /// descriptor; the others are eventfd placeholders standing in for opens that
    /// replay serves from the log (see `handle_virtual_fd_create`). Locking a
    /// placeholder would lock the wrong object, while replaying only the return
    /// value would falsely claim the lock exists. Replay therefore fails closed
    /// for such a descriptor rather than silently dropping the side effect.
    ///
    /// Unlike `handle_replayed_side_effect`, this re-issues the call even when
    /// the recording FAILED, and that is the load-bearing part. A recorded
    /// `EWOULDBLOCK` is the observable that proves the conflicting lock is
    /// really held; skipping the attempt on a failed record would leave replay
    /// unable to notice that no lock exists at all, because the only calls it
    /// checked would be the ones that succeed whether or not the lock domain is
    /// real. Re-issuing both outcomes makes the guest's own contention pattern
    /// the check: if a replayed run had faked its locks, the contended probe
    /// would come back `Ok` where the recording said `EWOULDBLOCK`.
    ///
    /// Consequence, stated rather than hidden: within the materialized set,
    /// replay now depends on real lock state the same way recording does. If a
    /// conflicting lock exists during replay but not during recording (or the
    /// reverse), the re-issued call disagrees with the recording and this
    /// reports the divergence instead of silently continuing. That is the
    /// intended failure direction: replay is not faithful under a contender the
    /// recording did not have, and saying so beats pretending. The exposure is
    /// narrow in practice, because a pre-existing host file is exactly what
    /// replay does NOT materialize -- the materialized set is dominated by
    /// files the guest itself created inside the replay root.
    async fn handle_flock<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Flock,
    ) -> Result<i64, Errno> {
        assert!(
            self.fd_is_in_replay_root(guest.pid(), syscall.fd()),
            "cannot replay flock side effects for descriptor {} outside the replay root; \
             returning the recorded result would falsely claim a lock was acquired",
            syscall.fd()
        );
        let call = Syscall::from(syscall);
        let recorded = next_event!(guest, Return);
        let actual = guest.inject_with_retry(call).await;
        assert_eq!(
            actual, recorded,
            "flock side effects diverged: replay observed {actual:?} where the recording \
             observed {recorded:?} for {call:?}"
        );
        recorded
    }

    async fn handle_unlinkat<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Unlinkat,
    ) -> Result<i64, Errno> {
        if syscall.dirfd() == libc::AT_FDCWD
            || self.fd_is_in_replay_root(guest.pid(), syscall.dirfd())
        {
            self.handle_optional_path_removal(guest, syscall.into())
                .await
        } else {
            self.handle_simple(guest, syscall.into()).await
        }
    }

    async fn handle_optional_path_removal<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        let recorded = next_event!(guest, Return);
        if let Ok(expected) = recorded {
            match guest.inject_with_retry(syscall).await {
                Ok(actual) => assert_eq!(
                    actual, expected,
                    "replayed path removal returned a different result"
                ),
                Err(error @ (Errno::ENOENT | Errno::ENOTDIR)) => {
                    tracing::debug!(
                        ?syscall,
                        %error,
                        "replay path unavailable; keeping path removal virtual"
                    );
                }
                Err(error) => {
                    panic!(
                        "replayed path removal {syscall:?} failed after recording returned {expected}: {error}"
                    );
                }
            }
        }
        recorded
    }

    async fn handle_optional_fd_position<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        let Syscall::Lseek(call) = syscall else {
            unreachable!("descriptor-position handler received {syscall:?}");
        };
        if !self.fd_is_in_replay_root(guest.pid(), call.fd()) {
            return self.handle_simple(guest, syscall).await;
        }
        if matches!(call.whence(), Whence::SEEK_DATA | Whence::SEEK_HOLE) {
            let recorded = next_event!(guest, Return);
            if let Ok(expected) = recorded {
                let duplicate = crate::fd::duplicate_guest_fd(guest.pid(), call.fd())
                    .unwrap_or_else(|error| {
                        panic!("failed to duplicate replay file for extent seek: {error}")
                    });
                // SAFETY: duplicate owns the same open-file description and the
                // recorded extent seek returned this nonnegative offset.
                let actual =
                    unsafe { libc::lseek(duplicate.as_raw_fd(), expected, libc::SEEK_SET) };
                assert_eq!(
                    actual, expected,
                    "failed to restore replay position after extent seek"
                );
            }
            return recorded;
        }
        let recorded = next_event!(guest, Return);
        if let Ok(expected) = recorded {
            match guest.inject_with_retry(syscall).await {
                Ok(actual) => assert_eq!(
                    actual, expected,
                    "replayed descriptor position returned a different offset"
                ),
                Err(error @ (Errno::EBADF | Errno::ESPIPE)) => {
                    tracing::debug!(
                        ?syscall,
                        %error,
                        "replay descriptor is virtual; keeping position change virtual"
                    );
                }
                Err(error) => {
                    panic!(
                        "replayed descriptor position {syscall:?} failed after recording returned {expected}: {error}"
                    );
                }
            }
        }
        recorded
    }

    /// Replays the recorded result of `close` while preserving its physical FD
    /// namespace effect.
    async fn handle_close<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        let recorded = next_event!(guest, Return);

        // Linux releases a descriptor even when close reports EINTR, EIO,
        // ENOSPC, or EDQUOT. EBADF leaves the namespace unchanged, while
        // ERESTARTSYS means Reverie must restart the injection first.
        if !matches!(recorded, Err(Errno::EBADF | Errno::ERESTARTSYS))
            && let Err(error) = guest.inject(syscall).await
        {
            if error == Errno::EBADF {
                // Some replayed descriptor sources, notably SCM_RIGHTS,
                // currently have no physical peer.
                tracing::debug!(?syscall, "replayed close had no physical descriptor");
            } else {
                tracing::warn!(
                    ?error,
                    "physical close during replay differed from the recorded result"
                );
            }
        }

        recorded
    }

    // Check if we received the expected syscall or not.
    fn expect_syscall<G: Guest<Self>>(&self, guest: &mut G, syscall: Syscall) {
        let thread = guest.tid();
        let next_count = guest.thread_state().count + 1;
        let debug_event = guest
            .thread_state_mut()
            .next_debug_event()
            .unwrap_or_else(|source| {
                panic!(
                    "Replay syscall stream ended unexpectedly for recording {} on thread {} at event {} while the guest executed {:?}: {}",
                    self.data.display(),
                    thread,
                    next_count,
                    syscall,
                    source,
                )
            });

        let actual_event = DebugEvent::new(syscall, &guest.memory());
        let exec_syscall = matches!(syscall, Syscall::Execve(_) | Syscall::Execveat(_));

        // Compare only the argument registers the syscall actually uses. Reverie
        // keeps all six raw registers in every typed syscall and derives
        // `PartialEq` over them, so unused registers (which hold arbitrary
        // leftover guest values) would otherwise produce false desyncs for any
        // syscall with fewer than six arguments.
        if normalize_unused_args(debug_event.syscall()) == normalize_unused_args(syscall)
            && debug_event.exec_request_matches(&actual_event)
        {
            return;
        }

        if guest.is_root_thread() && !guest.thread_state().bootstrapped && exec_syscall {
            // The controller-visible replay bootstrap pathname is deliberately
            // substituted before injection and therefore differs here.
            return;
        }

        let error = DesyncError {
            thread,
            stream_id: guest.thread_state().stream_id.clone(),
            count: guest.thread_state().count,
            actual: actual_event,
            expected: debug_event,
        };
        let summary = error.summary(&self.data, 16, 4).to_string();
        let report = match error.generate_report(&self.data) {
            Ok(report) => format!("Full desynchronization report: {}", report.display()),
            Err(report_error) => {
                format!("Could not write the full desynchronization report: {report_error}")
            }
        };

        panic!(
            "Replay diverged from recording {} on thread {} at syscall event {}. Re-record the workload with the same Hermit build after diagnosing the mismatch.\n{}\n{}",
            self.data.display(),
            thread,
            error.count,
            summary,
            report,
        );
    }

    /// Called for syscalls to explicitly let through. This should only be called
    /// for syscalls that cannot be recorded and are necessary for the program to
    /// function correctly. Examples of syscalls that fall into this category are
    /// ones that help with memory management (e.g., `brk`, `mprotect`, or
    /// `munmap`) or process management (e.g., `fork`, `vfork`, `clone`).
    ///
    /// For these syscalls, we just care about detecting dsynchronization and
    /// simply inject them to let them through.
    async fn let_through<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        // NOTE: Must use `inject_with_retry` here. Otherwise, we may end up
        // introducing non-determinism into the replay and popping multiple
        // syscall events.
        guest.inject_with_retry(syscall).await
    }

    /// Handles a syscall whose only value we care about is the return value
    /// (i.e., simple syscalls).
    ///
    /// For recording, this means we only record the return value of the syscall.
    /// For replay, this means we substitute the return value in lieu of actually
    /// performing the injection.
    ///
    /// The syscall must have two properties satisfied for this to be called:
    ///  1. The syscall must only have "input" arguments. That is, all arguments
    ///     must either be values or const pointers.
    ///  2. The execution of the program must not depend on anything else other
    ///     than the return value of the syscall. For example, `mmap` would violate
    ///     this rule since it affects later memory access.
    ///
    /// There are many syscalls who satisfy these two requirements.
    async fn handle_simple<G: Guest<Self>>(
        &self,
        guest: &mut G,
        _syscall: Syscall,
    ) -> Result<i64, Errno> {
        next_event!(guest, Return)
    }

    async fn handle_dup2<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        let recorded = next_event!(guest, Return);
        if recorded.is_ok() {
            let actual = guest.inject_with_retry(syscall).await;
            // Some source descriptors are virtual: open-family syscalls replay
            // their recorded return value without creating a live kernel fd.
            // Preserve that behavior when there is nothing to duplicate in the
            // replay process.
            if actual != Err(Errno::EBADF) {
                assert_eq!(actual, recorded, "dup2 fd-table mutation diverged");
            }
        }
        recorded
    }

    // AUTONOMOUS-BOT-IMPLEMENTED
    // TODO-HUMAN-REVIEW(#663)
    async fn handle_replayed_side_effect<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
        operation: &str,
    ) -> Result<i64, Errno> {
        let recorded = next_event!(guest, Return);
        if recorded.is_ok() {
            let actual = guest.inject_with_retry(syscall).await;
            assert_eq!(actual, recorded, "{operation} side effects diverged");
        }
        recorded
    }

    async fn handle_pidfd_getfd<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        let recorded = next_event!(guest, Return);
        let actual = guest.inject_with_retry(syscall).await;
        if let Some(fd) = unexpected_pidfd_getfd_fd(&recorded, &actual) {
            let cleanup = guest.inject_with_retry(Close::new().with_fd(fd)).await;
            assert_eq!(
                cleanup,
                Ok(0),
                "pidfd_getfd replay diverged and cleanup of unexpected fd {fd} failed"
            );
        }
        assert_eq!(
            actual, recorded,
            "pidfd_getfd side effects diverged: replay observed {actual:?}, recording observed {recorded:?}"
        );
        recorded
    }

    // TODO-HUMAN-REVIEW(#557): Audit close_range fd-table replay semantics.
    async fn handle_close_range<G: Guest<Self>>(
        &self,
        guest: &mut G,
        syscall: Syscall,
    ) -> Result<i64, Errno> {
        let recorded = next_event!(guest, Return);
        if recorded.is_ok() {
            let actual = guest.inject_with_retry(syscall).await;
            assert_eq!(actual, recorded, "close_range side effects diverged");
        }
        recorded
    }
}

#[cfg(test)]
mod exec_snapshot_tests {
    use super::*;

    fn replayer_with_snapshot(
        contents: &[u8],
    ) -> (tempfile::TempDir, Replayer, crate::event::ExecImage) {
        let directory = tempfile::tempdir().unwrap();
        let digest = detcore::Digest::new(contents);
        let snapshots = directory.path().join(crate::consts::EXEC_FILES_NAME);
        std::fs::create_dir(&snapshots).unwrap();
        std::fs::write(snapshots.join(digest.to_string()), contents).unwrap();
        let replayer = Replayer {
            data: directory.path().to_path_buf(),
            ..Default::default()
        };
        let image = crate::event::ExecImage {
            digest,
            mode: 0o755,
        };
        (directory, replayer, image)
    }

    #[test]
    fn recorded_exec_snapshot_digest_is_verified() {
        let (directory, replayer, image) = replayer_with_snapshot(b"recorded image");
        std::fs::write(
            directory
                .path()
                .join(crate::consts::EXEC_FILES_NAME)
                .join(image.digest.to_string()),
            b"corrupt image",
        )
        .unwrap();

        let error = replayer.open_exec_snapshot(&image).unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::InvalidData);
        assert!(error.to_string().contains("digest mismatch"));
    }

    #[test]
    fn missing_recorded_exec_snapshot_fails_closed() {
        let (directory, replayer, image) = replayer_with_snapshot(b"recorded image");
        std::fs::remove_file(
            directory
                .path()
                .join(crate::consts::EXEC_FILES_NAME)
                .join(image.digest.to_string()),
        )
        .unwrap();

        assert_eq!(
            replayer.open_exec_snapshot(&image).unwrap_err().kind(),
            io::ErrorKind::NotFound
        );
    }

    #[test]
    fn materialized_object_pin_survives_unlink_until_scope_drop() {
        let directory = tempfile::tempdir().unwrap();
        let root = crate::record_replay_path::open_directory_path(directory.path()).unwrap();
        let scope = ReplayMaterializationScope::new(root.as_raw_fd()).unwrap();
        let root_identity = identity_for_fd(root.as_raw_fd()).unwrap();
        let path = directory.path().join("image");
        std::fs::write(&path, b"recorded").unwrap();
        let object: OwnedFd = File::open(&path).unwrap().into();
        let identity = identity_for_fd(object.as_raw_fd()).unwrap();
        register_materialized(root_identity, object).unwrap();
        std::fs::remove_file(&path).unwrap();

        let registry = materialized_files()
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let pin = registry
            .get(&root_identity)
            .and_then(|files| files.get(&identity))
            .expect("registered object remains pinned after unlink");
        let pinned = std::fs::metadata(format!("/proc/self/fd/{}", pin.as_raw_fd())).unwrap();
        assert_eq!(
            (pinned.dev(), pinned.ino()),
            (identity.device, identity.inode)
        );
        drop(registry);

        std::fs::write(&path, b"replacement").unwrap();
        let replacement = std::fs::metadata(&path).unwrap();
        assert_ne!(
            (replacement.dev(), replacement.ino()),
            (identity.device, identity.inode)
        );
        assert_eq!(registered_materialized_count(root.as_raw_fd()), 1);

        drop(scope);
        assert_eq!(registered_materialized_count(root.as_raw_fd()), 0);
    }
}

#[cfg(test)]
mod pidfd_getfd_replay_tests {
    use super::*;

    #[test]
    fn exact_success_and_errno_need_no_cleanup() {
        assert_eq!(unexpected_pidfd_getfd_fd(&Ok(7), &Ok(7)), None);
        assert_eq!(
            unexpected_pidfd_getfd_fd(&Err(Errno::EBADF), &Err(Errno::EBADF)),
            None
        );
    }

    #[test]
    fn unexpected_success_is_owned_for_cleanup_before_refusal() {
        assert_eq!(
            unexpected_pidfd_getfd_fd(&Err(Errno::EBADF), &Ok(9)),
            Some(9)
        );
        assert_eq!(unexpected_pidfd_getfd_fd(&Ok(7), &Ok(9)), Some(9));
        assert_eq!(unexpected_pidfd_getfd_fd(&Ok(7), &Err(Errno::EPERM)), None);
    }
}