Skip to main content

polydat_core/kernel/
program.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! PolydatProgram: the immutable compiled DAG shared across all fibers.
5
6use std::collections::HashMap;
7use std::sync::Arc;
8
9use super::engines::{EngineCore, PolydatState, ProvScanState};
10use super::{InputDef, WireSource};
11use crate::ast::{PolydatNode, PortType, Value};
12use crate::dsl::ast::{PolydatFile, Statement};
13
14/// Evaluation lifecycle classification used by the const-binding
15/// contract (graph_compiler.md §3.1):
16/// `CompileConst` and `ScopeInit` are the effectively-const
17/// lifecycle's compile-fold and initialization paths.
18///
19/// The variants are *ordered* — `Dynamic > ScopeInit > CompileConst`
20/// — so propagation along wires is a `max()` operation: a node's
21/// lifecycle is the most-dynamic of its own seed and every upstream
22/// node's lifecycle.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
24pub(crate) enum EvalLifecycle {
25    /// Foldable at Polydat compile time. No dependency on extern slots
26    /// or cycle inputs.
27    CompileConst,
28    /// Foldable at scope activation, after `materialize_wiring_from_outer`
29    /// populates iteration externs. Effectively-const for the
30    /// duration of one activation.
31    ScopeInit,
32    /// Re-evaluated on each pull at execution time. Reaches a
33    /// graph input (cycle / external-write port) or a non-deterministic
34    /// source.
35    Dynamic,
36}
37
38/// Exact multi-word input-provenance mask: bit `i` set means the
39/// carrier transitively depends on graph input `i`, with no
40/// saturation: a workload root's params and shared wires can exceed
41/// 64 inputs, and each keeps its own bit. Self-sizing: `set` grows the
42/// word vector to the highest observed index, so callers never
43/// plumb an input-count and masks from different programs stay
44/// comparable (absent words read as zero).
45#[derive(Debug, Clone, Default, PartialEq, Eq)]
46pub struct ProvMask {
47    words: Vec<u64>,
48}
49
50impl ProvMask {
51    /// A mask with no bit set.
52    pub fn empty() -> Self {
53        Self { words: Vec::new() }
54    }
55
56    /// All bits `[0, n)` set — the "every input dirty" seed the
57    /// engine cone guards start from.
58    pub fn all_below(n: usize) -> Self {
59        let mut m = Self::empty();
60        for i in 0..n {
61            m.set(i);
62        }
63        m
64    }
65
66    /// Zero every bit, keeping the allocated words — the
67    /// per-cycle reset for hot-path change masks (no
68    /// reallocation once sized).
69    pub fn clear(&mut self) {
70        self.words.fill(0);
71    }
72
73    /// Set bit `idx`; returns `true` when the bit was newly set
74    /// (the fixpoint walker's change signal).
75    pub fn set(&mut self, idx: usize) -> bool {
76        let word = idx / 64;
77        if word >= self.words.len() {
78            self.words.resize(word + 1, 0);
79        }
80        let bit = 1u64 << (idx % 64);
81        let newly = self.words[word] & bit == 0;
82        self.words[word] |= bit;
83        newly
84    }
85
86    /// Whether bit `idx` is set.
87    pub fn contains(&self, idx: usize) -> bool {
88        self.words
89            .get(idx / 64)
90            .is_some_and(|w| w & (1u64 << (idx % 64)) != 0)
91    }
92
93    /// OR `other` into `self`; returns `true` when any bit was
94    /// newly set (the fixpoint walker's change signal).
95    pub fn union_with(&mut self, other: &Self) -> bool {
96        if other.words.len() > self.words.len() {
97            self.words.resize(other.words.len(), 0);
98        }
99        let mut changed = false;
100        for (dst, src) in self.words.iter_mut().zip(other.words.iter()) {
101            let merged = *dst | *src;
102            changed |= merged != *dst;
103            *dst = merged;
104        }
105        changed
106    }
107
108    /// Whether any bit is set in both masks.
109    pub fn intersects(&self, other: &Self) -> bool {
110        self.words
111            .iter()
112            .zip(other.words.iter())
113            .any(|(a, b)| a & b != 0)
114    }
115
116    /// Whether no bit is set.
117    pub fn is_zero(&self) -> bool {
118        self.words.iter().all(|w| *w == 0)
119    }
120
121    /// Ascending indices of the set bits.
122    pub fn iter_ones(&self) -> impl Iterator<Item = usize> + '_ {
123        self.words.iter().enumerate().flat_map(|(wi, w)| {
124            (0..64).filter_map(move |b| (w & (1u64 << b) != 0).then_some(wi * 64 + b))
125        })
126    }
127}
128
129/// The per-node reachability attributes computed by the ONE
130/// inventory walker ([`PolydatProgram::compute_node_inventory`]).
131/// Every reachability consumer is a projection of this — see the
132/// walker's doc before adding another traversal.
133pub(crate) struct NodeInventory {
134    /// Which inputs transitively feed each node (exact).
135    pub input_provenance: Vec<ProvMask>,
136    /// Nodes that are nondeterministic (nullary / declared) or
137    /// downstream of one — never current.
138    pub nondet_nodes: Vec<usize>,
139    /// Per-node flag: dependency cone contains a
140    /// `Purity::SideChannel` node.
141    pub side_channel_nodes: Vec<bool>,
142}
143
144/// The lifecycle of every node and the nodes that are never current
145/// (`classify_lifecycle`).
146pub(crate) struct LifecycleClasses {
147    pub lifecycle: Vec<EvalLifecycle>,
148    /// Declared nondeterministic or `volatile`, or downstream of one.
149    pub nondeterministic: Vec<bool>,
150}
151
152/// The compile accounting of one program tree: how many programs have
153/// been built for it, on any engine, over its lifetime. A root compile
154/// mints a ledger, and every program built on the tree's behalf
155/// records into the same one: each `for` body, each engine variant of
156/// a body, and each constant expression a traversal source or
157/// predicate compiles at open. A host reads it before and after an
158/// operation to verify the program-invariance property (for_traversal.md §5.1):
159/// compiling builds one program per body, and activation builds none.
160///
161/// Two trees never share a ledger, whatever thread or process runs
162/// them; two kernels over one program do. A compile charged to a
163/// ledger a host already holds is requested through
164/// [`CompileOptions::ledger`](crate::dsl::compile::CompileOptions).
165///
166/// The ledger also holds every native cone the interpreter planned and
167/// left on the interpreter because the cone could not be built
168/// ([`ConeFallback`], engines.md §2.1), and every comprehension compiled
169/// outside `pragma strict` that reads a name nothing binds
170/// ([`UnresolvedNameWarning`], comprehension_forms.md §5 V3).
171#[derive(Debug, Default)]
172pub struct CompileLedger {
173    programs: std::sync::atomic::AtomicU64,
174    cone_fallbacks: std::sync::Mutex<Vec<ConeFallback>>,
175    unresolved_names: std::sync::Mutex<Vec<UnresolvedNameWarning>>,
176}
177
178/// A comprehension statement compiled outside `pragma strict` that reads
179/// names neither the comprehension binds nor the scope it is read in has
180/// (comprehension_forms.md §5 V3), recorded on the tree's
181/// [`CompileLedger`]. The statement compiles, and each such name reads
182/// None when the comprehension is evaluated. Under `pragma strict` the
183/// same statement is refused with `ValidationError::V3UnresolvedNames`.
184#[derive(Clone, Debug, PartialEq, Eq)]
185pub struct UnresolvedNameWarning {
186    /// The diagnostic context of the program the statement belongs to.
187    pub context: String,
188    /// The statement as written: `for <source>` for a traversal, or
189    /// `<name> := for <source>` for a producer binding.
190    pub statement: String,
191    /// Line of the statement.
192    pub line: usize,
193    /// Column of the statement.
194    pub col: usize,
195    /// Each name nothing binds, with where the comprehension reads it,
196    /// in tree order.
197    pub reads: Vec<crate::iteration::comprehension::NameRead>,
198}
199
200impl std::fmt::Display for UnresolvedNameWarning {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        write!(
203            f,
204            "`{}` at line {}, col {}: {}",
205            self.statement,
206            self.line,
207            self.col,
208            crate::iteration::comprehension::ValidationWarning::UnresolvedNames {
209                reads: self.reads.clone()
210            }
211        )
212    }
213}
214
215/// Why a planned native cone stayed on the interpreter (engines.md §2.1).
216#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
217pub enum ConeFallbackKind {
218    /// Native code generation for the cone failed.
219    Codegen,
220    /// A single node reads more distinct boundary inputs than one cone
221    /// piece may have, so no piece can hold it.
222    InputBound,
223}
224
225/// A native cone the interpreter planned under `JitMode::Auto` or
226/// `JitMode::Force` and left on the interpreter, recorded on the tree's
227/// [`CompileLedger`]. Its members run as interpreter nodes, and every
228/// output keeps the value the interpreter computes.
229#[derive(Clone, Debug, PartialEq, Eq)]
230pub struct ConeFallback {
231    /// The diagnostic context of the program the cone belongs to.
232    pub context: String,
233    /// The members' function names in program order; its length is the
234    /// cone's size.
235    pub members: Vec<String>,
236    /// The program outputs the members produce, sorted by name.
237    pub outputs: Vec<String>,
238    /// The distinct boundary inputs the cone reads.
239    pub boundary_inputs: usize,
240    /// Why the cone stayed on the interpreter.
241    pub kind: ConeFallbackKind,
242    /// The code generator's error text, or the bound the inputs exceed.
243    pub reason: String,
244}
245
246impl CompileLedger {
247    /// A fresh ledger with nothing recorded, shared as every holder
248    /// keeps it.
249    pub fn new() -> Arc<Self> {
250        Arc::new(Self::default())
251    }
252
253    /// The programs built for this tree so far, on every engine.
254    pub fn programs(&self) -> u64 {
255        self.programs.load(std::sync::atomic::Ordering::Relaxed)
256    }
257
258    /// Record one program built.
259    pub(crate) fn record(&self) {
260        self.programs
261            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
262    }
263
264    /// The native cones left on the interpreter so far, in the order
265    /// they were planned, across every program of the tree.
266    pub fn cone_fallbacks(&self) -> Vec<ConeFallback> {
267        self.cone_fallbacks
268            .lock()
269            .unwrap_or_else(std::sync::PoisonError::into_inner)
270            .clone()
271    }
272
273    /// Record one native cone left on the interpreter.
274    #[cfg(feature = "jit")]
275    pub(crate) fn record_cone_fallback(&self, fallback: ConeFallback) {
276        self.cone_fallbacks
277            .lock()
278            .unwrap_or_else(std::sync::PoisonError::into_inner)
279            .push(fallback);
280    }
281
282    /// The comprehension statements compiled outside `pragma strict`
283    /// that read names nothing binds, in the order they compiled, across
284    /// every program of the tree, each statement once.
285    pub fn unresolved_names(&self) -> Vec<UnresolvedNameWarning> {
286        self.unresolved_names
287            .lock()
288            .unwrap_or_else(std::sync::PoisonError::into_inner)
289            .clone()
290    }
291
292    /// Record one statement that reads names nothing binds. A body
293    /// compiles once per engine it runs on, so a statement already
294    /// recorded is not recorded again.
295    pub(crate) fn record_unresolved_names(&self, warning: UnresolvedNameWarning) {
296        let mut recorded = self
297            .unresolved_names
298            .lock()
299            .unwrap_or_else(std::sync::PoisonError::into_inner);
300        if !recorded.contains(&warning) {
301            recorded.push(warning);
302        }
303    }
304}
305
306/// Count the programs reachable from `program`: itself plus every
307/// traversal body at every depth. This is the number of compiled
308/// programs a traversing kernel needs for its whole lifetime, however
309/// many tuples it dispenses.
310pub fn program_count(program: &PolydatProgram) -> usize {
311    1 + program
312        .traversals()
313        .iter()
314        .map(|t| program_count(&t.program))
315        .sum::<usize>()
316}
317
318/// The dataset forms the output of node `start` can depend on, in a
319/// graph of `nodes` wired by `wiring` over `input_defs`: the walk
320/// behind [`PolydatProgram::dataset_sources`], over the graph itself so
321/// that the assembler answers it for a compiled kernel from the same
322/// graph it compiles.
323///
324/// A `forms` node is constant when everything it reads is: a node that
325/// reads nothing, or one whose inputs all come from constant nodes. An
326/// interpreter's program has already folded such a node into a literal;
327/// the graph a compiled engine is built from has not, so the constant
328/// is computed here by evaluating that sub-graph, which is what the
329/// kernel's own initialization does. A dataset is opened once and
330/// shared, so the forms this hands out are the ones the kernel holds.
331/// A node that is not pure, or one that fails, is not a constant.
332pub(crate) fn dataset_sources_of(
333    nodes: &[Box<dyn PolydatNode>],
334    wiring: &[Vec<WireSource>],
335    input_defs: &[InputDef],
336    start: usize,
337) -> DatasetSources {
338    /// The outputs of node `i` when it is a constant, memoized.
339    fn constant(
340        i: usize,
341        nodes: &[Box<dyn PolydatNode>],
342        wiring: &[Vec<WireSource>],
343        memo: &mut [Option<Option<Vec<Value>>>],
344    ) -> Option<Vec<Value>> {
345        if let Some(known) = &memo[i] {
346            return known.clone();
347        }
348        let node = &nodes[i];
349        let outputs = (|| {
350            if !matches!(node.purity(), crate::ast::Purity::Pure) {
351                return None;
352            }
353            let mut inputs = Vec::with_capacity(wiring[i].len());
354            for source in &wiring[i] {
355                match source {
356                    WireSource::NodeOutput(j, port) => {
357                        inputs.push(constant(*j, nodes, wiring, memo)?.get(*port)?.clone());
358                    }
359                    WireSource::Input(_) => return None,
360                }
361            }
362            let mut outputs = vec![Value::None; node.meta().outs.len()];
363            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
364                node.eval(&inputs, &mut outputs);
365            }))
366            .ok()?;
367            Some(outputs)
368        })();
369        memo[i] = Some(outputs.clone());
370        outputs
371    }
372
373    let is_dataset_port = |typ: PortType| matches!(typ, PortType::Forms | PortType::Fragment);
374    let mut sources = DatasetSources::default();
375    let mut memo: Vec<Option<Option<Vec<Value>>>> = vec![None; nodes.len()];
376    let mut seen_nodes = vec![false; nodes.len()];
377    let mut seen_inputs = vec![false; input_defs.len()];
378    let mut pending = vec![start];
379    while let Some(i) = pending.pop() {
380        if std::mem::replace(&mut seen_nodes[i], true) {
381            continue;
382        }
383        let node = &nodes[i];
384        if node
385            .meta()
386            .outs
387            .iter()
388            .any(|port| port.typ == PortType::Forms)
389        {
390            let forms: Vec<_> = constant(i, nodes, wiring, &mut memo)
391                .into_iter()
392                .flatten()
393                .filter_map(|value| match value {
394                    Value::Dataset(forms) => Some(forms),
395                    _ => None,
396                })
397                .collect();
398            if forms.is_empty() {
399                sources.computed.push(node.meta().name.clone());
400            } else {
401                for value in forms {
402                    if !sources.constants.contains(&value) {
403                        sources.constants.push(value);
404                    }
405                }
406                // A constant's own inputs are constants too, and
407                // nothing behind them can supply other forms.
408                continue;
409            }
410        }
411        for source in &wiring[i] {
412            match source {
413                WireSource::NodeOutput(j, _) => pending.push(*j),
414                WireSource::Input(j) => {
415                    if !std::mem::replace(&mut seen_inputs[*j], true)
416                        && is_dataset_port(input_defs[*j].port_type)
417                    {
418                        sources.inputs.push(input_defs[*j].name.clone());
419                    }
420                }
421            }
422        }
423    }
424    sources.inputs.sort();
425    sources.computed.sort();
426    sources
427}
428
429/// The dataset forms an output can depend on
430/// ([`PolydatProgram::dataset_sources`]).
431#[derive(Debug, Clone, Default, PartialEq)]
432#[non_exhaustive]
433pub struct DatasetSources {
434    /// The `forms` values fixed when the program was built that the
435    /// output can depend on, each once.
436    pub constants: Vec<crate::dataset_value::DatasetValue>,
437    /// The names of the `forms` and `fragment` inputs the output can
438    /// depend on. A `forms` input holds its value from the moment the
439    /// kernel is bound under the scope that declares it
440    /// ([`Kernel::input_value`](super::Kernel::input_value)); a
441    /// `fragment` input holds nothing until a cycle.
442    pub inputs: Vec<String>,
443    /// The names of the nodes that compute `forms` from something not
444    /// fixed when the program was built, such as a source string that
445    /// arrives as an input. Their forms cannot be known before a cycle.
446    pub computed: Vec<String>,
447}
448
449/// A compiled program: the nodes in topological order, their wiring,
450/// the inputs, the outputs, and the metadata the compiler attached.
451/// Immutable once built, and shared across kernels through an `Arc`.
452pub struct PolydatProgram {
453    /// Node instances in topological order.
454    pub(crate) nodes: Vec<Box<dyn PolydatNode>>,
455    /// For each node, the wiring of its input ports.
456    pub(crate) wiring: Vec<Vec<WireSource>>,
457    /// All input definitions (coordinates first, then captures).
458    input_defs: Vec<InputDef>,
459    /// Original source text that produced this program. Arc-shared
460    /// so multiple references (diagnostics, describe, debugger) don't
461    /// duplicate the string. Empty if constructed programmatically.
462    source: Arc<String>,
463    /// Diagnostic context describing where this program came from
464    /// (e.g., "workload.yaml bindings", "phase rampup (pname=label-1)").
465    /// Required on all construction paths — no silent empty contexts.
466    context: Arc<String>,
467    /// How many of the inputs are coordinate inputs (set via set_inputs(&[u64])).
468    /// Inputs at indices [0..coord_count) are coordinates.
469    /// Inputs at indices [coord_count..) are capture inputs.
470    coord_count: usize,
471    /// Map from output variate name to `(node_index, output_port_index)`.
472    pub(crate) output_map: HashMap<String, (usize, usize)>,
473    /// Outputs in declaration order: (name, node_index, port_index).
474    /// Stable ordering for positional access.
475    output_list: Vec<(String, usize, usize)>,
476    /// Per-node input provenance (exact multi-word mask). Bit i
477    /// is set if the node transitively depends on graph input i.
478    /// One projection of the node inventory — see
479    /// [`Self::compute_node_inventory`].
480    pub(crate) input_provenance: Vec<ProvMask>,
481    /// Per-input dependent node lists. For each input, the list of
482    /// node indices that transitively depend on it.
483    input_dependents: Vec<Vec<usize>>,
484    /// Nodes that are nondeterministic (nullary / declared
485    /// `Purity::Nondeterministic`) or downstream of one — shared
486    /// by every state constructor's cache-invalidation seed.
487    nondet_nodes: Vec<usize>,
488    /// Per-node flag: dependency cone contains a
489    /// `Purity::SideChannel` node.
490    side_channel_nodes: Vec<bool>,
491    /// Output binding modifiers: `shared` or `final`.
492    /// Only populated for outputs that have a modifier; absent = default.
493    output_modifiers: HashMap<String, crate::dsl::ast::BindingModifier>,
494    /// Names exposed by this program *only* to pass them through
495    /// the scope chain — not because the scope's own bindings or
496    /// specs reference them. Set by intermediate-scope synthesis
497    /// (for_each / for_combinations / do-loop) when auto-cascading
498    /// workload params or other inherited values: an `extern` is
499    /// declared so `materialize_wiring_from_outer` can wire the value, but the
500    /// scope itself doesn't *own* the name. Display layers
501    /// (scenario tree pre-map, TUI per-scope listing) use this
502    /// to distinguish "names defined here" from "names visible
503    /// here through inheritance."
504    inherited_outputs: std::collections::HashSet<String>,
505    /// Source schemas declared in the Polydat program. The runtime queries
506    /// these to discover data sources and their extents.
507    cursor_schemas: Vec<crate::iteration::source::SourceSchema>,
508    /// The `const` bindings a kernel initializes, in dependency order.
509    const_inits: Vec<crate::kernel::ConstInit>,
510    /// How much of the graph was fused into native cones when the
511    /// program was built: what its kernels report as their engine.
512    cone_mode: crate::compile::cone::JitMode,
513    /// Compiled `for` traversals declared at this program's top level,
514    /// in document order (for_traversal.md). Each carries its child program.
515    traversals: Vec<crate::dsl::traversal::Traversal>,
516    /// Producer bindings (`name := for ...`) declared at this level.
517    producers: Vec<crate::dsl::traversal::Producer>,
518    /// Names declared with the `const` keyword in the source: literal
519    /// consts, folded at build, and consts evaluated when a kernel is
520    /// initialized (`const_inits`). Strict mode reads this set to find a
521    /// const whose value fell through to the enclosing scope.
522    pub(crate) const_outputs: std::collections::HashSet<String>,
523    /// Rule 2 write-through bindings produced when this program
524    /// was synthesized by the subcontext builder's finalize step
525    /// (subcontext_construction.md §3.1).
526    /// Each entry pairs an export name (a cell-bound input slot
527    /// on this program) with the synthetic `__write_<name>`
528    /// source output the rewrite emitted.
529    ///
530    /// Carried on the program — not just on the kernel — so any
531    /// kernel built from this program automatically inherits the
532    /// bindings. Without this, a kernel created from the cached
533    /// program (`from_program` / `create_kernel`) would
534    /// produce a kernel with empty write-throughs and the
535    /// per-cycle commit would silently no-op.
536    pub(crate) write_throughs: Vec<crate::kernel::KernelWriteThrough>,
537    /// Retained AST that produced this program. Live metadata —
538    /// read by the subscope synthesizer to integrate parent
539    /// bindings' matter into child scopes. A binding's graph
540    /// structure may not be contiguous in source text, so the AST
541    /// is the canonical view of what defines each binding. `None`
542    /// only for programmatic construction paths that bypass the
543    /// parser; the DSL entry points always populate this.
544    pub(crate) ast: Option<Arc<PolydatFile>>,
545    /// The ledger this program was recorded in: the root's, shared by
546    /// every program of the tree.
547    ledger: Arc<CompileLedger>,
548    /// The resource scope of the tree this program belongs to: the
549    /// root's, shared by every program of the tree.
550    resources: crate::resource::ResourceScope,
551    /// The digest of the graph the compiler resolved, before the
552    /// interpreter folded or fused it: what makes this program's
553    /// canonical hash equal the compiled engines'. `None` for a program
554    /// built without the compiler, whose own graph is hashed instead.
555    graph_identity: Option<[u8; 32]>,
556}
557
558unsafe impl Send for PolydatProgram {}
559unsafe impl Sync for PolydatProgram {}
560
561impl std::fmt::Debug for PolydatProgram {
562    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
563        f.debug_struct("PolydatProgram")
564            .field("nodes", &self.nodes.len())
565            .field("inputs", &self.input_names())
566            .field("coord_count", &self.coord_count)
567            .finish()
568    }
569}
570
571impl PolydatProgram {
572    /// Create a program with explicit input definitions and output
573    /// ordering, recorded in `ledger`.
574    // Nine parameters describe one compiled program definition; a
575    // params struct would reshape the construction protocol, not
576    // clean up a lint — see `PolydatKernel::new_with_inputs`.
577    #[allow(clippy::too_many_arguments)]
578    pub(crate) fn with_inputs(
579        nodes: Vec<Box<dyn PolydatNode>>,
580        wiring: Vec<Vec<WireSource>>,
581        input_defs: Vec<InputDef>,
582        coord_count: usize,
583        output_map: HashMap<String, (usize, usize)>,
584        output_order: Vec<String>,
585        source: &str,
586        context: &str,
587        ledger: Arc<CompileLedger>,
588    ) -> Self {
589        ledger.record();
590        let inventory = Self::compute_node_inventory(&nodes, &wiring);
591        let input_dependents =
592            Self::compute_dependents(&inventory.input_provenance, input_defs.len());
593        let output_list = Self::build_output_list(&output_order, &output_map);
594        Self {
595            nodes,
596            wiring,
597            input_defs,
598            coord_count,
599            output_map,
600            output_list,
601            input_provenance: inventory.input_provenance,
602            input_dependents,
603            nondet_nodes: inventory.nondet_nodes,
604            side_channel_nodes: inventory.side_channel_nodes,
605            source: Arc::new(source.to_string()),
606            context: Arc::new(context.to_string()),
607            output_modifiers: HashMap::new(),
608            inherited_outputs: std::collections::HashSet::new(),
609            cursor_schemas: Vec::new(),
610            const_inits: Vec::new(),
611            cone_mode: crate::compile::cone::JitMode::Off,
612            traversals: Vec::new(),
613            producers: Vec::new(),
614            const_outputs: std::collections::HashSet::new(),
615            write_throughs: Vec::new(),
616            ast: None,
617            ledger,
618            resources: crate::resource::ResourceScope::new(),
619            graph_identity: None,
620        }
621    }
622
623    /// Mark a binding as declared with the `const` keyword. The
624    /// const-binding contract (evaluation_model.md, "Const Binding
625    /// Contract") is checked against this set.
626    pub(crate) fn mark_const_output(&mut self, name: &str) {
627        self.const_outputs.insert(name.to_string());
628    }
629
630    /// Set the program's Rule 2 write-through bindings. Called
631    /// once by the subcontext builder's finalize step right after
632    /// compile, while the program Arc is still uniquely owned.
633    /// Every kernel built from this program afterwards inherits
634    /// the bindings via `from_program`'s automatic seeding.
635    pub(crate) fn set_write_throughs(
636        &mut self,
637        write_throughs: Vec<crate::kernel::KernelWriteThrough>,
638    ) {
639        self.write_throughs = write_throughs;
640    }
641
642    /// Read this program's Rule 2 write-through bindings.
643    /// Used by `PolydatKernel::from_program` to auto-seed the
644    /// kernel's `write_throughs` field, so the per-fiber
645    /// re-instance path picks them up without a side channel.
646    pub(crate) fn write_throughs(&self) -> &[crate::kernel::KernelWriteThrough] {
647        &self.write_throughs
648    }
649
650    /// Attach the parsed AST as live metadata. Called once by
651    /// every DSL compile entry point right after assembly, while
652    /// the program Arc is still uniquely owned.
653    pub(crate) fn set_ast(&mut self, ast: Arc<PolydatFile>) {
654        self.ast = Some(ast);
655    }
656
657    /// The retained AST that produced this program, if any. The
658    /// subscope synthesizer queries this to integrate parent bindings'
659    /// graph structure into child scopes. Returns `None` for
660    /// programs built via programmatic (non-DSL) paths.
661    pub fn ast(&self) -> Option<&Arc<PolydatFile>> {
662        self.ast.as_ref()
663    }
664
665    /// The compile ledger of the tree this program belongs to.
666    pub fn ledger(&self) -> &Arc<CompileLedger> {
667        &self.ledger
668    }
669
670    /// The resource scope of the tree this program belongs to.
671    pub fn resources(&self) -> &crate::resource::ResourceScope {
672        &self.resources
673    }
674
675    /// Record the resource scope of the tree, before the program is
676    /// shared.
677    pub(crate) fn set_resources(&mut self, resources: crate::resource::ResourceScope) {
678        self.resources = resources;
679    }
680
681    /// Find the `Statement` that defines binding `name` in this
682    /// program's retained AST. Matches both single-target
683    /// `InitBinding`/`CycleBinding` and tuple-target destructuring
684    /// bindings (where `name` is one of several targets). Returns
685    /// `None` if no AST is retained or no binding defines `name`.
686    pub fn binding_ast_for(&self, name: &str) -> Option<&Statement> {
687        let ast = self.ast.as_ref()?;
688        ast.statements.iter().find(|stmt| match stmt {
689            Statement::Binding(b) => b.targets.iter().any(|t| t == name),
690            _ => false,
691        })
692    }
693
694    /// Compute the transitive closure of bindings needed to
695    /// materialise `name` locally in a descendant scope: case 3
696    /// (local matter inclusion) of the wire-reference classification.
697    ///
698    /// Starting from the binding that defines `name`, recursively
699    /// walk the RHS expression tree following `Ident` references.
700    /// For each referenced name, if it's defined by another
701    /// binding in this program's AST AND is not effectively final
702    /// (the four-case rule treats final as a separate cascade),
703    /// include that binding too and recurse.
704    ///
705    /// Termination boundaries:
706    /// - `final` / `shared` outputs (effectively const upstream;
707    ///   caller emits as promoted-final in case 1)
708    /// - `extern` ports (caller handles as case 2 cascade)
709    /// - Input slots (`cycle`, etc.)
710    /// - Names defined nowhere (will surface as unresolved at
711    ///   compile time of the child scope)
712    ///
713    /// Returns the bindings in topological order (dependencies
714    /// first), each statement once: a tuple-target statement whose
715    /// targets are needed more than once appears at the first. The
716    /// contract is wire_materialization.md, "Local inclusion".
717    /// Names already in `excluded` are not re-walked,
718    /// letting callers express "stop here — this name is locally
719    /// defined / coordinated / already collected".
720    pub fn local_inclusion_chain<'a>(
721        &'a self,
722        name: &str,
723        excluded: &std::collections::HashSet<String>,
724    ) -> Vec<&'a Statement> {
725        let mut out: Vec<&'a Statement> = Vec::new();
726        let mut visited: std::collections::HashSet<String> = excluded.clone();
727        self.collect_chain_into(name, &mut out, &mut visited);
728        out
729    }
730
731    fn collect_chain_into<'a>(
732        &'a self,
733        name: &str,
734        out: &mut Vec<&'a Statement>,
735        visited: &mut std::collections::HashSet<String>,
736    ) {
737        if !visited.insert(name.to_string()) {
738            return;
739        }
740        // `final` / `shared` bindings stop the walk: they're case 1
741        // (promoted-final or shared-cell) at the call site, not
742        // case 3. Skip silently.
743        let modifier = self.output_modifier(name);
744        if modifier == crate::dsl::ast::BindingModifier::CONST
745            || modifier == crate::dsl::ast::BindingModifier::SHARED
746        {
747            return;
748        }
749        let Some(stmt) = self.binding_ast_for(name) else {
750            return;
751        };
752        let Statement::Binding(binding) = stmt else {
753            return;
754        };
755        // The statement defines every one of its targets, so each
756        // target is visited now: a tuple-target statement is included
757        // once, however many of its targets the chain needs.
758        for target in &binding.targets {
759            visited.insert(target.clone());
760        }
761        let value = &binding.value;
762        // Recurse into dependencies first, then push this stmt —
763        // produces topo order (deps before dependents).
764        let mut refs = std::collections::HashSet::new();
765        crate::dsl::validate::collect_references(value, &mut refs);
766        let mut refs_sorted: Vec<String> = refs.into_iter().collect();
767        refs_sorted.sort();
768        for r in refs_sorted {
769            self.collect_chain_into(&r, out, visited);
770        }
771        out.push(stmt);
772    }
773
774    /// Read the input classification for slot `idx`.
775    pub fn input_kind(&self, idx: usize) -> Option<crate::kernel::InputKind> {
776        self.input_defs.get(idx).map(|d| d.kind)
777    }
778
779    /// Look up `name` in the output map, returning `(node_idx, port_idx)`.
780    /// Public surface for the scope-init pass and other consumers
781    /// outside the kernel module.
782    pub fn output_map_lookup(&self, name: &str) -> Option<&(usize, usize)> {
783        self.output_map.get(name)
784    }
785
786    /// Iterate every (output-name, (node_idx, port_idx)) pair.
787    /// Used by the eval-panic enricher to reverse-resolve which
788    /// output(s) a given node feeds when reporting which binding
789    /// the panic originated from.
790    pub fn output_map_iter(&self) -> impl Iterator<Item = (&String, &(usize, usize))> {
791        self.output_map.iter()
792    }
793
794    /// Set the binding modifier for a named output.
795    pub(crate) fn set_output_modifier(
796        &mut self,
797        name: &str,
798        modifier: crate::dsl::ast::BindingModifier,
799    ) {
800        if modifier != crate::dsl::ast::BindingModifier::NONE {
801            self.output_modifiers.insert(name.to_string(), modifier);
802            if modifier.is_volatile() {
803                self.refresh_never_current();
804            }
805        }
806    }
807
808    /// Recompute the nodes an engine may never treat as current.
809    ///
810    /// The inventory computes that set when the program is built,
811    /// from the nodes' own declarations, and the output modifiers are
812    /// installed after — so the build's set leaves out a node feeding
813    /// a `volatile` output, and this recomputes it. `volatile` is the
814    /// author's statement that a wire's value is not a function of
815    /// its inputs, which is precisely the case the node cannot declare
816    /// for itself, and evaluation_model.md §"Non-Deterministic Nodes"
817    /// says such a node is excluded from the fold *and* never treated
818    /// as current, so a volatile binding is not cached per cycle.
819    fn refresh_never_current(&mut self) {
820        let classes = Self::classify_lifecycle(
821            &self.nodes,
822            &self.wiring,
823            &self.input_defs,
824            &self.output_map,
825            &self.output_modifiers,
826        );
827        let mut marked = vec![false; self.nodes.len()];
828        for &i in &self.nondet_nodes {
829            marked[i] = true;
830        }
831        for (i, nd) in classes.nondeterministic.iter().enumerate() {
832            if *nd {
833                marked[i] = true;
834            }
835        }
836        self.nondet_nodes = marked
837            .iter()
838            .enumerate()
839            .filter_map(|(i, m)| m.then_some(i))
840            .collect();
841    }
842
843    /// Query the binding modifier for a named output.
844    pub fn output_modifier(&self, name: &str) -> crate::dsl::ast::BindingModifier {
845        self.output_modifiers
846            .get(name)
847            .copied()
848            .unwrap_or(crate::dsl::ast::BindingModifier::NONE)
849    }
850
851    /// Return all output names that have the `shared` modifier.
852    pub fn shared_outputs(&self) -> Vec<&str> {
853        self.output_modifiers
854            .iter()
855            .filter(|(_, m)| **m == crate::dsl::ast::BindingModifier::SHARED)
856            .map(|(n, _)| n.as_str())
857            .collect()
858    }
859
860    /// Mark `name` as an inherited (cascade-propagated) output —
861    /// declared on this program only to flow the value through
862    /// to descendants via `materialize_wiring_from_outer`, not because this
863    /// scope's own bindings or specs reference it.
864    pub fn mark_inherited(&mut self, name: &str) {
865        self.inherited_outputs.insert(name.to_string());
866    }
867
868    /// Is `name` an inherited (cascade-propagated) output? See
869    /// [`Self::mark_inherited`].
870    pub fn is_inherited(&self, name: &str) -> bool {
871        self.inherited_outputs.contains(name)
872    }
873
874    /// Return only the outputs *owned* by this program — names
875    /// the scope's own bindings, externs, or specs declared,
876    /// excluding inherited cascade-propagation outputs. Used by
877    /// the scenario tree pre-map and TUI to render per-scope
878    /// "what's defined here" without listing every inherited
879    /// name. Output order matches `output_names`.
880    pub fn own_output_names(&self) -> Vec<&str> {
881        self.output_names()
882            .into_iter()
883            .filter(|name| !self.inherited_outputs.contains(*name))
884            .collect()
885    }
886
887    /// Return all output names that have the `const` modifier.
888    pub fn const_outputs(&self) -> Vec<&str> {
889        self.output_modifiers
890            .iter()
891            .filter(|(_, m)| **m == crate::dsl::ast::BindingModifier::CONST)
892            .map(|(n, _)| n.as_str())
893            .collect()
894    }
895
896    /// The original source text that produced this program.
897    pub fn source(&self) -> &str {
898        &self.source
899    }
900
901    /// Diagnostic context (e.g., "workload.yaml bindings").
902    pub fn context(&self) -> &str {
903        &self.context
904    }
905
906    /// Source schemas declared in this program. The runtime queries
907    /// these to discover data sources, their extents, and projections.
908    pub fn cursor_schemas(&self) -> &[crate::iteration::source::SourceSchema] {
909        &self.cursor_schemas
910    }
911
912    /// Set source schemas (called by the compiler after processing source declarations).
913    pub(crate) fn set_cursor_schemas(
914        &mut self,
915        schemas: Vec<crate::iteration::source::SourceSchema>,
916    ) {
917        self.cursor_schemas = schemas;
918    }
919
920    /// The `const` bindings a kernel of this program initializes, in the
921    /// order it evaluates them.
922    pub fn const_inits(&self) -> &[crate::kernel::ConstInit] {
923        &self.const_inits
924    }
925
926    /// Whether the output's value is fixed for a kernel's life: a
927    /// `const`, captured at initialization, or a value folded at build,
928    /// whose node reads nothing and is not nondeterministic. A computed
929    /// output is not, whether or not it has been pulled.
930    pub(crate) fn is_fixed_output(&self, name: &str) -> bool {
931        if self.const_outputs.contains(name) {
932            return true;
933        }
934        self.output_map.get(name).is_some_and(|(node, _)| {
935            self.wiring[*node].is_empty() && !self.nondet_nodes.contains(node)
936        })
937    }
938
939    /// Record the const bindings, before the program is shared.
940    pub(crate) fn set_const_inits(&mut self, inits: Vec<crate::kernel::ConstInit>) {
941        self.const_inits = inits;
942    }
943
944    /// How much of the graph was fused into native cones at build.
945    pub fn cone_mode(&self) -> crate::compile::cone::JitMode {
946        self.cone_mode
947    }
948
949    pub(crate) fn set_cone_mode(&mut self, mode: crate::compile::cone::JitMode) {
950        self.cone_mode = mode;
951    }
952
953    /// The `for` traversals declared at this program's top level, each
954    /// with its compiled child program (for_traversal.md §5.1: one program per
955    /// lexical position).
956    pub fn traversals(&self) -> &[crate::dsl::traversal::Traversal] {
957        &self.traversals
958    }
959
960    /// Producer bindings declared at this program's top level.
961    pub fn producers(&self) -> &[crate::dsl::traversal::Producer] {
962        &self.producers
963    }
964
965    pub(crate) fn set_traversals(
966        &mut self,
967        traversals: Vec<crate::dsl::traversal::Traversal>,
968        producers: Vec<crate::dsl::traversal::Producer>,
969    ) {
970        self.traversals = traversals;
971        self.producers = producers;
972    }
973
974    /// Build ordered output list from declaration order and the output map.
975    fn build_output_list(
976        output_order: &[String],
977        output_map: &HashMap<String, (usize, usize)>,
978    ) -> Vec<(String, usize, usize)> {
979        // Use declaration order from the assembler
980        let mut list: Vec<(String, usize, usize)> = output_order
981            .iter()
982            .filter_map(|name| output_map.get(name).map(|&(ni, pi)| (name.clone(), ni, pi)))
983            .collect();
984        // Add any outputs not in the declaration order (shouldn't happen,
985        // but defensive against manual assembler use). Sort the
986        // tail by name so the ordering is deterministic across
987        // processes — HashMap iteration is per-process-randomised,
988        // and a deterministic tail keeps the canonical-program
989        // identity (and therefore checkpoint phase-hash) stable
990        // across resume invocations.
991        let mut tail: Vec<(&String, &(usize, usize))> = output_map
992            .iter()
993            .filter(|(name, _)| !output_order.contains(*name))
994            .collect();
995        tail.sort_by(|a, b| a.0.cmp(b.0));
996        for (name, &(ni, pi)) in tail {
997            list.push((name.clone(), ni, pi));
998        }
999        list
1000    }
1001
1002    /// Invert provenance into per-input dependent node lists.
1003    pub(crate) fn compute_dependents(
1004        provenance: &[ProvMask],
1005        num_inputs: usize,
1006    ) -> Vec<Vec<usize>> {
1007        let mut deps = vec![Vec::new(); num_inputs];
1008        for (node_idx, prov) in provenance.iter().enumerate() {
1009            for (input_idx, dep) in deps.iter_mut().enumerate() {
1010                if prov.contains(input_idx) {
1011                    dep.push(node_idx);
1012                }
1013            }
1014        }
1015        deps
1016    }
1017
1018    /// Thin projection for callers that need only the provenance
1019    /// masks (assembly/select/hybrid feed them straight into
1020    /// [`Self::compute_dependents`]). Same ONE walker underneath.
1021    pub(crate) fn compute_provenance(
1022        nodes: &[Box<dyn PolydatNode>],
1023        wiring: &[Vec<WireSource>],
1024    ) -> Vec<ProvMask> {
1025        Self::compute_node_inventory(nodes, wiring).input_provenance
1026    }
1027
1028    /// The runtime model's lifecycle classification of every node
1029    /// (graph_compiler.md §3.1), the one rule the interpreter's
1030    /// fold and every compiled engine share: a node is compile-constant
1031    /// when no coordinate or external-write input reaches it and neither
1032    /// it nor anything upstream is declared nondeterministic or
1033    /// `volatile`; scope-init when only iteration externs reach it;
1034    /// dynamic otherwise. `nondeterministic` is the declared volatility
1035    /// and its downstream contagion on its own, which an engine never
1036    /// treats as current.
1037    pub(crate) fn classify_lifecycle(
1038        nodes: &[Box<dyn PolydatNode>],
1039        wiring: &[Vec<WireSource>],
1040        input_defs: &[InputDef],
1041        output_map: &HashMap<String, (usize, usize)>,
1042        output_modifiers: &HashMap<String, crate::dsl::ast::BindingModifier>,
1043    ) -> LifecycleClasses {
1044        use crate::kernel::InputKind;
1045        let n = nodes.len();
1046        let mut lifecycle: Vec<EvalLifecycle> = vec![EvalLifecycle::CompileConst; n];
1047        let mut nondeterministic: Vec<bool> = vec![false; n];
1048        for (i, wires) in wiring.iter().enumerate() {
1049            for source in wires {
1050                if let WireSource::Input(idx) = source {
1051                    let kind = input_defs
1052                        .get(*idx)
1053                        .map(|d| d.kind)
1054                        .unwrap_or(InputKind::Coordinate);
1055                    let lc = match kind {
1056                        // A const slot holds a value fixed when the kernel is
1057                        // initialized, so what reads it is not per-cycle work.
1058                        InputKind::IterationExtern | InputKind::Const => EvalLifecycle::ScopeInit,
1059                        InputKind::Coordinate | InputKind::ExternalWrite => EvalLifecycle::Dynamic,
1060                    };
1061                    if lc > lifecycle[i] {
1062                        lifecycle[i] = lc;
1063                    }
1064                }
1065            }
1066            // Per R1.v: a node declaring `Purity::Nondeterministic` is
1067            // intrinsically volatile; the fold leaves it alone and the
1068            // canonical hash sees its shape, never a value.
1069            let declared = matches!(
1070                nodes[i].purity(),
1071                crate::ast::Purity::Nondeterministic { .. }
1072            );
1073            // `volatile` is the author's declaration that a wire's
1074            // value is nondeterministic across invocations and must not
1075            // be folded into the workload's identity
1076            // (composition_substrate.md §3, "Volatility opt-in"). Every
1077            // output modifier is walked, not only the
1078            // exposed outputs, so a binding pruned from the output list
1079            // still marks its producing node.
1080            let modifier = output_modifiers.iter().any(|(name, m)| {
1081                m.is_volatile()
1082                    && output_map
1083                        .get(name)
1084                        .map(|(ni, _)| *ni == i)
1085                        .unwrap_or(false)
1086            });
1087            if declared || modifier {
1088                lifecycle[i] = EvalLifecycle::Dynamic;
1089                nondeterministic[i] = true;
1090            }
1091        }
1092        // Propagate: a node's lifecycle is the max of its own seed and
1093        // every upstream node's, and volatility is contagious downstream.
1094        let mut changed = true;
1095        while changed {
1096            changed = false;
1097            for i in 0..n {
1098                for source in &wiring[i] {
1099                    if let WireSource::NodeOutput(upstream, _) = source {
1100                        if lifecycle[*upstream] > lifecycle[i] {
1101                            lifecycle[i] = lifecycle[*upstream];
1102                            changed = true;
1103                        }
1104                        if nondeterministic[*upstream] && !nondeterministic[i] {
1105                            nondeterministic[i] = true;
1106                            changed = true;
1107                        }
1108                    }
1109                }
1110            }
1111        }
1112        LifecycleClasses {
1113            lifecycle,
1114            nondeterministic,
1115        }
1116    }
1117
1118    /// THE node-inventory walker — the ONE forward pass over the
1119    /// wire graph that computes every per-node reachability
1120    /// attribute the program carries:
1121    ///
1122    /// - **input provenance** — which inputs transitively feed
1123    ///   each node, as an exact multi-word [`ProvMask`], so a
1124    ///   consumed-params projection on a many-param workload root
1125    ///   sees every input it reads;
1126    /// - **nondeterminism contagion** — nullary or
1127    ///   `Purity::Nondeterministic` nodes and everything
1128    ///   downstream of them (per R1.v's intrinsic-volatility
1129    ///   carve-out; consumers of a volatile producer must not
1130    ///   retain stale cached values across cycles);
1131    /// - **side-channel contagion** — nodes whose dependency
1132    ///   cone contains a `Purity::SideChannel` node (`log_*`,
1133    ///   diagnostics), so the per-cycle fire-side-effects pass
1134    ///   knows which outputs to pull.
1135    ///
1136    /// Every other consumer — engine invalidation
1137    /// (`compute_dependents` → `input_dependents`, and the JIT's
1138    /// slot provenance derived from it), `extern_closure`,
1139    /// `cone_has_side_channel`, the two state constructors — is
1140    /// a PROJECTION of this inventory. Do not add another
1141    /// traversal over `wiring` for a per-node attribute; add a
1142    /// field here. (The engine cone guards — JIT and closure
1143    /// kernels' slot provenance / changed masks — carry the same
1144    /// multi-word [`ProvMask`] shape host-side; the generated
1145    /// machine code never sees a mask.)
1146    ///
1147    /// Fixpoint iteration (not a single topo pass) so the
1148    /// inventory is correct regardless of node ordering; the
1149    /// graphs are DAGs, so it converges in at most graph-depth
1150    /// rounds and in practice two.
1151    pub(crate) fn compute_node_inventory(
1152        nodes: &[Box<dyn PolydatNode>],
1153        wiring: &[Vec<WireSource>],
1154    ) -> NodeInventory {
1155        let n = nodes.len();
1156        let mut prov: Vec<ProvMask> = (0..n).map(|_| ProvMask::empty()).collect();
1157        let mut nondet: Vec<bool> = (0..n)
1158            .map(|i| {
1159                let nullary = wiring[i].is_empty() && nodes[i].meta().ins.is_empty();
1160                let declared = matches!(
1161                    nodes[i].purity(),
1162                    crate::ast::Purity::Nondeterministic { .. }
1163                );
1164                nullary || declared
1165            })
1166            .collect();
1167        let mut side: Vec<bool> = (0..n)
1168            .map(|i| matches!(nodes[i].purity(), crate::ast::Purity::SideChannel { .. }))
1169            .collect();
1170
1171        let mut changed = true;
1172        while changed {
1173            changed = false;
1174            for i in 0..n {
1175                for source in &wiring[i] {
1176                    match source {
1177                        WireSource::Input(idx) => {
1178                            changed |= prov[i].set(*idx);
1179                        }
1180                        WireSource::NodeOutput(up, _) => {
1181                            let up = *up;
1182                            if up == i {
1183                                continue; // defensive: DAGs don't self-loop
1184                            }
1185                            let (a, b) = if up < i {
1186                                let (l, r) = prov.split_at_mut(i);
1187                                (&l[up], &mut r[0])
1188                            } else {
1189                                let (l, r) = prov.split_at_mut(up);
1190                                (&r[0], &mut l[i])
1191                            };
1192                            changed |= b.union_with(a);
1193                            if nondet[up] && !nondet[i] {
1194                                nondet[i] = true;
1195                                changed = true;
1196                            }
1197                            if side[up] && !side[i] {
1198                                side[i] = true;
1199                                changed = true;
1200                            }
1201                        }
1202                    }
1203                }
1204            }
1205        }
1206        NodeInventory {
1207            input_provenance: prov,
1208            nondet_nodes: (0..n).filter(|&i| nondet[i]).collect(),
1209            side_channel_nodes: side,
1210        }
1211    }
1212
1213    /// The scratch every node of this program declares, one set per
1214    /// node, for a state of its own (axiom S3): storage belongs to the
1215    /// state, never to the shared node.
1216    fn node_scratch(&self) -> Vec<Vec<crate::ast::ScratchBuf>> {
1217        self.nodes
1218            .iter()
1219            .map(|n| {
1220                n.scratch_layout()
1221                    .into_iter()
1222                    .map(crate::ast::ScratchBuf::new)
1223                    .collect()
1224            })
1225            .collect()
1226    }
1227
1228    /// Build an EngineCore (shared by all state constructors).
1229    fn build_engine_core(&self) -> EngineCore {
1230        let buffers: Vec<Vec<Value>> = self
1231            .nodes
1232            .iter()
1233            .map(|n| vec![Value::None; n.meta().outs.len()])
1234            .collect();
1235        let node_count = self.nodes.len();
1236        let inputs: Vec<Value> = self.input_defs.iter().map(|d| d.default.clone()).collect();
1237        let input_defaults = inputs.clone();
1238        let max_inputs = self.wiring.iter().map(|w| w.len()).max().unwrap_or(0);
1239        let input_count = inputs.len();
1240        EngineCore {
1241            buffers,
1242            node_clean: vec![false; node_count],
1243            inputs,
1244            input_defaults,
1245            shared_cells: vec![None; input_count],
1246            // Broadcast cells allocated by `seed_output_cells`
1247            // (called from kernel constructors;
1248            // cross_fiber_invalidation.md §3.1). Start with an
1249            // empty Vec — the seed pass sizes it to match output
1250            // count.
1251            output_cells: Vec::new(),
1252            broadcasting: std::sync::atomic::AtomicBool::new(false),
1253            input_scratch: vec![Value::None; max_inputs],
1254            node_scratch: self.node_scratch(),
1255            // Per-scope intent-dirty vector + bit allocator
1256            // (cross_fiber_invalidation.md §3.1). Fresh atomic
1257            // per EngineCore — one per fiber state — so cells
1258            // allocated through this core publish their dirty
1259            // intent through a single shared atomic that this
1260            // fiber's check_clean walker reads against the
1261            // cone's interest mask.
1262            scope_intent_words: Vec::new(),
1263            next_cell_bit: 0,
1264            last_seen: std::collections::HashMap::new(),
1265            cell_cones: Vec::new(),
1266        }
1267    }
1268
1269    /// Create a new evaluation state for this program.
1270    pub fn create_state(&self) -> PolydatState {
1271        let buffers: Vec<Vec<Value>> = self
1272            .nodes
1273            .iter()
1274            .map(|n| vec![Value::None; n.meta().outs.len()])
1275            .collect();
1276        let node_count = self.nodes.len();
1277
1278        let inputs: Vec<Value> = self.input_defs.iter().map(|d| d.default.clone()).collect();
1279        let input_defaults = inputs.clone();
1280
1281        let max_inputs = self.wiring.iter().map(|w| w.len()).max().unwrap_or(0);
1282
1283        // Nondeterminism contagion (R1.v's intrinsic-volatility
1284        // carve-out): precomputed by the ONE inventory walker at
1285        // construction — see `compute_node_inventory`.
1286        let nondeterministic_nodes: Vec<usize> = self.nondet_nodes.clone();
1287
1288        let input_count = inputs.len();
1289        let core = EngineCore {
1290            buffers,
1291            node_clean: vec![false; node_count],
1292            inputs,
1293            input_defaults,
1294            shared_cells: vec![None; input_count],
1295            // Broadcast cells allocated by `seed_output_cells`
1296            // (called from kernel constructors;
1297            // cross_fiber_invalidation.md §3.1). Start with an
1298            // empty Vec — the seed pass sizes it to match output
1299            // count.
1300            output_cells: Vec::new(),
1301            broadcasting: std::sync::atomic::AtomicBool::new(false),
1302            input_scratch: vec![Value::None; max_inputs],
1303            node_scratch: self.node_scratch(),
1304            // Per-scope intent-dirty vector + bit allocator
1305            // (cross_fiber_invalidation.md §3.1).
1306            scope_intent_words: Vec::new(),
1307            next_cell_bit: 0,
1308            last_seen: std::collections::HashMap::new(),
1309            cell_cones: Vec::new(),
1310        };
1311
1312        PolydatState::from_parts(core, self.input_dependents.clone(), nondeterministic_nodes)
1313    }
1314
1315    /// Create the provenance-scan engine state (for benchmarking).
1316    pub fn create_provscan_state(&self) -> ProvScanState {
1317        let core = self.build_engine_core();
1318        // Nondeterminism contagion (R1.v's intrinsic-volatility
1319        // carve-out): precomputed by the ONE inventory walker at
1320        // construction — see `compute_node_inventory`.
1321        let nondeterministic_nodes: Vec<usize> = self.nondet_nodes.clone();
1322        ProvScanState::from_parts(core, self.input_provenance.clone(), nondeterministic_nodes)
1323    }
1324
1325    /// Return the names of all inputs.
1326    pub fn input_names(&self) -> Vec<String> {
1327        self.input_defs.iter().map(|d| d.name.clone()).collect()
1328    }
1329
1330    /// Return the number of coordinate inputs.
1331    pub fn coord_count(&self) -> usize {
1332        self.coord_count
1333    }
1334
1335    /// Find an input by name. Returns its index.
1336    pub fn find_input(&self, name: &str) -> Option<usize> {
1337        self.input_defs.iter().position(|d| d.name == name)
1338    }
1339
1340    /// Lookup the declared port type of a named input: for a converted
1341    /// input, the type its readers see, not the `Dyn` slot it is
1342    /// written through (input_variance.md §5).
1343    /// Returns `None` if the name isn't an input of this program.
1344    pub fn input_port_type(&self, name: &str) -> Option<crate::ast::PortType> {
1345        self.input_defs
1346            .iter()
1347            .find(|d| d.name == name)
1348            .map(|d| d.converts_to.unwrap_or(d.port_type))
1349    }
1350
1351    /// How input `name`'s type was established (input_variance.md §3).
1352    pub fn input_type_origin(&self, name: &str) -> Option<crate::kernel::TypeOrigin> {
1353        self.input_defs
1354            .iter()
1355            .find(|d| d.name == name)
1356            .map(|d| d.type_origin)
1357    }
1358
1359    /// Lookup the declared port type of an input by index.
1360    /// Returns `None` if `idx` is out of range. The typed write
1361    /// checks a value against it without reverse-resolving an index
1362    /// to a name.
1363    pub fn input_port_type_by_idx(&self, idx: usize) -> Option<crate::ast::PortType> {
1364        self.input_defs.get(idx).map(|d| d.port_type)
1365    }
1366
1367    /// The declared default for input `idx` — the wire's initial
1368    /// element. The capture layer's reset semantics (an empty
1369    /// min/max fold restores the wire to its author-declared
1370    /// identity rather than leaving `Value::None` on a typed slot)
1371    /// read it through this accessor.
1372    pub fn input_default_by_idx(&self, idx: usize) -> Option<&Value> {
1373        self.input_defs.get(idx).map(|d| &d.default)
1374    }
1375
1376    /// The name of the input at `idx`, if there is one.
1377    pub fn input_name_by_idx(&self, idx: usize) -> Option<&str> {
1378        self.input_defs.get(idx).map(|d| d.name.as_str())
1379    }
1380
1381    /// Number of declared outputs.
1382    pub fn output_count(&self) -> usize {
1383        self.output_list.len()
1384    }
1385
1386    /// Output name at index (declaration order).
1387    pub fn output_name(&self, idx: usize) -> &str {
1388        &self.output_list[idx].0
1389    }
1390
1391    /// Return all output names in declaration order.
1392    pub fn output_names(&self) -> Vec<&str> {
1393        self.output_list
1394            .iter()
1395            .map(|(n, _, _)| n.as_str())
1396            .collect()
1397    }
1398
1399    /// Resolve an output name to its (node_index, port_index).
1400    ///
1401    /// Dotted names follow the field-access wire convention
1402    /// (`q.cursor.idx` is the wire `q__cursor__idx`), so a
1403    /// text-context reference resolves through the same
1404    /// flattening the DSL compiler applies — mirroring
1405    /// `PolydatKernel::lookup`.
1406    pub fn resolve_output(&self, name: &str) -> Option<(usize, usize)> {
1407        if let Some(found) = self.output_map.get(name).copied() {
1408            return Some(found);
1409        }
1410        if name.contains('.') {
1411            return self.output_map.get(&name.replace('.', "__")).copied();
1412        }
1413        None
1414    }
1415
1416    /// The dataset forms the output `name` can depend on, through any
1417    /// path of the program: what a host needs, before the first cycle,
1418    /// to know which forms a `fragment` wire's values can belong to.
1419    /// `None` when the program has no such output.
1420    ///
1421    /// The answer comes from the program's wiring and is conservative:
1422    /// every input of every node the output can read is followed, so a
1423    /// node that selects between two wires contributes both, and a
1424    /// source the output never reads at run time may be listed, while
1425    /// one it does read never is missed. A host that prepares
1426    /// statements for one set of forms per wire accepts an output with
1427    /// exactly one source and refuses any other.
1428    ///
1429    /// Every engine's kernel answers the same question with the same
1430    /// answer ([`Kernel::dataset_sources`](super::Kernel::dataset_sources)),
1431    /// so a host holding a compiled kernel asks that.
1432    ///
1433    /// A source is one of three things ([`DatasetSources`]): a `forms`
1434    /// value fixed when the program was built, which is here to be
1435    /// read; a `forms` or `fragment` input; or a node that computes
1436    /// `forms` from something that is not constant, whose forms cannot
1437    /// be known before a cycle.
1438    ///
1439    /// An input is read on the kernel that has it, with no other scope
1440    /// consulted. A `forms` input is a constant of the enclosing scope,
1441    /// copied into this kernel when it was bound, so
1442    /// [`Kernel::input_value`](super::Kernel::input_value) hands back
1443    /// the forms before any cycle. A `fragment` input is a per-cycle
1444    /// value and holds nothing until its scope computes one, so nothing
1445    /// is known of it at construction: a scope that must know its forms
1446    /// then takes the `forms` and makes the fragment itself
1447    /// (`extern forms: forms`, then `predicate_at(forms, q)`). The
1448    /// [host questions guide] shows both with running programs.
1449    ///
1450    /// [host questions guide]: https://github.com/nosqlbench/polydat/blob/main/crates/polydat/docs/guides/host_questions.md
1451    pub fn dataset_sources(&self, name: &str) -> Option<DatasetSources> {
1452        let (start, _) = self.resolve_output(name)?;
1453        Some(dataset_sources_of(
1454            &self.nodes,
1455            &self.wiring,
1456            &self.input_defs,
1457            start,
1458        ))
1459    }
1460
1461    /// Resolve an output index to its (node_index, port_index).
1462    pub fn resolve_output_by_index(&self, idx: usize) -> (usize, usize) {
1463        let (_, ni, pi) = &self.output_list[idx];
1464        (*ni, *pi)
1465    }
1466
1467    /// Output names whose dependency cone contains a side-effecting
1468    /// (`Purity::SideChannel`) node — `log_*`, diagnostics, etc. These
1469    /// are the outputs a per-cycle "fire side effects" pass must pull so
1470    /// the effect runs even when the value is unused. An output whose
1471    /// cone is side-effect-free — including a pure or volatile
1472    /// metric-reader value — is excluded: it is evaluated only when its
1473    /// value is actually consumed, never per cycle just to fire a
1474    /// non-existent effect.
1475    pub fn outputs_with_side_effects(&self) -> Vec<String> {
1476        self.output_list
1477            .iter()
1478            .filter(|(_, node_idx, _)| self.cone_has_side_channel(*node_idx))
1479            .map(|(name, _, _)| name.clone())
1480            .collect()
1481    }
1482
1483    /// True if `start`'s transitive input cone contains a node declaring
1484    /// `Purity::SideChannel`. A projection of the construction-time
1485    /// node inventory — see [`Self::compute_node_inventory`].
1486    fn cone_has_side_channel(&self, start: usize) -> bool {
1487        self.side_channel_nodes.get(start).copied().unwrap_or(false)
1488    }
1489
1490    /// Find the output index for a name (for building memoized getters).
1491    pub(crate) fn output_list(&self) -> &[(String, usize, usize)] {
1492        &self.output_list
1493    }
1494
1495    /// The position of a named output in the output list, if declared.
1496    pub fn output_index(&self, name: &str) -> Option<usize> {
1497        self.output_list.iter().position(|(n, _, _)| n == name)
1498    }
1499
1500    /// Look up an output's [`crate::ast::PortType`] by name.
1501    ///
1502    /// Returns `None` for names not declared as outputs of this
1503    /// program. Used by the binder verification path
1504    /// (`polydat::binder::verify_against_kernel`) to type-check
1505    /// adapter binding shapes against the actual kernel wire
1506    /// types — symmetric counterpart to `input_port_type`.
1507    pub fn output_port_type(&self, name: &str) -> Option<crate::ast::PortType> {
1508        let (node_idx, port_idx) = self.resolve_output(name)?;
1509        let meta = self.node_meta(node_idx);
1510        meta.outs.get(port_idx).map(|out| out.typ)
1511    }
1512
1513    /// Get the provenance mask for a node by index. `None` for an
1514    /// out-of-range node index.
1515    pub fn input_provenance_for(&self, node_idx: usize) -> Option<&ProvMask> {
1516        self.input_provenance.get(node_idx)
1517    }
1518
1519    /// Hash-compare two programs for AST / constant
1520    /// equivalence. Two programs that produce the
1521    /// same `canonical_hash` are functionally equivalent at
1522    /// compile time; their runtime instances would differ
1523    /// only by parent-bound values, which `materialize_wiring_from_outer`
1524    /// handles. Cheap (one hash compare); doesn't allocate
1525    /// state. The pre-walker uses this to flatten one scope
1526    /// into another that materialises identical content.
1527    pub fn is_equivalent_to(&self, other: &PolydatProgram) -> bool {
1528        self.canonical_hash() == other.canonical_hash()
1529    }
1530
1531    /// The "can-flatten?" predicate. Returns true
1532    /// when this program adds no Polydat content the parent
1533    /// program doesn't already supply — i.e. when the inner
1534    /// scope's contribution is structurally a subset of the
1535    /// parent's. The pre-walker uses this for nodes that
1536    /// classified as `PolydatMatter::Definitions` to detect cases
1537    /// where the new content turns out to be parent-equivalent
1538    /// (rare, but correct: a binding that duplicates a parent
1539    /// declaration is structurally a no-op).
1540    ///
1541    /// The check is structural: true when the inner program has
1542    /// no outputs but its inputs' own and no inputs beyond what the
1543    /// parent already exposes. New bindings whose definitions equal
1544    /// parent bindings are not recognized as a subset.
1545    pub fn is_subset_of(&self, parent: &PolydatProgram) -> bool {
1546        // Equivalent programs flatten trivially.
1547        if self.is_equivalent_to(parent) {
1548            return true;
1549        }
1550        // The inner program contributes new content if it
1551        // declares outputs the parent doesn't, or constants
1552        // / nodes the parent doesn't carry. Cheapest check:
1553        // an inner program with no outputs of its own and
1554        // every input also declared by the parent is a
1555        // structural no-op. An output named for an input is the
1556        // input itself, which the compiler re-exports by name.
1557        let inputs: std::collections::HashSet<&str> =
1558            self.input_defs.iter().map(|d| d.name.as_str()).collect();
1559        if self
1560            .output_list
1561            .iter()
1562            .any(|(name, _, _)| !inputs.contains(name.as_str()))
1563        {
1564            return false;
1565        }
1566        // Inputs: every name declared by `self` must be
1567        // declared by `parent` (parent supplies the value).
1568        // Inner program might have empty input_defs entirely
1569        // — that's the "trivial wrapper" case and trivially
1570        // a subset.
1571        let parent_inputs: std::collections::HashSet<&str> =
1572            parent.input_defs.iter().map(|d| d.name.as_str()).collect();
1573        for d in &self.input_defs {
1574            if !parent_inputs.contains(d.name.as_str()) {
1575                return false;
1576            }
1577        }
1578        true
1579    }
1580
1581    /// Aggregate identity over this program **plus** an outer
1582    /// chain of ancestor programs (innermost first; the
1583    /// workload-root program is last). The result is a
1584    /// SHA-256 over each program's `canonical_hash` in
1585    /// declaration order, prefixed with a versioned tag so
1586    /// future reshapings can be detected.
1587    ///
1588    /// **Use this when callers need "did anything in scope
1589    /// change?"** — including upstream bindings that feed
1590    /// in via auto-extern. `canonical_hash` (the per-program
1591    /// flavour) covers only this program's own AST and
1592    /// cannot detect a workload-param edit that lands in a
1593    /// parent kernel's const slots.
1594    ///
1595    /// `canonical_hash` stays a pure local operation (no
1596    /// kernel-chain dependency); Polydat refuses to walk parent
1597    /// scopes inside a per-program hash. The runtime owns
1598    /// the parent-chain walk and feeds the resulting program
1599    /// chain here. Callers are responsible for ensuring every
1600    /// piece of state that should affect identity lives in
1601    /// some attached Polydat module — e.g. a host injects workload
1602    /// `params:` as a synthetic root module
1603    /// (`build_workload_params_kernel`) whose `const` bindings
1604    /// land in const slots `canonical_hash` covers.
1605    pub fn instance_hash(&self, ancestors: &[&PolydatProgram]) -> [u8; 32] {
1606        let chain: Vec<[u8; 32]> = ancestors.iter().map(|a| a.canonical_hash()).collect();
1607        instance_hash_of(self.canonical_hash(), &chain)
1608    }
1609
1610    /// Names of the non-coordinate inputs (iteration externs and
1611    /// external-write ports) that transitively feed the given
1612    /// outputs — the backward dataflow slice a scope needs from
1613    /// its enclosing scopes to produce exactly those outputs.
1614    ///
1615    /// A projection of the construction-time node inventory (see
1616    /// `Self::compute_node_inventory` — no traversal here):
1617    /// union the producing nodes' provenance masks, then map set
1618    /// bits to input names whose kind is not
1619    /// [`super::InputKind::Coordinate`] (coordinates are runtime
1620    /// dimensions like `cycle`, not outer-scope matter). Requested
1621    /// names this program does not declare as outputs are ignored
1622    /// — the caller keeps them unresolved and continues up its
1623    /// chain. Sorted, deduplicated.
1624    ///
1625    /// A host uses this per-ancestor to derive a phase's
1626    /// consumed-params closure: which workload params actually
1627    /// reach a given phase through the scope chain.
1628    pub fn extern_closure(&self, outputs: &[&str]) -> Vec<String> {
1629        let mut mask = ProvMask::empty();
1630        for (name, ni, _) in &self.output_list {
1631            if outputs.contains(&name.as_str())
1632                && let Some(prov) = self.input_provenance.get(*ni)
1633            {
1634                mask.union_with(prov);
1635            }
1636        }
1637        let names: std::collections::BTreeSet<String> = mask
1638            .iter_ones()
1639            .filter_map(|idx| self.input_defs.get(idx))
1640            .filter(|def| def.kind != super::InputKind::Coordinate)
1641            .map(|def| def.name.clone())
1642            .collect();
1643        names.into_iter().collect()
1644    }
1645
1646    /// [`Self::extern_closure`] over this program's OWNED outputs
1647    /// — inherited passthrough re-exports excluded. Ownership is
1648    /// what distinguishes consumption from plumbing: the scope
1649    /// cascade re-exports every inherited name so descendants can
1650    /// materialize it, and those passthroughs must not read as
1651    /// "this scope needs the name".
1652    pub fn owned_extern_closure(&self) -> Vec<String> {
1653        let owned: Vec<&str> = self
1654            .output_names()
1655            .into_iter()
1656            .filter(|n| !self.is_inherited(n))
1657            .collect();
1658        self.extern_closure(&owned)
1659    }
1660
1661    /// Resolve a seed of unresolved extern names THROUGH a chain
1662    /// of enclosing scope programs — innermost first, the same
1663    /// chain shape [`Self::instance_hash`] takes. Each name an
1664    /// ancestor outputs is replaced by that output's own extern
1665    /// slice ([`Self::extern_closure`] — per-output dataflow, so
1666    /// sibling outputs' externs are never dragged in); a
1667    /// passthrough re-export removes and re-adds the name, which
1668    /// is exactly "keep walking up"; a name no ancestor outputs
1669    /// stays. The returned TERMINAL set is what the outermost
1670    /// scope (e.g. a host's synthetic params module) must
1671    /// satisfy — a host's consumed-params derivation intersects
1672    /// it with the declared param names. Sorted, deduplicated.
1673    pub fn resolve_externs_through(
1674        seed: impl IntoIterator<Item = String>,
1675        ancestors: &[&PolydatProgram],
1676    ) -> Vec<String> {
1677        let mut unresolved: std::collections::BTreeSet<String> = seed.into_iter().collect();
1678        for prog in ancestors {
1679            if unresolved.is_empty() {
1680                break;
1681            }
1682            let outputs: std::collections::BTreeSet<&str> =
1683                prog.output_names().into_iter().collect();
1684            let produced: Vec<String> = unresolved
1685                .iter()
1686                .filter(|n| outputs.contains(n.as_str()))
1687                .cloned()
1688                .collect();
1689            if produced.is_empty() {
1690                continue;
1691            }
1692            let produced_refs: Vec<&str> = produced.iter().map(String::as_str).collect();
1693            let closure = prog.extern_closure(&produced_refs);
1694            for name in &produced {
1695                unresolved.remove(name);
1696            }
1697            unresolved.extend(closure);
1698        }
1699        unresolved.into_iter().collect()
1700    }
1701
1702    /// Canonical content-addressable hash of this program
1703    /// (scope_model.md §8).
1704    ///
1705    /// SHA-256 over a deterministic byte sequence describing
1706    /// every node's kind + constant slots, every wiring edge,
1707    /// and the named input / output declarations, taken over
1708    /// the graph the compiler resolved before any engine folded
1709    /// or fused it, so the same program on any engine hashes
1710    /// alike ([`Kernel::canonical_hash`](crate::Kernel::canonical_hash)).
1711    /// Stable across compilations of equivalent input — two
1712    /// programs produced from identical source + identical
1713    /// workload-scope state hash to the same value, and a change
1714    /// that affects what the program actually computes (a renamed
1715    /// output, a new node, a const-slot value change, a
1716    /// re-routed wire) shifts the hash.
1717    ///
1718    /// A host's checkpointing uses it for per-phase identity,
1719    /// hashing the compiled program rather than the source body:
1720    /// the resume planner skips a phase only when the saved
1721    /// hash matches the freshly-compiled program's hash, so a
1722    /// `{dataset}` change that ripples into a phase's
1723    /// compiled form correctly invalidates that phase's
1724    /// saved status, while phases whose programs are
1725    /// unaffected stay skip-eligible.
1726    ///
1727    /// ## Determinism contract
1728    ///
1729    /// - Outputs are emitted in alphabetical order (not the
1730    ///   compiler's declaration order, which can shuffle
1731    ///   slightly across compilation passes).
1732    /// - For each output, the producing node and its
1733    ///   transitive input chain are walked in deterministic
1734    ///   order — wire-source list iterated in port-position
1735    ///   order, recursion uses the producer's stable
1736    ///   (already-canonical) hash as the wire reference.
1737    /// - Const slots are iterated in `NodeMeta.ins` order,
1738    ///   which is the DSL-declared positional order and is
1739    ///   compiler-invariant.
1740    /// - `Input(idx)` wires are translated to the input's
1741    ///   *name* (stable across runs) rather than its index
1742    ///   (a compile-time positional choice).
1743    /// - Floating-point constants hash via their bit
1744    ///   representation, so 0.0 vs -0.0 hash differently and
1745    ///   NaNs are distinguishable from each other only by
1746    ///   their bit pattern (rare but consistent).
1747    pub fn canonical_hash(&self) -> [u8; 32] {
1748        let graph = self
1749            .graph_identity
1750            .unwrap_or_else(|| self.identity_graph().digest());
1751        program_identity(
1752            graph,
1753            self.inherited_outputs.iter(),
1754            &self.cursor_schemas,
1755            &self.traversals,
1756        )
1757    }
1758
1759    /// The graph this program's identity is computed over, as it stands.
1760    fn identity_graph(&self) -> IdentityGraph<'_> {
1761        IdentityGraph {
1762            nodes: &self.nodes,
1763            wiring: &self.wiring,
1764            input_defs: &self.input_defs,
1765            outputs: self
1766                .output_list
1767                .iter()
1768                .map(|(n, ni, pi)| (n.as_str(), *ni, *pi))
1769                .collect(),
1770            output_modifiers: &self.output_modifiers,
1771            const_outputs: &self.const_outputs,
1772        }
1773    }
1774
1775    /// Record the digest of the graph the compiler resolved, before any
1776    /// engine transformed it, as this program's graph identity.
1777    pub(crate) fn set_graph_identity(&mut self, digest: [u8; 32]) {
1778        self.graph_identity = Some(digest);
1779    }
1780}
1781
1782/// The part of a program's graph its identity covers: nodes, wiring,
1783/// inputs, outputs with their modifiers, and the `const` names. The
1784/// compiler builds one over the graph it resolved, before an engine
1785/// folds or fuses anything, so every engine starts from the same one
1786/// (scope_model.md §8).
1787pub(crate) struct IdentityGraph<'a> {
1788    pub(crate) nodes: &'a [Box<dyn PolydatNode>],
1789    pub(crate) wiring: &'a [Vec<WireSource>],
1790    pub(crate) input_defs: &'a [InputDef],
1791    /// `(name, node, port)` for every output.
1792    pub(crate) outputs: Vec<(&'a str, usize, usize)>,
1793    pub(crate) output_modifiers: &'a HashMap<String, crate::dsl::ast::BindingModifier>,
1794    pub(crate) const_outputs: &'a std::collections::HashSet<String>,
1795}
1796
1797/// The instance hash of a program whose canonical hash is `own`, under
1798/// ancestors whose canonical hashes are `ancestors`, innermost first:
1799/// SHA-256 over a versioned tag, `own`, and each ancestor's hash in
1800/// order. [`PolydatProgram::instance_hash`] is this over interpreter
1801/// programs; a host holding kernels of any engine passes each kernel's
1802/// [`Kernel::canonical_hash`](crate::Kernel::canonical_hash) and gets
1803/// the same value (scope_model.md §8).
1804pub fn instance_hash_of(own: [u8; 32], ancestors: &[[u8; 32]]) -> [u8; 32] {
1805    use sha2::{Digest, Sha256};
1806    let mut h = Sha256::new();
1807    h.update(b"PolydatProgram-instance-v1\n");
1808    h.update(own);
1809    for a in ancestors {
1810        h.update(a);
1811    }
1812    h.finalize().into()
1813}
1814
1815/// A program's canonical hash from its graph digest
1816/// ([`IdentityGraph::digest`]), its inherited-output names, its
1817/// cursors, and its traversals: what [`PolydatProgram::canonical_hash`] and
1818/// [`Kernel::canonical_hash`](crate::Kernel::canonical_hash) return.
1819pub(crate) fn program_identity<'a>(
1820    graph: [u8; 32],
1821    inherited: impl Iterator<Item = &'a String>,
1822    cursors: &[crate::iteration::source::SourceSchema],
1823    traversals: &[crate::dsl::traversal::Traversal],
1824) -> [u8; 32] {
1825    use sha2::{Digest, Sha256};
1826    let mut h = Sha256::new();
1827    h.update(b"PolydatProgram-v2\n");
1828    h.update(graph);
1829    // Inherited-output set: names that pass through this scope
1830    // without it owning them, which decides scope-coordinate
1831    // attribution.
1832    let mut inherited: Vec<&String> = inherited.collect();
1833    inherited.sort();
1834    for name in inherited {
1835        h.update(b"inh:");
1836        h.update(name.as_bytes());
1837        h.update(b"\n");
1838    }
1839    // Cursor schemas: a different source bound is a different program.
1840    for schema in cursors {
1841        h.update(b"cursor:");
1842        h.update(schema.name.as_bytes());
1843        h.update(b":");
1844        h.update(format!("{:?}", schema.extent).as_bytes());
1845        h.update(b"\n");
1846    }
1847    // Traversals, in document order: the comprehension as written and
1848    // the body program's own canonical hash, so a change inside a `for`
1849    // body is a different program.
1850    for t in traversals {
1851        h.update(b"for:");
1852        h.update((t.source_text.len() as u64).to_le_bytes().as_ref());
1853        h.update(t.source_text.as_bytes());
1854        h.update(b":");
1855        h.update(t.program.canonical_hash());
1856        h.update(b"\n");
1857    }
1858    h.finalize().into()
1859}
1860
1861impl IdentityGraph<'_> {
1862    /// SHA-256 over the graph in canonical form: the inputs by name,
1863    /// then each output by name with the Merkle hash of the node
1864    /// producing it and its modifier flags, then the `const` names.
1865    pub(crate) fn digest(&self) -> [u8; 32] {
1866        use sha2::{Digest, Sha256};
1867        let mut h = Sha256::new();
1868        h.update(b"PolydatGraph-v2\n");
1869
1870        // Inputs: name + port type + kind + declared default, sorted by
1871        // name, since declaration order is the compiler's choice. The
1872        // default is what the program computes from when nothing writes
1873        // the input, and is where a host fixes a value before compiling
1874        // (`transform::assign_values`).
1875        let mut inputs: Vec<&InputDef> = self.input_defs.iter().collect();
1876        inputs.sort_by(|a, b| a.name.cmp(&b.name));
1877        for def in &inputs {
1878            h.update(b"in:");
1879            h.update(def.name.as_bytes());
1880            h.update(b":");
1881            h.update(format!("{:?}", def.port_type).as_bytes());
1882            h.update(b":");
1883            h.update(format!("{:?}", def.kind).as_bytes());
1884            h.update(b":");
1885            h.update(format!("{:?}", def.default).as_bytes());
1886            h.update(b"\n");
1887        }
1888
1889        // Outputs, alphabetically: each with the memoised Merkle hash
1890        // of the node and port producing it.
1891        let mut outputs = self.outputs.clone();
1892        outputs.sort_by(|a, b| a.0.cmp(b.0));
1893        let mut node_hashes: HashMap<usize, [u8; 32]> = HashMap::new();
1894        for (name, ni, pi) in &outputs {
1895            let (nh, pi_eff) = self.port_identity(*ni, *pi, &mut node_hashes);
1896            h.update(b"out:");
1897            h.update(name.as_bytes());
1898            h.update(b":port:");
1899            h.update(pi_eff.to_le_bytes().as_ref());
1900            h.update(b":");
1901            h.update(nh);
1902            h.update(b"\n");
1903            // Modifier flags as individual bytes, so the hash does not
1904            // depend on the modifier type's layout.
1905            if let Some(m) = self.output_modifiers.get(*name) {
1906                h.update(b"  mod:");
1907                h.update(if m.is_const() { b"F" } else { b"-" });
1908                h.update(if m.is_shared() { b"S" } else { b"-" });
1909                h.update(if m.is_volatile() { b"V" } else { b"-" });
1910                h.update(b"\n");
1911            }
1912        }
1913
1914        // The names declared `const`: moving a binding in or out of
1915        // `const` changes when it is evaluated.
1916        let mut init_outs: Vec<&String> = self.const_outputs.iter().collect();
1917        init_outs.sort();
1918        for name in init_outs {
1919            h.update(b"init:");
1920            h.update(name.as_bytes());
1921            h.update(b"\n");
1922        }
1923
1924        h.finalize().into()
1925    }
1926
1927    /// Recursive helper: hash a single node's canonical form,
1928    /// memoising on node index. The hash incorporates the
1929    /// node's kind (`meta.name`), every const slot's value,
1930    /// and every wire input — wires to other nodes resolve to
1931    /// those nodes' canonical hashes, so the result is a
1932    /// Merkle-tree summary of the producer's full transitive
1933    /// dependency cone.
1934    fn node_canonical_hash(&self, ni: usize, memo: &mut HashMap<usize, [u8; 32]>) -> [u8; 32] {
1935        if let Some(h) = memo.get(&ni) {
1936            return *h;
1937        }
1938        // Insert a sentinel to handle the (theoretical)
1939        // cycle case — Polydat DAGs aren't supposed to cycle, but
1940        // guarding against an infinite recursion if a future
1941        // node graph violates that is cheap insurance.
1942        memo.insert(ni, [0u8; 32]);
1943
1944        use sha2::{Digest, Sha256};
1945        let mut h = Sha256::new();
1946        let meta = self.nodes[ni].meta();
1947        h.update(b"node:");
1948        h.update(meta.name.as_bytes());
1949        h.update(b"\n");
1950
1951        // Output ports: name + type, in declaration order.
1952        for port in &meta.outs {
1953            h.update(b"  outp:");
1954            h.update(port.name.as_bytes());
1955            h.update(b":");
1956            h.update(format!("{:?}", port.typ).as_bytes());
1957            h.update(b"\n");
1958        }
1959
1960        // Input slots in declaration order. For Wire slots,
1961        // pull the wire-source for that port and resolve it.
1962        // Const slots inline their value's bytes.
1963        let wires = &self.wiring[ni];
1964        let mut wire_idx = 0;
1965        for slot in &meta.ins {
1966            match slot {
1967                crate::ast::Slot::Wire(port) => {
1968                    h.update(b"  wirep:");
1969                    h.update(port.name.as_bytes());
1970                    h.update(b":");
1971                    h.update(format!("{:?}", port.typ).as_bytes());
1972                    h.update(b":");
1973                    if let Some(src) = wires.get(wire_idx) {
1974                        canonical_wire_source(src, self, memo, &mut h);
1975                    } else {
1976                        h.update(b"unwired");
1977                    }
1978                    h.update(b"\n");
1979                    wire_idx += 1;
1980                }
1981                crate::ast::Slot::Const { name, value } => {
1982                    h.update(b"  const:");
1983                    h.update(name.as_bytes());
1984                    h.update(b":");
1985                    canonical_const_value(value, &mut h);
1986                    h.update(b"\n");
1987                }
1988            }
1989        }
1990
1991        let result: [u8; 32] = h.finalize().into();
1992        memo.insert(ni, result);
1993        result
1994    }
1995
1996    /// Resolve the canonical identity behind `(ni, pi)`. For
1997    /// ordinary nodes this is the node's own hash and port; for
1998    /// fusion nodes (interpreter cones, engines.md §2) it is the ORIGINAL member's
1999    /// hash and port, computed by walking the stored subgraph —
2000    /// so program identity is extraction-invariant.
2001    fn port_identity(
2002        &self,
2003        ni: usize,
2004        pi: usize,
2005        memo: &mut HashMap<usize, [u8; 32]>,
2006    ) -> ([u8; 32], usize) {
2007        if let Some(sub) = self.nodes[ni].fusion_subgraph() {
2008            let (m, p) = sub.out_ports[pi];
2009            (self.fusion_member_hash(ni, &sub, m, memo), p)
2010        } else {
2011            (self.node_canonical_hash(ni, memo), pi)
2012        }
2013    }
2014
2015    /// Hash one member of a fusion node's subgraph exactly as
2016    /// `node_canonical_hash` would have hashed it before
2017    /// extraction. Local `Input(i)` boundary references resolve
2018    /// through the fusion node's OUTER wiring, so upstream
2019    /// producers — including const-folded literals — hash in
2020    /// their post-fold form, byte-identical to the unextracted
2021    /// program's walk. Members form a small acyclic subgraph;
2022    /// recursion is bounded and unmemoised.
2023    fn fusion_member_hash(
2024        &self,
2025        fusion_ni: usize,
2026        sub: &crate::ast::FusionSubgraph<'_>,
2027        m: usize,
2028        memo: &mut HashMap<usize, [u8; 32]>,
2029    ) -> [u8; 32] {
2030        use sha2::{Digest, Sha256};
2031        let mut h = Sha256::new();
2032        let meta = sub.members[m].meta();
2033        h.update(b"node:");
2034        h.update(meta.name.as_bytes());
2035        h.update(b"\n");
2036        for port in &meta.outs {
2037            h.update(b"  outp:");
2038            h.update(port.name.as_bytes());
2039            h.update(b":");
2040            h.update(format!("{:?}", port.typ).as_bytes());
2041            h.update(b"\n");
2042        }
2043        let wires = &sub.wiring[m];
2044        let mut wire_idx = 0;
2045        for slot in &meta.ins {
2046            match slot {
2047                crate::ast::Slot::Wire(port) => {
2048                    h.update(b"  wirep:");
2049                    h.update(port.name.as_bytes());
2050                    h.update(b":");
2051                    h.update(format!("{:?}", port.typ).as_bytes());
2052                    h.update(b":");
2053                    match wires.get(wire_idx) {
2054                        Some(super::WireSource::NodeOutput(j, p)) => {
2055                            h.update(b"node:");
2056                            let nh = self.fusion_member_hash(fusion_ni, sub, *j, memo);
2057                            h.update(nh);
2058                            h.update(b":port:");
2059                            h.update(p.to_le_bytes().as_ref());
2060                        }
2061                        Some(super::WireSource::Input(i)) => match self.wiring[fusion_ni].get(*i) {
2062                            Some(super::WireSource::NodeOutput(oj, op)) => {
2063                                h.update(b"node:");
2064                                let (nh, p_eff) = self.port_identity(*oj, *op, memo);
2065                                h.update(nh);
2066                                h.update(b":port:");
2067                                h.update(p_eff.to_le_bytes().as_ref());
2068                            }
2069                            Some(outer_input @ super::WireSource::Input(_)) => {
2070                                canonical_wire_source(outer_input, self, memo, &mut h);
2071                            }
2072                            None => h.update(b"unwired"),
2073                        },
2074                        None => h.update(b"unwired"),
2075                    }
2076                    h.update(b"\n");
2077                    wire_idx += 1;
2078                }
2079                crate::ast::Slot::Const { name, value } => {
2080                    h.update(b"  const:");
2081                    h.update(name.as_bytes());
2082                    h.update(b":");
2083                    canonical_const_value(value, &mut h);
2084                    h.update(b"\n");
2085                }
2086            }
2087        }
2088        h.finalize().into()
2089    }
2090}
2091
2092impl PolydatProgram {
2093    /// Number of nodes in the program.
2094    pub fn node_count(&self) -> usize {
2095        self.nodes.len()
2096    }
2097
2098    /// Total wire count (sum of all node input edges).
2099    pub fn wire_count(&self) -> usize {
2100        self.wiring.iter().map(|w| w.len()).sum()
2101    }
2102
2103    /// Average in-degree (wires per node).
2104    pub fn avg_degree(&self) -> f64 {
2105        let n = self.nodes.len();
2106        if n == 0 {
2107            return 0.0;
2108        }
2109        self.wire_count() as f64 / n as f64
2110    }
2111
2112    /// Access a node by index (trait object). Read-only
2113    /// introspection surface for reporting — evaluation stays
2114    /// behind the kernel APIs.
2115    pub fn node_ref(&self, idx: usize) -> &dyn crate::ast::PolydatNode {
2116        self.nodes[idx].as_ref()
2117    }
2118
2119    /// Access a node's metadata by index.
2120    pub fn node_meta(&self, idx: usize) -> &crate::ast::NodeMeta {
2121        self.nodes[idx].meta()
2122    }
2123
2124    /// Access the wiring for a node by index.
2125    /// Returns the list of `WireSource`s feeding this node's inputs.
2126    pub fn node_wiring(&self, idx: usize) -> &[super::WireSource] {
2127        &self.wiring[idx]
2128    }
2129
2130    /// The types of the wires feeding node `idx`: a coordinate or
2131    /// extern takes its declared input type, a wire from another node
2132    /// its producing port's. What a builder passes a node's kit, and
2133    /// what deciding the node's tier needs.
2134    pub fn node_wire_types(&self, idx: usize) -> Vec<crate::ast::PortType> {
2135        self.wiring[idx]
2136            .iter()
2137            .map(|src| match src {
2138                super::WireSource::Input(i) => self
2139                    .input_port_type_by_idx(*i)
2140                    .unwrap_or(crate::ast::PortType::U64),
2141                super::WireSource::NodeOutput(j, p) => self.nodes[*j].meta().outs[*p].typ,
2142            })
2143            .collect()
2144    }
2145
2146    /// Probe the compile level of a node by index.
2147    pub fn node_compile_level(&self, idx: usize) -> crate::ast::CompileLevel {
2148        crate::ast::compile_level_of(self.nodes[idx].as_ref(), &self.node_wire_types(idx))
2149    }
2150
2151    /// What the interpreter runs of this program: its native cones as
2152    /// native segments and every other node interpreted
2153    /// ([`Kernel::plan`](crate::Kernel::plan)).
2154    pub fn engine_plan(&self) -> crate::EnginePlan {
2155        let mut plan = crate::EnginePlan::default();
2156        for i in 0..self.node_count() {
2157            // A native segment is the one kind of node that stands in
2158            // for a subgraph, which it says by answering
2159            // `fusion_subgraph`. Its `jit_cone[…]` name is a
2160            // diagnostic label, and reading the plan off a label would
2161            // make the count a fact about how the label is spelled.
2162            if self.node_ref(i).fusion_subgraph().is_some() {
2163                plan.native_segments += 1;
2164            } else {
2165                plan.interpreted_nodes += 1;
2166            }
2167        }
2168        plan
2169    }
2170
2171    /// Probe the compile level of the last node.
2172    pub fn last_node_compile_level(&self) -> crate::ast::CompileLevel {
2173        if self.nodes.is_empty() {
2174            return crate::ast::CompileLevel::Phase1;
2175        }
2176        self.node_compile_level(self.nodes.len() - 1)
2177    }
2178
2179    /// True when no node declares `Purity::Nondeterministic`: the
2180    /// program's outputs are a pure function of its inputs, so two
2181    /// kernels compiled from the same source produce bit-identical
2182    /// pulls. The engine differential tests key on this to
2183    /// decide whether a force-compiled twin can be compared
2184    /// value-for-value against the interpreter form (engines.md §7).
2185    pub fn is_deterministic(&self) -> bool {
2186        !self
2187            .nodes
2188            .iter()
2189            .any(|n| matches!(n.purity(), crate::ast::Purity::Nondeterministic { .. }))
2190    }
2191
2192    /// Fold every init-lifecycle constant now, as the compiler does at the
2193    /// end of a build, and return how many were folded.
2194    pub fn fold_init_constants(
2195        &mut self,
2196    ) -> Result<usize, crate::compile::assembly::AssemblyError> {
2197        self.fold_init_constants_impl(None, false)
2198    }
2199
2200    /// Fold init-time constants, emitting diagnostic events to the log.
2201    /// Returns `Err` when a compile-constant step cannot be computed, or
2202    /// for a strict-mode violation.
2203    pub fn fold_init_constants_with_log(
2204        &mut self,
2205        log: Option<&mut crate::dsl::events::CompileEventLog>,
2206    ) -> Result<usize, crate::compile::assembly::AssemblyError> {
2207        self.fold_init_constants_impl(log, false)
2208    }
2209
2210    /// Every config wire fed by a cycle-time source, as `(node, port)`
2211    /// by the node's own name. A node fused into a native cone is
2212    /// checked through the cone's members: a member fed by another
2213    /// member reads a cycle-time value (every member is dynamic), and a
2214    /// member fed by a boundary input reads what the cone's own wire
2215    /// carries.
2216    pub(crate) fn config_wires_fed_by_cycle(
2217        nodes: &[Box<dyn PolydatNode>],
2218        wiring: &[Vec<WireSource>],
2219        is_init: &[bool],
2220    ) -> Vec<(String, String)> {
2221        let outer_is_cycle = |src: &WireSource| match src {
2222            WireSource::Input(_) => true,
2223            WireSource::NodeOutput(src_idx, _) => !is_init[*src_idx],
2224        };
2225        let mut found = Vec::new();
2226        for (node, wires) in nodes.iter().zip(wiring.iter()) {
2227            if let Some(sub) = node.fusion_subgraph() {
2228                for (m, member) in sub.members.iter().enumerate() {
2229                    let ports = member.meta().wire_inputs();
2230                    for (k, src) in sub.wiring[m].iter().enumerate() {
2231                        let Some(port) = ports.get(k) else { break };
2232                        if port.wire_cost != crate::ast::WireCost::Config {
2233                            continue;
2234                        }
2235                        let cycle = match src {
2236                            WireSource::Input(bi) => wires.get(*bi).is_none_or(outer_is_cycle),
2237                            WireSource::NodeOutput(..) => true,
2238                        };
2239                        if cycle {
2240                            found.push((member.meta().name.clone(), port.name.clone()));
2241                        }
2242                    }
2243                }
2244                continue;
2245            }
2246            let wire_inputs = node.meta().wire_inputs();
2247            for (port_idx, wire_source) in wires.iter().enumerate() {
2248                let Some(port) = wire_inputs.get(port_idx) else {
2249                    break;
2250                };
2251                if port.wire_cost != crate::ast::WireCost::Config {
2252                    continue;
2253                }
2254                if outer_is_cycle(wire_source) {
2255                    found.push((node.meta().name.clone(), port.name.clone()));
2256                }
2257            }
2258        }
2259        found
2260    }
2261
2262    /// What strict mode refuses in a resolved graph, on every engine: a
2263    /// config wire fed from a cycle-time source, a nondeterministic
2264    /// node no `volatile` output acknowledges, and a binding nothing
2265    /// reads. `is_init` marks the compile-constant nodes, from
2266    /// [`Self::classify_lifecycle`]. The first violation, as the error
2267    /// message; the interpreter's fold warns about the same findings
2268    /// when strict is off.
2269    pub(crate) fn strict_violation(
2270        nodes: &[Box<dyn PolydatNode>],
2271        wiring: &[Vec<WireSource>],
2272        is_init: &[bool],
2273        output_map: &HashMap<String, (usize, usize)>,
2274        output_modifiers: &HashMap<String, crate::dsl::ast::BindingModifier>,
2275    ) -> Option<String> {
2276        let n = nodes.len();
2277        if let Some((node_name, port_name)) =
2278            Self::config_wires_fed_by_cycle(nodes, wiring, is_init)
2279                .into_iter()
2280                .next()
2281        {
2282            return Some(format!(
2283                "strict mode: config wire '{port_name}' on node '{node_name}' is connected \
2284                 to a cycle-time source."
2285            ));
2286        }
2287        // A nondeterministic read is acknowledged by what consumes it: a
2288        // `volatile` output (read again on every read) or a `const`
2289        // output (read once, at initialization).
2290        let mut feeds_volatile = vec![false; n];
2291        for (out_name, (node_idx, _)) in output_map.iter() {
2292            if output_modifiers
2293                .get(out_name)
2294                .map(|m| m.is_volatile() || m.is_const())
2295                .unwrap_or(false)
2296            {
2297                feeds_volatile[*node_idx] = true;
2298            }
2299        }
2300        let mut changed = true;
2301        while changed {
2302            changed = false;
2303            for i in 0..n {
2304                if !feeds_volatile[i] {
2305                    continue;
2306                }
2307                for source in &wiring[i] {
2308                    if let WireSource::NodeOutput(upstream, _) = source
2309                        && !feeds_volatile[*upstream]
2310                    {
2311                        feeds_volatile[*upstream] = true;
2312                        changed = true;
2313                    }
2314                }
2315            }
2316        }
2317        for (i, node) in nodes.iter().enumerate() {
2318            let name = &node.meta().name;
2319            if wiring[i].is_empty() && !is_init[i] && !name.starts_with("__") && !feeds_volatile[i]
2320            {
2321                return Some(format!(
2322                    "strict mode: non-deterministic node '{name}' used without explicit \
2323                     acknowledgment. Use a deterministic alternative."
2324                ));
2325            }
2326        }
2327        let output_nodes: std::collections::HashSet<usize> =
2328            output_map.values().map(|(idx, _)| *idx).collect();
2329        for (i, node) in nodes.iter().enumerate() {
2330            let name = &node.meta().name;
2331            if name.starts_with("__") || output_nodes.contains(&i) {
2332                continue;
2333            }
2334            let consumed = wiring.iter().any(|w| {
2335                w.iter()
2336                    .any(|s| matches!(s, WireSource::NodeOutput(src, _) if *src == i))
2337            });
2338            if !consumed {
2339                return Some(format!(
2340                    "strict mode: binding '{name}' is never referenced. Remove it or mark as \
2341                     output."
2342                ));
2343            }
2344        }
2345        None
2346    }
2347
2348    /// Fold init-time constants with strict mode.
2349    pub fn fold_init_constants_strict(
2350        &mut self,
2351        log: Option<&mut crate::dsl::events::CompileEventLog>,
2352        strict: bool,
2353    ) -> Result<usize, crate::compile::assembly::AssemblyError> {
2354        self.fold_init_constants_impl(log, strict)
2355    }
2356
2357    // The `0..n` node-index loops below each fan one index out
2358    // across several parallel structures (`self.nodes`, `self.wiring`,
2359    // `is_init`, `state.core.buffers`) and feed it to
2360    // `eval_node_public(self, i)` — iterating any single array
2361    // misrepresents the logic and conflicts with the `&mut self`
2362    // borrows, so the index form stays.
2363    #[allow(clippy::needless_range_loop)]
2364    fn fold_init_constants_impl(
2365        &mut self,
2366        mut log: Option<&mut crate::dsl::events::CompileEventLog>,
2367        strict: bool,
2368    ) -> Result<usize, crate::compile::assembly::AssemblyError> {
2369        use crate::ast::Value;
2370        use crate::library::fixed::ConstF64;
2371        use crate::library::identity::{ConstExt, ConstHandle, ConstStr, ConstU64};
2372
2373        let n = self.nodes.len();
2374        if n == 0 {
2375            return Ok(0);
2376        }
2377
2378        // Phase 1: Classify each node by its evaluation lifecycle
2379        // (graph_compiler.md §3.1): every
2380        // node is CompileConst, ScopeInit, or Dynamic; the three are
2381        // ordered (Dynamic dominates ScopeInit dominates
2382        // CompileConst) and `max()`-propagate downstream.
2383        //
2384        // CompileConst: foldable now (no extern / cycle dependencies).
2385        // ScopeInit:    not foldable now, but will be at scope
2386        //               activation (depends on iteration externs).
2387        // Dynamic:      depends on cycle inputs, external-write ports, or
2388        //               non-deterministic sources.
2389        let lifecycle = Self::classify_lifecycle(
2390            &self.nodes,
2391            &self.wiring,
2392            &self.input_defs,
2393            &self.output_map,
2394            &self.output_modifiers,
2395        )
2396        .lifecycle;
2397
2398        // is_init is the compile-const subset. Subsequent fold
2399        // phases below only operate on CompileConst nodes; ScopeInit
2400        // nodes are deferred to the scope-activation pass.
2401        let mut is_init: Vec<bool> = lifecycle
2402            .iter()
2403            .map(|lc| *lc == EvalLifecycle::CompileConst)
2404            .collect();
2405
2406        // Strict refuses what the checks below warn about, through the
2407        // one function every engine's build applies.
2408        if strict
2409            && let Some(violation) = Self::strict_violation(
2410                &self.nodes,
2411                &self.wiring,
2412                &is_init,
2413                &self.output_map,
2414                &self.output_modifiers,
2415            )
2416        {
2417            return Err(crate::compile::assembly::AssemblyError::Other(violation));
2418        }
2419
2420        // Wire cost check: a config wire fed by a cycle-time source
2421        // warns, by the node's own name and port, through the cone's
2422        // members where the node was fused.
2423        for (node_name, port_name) in
2424            Self::config_wires_fed_by_cycle(&self.nodes, &self.wiring, &is_init)
2425        {
2426            crate::library::support::audit::warn(&format!(
2427                "config wire '{port_name}' on node '{node_name}' is connected to a \
2428                 cycle-time source."
2429            ));
2430            if let Some(ref mut log) = log {
2431                log.push(crate::dsl::events::CompileEvent::ConfigWireCycleWarning {
2432                    node: node_name,
2433                    port: port_name,
2434                });
2435            }
2436        }
2437
2438        // Non-deterministic node check (evaluation_model.md,
2439        // "Non-Deterministic Nodes"). Empty-wiring + not-init +
2440        // not-internal nodes are structurally-detected as
2441        // non-deterministic. The `volatile` keyword on a binding
2442        // wire is the author's explicit acknowledgment — when a
2443        // node's output feeds into a volatile output, suppress
2444        // both the strict-mode error and the audit warning.
2445        //
2446        // Direct-consumer check: walks `output_list` looking for
2447        // outputs that map to this node and checks whether the
2448        // output's modifier carries `is_volatile`. Transitive
2449        // volatility (R1.v contagion) is delivered separately by
2450        // the lifecycle classifier's fixed-point propagation: a
2451        // node marked Dynamic (via intrinsic Nondeterministic
2452        // purity or a downstream volatile modifier) propagates
2453        // Dynamic to every consumer through the existing pass at
2454        // `compute_lifecycles`. This loop handles only the
2455        // strict-mode / audit-warning side: was the
2456        // non-deterministic node consumed directly by an
2457        // author-declared `volatile` output? If yes, suppress the
2458        // warning.
2459        // Volatility acknowledgment is TRANSITIVE for suppression,
2460        // matching the lifecycle classifier's contagion: a
2461        // nondeterministic node feeding a volatile-marked output
2462        // through any expression chain (a stop-condition predicate's
2463        // `metric(...) > 3.0` puts a comparison between the reader
2464        // and the volatile output) is acknowledged. Reverse-reach:
2465        // seed the producing node of every volatile output, walk
2466        // producer edges to fixpoint.
2467        // A `const` output acknowledges a nondeterministic read as a
2468        // `volatile` one does: it takes one reading, at initialization.
2469        let mut feeds_volatile = vec![false; n];
2470        for (out_name, node_idx, _port) in self.output_list.iter() {
2471            if self
2472                .output_modifiers
2473                .get(out_name)
2474                .map(|m| m.is_volatile() || m.is_const())
2475                .unwrap_or(false)
2476            {
2477                feeds_volatile[*node_idx] = true;
2478            }
2479        }
2480        let mut changed = true;
2481        while changed {
2482            changed = false;
2483            for i in 0..n {
2484                if !feeds_volatile[i] {
2485                    continue;
2486                }
2487                for source in &self.wiring[i] {
2488                    if let WireSource::NodeOutput(upstream, _) = source
2489                        && !feeds_volatile[*upstream]
2490                    {
2491                        feeds_volatile[*upstream] = true;
2492                        changed = true;
2493                    }
2494                }
2495            }
2496        }
2497        for i in 0..n {
2498            let name = &self.nodes[i].meta().name;
2499            let is_nondeterministic =
2500                self.wiring[i].is_empty() && !is_init[i] && !name.starts_with("__");
2501            if !is_nondeterministic {
2502                continue;
2503            }
2504            let consumed_by_volatile = feeds_volatile[i];
2505            if consumed_by_volatile {
2506                continue;
2507            }
2508            let msg =
2509                format!("non-deterministic node '{name}' used without explicit acknowledgment");
2510            crate::library::support::audit::warn(&msg);
2511            if let Some(ref mut log) = log {
2512                log.push(crate::dsl::events::CompileEvent::Warning { message: msg });
2513            }
2514        }
2515
2516        // Unused binding check
2517        let output_node_indices: std::collections::HashSet<usize> =
2518            self.output_map.values().map(|(idx, _)| *idx).collect();
2519        for i in 0..n {
2520            let name = &self.nodes[i].meta().name;
2521            if name.starts_with("__") {
2522                continue;
2523            }
2524            let is_output = output_node_indices.contains(&i);
2525            let is_consumed = (0..n).any(|j| {
2526                self.wiring[j]
2527                    .iter()
2528                    .any(|w| matches!(w, WireSource::NodeOutput(src, _) if *src == i))
2529            });
2530            if !is_output && !is_consumed {
2531                let msg = format!("binding '{name}' is never referenced");
2532                if !name.contains("__") {
2533                    crate::library::support::audit::warn(&msg);
2534                    if let Some(ref mut log) = log {
2535                        log.push(crate::dsl::events::CompileEvent::Warning { message: msg });
2536                    }
2537                }
2538            }
2539        }
2540
2541        let init_count = is_init.iter().filter(|&&b| b).count();
2542        if init_count == 0 {
2543            return Ok(0);
2544        }
2545
2546        // Phase 2: Evaluate init-time nodes, on a state seeded without
2547        // opening a cycle. A program is compiled inside a root's cycle
2548        // — a traversal body, a projection body — and folding its
2549        // constants must not disturb what the root is part-way
2550        // through.
2551        let mut state = self.create_state();
2552        let dummy_inputs = vec![0u64; self.coord_count];
2553        state.seed_inputs(&dummy_inputs);
2554
2555        for i in 0..n {
2556            if is_init[i] {
2557                if self.nodes[i].meta().outs.len() != 1 {
2558                    is_init[i] = false;
2559                    continue;
2560                }
2561                // A compile-constant step is one no input reaches, so
2562                // what it does here it will do on every pull: there is
2563                // nothing a later evaluation could supply that would
2564                // make it succeed. Skipping the fold would only move
2565                // the same failure to the first pull and leave this
2566                // engine disagreeing with the three compiled ones,
2567                // which fail at build. What is knowable at build is
2568                // known at build, and fails at build.
2569                let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2570                    state.eval_node_public(self, i);
2571                }));
2572                if let Err(payload) = result {
2573                    // The eval path already enriched the payload with
2574                    // the node, the outputs it feeds and the inputs it
2575                    // was called with, the way any evaluation failure
2576                    // is enriched. Taking its text keeps one copy of
2577                    // that attribution rather than wrapping a second.
2578                    //
2579                    // Less the panic location: at build this is a
2580                    // diagnosis of the program, and the compiled
2581                    // engines report it without one, so dropping it is
2582                    // what makes the fold error read the same on every
2583                    // engine (`without_panic_location`).
2584                    return Err(crate::compile::assembly::AssemblyError::ConstantFold(
2585                        crate::kernel::engines::without_panic_location(
2586                            crate::kernel::engines::panic_payload_text(payload.as_ref()),
2587                        ),
2588                    ));
2589                }
2590            }
2591        }
2592
2593        // Phase 3: Replace init-time nodes with constants.
2594        let mut folded = 0;
2595        for i in 0..n {
2596            if !is_init[i] {
2597                continue;
2598            }
2599
2600            let value = state.core.buffers[i][0].clone();
2601            if matches!(value, Value::None) {
2602                continue;
2603            }
2604
2605            let const_node: Box<dyn crate::ast::PolydatNode> = match &value {
2606                Value::U64(v) => Box::new(ConstU64::new(*v)),
2607                Value::F64(v) => Box::new(ConstF64::new(*v)),
2608                // A Bool stays a Bool: the wire is Bool-typed, and a
2609                // `const_u64` here would make the interpreter read a
2610                // U64 where every compiled engine reads the Bool.
2611                Value::Bool(v) => Box::new(crate::library::fixed::ConstBool::new(*v)),
2612                Value::Str(s) => Box::new(ConstStr::new(s.to_string())),
2613                // Handles (e.g. `init prebuffered = dataset_prebuffer(...)`)
2614                // get a dedicated `ConstHandle` replacement so the original
2615                // side-effect-bearing node is removed from the program.
2616                // Without this, every fresh fiber's `PolydatState` would
2617                // walk the dirty original on first pull and re-fire its
2618                // eval — a per-fiber stampede that exhausts process
2619                // thread limits when the eval spawns HTTP workers.
2620                Value::Handle(arc) => {
2621                    let original_name = self.nodes[i].meta().name.clone();
2622                    // Per-node compile-time mechanic; one
2623                    // line per `const` binding pollutes
2624                    // session output with no actionable
2625                    // signal for the operator. Demote to
2626                    // Debug — visible under `--log-level
2627                    // debug` for compiler-pipeline
2628                    // inspection, silent on the default
2629                    // INFO console.
2630                    crate::library::support::audit::debug(&format!(
2631                        "fold: replacing init node '{original_name}' with ConstHandle \
2632                         (Arc<dyn Any>) — eval will not re-fire post-fold"
2633                    ));
2634                    Box::new(ConstHandle::new(arc.clone()))
2635                }
2636                // Ext-typed init values (cursor_partitions.md §2: Partition,
2637                // PartitionSpec, PartitionList, …) replace the
2638                // original node with a ConstExt leaf — same
2639                // shape as the Handle path so post-fold kernels
2640                // can read the value via `get_constant` and
2641                // descendant scopes see it as a stable Ext wire.
2642                Value::Ext(b) => {
2643                    let original_name = self.nodes[i].meta().name.clone();
2644                    crate::library::support::audit::debug(&format!(
2645                        "fold: replacing init node '{original_name}' with ConstExt \
2646                         ({}) — eval will not re-fire post-fold",
2647                        b.type_name(),
2648                    ));
2649                    Box::new(ConstExt::new(b.clone()))
2650                }
2651                // A dataset value fixed at build, such as the forms of
2652                // a facet, is surveyed once here and not by each fiber.
2653                #[cfg(feature = "vectordata")]
2654                Value::Dataset(d) => {
2655                    Box::new(crate::library::identity::ConstDataset::new(d.clone()))
2656                }
2657                // No dataset value exists without the feature.
2658                #[cfg(not(feature = "vectordata"))]
2659                Value::Dataset(d) => match *d {},
2660                _ => continue,
2661            };
2662
2663            let node_name = self.nodes[i].meta().name.clone();
2664            if let Some(ref mut log) = log {
2665                log.push(crate::dsl::events::CompileEvent::ConstantFolded {
2666                    node: node_name,
2667                    value: value.to_display_string(),
2668                });
2669            }
2670            self.nodes[i] = const_node;
2671            self.wiring[i] = Vec::new();
2672            folded += 1;
2673        }
2674
2675        Ok(folded)
2676    }
2677}
2678
2679/// Hash one [`super::WireSource`] in canonical form. Inputs
2680/// resolve to their *name* (stable identifier) rather than
2681/// their positional index. Node-output references recurse via
2682/// [`IdentityGraph::node_canonical_hash`].
2683fn canonical_wire_source(
2684    src: &super::WireSource,
2685    program: &IdentityGraph<'_>,
2686    memo: &mut HashMap<usize, [u8; 32]>,
2687    h: &mut sha2::Sha256,
2688) {
2689    use sha2::Digest;
2690    match src {
2691        super::WireSource::Input(idx) => {
2692            h.update(b"input:");
2693            if let Some(def) = program.input_defs.get(*idx) {
2694                h.update(def.name.as_bytes());
2695            } else {
2696                h.update(b"<oob>");
2697            }
2698        }
2699        super::WireSource::NodeOutput(ni, pi) => {
2700            h.update(b"node:");
2701            let (nh, pi_eff) = program.port_identity(*ni, *pi, memo);
2702            h.update(nh);
2703            h.update(b":port:");
2704            h.update(pi_eff.to_le_bytes().as_ref());
2705        }
2706    }
2707}
2708
2709/// Hash one [`crate::ast::ConstValue`] in canonical form.
2710/// Floats hash via their bit pattern so 0.0 vs -0.0 (and
2711/// distinct NaN payloads) are distinguishable. Strings and
2712/// vectors include explicit length tags so concatenation is
2713/// unambiguous.
2714fn canonical_const_value(v: &crate::ast::ConstValue, h: &mut sha2::Sha256) {
2715    use crate::ast::ConstValue;
2716    use sha2::Digest;
2717    match v {
2718        ConstValue::U64(x) => {
2719            h.update(b"u64:");
2720            h.update(x.to_le_bytes().as_ref());
2721        }
2722        ConstValue::F64(x) => {
2723            h.update(b"f64:");
2724            h.update(x.to_bits().to_le_bytes().as_ref());
2725        }
2726        ConstValue::Str(s) => {
2727            h.update(b"str:");
2728            h.update((s.len() as u64).to_le_bytes().as_ref());
2729            h.update(s.as_bytes());
2730        }
2731        ConstValue::VecU64(xs) => {
2732            h.update(b"vu64:");
2733            h.update((xs.len() as u64).to_le_bytes().as_ref());
2734            for x in xs {
2735                h.update(x.to_le_bytes().as_ref());
2736            }
2737        }
2738        ConstValue::VecF64(xs) => {
2739            h.update(b"vf64:");
2740            h.update((xs.len() as u64).to_le_bytes().as_ref());
2741            for x in xs {
2742                h.update(x.to_bits().to_le_bytes().as_ref());
2743            }
2744        }
2745    }
2746}
2747
2748#[cfg(test)]
2749mod canonical_hash_tests {
2750    use crate::dsl::compile_polydat_interpreter;
2751
2752    #[test]
2753    fn identical_source_produces_identical_hash() {
2754        let src = "const dataset := \"sift1m\"\nconst count := 100\n";
2755        let k1 = compile_polydat_interpreter(src).expect("compile1");
2756        let k2 = compile_polydat_interpreter(src).expect("compile2");
2757        assert_eq!(k1.program().canonical_hash(), k2.program().canonical_hash());
2758    }
2759
2760    #[test]
2761    fn different_const_value_changes_hash() {
2762        let a = compile_polydat_interpreter("const x := 100\n").expect("compile a");
2763        let b = compile_polydat_interpreter("const x := 101\n").expect("compile b");
2764        assert_ne!(
2765            a.program().canonical_hash(),
2766            b.program().canonical_hash(),
2767            "differing const value must change canonical hash"
2768        );
2769    }
2770
2771    #[test]
2772    fn different_string_value_changes_hash() {
2773        let a = compile_polydat_interpreter("const s := \"sift1m\"\n").expect("compile a");
2774        let b = compile_polydat_interpreter("const s := \"sift10m\"\n").expect("compile b");
2775        assert_ne!(
2776            a.program().canonical_hash(),
2777            b.program().canonical_hash(),
2778            "differing string value must change canonical hash"
2779        );
2780    }
2781
2782    #[test]
2783    fn renamed_output_changes_hash() {
2784        // Same RHS, different output name → different program
2785        // identity. The output map contributes to canonical
2786        // identity.
2787        let a = compile_polydat_interpreter("const foo := 42\n").expect("compile a");
2788        let b = compile_polydat_interpreter("const bar := 42\n").expect("compile b");
2789        assert_ne!(
2790            a.program().canonical_hash(),
2791            b.program().canonical_hash(),
2792            "renamed output must change canonical hash"
2793        );
2794    }
2795
2796    #[test]
2797    fn comment_only_change_does_not_change_hash() {
2798        let a = compile_polydat_interpreter("const x := 42\n").expect("compile a");
2799        let b = compile_polydat_interpreter(
2800            "# explanatory comment\nconst x := 42\n# trailing comment\n",
2801        )
2802        .expect("compile b");
2803        assert_eq!(
2804            a.program().canonical_hash(),
2805            b.program().canonical_hash(),
2806            "comment-only edits should not affect canonical hash — \
2807             the AST is what's hashed, not the source bytes"
2808        );
2809    }
2810
2811    #[test]
2812    fn whitespace_change_does_not_change_hash() {
2813        let a = compile_polydat_interpreter("const x := 42\n").expect("compile a");
2814        let b = compile_polydat_interpreter("const  x  :=  42\n\n\n").expect("compile b");
2815        assert_eq!(
2816            a.program().canonical_hash(),
2817            b.program().canonical_hash(),
2818            "whitespace-only edits should not affect canonical hash"
2819        );
2820    }
2821
2822    #[test]
2823    fn additional_binding_changes_hash() {
2824        let a = compile_polydat_interpreter("const x := 1\n").expect("compile a");
2825        let b = compile_polydat_interpreter("const x := 1\nconst y := 2\n").expect("compile b");
2826        assert_ne!(
2827            a.program().canonical_hash(),
2828            b.program().canonical_hash(),
2829            "added output must change canonical hash"
2830        );
2831    }
2832
2833    // -----------------------------------------------------------
2834    // instance_hash — aggregates over a parent-chain of programs
2835    // -----------------------------------------------------------
2836
2837    #[test]
2838    fn instance_hash_with_no_ancestors_differs_from_canonical_hash() {
2839        // The instance form prefixes a different domain tag, so
2840        // even with an empty ancestor chain the two flavours are
2841        // distinguishable. Prevents a caller from accidentally
2842        // comparing an instance_hash against a canonical_hash
2843        // and getting a coincidental match.
2844        let p = compile_polydat_interpreter("const x := 1\n").expect("compile");
2845        let prog = p.program();
2846        assert_ne!(prog.instance_hash(&[]), prog.canonical_hash());
2847    }
2848
2849    #[test]
2850    fn instance_hash_changes_when_an_ancestor_program_changes() {
2851        // Parent A vs B differ only in a const-slot literal —
2852        // canonical_hash distinguishes them, so instance_hash
2853        // computed against the same child must distinguish too.
2854        let parent_a = compile_polydat_interpreter("const ds := \"v1\"\n").expect("a");
2855        let parent_b = compile_polydat_interpreter("const ds := \"v2\"\n").expect("b");
2856        let child = compile_polydat_interpreter("const y := 42\n").expect("child");
2857        let cp = child.program();
2858        let h_a = cp.instance_hash(&[parent_a.program().as_ref()]);
2859        let h_b = cp.instance_hash(&[parent_b.program().as_ref()]);
2860        assert_ne!(
2861            h_a, h_b,
2862            "ancestor const-slot edit must change instance_hash even \
2863             when the child program is byte-identical"
2864        );
2865    }
2866
2867    #[test]
2868    fn instance_hash_is_order_sensitive_in_the_chain() {
2869        // The chain order matters — different scope-tree paths
2870        // must map to different identities. The hash mixes
2871        // ancestor[i].canonical_hash() in chain order, so swapping
2872        // ancestors yields a different result.
2873        let g = compile_polydat_interpreter("const g := 1\n").expect("g");
2874        let p = compile_polydat_interpreter("const p := 2\n").expect("p");
2875        let c = compile_polydat_interpreter("const c := 3\n").expect("c");
2876        let cp = c.program();
2877        let chain1 = cp.instance_hash(&[p.program().as_ref(), g.program().as_ref()]);
2878        let chain2 = cp.instance_hash(&[g.program().as_ref(), p.program().as_ref()]);
2879        assert_ne!(chain1, chain2);
2880    }
2881
2882    #[test]
2883    fn instance_hash_is_deterministic_across_rebuilds() {
2884        // Two independent compiles of the same source feeding
2885        // the same child must produce the same instance_hash.
2886        let parent_src = "const ds := \"sift1m\"\n";
2887        let p1 = compile_polydat_interpreter(parent_src).expect("p1");
2888        let p2 = compile_polydat_interpreter(parent_src).expect("p2");
2889        let child = compile_polydat_interpreter("const y := 42\n").expect("child");
2890        let cp = child.program();
2891        let h1 = cp.instance_hash(&[p1.program().as_ref()]);
2892        let h2 = cp.instance_hash(&[p2.program().as_ref()]);
2893        assert_eq!(h1, h2);
2894    }
2895
2896    // ── is_equivalent_to / is_subset_of ──
2897
2898    #[test]
2899    fn is_equivalent_to_identical_programs() {
2900        let src = "const x := 100\n";
2901        let a = compile_polydat_interpreter(src).expect("a");
2902        let b = compile_polydat_interpreter(src).expect("b");
2903        assert!(a.program().is_equivalent_to(b.program()));
2904        assert!(b.program().is_equivalent_to(a.program())); // symmetric
2905    }
2906
2907    #[test]
2908    fn is_equivalent_to_differs_when_const_differs() {
2909        let a = compile_polydat_interpreter("const x := 100\n").expect("a");
2910        let b = compile_polydat_interpreter("const x := 101\n").expect("b");
2911        assert!(!a.program().is_equivalent_to(b.program()));
2912    }
2913
2914    #[test]
2915    fn is_subset_of_self_is_true() {
2916        let p = compile_polydat_interpreter("const x := 1\n").expect("p");
2917        // A program is trivially a subset of itself (the
2918        // equivalence shortcut at the top of is_subset_of).
2919        assert!(p.program().is_subset_of(p.program()));
2920    }
2921
2922    #[test]
2923    fn is_subset_of_distinct_definitions_is_false() {
2924        // Inner declares a NEW output the parent doesn't —
2925        // structurally not a subset.
2926        let parent = compile_polydat_interpreter("const x := 1\n").expect("parent");
2927        let inner = compile_polydat_interpreter("const y := 2\n").expect("inner");
2928        assert!(!inner.program().is_subset_of(parent.program()));
2929    }
2930}
2931
2932#[cfg(test)]
2933mod ast_metadata_tests {
2934    use crate::dsl::ast::Statement;
2935    use crate::dsl::compile_polydat_interpreter;
2936
2937    #[test]
2938    fn retained_ast_is_present_after_compile() {
2939        let src = "const dataset := \"sift1m\"\ncount := 100\n";
2940        let k = compile_polydat_interpreter(src).expect("compile");
2941        assert!(
2942            k.program().ast().is_some(),
2943            "AST should be retained on program"
2944        );
2945    }
2946
2947    #[test]
2948    fn binding_ast_for_finds_init_binding() {
2949        let src = "const dataset := \"sift1m\"\nratio := 2.5\n";
2950        let k = compile_polydat_interpreter(src).expect("compile");
2951        let stmt = k
2952            .program()
2953            .binding_ast_for("dataset")
2954            .expect("dataset binding should be retrievable");
2955        match stmt {
2956            Statement::Binding(b) => assert_eq!(b.targets[0], "dataset"),
2957            other => panic!("expected InitBinding for 'dataset', got {other:?}"),
2958        }
2959    }
2960
2961    #[test]
2962    fn binding_ast_for_finds_cycle_binding() {
2963        let src = "count := 42\n";
2964        let k = compile_polydat_interpreter(src).expect("compile");
2965        let stmt = k
2966            .program()
2967            .binding_ast_for("count")
2968            .expect("count binding should be retrievable");
2969        match stmt {
2970            Statement::Binding(b) => {
2971                assert!(
2972                    b.targets.iter().any(|t| t == "count"),
2973                    "CycleBinding targets should include 'count'"
2974                );
2975            }
2976            other => panic!("expected CycleBinding for 'count', got {other:?}"),
2977        }
2978    }
2979
2980    #[test]
2981    fn binding_ast_for_unknown_name_returns_none() {
2982        let k = compile_polydat_interpreter("const x := 1\n").expect("compile");
2983        assert!(k.program().binding_ast_for("does_not_exist").is_none());
2984    }
2985
2986    #[test]
2987    fn local_inclusion_chain_unknown_name_is_empty() {
2988        let k = compile_polydat_interpreter("const x := 1\n").expect("compile");
2989        let chain = k
2990            .program()
2991            .local_inclusion_chain("missing", &std::collections::HashSet::new());
2992        assert!(chain.is_empty());
2993    }
2994}
2995
2996/// R1.v transitive contagion: a node whose dependency cone
2997/// reaches a volatile producer must itself be marked
2998/// nondeterministic at construction time, so its clean flag
2999/// is never set and downstream pulls re-evaluate.
3000/// Without contagion, a consumer of `current_epoch_millis`
3001/// would return a stale cached value referencing the prior
3002/// cycle's timestamp.
3003#[cfg(test)]
3004mod r1v_contagion_tests {
3005    use crate::ast::Value;
3006    use crate::dsl::compile_polydat_interpreter;
3007
3008    #[test]
3009    fn every_read_re_evaluates_a_volatile_node() {
3010        // Each pull of a volatile output is a read, and every read
3011        // re-evaluates the volatile node (R1.v), with or without a
3012        // write between them.
3013        let src = "input cycle: u64\n\
3014                   c := counter()\n";
3015        let mut k = compile_polydat_interpreter(src).expect("compile");
3016        k.set_inputs(&[0]);
3017        let a = match k.pull_ref("c") {
3018            Value::U64(v) => *v,
3019            _ => panic!(),
3020        };
3021        let b = match k.pull_ref("c") {
3022            Value::U64(v) => *v,
3023            _ => panic!(),
3024        };
3025        let c = match k.pull_ref("c") {
3026            Value::U64(v) => *v,
3027            _ => panic!(),
3028        };
3029        assert_eq!(b, a + 1, "the second read re-evaluated the counter");
3030        assert_eq!(c, b + 1, "the third read re-evaluated the counter");
3031    }
3032}
3033
3034#[cfg(test)]
3035mod provmask_tests {
3036    use super::ProvMask;
3037
3038    /// The exactness this type exists for: bits above 63 are
3039    /// first-class, not aliased into a saturated top bit.
3040    #[test]
3041    fn bits_above_63_are_exact() {
3042        let mut a = ProvMask::empty();
3043        assert!(a.set(2));
3044        assert!(a.set(63));
3045        assert!(a.set(64));
3046        assert!(a.set(130));
3047        assert!(!a.set(130), "re-set reports no change");
3048        assert!(a.contains(2) && a.contains(63));
3049        assert!(a.contains(64) && a.contains(130));
3050        assert!(!a.contains(65) && !a.contains(129));
3051        assert_eq!(a.iter_ones().collect::<Vec<_>>(), vec![2, 63, 64, 130]);
3052    }
3053
3054    #[test]
3055    fn union_and_intersect_across_word_boundaries() {
3056        let mut a = ProvMask::empty();
3057        a.set(1);
3058        let mut b = ProvMask::empty();
3059        b.set(100);
3060        assert!(!a.intersects(&b));
3061        assert!(a.union_with(&b), "union reports growth");
3062        assert!(!a.union_with(&b), "idempotent union reports none");
3063        assert!(a.contains(1) && a.contains(100));
3064        assert!(a.intersects(&b));
3065        assert!(ProvMask::empty().is_zero());
3066        assert!(!a.is_zero());
3067    }
3068}