hermit-detcore 0.4.0

Detcore: the deterministic scheduler and syscall determinization core of the Hermit execution engine.
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
/*
 * 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.
 */

use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::task::Poll;

use reverie::Errno;
use reverie::ExitStatus;
use reverie::Tool;

use super::*;
use crate::ThreadState;
use crate::types::ChildWaitExitClass;
use crate::types::ChildWaitSelector;
use crate::types::ChildWaitSpec;
use crate::types::ExactChildWaitState;

const PARENT: DetTid = DetTid::from_raw(1);
const LEADER: DetTid = DetTid::from_raw(17);
const WORKER: DetTid = DetTid::from_raw(18);

#[derive(Clone, Copy, PartialEq)]
enum Gate {
    None,
    BeforeCommit,
    AfterCommit,
}

// This transport binds the backend's sender independently of ThreadState.
// Both gated paths execute the production RPC; no successful reply is invented.
struct ExecRpc<'a> {
    state: &'a GlobalState,
    sender: DetTid,
    gate: Gate,
    reached: AtomicBool,
    release: Ivar<()>,
    requests: Mutex<Vec<GlobalRequest>>,
}

impl<'a> ExecRpc<'a> {
    fn new(state: &'a GlobalState, sender: DetTid, gate: Gate) -> Self {
        Self {
            state,
            sender,
            gate,
            reached: AtomicBool::new(false),
            release: Ivar::new(),
            requests: Mutex::new(Vec::new()),
        }
    }

    async fn suspend(&self) {
        self.reached.store(true, Ordering::SeqCst);
        self.release.clone().await;
    }
}

#[reverie::tool]
impl GlobalRPC<GlobalState> for ExecRpc<'_> {
    async fn send_rpc(
        &self,
        request: <GlobalState as GlobalTool>::Request,
    ) -> <GlobalState as GlobalTool>::Response {
        let reconnect = matches!(&request.2, GlobalRequest::ReconnectExec { .. });
        self.requests.lock().unwrap().push(request.2.clone());
        if reconnect && self.gate == Gate::BeforeCommit {
            self.suspend().await;
        }
        let result = self
            .state
            .receive_rpc(Tid::from_raw(self.sender.as_raw()), request)
            .await;
        if reconnect && self.gate == Gate::AfterCommit {
            assert_eq!(result, (None, GlobalResponse::ReconnectExec(true)));
            self.suspend().await;
        }
        result
    }

    fn config(&self) -> &Config {
        &self.state.cfg
    }
}

struct ExecGuest<'a> {
    rpc: ExecRpc<'a>,
    thread: ThreadState<()>,
}

#[reverie::tool]
impl GlobalRPC<GlobalState> for ExecGuest<'_> {
    async fn send_rpc(
        &self,
        request: <GlobalState as GlobalTool>::Request,
    ) -> <GlobalState as GlobalTool>::Response {
        self.rpc.send_rpc(request).await
    }

    fn config(&self) -> &Config {
        self.rpc.config()
    }
}

#[reverie::tool]
impl Guest<Detcore> for ExecGuest<'_> {
    type Memory = reverie::syscalls::LocalMemory;
    type Stack = ExternalRegistrationStack;

    fn tid(&self) -> Tid {
        Tid::from_raw(self.rpc.sender.as_raw())
    }
    fn pid(&self) -> Tid {
        Tid::from_raw(LEADER.as_raw())
    }
    fn ppid(&self) -> Option<Tid> {
        Some(Tid::from_raw(PARENT.as_raw()))
    }
    fn memory(&self) -> Self::Memory {
        panic!("exec identity handoff must not access guest memory")
    }
    fn thread_state(&self) -> &ThreadState<()> {
        &self.thread
    }
    fn thread_state_mut(&mut self) -> &mut ThreadState<()> {
        &mut self.thread
    }
    async fn regs(&mut self) -> libc::user_regs_struct {
        panic!("exec identity handoff must not read registers")
    }
    async fn stack(&mut self) -> Self::Stack {
        panic!("exec identity handoff must not use a guest stack")
    }
    async fn daemonize(&mut self) {
        panic!("exec identity handoff must not daemonize")
    }
    async fn inject<S: reverie::syscalls::SyscallInfo>(
        &mut self,
        _: S,
    ) -> Result<i64, reverie::Errno> {
        panic!("exec identity handoff must not inject syscalls")
    }
    async fn tail_inject<S: reverie::syscalls::SyscallInfo>(&mut self, _: S) -> reverie::Never {
        panic!("exec identity handoff must not retire a live guest")
    }
    fn set_timer(&mut self, _: reverie::TimerSchedule) -> Result<(), reverie::Error> {
        panic!("identity transfer must preserve the existing PMU timer")
    }
    fn set_timer_precise(&mut self, _: reverie::TimerSchedule) -> Result<(), reverie::Error> {
        panic!("identity transfer must preserve the existing PMU timer")
    }
    fn read_clock(&mut self) -> Result<u64, reverie::Error> {
        panic!("identity transfer must preserve the carried clock")
    }
}

struct Fixture {
    state: GlobalState,
    tool: Detcore,
    parent: ThreadState<()>,
    worker: ThreadState<()>,
    before_tail: LogicalTime,
}

fn child_wait() -> ChildWaitSpec {
    ChildWaitSpec {
        selector: ChildWaitSelector::Exact(LEADER),
        owner: None,
        exit_class: ChildWaitExitClass::Sigchld,
    }
}

async fn consume(state: &GlobalState, tool: &Detcore, sender: DetTid, thread: ThreadState<()>) {
    consume_with_status(state, tool, sender, thread, ExitStatus::Exited(73)).await;
}

async fn consume_with_status(
    state: &GlobalState,
    tool: &Detcore,
    sender: DetTid,
    thread: ThreadState<()>,
    status: ExitStatus,
) {
    let rpc = ExecRpc::new(state, sender, Gate::None);
    let mut exit =
        Box::pin(tool.on_exit_thread(Tid::from_raw(sender.as_raw()), &rpc, thread, status));
    assert!(
        matches!(futures::poll!(&mut exit), Poll::Ready(Ok(()))),
        "consuming cleanup must finish without a scheduler grant"
    );
    assert_eq!(rpc.requests.lock().unwrap().len(), 1);
}

impl Fixture {
    async fn prepared() -> Self {
        Self::with_leader_retired(true).await
    }

    async fn with_leader_retired(retire_leader: bool) -> Self {
        Self::configured(retire_leader, false).await
    }

    async fn configured(retire_leader: bool, backend_serializes_fork_children: bool) -> Self {
        let config = Config {
            sequentialize_threads: true,
            cancel_killed_thread_rpcs: false,
            backend_serializes_fork_children,
            max_timeslice: std::num::NonZeroU64::new(200_000_000),
            ..Config::default()
        };
        assert!(config.use_rcb_time());
        let state = GlobalState::initialize(&config, false);
        let tool = Detcore::new(Tid::from_raw(LEADER.as_raw()), &config);
        let mut parent = tool.init_thread_state(Tid::from_raw(PARENT.as_raw()), None);
        parent.detpid = Some(PARENT);
        parent.thread_start_entered = true;
        parent.thread_logical_time.add_syscall_with_cost(1_000);
        parent.thread_logical_time.add_rcbs(11);
        parent.account_process_cpu_time();
        parent.clone_flags = Some(CloneFlags::empty());
        let mut leader = tool.init_thread_state(
            Tid::from_raw(LEADER.as_raw()),
            Some((Tid::from_raw(PARENT.as_raw()), &parent)),
        );
        leader.detpid = Some(LEADER);
        leader.thread_start_entered = true;
        leader.thread_logical_time.add_syscall_with_cost(101);
        leader.thread_logical_time.add_rcbs(13);
        leader.account_process_cpu_time();
        leader.stats.syscall_count = 3;
        leader.stats.timeslice_stats.record(23);
        leader.clone_flags = Some(CloneFlags::CLONE_THREAD | CloneFlags::CLONE_VM);
        let mut worker = tool.init_thread_state(
            Tid::from_raw(WORKER.as_raw()),
            Some((Tid::from_raw(LEADER.as_raw()), &leader)),
        );
        worker.detpid = Some(LEADER);
        worker.thread_start_entered = true;
        worker.thread_logical_time.add_syscall_with_cost(211);
        worker.thread_logical_time.add_rcbs(17);
        worker.account_process_cpu_time();
        worker.stats.syscall_count = 7;
        worker.stats.timeslice_stats.record(41);
        let old_mm = worker.mm_id;
        {
            let mut sched = state.sched.lock().unwrap();
            sched.thread_tree.add_child(PARENT, PARENT, true);
            sched.thread_tree.add_child(PARENT, LEADER, true);
            sched.thread_tree.add_child(LEADER, WORKER, false);
        }
        for thread in [&leader, &worker] {
            install_test_registration(&state, thread.dettid, Ivar::new());
            state
                .sched
                .lock()
                .unwrap()
                .install_test_exec_incarnation(thread.dettid, old_mm);
        }
        for thread in [&parent, &leader, &worker] {
            state.global_time.lock().unwrap().update_global_time(
                thread.dettid,
                thread.thread_logical_time.as_nanos(),
                thread.thread_logical_time.inherited_nanos(),
            );
        }
        let prepared = state
            .receive_rpc(
                Tid::from_raw(WORKER.as_raw()),
                (
                    worker.thread_logical_time.clone(),
                    old_mm,
                    GlobalRequest::PrepareExec(LEADER, old_mm, Default::default()),
                ),
            )
            .await;
        assert_eq!(prepared, (None, GlobalResponse::PrepareExec(())));
        let before_tail = state.global_time.lock().unwrap().as_nanos();
        let epoch = DetTime::new(&config).as_nanos();
        assert_eq!(before_tail, epoch + LogicalTime::from_nanos(1_722));
        worker.thread_logical_time.add_syscall_with_cost(307);
        worker.thread_logical_time.add_rcbs(19);
        worker.mm_id = old_mm.for_exec(LEADER);
        // Ptrace consumes the displaced leader before delivering successful
        // exec to the surviving worker, whose backend TID is now LEADER.
        if retire_leader {
            consume(&state, &tool, LEADER, leader).await;
        }
        let fixture = Self {
            state,
            tool,
            parent,
            worker,
            before_tail,
        };
        fixture.assert_displaced_leader_receipt(retire_leader);
        fixture.assert_running();
        fixture
    }

    fn assert_running(&self) {
        let mut sched = self.state.sched.lock().unwrap();
        assert_eq!(
            sched.exact_child_wait_state(PARENT, LEADER),
            ExactChildWaitState::Running
        );
        assert_eq!(sched.ready_child_wait(PARENT, child_wait()), None);
        assert_eq!(sched.turn, 0, "identity transfer cannot grant a guest turn");
    }

    fn assert_displaced_leader_receipt(&self, observed: bool) {
        let sched = self.state.sched.lock().unwrap();
        let old_mm = MmId::initial(LEADER);
        // Physical consumption is authenticated separately from canonical
        // scheduler retirement. Its original registration remains in place
        // until the complete exec teardown can retire siblings in fixed order.
        assert!(sched.next_turns.contains_key(&LEADER));
        assert!(sched.next_turns[&LEADER].req.try_read().is_none());
        assert!(sched.rpc_incarnation_matches(LEADER, old_mm));
        assert_eq!(
            sched.exec_sibling_retirement_observed(LEADER, LEADER, old_mm),
            observed
        );
        assert!(!sched.exec_sibling_retirement_observed(LEADER, PARENT, old_mm));
        assert!(!sched.exec_sibling_retirement_observed(LEADER, LEADER, old_mm.for_exec(LEADER)));
        assert_eq!(
            sched.per_thread_syscalls.get(&LEADER),
            if observed { Some(&3) } else { None }
        );
    }

    fn guest(&self, gate: Gate) -> ExecGuest<'_> {
        ExecGuest {
            rpc: ExecRpc::new(&self.state, LEADER, gate),
            thread: self.worker.clone(),
        }
    }

    fn assert_final_clock(&self, owner: DetTid) {
        let global = self.state.global_time.lock().unwrap();
        assert_eq!(
            global.as_nanos(),
            self.before_tail + LogicalTime::from_nanos(497)
        );
        assert_eq!(
            global.threads_time(owner),
            self.worker.thread_logical_time.as_nanos()
        );
        let snapshot = serde_json::to_value(&*global).unwrap();
        assert_eq!(
            snapshot["inherited_time"][owner.as_raw().to_string()],
            serde_json::to_value(self.worker.thread_logical_time.inherited_nanos()).unwrap()
        );
    }

    fn assert_final_cpu_and_reap(&mut self) {
        let parent = serde_json::to_value(&*self.parent.process_cpu_time.lock().unwrap()).unwrap();
        let child = &parent["exited_children"][LEADER.as_raw().to_string()];
        assert_eq!(child["user"], serde_json::json!(490));
        assert_eq!(child["system"], serde_json::json!(619));
        for _ in 0..2 {
            self.parent.reap_child_process_cpu_time(LEADER);
            let cpu = self.parent.process_cpu_time();
            assert_eq!(cpu.children_user, LogicalTime::from_nanos(490));
            assert_eq!(cpu.children_system, LogicalTime::from_nanos(619));
        }
    }

    fn assert_final_stats(&self, committed: bool) {
        let sched = self.state.sched.lock().unwrap();
        let owner = if committed { LEADER } else { WORKER };
        let owner_count = if committed { 10 } else { 7 };
        assert_eq!(sched.per_thread_syscalls.get(&owner), Some(&owner_count));
        assert_eq!(sched.per_thread_syscalls.values().sum::<u64>(), 10);
        let mut expected = TimesliceStats::default();
        expected.record(41);
        if committed {
            expected.record(23);
        }
        assert_eq!(sched.per_thread_timeslice.get(&owner), Some(&expected));
        assert_eq!(
            sched
                .per_thread_timeslice
                .values()
                .map(|s| s.count)
                .sum::<u64>(),
            2
        );
        assert_eq!(
            sched
                .per_thread_timeslice
                .values()
                .map(|s| s.sum_ns)
                .sum::<u64>(),
            64
        );
    }

    async fn duplicate_bound_exit(&self) {
        let mut duplicate = deregistration(&self.worker);
        duplicate.dettid = LEADER;
        duplicate.syscall_count = 999;
        duplicate.timeslice_stats.record(999);
        let response = self
            .state
            .receive_rpc(
                Tid::from_raw(LEADER.as_raw()),
                (
                    self.worker.thread_logical_time.clone(),
                    duplicate.mm,
                    GlobalRequest::DeregisterThread(duplicate),
                ),
            )
            .await;
        assert_eq!(response, (None, GlobalResponse::DeregisterThread(())));
        self.assert_final_stats(true);
        self.assert_final_clock(LEADER);
    }
}

fn deregistration(thread: &ThreadState<()>) -> ThreadDeregistration {
    ThreadDeregistration {
        dettid: thread.dettid,
        detpid: thread.detpid.unwrap(),
        mm: thread.mm_id,
        thread_start_entered: thread.thread_start_entered,
        timeslice_stats: thread.stats.timeslice_stats,
        syscall_count: thread.stats.syscall_count,
        chaos_epochs: Vec::new(),
    }
}

#[tokio::test]
async fn transferred_exec_preemption_artifacts_refuse_before_replacement_turn() {
    for mode in 0..3 {
        let mut fixture = Fixture::prepared().await;
        // Exercise each public configuration spelling independently. The
        // artifact reader/writer's real file lifecycle is covered by the CLI
        // record-then-replay control; here the actual reconnect RPC must keep
        // its identity and clock invariants without granting replacement work.
        match mode {
            0 => fixture.state.cfg.record_preemptions = true,
            1 => fixture.state.cfg.record_preemptions_to = Some("record.json".into()),
            2 => fixture.state.cfg.replay_preemptions_from = Some("record.json".into()),
            _ => unreachable!(),
        }
        let mut guest = fixture.guest(Gate::None);
        let clock = guest.thread.thread_logical_time.clone();
        let deadline = clock.as_nanos() + LogicalTime::from_nanos(123_456);
        guest.thread.last_rcb_timer = Some(98_765);
        guest.thread.end_of_timeslice = Some(deadline);
        guest.thread.max_timeslice_end = Some(deadline);
        let mut reconnect = Box::pin(super::super::reconnect_exec(&mut guest));
        assert_eq!(
            futures::poll!(&mut reconnect),
            Poll::Ready(Err(Errno::EOPNOTSUPP))
        );
        drop(reconnect);
        assert_eq!(guest.thread.dettid, LEADER);
        assert_eq!(
            guest.thread.thread_logical_time.as_nanos(),
            clock.as_nanos()
        );
        assert_eq!(guest.thread.last_rcb_timer, Some(98_765));
        assert_eq!(guest.thread.end_of_timeslice, Some(deadline));
        assert_eq!(guest.thread.max_timeslice_end, Some(deadline));
        assert_eq!(
            *guest.rpc.requests.lock().unwrap(),
            [GlobalRequest::ReconnectExec {
                former: WORKER,
                process: LEADER,
            }],
            "refusal must precede ResumeExec or any replacement-image RPC"
        );
        fixture.assert_running();
        fixture.assert_final_clock(LEADER);
        let sched = fixture.state.sched.lock().unwrap();
        assert!(!sched.next_turns.contains_key(&WORKER));
        assert!(sched.next_turns[&LEADER].req.try_read().is_none());
        assert!(sched.next_turns[&LEADER].resp.try_read().is_none());
        assert!(fixture.state.pending_exec_states.lock().unwrap().is_empty());
        assert!(
            fixture
                .state
                .completed_exec_transfers
                .lock()
                .unwrap()
                .contains_key(&LEADER)
        );
    }
}

#[tokio::test]
async fn preemption_artifact_refusal_is_specific_to_transferred_exec() {
    let mut fixture = Fixture::prepared().await;
    fixture.state.cfg.record_preemptions = true;
    fixture.state.cfg.record_preemptions_to = Some("record.json".into());
    fixture.state.cfg.replay_preemptions_from = Some("record.json".into());
    let mut same_tid = ExecGuest {
        rpc: ExecRpc::new(&fixture.state, WORKER, Gate::None),
        thread: fixture.worker.clone(),
    };
    assert_eq!(super::super::reconnect_exec(&mut same_tid).await, Ok(()));
    assert!(same_tid.rpc.requests.lock().unwrap().is_empty());
    fixture.assert_displaced_leader_receipt(true);

    // Ordinary chaos execution without artifact flags still reaches its real
    // continuation request. Do not globally disable preemption or exec.
    let mut ordinary = Fixture::prepared().await;
    ordinary.state.cfg.chaos = true;
    let mut guest = ordinary.guest(Gate::None);
    {
        let mut reconnect = Box::pin(super::super::reconnect_exec(&mut guest));
        assert!(futures::poll!(&mut reconnect).is_pending());
    }
    assert_eq!(guest.thread.dettid, LEADER);
    assert!(matches!(
        guest.rpc.requests.lock().unwrap().as_slice(),
        [
            GlobalRequest::ReconnectExec { .. },
            GlobalRequest::ResumeExec(LEADER)
        ]
    ));
}

async fn cancelled_transfer(gate: Gate, backend_failed: bool) {
    let mut fixture = Fixture::prepared().await;
    let mut guest = fixture.guest(gate);
    {
        let mut reconnect = Box::pin(super::super::reconnect_exec(&mut guest));
        assert!(futures::poll!(&mut reconnect).is_pending());
        // Drop the real callback at the transport boundary, as backend cleanup
        // does. The local carried identity has not received an acknowledgment.
    }
    assert!(guest.rpc.reached.load(Ordering::SeqCst));
    assert_eq!(guest.thread.dettid, WORKER);
    assert_eq!(guest.rpc.requests.lock().unwrap().len(), 1);
    fixture.assert_running();
    let committed = gate == Gate::AfterCommit;
    assert_eq!(
        fixture
            .state
            .completed_exec_transfers
            .lock()
            .unwrap()
            .contains_key(&LEADER),
        committed
    );
    assert_eq!(
        fixture
            .state
            .pending_exec_states
            .lock()
            .unwrap()
            .contains_key(&LEADER),
        !committed
    );
    if committed {
        fixture.assert_final_clock(LEADER);
        assert!(
            !fixture
                .state
                .global_time
                .lock()
                .unwrap()
                .contains_thread(WORKER)
        );
        assert!(
            fixture.state.sched.lock().unwrap().next_turns[&LEADER]
                .req
                .try_read()
                .is_none()
        );
    } else {
        assert_eq!(
            fixture.state.global_time.lock().unwrap().as_nanos(),
            fixture.before_tail
        );
        fixture.assert_displaced_leader_receipt(true);
    }
    let duplicate = deregistration(&guest.thread);
    if backend_failed {
        fixture
            .state
            .report_backend_failure(reverie::BackendFailure {
                pid: Tid::from_raw(LEADER.as_raw()),
                tid: Tid::from_raw(LEADER.as_raw()),
                phase: "exec transport cancellation control",
            });
    }
    let status = if backend_failed {
        // A failure can race a task's actual normal exit. The published global
        // failure, rather than this numeric status, authorizes cleanup.
        ExitStatus::Exited(73)
    } else {
        ExitStatus::Signaled(Signal::SIGKILL, false)
    };
    consume_with_status(&fixture.state, &fixture.tool, LEADER, guest.thread, status).await;
    let owner = if committed { LEADER } else { WORKER };
    fixture.assert_final_clock(owner);
    assert!(fixture.state.pending_exec_states.lock().unwrap().is_empty());
    assert!(
        fixture
            .state
            .completed_exec_transfers
            .lock()
            .unwrap()
            .is_empty()
    );
    {
        let mut sched = fixture.state.sched.lock().unwrap();
        assert!(!sched.next_turns.contains_key(&LEADER));
        assert!(!sched.next_turns.contains_key(&WORKER));
        assert_eq!(sched.backend_failed(), backend_failed);
        assert_eq!(sched.turn, 0);
        assert_eq!(
            sched.exact_child_wait_state(PARENT, LEADER),
            ExactChildWaitState::LogicallyExited
        );
        assert_eq!(sched.ready_child_wait(PARENT, child_wait()), Some(LEADER));
    }
    fixture.assert_final_stats(committed);
    let before = serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap();
    let mut forged_time = fixture.worker.thread_logical_time.clone();
    forged_time.add_syscall_with_cost(999_999);
    let mut duplicate = duplicate;
    duplicate.syscall_count = 999;
    let replayed = fixture
        .state
        .receive_rpc(
            Tid::from_raw(LEADER.as_raw()),
            (
                forged_time,
                duplicate.mm,
                GlobalRequest::RetireExec {
                    thread: duplicate,
                    signaled: true,
                },
            ),
        )
        .await;
    assert_eq!(replayed, (None, GlobalResponse::RetireExec(false)));
    assert_eq!(
        serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
        before
    );
    fixture.assert_final_stats(committed);
    if committed {
        fixture.duplicate_bound_exit().await;
    }
    fixture.assert_final_cpu_and_reap();
}

#[tokio::test]
async fn cancelled_before_exec_commit_consumes_original_owner_without_admission() {
    cancelled_transfer(Gate::BeforeCommit, false).await;
}

#[tokio::test]
async fn cancelled_after_exec_commit_before_reply_consumes_replacement_once() {
    cancelled_transfer(Gate::AfterCommit, false).await;
}

#[tokio::test]
async fn backend_failure_before_exec_commit_still_consumes_original_owner() {
    cancelled_transfer(Gate::BeforeCommit, true).await;
}

#[tokio::test]
async fn backend_failure_after_exec_commit_still_consumes_replacement() {
    cancelled_transfer(Gate::AfterCommit, true).await;
}

#[tokio::test]
async fn unbound_exec_ordinary_rpc_fails_before_sending_or_retiring() {
    let fixture = Fixture::prepared().await;
    let mut guest = fixture.guest(Gate::None);
    let before = serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap();
    // This is the first ordinary helper reached if handle_post_exec omits its
    // reconnect. Catching just any panic would also accept the mock's forbidden
    // tail-injection panic, so require the protocol diagnostic AND no RPC.
    let result = futures::FutureExt::catch_unwind(std::panic::AssertUnwindSafe(
        super::super::send_and_update_time(&mut guest, GlobalRequest::GlobalTimeLowerBound),
    ))
    .await;
    let panic = result.expect_err("an unbound survivor must not request ordinary work");
    let diagnostic = panic
        .downcast_ref::<String>()
        .map(String::as_str)
        .or_else(|| panic.downcast_ref::<&str>().copied())
        .expect("identity assertion must provide a diagnostic");
    assert!(diagnostic.contains("replacement image must reconnect before ordinary RPCs"));
    assert!(guest.rpc.requests.lock().unwrap().is_empty());
    assert_eq!(guest.thread.dettid, WORKER);
    assert_eq!(
        serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
        before
    );
    assert!(
        fixture
            .state
            .pending_exec_states
            .lock()
            .unwrap()
            .contains_key(&LEADER)
    );
    assert!(
        fixture
            .state
            .completed_exec_transfers
            .lock()
            .unwrap()
            .is_empty()
    );
    fixture.assert_running();
}

#[tokio::test]
async fn unbound_exec_normal_exit_cannot_consume_pending_or_completed_transfer() {
    for committed in [false, true] {
        for status in [0, 73] {
            let fixture = Fixture::prepared().await;
            if committed {
                commit_without_acknowledgment(&fixture).await;
            }
            let before = serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap();
            let (syscalls, timeslices) = {
                let sched = fixture.state.sched.lock().unwrap();
                (
                    sched.per_thread_syscalls.clone(),
                    sched.per_thread_timeslice.clone(),
                )
            };
            let rpc = ExecRpc::new(&fixture.state, LEADER, Gate::None);
            let mut exit = Box::pin(fixture.tool.on_exit_thread(
                Tid::from_raw(LEADER.as_raw()),
                &rpc,
                fixture.worker.clone(),
                ExitStatus::Exited(status),
            ));
            let error = match futures::poll!(&mut exit) {
                Poll::Ready(Err(error)) => error,
                result => panic!("normal exit {status} must reject unbound cleanup: {result:?}"),
            };
            assert!(error.to_string().contains("EINVAL"));
            let requests = rpc.requests.lock().unwrap();
            assert!(matches!(
                requests.as_slice(),
                [GlobalRequest::RetireExec {
                    signaled: false,
                    ..
                }]
            ));
            assert_eq!(
                serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
                before
            );
            {
                let sched = fixture.state.sched.lock().unwrap();
                assert!(!sched.backend_failed());
                assert_eq!(sched.per_thread_syscalls, syscalls);
                assert_eq!(sched.per_thread_timeslice, timeslices);
                assert!(sched.next_turns.contains_key(&LEADER));
                assert_eq!(sched.next_turns.contains_key(&WORKER), !committed);
                assert_eq!(
                    sched.exec_sibling_retirement_observed(LEADER, LEADER, MmId::initial(LEADER)),
                    !committed
                );
            }
            assert_eq!(
                fixture
                    .state
                    .pending_exec_states
                    .lock()
                    .unwrap()
                    .contains_key(&LEADER),
                !committed
            );
            assert_eq!(
                fixture
                    .state
                    .completed_exec_transfers
                    .lock()
                    .unwrap()
                    .contains_key(&LEADER),
                committed
            );
            fixture.assert_running();
        }
    }
}

#[tokio::test]
async fn transferred_exec_waits_for_real_grant_and_preserves_clock_and_deadlines() {
    let mut fixture = Fixture::prepared().await;
    let mut guest = fixture.guest(Gate::None);
    let deadline = guest.thread.thread_logical_time.as_nanos() + LogicalTime::from_nanos(12_345);
    guest.thread.end_of_timeslice = Some(deadline);
    guest.thread.max_timeslice_end = Some(deadline);
    guest.thread.last_rcb_timer = Some(1_234);
    let clock = serde_json::to_value(&guest.thread.thread_logical_time).unwrap();
    {
        let mut reconnect = Box::pin(super::super::reconnect_exec(&mut guest));
        assert!(futures::poll!(&mut reconnect).is_pending());
        assert!(futures::poll!(&mut reconnect).is_pending());
        fixture.assert_running();
        fixture.assert_final_clock(LEADER);
        let turn = crate::scheduler::do_a_turn_blocking(
            fixture.state.sched.clone(),
            fixture.state.global_time.clone(),
            &Err(crate::scheduler::SkipTurn),
        )
        .await
        .expect("replacement must receive its continuation grant");
        assert_eq!(turn.tid, LEADER);
        assert_eq!(reconnect.await, Ok(()));
    }
    assert_eq!(guest.thread.dettid, LEADER);
    assert_eq!(
        serde_json::to_value(&guest.thread.thread_logical_time).unwrap(),
        clock
    );
    assert_eq!(guest.thread.end_of_timeslice, Some(deadline));
    assert_eq!(guest.thread.max_timeslice_end, Some(deadline));
    assert_eq!(guest.thread.last_rcb_timer, Some(1_234));
    assert_eq!(
        *guest.rpc.requests.lock().unwrap(),
        vec![
            GlobalRequest::ReconnectExec {
                former: WORKER,
                process: LEADER
            },
            GlobalRequest::ResumeExec(LEADER),
        ]
    );
    assert_eq!(fixture.state.sched.lock().unwrap().turn, 1);
    assert!(
        fixture
            .state
            .completed_exec_transfers
            .lock()
            .unwrap()
            .is_empty()
    );
    // The same ordinary helper is legal as soon as acknowledgment has bound
    // the carried state to the backend's current identity.
    assert_eq!(
        super::super::send_and_update_time(&mut guest, GlobalRequest::GlobalTimeLowerBound).await,
        (
            None,
            GlobalResponse::GlobalTimeLowerBound(
                fixture.before_tail + LogicalTime::from_nanos(497)
            )
        )
    );
    consume(&fixture.state, &fixture.tool, LEADER, guest.thread).await;
    fixture.assert_final_clock(LEADER);
    fixture.assert_final_stats(true);
    fixture.duplicate_bound_exit().await;
    fixture.assert_final_cpu_and_reap();
}

#[tokio::test]
async fn malformed_exec_transfer_never_accounts_clock_or_consumes_preparation() {
    let fixture = Fixture::prepared().await;
    let before = serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap();
    let old_mm = MmId::initial(LEADER);
    let new_mm = fixture.worker.mm_id;
    for (sender, former, process, mm) in [
        (WORKER, WORKER, LEADER, new_mm),
        (LEADER, LEADER, LEADER, new_mm),
        (LEADER, PARENT, LEADER, new_mm),
        (LEADER, WORKER, PARENT, new_mm),
        (LEADER, WORKER, LEADER, old_mm),
        (LEADER, WORKER, LEADER, new_mm.for_exec(LEADER)),
    ] {
        let mut time = fixture.worker.thread_logical_time.clone();
        time.add_syscall_with_cost(999_999);
        let result = fixture
            .state
            .receive_rpc(
                Tid::from_raw(sender.as_raw()),
                (time, mm, GlobalRequest::ReconnectExec { former, process }),
            )
            .await;
        assert_eq!(result, (None, GlobalResponse::ReconnectExec(false)));
        assert_eq!(
            serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
            before
        );
        assert!(
            fixture
                .state
                .pending_exec_states
                .lock()
                .unwrap()
                .contains_key(&LEADER)
        );
        assert!(
            fixture
                .state
                .completed_exec_transfers
                .lock()
                .unwrap()
                .is_empty()
        );
        fixture.assert_running();
    }
}

#[tokio::test]
async fn failed_exec_cancel_removes_authority_for_later_identity_takeover() {
    let fixture = Fixture::prepared().await;
    let result = fixture
        .state
        .receive_rpc(
            Tid::from_raw(WORKER.as_raw()),
            (
                fixture.worker.thread_logical_time.clone(),
                fixture.worker.mm_id,
                GlobalRequest::CancelExec(LEADER),
            ),
        )
        .await;
    assert_eq!(result, (None, GlobalResponse::CancelExec(())));
    let before = serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap();
    let mut guest = fixture.guest(Gate::None);
    assert_eq!(
        super::super::reconnect_exec(&mut guest).await,
        Err(reverie::Errno::EINVAL)
    );
    assert_eq!(guest.thread.dettid, WORKER);
    assert_eq!(
        serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
        before
    );
    fixture.assert_running();
}

#[tokio::test]
async fn exec_transfer_rejects_queued_former_and_live_displaced_leader() {
    for queued_former in [false, true] {
        let fixture = Fixture::with_leader_retired(queued_former).await;
        if queued_former {
            fixture.state.sched.lock().unwrap().next_turns[&WORKER]
                .req
                .put(Ok(Resources::new(WORKER)));
        }
        let before = serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap();
        let mut guest = fixture.guest(Gate::None);
        assert_eq!(
            super::super::reconnect_exec(&mut guest).await,
            Err(reverie::Errno::EINVAL)
        );
        assert_eq!(guest.thread.dettid, WORKER);
        assert_eq!(
            serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
            before
        );
        assert!(
            fixture
                .state
                .pending_exec_states
                .lock()
                .unwrap()
                .contains_key(&LEADER)
        );
        assert!(
            fixture
                .state
                .completed_exec_transfers
                .lock()
                .unwrap()
                .is_empty()
        );
        fixture.assert_displaced_leader_receipt(queued_former);
        if !queued_former {
            let payload = deregistration(&fixture.worker);
            let retired = fixture
                .state
                .receive_rpc(
                    Tid::from_raw(LEADER.as_raw()),
                    (
                        fixture.worker.thread_logical_time.clone(),
                        payload.mm,
                        GlobalRequest::RetireExec {
                            thread: payload,
                            signaled: true,
                        },
                    ),
                )
                .await;
            assert_eq!(retired, (None, GlobalResponse::RetireExec(false)));
            assert_eq!(
                serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
                before
            );
            assert!(
                fixture
                    .state
                    .sched
                    .lock()
                    .unwrap()
                    .next_turns
                    .contains_key(&WORKER)
            );
            assert!(
                fixture
                    .state
                    .pending_exec_states
                    .lock()
                    .unwrap()
                    .contains_key(&LEADER)
            );
        }
        fixture.assert_running();
    }
}

async fn commit_without_acknowledgment(fixture: &Fixture) {
    let mut guest = fixture.guest(Gate::AfterCommit);
    {
        let mut reconnect = Box::pin(super::super::reconnect_exec(&mut guest));
        assert!(futures::poll!(&mut reconnect).is_pending());
    }
    assert!(guest.rpc.reached.load(Ordering::SeqCst));
    assert_eq!(guest.thread.dettid, WORKER);
    assert!(
        fixture
            .state
            .completed_exec_transfers
            .lock()
            .unwrap()
            .contains_key(&LEADER)
    );
    fixture.assert_final_clock(LEADER);
    fixture.assert_running();
}

#[tokio::test]
async fn malformed_exec_retirement_cannot_consume_pending_or_completed_transfer() {
    for committed in [false, true] {
        let fixture = Fixture::prepared().await;
        if committed {
            commit_without_acknowledgment(&fixture).await;
        }
        let before = serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap();
        let good = deregistration(&fixture.worker);
        let old_mm = MmId::initial(LEADER);
        for fault in 0..7 {
            let mut payload = good.clone();
            let mut sender = LEADER;
            let mut header_mm = payload.mm;
            match fault {
                0 => sender = WORKER,
                1 => payload.dettid = PARENT,
                2 => payload.detpid = PARENT,
                3 => header_mm = old_mm,
                4 => payload.mm = old_mm,
                5 => {
                    payload.mm = payload.mm.for_exec(LEADER);
                    header_mm = payload.mm;
                }
                6 => payload.dettid = LEADER,
                _ => unreachable!(),
            }
            payload.syscall_count = 999;
            let mut forged_time = fixture.worker.thread_logical_time.clone();
            forged_time.add_syscall_with_cost(999_999);
            let response = fixture
                .state
                .receive_rpc(
                    Tid::from_raw(sender.as_raw()),
                    (
                        forged_time,
                        header_mm,
                        GlobalRequest::RetireExec {
                            thread: payload,
                            signaled: true,
                        },
                    ),
                )
                .await;
            assert_eq!(
                response,
                (None, GlobalResponse::RetireExec(false)),
                "fault {fault}"
            );
            assert_eq!(
                serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
                before
            );
            assert_eq!(
                fixture
                    .state
                    .pending_exec_states
                    .lock()
                    .unwrap()
                    .contains_key(&LEADER),
                !committed
            );
            assert_eq!(
                fixture
                    .state
                    .completed_exec_transfers
                    .lock()
                    .unwrap()
                    .contains_key(&LEADER),
                committed
            );
            assert!(
                !fixture
                    .state
                    .sched
                    .lock()
                    .unwrap()
                    .per_thread_syscalls
                    .contains_key(&WORKER)
            );
            fixture.assert_running();
        }
    }
}

#[tokio::test]
async fn retired_exec_former_rpc_cannot_recreate_clock_or_account_twice() {
    let fixture = Fixture::prepared().await;
    commit_without_acknowledgment(&fixture).await;
    let before = serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap();
    for mm in [MmId::initial(LEADER), fixture.worker.mm_id] {
        let mut payload = deregistration(&fixture.worker);
        payload.mm = mm;
        payload.syscall_count = 999;
        for request in [
            GlobalRequest::GlobalTimeLowerBound,
            GlobalRequest::RequestResources(Resources::new(WORKER), LEADER),
            GlobalRequest::DeregisterThread(payload),
        ] {
            let expected = if matches!(&request, GlobalRequest::DeregisterThread(_)) {
                GlobalResponse::DeregisterThread(())
            } else {
                GlobalResponse::ThreadExited
            };
            let mut forged_time = fixture.worker.thread_logical_time.clone();
            forged_time.add_syscall_with_cost(999_999);
            let mut late = Box::pin(
                fixture
                    .state
                    .receive_rpc(Tid::from_raw(WORKER.as_raw()), (forged_time, mm, request)),
            );
            assert_eq!(
                futures::poll!(&mut late),
                Poll::Ready((None, expected)),
                "a stale request must be rejected immediately, without a grant"
            );
            assert_eq!(
                serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
                before
            );
            assert!(
                !fixture
                    .state
                    .global_time
                    .lock()
                    .unwrap()
                    .contains_thread(WORKER)
            );
            {
                let sched = fixture.state.sched.lock().unwrap();
                assert!(!sched.next_turns.contains_key(&WORKER));
                assert!(!sched.per_thread_syscalls.contains_key(&WORKER));
                assert!(!sched.per_thread_timeslice.contains_key(&WORKER));
                assert!(sched.next_turns[&LEADER].req.try_read().is_none());
            }
            assert!(
                fixture
                    .state
                    .completed_exec_transfers
                    .lock()
                    .unwrap()
                    .contains_key(&LEADER)
            );
            fixture.assert_running();
        }
    }
    // A duplicate successful-exec notification must also fail before accounting.
    let result = fixture
        .state
        .receive_rpc(
            Tid::from_raw(LEADER.as_raw()),
            (
                fixture.worker.thread_logical_time.clone(),
                fixture.worker.mm_id,
                GlobalRequest::ReconnectExec {
                    former: WORKER,
                    process: LEADER,
                },
            ),
        )
        .await;
    assert_eq!(result, (None, GlobalResponse::ReconnectExec(false)));
    assert_eq!(
        serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
        before
    );
}

#[tokio::test]
async fn exec_continuation_applies_relative_grant_once_at_the_carried_current_clock() {
    let fixture = Fixture::prepared().await;
    let mut guest = fixture.guest(Gate::AfterCommit);
    let duration = LogicalTime::from_nanos(1_000_000);
    let now = guest.thread.thread_logical_time.as_nanos();
    let old_deadline = fixture.before_tail + duration;
    guest.thread.end_of_timeslice = Some(old_deadline);
    guest.thread.max_timeslice_end = Some(old_deadline);
    guest.thread.last_rcb_timer = Some(1_234);
    let release = guest.rpc.release.clone();
    {
        let mut reconnect = Box::pin(super::super::reconnect_exec(&mut guest));
        assert!(futures::poll!(&mut reconnect).is_pending());
        // Scheduler replay tests separately prove how the cursor stages this
        // duration. Here a real Go(Value) must reach the preserved local state.
        fixture
            .state
            .sched
            .lock()
            .unwrap()
            .timeslices
            .insert(LEADER, Some(duration));
        release.put(());
        assert!(futures::poll!(&mut reconnect).is_pending());
        let turn = crate::scheduler::do_a_turn_blocking(
            fixture.state.sched.clone(),
            fixture.state.global_time.clone(),
            &Err(crate::scheduler::SkipTurn),
        )
        .await
        .expect("replacement must receive its duration grant");
        assert_eq!(turn.tid, LEADER);
        assert_eq!(reconnect.await, Ok(()));
    }
    assert_eq!(guest.thread.dettid, LEADER);
    assert_eq!(guest.thread.thread_logical_time.as_nanos(), now);
    assert_eq!(guest.thread.end_of_timeslice, Some(now + duration));
    assert_eq!(guest.thread.max_timeslice_end, Some(now + duration));
    assert_ne!(guest.thread.end_of_timeslice, Some(old_deadline));
    assert_ne!(guest.thread.end_of_timeslice, Some(old_deadline + duration));
    assert_eq!(guest.thread.last_rcb_timer, Some(1_234));
    assert_eq!(fixture.state.sched.lock().unwrap().turn, 1);
    assert!(
        !fixture
            .state
            .sched
            .lock()
            .unwrap()
            .timeslices
            .contains_key(&LEADER)
    );
    fixture.assert_final_clock(LEADER);
}

#[tokio::test]
async fn reused_exec_worker_start_waits_for_parent_registration_before_clock_or_grant() {
    let fixture = Fixture::prepared().await;
    let mut parent = fixture.guest(Gate::None);
    {
        let mut reconnect = Box::pin(super::super::reconnect_exec(&mut parent));
        assert!(futures::poll!(&mut reconnect).is_pending());
        let turn = crate::scheduler::do_a_turn_blocking(
            fixture.state.sched.clone(),
            fixture.state.global_time.clone(),
            &Err(crate::scheduler::SkipTurn),
        )
        .await
        .unwrap();
        assert_eq!(turn.tid, LEADER);
        assert_eq!(reconnect.await, Ok(()));
    }
    assert_eq!(parent.thread.dettid, LEADER);
    let old_mm = MmId::initial(LEADER);
    let new_mm = parent.thread.mm_id;
    assert_ne!(old_mm, new_mm);
    let before = serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap();
    for mm in [old_mm, new_mm] {
        let rejected = fixture
            .state
            .receive_rpc(
                Tid::from_raw(WORKER.as_raw()),
                (
                    parent.thread.thread_logical_time.clone(),
                    mm,
                    GlobalRequest::GlobalTimeLowerBound,
                ),
            )
            .await;
        assert_eq!(rejected, (None, GlobalResponse::ThreadExited));
        assert_eq!(
            serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
            before
        );
    }

    // Construct the new child through the Tool's real inheritance path. Its
    // reused numeric TID does not authorize either clock publication or startup.
    let flags = CloneFlags::CLONE_THREAD | CloneFlags::CLONE_VM;
    parent.thread.clone_flags = Some(flags);
    let mut child = fixture.tool.init_thread_state(
        Tid::from_raw(WORKER.as_raw()),
        Some((Tid::from_raw(LEADER.as_raw()), &parent.thread)),
    );
    parent.thread.clone_flags = None;
    child.detpid = Some(LEADER);
    child.thread_start_entered = true;
    assert_eq!(child.mm_id, new_mm);
    let mut startup = Box::pin(fixture.state.receive_rpc(
        Tid::from_raw(WORKER.as_raw()),
        (
            child.thread_logical_time.clone(),
            new_mm,
            GlobalRequest::StartNewThread(WORKER, LEADER, None, None),
        ),
    ));
    for _ in 0..2 {
        assert!(futures::poll!(&mut startup).is_pending());
        assert_eq!(
            serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
            before
        );
        assert!(
            !fixture
                .state
                .global_time
                .lock()
                .unwrap()
                .contains_thread(WORKER)
        );
        let sched = fixture.state.sched.lock().unwrap();
        assert!(sched.transferred_exec_tid_requires_registration(WORKER));
        assert!(!sched.next_turns.contains_key(&WORKER));
        assert_eq!(sched.turn, 1);
    }

    // The authenticated parent registers the actual clone and then parks on
    // ParentContinue. A higher child priority makes the next grant unambiguous.
    let mut registration = Box::pin(fixture.state.receive_rpc(
        Tid::from_raw(LEADER.as_raw()),
        (
            parent.thread.thread_logical_time.clone(),
            new_mm,
            GlobalRequest::CreateChildThread(
                WORKER,
                LEADER,
                0,
                Some(flags),
                0,
                None,
                Some(DEFAULT_PRIORITY - 1),
            ),
        ),
    ));
    assert!(futures::poll!(&mut registration).is_pending());
    {
        let sched = fixture.state.sched.lock().unwrap();
        assert!(!sched.transferred_exec_tid_requires_registration(WORKER));
        assert!(sched.next_turns.contains_key(&WORKER));
        assert!(sched.rpc_incarnation_matches(WORKER, new_mm));
        assert!(!sched.rpc_incarnation_matches(WORKER, old_mm));
        assert_eq!(sched.turn, 1);
    }
    assert!(
        !fixture
            .state
            .global_time
            .lock()
            .unwrap()
            .contains_thread(WORKER)
    );
    assert!(futures::poll!(&mut startup).is_pending());
    assert!(futures::poll!(&mut startup).is_pending());
    assert!(
        fixture.state.sched.lock().unwrap().next_turns[&WORKER]
            .req
            .try_read()
            .is_some()
    );
    let child_turn = crate::scheduler::do_a_turn_blocking(
        fixture.state.sched.clone(),
        fixture.state.global_time.clone(),
        &Err(crate::scheduler::SkipTurn),
    )
    .await
    .expect("registered reused newborn must receive a real grant");
    assert_eq!(child_turn.tid, WORKER);
    assert_eq!(startup.await, (None, GlobalResponse::StartNewThread(None)));
    assert_eq!(fixture.state.sched.lock().unwrap().turn, 2);
    let total = fixture.before_tail + LogicalTime::from_nanos(497);
    assert_eq!(fixture.state.global_time.lock().unwrap().as_nanos(), total);
    let allowed = fixture
        .state
        .receive_rpc(
            Tid::from_raw(WORKER.as_raw()),
            (
                child.thread_logical_time.clone(),
                new_mm,
                GlobalRequest::GlobalTimeLowerBound,
            ),
        )
        .await;
    assert_eq!(allowed, (None, GlobalResponse::GlobalTimeLowerBound(total)));

    let registered_clock =
        serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap();
    for request in [
        GlobalRequest::StartNewThread(WORKER, LEADER, None, None),
        GlobalRequest::GlobalTimeLowerBound,
    ] {
        let mut forged_time = child.thread_logical_time.clone();
        forged_time.add_syscall_with_cost(999_999);
        let mut stale = Box::pin(fixture.state.receive_rpc(
            Tid::from_raw(WORKER.as_raw()),
            (forged_time, old_mm, request),
        ));
        assert_eq!(
            futures::poll!(&mut stale),
            Poll::Ready((None, GlobalResponse::ThreadExited))
        );
        assert_eq!(
            serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
            registered_clock
        );
        assert_eq!(fixture.state.sched.lock().unwrap().turn, 2);
    }

    // Complete both genuine owners so this test does not abandon the parent's
    // parked registration future after observing the child's successful start.
    consume(&fixture.state, &fixture.tool, WORKER, child).await;
    let parent_turn = crate::scheduler::do_a_turn_blocking(
        fixture.state.sched.clone(),
        fixture.state.global_time.clone(),
        &Err(crate::scheduler::SkipTurn),
    )
    .await
    .unwrap();
    assert_eq!(parent_turn.tid, LEADER);
    assert_eq!(
        registration.await,
        (None, GlobalResponse::CreateChildThread(None))
    );
    assert_eq!(fixture.state.sched.lock().unwrap().turn, 3);
    assert_eq!(fixture.state.global_time.lock().unwrap().as_nanos(), total);

    for flags in [
        CloneFlags::CLONE_VFORK,
        CloneFlags::CLONE_VFORK | CloneFlags::CLONE_VM,
    ] {
        reused_exec_worker_vfork_registration_requires_creation_mode(flags, false).await;
    }
    reused_exec_worker_vfork_registration_requires_creation_mode(CloneFlags::empty(), true).await;
}

async fn reused_exec_worker_vfork_registration_requires_creation_mode(
    valid_flags: CloneFlags,
    backend_serializes_fork_children: bool,
) {
    let fixture = Fixture::configured(true, backend_serializes_fork_children).await;
    let mut parent = fixture.guest(Gate::None);
    {
        let mut reconnect = Box::pin(super::super::reconnect_exec(&mut parent));
        assert!(futures::poll!(&mut reconnect).is_pending());
        let turn = crate::scheduler::do_a_turn_blocking(
            fixture.state.sched.clone(),
            fixture.state.global_time.clone(),
            &Err(crate::scheduler::SkipTurn),
        )
        .await
        .unwrap();
        assert_eq!(turn.tid, LEADER);
        assert_eq!(reconnect.await, Ok(()));
    }
    let parent_mm = parent.thread.mm_id;
    let child_mm = MmId::for_clone(
        parent_mm,
        WORKER,
        valid_flags.contains(CloneFlags::CLONE_VM),
    );
    let child_time = parent.thread.thread_logical_time.clone_for_child();
    let mut resources = Resources::new(LEADER);
    resources.insert(
        ResourceID::BlockingVfork(ExternalOpId::new(LEADER, 1)),
        Permission::RW,
    );
    let mut blocking = Box::pin(fixture.state.receive_rpc(
        Tid::from_raw(LEADER.as_raw()),
        (
            parent.thread.thread_logical_time.clone(),
            parent_mm,
            GlobalRequest::RequestResources(resources, LEADER),
        ),
    ));
    assert!(futures::poll!(&mut blocking).is_pending());
    let background = crate::scheduler::do_a_turn_blocking(
        fixture.state.sched.clone(),
        fixture.state.global_time.clone(),
        &Err(crate::scheduler::SkipTurn),
    )
    .await;
    assert!(background.is_err());
    assert_eq!(
        blocking.await,
        (None, GlobalResponse::RequestResources(ResumeStatus::Normal))
    );
    let before = serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap();
    let before_total = fixture.state.global_time.lock().unwrap().as_nanos();
    assert_eq!(fixture.state.sched.lock().unwrap().turn, 2);

    // The parent/mm proof is genuinely valid here. Only the creation mode is
    // wrong: ordinary clones cannot borrow a vfork grant, and a backend that
    // serializes process forks does not thereby authorize thread clones.
    let wrong_flags = if backend_serializes_fork_children {
        CloneFlags::CLONE_THREAD | CloneFlags::CLONE_VM
    } else {
        valid_flags & !CloneFlags::CLONE_VFORK
    };
    let wrong_mm = MmId::for_clone(
        parent_mm,
        WORKER,
        wrong_flags.contains(CloneFlags::CLONE_VM),
    );
    {
        let sched = fixture.state.sched.lock().unwrap();
        assert!(sched.pending_vfork_registration_matches(
            LEADER,
            LEADER,
            WORKER,
            wrong_mm,
            wrong_flags.contains(CloneFlags::CLONE_VM),
        ));
        assert!(sched.transferred_exec_tid_requires_registration(WORKER));
    }
    let mut forged_time = child_time.clone();
    forged_time.add_syscall_with_cost(999_999);
    let rejected = fixture
        .state
        .receive_rpc(
            Tid::from_raw(WORKER.as_raw()),
            (
                forged_time,
                wrong_mm,
                GlobalRequest::CreateVforkChildThread(
                    LEADER,
                    LEADER,
                    WORKER,
                    0,
                    wrong_flags,
                    libc::SIGCHLD,
                    Some(DEFAULT_PRIORITY),
                ),
            ),
        )
        .await;
    assert_eq!(rejected, (None, GlobalResponse::ThreadExited));
    assert_eq!(
        serde_json::to_value(&*fixture.state.global_time.lock().unwrap()).unwrap(),
        before
    );
    assert!(
        !fixture
            .state
            .global_time
            .lock()
            .unwrap()
            .contains_thread(WORKER)
    );
    {
        let sched = fixture.state.sched.lock().unwrap();
        assert!(sched.transferred_exec_tid_requires_registration(WORKER));
        assert!(!sched.next_turns.contains_key(&WORKER));
        assert_eq!(sched.turn, 2);
        assert!(sched.pending_vfork_registration_matches(
            LEADER,
            LEADER,
            WORKER,
            child_mm,
            valid_flags.contains(CloneFlags::CLONE_VM),
        ));
    }

    // The same, still-unconsumed grant admits the valid raw-vfork mode or the
    // configured serialized-process-fork mode, without double-counting ancestry.
    let created = fixture
        .state
        .receive_rpc(
            Tid::from_raw(WORKER.as_raw()),
            (
                child_time.clone(),
                child_mm,
                GlobalRequest::CreateVforkChildThread(
                    LEADER,
                    LEADER,
                    WORKER,
                    0,
                    valid_flags,
                    libc::SIGCHLD,
                    Some(DEFAULT_PRIORITY),
                ),
            ),
        )
        .await;
    assert_eq!(created, (None, GlobalResponse::CreateChildThread(None)));
    assert_eq!(
        fixture.state.global_time.lock().unwrap().as_nanos(),
        before_total
    );
    assert_eq!(
        fixture
            .state
            .global_time
            .lock()
            .unwrap()
            .threads_time(WORKER),
        child_time.as_nanos()
    );
    {
        let sched = fixture.state.sched.lock().unwrap();
        assert!(!sched.transferred_exec_tid_requires_registration(WORKER));
        assert_eq!(sched.registered_process(WORKER), Some(WORKER));
        assert!(sched.rpc_incarnation_matches(WORKER, child_mm));
        assert!(!sched.pending_vfork_registration_matches(
            LEADER,
            LEADER,
            WORKER,
            child_mm,
            valid_flags.contains(CloneFlags::CLONE_VM),
        ));
        assert_eq!(sched.turn, 2);
    }
    let mut startup = Box::pin(fixture.state.receive_rpc(
        Tid::from_raw(WORKER.as_raw()),
        (
            child_time,
            child_mm,
            GlobalRequest::StartNewThread(WORKER, WORKER, None, None),
        ),
    ));
    assert!(futures::poll!(&mut startup).is_pending());
    assert!(futures::poll!(&mut startup).is_pending());
    let turn = crate::scheduler::do_a_turn_blocking(
        fixture.state.sched.clone(),
        fixture.state.global_time.clone(),
        &background,
    )
    .await
    .expect("authorized reused vfork child must receive its first turn");
    assert_eq!(turn.tid, WORKER);
    assert_eq!(startup.await, (None, GlobalResponse::StartNewThread(None)));
    assert_eq!(fixture.state.sched.lock().unwrap().turn, 3);
    assert_eq!(
        fixture.state.global_time.lock().unwrap().as_nanos(),
        before_total
    );
}