Skip to main content

polydat_core/kernel/
program.rs

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