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