1use 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
26pub struct SimFlow<'a> {
28 pub(crate) ir: Vec<HydroRoot>,
29
30 pub(crate) processes: SparseSecondaryMap<LocationKey, SimNode>,
32 pub(crate) clusters: SparseSecondaryMap<LocationKey, SimNode>,
34 pub(crate) externals: SparseSecondaryMap<LocationKey, SimExternal>,
36
37 pub(crate) cluster_max_sizes: SparseSecondaryMap<LocationKey, usize>,
39 pub(crate) externals_port_registry: Rc<RefCell<SimExternalPortRegistry>>,
41
42 pub(crate) location_version: SecondaryMap<LocationKey, u32>,
45
46 pub(crate) location_version_group_root: SecondaryMap<LocationKey, LocationKey>,
50
51 pub(crate) test_safety_only: bool,
53
54 pub(crate) skip_consistency_assertions: bool,
58
59 pub(crate) unit_test_fuzz_iterations: usize,
61
62 pub(crate) fuzz_max_len: usize,
64
65 pub(crate) retries_depth: Option<usize>,
67
68 pub(crate) _phantom: Invariant<'a>,
69}
70
71impl<'a> SimFlow<'a> {
72 #[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 #[must_use]
88 pub fn test_safety_only(mut self) -> Self {
89 self.test_safety_only = true;
90 self
91 }
92
93 #[must_use]
98 pub fn skip_consistency_assertions(mut self) -> Self {
99 self.skip_consistency_assertions = true;
100 self
101 }
102
103 #[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 #[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 #[must_use]
134 pub fn retries_depth(mut self, depth: usize) -> Self {
135 self.retries_depth = Some(depth);
136 self
137 }
138
139 pub fn with_instance<T>(self, thunk: impl FnOnce(CompiledSimInstance<'_>) -> T) -> T {
141 self.compiled().with_instance(thunk)
142 }
143
144 #[track_caller]
155 pub fn fuzz(self, thunk: impl AsyncFnMut() + RefUnwindSafe) {
156 self.compiled().fuzz(thunk)
157 }
158
159 pub fn exhaustive(self, thunk: impl AsyncFnMut() + RefUnwindSafe) -> usize {
170 self.compiled().exhaustive(thunk)
171 }
172
173 pub fn deterministic(self, thunk: impl AsyncFnOnce() + RefUnwindSafe) {
177 self.compiled().deterministic(thunk)
178 }
179
180 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 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 fn cluster_sizing(
324 &self,
325 ) -> (
326 SparseSecondaryMap<LocationKey, usize>,
327 BTreeMap<LocationId, Vec<u32>>,
328 ) {
329 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 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}