Skip to main content

hydro_lang/sim/
flow.rs

1//! Entrypoint for compiling and running Hydro simulations.
2
3use std::cell::RefCell;
4use std::collections::{BTreeMap, HashMap, HashSet};
5use std::panic::RefUnwindSafe;
6use std::rc::Rc;
7
8use dfir_lang::graph::{DfirGraph, FlatGraphBuilder, FlatGraphBuilderOutput};
9use libloading::Library;
10use slotmap::{SecondaryMap, SparseSecondaryMap};
11
12use super::builder::SimBuilder;
13use super::compiled::{CompiledSim, CompiledSimInstance};
14use super::graph::{SimDeploy, SimExternal, SimNode, compile_sim, create_sim_graph_trybuild};
15use crate::compile::builder::StmtId;
16use crate::compile::ir::HydroRoot;
17use crate::location::LocationKey;
18use crate::location::dynamic::LocationId;
19use crate::prelude::Cluster;
20use crate::sim::graph::SimExternalPortRegistry;
21use crate::staging_util::Invariant;
22
23pub(crate) const DEFAULT_FUZZ_MAX_LEN: usize = 4096;
24pub(crate) const DEFAULT_UNIT_FUZZ_ITERATIONS: usize = 8192;
25
26/// A not-yet-compiled simulator for a Hydro program.
27pub struct SimFlow<'a> {
28    pub(crate) ir: Vec<HydroRoot>,
29
30    /// [`SimNode`] for each Process.
31    pub(crate) processes: SparseSecondaryMap<LocationKey, SimNode>,
32    /// [`SimNode`] for each Cluster.
33    pub(crate) clusters: SparseSecondaryMap<LocationKey, SimNode>,
34    /// [`SimExternal`] for each External.
35    pub(crate) externals: SparseSecondaryMap<LocationKey, SimExternal>,
36
37    /// Max size of each cluster.
38    pub(crate) cluster_max_sizes: SparseSecondaryMap<LocationKey, usize>,
39    /// Handle to state handling `external`s' ports.
40    pub(crate) externals_port_registry: Rc<RefCell<SimExternalPortRegistry>>,
41
42    /// The program version each location belongs to (all `0` for a single-version flow). Every
43    /// location has an entry.
44    pub(crate) location_version: SecondaryMap<LocationKey, u32>,
45
46    /// Maps each location to the root key of its cross-version correspondence group: version 0 of
47    /// the same logical location. Every location has an entry (its own key unless it is a
48    /// `next_version` successor); populated eagerly at location creation.
49    pub(crate) location_version_group_root: SecondaryMap<LocationKey, LocationKey>,
50
51    /// When true, the simulator only tests safety properties (not liveness).
52    pub(crate) test_safety_only: bool,
53
54    /// When true, consistency assertions are skipped (treated as identity no-ops).
55    /// When false (default), encountering a consistency assertion panics because
56    /// validating consistency assertions is not yet supported in the simulator.
57    pub(crate) skip_consistency_assertions: bool,
58
59    /// Number of iterations to use for fuzzing, defaults to 8192
60    pub(crate) unit_test_fuzz_iterations: usize,
61
62    /// See [`Self::fuzz_max_len`].
63    pub(crate) fuzz_max_len: usize,
64
65    /// See [`Self::retries_depth`].
66    pub(crate) retries_depth: Option<usize>,
67
68    pub(crate) _phantom: Invariant<'a>,
69}
70
71impl<'a> SimFlow<'a> {
72    /// Sets the maximum size of the given cluster in the simulation.
73    #[must_use]
74    pub fn with_cluster_size<C>(mut self, cluster: &Cluster<'a, C>, max_size: usize) -> Self {
75        self.cluster_max_sizes.insert(cluster.key, max_size);
76        self
77    }
78
79    /// Opts in to safety-only testing, which is required when using
80    /// [`lossy_delayed_forever`](crate::networking::NetworkingConfig::lossy_delayed_forever)
81    /// networking.
82    ///
83    /// The simulator models dropped messages as indefinitely delayed, which means
84    /// it only tests safety properties—not liveness—since messages may never arrive.
85    /// Calling this method acknowledges that the simulation will not verify that the
86    /// program eventually makes progress.
87    #[must_use]
88    pub fn test_safety_only(mut self) -> Self {
89        self.test_safety_only = true;
90        self
91    }
92
93    /// Opts in to skipping consistency assertions. When enabled, `assert_is_consistent`
94    /// nodes are treated as identity no-ops in the simulator. When disabled (the default),
95    /// encountering a consistency assertion will panic because validating consistency
96    /// assertions is not yet supported in the simulator.
97    #[must_use]
98    pub fn skip_consistency_assertions(mut self) -> Self {
99        self.skip_consistency_assertions = true;
100        self
101    }
102
103    /// Sets the number of fuzz iterations for this test. Overrides the
104    /// the default value of 8192.
105    #[must_use]
106    pub fn unit_test_fuzz_iterations(mut self, iterations: usize) -> Self {
107        self.unit_test_fuzz_iterations = iterations;
108        self
109    }
110
111    /// Limits how many bytes of random input each fuzz iteration may consume when a fuzz
112    /// test runs. Once the limit is reached, every remaining decision gets the driver's
113    /// fallback value. Defaults to 4096 (the default for bolero / libfuzzer).
114    #[must_use]
115    pub fn fuzz_max_len(mut self, max_len: usize) -> Self {
116        self.fuzz_max_len = max_len;
117        self
118    }
119
120    /// Bounds the number of retries the simulator generates at at-least-once operators
121    /// (`assume_retries`, and `assume_ordering` / `batch` on an `AtLeastOnce` stream) that
122    /// are not bound to a sim hook, to `depth` per operator. So `retries_depth(0)` delivers
123    /// every element exactly once.
124    ///
125    /// Required by [`exhaustive`](Self::exhaustive) when there are such operators. Under
126    /// [`fuzz`](Self::fuzz), retries are unbounded unless this is set.
127    /// [`deterministic`](Self::deterministic) ignores it, since every at-least-once operator
128    /// must be scripted there.
129    ///
130    /// The budget is per operator (and per cluster member). Operators inside a tick get a
131    /// fresh budget on every tick execution. Each top-level operator consumes its budget
132    /// across ticks with no refreshes.
133    #[must_use]
134    pub fn retries_depth(mut self, depth: usize) -> Self {
135        self.retries_depth = Some(depth);
136        self
137    }
138
139    /// Executes the given closure with a single instance of the compiled simulation.
140    pub fn with_instance<T>(self, thunk: impl FnOnce(CompiledSimInstance<'_>) -> T) -> T {
141        self.compiled().with_instance(thunk)
142    }
143
144    /// Uses a fuzzing strategy to explore possible executions of the simulation. The provided
145    /// closure will be repeatedly executed with instances of the Hydro program where the
146    /// batching boundaries, order of messages, and retries are varied.
147    ///
148    /// During development, you should run the test that invokes this function with the `cargo sim`
149    /// command, which will use `libfuzzer` to intelligently explore the execution space. If a
150    /// failure is found, a minimized test case will be produced in a `sim-failures` directory.
151    /// When running the test with `cargo test` (such as in CI), if a reproducer is found it will
152    /// be executed, and if no reproducer is found a small number of random executions will be
153    /// performed.
154    #[track_caller]
155    pub fn fuzz(self, thunk: impl AsyncFnMut() + RefUnwindSafe) {
156        self.compiled().fuzz(thunk)
157    }
158
159    /// Exhaustively searches all possible executions of the simulation. The provided
160    /// closure will be repeatedly executed with instances of the Hydro program where the
161    /// batching boundaries, order of messages, and retries are varied.
162    ///
163    /// Exhaustive searching is feasible when the inputs to the Hydro program are finite and there
164    /// are no dataflow loops that generate infinite messages. Exhaustive searching provides a
165    /// stronger guarantee of correctness than fuzzing, but may take a long time to complete.
166    /// Because no fuzzer is involved, you can run exhaustive tests with `cargo test`.
167    ///
168    /// Returns the number of distinct executions explored.
169    pub fn exhaustive(self, thunk: impl AsyncFnMut() + RefUnwindSafe) -> usize {
170        self.compiled().exhaustive(thunk)
171    }
172
173    /// Runs the test body against exactly **one** execution of the program, with no fuzzer
174    /// involved anywhere. Requires every unsafe operator that receives data to be bound to
175    /// a sim hook and scripted; see [`crate::sim::compiled::CompiledSim::deterministic`].
176    pub fn deterministic(self, thunk: impl AsyncFnOnce() + RefUnwindSafe) {
177        self.compiled().deterministic(thunk)
178    }
179
180    /// Compiles the simulation into a dynamically loadable library, and returns a handle to it.
181    pub fn compiled(mut self) -> CompiledSim {
182        use dfir_lang::graph::{eliminate_extra_unions_tees, partition_graph};
183
184        let compiled_span = tracing::debug_span!(target: "hydro_build", "sim_compiled").entered();
185        let flow_build_span = tracing::debug_span!(target: "hydro_build", "flow_build").entered();
186
187        let is_multi_version = self.location_version.values().any(|&v| v > 0);
188
189        let mut sim_emit = SimBuilder {
190            process_graphs: BTreeMap::new(),
191            cluster_graphs: BTreeMap::new(),
192            process_tick_dfirs: BTreeMap::new(),
193            cluster_tick_dfirs: BTreeMap::new(),
194            extra_stmts_global: vec![],
195            extra_stmts_cluster: BTreeMap::new(),
196            next_hoff_id: crate::Counter::default(),
197            test_safety_only: self.test_safety_only,
198            skip_consistency_assertions: self.skip_consistency_assertions,
199            unhooked_at_least_once: vec![],
200            channel_tables: BTreeMap::new(),
201            bound_sim_hooks: HashMap::new(),
202        };
203
204        // Ensure the default (0) external is always present.
205        self.externals.insert(
206            LocationKey::FIRST,
207            SimExternal {
208                shared_inner: self.externals_port_registry.clone(),
209            },
210        );
211
212        let mut seen_tees_instantiate: HashMap<_, _> = HashMap::new();
213        let mut seen_cluster_members = HashSet::new();
214        self.ir.iter_mut().for_each(|leaf| {
215            leaf.compile_network::<SimDeploy>(
216                &mut SparseSecondaryMap::new(),
217                &mut seen_tees_instantiate,
218                &mut seen_cluster_members,
219                &self.processes,
220                &self.clusters,
221                &self.externals,
222                &mut (),
223            );
224        });
225
226        if is_multi_version {
227            super::versioned_network::splice_versioned_networks(
228                &mut self.ir,
229                &self.location_version_group_root,
230                &self.location_version,
231            );
232        }
233
234        let mut seen_tees = HashMap::new();
235        let mut built_tees = HashMap::new();
236        let mut next_stmt_id = crate::Counter::<StmtId>::default();
237        let mut fold_hooked_idents = HashSet::new();
238        for leaf in &mut self.ir {
239            leaf.emit(
240                &mut sim_emit,
241                &mut seen_tees,
242                &mut built_tees,
243                &mut next_stmt_id,
244                &mut fold_hooked_idents,
245            );
246        }
247
248        fn build_graphs(
249            graphs: BTreeMap<LocationId, FlatGraphBuilder>,
250        ) -> BTreeMap<LocationId, DfirGraph> {
251            graphs
252                .into_iter()
253                .map(|(l, g)| {
254                    let FlatGraphBuilderOutput { mut flat_graph, .. } =
255                        g.build().expect("Failed to build DFIR flat graph.");
256                    eliminate_extra_unions_tees(&mut flat_graph);
257                    let partitioned = partition_graph(flat_graph).unwrap_or_else(|err| {
258                        panic!(
259                            "Failed to partition DFIR graph for location {l:?}: {}",
260                            err.diagnostic
261                        )
262                    });
263                    (l, partitioned)
264                })
265                .collect()
266        }
267
268        let process_graphs = build_graphs(sim_emit.process_graphs);
269        let cluster_graphs = build_graphs(sim_emit.cluster_graphs);
270        let process_tick_graphs = build_graphs(sim_emit.process_tick_dfirs);
271        let cluster_tick_graphs = build_graphs(sim_emit.cluster_tick_dfirs);
272
273        #[expect(
274            clippy::disallowed_methods,
275            reason = "nondeterministic iteration order, fine for checks"
276        )]
277        for c in self.clusters.keys() {
278            assert!(
279                self.cluster_max_sizes.contains_key(c),
280                "Cluster {:?} missing max size; call with_cluster_size() before compiled()",
281                c
282            );
283        }
284
285        let (cluster_max_sizes, cluster_member_ids) = self.cluster_sizing();
286        drop(flow_build_span);
287
288        let (bin, trybuild) = create_sim_graph_trybuild(
289            process_graphs,
290            cluster_graphs,
291            cluster_max_sizes,
292            cluster_member_ids,
293            process_tick_graphs,
294            cluster_tick_graphs,
295            sim_emit.extra_stmts_global,
296            sim_emit.extra_stmts_cluster,
297        );
298
299        let unhooked_at_least_once = std::mem::take(&mut sim_emit.unhooked_at_least_once);
300        let out = compile_sim(bin, trybuild).unwrap();
301        let lib = {
302            let _span = tracing::debug_span!(target: "hydro_build", "load_dylib").entered();
303            unsafe { Library::new(&out).unwrap() }
304        };
305        drop(compiled_span);
306
307        CompiledSim {
308            lib,
309            externals_port_registry: self.externals_port_registry.take(),
310            unit_test_fuzz_iterations: self.unit_test_fuzz_iterations,
311            fuzz_max_len: self.fuzz_max_len,
312            retries_depth: self.retries_depth,
313            unhooked_at_least_once,
314        }
315    }
316
317    /// Computes each cluster's merged size and the global member-id slice it constructs.
318    ///
319    /// Corresponding clusters (a [`next_version`](crate::location::Cluster::next_version) chain)
320    /// share a group key; the merged size for a group is the sum of its per-version sizes, and each
321    /// version gets a contiguous member-id slice assigned in version order. A single-version
322    /// cluster is the degenerate case: its own group, one version, slice `0..size`.
323    fn cluster_sizing(
324        &self,
325    ) -> (
326        SparseSecondaryMap<LocationKey, usize>,
327        BTreeMap<LocationId, Vec<u32>>,
328    ) {
329        // Group corresponding clusters by their shared group root, recording each version's size.
330        let mut sizes_by_group_root: BTreeMap<LocationKey, BTreeMap<u32, usize>> = BTreeMap::new();
331        #[expect(
332            clippy::disallowed_methods,
333            reason = "each cluster key is unique; iteration order does not affect the result"
334        )]
335        for key in self.clusters.keys() {
336            let group_root = self.location_version_group_root[key];
337            let version = self.location_version[key];
338            let size = *self.cluster_max_sizes.get(key).unwrap_or_else(|| {
339                panic!(
340                    "cluster {key:?} missing max size; `compiled()` asserts every cluster has one \
341                     before calling `cluster_sizing`"
342                )
343            });
344            let prev = sizes_by_group_root
345                .entry(group_root)
346                .or_default()
347                .insert(version, size);
348            assert!(
349                prev.is_none(),
350                "multi-version simulation has two corresponding clusters at the same version; \
351                 each `next_version()` call must advance to a distinct version"
352            );
353        }
354
355        // Each cluster location gets the merged total size (so its membership lists the union) and
356        // its own contiguous slice of the global member-id range, assigned in version order.
357        let mut cluster_sizes: SparseSecondaryMap<LocationKey, usize> = SparseSecondaryMap::new();
358        let mut cluster_member_ids: BTreeMap<LocationId, Vec<u32>> = BTreeMap::new();
359        #[expect(
360            clippy::disallowed_methods,
361            reason = "each cluster key is unique; iteration order does not affect the result"
362        )]
363        for key in self.clusters.keys() {
364            let group_root = self.location_version_group_root[key];
365            let version = self.location_version[key];
366            let per_version = &sizes_by_group_root[&group_root];
367            let merged_total: usize = per_version.values().sum();
368            let offset: u32 = per_version.range(..version).map(|(_, &n)| n as u32).sum();
369            let size = *per_version
370                .get(&version)
371                .expect("every (group, version) was recorded by the first pass above")
372                as u32;
373            cluster_sizes.insert(key, merged_total);
374            cluster_member_ids.insert(LocationId::Cluster(key), (offset..offset + size).collect());
375        }
376
377        (cluster_sizes, cluster_member_ids)
378    }
379}