hydro_lang 0.16.0

A Rust framework for correct and performant distributed systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::process::{Command, Stdio};
use std::rc::Rc;

use dfir_lang::diagnostic::Diagnostics;
use dfir_lang::graph::DfirGraph;
use proc_macro2::Span;
use quote::quote;
use sha2::{Digest, Sha256};
use slotmap::SparseSecondaryMap;
use stageleft::QuotedWithContext;
use syn::visit_mut::VisitMut;
use tempfile::TempPath;
use trybuild_internals_api::{cargo, dependencies, path};

use crate::compile::builder::ExternalPortId;
use crate::compile::deploy_provider::{Deploy, DynSourceSink, Node, RegisterPort};
#[cfg(feature = "deploy")]
use crate::compile::trybuild::generate::LinkingMode;
use crate::compile::trybuild::generate::{
    CONCURRENT_TEST_LOCK, IS_TEST, TrybuildConfig, create_trybuild, write_atomic,
};
use crate::compile::trybuild::rewriters::UseTestModeStaged;
use crate::deploy::deploy_runtime::cluster_membership_stream;
use crate::location::dynamic::LocationId;
use crate::location::member_id::TaglessMemberId;
use crate::location::{LocationKey, MembershipEvent};
use crate::staging_util::get_this_crate;

crate::newtype_counter! {
    /// Represents a [`SimNode`] port.
    pub struct SimNodePort(usize);

    /// Represents a [`SimExternal`] port.
    pub struct SimExternalPort(usize);
}

#[derive(Clone)]
pub struct SimNode {
    /// Counter for port IDs, must be shared across all nodes in a simulation to prevent collisions.
    pub shared_port_counter: Rc<RefCell<SimNodePort>>,
}

impl Node for SimNode {
    type Port = SimNodePort;
    type Meta = ();
    type InstantiateEnv = ();

    fn next_port(&self) -> Self::Port {
        self.shared_port_counter.borrow_mut().get_and_increment()
    }

    fn update_meta(&self, _meta: &Self::Meta) {}

    fn instantiate(
        &self,
        _env: &mut Self::InstantiateEnv,
        _meta: &mut Self::Meta,
        _graph: DfirGraph,
        _extra_stmts: &[syn::Stmt],
        _sidecars: &[syn::Expr],
    ) {
    }
}

#[derive(Clone, Default)]
pub(crate) struct SimExternalPortRegistry {
    pub(crate) port_counter: SimExternalPort,
    /// A mapping from external port IDs (generated in `FlowState`)
    /// which are used for looking up connections, to the IDs
    /// of the external channels created in the simulation.
    pub(crate) registered: HashMap<ExternalPortId, SimExternalPort>,
}

#[derive(Clone, Default)]
pub struct SimExternal {
    pub(crate) shared_inner: Rc<RefCell<SimExternalPortRegistry>>,
}

impl Node for SimExternal {
    type Port = SimExternalPort;
    type Meta = ();
    type InstantiateEnv = ();

    fn next_port(&self) -> Self::Port {
        self.shared_inner
            .borrow_mut()
            .port_counter
            .get_and_increment()
    }

    fn update_meta(&self, _meta: &Self::Meta) {
        todo!("SimExternal::update_meta is not yet implemented")
    }

    fn instantiate(
        &self,
        _env: &mut Self::InstantiateEnv,
        _meta: &mut Self::Meta,
        _graph: DfirGraph,
        _extra_stmts: &[syn::Stmt],
        _sidecars: &[syn::Expr],
    ) {
    }
}

impl<'a> RegisterPort<'a, SimDeploy> for SimExternal {
    fn register(&self, external_port_id: ExternalPortId, port: Self::Port) {
        assert!(
            self.shared_inner
                .borrow_mut()
                .registered
                .insert(external_port_id, port)
                .is_none_or(|old| old == port)
        );
    }

    #[expect(clippy::manual_async_fn, reason = "false positive, involves lifetimes")]
    fn as_bytes_bidi(
        &self,
        _external_port_id: ExternalPortId,
    ) -> impl Future<
        Output = DynSourceSink<
            Result<bytes::BytesMut, std::io::Error>,
            bytes::Bytes,
            std::io::Error,
        >,
    > + 'a {
        async { todo!("SimExternal::as_bytes_bidi is not yet supported in simulation") }
    }

    #[expect(clippy::manual_async_fn, reason = "false positive, involves lifetimes")]
    fn as_bincode_bidi<InT, OutT>(
        &self,
        _external_port_id: ExternalPortId,
    ) -> impl Future<Output = DynSourceSink<OutT, InT, std::io::Error>> + 'a
    where
        InT: serde::Serialize + 'static,
        OutT: serde::de::DeserializeOwned + 'static,
    {
        async { todo!("SimExternal::as_bincode_bidi is not yet supported in simulation") }
    }

    #[expect(clippy::manual_async_fn, reason = "false positive, involves lifetimes")]
    fn as_bincode_sink<T>(
        &self,
        _external_port_id: ExternalPortId,
    ) -> impl Future<Output = std::pin::Pin<Box<dyn futures::Sink<T, Error = std::io::Error>>>> + 'a
    where
        T: serde::Serialize + 'static,
    {
        async { todo!("SimExternal::as_bincode_sink is not yet supported in simulation") }
    }

    #[expect(clippy::manual_async_fn, reason = "false positive, involves lifetimes")]
    fn as_bincode_source<T>(
        &self,
        _external_port_id: ExternalPortId,
    ) -> impl Future<Output = std::pin::Pin<Box<dyn futures::Stream<Item = T>>>> + 'a
    where
        T: serde::de::DeserializeOwned + 'static,
    {
        async { todo!("SimExternal::as_bincode_source is not yet supported in simulation") }
    }
}

pub(super) struct SimDeploy {}
impl<'a> Deploy<'a> for SimDeploy {
    type Meta = ();
    type InstantiateEnv = ();

    type Process = SimNode;
    type Cluster = SimNode;
    type External = SimExternal;

    fn o2o_sink_source(
        _env: &mut Self::InstantiateEnv,
        _p1: &Self::Process,
        p1_port: &<Self::Process as Node>::Port,
        _p2: &Self::Process,
        p2_port: &<Self::Process as Node>::Port,
        _name: Option<&str>,
        _networking_info: &crate::networking::NetworkingInfo,
    ) -> (syn::Expr, syn::Expr) {
        let ident_sink =
            syn::Ident::new(&format!("__hydro_o2o_sink_{}", p1_port), Span::call_site());
        let ident_source = syn::Ident::new(
            &format!("__hydro_o2o_source_{}", p2_port),
            Span::call_site(),
        );
        (
            syn::parse_quote!(#ident_sink),
            syn::parse_quote!(#ident_source),
        )
    }

    fn o2o_connect(
        _p1: &Self::Process,
        _p1_port: &<Self::Process as Node>::Port,
        _p2: &Self::Process,
        _p2_port: &<Self::Process as Node>::Port,
    ) -> Box<dyn FnOnce()> {
        Box::new(|| {})
    }

    fn o2m_sink_source(
        _env: &mut Self::InstantiateEnv,
        _p1: &Self::Process,
        p1_port: &<Self::Process as Node>::Port,
        _c2: &Self::Cluster,
        c2_port: &<Self::Cluster as Node>::Port,
        _name: Option<&str>,
        _networking_info: &crate::networking::NetworkingInfo,
    ) -> (syn::Expr, syn::Expr) {
        let ident_sink =
            syn::Ident::new(&format!("__hydro_o2m_sink_{}", p1_port), Span::call_site());
        let ident_source = syn::Ident::new(
            &format!("__hydro_o2m_source_{}", c2_port),
            Span::call_site(),
        );
        (
            syn::parse_quote!(#ident_sink),
            syn::parse_quote!(#ident_source),
        )
    }

    fn o2m_connect(
        _p1: &Self::Process,
        _p1_port: &<Self::Process as Node>::Port,
        _c2: &Self::Cluster,
        _c2_port: &<Self::Cluster as Node>::Port,
    ) -> Box<dyn FnOnce()> {
        Box::new(|| {})
    }

    fn m2o_sink_source(
        _env: &mut Self::InstantiateEnv,
        _c1: &Self::Cluster,
        c1_port: &<Self::Cluster as Node>::Port,
        _p2: &Self::Process,
        p2_port: &<Self::Process as Node>::Port,
        _name: Option<&str>,
        _networking_info: &crate::networking::NetworkingInfo,
    ) -> (syn::Expr, syn::Expr) {
        let ident_sink =
            syn::Ident::new(&format!("__hydro_m2o_sink_{}", c1_port), Span::call_site());
        let ident_source = syn::Ident::new(
            &format!("__hydro_m2o_source_{}", p2_port),
            Span::call_site(),
        );

        (
            syn::parse_quote!(#ident_sink),
            syn::parse_quote!(#ident_source),
        )
    }

    fn m2o_connect(
        _c1: &Self::Cluster,
        _c1_port: &<Self::Cluster as Node>::Port,
        _p2: &Self::Process,
        _p2_port: &<Self::Process as Node>::Port,
    ) -> Box<dyn FnOnce()> {
        Box::new(|| {})
    }

    fn m2m_sink_source(
        _env: &mut Self::InstantiateEnv,
        _c1: &Self::Cluster,
        c1_port: &<Self::Cluster as Node>::Port,
        _c2: &Self::Cluster,
        c2_port: &<Self::Cluster as Node>::Port,
        _name: Option<&str>,
        _networking_info: &crate::networking::NetworkingInfo,
    ) -> (syn::Expr, syn::Expr) {
        let ident_sink =
            syn::Ident::new(&format!("__hydro_m2m_sink_{}", c1_port), Span::call_site());
        let ident_source = syn::Ident::new(
            &format!("__hydro_m2m_source_{}", c2_port),
            Span::call_site(),
        );
        (
            syn::parse_quote!(#ident_sink),
            syn::parse_quote!(#ident_source),
        )
    }

    fn m2m_connect(
        _c1: &Self::Cluster,
        _c1_port: &<Self::Cluster as Node>::Port,
        _c2: &Self::Cluster,
        _c2_port: &<Self::Cluster as Node>::Port,
    ) -> Box<dyn FnOnce()> {
        Box::new(|| {})
    }

    fn e2o_many_source(
        _extra_stmts: &mut Vec<syn::Stmt>,
        _p2: &Self::Process,
        _p2_port: &<Self::Process as Node>::Port,
        _codec_type: &syn::Type,
        _shared_handle: String,
    ) -> syn::Expr {
        todo!("e2o_many_source is not yet supported in simulation")
    }

    fn e2o_many_sink(_shared_handle: String) -> syn::Expr {
        todo!("e2o_many_sink is not yet supported in simulation")
    }

    fn e2o_source(
        _extra_stmts: &mut Vec<syn::Stmt>,
        _p1: &Self::External,
        p1_port: &<Self::External as Node>::Port,
        _p2: &Self::Process,
        _p2_port: &<Self::Process as Node>::Port,
        _codec_type: &syn::Type,
        _shared_handle: String,
    ) -> syn::Expr {
        let ident = syn::Ident::new("__hydro_external_in", Span::call_site());
        let p1_port_usize = p1_port.0;
        syn::parse_quote!({
            let (__sender, __receiver) = __root_dfir_rs::util::unbounded_channel::<__root_dfir_rs::bytes::Bytes>();
            #ident.insert(#p1_port_usize, __sender);
            __receiver
        })
    }

    fn e2o_connect(
        _p1: &Self::External,
        _p1_port: &<Self::External as Node>::Port,
        _p2: &Self::Process,
        _p2_port: &<Self::Process as Node>::Port,
        _many: bool,
        _server_hint: crate::location::NetworkHint,
    ) -> Box<dyn FnOnce()> {
        Box::new(|| {})
    }

    fn o2e_sink(
        _p1: &Self::Process,
        _p1_port: &<Self::Process as Node>::Port,
        _p2: &Self::External,
        p2_port: &<Self::External as Node>::Port,
        _shared_handle: String,
    ) -> syn::Expr {
        let ident = syn::Ident::new("__hydro_external_out", Span::call_site());
        let p2_port_usize = p2_port.0;
        syn::parse_quote!({
            let (__sender, __receiver) = __root_dfir_rs::util::unbounded_channel::<__root_dfir_rs::bytes::Bytes>();
            #ident.insert(#p2_port_usize, __root_dfir_rs::tokio_stream::wrappers::UnboundedReceiverStream::new(__receiver.into_inner()));
            __sender
        })
    }

    fn e2m_source(
        _extra_stmts: &mut Vec<syn::Stmt>,
        _p1: &Self::External,
        p1_port: &<Self::External as Node>::Port,
        _c2: &Self::Cluster,
        _c2_port: &<Self::Cluster as Node>::Port,
        _codec_type: &syn::Type,
        _shared_handle: String,
    ) -> syn::Expr {
        let ident = syn::Ident::new("__hydro_cluster_external_in", Span::call_site());
        let p1_port_usize = p1_port.0;
        syn::parse_quote!({
            let (__sender, __receiver) = __root_dfir_rs::util::unbounded_channel::<__root_dfir_rs::bytes::Bytes>();
            #ident.entry(#p1_port_usize).or_insert_with(Vec::new).push(__sender);
            __receiver
        })
    }

    fn e2m_connect(
        _p1: &Self::External,
        _p1_port: &<Self::External as Node>::Port,
        _c2: &Self::Cluster,
        _c2_port: &<Self::Cluster as Node>::Port,
        _server_hint: crate::location::NetworkHint,
    ) -> Box<dyn FnOnce()> {
        Box::new(|| {})
    }

    fn m2e_sink(
        _c1: &Self::Cluster,
        _c1_port: &<Self::Cluster as Node>::Port,
        _p2: &Self::External,
        p2_port: &<Self::External as Node>::Port,
        _shared_handle: String,
    ) -> syn::Expr {
        let ident = syn::Ident::new("__hydro_cluster_external_out", Span::call_site());
        let p2_port_usize = p2_port.0;
        syn::parse_quote!({
            let (__sender, __receiver) = __root_dfir_rs::util::unbounded_channel::<__root_dfir_rs::bytes::Bytes>();
            #ident.entry(#p2_port_usize).or_insert_with(Vec::new).push(__root_dfir_rs::tokio_stream::wrappers::UnboundedReceiverStream::new(__receiver.into_inner()));
            __sender
        })
    }

    #[expect(unreachable_code, reason = "todo!() is unreachable")]
    fn cluster_ids(
        _of_cluster: LocationKey,
    ) -> impl QuotedWithContext<'a, &'a [TaglessMemberId], ()> + Clone + 'a {
        todo!("cluster_ids is not yet supported in simulation");
        stageleft::q!(todo!())
    }

    #[expect(unreachable_code, reason = "todo!() is unreachable")]
    fn cluster_self_id() -> impl QuotedWithContext<'a, TaglessMemberId, ()> + Clone + 'a {
        todo!("cluster_self_id is not yet supported in simulation");
        stageleft::q!(todo!())
    }

    fn cluster_membership_stream(
        _env: &mut Self::InstantiateEnv,
        _at_location: &LocationId,
        location_id: &LocationId,
    ) -> impl QuotedWithContext<
        'a,
        Box<dyn futures::Stream<Item = (TaglessMemberId, MembershipEvent)> + Unpin>,
        (),
    > {
        cluster_membership_stream(location_id)
    }
}

pub(super) fn compile_sim(bin: String, trybuild: TrybuildConfig) -> Result<TempPath, ()> {
    let mut command = Command::new("cargo");

    let is_fuzz = std::env::var("BOLERO_FUZZER").is_ok();

    // Run from dylib-examples crate which has the dylib as a dev-dependency (only if not fuzzing)
    let crate_to_compile = if is_fuzz {
        trybuild.project_dir.clone()
    } else {
        path!(trybuild.project_dir / "dylib-examples")
    };
    command.current_dir(&crate_to_compile);
    command.args(["rustc", "--locked"]);
    command.args(["--example", "sim-dylib"]);
    command.args(["--target-dir", trybuild.target_dir.to_str().unwrap()]);
    if let Some(features) = &trybuild.features {
        command.args(["--features", &features.join(",")]);
    }
    command.args(["--config", "build.incremental = false"]);
    command.args(["--crate-type", "cdylib"]);
    command.arg("--message-format=json-diagnostic-rendered-ansi");
    command.env("STAGELEFT_TRYBUILD_BUILD_STAGED", "1");
    command.env("TRYBUILD_LIB_NAME", &bin);

    command.arg("--");

    if cfg!(target_os = "linux") {
        let debug_path = if let Ok(target) = std::env::var("CARGO_BUILD_TARGET") {
            path!(trybuild.target_dir / target / "debug")
        } else {
            path!(trybuild.target_dir / "debug")
        };

        command.args([&format!(
            "-Clink-arg=-Wl,-rpath,{}",
            debug_path.to_str().unwrap()
        )]);

        if cfg!(target_env = "gnu") {
            command.arg(
                // https://github.com/rust-lang/rust/issues/91979
                "-Clink-args=-Wl,-z,nodelete",
            );
        }
    }

    if let Ok(fuzzer) = std::env::var("BOLERO_FUZZER") {
        command.env_remove("BOLERO_FUZZER");

        if fuzzer == "libfuzzer" {
            #[cfg(target_os = "macos")]
            {
                command.args(["-Clink-arg=-undefined", "-Clink-arg=dynamic_lookup"]);
            }

            #[cfg(target_os = "linux")]
            {
                command.args(["-Clink-arg=-Wl,--unresolved-symbols=ignore-all"]);
            }
        }
    }

    let mut spawned = command
        .stdout(Stdio::piped())
        .stdin(Stdio::null())
        .spawn()
        .unwrap();
    let reader = std::io::BufReader::new(spawned.stdout.take().unwrap());

    let mut out = Err(());
    for message in cargo_metadata::Message::parse_stream(reader) {
        match message.unwrap() {
            cargo_metadata::Message::CompilerArtifact(artifact) => {
                // unlike dylib, cdylib only exports the explicitly exported symbols
                let is_output = artifact.target.is_example();

                if is_output {
                    use std::path::PathBuf;

                    let path = artifact.filenames.first().unwrap();
                    let path_buf: PathBuf = path.clone().into();
                    out = Ok(path_buf);
                }
            }
            cargo_metadata::Message::CompilerMessage(mut msg) => {
                // Update the path displayed to enable clicking in IDE.
                // TODO(mingwei): deduplicate code with hydro_deploy rust_crate/build.rs
                if let Some(rendered) = msg.message.rendered.as_mut() {
                    let file_names = msg
                        .message
                        .spans
                        .iter()
                        .map(|s| &s.file_name)
                        .collect::<std::collections::BTreeSet<_>>();
                    for file_name in file_names {
                        *rendered = rendered.replace(
                            file_name,
                            &format!("(full path) {}/{file_name}", trybuild.project_dir.display()),
                        )
                    }
                }
                eprintln!("{}", msg.message);
            }
            cargo_metadata::Message::TextLine(line) => {
                eprintln!("{}", line);
            }
            cargo_metadata::Message::BuildFinished(_) => {}
            cargo_metadata::Message::BuildScriptExecuted(_) => {}
            msg => panic!("Unexpected message type: {:?}", msg),
        }
    }

    spawned.wait().unwrap();

    let out_file = tempfile::NamedTempFile::new().unwrap().into_temp_path();
    fs::copy(out.as_ref().unwrap(), &out_file).unwrap();
    Ok(out_file)
}

pub(super) fn create_sim_graph_trybuild(
    process_graphs: BTreeMap<LocationId, DfirGraph>,
    cluster_graphs: BTreeMap<LocationId, DfirGraph>,
    cluster_max_sizes: SparseSecondaryMap<LocationKey, usize>,
    process_tick_graphs: BTreeMap<LocationId, DfirGraph>,
    cluster_tick_graphs: BTreeMap<LocationId, DfirGraph>,
    extra_stmts_global: Vec<syn::Stmt>,
    extra_stmts_cluster: BTreeMap<LocationId, Vec<syn::Stmt>>,
) -> (String, TrybuildConfig) {
    let source_dir = cargo::manifest_dir().unwrap();
    let source_manifest = dependencies::get_manifest(&source_dir).unwrap();
    let crate_name = source_manifest.package.name.replace("-", "_");

    let is_test = IS_TEST.load(std::sync::atomic::Ordering::Relaxed);

    let generated_code = compile_sim_graph_trybuild(
        process_graphs,
        cluster_graphs,
        cluster_max_sizes,
        process_tick_graphs,
        cluster_tick_graphs,
        extra_stmts_global,
        extra_stmts_cluster,
        &crate_name,
        is_test,
    );

    let inlined_staged = if is_test {
        let raw_toml_manifest = toml::from_str::<toml::Value>(
            &fs::read_to_string(path!(source_dir / "Cargo.toml")).unwrap(),
        )
        .unwrap();

        let maybe_custom_lib_path = raw_toml_manifest
            .get("lib")
            .and_then(|lib| lib.get("path"))
            .and_then(|path| path.as_str());

        let mut gen_staged = stageleft_tool::gen_staged_trybuild(
            &maybe_custom_lib_path
                .map(|s| path!(source_dir / s))
                .unwrap_or_else(|| path!(source_dir / "src" / "lib.rs")),
            &path!(source_dir / "Cargo.toml"),
            &crate_name,
            Some("hydro___test".to_owned()),
        );

        gen_staged.attrs.insert(
            0,
            syn::parse_quote! {
                #![allow(
                    unused,
                    ambiguous_glob_reexports,
                    clippy::suspicious_else_formatting,
                    unexpected_cfgs,
                    reason = "generated code"
                )]
            },
        );

        Some(prettyplease::unparse(&gen_staged))
    } else {
        None
    };

    let source = prettyplease::unparse(&generated_code);

    let hash = format!("{:X}", Sha256::digest(&source))
        .chars()
        .take(8)
        .collect::<String>();

    let bin_name = hash;

    let (project_dir, target_dir, mut cur_bin_enabled_features) = create_trybuild().unwrap();

    let is_fuzz = std::env::var("BOLERO_FUZZER").is_ok();

    // Sim builds use dynamic linking, so put examples in dylib-examples crate
    // Fuzzing does not, so put them in the main trybuild project dir
    let examples_dir = if is_fuzz {
        path!(project_dir / "examples")
    } else {
        path!(project_dir / "dylib-examples" / "examples")
    };

    // TODO(shadaj): garbage collect this directory occasionally
    fs::create_dir_all(path!(project_dir / "src")).unwrap();
    fs::create_dir_all(&examples_dir).unwrap();

    let out_path = path!(examples_dir / format!("{bin_name}.rs"));
    {
        let _concurrent_test_lock = CONCURRENT_TEST_LOCK.lock().unwrap();
        write_atomic(source.as_ref(), &out_path).unwrap();
    }

    if let Some(inlined_staged) = inlined_staged {
        let staged_path = path!(project_dir / "src" / "__staged.rs");
        {
            let _concurrent_test_lock = CONCURRENT_TEST_LOCK.lock().unwrap();
            write_atomic(inlined_staged.as_bytes(), &staged_path).unwrap();
        }
    }

    if is_test {
        if cur_bin_enabled_features.is_none() {
            cur_bin_enabled_features = Some(vec![]);
        }

        cur_bin_enabled_features
            .as_mut()
            .unwrap()
            .push("hydro___test".to_owned());
    }

    (
        bin_name,
        TrybuildConfig {
            project_dir,
            target_dir,
            features: cur_bin_enabled_features,
            #[cfg(feature = "deploy")]
            linking_mode: LinkingMode::Dynamic,
        },
    )
}

#[expect(clippy::too_many_arguments, reason = "necessary for code generation")]
fn compile_sim_graph_trybuild(
    process_graphs: BTreeMap<LocationId, DfirGraph>,
    cluster_graphs: BTreeMap<LocationId, DfirGraph>,
    cluster_max_sizes: SparseSecondaryMap<LocationKey, usize>,
    process_tick_graphs: BTreeMap<LocationId, DfirGraph>,
    cluster_tick_graphs: BTreeMap<LocationId, DfirGraph>,
    mut extra_stmts_global: Vec<syn::Stmt>,
    mut extra_stmts_cluster: BTreeMap<LocationId, Vec<syn::Stmt>>,
    crate_name: &str,
    is_test: bool,
) -> syn::File {
    let mut diagnostics = Diagnostics::new();

    let mut dfir_into_code = |g: &DfirGraph| {
        let mut dfir_expr: syn::Expr = syn::parse2(
            g.as_code_with_options(
                &quote! { __root_dfir_rs },
                true,
                false,
                quote!(),
                &mut diagnostics,
            )
            .expect("DFIR code generation failed with diagnostics."),
        )
        .unwrap();

        if is_test {
            UseTestModeStaged { crate_name }.visit_expr_mut(&mut dfir_expr);
        }

        dfir_expr
    };

    // Wrap to erase the concrete closure type so all locations can go in a Vec.
    let mut dfir_into_code_erased = |g: &DfirGraph| -> syn::Expr {
        let inner = dfir_into_code(g);
        syn::parse_quote! {
            __root_dfir_rs::scheduled::context::Dfir::into_erased(#inner)
        }
    };

    if is_test {
        extra_stmts_global.iter_mut().for_each(|stmt| {
            UseTestModeStaged { crate_name }.visit_stmt_mut(stmt);
        });

        extra_stmts_cluster.values_mut().for_each(|stmts| {
            stmts.iter_mut().for_each(|stmt| {
                UseTestModeStaged { crate_name }.visit_stmt_mut(stmt);
            })
        });
    }

    let process_dfir_exprs = process_graphs
        .into_iter()
        .map(|(lid, g)| {
            let dfir_expr = dfir_into_code_erased(&g);
            let ser_lid = serde_json::to_string(&lid).unwrap();
            syn::parse_quote!((#ser_lid, None, #dfir_expr))
        })
        .collect::<Vec<syn::Expr>>();

    let mut cluster_ticks_grouped_by_root = cluster_tick_graphs.into_iter().fold::<BTreeMap<
        LocationId,
        Vec<(LocationId, DfirGraph)>,
    >, _>(
        BTreeMap::new(),
        |mut acc, (lid, g)| {
            let root = lid.root();
            acc.entry(root.clone()).or_default().push((lid, g));
            acc
        },
    );

    let root = get_this_crate();

    let cluster_dfir_stmts = cluster_graphs
        .into_iter()
        .map(|(lid, g)| {
            let dfir_expr = dfir_into_code_erased(&g);

            let tick_dfir_stmts = cluster_ticks_grouped_by_root
                .remove(&lid)
                .unwrap_or_default()
                .into_iter()
                .map(|(tick_lid, tick_g)| {
                    let tick_dfir_expr = dfir_into_code_erased(&tick_g);
                    let ser_tick_lid = serde_json::to_string(&tick_lid).unwrap();
                    syn::parse_quote! {
                        __tick_dfirs.push((
                            #ser_tick_lid,
                            Some(__current_cluster_id),
                            #tick_dfir_expr
                        ));
                    }
                })
                .collect::<Vec<syn::Stmt>>();

            let ser_lid = serde_json::to_string(&lid).unwrap();
            let extra_stmts_per_cluster =
                extra_stmts_cluster.get(&lid).cloned().unwrap_or_default();
            let max_size = cluster_max_sizes.get(lid.key()).cloned().unwrap() as u32;

            let self_id_ident = syn::Ident::new(
                &format!("__hydro_lang_cluster_self_id_{}", lid.key()),
                Span::call_site(),
            );

            syn::parse_quote! {
                for __current_cluster_id in 0..#max_size {
                    __async_dfirs.push((
                        #ser_lid,
                        Some(__current_cluster_id),
                        {
                            #(#extra_stmts_per_cluster)*
                            let #self_id_ident = &*Box::leak(Box::new(#root::__staged::location::TaglessMemberId::from_raw_id(__current_cluster_id)));

                            #(#tick_dfir_stmts)*

                            #dfir_expr
                        }
                    ));
                }
            }
        })
        .collect::<Vec<syn::Stmt>>();

    let process_tick_dfir_exprs = process_tick_graphs
        .into_iter()
        .map(|(lid, g)| {
            let dfir_expr = dfir_into_code_erased(&g);
            let ser_lid = serde_json::to_string(&lid).unwrap();
            syn::parse_quote!((#ser_lid, None, #dfir_expr))
        })
        .collect::<Vec<syn::Expr>>();

    // TODO(mingwei): https://github.com/rust-lang/rust-clippy/issues/8581
    // #[expect(
    //     clippy::disallowed_methods,
    //     reason = "nondeterministic iteration order, will be sorted"
    // )]
    let mut cluster_max_sizes = cluster_max_sizes.into_iter().collect::<Vec<_>>();
    cluster_max_sizes.sort();
    let cluster_ids_stmts = cluster_max_sizes.into_iter()
        .map(|(loc_key, max_size)| {
            let ident = syn::Ident::new(
                &format!(
                    "__hydro_lang_cluster_ids_{}",
                    loc_key,
                ),
                Span::call_site(),
            );

            let elements = (0..max_size as u32)
                .map(|i| syn::parse_quote! { #i })
                .collect::<Vec<syn::Expr>>();

            syn::parse_quote! {
                let #ident: &'static [#root::__staged::location::TaglessMemberId] = Box::leak(Box::new([#(#root::__staged::location::TaglessMemberId::from_raw_id(#elements)),*]));
            }
        })
        .collect::<Vec<syn::Stmt>>();

    let orig_crate_name = quote::format_ident!("{}", crate_name);
    let trybuild_crate_name_ident = quote::format_ident!("{}_hydro_trybuild", crate_name);

    let source_ast: syn::File = syn::parse_quote! {
        use #trybuild_crate_name_ident::__root as #orig_crate_name;
        use #trybuild_crate_name_ident::__staged::__deps::*;
        use #root::prelude::*;
        use #root::runtime_support::dfir_rs as __root_dfir_rs;
        pub use #trybuild_crate_name_ident::__staged;

        /// NOTE: This method signature MUST BE THE SAME as `SimLoaded`.
        /// TODO(mingwei): enforce/check this, somehow
        #[allow(unused)]
        fn __hydro_runtime_core<'a>(
            __hydro_external_out: &mut ::std::collections::HashMap<usize, __root_dfir_rs::tokio_stream::wrappers::UnboundedReceiverStream<__root_dfir_rs::bytes::Bytes>>,
            __hydro_external_in: &mut ::std::collections::HashMap<usize, __root_dfir_rs::tokio::sync::mpsc::UnboundedSender<__root_dfir_rs::bytes::Bytes>>,
            __hydro_cluster_external_out: &mut ::std::collections::HashMap<usize, Vec<__root_dfir_rs::tokio_stream::wrappers::UnboundedReceiverStream<__root_dfir_rs::bytes::Bytes>>>,
            __hydro_cluster_external_in: &mut ::std::collections::HashMap<usize, Vec<__root_dfir_rs::tokio::sync::mpsc::UnboundedSender<__root_dfir_rs::bytes::Bytes>>>,
            __println_handler: fn(::std::fmt::Arguments<'_>),
            __eprintln_handler: fn(::std::fmt::Arguments<'_>),
        ) -> (
            Vec<(&'static str, Option<u32>, __root_dfir_rs::scheduled::context::DfirErased)>,
            Vec<(&'static str, Option<u32>, __root_dfir_rs::scheduled::context::DfirErased)>,
            #root::sim::runtime::Hooks<&'static str>,
            #root::sim::runtime::InlineHooks<&'static str>,
        ) {
            macro_rules! println {
                ($($arg:tt)*) => ({
                    __println_handler(::std::format_args!($($arg)*));
                })
            }

            macro_rules! eprintln {
                ($($arg:tt)*) => ({
                    __eprintln_handler(::std::format_args!($($arg)*));
                })
            }

            // copy-pasted from std::dbg! so we can use the local eprintln! above
            macro_rules! dbg {
                // NOTE: We cannot use `concat!` to make a static string as a format argument
                // of `eprintln!` because `file!` could contain a `{` or
                // `$val` expression could be a block (`{ .. }`), in which case the `eprintln!`
                // will be malformed.
                () => {
                    eprintln!("[{}:{}:{}]", ::std::file!(), ::std::line!(), ::std::column!())
                };
                ($val:expr $(,)?) => {
                    // Use of `match` here is intentional because it affects the lifetimes
                    // of temporaries - https://stackoverflow.com/a/48732525/1063961
                    match $val {
                        tmp => {
                            eprintln!("[{}:{}:{}] {} = {:#?}",
                                ::std::file!(),
                                ::std::line!(),
                                ::std::column!(),
                                ::std::stringify!($val),
                                // The `&T: Debug` check happens here (not in the format literal desugaring)
                                // to avoid format literal related messages and suggestions.
                                &&tmp as &dyn ::std::fmt::Debug,
                            );
                            tmp
                        }
                    }
                };
                ($($val:expr),+ $(,)?) => {
                    ($(dbg!($val)),+,)
                };
            }

            let mut __hydro_hooks: ::std::collections::HashMap<(&'static str, Option<u32>), ::std::vec::Vec<Box<dyn #root::sim::runtime::SimHook>>> = ::std::collections::HashMap::new();
            let mut __hydro_inline_hooks: ::std::collections::HashMap<(&'static str, Option<u32>), ::std::vec::Vec<Box<dyn #root::sim::runtime::SimInlineHook>>> = ::std::collections::HashMap::new();
            #(#extra_stmts_global)*
            #(#cluster_ids_stmts)*

            let mut __async_dfirs = vec![#(#process_dfir_exprs),*];
            let mut __tick_dfirs = vec![#(#process_tick_dfir_exprs),*];
            #(#cluster_dfir_stmts)*
            (__async_dfirs, __tick_dfirs, __hydro_hooks, __hydro_inline_hooks)
        }

        #[unsafe(no_mangle)]
        unsafe extern "Rust" fn __hydro_runtime(
            should_color: bool,
            __hydro_external_out: &mut ::std::collections::HashMap<usize, __root_dfir_rs::tokio_stream::wrappers::UnboundedReceiverStream<__root_dfir_rs::bytes::Bytes>>,
            __hydro_external_in: &mut ::std::collections::HashMap<usize, __root_dfir_rs::tokio::sync::mpsc::UnboundedSender<__root_dfir_rs::bytes::Bytes>>,
            __hydro_cluster_external_out: &mut ::std::collections::HashMap<usize, Vec<__root_dfir_rs::tokio_stream::wrappers::UnboundedReceiverStream<__root_dfir_rs::bytes::Bytes>>>,
            __hydro_cluster_external_in: &mut ::std::collections::HashMap<usize, Vec<__root_dfir_rs::tokio::sync::mpsc::UnboundedSender<__root_dfir_rs::bytes::Bytes>>>,
            __println_handler: fn(::std::fmt::Arguments<'_>),
            __eprintln_handler: fn(::std::fmt::Arguments<'_>),
        ) -> (
            Vec<(&'static str, Option<u32>, __root_dfir_rs::scheduled::context::DfirErased)>,
            Vec<(&'static str, Option<u32>, __root_dfir_rs::scheduled::context::DfirErased)>,
            #root::sim::runtime::Hooks<&'static str>,
            #root::sim::runtime::InlineHooks<&'static str>,
        ) {
            #root::runtime_support::colored::control::set_override(should_color);
            __hydro_runtime_core(__hydro_external_out, __hydro_external_in, __hydro_cluster_external_out, __hydro_cluster_external_in, __println_handler, __eprintln_handler)
        }
    };
    source_ast
}