Skip to main content

hydro_lang/sim/
compiled.rs

1//! Interfaces for compiled Hydro simulators and concrete simulation instances.
2//!
3//! # Quiescence and observation soundness
4//!
5//! The scheduler distinguishes two kinds of simulation work:
6//! - **Deterministic work**: running the top-level async dataflows, which simply propagate
7//!   whatever data is already in flight. This makes no `nondet!` decisions, so running it can
8//!   never change which executions are explored.
9//! - **Nondeterministic work**: running ticks and observations, whose behavior depends on
10//!   decisions drawn from the bolero driver (batch boundaries, snapshot versions, message
11//!   orderings). Each decision forks the space of possible executions.
12//!
13//! The simulation is **quiescent** when neither kind of work can make progress without new
14//! external input. Test-side observations (the methods on [`SimReceiver`] /
15//! [`SimClusterReceiver`]) interact with the scheduler while waiting, and the key soundness
16//! question is: *when is it okay for an observation to let nondeterministic work run?*
17//!
18//! **Waiting for a message is always sound.** If the message eventually arrives, the work
19//! that ran was necessary to produce it (schedules that run *extra* work are also valid
20//! executions and are explored separately). If the simulation instead quiesces without
21//! producing the message, the assertion fails and the instance ends, so nothing can observe
22//! the overrun. This is why [`SimReceiver::next`], [`SimReceiver::collect_n`], and the
23//! `assert_yields*` prefix checks are safe to use in the middle of a test.
24//!
25//! **Observing the *absence* of a message is dangerous.** Proving that "no more messages can
26//! arrive" requires driving the simulation all the way to quiescence, running *all* pending
27//! nondeterministic work. A later assertion may have needed to observe a state where that
28//! work had not yet run — e.g., `assert_yields_only([1, 2])` followed by reading a counter
29//! must be able to see the counter *before* the ticks that count `1` and `2` have fired.
30//! Forcing quiescence at the first assertion would make some executions unobservable, and
31//! extra messages produced by the forced work could surface at a *later* assertion,
32//! misattributing the failure. Absence-observing APIs therefore proceed in phases:
33//!
34//! 1. **Settle** (see `SettlePauseGuard::poll_settle`): the scheduler runs only deterministic work, pausing
35//!    just before nondeterministic work. If the simulation reaches quiescence this way, the
36//!    end-of-stream check is *free* — no decision was forced, no execution was cut off — and
37//!    the test simply continues.
38//! 2. If nondeterministic work is pending, the check would overrun. What happens next depends
39//!    on the API and engine:
40//!    - The assertion APIs ([`SimReceiver::assert_no_more`], `assert_yields_only*`,
41//!      `collect_n_only`) under [`CompiledSim::exhaustive`] **fork** the search on a bolero
42//!      decision: one instance performs the check and then ends (via a discard panic, like
43//!      `sim::continue_if!`), while sibling instances skip the check entirely and continue. The
44//!      exhaustive driver enumerates the checking instance *first*, so a failing check is
45//!      found before any instance runs past it — with a decision trace that leads exactly to
46//!      the failing assertion. Since nothing after the check runs in the checking instance,
47//!      the overrun it performs is unobservable, and the continuing instances never quiesce,
48//!      so every downstream state remains reachable.
49//!    - Otherwise (fuzz / RNG / replay engines, or the drain-everything APIs
50//!      [`SimReceiver::try_next`], [`SimReceiver::collect`], and `collect_sorted` in every
51//!      mode), the pending work runs and the instance is **tainted**
52//!      (`QuiescenceState::tainted`). Reads of the now-quiescent state remain sound (they
53//!      observe a fully-drained simulation that can no longer advance), so tests may drain
54//!      multiple output ports at the end. But once new input is sent, the instance is
55//!      **poisoned** (`QuiescenceState::poisoned`): any further receive panics (see
56//!      `guard_not_poisoned`), because a failure observed after the forced overrun could
57//!      have been caused by it and attributed to the wrong assertion.
58//!
59//! NOTE: This module runs inside bolero's `catch_unwind` scope, which silently
60//! swallows panics. Internal invariant checks should use `abort_assert!`
61//! rather than `panic!`/`assert!`.
62//!
63//! Panics inside the tick DFIR (generated code in the dylib) are caught in the dylib and raised
64//! again on the host as ordinary panics (see `sim::panic_guard`), so they reach bolero's
65//! `catch_unwind` like panics in the test body.
66
67/// Like `assert!`, but calls `std::process::abort()` instead of `panic!()`.
68/// Use for internal invariants that must not be silently caught by bolero.
69macro_rules! abort_assert {
70    ($cond:expr, $($arg:tt)*) => {
71        if !$cond {
72            eprintln!("Simulator internal error: {}", format!($($arg)*));
73            std::process::abort();
74        }
75    };
76}
77
78use core::{fmt, panic};
79use std::cell::{Cell, RefCell};
80use std::collections::{HashMap, VecDeque};
81use std::fmt::Debug;
82use std::panic::{Location, RefUnwindSafe};
83use std::path::{Path, PathBuf};
84use std::pin::{Pin, pin};
85use std::rc::Rc;
86use std::task::{Poll, ready};
87
88use bytes::Bytes;
89use colored::Colorize;
90use dfir_rs::scheduled::context::DfirErased;
91use dfir_rs::util::unsync::mpsc::{Receiver as UnsyncReceiver, Sender as UnsyncSender};
92use futures::StreamExt;
93use libloading::Library;
94use tokio::sync::{Mutex, Notify};
95
96use super::runtime::{
97    Hooks, InlineHooks, ObservationHooks, RetryBudget, ScriptTarget, ScriptedHookControl,
98    ScriptedHookRegistry, ScriptedInlineHooks, ScriptedObservationHooks, ScriptedTickHooks,
99    SimLocation,
100};
101use super::{SimClusterReceiver, SimClusterSender, SimReceiver, SimSender};
102use crate::compile::builder::ExternalPortId;
103use crate::live_collections::stream::{ExactlyOnce, NoOrder, Ordering, Retries, TotalOrder};
104use crate::location::dynamic::LocationId;
105use crate::sim::graph::{SimExternalPort, SimExternalPortRegistry};
106use crate::sim::runtime::{
107    InlineHook, ObservationHook, ScriptedObservationHook, ScriptedTickInputHook, TickInputHook,
108};
109
110struct QuiescenceState {
111    /// Set to true when the scheduler reaches quiescence; reset to false when new input is sent.
112    quiescent: Cell<bool>,
113    /// Notified when the scheduler reaches quiescence (wakes receivers waiting for data).
114    quiescence_notify: Notify,
115    /// Notified when new input is sent, signaling the scheduler to resume.
116    resume_notify: Notify,
117    /// When nonzero, the scheduler must not start nondeterministic work (ticks /
118    /// observations): once only such work remains, it sets `nondet_pending` and pauses until
119    /// resumed. Used by receivers to query whether the simulation can quiesce
120    /// deterministically. This is a count (not a bool) because multiple settling futures can
121    /// be in flight at once (e.g. `select!`/`join!` between two receiver awaits): the
122    /// scheduler must stay paused until *every* one of them has finished settling.
123    pause_nondet: Cell<usize>,
124    /// Set while the scheduler is paused because nondeterministic work is ready to run but
125    /// `pause_nondet` is set.
126    nondet_pending: Cell<bool>,
127    /// Wakers for test-side tasks waiting for the scheduler to settle (either quiesce or set
128    /// `nondet_pending`) while `pause_nondet` is set. Also used by scripting futures that
129    /// need to be woken when the scheduler parks.
130    settle_wakers: RefCell<Vec<std::task::Waker>>,
131    /// Set when an observation *forced* the simulation to quiesce (running pending
132    /// nondeterministic work) outside of exhaustive mode's forking. Further observations of
133    /// the quiescent state remain sound, but once new input is sent (see `poisoned`), later
134    /// observations could misattribute failures caused by the forced overrun.
135    tainted: Cell<bool>,
136    /// Set when new input is sent after `tainted`; all further receives panic.
137    poisoned: Cell<bool>,
138}
139
140impl QuiescenceState {
141    /// Signal that new input has been sent, waking the scheduler if it was quiescent.
142    fn resume(&self) {
143        if self.tainted.get() {
144            self.poisoned.set(true);
145        }
146        self.quiescent.set(false);
147        // `notify_one` (rather than `notify_waiters`) stores a permit if the scheduler driver
148        // is not currently parked on [`Self::resumed`], so a resume that fires before the
149        // driver parks (e.g. input sent while the driver is polling the thunk) is not lost.
150        self.resume_notify.notify_one();
151    }
152
153    /// Whether the scheduler is currently quiescent (no more progress possible without input).
154    fn is_quiescent(&self) -> bool {
155        self.quiescent.get()
156    }
157
158    /// Returns a future that completes when the scheduler next reaches quiescence.
159    fn notified(&self) -> tokio::sync::futures::Notified<'_> {
160        self.quiescence_notify.notified()
161    }
162
163    /// Wakes test-side tasks waiting for the scheduler to settle.
164    fn wake_settled(&self) {
165        for waker in self.settle_wakers.borrow_mut().drain(..) {
166            waker.wake();
167        }
168    }
169
170    /// Enter quiescence, waking receivers waiting for data (their streams end). The scheduler
171    /// driver is responsible for parking until [`Self::resume`] is called with new input.
172    fn enter_quiescence(&self) {
173        self.quiescent.set(true);
174        self.quiescence_notify.notify_waiters();
175        self.wake_settled();
176    }
177
178    /// Completes when new input arrives (via [`Self::resume`]).
179    async fn resumed(&self) {
180        self.resume_notify.notified().await;
181    }
182
183    /// Registers a waker to be woken the next time the scheduler parks (quiescence or
184    /// settle-pause). Used by scripting futures: while the scheduler is running, the test
185    /// body is re-polled after every step anyway, so a waker is only needed for the parked
186    /// cases. Duplicate registrations are harmless.
187    fn push_park_waker(&self, waker: &std::task::Waker) {
188        self.settle_wakers.borrow_mut().push(waker.clone());
189    }
190}
191
192/// The **current group** of scripted decisions: consecutive decision calls in the test body
193/// that target different hooks of the same tick form a group, describing one execution of
194/// that tick. At most one group's decisions are ever installed at a time; the first decision
195/// call of the *next* group suspends until the current group's tick execution has consumed
196/// every installed decision.
197pub(crate) struct CurrentGroup {
198    /// The scheduler action the group's decisions apply to.
199    target: ScriptTarget,
200    /// The registry keys (handle ID plus cluster member) with an installed decision in
201    /// this group.
202    members: Vec<(usize, Option<u32>)>,
203    /// Set when the scheduler starts a step. Until then, consecutive decisions for different
204    /// hooks of this tick may join the group in the same poll of the test body.
205    sealed: bool,
206}
207
208/// Coordinates the script protocol between test-side hook handles and the scheduler.
209#[derive(Default)]
210pub(crate) struct ScriptCoordinator {
211    /// `Some` means exactly one decision group is outstanding. The scheduler clears it only
212    /// after that group's tick executes, so the test cannot replace an unconsumed group.
213    current: Option<CurrentGroup>,
214    /// Set by the scheduler at each quiescence: `true` when the outstanding group is stuck
215    /// even though every queued decision is satisfiable, because none of them can trigger
216    /// the tick (and no unscripted input on the tick can trigger it either — otherwise the
217    /// tick would be runnable and the simulation would not be quiescent). Selects the
218    /// stuck-script error style rendered at the suspended test-side await; `false` means
219    /// some decision is waiting on input that can never arrive.
220    stuck_cannot_trigger: bool,
221}
222
223impl ScriptCoordinator {
224    /// Describes the not-yet-consumed decisions of the current group, one per line
225    /// (without a trailing newline), for error messages. `None` when no group is
226    /// outstanding or every decision is consumed.
227    fn describe_unconsumed(&self, hooks: &ScriptedHookRegistry) -> Option<String> {
228        let group = self.current.as_ref()?;
229        let mut out = String::new();
230        for key in &group.members {
231            let hook = hooks.get(key).unwrap().borrow();
232            if let Some(decision) = hook.describe_decision() {
233                use std::fmt::Write;
234                if !out.is_empty() {
235                    out.push('\n');
236                }
237                let member = key
238                    .1
239                    .map(|m| format!(" (cluster member {m})"))
240                    .unwrap_or_default();
241                write!(
242                    out,
243                    "  {} is waiting on the hook at {}{}, which has {}",
244                    decision,
245                    hook.location_meta().location,
246                    member,
247                    hook.describe_pending()
248                        .as_deref()
249                        .unwrap_or("no pending input"),
250                )
251                .unwrap();
252            }
253        }
254        (!out.is_empty()).then_some(out)
255    }
256}
257
258/// The per-instance scripting context, resolved through the task-local sim connections.
259///
260/// The three `Rc`s are genuinely distinct (not one shared allocation) because they have
261/// different owners and lifetimes: the hook registry only materializes when the dylib is
262/// launched (it is part of the `DylibResult`), while the coordinator and quiescence
263/// state live in the pre-launch `SimConnections` and are independently shared with
264/// receivers and test-side handles (quiescence is also used by non-scripting paths).
265/// This struct is the bundle of all three, assembled by-clone at resolution time.
266pub(crate) struct ScriptCtx {
267    hooks: Rc<ScriptedHookRegistry>,
268    coordinator: Rc<RefCell<ScriptCoordinator>>,
269    quiescence: Rc<QuiescenceState>,
270}
271
272/// The result of attempting to schedule one decision; see
273/// [`ScriptCtx::try_schedule_decision`].
274pub(crate) enum ScheduleDecision {
275    /// The decision was installed into the current group.
276    Installed,
277    /// The previous group has not been consumed yet; the decision blob is handed back and
278    /// the caller should retry after the scheduler makes progress.
279    Wait(Vec<u8>),
280}
281
282const UNBOUND_HOOK_ERROR: &str = "this sim hook handle is not bound to any operator in the simulated flow; \
283     attach it with `nondet!(... hook = handle)` at the operator it should control";
284
285impl ScriptCtx {
286    /// Resolves a hook handle's scripted hook instance; `member` selects a cluster
287    /// member's instance (`None` for hooks on processes). Panics if the handle is not
288    /// bound to an operator or the member does not exist.
289    #[track_caller]
290    pub(crate) fn control(
291        &self,
292        hook_id: usize,
293        member: Option<u32>,
294    ) -> Rc<RefCell<dyn ScriptedHookControl>> {
295        if let Some(hook) = self.hooks.get(&(hook_id, member)) {
296            return hook.clone();
297        }
298
299        // The exact instance is missing; distinguish the misuse cases from a handle
300        // that was never bound at all.
301        let bound_members: Vec<u32> = self
302            .hooks
303            .range((hook_id, None)..=(hook_id, Some(u32::MAX)))
304            .filter_map(|((_, m), _)| *m)
305            .collect();
306        match member {
307            None if !bound_members.is_empty() => panic!(
308                "this sim hook handle is bound to an operator running on a cluster, where every member has its own independent instance to script; \
309                 select one with `.on(member_id)` (members: {:?})",
310                bound_members
311            ),
312            Some(m) if self.hooks.contains_key(&(hook_id, None)) => panic!(
313                "`.on({m})` was used on a sim hook handle bound to an operator running on a process, which has no cluster members; \
314                 script the handle without `.on(..)`"
315            ),
316            Some(m) if !bound_members.is_empty() => panic!(
317                "`.on({m})` does not name a member of the cluster this sim hook handle is bound to (members: {:?})",
318                bound_members
319            ),
320            _ => panic!("{}", UNBOUND_HOOK_ERROR),
321        }
322    }
323
324    /// Whether the simulation is currently quiescent (no more progress possible).
325    pub(crate) fn is_quiescent(&self) -> bool {
326        self.quiescence.is_quiescent()
327    }
328
329    /// See [`QuiescenceState::push_park_waker`].
330    pub(crate) fn push_park_waker(&self, waker: &std::task::Waker) {
331        self.quiescence.push_park_waker(waker);
332    }
333
334    /// Attempts to install a decision (MessagePack-serialized; the handle and hook statically
335    /// know the matching type) for the hook instance `(hook_id, member)` under the group
336    /// protocol: join the current group if this decision belongs to it, open a new group
337    /// if the previous one has been consumed, or hand the decision back to be retried
338    /// once the previous group's tick execution has happened. Each cluster member's tick
339    /// is its own scheduler action, so decisions for different members never share a
340    /// group.
341    #[track_caller]
342    pub(crate) fn try_schedule_decision(
343        &self,
344        hook_id: usize,
345        member: Option<u32>,
346        decision_blob: Vec<u8>,
347    ) -> Result<ScheduleDecision, String> {
348        let key = (hook_id, member);
349        let hook = self.control(hook_id, member);
350        let target = hook.borrow().target();
351
352        let mut coordinator = self.coordinator.borrow_mut();
353
354        enum Action {
355            Join,
356            NewGroup,
357            Wait,
358        }
359
360        let action = match &coordinator.current {
361            None => Action::NewGroup,
362            Some(group)
363                if !group.sealed
364                    && matches!(target, ScriptTarget::Tick { .. })
365                    && group.target == target
366                    && !group.members.contains(&key) =>
367            {
368                Action::Join
369            }
370            Some(_) => Action::Wait,
371        };
372
373        match action {
374            Action::Join => {
375                coordinator.current.as_mut().unwrap().members.push(key);
376            }
377            Action::NewGroup => {
378                coordinator.current = Some(CurrentGroup {
379                    target,
380                    members: vec![key],
381                    sealed: false,
382                });
383            }
384            Action::Wait => {
385                // The previous group's execution hasn't happened yet; hand the decision
386                // back to be retried. The waiting hook stays subject to the boundary scan:
387                // buffered input held across this wait must be declared with an explicit
388                // pause (the waiting decision names a *later* execution).
389                if self.quiescence.is_quiescent() {
390                    let stuck = coordinator.describe_unconsumed(&self.hooks);
391                    let stuck = stuck.as_deref().unwrap_or("  (unknown decision)");
392                    let header = if coordinator.stuck_cannot_trigger {
393                        "a previously scripted decision group can never run: none of its tick's hooks can trigger it (no scripted decision triggers, and no unscripted input has data)"
394                    } else {
395                        "a previously scripted decision can never be satisfied (the simulation has no more work it can do)"
396                    };
397                    return Err(format!("cannot script this decision: {header}:\n{stuck}"));
398                }
399                return Ok(ScheduleDecision::Wait(decision_blob));
400            }
401        }
402        drop(coordinator);
403
404        hook.borrow_mut().install_decision(&decision_blob);
405        // Installing a decision can make a tick runnable; wake the scheduler if parked.
406        self.quiescence.resume();
407        Ok(ScheduleDecision::Installed)
408    }
409}
410
411/// Resolves the per-instance scripting context. Panics if called outside a simulation.
412pub(crate) fn script_ctx() -> ScriptCtx {
413    CURRENT_SIM_CONNECTIONS.with(|connections| {
414        let connections = connections.borrow();
415        ScriptCtx {
416            hooks: connections.scripted_hooks.clone(),
417            coordinator: connections.script_coordinator.clone(),
418            quiescence: connections.quiescence.clone(),
419        }
420    })
421}
422
423/// Renders the stuck-script error for a quiescent simulation with an outstanding group.
424/// Two distinct failure styles: a decision that is *unsatisfiable* (waiting on input that
425/// can never arrive), vs decisions that are all satisfiable but *cannot trigger* their
426/// tick (none of them triggers, and no unscripted input on the tick has data).
427fn render_stuck_script_error(cannot_trigger: bool, stuck: &str) -> String {
428    if cannot_trigger {
429        format!(
430            "the simulation has stopped, but scripted decisions are still pending: none of the tick's hooks can trigger it (no scripted decision triggers, and no unscripted input has data):\n{stuck}\nhelp: script a decision that triggers the tick, or drive an unscripted input, so the tick can run"
431        )
432    } else {
433        format!("a scripted decision can never be satisfied:\n{stuck}")
434    }
435}
436
437/// Renders the stuck-script error for the current instance (see
438/// [`render_stuck_script_error`]); the scheduler classified the failure style when it
439/// reached quiescence.
440pub(crate) fn script_stuck_error(stuck: &str) -> String {
441    let cannot_trigger = CURRENT_SIM_CONNECTIONS.with(|connections| {
442        let connections = connections.borrow();
443        let coordinator = connections.script_coordinator.borrow();
444        coordinator.stuck_cannot_trigger
445    });
446    render_stuck_script_error(cannot_trigger, stuck)
447}
448
449/// If a scripted group is outstanding, returns a description of its decisions (used by
450/// output awaits and `pause_until` waits, which are script barriers: they must not
451/// resolve until every decision scripted so far has run).
452pub(crate) fn script_unconsumed_description() -> Option<String> {
453    CURRENT_SIM_CONNECTIONS.with(|connections| {
454        let connections = connections.borrow();
455        let coordinator = connections.script_coordinator.borrow();
456        coordinator.current.as_ref()?;
457        Some(
458            coordinator
459                .describe_unconsumed(&connections.scripted_hooks)
460                .unwrap_or_else(|| "  (unknown decision)".to_owned()),
461        )
462    })
463}
464
465/// Tracks a pending "settle" pause request to the scheduler (see
466/// [`QuiescenceState::pause_nondet`]), releasing it if the requesting future is dropped
467/// mid-settle (e.g. by `select!`) so the scheduler is not left paused forever. Pause
468/// requests are counted, so concurrent settling futures each hold their own request.
469struct SettlePauseGuard {
470    quiescence: Rc<QuiescenceState>,
471    active: bool,
472}
473
474impl SettlePauseGuard {
475    fn new(quiescence: Rc<QuiescenceState>) -> Self {
476        SettlePauseGuard {
477            quiescence,
478            active: false,
479        }
480    }
481
482    fn acquire(&mut self) {
483        abort_assert!(!self.active, "settle pause acquired twice");
484        self.quiescence
485            .pause_nondet
486            .set(self.quiescence.pause_nondet.get() + 1);
487        self.active = true;
488    }
489
490    fn release(&mut self) {
491        abort_assert!(self.active, "settle pause released without being acquired");
492        self.active = false;
493        self.quiescence
494            .pause_nondet
495            .set(self.quiescence.pause_nondet.get() - 1);
496    }
497
498    /// Polls the "settle" handshake with the scheduler: deterministic (non-tick) work is
499    /// allowed to run, but the scheduler pauses instead of starting nondeterministic work
500    /// (ticks / observations). Resolves to `true` if the simulation reached quiescence
501    /// deterministically, or `false` if nondeterministic work is pending (in which case the
502    /// scheduler is resumed).
503    fn poll_settle(&mut self, cx: &mut std::task::Context<'_>) -> Poll<bool> {
504        let quiescence = self.quiescence.clone();
505        if !self.active {
506            if quiescence.is_quiescent() {
507                return Poll::Ready(true);
508            }
509            self.acquire();
510        }
511
512        if quiescence.is_quiescent() {
513            self.release();
514            Poll::Ready(true)
515        } else if quiescence.nondet_pending.get() {
516            self.release();
517            // `notify_one` (permit-based): the driver only parks *between* thunk polls, so it
518            // is not parked right now — the permit ensures this resume is not lost.
519            quiescence.resume_notify.notify_one();
520            Poll::Ready(false)
521        } else {
522            // This may push a duplicate waker if we are re-polled without an intervening
523            // `wake_settled` (e.g. a `join!` sibling waking the shared task), but duplicates
524            // are harmless (waking is idempotent) and are cleared at the next `wake_settled`,
525            // so deduplicating here isn't worth the scan on every poll.
526            quiescence
527                .settle_wakers
528                .borrow_mut()
529                .push(cx.waker().clone());
530            Poll::Pending
531        }
532    }
533}
534
535impl Drop for SettlePauseGuard {
536    fn drop(&mut self) {
537        if self.active {
538            self.release();
539            // Resume the scheduler in case this was the last pause request (otherwise it
540            // would stay parked forever with nobody left to resume it). `notify_one`
541            // (permit-based) so the resume is not lost if the driver has not parked yet. If
542            // other settlers still hold requests, this wakeup is spurious but harmless: the
543            // scheduler re-checks `pause_nondet > 0` before starting any nondeterministic
544            // work, so it immediately re-parks without running anything.
545            self.quiescence.resume_notify.notify_one();
546        }
547    }
548}
549
550/// Panics if the simulation has been poisoned: an earlier observation forced the simulation
551/// to quiesce (running pending nondeterministic work), and new input has been sent since, so
552/// further observations could misattribute failures caused by the forced overrun.
553fn guard_not_poisoned(quiescence: &QuiescenceState) {
554    assert!(
555        !quiescence.poisoned.get(),
556        "cannot receive more simulator output: an earlier observation (such as `try_next`, `collect`, or a quiescence assertion outside exhaustive mode) forced the simulation to quiesce by running pending nondeterministic work, and new input has been sent since. Failures observed now could be misattributed, so either restructure the test to make quiescence-forcing observations its last step, or insert an explicit `sim::quiesce().await` phase barrier before sending more input."
557    );
558}
559
560/// Runs the simulation to quiescence, as an explicit *phase barrier* between rounds of a
561/// multi-phase test.
562///
563/// All pending nondeterministic work (ticks / observations) is forced to run until no more
564/// progress is possible without new input. This deliberately narrows the explored executions:
565/// inputs sent after the barrier will never interleave with work from before it, modeling
566/// scenarios where new stimuli (such as timer ticks) arrive long after the system settles.
567/// Pair such tests with a separate barrier-free test if interleaved executions should also be
568/// explored.
569///
570/// Because the barrier is explicit, observations after it are *intended* to see the fully
571/// settled state, so — unlike [`SimReceiver::try_next`] / [`SimReceiver::collect`] forcing
572/// quiescence implicitly — it does not restrict what the test may do afterwards: receives
573/// after the barrier observe only buffered output (plus whatever later input produces), and
574/// failures cannot be misattributed across it.
575pub async fn quiesce() {
576    let quiescence =
577        CURRENT_SIM_CONNECTIONS.with(|connections| connections.borrow().quiescence.clone());
578    guard_not_poisoned(&quiescence);
579
580    let mut notified_fut = pin!(None);
581    std::future::poll_fn(|cx| {
582        if quiescence.is_quiescent() {
583            // A stuck scripted decision makes this a *dirty* quiescence: report it here
584            // rather than letting the barrier silently pass.
585            if let Some(stuck) = script_unconsumed_description() {
586                panic!("{}", script_stuck_error(&stuck));
587            }
588            return Poll::Ready(());
589        }
590        // Registered before the scheduler can run (single-threaded), so the quiescence
591        // notification cannot be missed.
592        if notified_fut.is_none() {
593            notified_fut.set(Some(quiescence.notified()));
594        }
595        let () = ready!(notified_fut.as_mut().as_pin_mut().unwrap().poll(cx));
596        Poll::Ready(())
597    })
598    .await;
599
600    // The barrier subsumes any quiescence forced by earlier observations in this phase:
601    // everything before it has fully settled, and the test has explicitly opted into
602    // observing only post-quiescence states from here on.
603    quiescence.tainted.set(false);
604}
605
606/// Receives the next message from `receiver` while trying not to overrun the simulation:
607/// first the simulation *settles* (deterministic work runs, but the scheduler pauses before
608/// nondeterministic work). If a message arrives, it is returned; if the simulation settles to
609/// quiescence, returns `None` without having run any nondeterministic work. Otherwise the
610/// scheduler is resumed and pending nondeterministic work runs until a message arrives or the
611/// simulation quiesces; quiescing this way *taints* the simulation (see
612/// [`QuiescenceState::tainted`]).
613async fn try_next_bytes(
614    receiver: &Mutex<UnsyncReceiver<Bytes>>,
615    quiescence: &Rc<QuiescenceState>,
616) -> Option<Bytes> {
617    guard_not_poisoned(quiescence);
618
619    let mut receiver_stream = receiver.lock().await;
620    let mut settle_guard = SettlePauseGuard::new(quiescence.clone());
621    // `Some` once the settle phase has concluded that nondeterministic work is pending and
622    // we have started forcing it to run.
623    let mut notified_fut = pin!(None);
624
625    std::future::poll_fn(|cx| {
626        // **Scripted-decision barrier**: an output await completes only after every
627        // decision scripted so far has been consumed, so every point where the test body
628        // resumes is a clean synchronization point (the script written so far has fully
629        // happened). If the simulation runs out of work while a scripted decision is still
630        // waiting, that decision can never be honored — panic instead of yielding output
631        // or end-of-stream, so a stuck script cannot masquerade as a completed one.
632        if let Some(stuck) = script_unconsumed_description() {
633            assert!(!quiescence.is_quiescent(), "{}", script_stuck_error(&stuck));
634            quiescence.push_park_waker(cx.waker());
635            return Poll::Pending;
636        }
637
638        // A message may become available at any point (including from deterministic work
639        // while settling), so always check the stream first.
640        match receiver_stream.poll_next_unpin(cx) {
641            Poll::Ready(Some(bytes)) => return Poll::Ready(Some(bytes)),
642            Poll::Ready(None) => return Poll::Ready(None),
643            Poll::Pending => {}
644        }
645
646        if notified_fut.is_none() {
647            match settle_guard.poll_settle(cx) {
648                // Deterministically quiescent: no more messages, and nothing was overrun.
649                Poll::Ready(true) => return Poll::Ready(None),
650                // Nondeterministic work is pending; start forcing it to run. The `Notified`
651                // is created here and polled (registered) below in this same synchronous
652                // poll — before the scheduler can run — and the simulation is not currently
653                // quiescent, so the quiescence notification cannot be missed.
654                Poll::Ready(false) => notified_fut.set(Some(quiescence.notified())),
655                Poll::Pending => return Poll::Pending,
656            }
657        }
658
659        // Let the scheduler run nondeterministic work until a message arrives or the
660        // simulation quiesces. Note that merely entering this phase does not taint: if a
661        // message arrives (the `Some` exit at the top), waiting was sound for the same
662        // reason as `SimReceiver::next` — the work that ran was needed to produce it. Only
663        // *observing quiescence* after forcing the pending work taints, since that is the
664        // overrun a later observation could misattribute.
665        let () = ready!(notified_fut.as_mut().as_pin_mut().unwrap().poll(cx));
666        quiescence.tainted.set(true);
667        Poll::Ready(None)
668    })
669    .await
670}
671
672struct SimConnections {
673    input_senders: HashMap<SimExternalPort, UnsyncSender<Bytes>>,
674    output_receivers: HashMap<SimExternalPort, Rc<Mutex<UnsyncReceiver<Bytes>>>>,
675    cluster_input_senders: HashMap<SimExternalPort, HashMap<u32, UnsyncSender<Bytes>>>,
676    cluster_output_receivers:
677        HashMap<SimExternalPort, HashMap<u32, Rc<Mutex<UnsyncReceiver<Bytes>>>>>,
678    external_registered: HashMap<ExternalPortId, SimExternalPort>,
679    quiescence: Rc<QuiescenceState>,
680    /// Every scripted hook (shared with the scheduler's tick lists), keyed by handle ID.
681    scripted_hooks: Rc<ScriptedHookRegistry>,
682    /// Coordinates the decision-group protocol between hook handles and the scheduler.
683    script_coordinator: Rc<RefCell<ScriptCoordinator>>,
684    log: bool,
685    /// Whether this instance is being executed by the exhaustive engine (see
686    /// [`CompiledSim::exhaustive`]), which affects how `assert_yields_only` explores
687    /// quiescence checks.
688    exhaustive: bool,
689}
690
691/// Implementation detail of [`crate::sim::continue_if!`](crate::continue_if); do not call directly.
692///
693/// If `condition` is false, aborts the current simulation instance by panicking with a special
694/// payload ([`bolero::generator::bolero_generator::any::Error`]) that bolero recognizes as an
695/// "invalid input" marker: the instance is discarded (not treated as a test failure, and never
696/// recorded as a reproducer) and exploration moves on to the next instance. If logging is
697/// enabled for the current instance, the failed assumption is logged first.
698#[doc(hidden)]
699#[track_caller]
700pub fn continue_if_impl(condition: bool, message: fmt::Arguments<'_>) {
701    if condition {
702        return;
703    }
704
705    let log = CURRENT_SIM_CONNECTIONS
706        .try_with(|connections| connections.borrow().log)
707        .unwrap_or(true);
708    if log {
709        eprintln!(
710            "{}",
711            render_continue_if_failure(Location::caller(), message)
712        );
713    }
714
715    // Panics with `bolero_generator::any::Error`, which bolero's engines treat as an invalid
716    // input rather than a test failure. Both this function and bolero's `assume` are
717    // `#[track_caller]`, so the recorded location is the user's `continue_if!` call site.
718    bolero::generator::bolero_generator::any::assume(false, "simulation assumption failed");
719}
720
721/// Renders the log message for a failed assumption, echoing the source line with a caret
722/// pointing at the `continue_if!` call site, in the same style as the other simulator logs.
723fn render_continue_if_failure(location: &Location<'_>, message: fmt::Arguments<'_>) -> String {
724    use std::fmt::Write;
725
726    let source_line = std::env::current_dir()
727        .ok()
728        .and_then(|cwd| resolve_source_file(Path::new(location.file()), &cwd))
729        .and_then(|path| std::fs::read_to_string(path).ok())
730        .and_then(|content| {
731            content
732                .lines()
733                .nth((location.line() as usize).saturating_sub(1))
734                .map(|line| line.to_owned())
735        })
736        .unwrap_or_default();
737
738    let caret_indent = " ".repeat((location.column() as usize).saturating_sub(1));
739
740    let mut out = String::new();
741    let _ = writeln!(
742        out,
743        "\n{}",
744        "Condition failed (discarding simulation instance):"
745            .color(colored::Color::Yellow)
746            .bold()
747    );
748    let _ = writeln!(out, "{} {}", "-->".color(colored::Color::Blue), location);
749    let _ = writeln!(out, " {}{}", "|".color(colored::Color::Blue), source_line);
750    let _ = write!(
751        out,
752        " {}{}{}",
753        "|".color(colored::Color::Blue),
754        caret_indent,
755        format!("^ {}", message).color(colored::Color::Yellow)
756    );
757    out
758}
759
760tokio::task_local! {
761    static CURRENT_SIM_CONNECTIONS: RefCell<SimConnections>;
762}
763
764/// A handle to a compiled Hydro simulation, which can be instantiated and run.
765pub struct CompiledSim {
766    pub(super) lib: Library,
767    pub(super) externals_port_registry: SimExternalPortRegistry,
768    pub(super) unit_test_fuzz_iterations: usize,
769    pub(super) fuzz_max_len: usize,
770    /// See [`SimFlow::retries_depth`](super::flow::SimFlow::retries_depth).
771    pub(super) retries_depth: Option<usize>,
772    /// At-least-once operators not bound to a sim hook, rendered for error messages.
773    pub(super) unhooked_at_least_once: Vec<String>,
774}
775
776#[sealed::sealed]
777/// A trait implemented by closures that can instantiate a compiled simulation.
778///
779/// This is needed to ensure [`RefUnwindSafe`] so instances can be created during fuzzing.
780pub trait Instantiator<'a>: RefUnwindSafe + Fn() -> CompiledSimInstance<'a> {}
781#[sealed::sealed]
782impl<'a, T: RefUnwindSafe + Fn() -> CompiledSimInstance<'a>> Instantiator<'a> for T {}
783
784fn null_handler(_args: fmt::Arguments<'_>) {}
785
786fn println_handler(args: fmt::Arguments<'_>) {
787    println!("{}", args);
788}
789
790fn eprintln_handler(args: fmt::Arguments<'_>) {
791    eprintln!("{}", args);
792}
793
794/// Creates a simulation instance, returning:
795/// - A list of async DFIRs to run (all process / cluster logic outside a tick)
796/// - A list of tick DFIRs to run (where the &'static str is for the tick location id)
797/// - A mapping of hooks for non-deterministic decisions at tick-input boundaries
798/// - A mapping of inline hooks for non-deterministic decisions inside ticks
799type SimLoaded<'a> = libloading::Symbol<
800    'a,
801    unsafe extern "Rust" fn(
802        should_color: bool,
803        external_out: &mut HashMap<usize, UnsyncReceiver<Bytes>>,
804        external_in: &mut HashMap<usize, UnsyncSender<Bytes>>,
805        cluster_external_out: &mut HashMap<usize, HashMap<u32, UnsyncReceiver<Bytes>>>,
806        cluster_external_in: &mut HashMap<usize, HashMap<u32, UnsyncSender<Bytes>>>,
807        println_handler: fn(fmt::Arguments<'_>),
808        eprintln_handler: fn(fmt::Arguments<'_>),
809        panic_handler: super::panic_guard::PanicHandler,
810        retry_budget: RetryBudget,
811    ) -> (
812        Vec<(LocationId, Option<u32>, DfirErased<()>)>,
813        Vec<(LocationId, Option<u32>, DfirErased<()>)>,
814        Hooks,
815        ObservationHooks,
816        InlineHooks,
817        ScriptedTickHooks,
818        ScriptedObservationHooks,
819        ScriptedInlineHooks,
820        ScriptedHookRegistry,
821    ),
822>;
823
824impl CompiledSim {
825    /// Executes the given closure with a single instance of the compiled simulation.
826    pub fn with_instance<T>(&self, thunk: impl FnOnce(CompiledSimInstance<'_>) -> T) -> T {
827        self.with_instantiator(|instantiator| thunk(instantiator()), true)
828    }
829
830    /// Executes the given closure with an [`Instantiator`], which can be called to create
831    /// independent instances of the simulation. This is useful for fuzzing, where we need to
832    /// re-execute the simulation several times with different decisions.
833    ///
834    /// The `always_log` parameter controls whether to log tick executions and stream releases. If
835    /// it is `true`, logging will always be enabled. If it is `false`, logging will only be
836    /// enabled if the `HYDRO_SIM_LOG` environment variable is set to `1`.
837    pub fn with_instantiator<T>(
838        &self,
839        thunk: impl FnOnce(&dyn Instantiator<'_>) -> T,
840        always_log: bool,
841    ) -> T {
842        let func: SimLoaded<'_> = unsafe { self.lib.get(b"__hydro_runtime").unwrap() };
843        let log = always_log || std::env::var("HYDRO_SIM_LOG").is_ok_and(|v| v == "1");
844        let retry_budget = self.fuzz_retry_budget();
845        thunk(
846            &(|| CompiledSimInstance {
847                func: func.clone(),
848                externals_port_registry: self.externals_port_registry.clone(),
849                dylib_result: None,
850                log,
851                exhaustive: false,
852                deterministic: false,
853                retry_budget,
854            }),
855        )
856    }
857
858    fn fuzz_retry_budget(&self) -> RetryBudget {
859        match self.retries_depth {
860            Some(depth) => RetryBudget::Bounded(depth),
861            None => RetryBudget::Unbounded,
862        }
863    }
864
865    fn exhaustive_retry_budget(&self) -> RetryBudget {
866        match self.retries_depth {
867            Some(depth) => RetryBudget::Bounded(depth),
868            None if self.unhooked_at_least_once.is_empty() => RetryBudget::Bounded(0),
869            None => {
870                let points = self.unhooked_at_least_once.join("\n");
871                panic!(
872                    "exhaustive simulation needs a bound on the number of retries, but these \
873                     at-least-once operators are not bound to a sim hook:\n{points}\nhelp: call \
874                     `.retries_depth(n)` on the `SimFlow` to allow at most `n` retries per \
875                     operator, or bind sim hooks to these operators (`nondet!(... hook = \
876                     handle)`) and script their decisions"
877                );
878            }
879        }
880    }
881
882    /// Uses a fuzzing strategy to explore possible executions of the simulation. The provided
883    /// closure will be repeatedly executed with instances of the Hydro program where the
884    /// batching boundaries, order of messages, and retries are varied.
885    ///
886    /// During development, you should run the test that invokes this function with the `cargo sim`
887    /// command, which will use `libfuzzer` to intelligently explore the execution space. If a
888    /// failure is found, a minimized test case will be produced in a `sim-failures` directory.
889    /// When running the test with `cargo test` (such as in CI), if a reproducer is found it will
890    /// be executed, and if no reproducer is found a small number of random executions will be
891    /// performed.
892    #[track_caller]
893    pub fn fuzz(&self, mut thunk: impl AsyncFnMut() + RefUnwindSafe) {
894        // The reproducer's path comes from compile-time facts, the caller's location and
895        // `thunk`'s type, so debug info and inlining cannot change which reproducer a test runs.
896        let caller = Location::caller();
897        let caller_fuzz_repro_path = repro_path(
898            Path::new(caller.file()),
899            std::env::current_dir(),
900            std::any::type_name_of_val(&thunk),
901        )
902        .map_err(|reason| format!("for the `fuzz` call at {caller}, {reason}"));
903
904        if std::env::var("BOLERO_FUZZER").is_ok() {
905            let corpus_dir = std::env::current_dir().unwrap().join(".fuzz-corpus");
906            std::fs::create_dir_all(&corpus_dir).unwrap();
907            let libfuzzer_args = format!(
908                "{} {} -artifact_prefix={}/ -handle_abrt=0",
909                corpus_dir.to_str().unwrap(),
910                corpus_dir.to_str().unwrap(),
911                corpus_dir.to_str().unwrap(),
912            );
913
914            if !std::env::var("HYDRO_NO_FAILURE_OUTPUT").is_ok_and(|v| v == "1") {
915                let caller_fuzz_repro_path = caller_fuzz_repro_path.unwrap_or_else(|reason| {
916                    panic!("`cargo sim` cannot save a failure as a reproducer: {reason}")
917                });
918                std::fs::create_dir_all(caller_fuzz_repro_path.parent().unwrap()).unwrap();
919                unsafe {
920                    std::env::set_var(
921                        "BOLERO_FAILURE_OUTPUT",
922                        caller_fuzz_repro_path.to_str().unwrap(),
923                    );
924                }
925            }
926
927            unsafe {
928                std::env::set_var("BOLERO_LIBFUZZER_ARGS", libfuzzer_args);
929            }
930
931            self.with_instantiator(
932                |instantiator| {
933                    bolero::test(bolero::TargetLocation {
934                        package_name: "",
935                        manifest_dir: "",
936                        module_path: "",
937                        file: "",
938                        line: 0,
939                        item_path: "<unknown>::__bolero_item_path__",
940                        test_name: None,
941                    })
942                    .with_max_len(self.fuzz_max_len)
943                    .run_with_replay(move |is_replay| {
944                        let mut instance = instantiator();
945
946                        if instance.log {
947                            eprintln!(
948                                "{}",
949                                "\n==== New Simulation Instance ===="
950                                    .color(colored::Color::Cyan)
951                                    .bold()
952                            );
953                        }
954
955                        if is_replay {
956                            instance.log = true;
957                        }
958
959                        tokio::runtime::Builder::new_current_thread()
960                            .build()
961                            .unwrap()
962                            .block_on(async { instance.run(&mut thunk).await })
963                    })
964                },
965                false,
966            );
967        } else if let Some(existing_bytes) = caller_fuzz_repro_path
968            .as_ref()
969            .ok()
970            .and_then(|path| std::fs::read(path).ok())
971        {
972            self.fuzz_repro(existing_bytes, async |compiled| {
973                compiled.run_with_scheduler(thunk()).await
974            });
975        } else {
976            match &caller_fuzz_repro_path {
977                Ok(path) => eprintln!(
978                    "Running a fuzz test without `cargo sim` and no reproducer found at {}, using {} iterations with random inputs.",
979                    path.display(),
980                    self.unit_test_fuzz_iterations,
981                ),
982                Err(reason) => eprintln!(
983                    "Running a fuzz test without `cargo sim` and without looking for a reproducer: {reason}. Using {} iterations with random inputs.",
984                    self.unit_test_fuzz_iterations,
985                ),
986            }
987            self.with_instantiator(
988                |instantiator| {
989                    bolero::test(bolero::TargetLocation {
990                        package_name: "",
991                        manifest_dir: "",
992                        module_path: "",
993                        file: ".",
994                        line: 0,
995                        item_path: "<unknown>::__bolero_item_path__",
996                        test_name: None,
997                    })
998                    .with_max_len(self.fuzz_max_len)
999                    .with_iterations(self.unit_test_fuzz_iterations)
1000                    .run_with_replay(move |is_replay| {
1001                        let mut instance = instantiator();
1002
1003                        if instance.log {
1004                            eprintln!(
1005                                "{}",
1006                                "\n==== New Simulation Instance ===="
1007                                    .color(colored::Color::Cyan)
1008                                    .bold()
1009                            );
1010                        }
1011
1012                        if is_replay {
1013                            instance.log = true;
1014                        }
1015
1016                        tokio::runtime::Builder::new_current_thread()
1017                            .build()
1018                            .unwrap()
1019                            .block_on(async { instance.run(&mut thunk).await })
1020                    })
1021                },
1022                false,
1023            );
1024        }
1025    }
1026
1027    /// Executes the given closure with a single instance of the compiled simulation, using the
1028    /// provided bytes as the source of fuzzing decisions. This can be used to manually reproduce a
1029    /// failure found during fuzzing.
1030    pub fn fuzz_repro<'a>(
1031        &'a self,
1032        bytes: Vec<u8>,
1033        thunk: impl AsyncFnOnce(CompiledSimInstance<'_>) + RefUnwindSafe,
1034    ) {
1035        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1036            self.with_instance(|instance| {
1037                bolero::bolero_engine::any::scope::with(
1038                    Box::new(bolero::bolero_engine::driver::object::Object(
1039                        bolero::bolero_engine::driver::bytes::Driver::new(
1040                            bytes,
1041                            &Default::default(),
1042                        ),
1043                    )),
1044                    || {
1045                        tokio::runtime::Builder::new_current_thread()
1046                            .build()
1047                            .unwrap()
1048                            .block_on(async { instance.run_without_launching(thunk).await })
1049                    },
1050                )
1051            })
1052        }));
1053
1054        if let Err(payload) = result {
1055            if payload
1056                .downcast_ref::<bolero::generator::bolero_generator::any::Error>()
1057                .is_some()
1058            {
1059                // A `continue_if!` failed (or the driver ran out of entropy) while replaying the
1060                // recorded bytes. Instances that fail an assumption are never recorded as
1061                // failures, so this means the reproducer is stale or does not correspond to
1062                // this program.
1063                panic!(
1064                    "simulation assumption failed while replaying recorded fuzz decisions; the reproducer may be stale or may not correspond to this program"
1065                );
1066            }
1067            std::panic::resume_unwind(payload);
1068        }
1069    }
1070
1071    /// Exhaustively searches all possible executions of the simulation. The provided
1072    /// closure will be repeatedly executed with instances of the Hydro program where the
1073    /// batching boundaries, order of messages, and retries are varied.
1074    ///
1075    /// Exhaustive searching is feasible when the inputs to the Hydro program are finite and there
1076    /// are no dataflow loops that generate infinite messages. Exhaustive searching provides a
1077    /// stronger guarantee of correctness than fuzzing, but may take a long time to complete.
1078    /// Because no fuzzer is involved, you can run exhaustive tests with `cargo test`.
1079    ///
1080    /// Returns the number of distinct executions explored.
1081    pub fn exhaustive(&self, mut thunk: impl AsyncFnMut() + RefUnwindSafe) -> usize {
1082        if std::env::var("BOLERO_FUZZER").is_ok() {
1083            eprintln!(
1084                "Cannot run exhaustive tests with a fuzzer. Please use `cargo test` instead of `cargo sim`."
1085            );
1086            std::process::abort();
1087        }
1088
1089        let retry_budget = self.exhaustive_retry_budget();
1090
1091        let mut count = 0;
1092        let count_mut = &mut count;
1093
1094        let _span = tracing::debug_span!(target: "hydro_build", "sim_exhaustive").entered();
1095
1096        self.with_instantiator(
1097            |instantiator| {
1098                bolero::test(bolero::TargetLocation {
1099                    package_name: "",
1100                    manifest_dir: "",
1101                    module_path: "",
1102                    file: "",
1103                    line: 0,
1104                    item_path: "<unknown>::__bolero_item_path__",
1105                    test_name: None,
1106                })
1107                .exhaustive()
1108                .run_with_replay(move |is_replay| {
1109                    *count_mut += 1;
1110
1111                    let mut instance = instantiator();
1112                    instance.exhaustive = true;
1113                    instance.retry_budget = retry_budget;
1114                    if instance.log {
1115                        eprintln!(
1116                            "{}",
1117                            "\n==== New Simulation Instance ===="
1118                                .color(colored::Color::Cyan)
1119                                .bold()
1120                        );
1121                    }
1122
1123                    if is_replay {
1124                        instance.log = true;
1125                    }
1126
1127                    tokio::runtime::Builder::new_current_thread()
1128                        .build()
1129                        .unwrap()
1130                        .block_on(async { instance.run(&mut thunk).await })
1131                })
1132            },
1133            false,
1134        );
1135
1136        count
1137    }
1138
1139    /// Runs the test body against exactly **one** execution of the program, with no fuzzer
1140    /// involved anywhere: if it passes once, it passes always, on every machine.
1141    ///
1142    /// Every source of variation must be pinned: inputs are already scripted (via
1143    /// `sim_input`), and every unsafe operator that receives data must be bound to a sim
1144    /// hook (see [`crate::sim_hooks`]) and scripted — encountering an unhooked operator
1145    /// with meaningful input panics, naming the operator. The scheduler needs no
1146    /// tie-breaking policy because at most one tick is ever runnable: scripted decisions
1147    /// activate one group at a time, so the *script* is the schedule.
1148    pub fn deterministic(&self, thunk: impl AsyncFnOnce() + RefUnwindSafe) {
1149        // no fuzzer to draw retries from, regardless of `retries_depth`
1150        assert!(
1151            self.unhooked_at_least_once.is_empty(),
1152            "deterministic simulation requires every at-least-once operator to be bound to a \
1153             sim hook, but these are not:\n{}\nhelp: bind a sim hook to each of these \
1154             operators (`nondet!(... hook = handle)`) and script its decisions, or run under \
1155             `fuzz` / `exhaustive` instead",
1156            self.unhooked_at_least_once.join("\n")
1157        );
1158        self.with_instance(|mut instance| {
1159            instance.deterministic = true;
1160            // unused, every at-least-once hook is scripted
1161            instance.retry_budget = RetryBudget::Bounded(0);
1162
1163            // Deliberately do not install a Bolero entropy scope. Deterministic execution
1164            // must never draw entropy; Bolero's unset thread-local scope makes any accidental
1165            // draw fail immediately with `no scope set`.
1166            tokio::runtime::Builder::new_current_thread()
1167                .build()
1168                .unwrap()
1169                .block_on(instance.run(thunk));
1170        })
1171    }
1172}
1173
1174// This must be a tuple because it is referenced from generated code in `graph.rs`.
1175type DylibResult = (
1176    Vec<(LocationId, Option<u32>, DfirErased<()>)>,
1177    Vec<(LocationId, Option<u32>, DfirErased<()>)>,
1178    Hooks,
1179    ObservationHooks,
1180    InlineHooks,
1181    ScriptedTickHooks,
1182    ScriptedObservationHooks,
1183    ScriptedInlineHooks,
1184    ScriptedHookRegistry,
1185);
1186
1187/// A single instance of a compiled Hydro simulation, which provides methods to interactively
1188/// execute the simulation, feed inputs, and receive outputs.
1189pub struct CompiledSimInstance<'a> {
1190    func: SimLoaded<'a>,
1191    externals_port_registry: SimExternalPortRegistry,
1192    dylib_result: Option<DylibResult>,
1193    log: bool,
1194    exhaustive: bool,
1195    deterministic: bool,
1196    retry_budget: RetryBudget,
1197}
1198
1199impl<'a> CompiledSimInstance<'a> {
1200    async fn run(self, thunk: impl AsyncFnOnce() + RefUnwindSafe) {
1201        self.run_without_launching(async |instance| {
1202            instance.run_with_scheduler(thunk()).await;
1203        })
1204        .await;
1205    }
1206
1207    async fn run_without_launching(
1208        mut self,
1209        thunk: impl AsyncFnOnce(CompiledSimInstance<'_>) + RefUnwindSafe,
1210    ) {
1211        let mut external_out: HashMap<usize, UnsyncReceiver<Bytes>> = HashMap::new();
1212        let mut external_in: HashMap<usize, UnsyncSender<Bytes>> = HashMap::new();
1213        let mut cluster_external_out: HashMap<usize, HashMap<u32, UnsyncReceiver<Bytes>>> =
1214            HashMap::new();
1215        let mut cluster_external_in: HashMap<usize, HashMap<u32, UnsyncSender<Bytes>>> =
1216            HashMap::new();
1217
1218        let mut dylib_result = unsafe {
1219            (self.func)(
1220                colored::control::SHOULD_COLORIZE.should_colorize(),
1221                &mut external_out,
1222                &mut external_in,
1223                &mut cluster_external_out,
1224                &mut cluster_external_in,
1225                if self.log {
1226                    println_handler
1227                } else {
1228                    null_handler
1229                },
1230                if self.log {
1231                    eprintln_handler
1232                } else {
1233                    null_handler
1234                },
1235                super::panic_guard::host_handler,
1236                self.retry_budget,
1237            )
1238        };
1239
1240        let registered = &self.externals_port_registry.registered;
1241
1242        let quiescence = Rc::new(QuiescenceState {
1243            quiescent: Cell::new(false),
1244            quiescence_notify: Notify::new(),
1245            resume_notify: Notify::new(),
1246            pause_nondet: Cell::new(0),
1247            nondet_pending: Cell::new(false),
1248            settle_wakers: RefCell::new(vec![]),
1249            tainted: Cell::new(false),
1250            poisoned: Cell::new(false),
1251        });
1252
1253        let mut input_senders = HashMap::new();
1254        let mut output_receivers = HashMap::new();
1255        let mut cluster_input_senders = HashMap::new();
1256        let mut cluster_output_receivers = HashMap::new();
1257
1258        #[expect(
1259            clippy::disallowed_methods,
1260            reason = "inserts into maps also unordered"
1261        )]
1262        for sim_port in registered.values() {
1263            let usize_key = sim_port.into_inner();
1264            if let Some(sender) = external_in.remove(&usize_key) {
1265                input_senders.insert(*sim_port, sender);
1266            }
1267            if let Some(receiver) = external_out.remove(&usize_key) {
1268                output_receivers.insert(*sim_port, Rc::new(Mutex::new(receiver)));
1269            }
1270            if let Some(senders) = cluster_external_in.remove(&usize_key) {
1271                cluster_input_senders.insert(*sim_port, senders);
1272            }
1273            if let Some(receivers) = cluster_external_out.remove(&usize_key) {
1274                cluster_output_receivers.insert(
1275                    *sim_port,
1276                    receivers
1277                        .into_iter()
1278                        .map(|(member, r)| (member, Rc::new(Mutex::new(r))))
1279                        .collect(),
1280                );
1281            }
1282        }
1283
1284        let scripted_hooks = Rc::new(std::mem::take(&mut dylib_result.8));
1285        self.dylib_result = Some(dylib_result);
1286
1287        CURRENT_SIM_CONNECTIONS
1288            .scope(
1289                RefCell::new(SimConnections {
1290                    input_senders,
1291                    output_receivers,
1292                    cluster_input_senders,
1293                    cluster_output_receivers,
1294                    external_registered: self.externals_port_registry.registered.clone(),
1295                    quiescence: quiescence.clone(),
1296                    scripted_hooks,
1297                    script_coordinator: Rc::new(RefCell::new(ScriptCoordinator::default())),
1298                    log: self.log,
1299                    exhaustive: self.exhaustive,
1300                }),
1301                async move {
1302                    thunk(self).await;
1303                },
1304            )
1305            .await;
1306    }
1307
1308    /// Runs the simulation scheduler alongside the given future, until the future completes.
1309    ///
1310    /// The future always gets to run first; whenever it is blocked (e.g. waiting to receive
1311    /// simulation outputs), the scheduler runs a single step to completion. Steps are atomic
1312    /// with respect to the future: it is re-polled between every pair of scheduler steps, but
1313    /// never while a step is in flight. The [`LaunchedSim`] state struct lives across steps,
1314    /// in this function's frame.
1315    async fn run_with_scheduler(self, thunk: impl Future<Output = ()>) {
1316        self.run_with_scheduler_and_maybe_logger::<std::io::Empty>(None, thunk)
1317            .await;
1318    }
1319
1320    /// Runs the simulation scheduler alongside the given future, until the future completes,
1321    /// reporting the simulation trace to the given logger.
1322    ///
1323    /// The future always gets to run first; whenever it is blocked (e.g. waiting to receive
1324    /// simulation outputs), the scheduler runs a single step to completion. Steps are atomic
1325    /// with respect to the future: it is re-polled between every pair of scheduler steps, but
1326    /// never while a step is in flight.
1327    pub async fn run_with_scheduler_and_logger<W: std::io::Write>(
1328        self,
1329        log_writer: W,
1330        thunk: impl Future<Output = ()>,
1331    ) {
1332        self.run_with_scheduler_and_maybe_logger(Some(log_writer), thunk)
1333            .await;
1334    }
1335
1336    async fn run_with_scheduler_and_maybe_logger<W: std::io::Write>(
1337        self,
1338        log_override: Option<W>,
1339        thunk: impl Future<Output = ()>,
1340    ) {
1341        let mut sim = self.start(log_override);
1342        let mut thunk_fut = pin!(thunk);
1343        let mut thunk_complete = false;
1344        loop {
1345            // The thunk always gets to run first until it completes. Completion is itself a
1346            // script barrier: after the body returns, keep stepping until every decision it
1347            // installed has been consumed (or report a decision that can never be honored).
1348            if !thunk_complete && futures::poll!(thunk_fut.as_mut()).is_ready() {
1349                thunk_complete = true;
1350            }
1351
1352            if thunk_complete {
1353                let Some(stuck) = script_unconsumed_description() else {
1354                    break;
1355                };
1356                assert!(
1357                    !sim.quiescence.is_quiescent(),
1358                    "{}",
1359                    script_stuck_error(&stuck)
1360                );
1361                sim.step().await;
1362                continue;
1363            }
1364
1365            if sim.quiescence.is_quiescent() || sim.quiescence.nondet_pending.get() {
1366                // The scheduler is parked: either no step can make progress until the thunk
1367                // sends new input (quiescent), or nondeterministic work is ready but a
1368                // settling test-side observation has paused the scheduler (nondet_pending).
1369                // Park until either the thunk is woken independently or the scheduler is
1370                // resumed. (`resumed()` is permit-based, so a resume that fired while polling
1371                // the thunk above is not lost.)
1372                tokio::select! {
1373                    biased;
1374                    () = &mut thunk_fut => break,
1375                    () = sim.quiescence.resumed() => {}
1376                }
1377                sim.quiescence.nondet_pending.set(false);
1378            } else {
1379                // Run a single scheduler step to completion. This is awaited directly (not
1380                // raced against the thunk), so a step is atomic: the thunk is never polled
1381                // while a step is in flight, and a step is never cancelled mid-execution.
1382                sim.step().await;
1383            }
1384        }
1385    }
1386
1387    /// Consumes this instance and constructs the [`LaunchedSim`] state struct, which is
1388    /// advanced incrementally via [`LaunchedSim::step`].
1389    fn start<W: std::io::Write>(mut self, log_override: Option<W>) -> LaunchedSim<W> {
1390        let (
1391            async_dfirs,
1392            tick_dfirs,
1393            mut hooks,
1394            mut observation_hooks,
1395            mut inline_hooks,
1396            mut scripted_hooks,
1397            mut scripted_observation_hooks,
1398            mut scripted_inline_hooks,
1399            _registry,
1400        ) = self.dylib_result.take().unwrap();
1401
1402        // The generated code keys hooks and tick DFIRs by the same locations, so we can
1403        // move each tick's / observation's hooks out of the maps and attach them
1404        // directly. This lets the scheduler's hot paths avoid keyed lookups entirely.
1405        let not_ready_ticks = tick_dfirs
1406            .into_iter()
1407            .map(|(location, cluster_id, dfir)| {
1408                let key = SimLocation {
1409                    location,
1410                    cluster_id,
1411                };
1412                let LocationId::Tick {
1413                    tick: _,
1414                    parent_location,
1415                } = &key.location
1416                else {
1417                    unreachable!("tick DFIRs are always keyed by a tick location")
1418                };
1419                let parent_location = (**parent_location).clone();
1420                let tick = SimTick {
1421                    parent_location,
1422                    cluster_id,
1423                    dfir,
1424                    hooks: hooks.remove(&key).unwrap_or_default(),
1425                    scripted_hooks: scripted_hooks.remove(&key).unwrap_or_default(),
1426                    inline_hooks: inline_hooks.remove(&key).unwrap_or_default(),
1427                    scripted_inline_hooks: scripted_inline_hooks.remove(&key).unwrap_or_default(),
1428                    location: key.location,
1429                };
1430                abort_assert!(
1431                    !(tick.hooks.is_empty() && tick.scripted_hooks.is_empty()),
1432                    "every tick DFIR must have at least one hook"
1433                );
1434                tick
1435            })
1436            .collect();
1437
1438        let (quiescence, script_coordinator) = CURRENT_SIM_CONNECTIONS.with(|connections| {
1439            let connections = connections.borrow();
1440            (
1441                connections.quiescence.clone(),
1442                connections.script_coordinator.clone(),
1443            )
1444        });
1445
1446        let not_ready_observations = async_dfirs
1447            .iter()
1448            .flat_map(|(location, cluster_id, _)| {
1449                let key = SimLocation {
1450                    location: location.clone(),
1451                    cluster_id: *cluster_id,
1452                };
1453                let cluster_id = *cluster_id;
1454                let unscripted = observation_hooks
1455                    .remove(&key)
1456                    .unwrap_or_default()
1457                    .into_iter()
1458                    .map(|hook| ObservationSlot::Unscripted { hook });
1459                let scripted = scripted_observation_hooks
1460                    .remove(&key)
1461                    .unwrap_or_default()
1462                    .into_iter()
1463                    .map(|hook| {
1464                        let ScriptTarget::Observation { hook_id, .. } = hook.borrow().target()
1465                        else {
1466                            unreachable!("observation-registered scripted hook had a tick target")
1467                        };
1468                        ObservationSlot::Scripted { hook_id, hook }
1469                    });
1470                unscripted.chain(scripted).map(move |hook| SimObservation {
1471                    location: key.location.clone(),
1472                    cluster_id,
1473                    hook,
1474                })
1475            })
1476            .collect();
1477
1478        debug_assert!(
1479            hooks.is_empty()
1480                && observation_hooks.is_empty()
1481                && inline_hooks.is_empty()
1482                && scripted_hooks.is_empty()
1483                && scripted_observation_hooks.is_empty()
1484                && scripted_inline_hooks.is_empty(),
1485            "all hooks should belong to either a tick DFIR or a top-level location"
1486        );
1487
1488        LaunchedSim {
1489            async_dfirs,
1490            possibly_ready_ticks: vec![],
1491            not_ready_ticks,
1492            current_scripted_tick: None,
1493            current_scripted_observation: None,
1494            script_coordinator,
1495            possibly_ready_observations: vec![],
1496            not_ready_observations,
1497            log: if self.log {
1498                if let Some(w) = log_override {
1499                    LogKind::Custom(w)
1500                } else {
1501                    LogKind::Stderr
1502                }
1503            } else {
1504                LogKind::Null
1505            },
1506            quiescence,
1507            deterministic: self.deterministic,
1508        }
1509    }
1510}
1511
1512impl<T, O: Ordering, R: Retries> Clone for SimReceiver<T, O, R> {
1513    fn clone(&self) -> Self {
1514        *self
1515    }
1516}
1517
1518impl<T, O: Ordering, R: Retries> Copy for SimReceiver<T, O, R> {}
1519
1520/// How a [`QuiescenceCheckFuture`] resolves the "did the stream end?" check of
1521/// `assert_no_more`. Decided once the simulation has settled (run out of deterministic
1522/// work).
1523#[derive(Clone, Copy)]
1524enum QuiescenceBranch {
1525    /// Skip the check and continue the test. Only taken in exhaustive mode, where a
1526    /// sibling instance performs the check instead.
1527    Continue,
1528    /// Perform the check, then end this simulation instance (exhaustive mode), letting
1529    /// sibling instances continue past this point without forcing quiescence.
1530    CheckThenEnd,
1531    /// Perform the check and keep running. Taken when the simulation is already quiescent
1532    /// (the check is free) and in non-exhaustive modes.
1533    CheckAndKeepRunning,
1534}
1535
1536/// Decides how to run the quiescence check when the simulation has pending nondeterministic
1537/// work (ticks / observations) that the check would force to run.
1538fn decide_quiescence_branch() -> QuiescenceBranch {
1539    let (exhaustive, log) = CURRENT_SIM_CONNECTIONS.with(|connections| {
1540        let connections = connections.borrow();
1541        (connections.exhaustive, connections.log)
1542    });
1543
1544    if !exhaustive {
1545        return QuiescenceBranch::CheckAndKeepRunning;
1546    }
1547
1548    // In exhaustive mode, fork the search on a bolero decision. The exhaustive driver
1549    // enumerates `false` first, so the instance that performs the quiescence check is
1550    // explored *before* any instance that continues past this assertion. This ensures that
1551    // if the stream has extra output, the failure is attributed to this assertion (with a
1552    // decision trace leading exactly to the check) rather than leaking the extra messages
1553    // into a later assertion.
1554    let continue_without_check: bool = bolero::any();
1555    if continue_without_check {
1556        if log {
1557            eprintln!(
1558                "\n{}",
1559                "Continuing past quiescence assertion without checking (checked by an earlier instance)"
1560                    .color(colored::Color::Cyan)
1561                    .bold()
1562            );
1563        }
1564        QuiescenceBranch::Continue
1565    } else {
1566        if log {
1567            eprintln!(
1568                "\n{}",
1569                "Checking that no more messages arrive (this instance will end after the check)"
1570                    .color(colored::Color::Cyan)
1571                    .bold()
1572            );
1573        }
1574        QuiescenceBranch::CheckThenEnd
1575    }
1576}
1577
1578/// Ends the current simulation instance after a passing quiescence check, by panicking with
1579/// [`bolero::generator::bolero_generator::any::Error`], which bolero's engines treat as an
1580/// invalid input rather than a test failure. The instance has verified everything up to and
1581/// including the quiescence check; sibling instances continue past the check instead.
1582fn end_instance_after_quiescence_check() -> ! {
1583    bolero::generator::bolero_generator::any::assume(
1584        false,
1585        "simulation instance ended after quiescence check",
1586    );
1587    unreachable!()
1588}
1589
1590pin_project_lite::pin_project! {
1591    // The "and then the stream ends" half of `assert_no_more` (and thus of
1592    // `assert_yields_only*` / `collect_n_only`). First lets the simulation *settle* (see
1593    // `poll_settle`): if it settles to quiescence, the check is free and the test simply
1594    // continues. Otherwise, in exhaustive mode the search forks into a checking instance and
1595    // continuing instances (see `SimReceiver::assert_no_more` and
1596    // `decide_quiescence_branch`); in non-exhaustive modes the check runs, forcing the
1597    // pending work (which taints the simulation, via `try_next_bytes`).
1598    //
1599    // See [`FutureTrackingCaller`] for why `poll` is `#[track_caller]`.
1600    struct QuiescenceCheckFuture<F: Future<Output = ()>> {
1601        #[pin]
1602        check: F,
1603        settle: SettlePauseGuard,
1604        branch: Option<QuiescenceBranch>,
1605    }
1606}
1607
1608impl<F: Future<Output = ()>> QuiescenceCheckFuture<F> {
1609    fn new(check: F) -> Self {
1610        QuiescenceCheckFuture {
1611            check,
1612            settle: SettlePauseGuard::new(
1613                CURRENT_SIM_CONNECTIONS.with(|connections| connections.borrow().quiescence.clone()),
1614            ),
1615            branch: None,
1616        }
1617    }
1618}
1619
1620impl<F: Future<Output = ()>> Future for QuiescenceCheckFuture<F> {
1621    type Output = ();
1622
1623    #[track_caller]
1624    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1625        let this = self.as_mut().project();
1626
1627        if this.branch.is_none() {
1628            *this.branch = Some(if ready!(this.settle.poll_settle(cx)) {
1629                // Settled to quiescence deterministically, so the check is free.
1630                QuiescenceBranch::CheckAndKeepRunning
1631            } else {
1632                // The check would force nondeterministic work to run.
1633                decide_quiescence_branch()
1634            });
1635        }
1636
1637        match this.branch.unwrap() {
1638            QuiescenceBranch::Continue => Poll::Ready(()),
1639            QuiescenceBranch::CheckAndKeepRunning => this.check.poll(cx),
1640            QuiescenceBranch::CheckThenEnd => {
1641                ready!(this.check.poll(cx));
1642                end_instance_after_quiescence_check()
1643            }
1644        }
1645    }
1646}
1647
1648impl<T, O: Ordering, R: Retries> SimReceiver<T, O, R> {
1649    fn connections(&self) -> (Rc<Mutex<UnsyncReceiver<Bytes>>>, Rc<QuiescenceState>) {
1650        CURRENT_SIM_CONNECTIONS.with(|connections| {
1651            let connections = connections.borrow();
1652            let port = connections.external_registered.get(&self.0).unwrap();
1653            (
1654                connections.output_receivers.get(port).unwrap().clone(),
1655                connections.quiescence.clone(),
1656            )
1657        })
1658    }
1659
1660    /// See [`try_next_bytes`].
1661    async fn try_next_impl(&self) -> Option<T> {
1662        let (receiver, quiescence) = self.connections();
1663        try_next_bytes(&receiver, &quiescence)
1664            .await
1665            .map(|bytes| (self.2)(&bytes))
1666    }
1667
1668    /// Asserts that the stream has ended and no more messages can possibly arrive.
1669    ///
1670    /// If the check cannot be answered without running pending nondeterministic work (such
1671    /// as ticks with buffered inputs):
1672    /// - Under [`CompiledSim::exhaustive`], the search forks: one instance performs the
1673    ///   check and ends there, while sibling instances skip the check and continue.
1674    /// - In other modes, the pending work runs; afterwards, sending more input and then
1675    ///   attempting to receive output will panic.
1676    pub fn assert_no_more(self) -> impl Future<Output = ()>
1677    where
1678        T: Debug,
1679    {
1680        QuiescenceCheckFuture::new(FutureTrackingCaller {
1681            future: async move {
1682                if let Some(next) = self.try_next_impl().await {
1683                    return Err(format!(
1684                        "Stream yielded unexpected message: {:?}, expected termination",
1685                        next
1686                    ));
1687                }
1688                Ok(())
1689            },
1690        })
1691    }
1692}
1693
1694impl<T> SimReceiver<T, TotalOrder, ExactlyOnce> {
1695    /// Receives the next message from the simulation output stream, waiting (and letting the
1696    /// scheduler run any pending simulation work) until one is available. If the simulation
1697    /// becomes quiescent without producing a message, the test fails.
1698    ///
1699    /// This is safe to use in the middle of a test; to observe the *absence* of a message,
1700    /// use [`Self::try_next`] or [`Self::assert_no_more`].
1701    pub fn next(&self) -> impl use<'_, T> + Future<Output = T> {
1702        // Waiting for a message never "overruns" the simulation, even though the scheduler
1703        // may run nondeterministic ticks while we wait: if a message arrives, some pending
1704        // work was necessary to produce it (schedules that run *extra* work are also valid
1705        // executions, explored separately), and if the simulation quiesces instead, the test
1706        // fails right here — so no later observation can be affected by the overrun (the
1707        // taint set by `try_next_impl` is unobservable). See the module docs for the full
1708        // soundness reasoning.
1709        FutureTrackingCaller {
1710            future: async move {
1711                self.try_next_impl().await.ok_or_else(|| {
1712                    "Stream ended (simulation quiescent), but another message was expected"
1713                        .to_owned()
1714                })
1715            },
1716        }
1717    }
1718
1719    /// Receives the next message from the simulation output stream, or returns `None` if no
1720    /// more messages can possibly arrive.
1721    ///
1722    /// If answering requires forcing pending nondeterministic work to run, then afterwards,
1723    /// sending more input and then attempting to receive output will panic. Prefer
1724    /// [`Self::next`] (or [`Self::assert_no_more`]) when possible.
1725    pub async fn try_next(&self) -> Option<T> {
1726        self.try_next_impl().await
1727    }
1728
1729    /// Receives the next `n` messages from the simulation output stream, waiting (and letting
1730    /// the scheduler run any pending simulation work) until they are available. If the
1731    /// simulation becomes quiescent before `n` messages arrive, the test fails.
1732    ///
1733    /// Like [`Self::next`], this is safe to use in the middle of a test. It does not check
1734    /// that the stream ends afterwards; use [`Self::collect_n_only`] for that.
1735    pub fn collect_n<C: Default + Extend<T>>(
1736        &self,
1737        n: usize,
1738    ) -> impl use<'_, T, C> + Future<Output = C> {
1739        FutureTrackingCaller {
1740            future: async move {
1741                let mut out = C::default();
1742                for i in 0..n {
1743                    // Like `next`, waiting for each message is safe mid-test; the taint on a
1744                    // forced `None` is unobservable because the test fails below.
1745                    if let Some(v) = self.try_next_impl().await {
1746                        out.extend([v]);
1747                    } else {
1748                        return Err(format!(
1749                            "Stream ended (simulation quiescent) after {} messages, but {} were expected",
1750                            i, n
1751                        ));
1752                    }
1753                }
1754                Ok(out)
1755            },
1756        }
1757    }
1758
1759    /// Receives the next `n` messages (like [`Self::collect_n`]) and then asserts that the
1760    /// stream ends (like [`Self::assert_no_more`], forking the search in exhaustive mode).
1761    pub async fn collect_n_only<C: Default + Extend<T>>(self, n: usize) -> C
1762    where
1763        T: Debug,
1764    {
1765        let out = self.collect_n(n).await;
1766        self.assert_no_more().await;
1767        out
1768    }
1769
1770    /// Collects all remaining messages from the simulation output stream into a collection,
1771    /// waiting until no more messages can possibly arrive.
1772    ///
1773    /// If this has to force pending nondeterministic work to run, it should be the last
1774    /// observation of the test: afterwards, sending more input and then attempting to
1775    /// receive output will panic. When the number of expected messages is known, prefer
1776    /// [`Self::collect_n`] / [`Self::collect_n_only`].
1777    pub async fn collect<C: Default + Extend<T>>(self) -> C {
1778        let mut out = C::default();
1779        while let Some(v) = self.try_next_impl().await {
1780            out.extend([v]);
1781        }
1782        out
1783    }
1784
1785    /// Asserts that the stream yields exactly the expected sequence of messages, in order.
1786    /// This does not check that the stream ends, use [`Self::assert_yields_only`] for that.
1787    ///
1788    /// Like [`Self::next`], this is safe to use in the middle of a test.
1789    pub fn assert_yields<T2: Debug, I: IntoIterator<Item = T2>>(
1790        &self,
1791        expected: I,
1792    ) -> impl use<'_, T, T2, I> + Future<Output = ()>
1793    where
1794        T: Debug + PartialEq<T2>,
1795    {
1796        FutureTrackingCaller {
1797            future: async {
1798                let mut expected: VecDeque<T2> = expected.into_iter().collect();
1799
1800                while !expected.is_empty() {
1801                    // Like `next`, waiting for each expected message is safe mid-test; the
1802                    // taint on a forced `None` is unobservable because the test fails below.
1803                    if let Some(next) = self.try_next_impl().await {
1804                        let next_expected = expected.pop_front().unwrap();
1805                        if next != next_expected {
1806                            return Err(format!(
1807                                "Stream yielded unexpected message: {:?}, expected: {:?}",
1808                                next, next_expected
1809                            ));
1810                        }
1811                    } else {
1812                        return Err(format!(
1813                            "Stream ended early, still expected: {:?}",
1814                            expected
1815                        ));
1816                    }
1817                }
1818
1819                Ok(())
1820            },
1821        }
1822    }
1823
1824    /// Asserts that the stream yields only the expected sequence of messages, in order,
1825    /// and then ends (like [`Self::assert_no_more`], forking the search in exhaustive mode).
1826    pub fn assert_yields_only<T2: Debug, I: IntoIterator<Item = T2>>(
1827        &self,
1828        expected: I,
1829    ) -> impl use<'_, T, T2, I> + Future<Output = ()>
1830    where
1831        T: Debug + PartialEq<T2>,
1832    {
1833        ChainedFuture {
1834            first: self.assert_yields(expected),
1835            second: self.assert_no_more(),
1836            first_done: false,
1837        }
1838    }
1839}
1840
1841pin_project_lite::pin_project! {
1842    // A future that tracks the location of the `.await` call for better panic messages.
1843    //
1844    // `#[track_caller]` is important for us to create assertion methods because it makes
1845    // the panic backtrace show up at that method (instead of inside the call tree within
1846    // that method). This is e.g. what `Option::unwrap` uses. Unfortunately, `#[track_caller]`
1847    // does not work correctly for async methods (or `dyn Future` either), so we have to
1848    // create these concrete future types that (1) have `#[track_caller]` on their `poll()`
1849    // method and (2) have the `panic!` triggered in their `poll()` method (or in a directly
1850    // nested concrete future).
1851    struct FutureTrackingCaller<F> {
1852        #[pin]
1853        future: F,
1854    }
1855}
1856
1857impl<T, F: Future<Output = Result<T, String>>> Future for FutureTrackingCaller<F> {
1858    type Output = T;
1859
1860    #[track_caller]
1861    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1862        match ready!(self.as_mut().project().future.poll(cx)) {
1863            Ok(v) => Poll::Ready(v),
1864            Err(e) => panic!("{}", e),
1865        }
1866    }
1867}
1868
1869pin_project_lite::pin_project! {
1870    // A future that first awaits the first future, then the second, propagating caller info.
1871    //
1872    // See [`FutureTrackingCaller`] for context.
1873    struct ChainedFuture<F1: Future<Output = ()>, F2: Future<Output = ()>> {
1874        #[pin]
1875        first: F1,
1876        #[pin]
1877        second: F2,
1878        first_done: bool,
1879    }
1880}
1881
1882impl<F1: Future<Output = ()>, F2: Future<Output = ()>> Future for ChainedFuture<F1, F2> {
1883    type Output = ();
1884
1885    #[track_caller]
1886    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1887        if !self.first_done {
1888            ready!(self.as_mut().project().first.poll(cx));
1889            *self.as_mut().project().first_done = true;
1890        }
1891
1892        self.as_mut().project().second.poll(cx)
1893    }
1894}
1895
1896impl<T> SimReceiver<T, NoOrder, ExactlyOnce> {
1897    /// Receives the next `n` messages, sorted, and then asserts that the stream ends (like
1898    /// [`SimReceiver::assert_no_more`], forking the search in exhaustive mode). If the
1899    /// simulation becomes quiescent before `n` messages arrive, the test fails.
1900    ///
1901    /// Unlike [`collect_n`](SimReceiver::collect_n) on ordered streams, there is no variant
1902    /// of this API that skips the end-of-stream check. On an unordered stream, the set of
1903    /// messages that arrives *first* is not well-defined, so observing a strict prefix of
1904    /// the output would be sensitive to arrival orders that the simulator does not explore
1905    /// (delivery into the port is FIFO, with no ordering hook); sorting normalizes the
1906    /// permutation of the received messages, but not the choice of *subset*. The quiescence
1907    /// check makes the observation sound: it proves the `n` messages are *all* the messages
1908    /// the program can produce from the input so far, a set which does not depend on
1909    /// arrival order.
1910    pub async fn collect_n_sorted_only<C: Default + Extend<T> + AsMut<[T]>>(self, n: usize) -> C
1911    where
1912        T: Debug + Ord,
1913    {
1914        let out = FutureTrackingCaller {
1915            future: async move {
1916                let mut out = C::default();
1917                for i in 0..n {
1918                    // Like `next`, waiting for each message is safe mid-test; the taint on a
1919                    // forced `None` is unobservable because the test fails below.
1920                    if let Some(v) = self.try_next_impl().await {
1921                        out.extend([v]);
1922                    } else {
1923                        return Err(format!(
1924                            "Stream ended (simulation quiescent) after {} messages, but {} were expected",
1925                            i, n
1926                        ));
1927                    }
1928                }
1929                out.as_mut().sort();
1930                Ok(out)
1931            },
1932        }
1933        .await;
1934        self.assert_no_more().await;
1935        out
1936    }
1937
1938    /// Receives the next message, and then asserts that the stream ends (like
1939    /// [`SimReceiver::assert_no_more`], forking the search in exhaustive mode). If the
1940    /// simulation becomes quiescent without producing a message, the test fails.
1941    ///
1942    /// This is a shortcut for [`Self::collect_n_sorted_only`] with `n = 1`. Unlike
1943    /// [`next`](SimReceiver::next) on ordered streams, there is no variant that skips the
1944    /// end-of-stream check, because on an unordered stream *which* message arrives first is
1945    /// not well-defined; the check proves the message is the *only* one the program can
1946    /// produce from the input so far.
1947    pub async fn next_only(self) -> T
1948    where
1949        T: Debug + Ord,
1950    {
1951        let mut out: Vec<T> = self.collect_n_sorted_only(1).await;
1952        out.remove(0)
1953    }
1954
1955    /// Collects all remaining messages from the simulation output stream into a collection,
1956    /// sorting them. This will wait until no more messages can possibly arrive.
1957    ///
1958    /// If this has to force pending nondeterministic work to run, it should be the last
1959    /// observation of the test; see [`collect`](SimReceiver::collect).
1960    pub async fn collect_sorted<C: Default + Extend<T> + AsMut<[T]>>(self) -> C
1961    where
1962        T: Ord,
1963    {
1964        let mut collected = C::default();
1965        while let Some(v) = self.try_next_impl().await {
1966            collected.extend([v]);
1967        }
1968        collected.as_mut().sort();
1969        collected
1970    }
1971
1972    /// Asserts that the stream yields exactly the expected sequence of messages, in some order.
1973    /// This does not check that the stream ends, use [`Self::assert_yields_only_unordered`] for that.
1974    ///
1975    /// Like [`SimReceiver::next`], this is safe to use in the middle of a test.
1976    pub fn assert_yields_unordered<T2: Debug, I: IntoIterator<Item = T2>>(
1977        &self,
1978        expected: I,
1979    ) -> impl use<'_, T, T2, I> + Future<Output = ()>
1980    where
1981        T: Debug + PartialEq<T2>,
1982    {
1983        FutureTrackingCaller {
1984            future: async {
1985                let mut expected: Vec<T2> = expected.into_iter().collect();
1986
1987                while !expected.is_empty() {
1988                    // Like `next`, waiting for each expected message is safe mid-test; the
1989                    // taint on a forced `None` is unobservable because the test fails below.
1990                    if let Some(next) = self.try_next_impl().await {
1991                        let idx = expected.iter().enumerate().find(|(_, e)| &next == *e);
1992                        if let Some((i, _)) = idx {
1993                            expected.swap_remove(i);
1994                        } else {
1995                            return Err(format!("Stream yielded unexpected message: {:?}", next));
1996                        }
1997                    } else {
1998                        return Err(format!(
1999                            "Stream ended early, still expected: {:?}",
2000                            expected
2001                        ));
2002                    }
2003                }
2004
2005                Ok(())
2006            },
2007        }
2008    }
2009
2010    /// Asserts that the stream yields only the expected sequence of messages, in some order,
2011    /// and then ends (like [`Self::assert_no_more`], forking the search in exhaustive mode).
2012    pub fn assert_yields_only_unordered<T2: Debug, I: IntoIterator<Item = T2>>(
2013        &self,
2014        expected: I,
2015    ) -> impl use<'_, T, T2, I> + Future<Output = ()>
2016    where
2017        T: Debug + PartialEq<T2>,
2018    {
2019        ChainedFuture {
2020            first: self.assert_yields_unordered(expected),
2021            second: self.assert_no_more(),
2022            first_done: false,
2023        }
2024    }
2025}
2026
2027impl<T, O: Ordering, R: Retries> SimSender<T, O, R> {
2028    fn with_sink<Out>(&self, thunk: impl FnOnce(&dyn Fn(T)) -> Out) -> Out {
2029        let (sender, quiescence) = CURRENT_SIM_CONNECTIONS.with(|connections| {
2030            let connections = connections.borrow();
2031            (
2032                connections
2033                    .input_senders
2034                    .get(connections.external_registered.get(&self.0).unwrap())
2035                    .unwrap()
2036                    .clone(),
2037                connections.quiescence.clone(),
2038            )
2039        });
2040
2041        let encode = self.2;
2042        thunk(&move |t| {
2043            sender.try_send(encode(&t).into()).unwrap();
2044            quiescence.resume();
2045        })
2046    }
2047}
2048
2049impl<T, O: Ordering> SimSender<T, O, ExactlyOnce> {
2050    /// Sends several messages to the simulation input. The messages will be asynchronously
2051    /// processed as part of the simulation, in non-deterministic order.
2052    pub fn send_many_unordered<I: IntoIterator<Item = T>>(&self, iter: I) {
2053        self.with_sink(|send| {
2054            for t in iter {
2055                send(t);
2056            }
2057        })
2058    }
2059}
2060
2061impl<T> SimSender<T, TotalOrder, ExactlyOnce> {
2062    /// Sends a message to the simulation input. The message will be asynchronously processed
2063    /// as part of the simulation.
2064    pub fn send(&self, t: T) {
2065        self.with_sink(|send| send(t));
2066    }
2067
2068    /// Sends several messages to the simulation input. The messages will be asynchronously
2069    /// processed as part of the simulation.
2070    pub fn send_many<I: IntoIterator<Item = T>>(&self, iter: I) {
2071        self.with_sink(|send| {
2072            for t in iter {
2073                send(t);
2074            }
2075        })
2076    }
2077}
2078
2079impl<T, O: Ordering, R: Retries> Clone for SimClusterReceiver<T, O, R> {
2080    fn clone(&self) -> Self {
2081        *self
2082    }
2083}
2084
2085impl<T, O: Ordering, R: Retries> Copy for SimClusterReceiver<T, O, R> {}
2086
2087impl<T, O: Ordering, R: Retries> SimClusterReceiver<T, O, R> {
2088    fn member_connections(
2089        &self,
2090        member_id: u32,
2091    ) -> (Rc<Mutex<UnsyncReceiver<Bytes>>>, Rc<QuiescenceState>) {
2092        CURRENT_SIM_CONNECTIONS.with(|connections| {
2093            let connections = connections.borrow();
2094            let port = connections.external_registered.get(&self.0).unwrap();
2095            let receivers = connections.cluster_output_receivers.get(port).unwrap();
2096            (
2097                receivers[&member_id].clone(),
2098                connections.quiescence.clone(),
2099            )
2100        })
2101    }
2102
2103    /// See [`try_next_bytes`].
2104    async fn try_next_impl(&self, member_id: u32) -> Option<T> {
2105        let (receiver, quiescence) = self.member_connections(member_id);
2106        try_next_bytes(&receiver, &quiescence)
2107            .await
2108            .map(|bytes| (self.2)(&bytes))
2109    }
2110
2111    /// Asserts that the stream from a specific cluster member has ended and no more messages
2112    /// can possibly arrive.
2113    ///
2114    /// If the check cannot be answered without running pending nondeterministic work (such
2115    /// as ticks with buffered inputs):
2116    /// - Under [`CompiledSim::exhaustive`], the search forks: one instance performs the
2117    ///   check and ends there, while sibling instances skip the check and continue.
2118    /// - In other modes, the pending work runs; afterwards, sending more input and then
2119    ///   attempting to receive output will panic.
2120    pub fn assert_no_more(self, member_id: u32) -> impl Future<Output = ()>
2121    where
2122        T: Debug,
2123    {
2124        QuiescenceCheckFuture::new(FutureTrackingCaller {
2125            future: async move {
2126                if let Some(next) = self.try_next_impl(member_id).await {
2127                    return Err(format!(
2128                        "Stream yielded unexpected message: {:?}, expected termination",
2129                        next
2130                    ));
2131                }
2132                Ok(())
2133            },
2134        })
2135    }
2136}
2137
2138impl<T> SimClusterReceiver<T, TotalOrder, ExactlyOnce> {
2139    /// Receives the next value from a specific cluster member, waiting (and letting the
2140    /// scheduler run any pending simulation work) until one is available. If the simulation
2141    /// becomes quiescent without producing a value, the test fails.
2142    ///
2143    /// This is safe to use in the middle of a test; to observe the *absence* of a value,
2144    /// use [`Self::try_next`].
2145    pub fn next(&self, member_id: u32) -> impl use<'_, T> + Future<Output = T> {
2146        // See `SimReceiver::next` for why waiting for a value never "overruns" the
2147        // simulation.
2148        FutureTrackingCaller {
2149            future: async move {
2150                self.try_next_impl(member_id).await.ok_or_else(|| {
2151                    "Stream ended (simulation quiescent), but another message was expected"
2152                        .to_owned()
2153                })
2154            },
2155        }
2156    }
2157
2158    /// Receives the next value from a specific cluster member, or returns `None` if no more
2159    /// values can possibly arrive.
2160    ///
2161    /// If answering requires forcing pending nondeterministic work to run, then afterwards,
2162    /// sending more input and then attempting to receive output will panic. Prefer
2163    /// [`Self::next`] when possible.
2164    pub async fn try_next(&self, member_id: u32) -> Option<T> {
2165        self.try_next_impl(member_id).await
2166    }
2167
2168    /// Collects all remaining values from a specific cluster member into a collection,
2169    /// waiting until no more values can possibly arrive.
2170    ///
2171    /// If this has to force pending nondeterministic work to run, it should be the last
2172    /// observation of the test; see [`SimReceiver::collect`].
2173    pub async fn collect<C: Default + Extend<T>>(self, member_id: u32) -> C {
2174        let mut out = C::default();
2175        while let Some(v) = self.try_next_impl(member_id).await {
2176            out.extend([v]);
2177        }
2178        out
2179    }
2180}
2181
2182impl<T> SimClusterReceiver<T, NoOrder, ExactlyOnce> {
2183    /// Receives the next `n` values from a specific cluster member, sorted, and then
2184    /// asserts that the stream ends (like [`Self::assert_no_more`], forking the search in
2185    /// exhaustive mode). If the simulation becomes quiescent before `n` values arrive, the
2186    /// test fails.
2187    ///
2188    /// There is no variant of this API that skips the end-of-stream check; see
2189    /// [`SimReceiver::collect_n_sorted_only`] for why observing a strict prefix of an
2190    /// unordered stream would be unsound.
2191    pub async fn collect_n_sorted_only<C: Default + Extend<T> + AsMut<[T]>>(
2192        self,
2193        member_id: u32,
2194        n: usize,
2195    ) -> C
2196    where
2197        T: Debug + Ord,
2198    {
2199        let out = FutureTrackingCaller {
2200            future: async move {
2201                let mut out = C::default();
2202                for i in 0..n {
2203                    // Like `SimReceiver::next`, waiting for each message is safe mid-test;
2204                    // the taint on a forced `None` is unobservable because the test fails
2205                    // below.
2206                    if let Some(v) = self.try_next_impl(member_id).await {
2207                        out.extend([v]);
2208                    } else {
2209                        return Err(format!(
2210                            "Stream ended (simulation quiescent) after {} messages, but {} were expected",
2211                            i, n
2212                        ));
2213                    }
2214                }
2215                out.as_mut().sort();
2216                Ok(out)
2217            },
2218        }
2219        .await;
2220        self.assert_no_more(member_id).await;
2221        out
2222    }
2223
2224    /// Receives the next value from a specific cluster member, and then asserts that the
2225    /// stream ends (like [`Self::assert_no_more`], forking the search in exhaustive mode).
2226    /// If the simulation becomes quiescent without producing a value, the test fails.
2227    ///
2228    /// This is a shortcut for [`Self::collect_n_sorted_only`] with `n = 1`; see
2229    /// [`SimReceiver::next_only`] for why there is no variant that skips the end-of-stream
2230    /// check.
2231    pub async fn next_only(self, member_id: u32) -> T
2232    where
2233        T: Debug + Ord,
2234    {
2235        let mut out: Vec<T> = self.collect_n_sorted_only(member_id, 1).await;
2236        out.remove(0)
2237    }
2238
2239    /// Collects all remaining values from a specific cluster member, sorted, waiting until no
2240    /// more values can possibly arrive.
2241    ///
2242    /// If this has to force pending nondeterministic work to run, it should be the last
2243    /// observation of the test; see [`SimReceiver::collect`].
2244    pub async fn collect_sorted<C: Default + Extend<T> + AsMut<[T]>>(self, member_id: u32) -> C
2245    where
2246        T: Ord,
2247    {
2248        let mut collected = C::default();
2249        while let Some(v) = self.try_next_impl(member_id).await {
2250            collected.extend([v]);
2251        }
2252        collected.as_mut().sort();
2253        collected
2254    }
2255}
2256
2257impl<T, O: Ordering, R: Retries> SimClusterSender<T, O, R> {
2258    fn with_sink<Out>(&self, thunk: impl FnOnce(&dyn Fn(u32, T)) -> Out) -> Out {
2259        let (senders, quiescence) = CURRENT_SIM_CONNECTIONS.with(|connections| {
2260            let connections = connections.borrow();
2261            (
2262                connections
2263                    .cluster_input_senders
2264                    .get(connections.external_registered.get(&self.0).unwrap())
2265                    .unwrap()
2266                    .clone(),
2267                connections.quiescence.clone(),
2268            )
2269        });
2270
2271        let encode = self.2;
2272        thunk(&move |member_id: u32, t: T| {
2273            senders[&member_id].try_send(encode(&t).into()).unwrap();
2274            quiescence.resume();
2275        })
2276    }
2277}
2278
2279impl<T, O: Ordering> SimClusterSender<T, O, ExactlyOnce> {
2280    /// Sends multiple values to specific cluster members. The messages will be asynchronously
2281    /// processed as part of the simulation, in non-deterministic order.
2282    pub fn send_many_unordered<I: IntoIterator<Item = (u32, T)>>(&self, iter: I) {
2283        self.with_sink(|send| {
2284            for (member_id, t) in iter {
2285                send(member_id, t);
2286            }
2287        })
2288    }
2289}
2290
2291impl<T> SimClusterSender<T, TotalOrder, ExactlyOnce> {
2292    /// Sends a value to a specific cluster member.
2293    pub fn send(&self, member_id: u32, t: T) {
2294        self.with_sink(|send| send(member_id, t));
2295    }
2296
2297    /// Sends multiple values to specific cluster members.
2298    pub fn send_many<I: IntoIterator<Item = (u32, T)>>(&self, iter: I) {
2299        self.with_sink(|send| {
2300            for (member_id, t) in iter {
2301                send(member_id, t);
2302            }
2303        })
2304    }
2305}
2306
2307enum LogKind<W: std::io::Write> {
2308    Null,
2309    Stderr,
2310    Custom(W),
2311}
2312
2313// via https://www.reddit.com/r/rust/comments/t69sld/is_there_a_way_to_allow_either_stdfmtwrite_or/
2314impl<W: std::io::Write> std::fmt::Write for LogKind<W> {
2315    fn write_str(&mut self, s: &str) -> Result<(), std::fmt::Error> {
2316        match self {
2317            LogKind::Null => Ok(()),
2318            LogKind::Stderr => {
2319                eprint!("{}", s);
2320                Ok(())
2321            }
2322            LogKind::Custom(w) => w.write_all(s.as_bytes()).map_err(|_| std::fmt::Error),
2323        }
2324    }
2325}
2326
2327/// A tick-scoped DFIR together with the hooks that feed it data.
2328struct SimTick {
2329    /// The tick's location, used to match this tick to an outstanding script group.
2330    location: LocationId,
2331    /// The location of the process/cluster the tick lives on, used to match this tick
2332    /// against the async DFIR that produces its input data.
2333    parent_location: LocationId,
2334    /// The cluster member ID, if the tick lives on a cluster.
2335    cluster_id: Option<u32>,
2336    /// The tick DFIR, executed once per tick.
2337    dfir: DfirErased<()>,
2338    /// Hooks (e.g. from `batch`) resolved *before* the tick runs, deciding what data to
2339    /// release into it.
2340    hooks: Vec<Box<dyn TickInputHook>>,
2341    /// Scripted hooks (bound to test-side handles), also resolved before the tick runs.
2342    /// Kept separate from `hooks` so the scheduler can apply the script-specific rules
2343    /// (the boundary scan and `blocks_tick`), and shared (`Rc`) with the per-instance
2344    /// registry that test-side handles resolve through (see [`ScriptedRuntimeHook`]).
2345    scripted_hooks: Vec<Rc<RefCell<dyn ScriptedTickInputHook>>>,
2346    /// Hooks (e.g. from `assume_ordering` inside the tick) resolved *while* the tick DFIR
2347    /// is running, via a `tokio::select!` loop, for operators that block on ordering
2348    /// decisions mid-tick.
2349    inline_hooks: Vec<Box<dyn InlineHook>>,
2350    scripted_inline_hooks: Vec<Rc<RefCell<dyn crate::sim::runtime::ScriptedInlineHook>>>,
2351}
2352
2353impl SimTick {
2354    /// Whether the scheduler can execute this tick right now.
2355    fn can_run(&self) -> bool {
2356        // No scripted hook may have a queued decision that is not yet honorable
2357        // (such a decision names this tick's *next* execution, so the tick must wait
2358        // until it can be honored in full)...
2359        !self
2360            .scripted_hooks
2361            .iter()
2362            .any(|hook| hook.borrow().blocks_tick())
2363            // ...and at least one hook must be able to trigger the tick.
2364            && (self.hooks.iter().any(|hook| hook.can_trigger_tick())
2365                || self
2366                    .scripted_hooks
2367                    .iter()
2368                    .any(|hook| hook.borrow().can_trigger_tick()))
2369    }
2370}
2371
2372/// A single top-level hook (e.g. from `assume_ordering` on a non-tick stream) that needs
2373/// scheduling decisions, but has no tick DFIR to execute. The scheduler just resolves the
2374/// hook.
2375///
2376/// Each top-level hook is its own observation ("its own virtual tick"), even when several
2377/// hooks live at the same location: unlike a tick's hooks, which one atomic tick
2378/// execution consumes together, co-located top-level hooks are causally independent
2379/// operators, so resolving them jointly would only couple their decisions. Grouping them
2380/// would both add redundant schedules (releasing jointly is equivalent to releasing in
2381/// consecutive steps, which is explored anyway) and *lose* schedules for hook kinds whose
2382/// decisions always release when resolved (a fold could never stay silent while a
2383/// co-located sibling acts). With one hook per observation, "act" and "stay silent" are
2384/// expressed purely by the scheduler picking or not picking the observation, and a picked
2385/// observation always makes a nontrivial decision.
2386struct SimObservation {
2387    /// The top-level location, used to match this observation against the async DFIR that
2388    /// produces its input data (and, for a scripted hook, against an outstanding script
2389    /// group).
2390    location: LocationId,
2391    /// The cluster member ID, if the location is a cluster.
2392    cluster_id: Option<u32>,
2393    /// The hook resolved when the scheduler selects this observation.
2394    hook: ObservationSlot,
2395}
2396
2397/// The single hook of a [`SimObservation`]: either an ordinary autonomous hook, or a
2398/// scripted hook (bound to a test-side handle), tagged with its hook ID so a script group
2399/// can be matched to exactly this observation.
2400enum ObservationSlot {
2401    /// An ordinary autonomous hook, owned by the scheduler.
2402    Unscripted { hook: Box<dyn ObservationHook> },
2403    /// A hook bound to a test-side handle, shared (`Rc`) with the per-instance registry.
2404    Scripted {
2405        /// The bound handle's ID, used to match a script group to this observation.
2406        hook_id: usize,
2407        hook: Rc<RefCell<dyn ScriptedObservationHook>>,
2408    },
2409}
2410
2411impl SimObservation {
2412    /// Whether the scheduler can resolve this observation's hook right now.
2413    fn can_run(&self) -> bool {
2414        match &self.hook {
2415            // Running an observation *is* releasing, so it is runnable whenever its hook
2416            // can release something.
2417            ObservationSlot::Unscripted { hook } => hook.can_release(),
2418            ObservationSlot::Scripted { hook, .. } => hook.borrow().can_fire(),
2419        }
2420    }
2421}
2422
2423/// A running simulation, which manages the async DFIRs, tick DFIRs, and hook-based
2424/// scheduling decisions for non-deterministic operators like `batch` and `assume_ordering`.
2425///
2426/// This struct holds all simulator state across scheduler steps. Each [`Self::step`] performs
2427/// one of three kinds of work:
2428/// - **Async DFIRs**: long-running top-level dataflows (one per process/cluster member) that
2429///   produce data consumed by ticks and observations.
2430/// - **Ticks**: tick-scoped DFIRs that execute a single tick. Before running, their associated
2431///   hooks (e.g. from `batch`) are resolved to decide what data to release into the tick.
2432/// - **Observations**: top-level locations that have hooks (e.g. from `assume_ordering` on a
2433///   non-tick stream) needing decisions, but no tick DFIR to execute. The scheduler just
2434///   resolves their hooks.
2435struct LaunchedSim<W: std::io::Write> {
2436    /// Top-level async DFIRs, one per process/cluster member. These run continuously and
2437    /// produce data that feeds into ticks and observations.
2438    async_dfirs: Vec<(LocationId, Option<u32>, DfirErased<()>)>,
2439    /// Ticks whose parent async DFIR has made progress, so they may be ready to run.
2440    /// The scheduler further filters these by checking whether their hooks have pending decisions.
2441    possibly_ready_ticks: Vec<SimTick>,
2442    /// Ticks whose parent async DFIR has not yet made progress since they were last checked.
2443    not_ready_ticks: Vec<SimTick>,
2444    /// The tick owned by the one sealed, outstanding scripted decision group. It is kept
2445    /// outside the ordinary ready lists until it executes and consumes that group.
2446    current_scripted_tick: Option<SimTick>,
2447    current_scripted_observation: Option<SimObservation>,
2448    /// Coordinates the decision group shared with test-side hook handles.
2449    script_coordinator: Rc<RefCell<ScriptCoordinator>>,
2450    /// Observations whose async DFIR has made progress, so their hooks may have decisions
2451    /// to resolve.
2452    possibly_ready_observations: Vec<SimObservation>,
2453    /// Observations whose async DFIR has not yet made progress since they were last checked.
2454    not_ready_observations: Vec<SimObservation>,
2455    log: LogKind<W>,
2456    /// Represents quiescence state of the simulation.
2457    quiescence: Rc<QuiescenceState>,
2458    /// When true, this simulation runs in deterministic mode: no fuzzer entropy is ever
2459    /// drawn, every unsafe operator with meaningful input must be scripted, and at most
2460    /// one tick is ever runnable (see `SimFlow::deterministic`).
2461    deterministic: bool,
2462}
2463
2464impl<W: std::io::Write> LaunchedSim<W> {
2465    /// Runs a single step of the simulation scheduler.
2466    ///
2467    /// A step first advances all async DFIRs; if none of them made progress, it instead runs
2468    /// one ready tick or resolves one ready observation. If nothing at all can make progress,
2469    /// the simulation is quiescent: this signals waiting receivers and returns; the driver is
2470    /// responsible for parking until new external input arrives (see
2471    /// [`QuiescenceState::resumed`]).
2472    ///
2473    /// This future is always awaited to completion by the driver, so a step is atomic: user
2474    /// code never runs (and never observes intermediate state) while a step is in flight.
2475    async fn step(&mut self) {
2476        // A group remains joinable only while the test body is in the same synchronous poll
2477        // that created it. Starting any scheduler step seals it and moves its tick out of
2478        // the ordinary lists exactly once; `Some(current)` then means that tick exclusively
2479        // owns the one outstanding group until it executes.
2480        let outstanding_target = {
2481            let mut coordinator = self.script_coordinator.borrow_mut();
2482            coordinator.current.as_mut().map(|group| {
2483                group.sealed = true;
2484                group.target.clone()
2485            })
2486        };
2487        match outstanding_target {
2488            Some(ScriptTarget::Tick {
2489                location:
2490                    SimLocation {
2491                        location: group_location,
2492                        cluster_id: group_cluster_id,
2493                    },
2494            }) => {
2495                abort_assert!(
2496                    self.current_scripted_observation.is_none(),
2497                    "scripted observation remained active for a tick group"
2498                );
2499                if self.current_scripted_tick.is_none() {
2500                    let matches_group = |tick: &SimTick| {
2501                        tick.location == group_location && tick.cluster_id == group_cluster_id
2502                    };
2503                    self.current_scripted_tick = self
2504                        .possibly_ready_ticks
2505                        .iter()
2506                        .position(matches_group)
2507                        .map(|index| self.possibly_ready_ticks.swap_remove(index))
2508                        .or_else(|| {
2509                            self.not_ready_ticks
2510                                .iter()
2511                                .position(matches_group)
2512                                .map(|index| self.not_ready_ticks.swap_remove(index))
2513                        });
2514                }
2515                let tick = self.current_scripted_tick.as_ref().unwrap();
2516                abort_assert!(
2517                    tick.location == group_location && tick.cluster_id == group_cluster_id,
2518                    "outstanding scripted group changed before its tick executed"
2519                );
2520            }
2521            Some(ScriptTarget::Observation {
2522                location:
2523                    SimLocation {
2524                        location: group_location,
2525                        cluster_id: group_cluster_id,
2526                    },
2527                hook_id,
2528            }) => {
2529                abort_assert!(
2530                    self.current_scripted_tick.is_none(),
2531                    "scripted tick remained active for an observation group"
2532                );
2533                if self.current_scripted_observation.is_none() {
2534                    let matches_group = |observation: &SimObservation| {
2535                        observation.location == group_location
2536                            && observation.cluster_id == group_cluster_id
2537                            && matches!(observation.hook, ObservationSlot::Scripted { hook_id: id, .. } if id == hook_id)
2538                    };
2539                    self.current_scripted_observation = self
2540                        .possibly_ready_observations
2541                        .iter()
2542                        .position(matches_group)
2543                        .map(|index| self.possibly_ready_observations.swap_remove(index))
2544                        .or_else(|| {
2545                            self.not_ready_observations
2546                                .iter()
2547                                .position(matches_group)
2548                                .map(|index| self.not_ready_observations.swap_remove(index))
2549                        });
2550                }
2551                abort_assert!(
2552                    self.current_scripted_observation.is_some(),
2553                    "outstanding scripted group did not match an observation"
2554                );
2555            }
2556            None => abort_assert!(
2557                self.current_scripted_tick.is_none() && self.current_scripted_observation.is_none(),
2558                "scripted action remained active without an outstanding group"
2559            ),
2560        }
2561
2562        let mut any_made_progress = false;
2563        for (loc, c_id, dfir) in &mut self.async_dfirs {
2564            if dfir.run_tick().await {
2565                any_made_progress = true;
2566
2567                // This async DFIR may have produced new data, so the ticks and observations
2568                // it feeds may now be ready.
2569                self.possibly_ready_ticks
2570                    .extend(self.not_ready_ticks.extract_if(.., |tick| {
2571                        tick.parent_location == *loc && tick.cluster_id == *c_id
2572                    }));
2573                self.possibly_ready_observations.extend(
2574                    self.not_ready_observations
2575                        .extract_if(.., |obs| obs.location == *loc && obs.cluster_id == *c_id),
2576                );
2577            }
2578        }
2579
2580        if any_made_progress {
2581            return;
2582        }
2583
2584        // The **boundary scan**: the async dataflows have stopped making progress and we
2585        // are about to consider running ticks — the first moment where a missing scripted
2586        // decision could influence what happens next. Check ticks exposed by async progress,
2587        // plus the active scripted tick (which lives outside the ordinary ready lists).
2588        for tick in self
2589            .possibly_ready_ticks
2590            .iter()
2591            .chain(self.current_scripted_tick.iter())
2592        {
2593            for hook in &tick.scripted_hooks {
2594                if let Err(message) = hook.borrow().boundary_check() {
2595                    panic!("{}", message);
2596                }
2597            }
2598        }
2599
2600        for observation in self
2601            .possibly_ready_observations
2602            .iter()
2603            .chain(self.current_scripted_observation.iter())
2604        {
2605            if let ObservationSlot::Scripted { hook, .. } = &observation.hook
2606                && let Err(message) = hook.borrow().boundary_check()
2607            {
2608                panic!("{}", message);
2609            }
2610        }
2611
2612        // A fully scripted tick needs at least one decision that can eventually trigger
2613        // it. There is exactly one outstanding group, so only its owned tick can contain
2614        // a newly installed group in which no decision can trigger.
2615        if let Some(tick) = &self.current_scripted_tick
2616            && tick.hooks.is_empty()
2617        {
2618            let has_pending_decision = tick
2619                .scripted_hooks
2620                .iter()
2621                .any(|hook| hook.borrow().has_decision());
2622            let any_pending_decision_can_eventually_trigger =
2623                tick.scripted_hooks.iter().any(|hook| {
2624                    let hook = hook.borrow();
2625                    // A decision that is not yet honorable may become honorable and
2626                    // trigger once more data arrives, so it does not fail this check.
2627                    hook.has_decision() && (hook.blocks_tick() || hook.can_trigger_tick())
2628                });
2629
2630            if has_pending_decision && !any_pending_decision_can_eventually_trigger {
2631                let mut details = String::new();
2632                let member = tick
2633                    .cluster_id
2634                    .map(|m| format!(" (cluster member {m})"))
2635                    .unwrap_or_default();
2636                for hook in &tick.scripted_hooks {
2637                    let hook = hook.borrow();
2638                    if let Some(decision) = hook.describe_decision() {
2639                        let loc = ScriptedHookControl::location_meta(&*hook).location;
2640                        use std::fmt::Write;
2641                        write!(details, "\n  {} on the hook at {}{}", decision, loc, member)
2642                            .unwrap();
2643                    }
2644                }
2645                panic!(
2646                    "none of the scripted decisions in this group can trigger their tick, so the tick can never run; at least one decision in the group must trigger it:{}",
2647                    details
2648                );
2649            }
2650        }
2651
2652        use bolero::generator::*;
2653
2654        // Send anything that can't make a scheduling decision back to the not-ready lists.
2655        self.not_ready_ticks.extend(
2656            self.possibly_ready_ticks
2657                .extract_if(.., |tick| !tick.can_run()),
2658        );
2659        self.not_ready_observations.extend(
2660            self.possibly_ready_observations
2661                .extract_if(.., |obs| !obs.can_run()),
2662        );
2663
2664        let scripted_tick_runnable = self
2665            .current_scripted_tick
2666            .as_ref()
2667            .is_some_and(SimTick::can_run);
2668        let scripted_observation_runnable = self
2669            .current_scripted_observation
2670            .as_ref()
2671            .is_some_and(SimObservation::can_run);
2672
2673        if self.possibly_ready_ticks.is_empty()
2674            && !scripted_tick_runnable
2675            && !scripted_observation_runnable
2676            && self.possibly_ready_observations.is_empty()
2677        {
2678            // Classify why the outstanding scripted group (if any) is stuck, so the
2679            // suspended test-side await renders the right error: `true` when every
2680            // queued decision is satisfiable but none can trigger the tick — given
2681            // quiescence, no unscripted input on the tick can trigger it either, or the
2682            // tick would be runnable.
2683            self.script_coordinator.borrow_mut().stuck_cannot_trigger =
2684                self.current_scripted_tick.as_ref().is_some_and(|tick| {
2685                    let mut queued = tick
2686                        .scripted_hooks
2687                        .iter()
2688                        .filter(|hook| hook.borrow().has_decision())
2689                        .peekable();
2690                    queued.peek().is_some() && queued.all(|hook| !hook.borrow().blocks_tick())
2691                });
2692
2693            // Signal quiescence, waking receivers waiting for data (their streams end). The
2694            // driver is responsible for parking until new input arrives.
2695            self.quiescence.enter_quiescence();
2696        } else if self.quiescence.pause_nondet.get() > 0 {
2697            // The test is querying whether the simulation can quiesce without
2698            // nondeterministic work (see `SettlePauseGuard::poll_settle`). Report that
2699            // ticks/observations are pending and pause; the driver parks until the test
2700            // decides how to proceed.
2701            self.quiescence.nondet_pending.set(true);
2702            self.quiescence.wake_settled();
2703        } else {
2704            let ordinary_tick_count = self.possibly_ready_ticks.len();
2705            let scripted_tick_index = ordinary_tick_count;
2706            let observation_start = scripted_tick_index + usize::from(scripted_tick_runnable);
2707            let scripted_observation_index =
2708                observation_start + self.possibly_ready_observations.len();
2709            let candidate_count =
2710                scripted_observation_index + usize::from(scripted_observation_runnable);
2711            let next_tick_or_obs = if self.deterministic {
2712                for tick in self.possibly_ready_ticks.iter().chain(
2713                    self.current_scripted_tick
2714                        .iter()
2715                        .filter(|_| scripted_tick_runnable),
2716                ) {
2717                    for hook in &tick.hooks {
2718                        assert!(
2719                            hook.only_one_possible_decision(),
2720                            "{}",
2721                            crate::sim::runtime::render_unhooked_nondet_error(hook.location_meta())
2722                        );
2723                    }
2724                }
2725                for obs in &self.possibly_ready_observations {
2726                    if let ObservationSlot::Unscripted { hook } = &obs.hook
2727                        && !hook.only_one_possible_decision()
2728                    {
2729                        panic!(
2730                            "{}",
2731                            crate::sim::runtime::render_unhooked_nondet_error(hook.location_meta())
2732                        );
2733                    }
2734                }
2735                // Each action on its own may be free of choices, but the order in
2736                // which they run is not determined, and it can be observable.
2737                assert!(
2738                    candidate_count <= 1,
2739                    "deterministic simulation reached a state with more than one runnable tick/observation; the order in which they run is not deterministic\nhelp: script the involved operators so the schedule is explicit, or run under `fuzz` / `exhaustive` instead"
2740                );
2741                0
2742            } else {
2743                (0..candidate_count).any()
2744            };
2745
2746            if next_tick_or_obs < observation_start {
2747                let is_scripted_tick = next_tick_or_obs == scripted_tick_index;
2748                let mut tick = if is_scripted_tick {
2749                    self.current_scripted_tick.take().unwrap()
2750                } else {
2751                    self.possibly_ready_ticks.remove(next_tick_or_obs)
2752                };
2753
2754                match &mut self.log {
2755                    LogKind::Null => {}
2756                    LogKind::Stderr => {
2757                        if let Some(cid) = &tick.cluster_id {
2758                            eprintln!(
2759                                "\n{}",
2760                                format!("Running Tick (Cluster Member {})", cid)
2761                                    .color(colored::Color::Magenta)
2762                                    .bold()
2763                            )
2764                        } else {
2765                            eprintln!("\n{}", "Running Tick".color(colored::Color::Magenta).bold())
2766                        }
2767                    }
2768                    LogKind::Custom(writer) => {
2769                        writeln!(
2770                            writer,
2771                            "\n{}",
2772                            "Running Tick".color(colored::Color::Magenta).bold()
2773                        )
2774                        .unwrap();
2775                    }
2776                }
2777
2778                let mut asterisk_indenter = |_line_no, write: &mut dyn std::fmt::Write| {
2779                    write.write_str(&"*".color(colored::Color::Magenta).bold())?;
2780                    write.write_str(" ")
2781                };
2782
2783                let mut tick_decision_writer = (!matches!(self.log, LogKind::Null)).then(|| {
2784                    indenter::indented(&mut self.log).with_format(indenter::Format::Custom {
2785                        inserter: &mut asterisk_indenter,
2786                    })
2787                });
2788
2789                run_hooks(
2790                    tick_decision_writer.as_mut(),
2791                    &mut tick.hooks,
2792                    &tick.scripted_hooks,
2793                );
2794
2795                let run_tick_future = tick.dfir.run_tick();
2796                if !tick.inline_hooks.is_empty() || !tick.scripted_inline_hooks.is_empty() {
2797                    let mut run_tick_future_pinned = pin!(run_tick_future);
2798                    let deterministic = self.deterministic;
2799
2800                    loop {
2801                        tokio::select! {
2802                            biased;
2803                            r = &mut run_tick_future_pinned => {
2804                                abort_assert!(r, "runnable tick's DFIR run_tick() returned false");
2805                                break;
2806                            }
2807                            () = async {} => {
2808                                  for hook in &tick.scripted_inline_hooks {
2809                                      if hook.borrow().has_pending_input() {
2810                                          let run = hook.borrow_mut().run_decision(
2811                                              tick_decision_writer
2812                                                  .as_mut()
2813                                                  .map(|w| w as &mut dyn std::fmt::Write),
2814                                          );
2815                                          // The error is reported here, on the host side of
2816                                          // the dylib boundary (unwinding across it aborts).
2817                                          if let Err(message) = run {
2818                                              panic!("{}", message);
2819                                          }
2820                                      }
2821                                  }
2822                                  if !tick.inline_hooks.is_empty() {
2823                                      bolero_generator::any::scope::borrow_with(|driver| {
2824                                          for hook in tick.inline_hooks.iter_mut() {
2825                                              if hook.has_pending_input() {
2826                                                  // In deterministic mode there is no fuzzer
2827                                                  // to decide for this operator; it may only
2828                                                  // proceed when exactly one outcome is
2829                                                  // possible.
2830                                                  if deterministic {
2831                                                      assert!(
2832                                                          hook.only_one_possible_decision(),
2833                                                          "{}",
2834                                                          crate::sim::runtime::render_unhooked_nondet_error(
2835                                                              hook.location_meta()
2836                                                          )
2837                                                      );
2838                                                  }
2839                                                  hook.autonomous_decision(driver);
2840                                                  hook.release_decision(
2841                                                      tick_decision_writer
2842                                                          .as_mut()
2843                                                          .map(|w| w as &mut dyn std::fmt::Write),
2844                                                  );
2845                                              }
2846                                          }
2847                                      });
2848                                  }
2849                            }
2850                        }
2851                    }
2852                } else {
2853                    let made_progress = run_tick_future.await;
2854                    abort_assert!(
2855                        made_progress,
2856                        "runnable tick's DFIR run_tick() returned false"
2857                    );
2858                }
2859
2860                if is_scripted_tick {
2861                    for hook in &tick.scripted_inline_hooks {
2862                        abort_assert!(
2863                            !hook.borrow().has_decision(),
2864                            "tick completed without consuming a scripted inline decision"
2865                        );
2866                    }
2867                    let group = self.script_coordinator.borrow_mut().current.take();
2868                    abort_assert!(
2869                        group.is_some(),
2870                        "scripted tick executed without an outstanding group"
2871                    );
2872                }
2873                self.possibly_ready_ticks.push(tick);
2874            } else {
2875                let is_scripted_observation = next_tick_or_obs == scripted_observation_index;
2876                let observation = if is_scripted_observation {
2877                    self.current_scripted_observation.as_mut().unwrap()
2878                } else {
2879                    &mut self.possibly_ready_observations[next_tick_or_obs - observation_start]
2880                };
2881                let log_writer = (!matches!(self.log, LogKind::Null)).then_some(&mut self.log);
2882                match &mut observation.hook {
2883                    ObservationSlot::Unscripted { hook } => {
2884                        run_observation_hook(log_writer, &mut **hook);
2885                    }
2886                    ObservationSlot::Scripted { hook, .. } => {
2887                        abort_assert!(
2888                            hook.borrow().can_fire(),
2889                            "scripted observation ran without a releasing decision"
2890                        );
2891                        hook.borrow_mut()
2892                            .run_decision(log_writer.map(|w| w as &mut dyn std::fmt::Write));
2893                    }
2894                }
2895                if is_scripted_observation {
2896                    let group = self.script_coordinator.borrow_mut().current.take();
2897                    abort_assert!(group.is_some(), "scripted observation ran without a group");
2898                    let observation = self.current_scripted_observation.take().unwrap();
2899                    self.possibly_ready_observations.push(observation);
2900                }
2901            }
2902        }
2903    }
2904}
2905
2906fn run_hooks<W: std::fmt::Write>(
2907    mut tick_decision_writer: Option<&mut W>,
2908    hooks: &mut [Box<dyn TickInputHook>],
2909    scripted_hooks: &[Rc<RefCell<dyn ScriptedTickInputHook>>],
2910) {
2911    // Scripted hooks own and release their decisions without entropy. Run them completely
2912    // before considering regular hooks; only regular hooks need a Bolero driver.
2913    let mut made_triggering_decision = false;
2914    for hook in scripted_hooks {
2915        let mut hook = hook.borrow_mut();
2916        // Whether a scripted decision triggers is known before running it.
2917        made_triggering_decision |= hook.can_trigger_tick();
2918        hook.run_decision(
2919            tick_decision_writer
2920                .as_deref_mut()
2921                .map(|w| w as &mut dyn std::fmt::Write),
2922        );
2923    }
2924
2925    if !hooks.is_empty() {
2926        let mut decided = vec![false; hooks.len()];
2927        // Snapshot hooks never trigger ([`TickInputHook::can_trigger_tick`] is false), so
2928        // forcing must land on a hook that *can* trigger: track how many undecided hooks
2929        // remain capable of triggering, and force the last one when nothing has triggered.
2930        let can_trigger: Vec<bool> = hooks.iter().map(|hook| hook.can_trigger_tick()).collect();
2931        let mut remaining_trigger_capable = can_trigger.iter().filter(|&&c| c).count();
2932        bolero::generator::bolero_generator::any::scope::borrow_with(|driver| {
2933            // First, resolve every hook that faces no choice (its decision consumes no
2934            // entropy). Doing this before the second pass lets the final undecided hook
2935            // that can trigger be forced to do so when no earlier hook made a triggering
2936            // decision.
2937            for ((hook, decided), can_trigger) in
2938                hooks.iter_mut().zip(decided.iter_mut()).zip(&can_trigger)
2939            {
2940                if hook.only_one_possible_decision() {
2941                    // The no-choice decision can still trigger the tick (the passthrough
2942                    // singleton always releases the latest value), so its result counts.
2943                    made_triggering_decision |= hook.autonomous_decision(driver, false);
2944                    *decided = true;
2945                    remaining_trigger_capable -= usize::from(*can_trigger);
2946                }
2947            }
2948
2949            for ((hook, decided), can_trigger) in
2950                hooks.iter_mut().zip(decided.iter()).zip(&can_trigger)
2951            {
2952                if !decided {
2953                    let force_trigger =
2954                        *can_trigger && !made_triggering_decision && remaining_trigger_capable == 1;
2955                    made_triggering_decision |= hook.autonomous_decision(driver, force_trigger);
2956                    remaining_trigger_capable -= usize::from(*can_trigger);
2957                }
2958
2959                hook.release_decision(
2960                    tick_decision_writer
2961                        .as_deref_mut()
2962                        .map(|w| w as &mut dyn std::fmt::Write),
2963                );
2964            }
2965        });
2966    }
2967
2968    abort_assert!(
2969        made_triggering_decision,
2970        "runnable tick had no hook make a triggering decision"
2971    );
2972}
2973
2974/// Resolves a single unscripted observation hook. The observation was only scheduled
2975/// because it has pending input (running an observation *is* releasing), so its
2976/// autonomous decision must stage a release — running an observation without releasing
2977/// would be a wasted schedule step the exploration must not contain.
2978fn run_observation_hook<W: std::fmt::Write>(
2979    writer: Option<&mut W>,
2980    hook: &mut dyn ObservationHook,
2981) {
2982    bolero::generator::bolero_generator::any::scope::borrow_with(|driver| {
2983        hook.autonomous_decision(driver);
2984    });
2985    // `release_decision` panics if the autonomous decision staged nothing, so a
2986    // contract violation cannot pass silently.
2987    hook.release_decision(writer.map(|w| w as &mut dyn std::fmt::Write));
2988}
2989
2990/// Returns the path of the source file `file`, as [`Location::file`] gives it, or `None` if it
2991/// does not exist. A relative `file` is relative to the workspace root, and `cargo test` runs
2992/// in the crate's directory, so `file` is looked for in `cwd` and each of its parents.
2993fn resolve_source_file(file: &Path, cwd: &Path) -> Option<PathBuf> {
2994    cwd.ancestors()
2995        .map(|dir| dir.join(file))
2996        .find(|candidate| candidate.is_file())
2997}
2998
2999/// Returns the reproducer of a `fuzz` call in `source_file` whose closure has the type name
3000/// `closure_type_name`, or why it cannot be located. It is in `sim-failures` next to the source
3001/// file, named after the function that defines the closure: the type name without its
3002/// `::{{closure}}` suffixes.
3003fn repro_path(
3004    source_file: &Path,
3005    cwd: std::io::Result<PathBuf>,
3006    closure_type_name: &str,
3007) -> Result<PathBuf, String> {
3008    let cwd = cwd.map_err(|error| format!("the current directory cannot be read: {error}"))?;
3009    let source_path = resolve_source_file(source_file, &cwd).ok_or_else(|| {
3010        format!(
3011            "its source file `{}` is not in `{}` or any of that directory's parents",
3012            source_file.display(),
3013            cwd.display(),
3014        )
3015    })?;
3016    let mut fn_path = closure_type_name;
3017    while let Some(outer) = fn_path.strip_suffix("::{{closure}}") {
3018        fn_path = outer;
3019    }
3020    Ok(source_path
3021        .parent()
3022        .unwrap()
3023        .join("sim-failures")
3024        .join(fn_path.replace("::", "__"))
3025        .with_extension("bin"))
3026}
3027
3028#[cfg(test)]
3029mod repro_path_tests {
3030    use std::env::current_dir;
3031    use std::path::Path;
3032
3033    use super::repro_path;
3034
3035    #[test]
3036    fn the_reproducer_is_in_sim_failures_next_to_the_source_file() {
3037        // `file!()` is relative to the workspace root, the parent of the crate directory that
3038        // `cargo test` runs in.
3039        let this_file = current_dir().unwrap().parent().unwrap().join(file!());
3040        assert_eq!(
3041            repro_path(Path::new(file!()), current_dir(), "a::b::{{closure}}"),
3042            Ok(this_file.with_file_name("sim-failures").join("a__b.bin"))
3043        );
3044    }
3045
3046    #[test]
3047    fn a_missing_source_file_is_the_reason() {
3048        let reason = repro_path(
3049            Path::new("hydro_lang/src/sim/missing.rs"),
3050            current_dir(),
3051            "a::{{closure}}",
3052        )
3053        .unwrap_err();
3054        assert!(
3055            reason.starts_with("its source file `hydro_lang/src/sim/missing.rs` is not in"),
3056            "{reason}"
3057        );
3058    }
3059
3060    #[test]
3061    fn a_nested_closure_is_named_after_the_function_that_defines_it() {
3062        let outer = || async || {};
3063        let path = repro_path(
3064            Path::new(file!()),
3065            current_dir(),
3066            std::any::type_name_of_val(&outer()),
3067        )
3068        .unwrap();
3069        assert_eq!(
3070            path.file_name().unwrap(),
3071            "hydro_lang__sim__compiled__repro_path_tests__a_nested_closure_is_named_after_the_function_that_defines_it.bin"
3072        );
3073    }
3074}