vj-sim 0.3.0

Netlist, scheduler and process model of the vj SystemVerilog simulator.
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
//! SCHED (`vj-sim::sched`) — cross-track contract only: the event
//! scheduler/kernel-control surface shared with STATE, A2-PROCESS, DETERMINISM,
//! RUNTIME and the debugger (scheduler.md). Real event-queue/time-wheel
//! implementation belongs to the `sched` track, not this wave.

use vj_abi::{Region, SimHandle, SimTime};

use crate::process::{PredicateFn, StmtId};
use crate::state::{EdgeKind, FourStateValue, StateCellId};

pub mod assert_control;
pub mod class_event;
mod control;
mod dedup;
mod deferred;
mod finals;
mod guard;
pub mod host;
mod io_gate;
mod kernel_adapter;
pub mod mailbox;
pub mod maturation;
mod nba;
mod notify;
mod ops;
mod order;
pub mod proc_assert;
pub mod process_rng;
mod process_table;
mod queues;
mod region_callback;
mod repeat;
mod reschedule_req_proposal;
mod resume;
pub mod semaphore;
mod sensitivity;
mod subscribe;
pub mod thread_hooks;
mod violation;
mod wheel;
pub use control::*;
pub use dedup::*;
pub use deferred::{
    deferred_call_for, deferred_cancel_for, deferred_report, deferred_report_for,
    set_deferred_writer,
};
pub use finals::*;
pub use guard::*;
pub use io_gate::*;
pub use kernel_adapter::*;
pub use nba::*;
pub use notify::*;
pub use ops::*;
pub use order::*;
pub use process_table::*;
pub use queues::*;
pub use region_callback::*;
pub use repeat::*;
pub use resume::*;
pub use sensitivity::*;
pub use subscribe::*;
pub use thread_hooks::{
    ThreadEvent, ThreadHook, fire_thread_event, set_thread_hook, thread_hook_installed,
};
pub use violation::{
    DEFERRED_MODE_CANCEL, DEFERRED_MODE_FINAL, DEFERRED_MODE_OBSERVED, ViolationType,
    set_violation_writer, violation_report, violation_report_for,
};
pub use wheel::*;

pub type ProcessId = u32;
pub type ActivationId = u64;

/// Ticks at the compilation's minimum time precision (SC-064).
pub type SimTick = u64;

/// The scheduler-internal logical-time value (scheduler.md §2; ledger SC-023,
/// SC-033, SC-129). **Deliberately a different type from the ABI-facing
/// `vj_abi::SimTime{sim_units, delta}`** (docs/CONTRACTS.md r3 item 1):
/// `delta` is not a field here and never will be — it is purely a local
/// iteration count of the inner Active/Inactive/NBA convergence loop
/// (`reconv_iter` on [`PendingActivation`]/`CanonicalEventKey`), discarded
/// once that loop converges (SC-023). The only way to get from this type to
/// the ABI's is [`SchedTime::to_abi_display`], the one documented conversion
/// point (SC-129) — it never runs the other way, and nothing derives a
/// `delta` from `ticks` internally.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct SchedTime {
    pub ticks: SimTick,
}

const _: () = assert!(core::mem::size_of::<SchedTime>() == 8);

impl SchedTime {
    /// The one documented `SchedTime` -> `vj_abi::SimTime` conversion
    /// point (SC-129), used only at the ABI/display boundary. `delta` is
    /// always the caller's own delta-loop iteration counter — never read from
    /// or derived from `self.ticks` — because the internal type never carries
    /// one (SC-023).
    pub fn to_abi_display(self, delta: u32) -> vj_abi::SimTime {
        vj_abi::SimTime {
            sim_units: self.ticks as i64,
            delta,
        }
    }
}

/// The reconciled 5-region ABI discriminant, exhaustively matched (SC-016,
/// SC-117): pins `region_ordinal` to `Region`'s own `#[repr(u32)]`
/// discriminant rather than a second, hand-maintained numbering that could
/// drift from it. No wildcard arm — adding a 6th `Region` variant fails this
/// match to compile.
pub fn region_ordinal(region: Region) -> u32 {
    match region {
        Region::Active => Region::Active as u32,
        Region::Inactive => Region::Inactive as u32,
        Region::Nba => Region::Nba as u32,
        Region::Reactive => Region::Reactive as u32,
        Region::Postponed => Region::Postponed as u32,
        // sva T1 (§1.4, review fix, blocking finding 2): mechanical, like
        // every other arm above.
        Region::Preponed => Region::Preponed as u32,
        // sva T2 (§1.4, review fix, blocking finding 2), Observed's half:
        // equally mechanical.
        Region::Observed => Region::Observed as u32,
    }
}

/// What woke a `CompiledProcess::resume()` call (scheduler.md §5).
#[derive(Clone, Copy, Debug)]
pub enum ResumeArg {
    Start,
    TimeElapsed,
    EventFired {
        term_index: usize,
    },
    ForkChildDone {
        child: ProcessId,
    },
    Disabled,
    /// **NEW (Task 9, B-sched wave, ledger SC-125).** `Suspend::WaitFork`'s
    /// resolution: every `ProcessId` live in the resuming process's own
    /// `fork_children` at the moment it suspended has now reached
    /// `Suspend::Done` and been reclaimed.
    AllForkChildrenDone,
    /// **NEW (Task 9, SC-125).** `Suspend::WaitOrder(order)`'s resolution:
    /// every `ProcessId` in `order` completed, in exactly that declared
    /// order.
    WaitOrderSatisfied,
}

/// `BlockStatement`'s three join semantics (`StatementBlockKind` mirror; ledger
/// PR-086 and the fork/join family).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum JoinKind {
    All,
    Any,
    None,
}

/// One `@(...)`/`wait(...)` disjunct (scheduler.md §4/§5; ledger SC-048..SC-051,
/// SC-065).
#[derive(Clone, Debug)]
pub enum EventTerm {
    Edge {
        cell: StateCellId,
        edge: EdgeKind,
        iff: Option<PredicateFn>,
    },
    ImplicitAny(Vec<StateCellId>),
    /// A wait on a bit/part select of one cell (`@(v[3])`, `@(posedge
    /// v[5:4])`, LRM 9.4.2): it fires on an update that changed bits `[lsb,
    /// lsb + width)` of `cell` (any change when `edge` is `None`, else the
    /// transition of bit `lsb` classified as `edge`). The update is judged on
    /// its own old/new words (`ChangeDelta`), so a bit that is set and cleared
    /// again by two updates in one time step wakes the waiter once per
    /// update, exactly as the LRM's update events do (4.9.4).
    Select {
        cell: StateCellId,
        edge: EdgeKind,
        lsb: u32,
        width: u32,
    },
    /// **Also the resolution for `BlockEventListControl` (`@(block.
    /// triggered)`), SC-054's own "kept as a hook-only `EventTerm` mapping
    /// in v1" acceptance, resolved here rather than by adding a 5th
    /// variant:** `@(block.triggered)` needs no new `EventTerm` shape at
    /// all -- codegen reserves one synthetic `StateCellId` per named
    /// statement block and fires it (through the same `TimerAction::
    /// TriggerEvent`/direct `notify_change` fan-out an ordinary `->`/`->>`
    /// trigger already uses, `sched::wheel`'s own SC-069 doc comment)
    /// exactly when that block completes -- i.e. `.triggered` is modeled as
    /// an ordinary named event whose trigger site is block-exit instead of
    /// an explicit `->` statement. `NamedEventTrigger`'s own
    /// scheduler-side consumption (installing an any-change dynamic entry
    /// keyed by the cell, waking every waiter on a real fire) is already
    /// real and tested (Task 5, `sched::sensitivity::tests::
    /// named_event_trigger_term_installs_an_any_change_dynamic_entry`) --
    /// what remains for `@(block.triggered)`
    /// specifically is purely whether codegen (B-process, out of this
    /// track's ownership) actually emits the block-exit trigger call; this
    /// scheduler-side half never hits a silent mis-simulation regardless
    /// (SC-054's own negative acceptance clause), since an unfired trigger
    /// cell simply never wakes anyone -- observably a hang/timeout, never a
    /// wrong value.
    NamedEventTrigger(StateCellId),
    /// `repeat(count)@(...)` (mirrors slang's `RepeatedEventControl{expr,
    /// event}`; ledger SC-052). `SensitivityTable::install_term` installs
    /// only `inner`'s own edge at *this* term's index — the count itself is
    /// resume-orchestration state, tracked live by
    /// [`RepeatCounters`](crate::sched::RepeatCounters) (`sched/repeat.rs`),
    /// not by the sensitivity table.
    ///
    /// **`##N`/clocking-block cycle delays reduce to this term, with no
    /// second mechanism (SC-004, SC-005, SC-053):** per ARCHITECTURE §6.5,
    /// `CycleDelayControl` is resolved to absolute ticks *at runtime*, not
    /// pre-resolved by codegen/elaboration — `##N` relative to a clocking
    /// block's bound clock is semantically `Repeat{count: N, inner:
    /// Edge{cell: <bound clock's cell>, edge: Posedge, iff: None}}`. Because
    /// `RepeatCounters` counts live firings of `inner`'s real signal rather
    /// than precomputing an absolute tick offset, "the same compiled `##N`
    /// delay produces different absolute tick timing when its associated
    /// clock's period changes dynamically at runtime" (SC-053's own
    /// differentiating acceptance clause) holds by construction: there is no
    /// cached tick offset to go stale. See `sched::repeat`'s own module doc
    /// comment and `sched::control`'s
    /// `sc053_repeat_based_wait_re_reads_the_clocks_live_period_not_a_cached_tick_offset`
    /// for the proof against a deliberately irregular (non-periodic) clock.
    Repeat {
        count: u64,
        inner: Box<EventTerm>,
    },
}

/// `WaitKind::Any` is SV's only real semantics; kept as an explicit list for
/// `##N`/`repeat` (scheduler.md).
#[derive(Clone, Debug, Default)]
pub struct EventWaitSet {
    pub terms: Vec<EventTerm>,
    /// `true` for `wait(expr)`: the resumed process re-checks its condition
    /// before running on, so a wake delivered while the process was
    /// suspended (`process::suspend`, LRM 9.7.4) can be parked and replayed
    /// by `resume()` harmlessly. `false` for an `@(...)` event control,
    /// where the LRM desensitises a suspended waiter: an event that fires
    /// during the suspension is missed, not replayed.
    pub rechecks_on_wake: bool,
}

/// What a `CompiledProcess::resume()` call returns to the in-process scheduler
/// orchestration loop. See [`crate::process::WaitSpec`] for the lower-level,
/// codegen/ABI-facing sibling of this type and the reconciliation note there.
///
/// **Fork/join (RESOLVED, docs/CONTRACTS.md "Resolved design decisions" D1).**
/// A `fork` hands the scheduler *spawn descriptors*, not process identities and
/// not process objects. The three design docs disagreed three ways
/// (scheduler.md: `Vec<Box<dyn CompiledProcess>>`; the r2 placeholder:
/// `Vec<ProcessId>`; process.md §7: an undefined `ProcessHandle`):
/// - `Vec<ProcessId>` is wrong: the children do not exist yet when the parent
///   suspends, so nothing could have assigned those ids.
/// - `Box<dyn CompiledProcess>` contradicts ARCHITECTURE §5's frozen ABI (a
///   process is an `extern "C"` `ProcessFn` entry in `VJ_PROCESS_TABLE`,
///   not a Rust trait object) and cannot satisfy `Suspend: Clone`.
///
/// Fork branches are statically known code: codegen emits each branch as its
/// own process-table kernel. So the parent returns one [`SpawnSpec`] per
/// branch; the scheduler registers each, assigns the child its [`ProcessId`],
/// records the ids in the parent's `ForkFrame::children`, sets
/// `ForkFrame::remaining` per [`JoinKind`] (All = n, Any = 1, None = 0 — the
/// parent resumes immediately), and later reports each completion back via
/// `ResumeArg::ForkChildDone { child }`. Children reach variables declared in
/// the parent's enclosing scopes through [`SpawnSpec::parent`] (LRM 9.3.2).
/// Rolling back a parent that has already spawned live children must also
/// roll back / kill those children — owned by the determinism rows, not this
/// type.
#[derive(Clone, Debug)]
pub enum Suspend {
    Delay(u64),
    WaitEvents(EventWaitSet),
    ForkJoin(JoinKind, Vec<SpawnSpec>),
    /// **NEW (Task 9, B-sched wave, ledger SC-125) — scheduler-side half of
    /// `wait fork;`.** Blocks the calling process until every `ProcessId`
    /// currently live in its own `ProcessDescriptor::fork_children`
    /// (populated by an earlier `fork ... join_none`) has reached
    /// `Suspend::Done` and been reclaimed; resumes via
    /// `ResumeArg::AllForkChildrenDone`. See `sched::control::Engine::
    /// apply_wait_fork` and `sched::resume::ResumeDriver::on_child_done`'s
    /// own doc comments for the mechanism. `disable fork;` is deliberately
    /// **not** a `Suspend` variant here -- it never suspends the caller, so
    /// it is instead a synchronous `SchedulerOps::disable_fork` call (see
    /// that method's own doc comment).
    WaitFork,
    /// **NEW (Task 9, SC-125) — scheduler-side half of `wait_order(a, b,
    /// c);`.** Blocks the calling process until every `ProcessId` in
    /// `order` has completed, in exactly that declared order; resumes via
    /// `ResumeArg::WaitOrderSatisfied` on success. An out-of-order
    /// completion never silently satisfies the wait or panics -- it is
    /// surfaced as `sched::resume::ResumeError::WaitOrderViolated` (see
    /// that type's own doc comment).
    WaitOrder(Vec<ProcessId>),
    /// Task 8 (AB-085): a barrier-wait suspend -- the process yields until
    /// every parallel lane has reached the same GVT boundary. Deliberately
    /// carries no payload and needs no new coroutine/stack mechanism: it
    /// reuses the exact same suspend/resume dispatch every other `Suspend`
    /// variant goes through (`apply_suspend` in `sched::control` handles it
    /// by delegating to the `Delay(0)` arm's existing code path -- see that
    /// function's own doc comment). The real GVT-barrier semantics (actually
    /// gating resumption on every parallel lane's progress, not just
    /// resolving at the next delta step) belong to the determinism/parallel-
    /// engine track and are not implemented by this wave; this variant only
    /// wires the ABI-level suspend reason into the existing dispatch so a
    /// compiled process can report it.
    WaitForGvt,
    /// Classes plan Task 13 (LRM 9.7): the process yields because it just
    /// queued a [`ProcessRequest`] through [`SchedulerOps::process_request`]
    /// (`p.await()` / `p.suspend()` called as a statement). Unlike every
    /// other variant it carries no wake condition of its own: the engine
    /// resumes the process immediately unless the request left it
    /// self-suspended or awaiting another process (see
    /// `sched::control::Engine::apply_by_request`).
    ByRequest,
    Done,
}

/// `process::state` (LRM 9.7), in the enum's declaration order -- the
/// discriminant IS the value `p.status()` returns.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum ProcessState {
    Finished = 0,
    Running = 1,
    Waiting = 2,
    Suspended = 3,
    Killed = 4,
}

/// One `process` class method call that mutates another process (or this
/// one), queued by [`SchedulerOps::process_request`] and applied by the
/// engine at the next suspend point -- the same drain-at-`apply_suspend`
/// shape `disable fork` uses, because `SchedulerOps` methods take `&self`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ProcessRequest {
    Kill(ProcessId),
    Suspend(ProcessId),
    Resume(ProcessId),
    Await(ProcessId),
    /// Classes plan Task 17 (LRM 15.3): the requester called a blocking
    /// synchronisation-object method (`semaphore.get`) that must wait; it
    /// stays yielded after its `Suspend::ByRequest` until a
    /// [`ProcessRequest::SyncWake`] names it.
    SyncBlock,
    /// The named process's blocked `get` has been granted its keys: it runs
    /// again. Queued by the `put` (or kill) that released it.
    SyncWake(ProcessId),
}

/// One fork branch the scheduler must instantiate (see [`Suspend::ForkJoin`]).
///
/// Not `Copy` (unlike every other scheduler ABI value): [`Self::disable_name`]
/// is a real, possibly-nonempty `String`, not FFI/ABI data -- this struct
/// stays a plain, compile-time-constant Rust value (per its own module's
/// `decode_reschedule_with_fork_table`/`fork_table` doc comments), never
/// crosses an `extern "C"` boundary, so losing `Copy` costs nothing a real
/// caller observes; every construction site this adds a field to is a
/// struct literal, so a missed one is a compile error, never a silent gap.
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct SpawnSpec {
    /// Index into the compiled kernel's `VJ_PROCESS_TABLE` of the kernel
    /// codegen emitted for this fork branch.
    pub kernel: u32,
    /// Resume point (segment / `resume_pc`) at which the child starts.
    pub entry_pc: u32,
    /// The spawning process; the child's activation record links to it for
    /// access to variables declared in enclosing scopes (LRM 9.3.2).
    pub parent: ProcessId,
    /// The name(s) a `disable` elsewhere may target this branch by (LRM
    /// 9.6.2): the enclosing `fork : NAME` label, if any, and/or this
    /// branch's own named outermost block, if it has one -- both resolved at
    /// compile time by `vj_sim::process::cfg`'s fork-branch walk. Empty
    /// for an unnamed branch of an unnamed fork, which no `disable` can ever
    /// single out. `Engine::apply_suspend`'s `Suspend::ForkJoin` handling
    /// tags each newly minted child's `ProcessDescriptor::disable_names`
    /// with this list the moment `handle_fork` hands back its `ProcessId`.
    pub disable_name: Vec<String>,
}

/// One resumable process (scheduler.md §5): the scheduler owns zero per-process
/// program-counter state — it lives in STATE-arena-allocated, A2-process-owned
/// `ActivationRecord` storage.
///
/// **SC-127 scheduler-side resolution (Task 8, B-sched wave):** the
/// scheduler places no restriction on *where*, syntactically or
/// call-stack-wise, a [`Suspend`] value is constructed inside `resume()`.
/// `resume()` is a plain function returning a plain value — the dispatch
/// loop (`sched::control::Engine::apply_suspend`) matches only on the
/// *returned* `Suspend` variant, never on how deep in the call stack it was
/// built or what code ran to build it. A DPI-imported-task call site that
/// itself calls back into blocking SV (LRM 35.5.6) is therefore
/// representable today, with zero scheduler-side changes, exactly like this
/// module's own `sc127_a_mock_process_may_suspend_from_a_point_that_
/// stands_in_for_a_dpi_imported_task_callback` test constructs: a `Suspend`
/// returned from several stack frames deep inside ordinary Rust calls
/// dispatches and completes identically to one returned directly from
/// `resume`'s own top-level match arm. **What this does *not* resolve** —
/// whether `vj-sim::process`'s CFG builder / `analysis::dpi` actually
/// choose to treat a given DPI-imported-task call site as a suspend point at
/// all (i.e. which call sites qualify, and whether codegen ever emits one),
/// per SC-127's own acceptance clause (a) vs. (b) — is that track's decision,
/// not `sched`'s, and is cross-referenced here rather than silently assumed
/// resolved.
pub trait CompiledProcess: Send {
    fn resume(&mut self, state: SimHandle, arg: ResumeArg, ops: &dyn SchedulerOps) -> Suspend;

    /// Builds the real child process for one branch of a `fork` this process
    /// just suspended on (`Suspend::ForkJoin`, PR-085). `None` means this
    /// process has no compiled branch kernels to offer (every hand-written
    /// test process); `Engine` then falls back to its inert placeholder
    /// child. A compiled kernel process overrides this so `vj run`
    /// actually executes each branch body.
    fn mint_fork_child(&self, _spec: &SpawnSpec) -> Option<Box<dyn CompiledProcess>> {
        None
    }

    /// The instance whose block and task names a `disable <label>;` run by
    /// this process (or a fork branch of it) ends the activities of (LRM
    /// 9.6.2); `None` for a process that has none (hand-written test
    /// processes, fork branches).
    fn disable_instance(&self) -> Option<u32> {
        None
    }

    /// Where this process, suspended, resumes if its activity inside the
    /// named block or task activation `label` is disabled: the block's (or the
    /// call's) end. `None` when it is not inside `label`, or has finished.
    fn disable_exit(&self, _label: &str) -> Option<u32> {
        None
    }

    /// Whether the process has a disable scope `label` at all, whether or not
    /// it is inside it now (or has finished): a `disable` of that block ends
    /// the fork branches it left running (LRM 9.6.2).
    fn owns_disable_scope(&self, _label: &str) -> bool {
        false
    }

    /// Makes the process's next resume continue at `pc`
    /// ([`Self::disable_exit`]). Returns whether it was blocked joining the
    /// processes it forked (`join`, `join_any`, `wait fork`, `wait_order`).
    fn redirect_resume(&mut self, _pc: u32) -> bool {
        false
    }
}

/// A deferred, GVT-gated I/O callback (see [`SchedulerOps::defer_io`]).
pub type DeferredIoCallback = Box<dyn FnOnce(&mut dyn IoCtx) + Send>;

/// The scheduler-provided operations a running kernel/process calls back into
/// (scheduler.md's `SchedulerOps`; ledger SC-036, SC-042, SC-044, SC-070, SC-075,
/// SC-116).
pub trait SchedulerOps {
    fn now(&self) -> SchedTime;
    fn current_region(&self) -> Region;
    /// Any concrete implementation MUST call [`NbaLog::stage`] and MUST NOT
    /// provide any other write path for a nonblocking (`<=`) assignment —
    /// this is the textual pin for SC-036 (no direct-apply path for NBA
    /// writes anywhere in the scheduler), made enforceable by Task 8's
    /// mock `SchedulerOps` test.
    fn stage_nba(&self, cell: StateCellId, value: FourStateValue, source: ProcessId);
    fn commit_blocking_write(&self, cell: StateCellId, value: FourStateValue);
    /// The future simulation ticks with something scheduled (timed process
    /// wake-ups, delayed nonblocking writes), ascending: the time queue a
    /// VPI application iterates (IEEE 1800-2023 37.81). Empty where the
    /// implementation has no time wheel.
    fn pending_ticks(&self) -> Vec<u64> {
        Vec::new()
    }
    /// The processes waiting on `cell` now (a suspended `@`/`wait` or a
    /// static sensitivity), for VPI's `vpiWaitingProcesses` (IEEE 1800-2023
    /// 37.27). Empty where the implementation tracks no sensitivity.
    fn waiting_processes(&self, _cell: StateCellId) -> Vec<ProcessId> {
        Vec::new()
    }
    fn request_finish(&self, code: i32);
    fn defer_io(&self, at: SchedTime, region: Region, cb: DeferredIoCallback);
    /// **NEW (Task 4, ledger SC-090/SC-123).** Registers `cb` to run exactly
    /// once, at the first point `region` is drained with `now >= at` (see
    /// `region_callback`'s own module doc for the `1step` placement this
    /// pins and `sched::control::Engine::drain_region_callbacks`'s doc
    /// comment for exactly when that drain happens relative to
    /// `dispatch_ready_set`). The one real production implementation is
    /// `EngineOps` (`sched/control.rs`); every other `SchedulerOps` test
    /// double in this crate implements this as a no-op, matching this
    /// trait's own established pattern for methods a given test double's
    /// own tests don't exercise.
    fn register_region_callback(&self, region: Region, at: SchedTime, cb: Box<dyn RegionCallback>);

    /// **NEW (Task 9, B-sched wave, ledger SC-125).** `disable fork;`'s
    /// scheduler-side half: recursively terminates every live descendant
    /// `proc` has spawned via `fork` (its own `fork_children`, and theirs,
    /// ...) WITHOUT suspending `proc` itself -- called mid-`resume()`,
    /// synchronously, the same call shape as the already-real
    /// [`Self::commit_blocking_write`].
    ///
    /// **Deliberately given a default (no-op) body, unlike
    /// [`Self::register_region_callback`] (Task 4), which this trait's own
    /// established pattern otherwise favors (every implementor updated
    /// exhaustively):** several of `SchedulerOps`'s other implementors live
    /// in sibling tracks' own concurrently-landing files this wave
    /// (`vj-codegen/tests/*.rs`, `vj-runtime::runtime_ctx`) that
    /// this task's own file list does not name and must not touch (this
    /// wave's binding rule 7 -- "keep edits outside sched/ and the files
    /// your plan names minimal"). The one real production override is
    /// `EngineOps` (`sched/control.rs`); every test double in this crate
    /// that does not exercise `disable fork` inherits this default,
    /// unchanged.
    fn disable_fork(&self, _proc: ProcessId) {}

    /// Starts `proc` as a process of its own in the Reactive region, with no
    /// parent: the thread LRM 1800-2023 16.11 schedules for a task a sequence
    /// match item calls ("scheduled in the Reactive region"). Deferred like
    /// [`Self::disable_fork`] (the table mutation needs `&mut Engine`); the
    /// Reactive set drains until the process, and what it wakes, has run.
    /// Default no-op: a test double that never spawns it inherits it.
    fn spawn_detached(&self, _proc: Box<dyn CompiledProcess>) {}

    /// `disable f;` executed by `proc`, a branch of the fork block `f`
    /// (LRM 1800-2023 §9.6.2): every other branch of that fork ends, with
    /// all descendants (`proc`'s own too), and the parent's join is
    /// satisfied once `proc` itself finishes -- which it does right after.
    /// Default no-op for the same reason as [`Self::disable_fork`].
    fn disable_fork_block(&self, _proc: ProcessId) {}

    /// `disable <name>;` where `<name>` is not an enclosing named block of
    /// `requester`'s own statement tree, not its own fork
    /// ([`Self::disable_fork_block`] already covers that case), and not a
    /// procedural-assertion label: a fork-spawned branch's label, reachable
    /// from `requester` because `requester` is the branch's parent, a
    /// sibling branch, or a descendant of an ancestor fork (LRM 9.6.2:
    /// disabling a named block terminates all its activity wherever it
    /// executes, including a nested fork and tasks called from it).
    /// Queues the kill of every live, currently-tagged ([`super::SpawnSpec::
    /// disable_name`]) match reachable from `requester`'s own top-level fork
    /// ancestor -- deferred exactly like [`Self::disable_fork`] (the actual
    /// table mutation cannot happen synchronously inside this `&self` call).
    /// Returns `true` iff `requester` itself is one of the matches, or
    /// descends from one (the compiled caller must leave its own kernel at
    /// once, mirroring [`Self::process_request`]'s identical `Kill` case) --
    /// `requester` is never actually killed through this call (its own CFG,
    /// via the abort flag, is what ends it; only OTHER matches/descendants
    /// are force-killed). Default false/no-op for the same reason as
    /// [`Self::disable_fork`].
    fn disable_named(&self, _requester: ProcessId, _label: &str) -> bool {
        false
    }

    /// Classes plan Task 13 (LRM 9.7): `requester` called a `process` class
    /// method that mutates `req`'s target. The request is queued and applied
    /// by the engine at the requester's next suspend (or, for `Kill`, ends the
    /// target synchronously enough that [`Self::process_state`] already
    /// reports it). Returns `true` iff the request terminates `requester`
    /// itself (it is, or descends from, the kill target) -- the caller then
    /// leaves its kernel at once. Default no-op for scheduler test doubles.
    fn process_request(&self, _requester: ProcessId, _req: ProcessRequest) -> bool {
        false
    }
    /// `p.status()` for the process `target` (LRM 9.7). A test double with no
    /// process table reports every process `Running`.
    fn process_state(&self, _target: ProcessId) -> ProcessState {
        ProcessState::Running
    }
    /// Marks `proc` as one a `process` handle exists for, so its exit is
    /// recorded (`FINISHED` vs `KILLED`) after the scheduler reclaims it.
    /// Default no-op for the same reason as [`Self::disable_fork`].
    fn process_track(&self, _proc: ProcessId) {}

    /// Resumes `proc`, a process parked with no sensitivity (an empty event
    /// list), in the current time step with `ResumeArg::EventFired { term }`.
    /// The `expect` statement's wake (LRM 1800-2023 §16.17): the assertion
    /// engine, running in the Observed region, reports the outcome and the
    /// blocked process continues in this same step. Default no-op for the
    /// same reason as [`Self::disable_fork`].
    fn wake_process(&self, _proc: ProcessId, _term: usize) {}
    /// `$monitor` (LRM 21.2.3): the cells of the active monitor's argument
    /// signals. Any value change to one of them -- even a transient one
    /// that ends where it started within the timestep -- marks the monitor
    /// changed; `SchedulerCtx::take_monitor_changed` reads-and-clears that
    /// at the end of the timestep. Replaces any previous watch set and marks
    /// changed (a new `$monitor` always prints once). Default no-op, like
    /// `disable_fork`, for scheduler test doubles.
    fn set_monitor_watch(&self, _cells: Vec<StateCellId>) {}
    /// A blocking write to one ROW of a memory (whole-array `cell`), already
    /// committed to STATE by the caller, changed the stored value: wake
    /// processes sensitive to the memory (`ops::notify_blocking_change`,
    /// any-change edge). Default no-op, like `disable_fork`, for scheduler
    /// test doubles.
    fn notify_blocking_row_change(&self, _cell: StateCellId) {}
    /// A windowed blocking commit to a huge signal (`state::huge_commit`),
    /// already stored in STATE by the caller, changed its value: wake the
    /// processes sensitive to `cell` with `edge` (the lsb edge). Default
    /// no-op, like `disable_fork`, for scheduler test doubles. `delta` is the
    /// changed plane words, present only when [`Self::wants_delta`] said a
    /// select waiter needs them.
    fn notify_blocking_wide_change(
        &self,
        _cell: StateCellId,
        _edge: EdgeKind,
        _delta: Option<crate::state::ChangeDelta>,
    ) {
    }
    /// Whether a process waits on a bit/part select of `cell`, so a windowed
    /// commit must report its changed words (see
    /// [`crate::state::ValueChangeSink::wants_delta`]). Default `false`.
    fn wants_delta(&self, _cell: StateCellId) -> bool {
        false
    }
    /// Stages a partial / memory-row nonblocking write
    /// (`nba::MaskedNbaUpdate`). The one real implementation is `EngineOps`;
    /// a test double that never compiles such a write never reaches this.
    fn stage_nba_masked(
        &self,
        cell: StateCellId,
        row: Option<u64>,
        value: FourStateValue,
        mask: Vec<u64>,
        source: ProcessId,
    ) {
        let _ = (row, value, mask, source);
        unreachable!("stage_nba_masked({cell:?}) on a SchedulerOps without an NBA log")
    }
    /// [`Self::stage_nba_masked`] for an intra-assignment-delayed
    /// nonblocking write (`q <= #d v`, LRM 1800-2023 §10.4.2): staged into
    /// the NBA log when the time step `delay` ticks from now begins, so it
    /// commits in that step's NBA region. A zero delay stages now.
    fn stage_nba_masked_delayed(
        &self,
        cell: StateCellId,
        row: Option<u64>,
        value: FourStateValue,
        mask: Vec<u64>,
        source: ProcessId,
        delay: u64,
    ) {
        let _ = (row, value, mask, source, delay);
        unreachable!("stage_nba_masked_delayed({cell:?}) on a SchedulerOps without an NBA log")
    }
    /// Stages a nonblocking write of one element of the collection whose
    /// handle `cell` (row `row`) holds (`nba::MaskedNbaUpdate::coll`),
    /// `delay` ticks from now (zero stages now).
    fn stage_nba_coll(
        &self,
        cell: StateCellId,
        row: Option<u64>,
        elem: Vec<u64>,
        coll: nba::CollWrite,
        source: ProcessId,
        delay: u64,
    ) {
        let _ = (row, elem, coll, source, delay);
        unreachable!("stage_nba_coll({cell:?}) on a SchedulerOps without an NBA log")
    }
    /// Stages a nonblocking write of class-property bits
    /// (`nba::MaskedNbaUpdate::obj`), `delay` ticks from now (zero stages now).
    fn stage_nba_obj(&self, w: nba::ObjWrite, source: ProcessId, delay: u64) {
        let _ = (w, source, delay);
        unreachable!("stage_nba_obj on a SchedulerOps without an NBA log")
    }
    /// A clocking-block synchronous drive is about to stage writes (LRM
    /// 14.16: they update in the Re-NBA region): turns the Re-NBA region on
    /// for a design with no Reactive process. Default: nothing to turn on.
    fn note_reactive_drive(&self) {}
    /// A clocking block's event was just triggered (its event counter
    /// `counter` bumped): a synchronous drive executing later in this time
    /// step is coincident with it (LRM 14.16). Default: nothing to record.
    fn note_clocking_event(&self, counter: StateCellId) {
        let _ = counter;
    }
    /// Stages a nonblocking event trigger (`->> e` / `->> #d e`, LRM
    /// 1800-2023 15.5.2): at the NBA region of the step `delay` ticks from now
    /// (a zero delay: this step) the event cell (row `row` of an event array)
    /// is triggered.
    fn stage_nba_pulse(&self, cell: StateCellId, row: Option<u64>, source: ProcessId, delay: u64) {
        let _ = (row, source, delay);
        unreachable!("stage_nba_pulse({cell:?}) on a SchedulerOps without an NBA log")
    }
    /// Stages a windowed partial write to a huge vector (`mask`/`value` span
    /// only the plane words from `window` on; see
    /// [`nba::MaskedNbaUpdate::window`]), delayed by `delay` ticks (zero
    /// stages now).
    fn stage_nba_window(
        &self,
        cell: StateCellId,
        window: u32,
        value: FourStateValue,
        mask: Vec<u64>,
        source: ProcessId,
        delay: u64,
    ) {
        let _ = (window, value, mask, source, delay);
        unreachable!("stage_nba_window({cell:?}) on a SchedulerOps without an NBA log")
    }
}

/// Reserved hook for RUNTIME's `defer_io` callback context (scheduler.md names
/// `IoCtx` as RUNTIME's concern; the concrete fields are RUNTIME's to define).
pub trait IoCtx {}

/// Codegen-supplied read-set metadata for `always_comb`/`always_latch`/
/// `always_ff` (scheduler.md `StaticSensitivity`; ledger CG-079, SC-067,
/// NL-036..NL-038, NL-045).
#[derive(Clone, Debug, Default)]
pub struct StaticSensitivity {
    pub edges: Vec<(StateCellId, Option<EdgeKind>)>,
}

/// The canonical, thread-count-independent ordering key entry (scheduler.md §6;
/// ledger SC-014, SC-029, DT-005, DT-042).
///
/// Fixed vs. scheduler.md's literal `logical_order: (SimTime, Region, u64)`
/// 3-tuple (review fix, DT-042): DT-042 itself records that scheduler.md's
/// design "describes discarding [the delta/reconvergence-iteration count]
/// once the delta loop converges, which conflicts with ARCHITECTURE §4's
/// 5-tuple key requiring it everywhere" — and per this workspace's spec
/// precedence (ARCHITECTURE.md §4 wins over docs/design/*.md), `reconv_iter`
/// must be threaded through every `PendingActivation`. Without it, two
/// activations of the same process in two different delta-loop reconvergence
/// passes at the same `(SchedTime, Region)` compared equal under the old
/// 3-tuple, collapsing a real ordering distinction DT-042/SC-013 require.
/// (The tuple's first field is now `SchedTime`, not `vj_abi::SimTime` —
/// Task 1, SC-023/SC-033/SC-129: see `SchedTime`'s own doc comment.)
/// `id` is new for the same review pass: `determinism::DeterminismController
/// ::on_read`/`on_write` and `ResolvedBatch::completed` all key on
/// `ActivationId`, but nothing previously let a `PendingActivation`/`WorkItem`
/// report which `ActivationId` it is — `id` is that missing correlation.
#[derive(Clone, Copy, Debug)]
pub struct PendingActivation {
    pub id: ActivationId,
    pub proc: ProcessId,
    pub arg: ResumeArg,
    /// The delta/reconvergence-loop iteration count within `(SchedTime, Region)`
    /// — the canonical 5-tuple's third field (ARCHITECTURE §4 item 3; DT-042).
    pub reconv_iter: u32,
    pub logical_order: (SchedTime, Region, u64),
}

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct BreakpointId(pub u32);

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct CheckpointHandle(pub u64);

/// (debugger.md `BreakCondition`; ledger CG-153, SC-096..SC-100.)
#[derive(Clone, Debug)]
pub enum BreakCondition {
    Time(SimTime),
    StmtHit {
        stmt: StmtId,
        cond: Option<PredicateFn>,
    },
    Watch {
        cell: StateCellId,
        edge: EdgeKind,
        cond: Option<PredicateFn>,
    },
    ProcessSuspend(ProcessId),
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SuspendReason {
    WaitTime,
    WaitEvent,
    WaitFork,
    Blocked,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ProcessRunState {
    Running,
    Suspended(SuspendReason),
}

#[derive(Clone, Copy, Debug)]
pub struct ProcessSnapshot {
    pub id: ProcessId,
    pub state: ProcessRunState,
    pub current: StmtId,
}

#[derive(Clone, Debug)]
pub struct KernelSnapshot {
    pub gvt: SimTime,
    pub processes: Vec<ProcessSnapshot>,
}

#[derive(Clone, Copy, Debug)]
pub struct SpeculationBound {
    /// `0` == fully conservative; the checked-in v1 default per ARCHITECTURE §4
    /// item 1 (ledger DB-033).
    pub max_lookahead_cycles: u32,
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RewindError {
    PastFossilHorizon,
    LayoutMismatch,
}

/// Implemented BY the engine (sched+determinism), called by `vj-debug`
/// (debugger.md: "Breakpoints/watchpoints are kernel-evaluated... Arming any
/// breakpoint bounds speculation to conservative for that session"; ledger
/// SC-094, SC-095, SC-097, SC-100, DB-002, DB-014, CheckpointHandle: SC-105,
/// DB-029, DB-030, DB-033, DB-046, DB-048).
pub trait KernelControl: Send {
    fn arm(&mut self, cond: BreakCondition) -> BreakpointId;
    fn disarm(&mut self, id: BreakpointId);
    fn snapshot(&self) -> KernelSnapshot;
    fn gvt(&self) -> SimTime;
    fn checkpoint(&mut self) -> CheckpointHandle;
    fn rewind(&mut self, cp: CheckpointHandle) -> Result<(), RewindError>;
    fn set_speculation_bound(&mut self, bound: SpeculationBound);
}

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

    #[test]
    fn pending_activation_logical_order_is_a_plain_copy_tuple() {
        let a = PendingActivation {
            id: 42,
            proc: 3,
            arg: ResumeArg::Start,
            reconv_iter: 0,
            logical_order: (SchedTime { ticks: 10 }, Region::Active, 7),
        };
        let b = a;
        assert_eq!(a.proc, b.proc);
        assert_eq!(a.id, b.id);
        assert_eq!(a.logical_order.2, 7);
    }

    /// Review fix: two activations of the same process at the same
    /// `(SimTime, Region)` but different delta-loop reconvergence passes must
    /// be distinguishable — this is the whole point of DT-042's `reconv_iter`.
    #[test]
    fn reconv_iter_distinguishes_same_process_same_tick_different_passes() {
        let base = SchedTime { ticks: 10 };
        let pass0 = PendingActivation {
            id: 1,
            proc: 3,
            arg: ResumeArg::TimeElapsed,
            reconv_iter: 0,
            logical_order: (base, Region::Active, 7),
        };
        let pass1 = PendingActivation {
            reconv_iter: 1,
            ..pass0
        };
        assert_eq!(pass0.logical_order, pass1.logical_order);
        assert_ne!(
            pass0.reconv_iter, pass1.reconv_iter,
            "same 3-tuple logical_order must still be distinguishable via reconv_iter"
        );
    }

    // --- Task 1 (SC-016, SC-023, SC-033, SC-064, SC-117, SC-129) ---

    #[test]
    fn sched_time_has_no_delta_field_and_is_integer_only() {
        let t = SchedTime { ticks: 10 };
        let t2 = SchedTime { ticks: t.ticks + 5 };
        assert_eq!(t2.ticks, 15);
        assert_eq!(core::mem::size_of::<SchedTime>(), 8);
    }

    #[test]
    fn sched_time_to_abi_display_only_populates_delta_from_the_given_counter() {
        let t = SchedTime { ticks: 7 };
        let a = t.to_abi_display(3);
        assert_eq!(
            a,
            vj_abi::SimTime {
                sim_units: 7,
                delta: 3,
            }
        );
        let b = t.to_abi_display(9);
        assert_eq!(a.sim_units, b.sim_units);
        assert_ne!(
            a.delta, b.delta,
            "delta must come from the caller's counter, not be derived from ticks"
        );
    }

    #[test]
    fn pending_activation_logical_order_uses_sched_time_not_abi_simtime() {
        let a = PendingActivation {
            id: 1,
            proc: 0,
            arg: ResumeArg::Start,
            reconv_iter: 0,
            logical_order: (SchedTime { ticks: 1 }, Region::Active, 0),
        };
        assert_eq!(a.logical_order.0.ticks, 1);
    }

    /// sva T1 (§1.4, review fix, blocking finding 2): was
    /// `region_has_exactly_five_variants_no_preponed_observed_re_inactive_re_nba`
    /// -- `Preponed` is now a real, additive 6th variant (`Observed`/
    /// `Re-Inactive`/`Re-NBA` stay unimplemented).
    ///
    /// sva T2: renamed again -- `Observed` is now a real, additive 7th
    /// variant too (`Re-Inactive`/`Re-NBA` stay unimplemented per §1.4's own
    /// documented simplification).
    #[test]
    fn region_has_exactly_seven_variants_preponed_and_observed_added_re_inactive_re_nba_still_not()
    {
        let all = [
            Region::Active,
            Region::Inactive,
            Region::Nba,
            Region::Reactive,
            Region::Postponed,
            Region::Preponed,
            Region::Observed,
        ];
        for r in all {
            let _ = region_ordinal(r);
        }
        assert_eq!(all.len(), 7);
    }

    #[test]
    fn region_ordinal_matches_discriminant_for_every_variant() {
        for r in [
            Region::Active,
            Region::Inactive,
            Region::Nba,
            Region::Reactive,
            Region::Postponed,
            Region::Preponed,
            Region::Observed,
        ] {
            assert_eq!(region_ordinal(r), r as u32);
        }
    }

    #[test]
    fn sc064_type_aliases_have_exact_underlying_representations() {
        assert_eq!(core::mem::size_of::<SimTick>(), 8);
        assert_eq!(core::mem::size_of::<ProcessId>(), 4);
        assert_eq!(core::mem::size_of::<ActivationId>(), 8);
        assert_eq!(core::mem::size_of::<crate::state::StateCellId>(), 8);
        assert_eq!(crate::state::StateCellId(42).0, 42);
    }

    // --- Task 8 (SC-127: DPI-imported-task suspend-point ABI proof) ---

    /// SC-127's scheduler-side half: proves, constructively, that
    /// `CompiledProcess::resume`'s ABI imposes no structural restriction on
    /// *where* a `Suspend` value is constructed — a DPI-imported-task
    /// callback that blocks by calling back into SV is representable today
    /// with zero scheduler-side special-casing. `DpiCallbackWaiter::resume`
    /// stands in for "control has been handed to a foreign DPI-imported
    /// task, which itself calls back into blocking SV": it returns
    /// `Suspend::Delay(5)` from three stack frames deep inside ordinary Rust
    /// helper calls, never directly from `resume`'s own top-level match arm
    /// (the scheduler ABI is agnostic to *where* in Rust call-stack terms a
    /// `Suspend` value was constructed — it only ever sees the returned
    /// value). Drives this through the real `Engine`/`SchedulerControl`/
    /// `ResumeDriver` dispatch loop, using zero DPI-specific engine API
    /// (there is none), and asserts it dispatches and completes exactly like
    /// any other delay-suspending process. Fails if a future change ever
    /// special-cases suspend-point construction by call-stack shape (e.g.
    /// panicking, dropping the suspend, or resuming with a different
    /// `ResumeArg`), which would be exactly the "silently mis-scheduling"
    /// failure SC-127's own acceptance clause (b) warns against for anything
    /// that does not take option (a) explicitly.
    #[test]
    fn sc127_a_mock_process_may_suspend_from_a_point_that_stands_in_for_a_dpi_imported_task_callback()
     {
        struct NoopArena;
        impl crate::state::SignalAccess for NoopArena {
            fn read(&self, _cell: crate::state::StateCellId) -> FourStateValue {
                FourStateValue::Narrow(0)
            }
            fn write(&mut self, _cell: crate::state::StateCellId, _value: FourStateValue) -> bool {
                false
            }
            fn subscribe(
                &mut self,
                _cell: crate::state::StateCellId,
                _role: crate::state::ListenerRole,
                _sink: Box<dyn crate::state::ValueChangeSink + Send>,
            ) {
            }
        }

        struct NoopIoSink;
        impl IoSink for NoopIoSink {
            fn enqueue(&self, _at: SchedTime, _region: Region, _seq: u64, _cb: DeferredIoCallback) {
            }
        }

        // Three stack frames deep -- the suspend point is nowhere near
        // `resume`'s own top-level match arm, standing in for control having
        // passed through a foreign (DPI) call stack before a callback into
        // blocking SV constructs the `Suspend` value.
        fn dpi_frame_3(delay: u64) -> Suspend {
            Suspend::Delay(delay)
        }
        fn dpi_frame_2(delay: u64) -> Suspend {
            dpi_frame_3(delay)
        }
        fn dpi_frame_1(delay: u64) -> Suspend {
            dpi_frame_2(delay)
        }

        struct DpiCallbackWaiter {
            log: std::sync::Arc<std::sync::Mutex<Vec<ResumeArg>>>,
        }
        impl CompiledProcess for DpiCallbackWaiter {
            fn resume(
                &mut self,
                _state: SimHandle,
                arg: ResumeArg,
                _ops: &dyn SchedulerOps,
            ) -> Suspend {
                self.log.lock().unwrap().push(arg);
                match arg {
                    ResumeArg::Start => dpi_frame_1(5),
                    _ => Suspend::Done,
                }
            }
        }

        let log = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let mut engine = Engine::new(Box::new(NoopArena), Box::new(NoopIoSink));
        engine.register_process(
            Box::new(DpiCallbackWaiter { log: log.clone() }),
            ProcessKind::Initial,
            None,
            0,
        );

        let result = engine.run_until(None);

        assert!(
            matches!(result, RunResult::Completed),
            "a delay suspended from deep inside a DPI-callback-shaped call stack must \
             still let the run reach quiescence like any other process, got {:?}",
            result
        );
        assert_eq!(engine.now(), SchedTime { ticks: 5 });
        let log = log.lock().unwrap();
        assert_eq!(
            log.len(),
            2,
            "must resume exactly twice: Start (which suspends via the DPI-shaped \
             callback) and TimeElapsed (which completes)"
        );
        assert!(matches!(log[0], ResumeArg::Start));
        assert!(
            matches!(log[1], ResumeArg::TimeElapsed),
            "the deeply-nested Suspend::Delay(5) must resume the process via an \
             ordinary TimeElapsed wakeup -- no DPI-specific ResumeArg variant exists \
             or is needed"
        );
    }

    // --- Task 8 (AB-085) ---

    /// Type-level check only, NOT proof of AB-085's dispatch-delegation
    /// claim: this asserts that `Suspend::WaitForGvt` needs no more than a
    /// label in a plain, single-depth `match` -- i.e. it fits the enum's
    /// existing shape rather than requiring a new variant-specific branch
    /// structure -- and, because the `label` match below has no wildcard
    /// arm, that a new `Suspend` variant added later without updating every
    /// such match is a compile error, not a silently-passing gate. It does
    /// NOT exercise `sched::control::Engine::apply_suspend` and so proves
    /// nothing about whether `WaitForGvt` actually delegates to the
    /// `Delay(0)` code path at runtime; that behavioral claim is covered by
    /// `apply_suspend_wait_for_gvt_delegates_to_the_same_path_as_delay_zero`
    /// in `sched::control`'s test module, which drives a real process
    /// through the real `Engine` and compares the observed outcome against
    /// `Delay(0)`'s.
    #[test]
    fn wait_for_gvt_fits_the_suspend_enums_existing_match_shape() {
        fn label(s: &Suspend) -> &'static str {
            match s {
                Suspend::Delay(_) => "delay",
                Suspend::WaitEvents(_) => "wait_events",
                Suspend::ForkJoin(_, _) => "fork_join",
                Suspend::WaitFork => "wait_fork",
                Suspend::WaitOrder(_) => "wait_order",
                Suspend::WaitForGvt => "wait_for_gvt",
                Suspend::ByRequest => "by_request",
                Suspend::Done => "done",
            }
        }

        assert_eq!(label(&Suspend::WaitForGvt), "wait_for_gvt");
        // The other variants still label correctly through the same match --
        // proving WaitForGvt didn't need a different match shape.
        assert_eq!(label(&Suspend::Delay(0)), "delay");
        assert_eq!(
            label(&Suspend::WaitEvents(EventWaitSet::default())),
            "wait_events"
        );
        assert_eq!(
            label(&Suspend::ForkJoin(JoinKind::All, Vec::new())),
            "fork_join"
        );
        assert_eq!(label(&Suspend::WaitFork), "wait_fork");
        assert_eq!(label(&Suspend::WaitOrder(Vec::new())), "wait_order");
        assert_eq!(label(&Suspend::Done), "done");
    }
}