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