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
use std::time::Duration;

use hydro_lang::*;

pub struct Worker {}
pub struct Leader {}

pub fn compute_pi<'a>(
    flow: &FlowBuilder<'a>,
    batch_size: usize,
) -> (Cluster<'a, Worker>, Process<'a, Leader>) {
    let cluster = flow.cluster();
    let process = flow.process();

    let trials = cluster
        .tick()
        .spin_batch(q!(batch_size))
        .map(q!(|_| rand::random::<(f64, f64)>()))
        .map(q!(|(x, y)| x * x + y * y < 1.0))
        .fold(
            q!(|| (0u64, 0u64)),
            q!(|(inside, total), sample_inside| {
                if sample_inside {
                    *inside += 1;
                }

                *total += 1;
            }),
        )
        .all_ticks();

    let estimate = trials
        .send_bincode_interleaved(&process)
        .reduce_commutative(q!(|(inside, total), (inside_batch, total_batch)| {
            *inside += inside_batch;
            *total += total_batch;
        }));

    unsafe {
        // SAFETY: intentional non-determinism
        estimate.sample_every(q!(Duration::from_secs(1)))
    }
    .for_each(q!(|(inside, total)| {
        println!(
            "pi: {} ({} trials)",
            4.0 * inside as f64 / total as f64,
            total
        );
    }));

    (cluster, process)
}

#[cfg(test)]
mod tests {
    use hydro_lang::deploy::DeployRuntime;
    use stageleft::RuntimeData;

    #[test]
    fn compute_pi_ir() {
        let builder = hydro_lang::FlowBuilder::new();
        let _ = super::compute_pi(&builder, 8192);
        let built = builder.with_default_optimize::<DeployRuntime>();

        insta::assert_debug_snapshot!(built.ir());

        for (id, ir) in built.compile(&RuntimeData::new("FAKE")).hydroflow_ir() {
            insta::with_settings!({snapshot_suffix => format!("surface_graph_{id}")}, {
                insta::assert_snapshot!(ir.surface_syntax_string());
            });
        }
    }
}