Skip to main content

polydat_core/compile/
select.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! The engine a host chooses, the provenance mode a compiled engine is
5//! built with, and the selector that picks a mode from a graph's shape
6//! when the host leaves it to `Provenance::Auto`.
7
8use crate::ast::PolydatNode;
9use crate::kernel::WireSource;
10use std::collections::HashMap;
11
12/// Which provenance optimization the compiler selected.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum ProvMode {
15    /// No provenance — eval runs all nodes unconditionally.
16    Raw,
17    /// Pull-side cone guard only. `set_inputs` tracks `changed_mask`,
18    /// `eval_for_slot` skips eval when the output cone is clean.
19    /// Zero overhead on all-dirty graphs.
20    Pull,
21    /// Push + pull. Per-node dirty tracking in `set_inputs` +
22    /// cone guard. Selected whenever the graph has two or more inputs.
23    PushPull,
24}
25
26/// Graph analysis results used by the engine selection heuristic.
27#[derive(Debug, Clone)]
28pub struct GraphAnalysis {
29    /// Nodes in the graph.
30    pub total_nodes: usize,
31    /// Inputs.
32    pub num_inputs: usize,
33    /// Named outputs.
34    pub num_outputs: usize,
35    /// Per-output cone size (number of nodes in transitive dependency).
36    pub output_cone_sizes: Vec<(String, usize)>,
37    /// max(cone_size) / total_nodes
38    pub max_cone_ratio: f64,
39    /// Average cone_size / total_nodes
40    pub avg_cone_ratio: f64,
41}
42
43/// Analyze a resolved DAG to compute structural metrics.
44pub fn analyze_graph(
45    nodes: &[Box<dyn PolydatNode>],
46    wiring: &[Vec<WireSource>],
47    output_map: &HashMap<String, (usize, usize)>,
48) -> GraphAnalysis {
49    let total_nodes = nodes.len();
50
51    // Compute per-output cone size: count nodes reachable from each output.
52    // A node is in the cone if its provenance overlaps with the output's.
53    // Actually, we need the transitive upstream set, which is the set of
54    // nodes that can reach this output. We compute this by walking backward
55    // from the output node.
56    let mut output_cone_sizes = Vec::new();
57    for (name, &(node_idx, _port)) in output_map {
58        let cone_size = compute_cone_size(node_idx, wiring);
59        output_cone_sizes.push((name.clone(), cone_size));
60    }
61
62    let max_cone = output_cone_sizes.iter().map(|(_, s)| *s).max().unwrap_or(0);
63    let avg_cone: f64 = if output_cone_sizes.is_empty() {
64        0.0
65    } else {
66        output_cone_sizes
67            .iter()
68            .map(|(_, s)| *s as f64)
69            .sum::<f64>()
70            / output_cone_sizes.len() as f64
71    };
72
73    let max_cone_ratio = if total_nodes > 0 {
74        max_cone as f64 / total_nodes as f64
75    } else {
76        1.0
77    };
78    let avg_cone_ratio = if total_nodes > 0 {
79        avg_cone / total_nodes as f64
80    } else {
81        1.0
82    };
83
84    // Count distinct inputs
85    let mut max_input = 0usize;
86    for sources in wiring {
87        for s in sources {
88            if let WireSource::Input(idx) = s {
89                max_input = max_input.max(*idx + 1);
90            }
91        }
92    }
93
94    GraphAnalysis {
95        total_nodes,
96        num_inputs: max_input,
97        num_outputs: output_map.len(),
98        output_cone_sizes,
99        max_cone_ratio,
100        avg_cone_ratio,
101    }
102}
103
104/// Count the number of nodes in the transitive upstream cone of a node.
105fn compute_cone_size(node_idx: usize, wiring: &[Vec<WireSource>]) -> usize {
106    let mut visited = vec![false; wiring.len()];
107    let mut stack = vec![node_idx];
108    let mut count = 0;
109    while let Some(idx) = stack.pop() {
110        if idx >= visited.len() || visited[idx] {
111            continue;
112        }
113        visited[idx] = true;
114        count += 1;
115        for source in &wiring[idx] {
116            if let WireSource::NodeOutput(upstream, _) = source
117                && !visited[*upstream]
118            {
119                stack.push(*upstream);
120            }
121        }
122    }
123    count
124}
125
126/// Select the optimal provenance mode based on graph analysis.
127///
128/// Heuristic (`crates/polydat/docs/design/engines.md`):
129/// - Pull has zero overhead on all-dirty graphs (cone check ~2ns)
130/// - Pull is the safe default for selective output access
131/// - PushPull when multiple inputs exist (push skip helps within
132///   dirty cones when some subgraphs are stable)
133/// - Raw only for tiny single-input graphs
134pub fn select_prov_mode(analysis: &GraphAnalysis) -> ProvMode {
135    // Tiny single-input graphs: skip provenance data entirely.
136    // The overhead of tracking changed_mask isn't worth it.
137    if analysis.total_nodes < 15 && analysis.num_inputs <= 1 {
138        return ProvMode::Raw;
139    }
140
141    // Multiple inputs: some may be stable at runtime, enabling both
142    // push-side skip (within dirty cones) and pull-side skip (clean cones).
143    // PushPull is the right choice because:
144    // - If an output's cone is clean: pull guard skips eval entirely
145    // - If an output's cone is dirty: push skip avoids stable nodes
146    // The push overhead (~10ns in set_inputs for dependent marking)
147    // is justified by the potential to skip 30-80% of nodes within
148    // dirty cones.
149    if analysis.num_inputs >= 2 {
150        return ProvMode::PushPull;
151    }
152
153    // Single input: every node's cone includes the one input, so the
154    // pull guard will always see "dirty" and fall through. Pull still
155    // has zero overhead (the AND + branch costs ~2ns), so prefer it
156    // over Raw as free insurance for future multi-output scenarios
157    // where not all outputs are pulled every cycle.
158    ProvMode::Pull
159}
160
161// ── The engine a host chooses (engine_parity.md, step 4) ──────────
162
163/// How much of a kernel's work is skipped when inputs repeat: the
164/// provenance mode a compiled engine is built with. Every mode computes
165/// the same values; the modes differ in what they recompute.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
167pub enum Provenance {
168    /// Every evaluation runs every step.
169    Raw,
170    /// A changed input reruns only the steps downstream of it.
171    Push,
172    /// An output whose cone no changed input reaches is not recomputed.
173    Pull,
174    /// Both: per-step skipping and the cone guard.
175    PushPull,
176    /// The selector's choice from the graph's shape
177    /// ([`select_prov_mode`]).
178    Auto,
179}
180
181/// The engine a program runs on. Every engine accepts every program the
182/// interpreter accepts, or refuses it with a reason
183/// ([`KernelError::Refused`]); the choice changes how fast the program
184/// runs and nothing else (docs/design/engine_parity.md).
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
186pub enum Engine {
187    /// The interpreter, with as much of its graph fused into native
188    /// cones as the [`JitMode`](crate::JitMode) says: what `compile()`
189    /// builds, under the assembler's mode.
190    Interpreter(crate::compile::cone::JitMode),
191    /// The closure tier: every node runs its generated closure over
192    /// one slot buffer.
193    Closures(Provenance),
194    /// Native code where a node has a lowering, its closure elsewhere:
195    /// the P3 tier. Refused by a build without the `jit` feature.
196    Native(Provenance),
197}
198
199impl Default for Engine {
200    /// The engine a host gets when it names none: the fastest this build
201    /// has, P3 with the `jit` feature and the closure tier without, with
202    /// the provenance mode left to the selector. Compiled code is the
203    /// default; the interpreter is a choice.
204    fn default() -> Self {
205        #[cfg(feature = "jit")]
206        {
207            Engine::Native(Provenance::Auto)
208        }
209        #[cfg(not(feature = "jit"))]
210        {
211            Engine::Closures(Provenance::Auto)
212        }
213    }
214}
215
216impl std::fmt::Display for Engine {
217    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
218        match self {
219            Engine::Interpreter(crate::compile::cone::JitMode::Auto) => write!(f, "interpreter"),
220            Engine::Interpreter(crate::compile::cone::JitMode::Off) => {
221                write!(f, "interpreter (cones off)")
222            }
223            Engine::Interpreter(crate::compile::cone::JitMode::Force) => {
224                write!(f, "interpreter (cones forced)")
225            }
226            Engine::Closures(p) => write!(f, "closures ({p:?})"),
227            Engine::Native(p) => write!(f, "native ({p:?})"),
228        }
229    }
230}
231
232/// What a kernel's engine decided for its program: how much of it runs
233/// as native segments, as closure steps, and on the interpreter. The one
234/// planning detail a kernel exposes, on every engine
235/// ([`Kernel::plan`](crate::Kernel::plan)).
236#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
237pub struct EnginePlan {
238    /// Runs of nodes compiled to one native function each; on the
239    /// interpreter, its native cones.
240    pub native_segments: usize,
241    /// Nodes that run their generated closure.
242    pub closure_steps: usize,
243    /// Nodes the interpreter dispatches itself.
244    pub interpreted_nodes: usize,
245}
246
247impl std::fmt::Display for EnginePlan {
248    /// The non-zero counts, native first: `4 native segment(s), 3
249    /// closure step(s)`; `nothing` for an empty program.
250    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
251        let mut parts = Vec::new();
252        if self.native_segments > 0 {
253            parts.push(format!("{} native segment(s)", self.native_segments));
254        }
255        if self.closure_steps > 0 {
256            parts.push(format!("{} closure step(s)", self.closure_steps));
257        }
258        if self.interpreted_nodes > 0 {
259            parts.push(format!("{} interpreted node(s)", self.interpreted_nodes));
260        }
261        if parts.is_empty() {
262            write!(f, "nothing")
263        } else {
264            write!(f, "{}", parts.join(", "))
265        }
266    }
267}
268
269/// Why a kernel was not built: the one error type of every constructor
270/// that takes an [`Engine`].
271#[derive(Debug)]
272pub enum KernelError {
273    /// The source did not parse or compile; the message is the DSL
274    /// front end's.
275    Source(String),
276    /// The graph did not assemble.
277    Assembly(crate::compile::assembly::AssemblyError),
278    /// The engine refuses this graph, which the interpreter accepts;
279    /// `reason` names the node or construct.
280    Refused {
281        /// The engine that refused.
282        engine: Engine,
283        /// The node or construct it cannot run.
284        reason: String,
285    },
286}
287
288impl std::fmt::Display for KernelError {
289    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
290        match self {
291            KernelError::Source(e) => write!(f, "{e}"),
292            KernelError::Assembly(e) => write!(f, "{e}"),
293            KernelError::Refused { engine, reason } => {
294                write!(f, "the {engine} engine refuses this program: {reason}")
295            }
296        }
297    }
298}
299
300impl std::error::Error for KernelError {}
301
302impl From<crate::compile::assembly::AssemblyError> for KernelError {
303    fn from(e: crate::compile::assembly::AssemblyError) -> Self {
304        KernelError::Assembly(e)
305    }
306}