Skip to main content

nmbrs_runtime/
scope_tree.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Canonical scope tree for a workload's runtime hierarchy.
5//!
6//! `ScenarioNode` (in `nmbrs-workload`) is the *static authored*
7//! tree — what the user wrote in YAML. `ScopeTree` is the
8//! *runtime hierarchy* — what Polydat and the scheduler see. Every
9//! non-trivial scenario node gets a 1:1 scope here, with
10//! parent pointers, depth, pragma sets, and a slot for a compiled
11//! kernel.
12//!
13//! This module is **structural only** — it builds the tree and
14//! exposes traversal helpers. Pragma attachment, kernel
15//! compilation, and execution scheduling live in subsequent
16//! steps of SRD 18b §"Migration":
17//!
18//! 1. *(this module)* introduce the data structure
19//! 2. nest each scope's `PragmaSet` in its parent's at scope-tree construction
20//!    (M2 follow-up)
21//! 3. replace text-substitution of iteration vars with extern
22//!    binding (compile leaf phases once)
23//! 4. pluggable scheduler reading the `schedule=<level0>/...`
24//!    spec
25//! 5. hierarchical display surface
26//!
27//! Until those steps land, `ScopeTree` is built but not consumed
28//! by the runner — the existing executor continues to drive
29//! traversal directly off `ScenarioNode`. Building the tree is
30//! cheap and deterministic; intermediate sysrefs (TUI display,
31//! `dryrun=phase`) can already start consuming it.
32
33use nmbrs_workload::model::ScenarioNode;
34use polydat::dsl::pragmas::PragmaSet;
35use polydat::iteration::comprehension::Comprehension;
36
37/// Index into the `ScopeTree.nodes` vector. Stable for the
38/// lifetime of the tree.
39pub type ScopeNodeIdx = usize;
40
41/// What kind of scope a `ScopeNode` represents. Mirrors the
42/// `ScenarioNode` variants 1:1, with two extra kinds for the
43/// implicit workload root and the named scenario layer that
44/// wraps the user's authored children. SRD 18b §"Canonical
45/// traversal".
46#[derive(Debug, Clone)]
47pub enum ScopeKind {
48    /// The session root — **one per process** (SRD-88). The shared
49    /// common root every execution derives from: it owns the session
50    /// polydat scope (the process/session-level args) and the
51    /// `session=<id>` identity. Each [`ScopeKind::Workload`] hangs
52    /// under it as one execution. For a single-execution run there is
53    /// exactly one workload child.
54    Session,
55    /// A workload root — **one per execution** (SRD-88). Owns the
56    /// outer Polydat Kernel for its workload, compiled at execution
57    /// start, binding the session scope as its outer.
58    Workload,
59    /// A named scenario. Wraps the scenario's children so that
60    /// "phase P in scenario default" survives as a path query
61    /// rather than a elided label.
62    Scenario { name: String },
63    /// Iteration scope — `for_each` (single or multi-clause) or
64    /// `for_each_union`. The `Comprehension` AST captures the
65    /// shape and clauses; the executor uses it to enumerate
66    /// tuples and bind iteration variables on per-iteration
67    /// child kernels.
68    Comprehension { comprehension: Comprehension },
69    /// Logical inclusion of another scenario by name. The
70    /// runtime walks straight through to the children; the
71    /// scope is preserved purely so the scope tree retains the
72    /// include hierarchy for `dryrun=phase` and TUI output.
73    /// See
74    /// [`nmbrs_workload::model::ScenarioNode::IncludedScenario`].
75    IncludedScenario { name: String },
76    /// `do_while` with optional counter as a scope output.
77    DoWhile {
78        condition: String,
79        counter: Option<String>,
80    },
81    /// `do_until` with optional counter as a scope output.
82    DoUntil {
83        condition: String,
84        counter: Option<String>,
85    },
86    /// A phase reference. With SRD-13d Phase 6 the phase is no
87    /// longer a leaf — every op template the phase declares
88    /// becomes an `OpTemplate` child of this node. The kernel
89    /// slot, if filled, holds the per-phase Polydat program.
90    Phase { name: String },
91    /// SRD-13d Phase 6 — an op template's scope, child of its
92    /// declaring phase. Per-template Polydat content (`bindings:`,
93    /// `metrics:` wire-injections, inline `{{<expr>}}` rewrites)
94    /// hangs off this node; the scope-elision pre-walk
95    /// (§3.3) decides whether it materialises its own kernel
96    /// or elides into the parent phase. Op-template scopes
97    /// also own per-op `Component` instances at runtime so
98    /// SRD-40b's duplicate-family check (via
99    /// `Component::register_instrument`) surfaces per-op
100    /// rather than per-phase.
101    OpTemplate { name: String },
102    /// Scenario-tree-level Polydat bindings block (see
103    /// [`nmbrs_workload::model::ScenarioNode::Bindings`]). The
104    /// `source` is Polydat matter text that compiles into a kernel
105    /// layered over the parent scope. Used for any scope-tree-
106    /// level state injection: workload-param shadowing (the
107    /// `set: { ... }` sugar form), derived bindings spanning a
108    /// subtree, shared cells, etc. — the Polydat grammar is the
109    /// only constraint on what the source may contain.
110    Bindings { source: String },
111}
112
113impl ScopeKind {
114    /// True if this kind opens a *new* Polydat scope (its own
115    /// kernel + pragmas + extern wiring). Phase scopes are only
116    /// "new" when the phase has its own bindings or it's an
117    /// iteration of a parent — that decision lives in the
118    /// compiler step, not this static descriptor.
119    pub fn opens_kernel(&self) -> bool {
120        !matches!(self, ScopeKind::Workload | ScopeKind::Session)
121    }
122
123    /// Short label for diagnostic output (`dryrun=phase`, TUI).
124    pub fn label(&self) -> String {
125        match self {
126            ScopeKind::Session => "session".into(),
127            ScopeKind::Workload => "workload".into(),
128            ScopeKind::Scenario { name } => format!("scenario '{name}'"),
129            ScopeKind::Comprehension { comprehension } => label_for_comprehension(comprehension),
130            ScopeKind::IncludedScenario { name } => format!("scenario '{name}'"),
131            ScopeKind::DoWhile { condition, counter } => match counter {
132                Some(c) => format!("do_while {condition} ({c})"),
133                None => format!("do_while {condition}"),
134            },
135            ScopeKind::DoUntil { condition, counter } => match counter {
136                Some(c) => format!("do_until {condition} ({c})"),
137                None => format!("do_until {condition}"),
138            },
139            ScopeKind::Phase { name } => format!("phase '{name}'"),
140            ScopeKind::OpTemplate { name } => format!("op '{name}'"),
141            ScopeKind::Bindings { source } => bindings_label(source),
142        }
143    }
144}
145
146/// Render a one-line label for an algebra-AST comprehension.
147///
148/// Strips off outer `Order` / `Filter` wrappers (which don't
149/// affect the structural display) to find the inner body
150/// shape: `Cartesian` renders as `each v1, v2, ...`, `Union`
151/// renders as `for_each_union {[...]; [...]}`, and a bare
152/// `Clause` renders as `each <var>`.
153fn label_for_comprehension(comp: &Comprehension) -> String {
154    use polydat::iteration::comprehension::source::Source;
155    // Peel outer Order/Filter — these are non-structural for
156    // the label.
157    let mut body = comp;
158    while let Comprehension::Order { child, .. } | Comprehension::Filter { child, .. } = body {
159        body = child.as_ref();
160    }
161    fn var_of(node: &Comprehension) -> String {
162        match node {
163            Comprehension::Clause { name, .. } => name.clone(),
164            Comprehension::Zip { children, .. } => {
165                let vs: Vec<String> = children.iter().map(var_of).collect();
166                format!("({})", vs.join(", "))
167            }
168            _ => "?".to_string(),
169        }
170    }
171    fn expr_of(node: &Comprehension) -> String {
172        match node {
173            Comprehension::Clause { source, .. } => match source {
174                Source::IntRange { lo, hi, step } if *step == 1 => format!("{lo}..{hi}"),
175                Source::IntRange { lo, hi, step } => format!("{lo}..{hi} step {step}"),
176                Source::Literal { values } if values.len() == 1 => format!("{:?}", values[0]),
177                Source::Literal { values } => format!("[{} values]", values.len()),
178                Source::Generator { expr, .. } => expr.clone(),
179                Source::WorkloadParamList { name, .. } => format!("{{{name}}}"),
180                Source::ContinuousInterval { interval, .. } => {
181                    format!("{}..{}", interval.lo, interval.hi)
182                }
183                Source::Distribution { .. } => "<dist>".to_string(),
184            },
185            Comprehension::Zip { children, .. } => {
186                let es: Vec<String> = children.iter().map(expr_of).collect();
187                format!("({})", es.join(", "))
188            }
189            _ => "?".to_string(),
190        }
191    }
192    match body {
193        Comprehension::Clause { name, .. } => format!("each {name}"),
194        Comprehension::Cartesian { children } if children.len() == 1 => {
195            format!("each {}", var_of(&children[0]))
196        }
197        Comprehension::Cartesian { children } => {
198            let vars: Vec<String> = children.iter().map(var_of).collect();
199            format!("each {}", vars.join(", "))
200        }
201        Comprehension::Union { children } => {
202            let parts: Vec<String> = children
203                .iter()
204                .map(|sub| {
205                    // Each Union child is itself a Cartesian (or
206                    // single Clause/Zip). Render its dims.
207                    let dims: Vec<String> = match sub {
208                        Comprehension::Cartesian { children: c } => c
209                            .iter()
210                            .map(|n| format!("{} in {}", var_of(n), expr_of(n)))
211                            .collect(),
212                        other => vec![format!("{} in {}", var_of(other), expr_of(other))],
213                    };
214                    format!("[{}]", dims.join(", "))
215                })
216                .collect();
217            format!("for_each_union {{{}}}", parts.join(" | "))
218        }
219        Comprehension::Zip { .. } => format!("each {}", var_of(body)),
220        Comprehension::Filter { .. } | Comprehension::Order { .. } => unreachable!(),
221    }
222}
223
224/// One node in the runtime scope tree. Carries enough metadata
225/// for the scheduler to walk and the compiler to fill in.
226#[derive(Debug)]
227pub struct ScopeNode {
228    pub kind: ScopeKind,
229    pub parent: Option<ScopeNodeIdx>,
230    pub children: Vec<ScopeNodeIdx>,
231    /// Depth from the root. Root is 0; its children are 1; and
232    /// so on. The scheduler's `schedule=<level0>/<level1>/...`
233    /// spec indexes by *child depth*, so a node at depth `d`
234    /// schedules its children with the spec entry for index
235    /// `d`.
236    pub depth: usize,
237    /// Pragmas declared at this scope level. Empty by default;
238    /// step 2 of the migration fills these in by walking the
239    /// node's source (or, for control-flow nodes, the optional
240    /// inline pragma block once the workload model supports
241    /// per-node pragmas).
242    pub pragmas: PragmaSet,
243    /// This scope's canonical kernel ([`crate::scope_kernel::ScopeKernel`]):
244    /// the interpreter program synthesis reads, beside the kernel that runs
245    /// on the fiber engine, and for an op-template scope the module each
246    /// fiber instantiates its per-op kernel from. Populated at pre-map
247    /// time by [`ScopeTree::install_kernel`].
248    ///
249    /// SRD 18b §"Iteration variables as scope outputs": every
250    /// non-trivial scope owns a kernel. The cached kernel is
251    /// shared via `Arc` (read-only canonical state). Mutable
252    /// per-iteration / per-fiber execution binds another instance of
253    /// it under the live parent ([`crate::scope_kernel::ScopeKernel::bind_under`]).
254    ///
255    /// `OnceLock` keeps installation lock-free; downstream
256    /// readers walk the parent chain via
257    /// [`ScopeTree::nearest_installed_ancestor_kernel`] /
258    /// [`ScopeTree::ancestor_kernels`] and only ever read
259    /// this slot.
260    pub cached_kernel: std::sync::OnceLock<std::sync::Arc<crate::scope_kernel::ScopeKernel>>,
261    /// SRD-13d §3 scope-elision mark — set once at
262    /// pre-walk by [`ScopeTree::mark_scope_elision`] and
263    /// read by every consumer (premap, runtime, diagnostics).
264    /// `None` means "not yet computed"; the pre-walk
265    /// guarantees every node has `Some` after it finishes.
266    /// `true` ⇒ this scope materialises its own kernel;
267    /// `false` ⇒ elided into the nearest materialised
268    /// ancestor.
269    pub materialised: Option<bool>,
270    /// SRD-13d §5.3 logical kernel name. Stable, fully-
271    /// qualified scope-tree path (`workload`, `phase.<n>`,
272    /// `phase.<n>.op.<o>`, etc.). Used by `dryrun=op`
273    /// diagnostics and `nmbrs describe wiring` displays. Empty
274    /// before the pre-walk runs.
275    pub logical_name: String,
276}
277
278// `OnceLock` doesn't implement `Clone`, so neither does
279// `ScopeNode` automatically. We don't actually need clones today
280// — the tree is built once and shared via `Arc<ScopeTree>` — but
281// some test helpers and serialisation paths assume `Clone`.
282// Provide a manual clone that drops the cache (subsequent reads
283// repopulate from a fresh compile, which is correct for clones
284// since each clone owns an independent cache).
285impl Clone for ScopeNode {
286    fn clone(&self) -> Self {
287        Self {
288            kind: self.kind.clone(),
289            parent: self.parent,
290            children: self.children.clone(),
291            depth: self.depth,
292            pragmas: self.pragmas.clone(),
293            cached_kernel: std::sync::OnceLock::new(),
294            materialised: self.materialised,
295            logical_name: self.logical_name.clone(),
296        }
297    }
298}
299
300/// A workload's runtime scope hierarchy. Built once per session.
301/// Stable indices into `nodes`; parent / child pointers are
302/// `ScopeNodeIdx`. Use the helpers on this struct for traversal
303/// — direct `nodes` access is fine for read-only inspection but
304/// the navigation helpers are easier to read.
305#[derive(Debug, Clone)]
306pub struct ScopeTree {
307    pub nodes: Vec<ScopeNode>,
308    pub root: ScopeNodeIdx,
309}
310
311impl ScopeTree {
312    /// Build a scope tree from the resolved scenario children.
313    /// `scenario_name` becomes the named [`ScopeKind::Scenario`]
314    /// that wraps `nodes` — the user's authored grouping is
315    /// preserved as a real ancestor, restoring "phase P in
316    /// scenario default" as a path query.
317    pub fn build(scenario_name: &str, nodes: &[ScenarioNode]) -> Self {
318        let mut tree = ScopeTree {
319            nodes: Vec::new(),
320            root: 0,
321        };
322
323        // Root: the session — one per process (SRD-88), the shared
324        // common root. Always at index 0.
325        tree.nodes.push(ScopeNode {
326            kind: ScopeKind::Session,
327            parent: None,
328            children: Vec::new(),
329            depth: 0,
330            pragmas: PragmaSet::default(),
331            cached_kernel: std::sync::OnceLock::new(),
332            materialised: None,
333            logical_name: String::new(),
334        });
335
336        // The workload root — one per execution (SRD-88), under the
337        // session. Owns the outer workload Polydat Kernel.
338        let workload_idx = tree.add_node(ScopeNode {
339            kind: ScopeKind::Workload,
340            parent: Some(0),
341            children: Vec::new(),
342            depth: 1,
343            pragmas: PragmaSet::default(),
344            cached_kernel: std::sync::OnceLock::new(),
345            materialised: None,
346            logical_name: String::new(),
347        });
348        tree.nodes[0].children.push(workload_idx);
349
350        // Scenario layer wraps the user's children. This is the
351        // "lost grouping" the user called out — a real scope
352        // ancestor named after the scenario.
353        let scenario_idx = tree.add_node(ScopeNode {
354            kind: ScopeKind::Scenario {
355                name: scenario_name.into(),
356            },
357            parent: Some(workload_idx),
358            children: Vec::new(),
359            depth: 2,
360            pragmas: PragmaSet::default(),
361            cached_kernel: std::sync::OnceLock::new(),
362            materialised: None,
363            logical_name: String::new(),
364        });
365        tree.nodes[workload_idx].children.push(scenario_idx);
366
367        // Walk the user's children recursively under the scenario.
368        for child in nodes {
369            tree.append_subtree(scenario_idx, child);
370        }
371
372        tree
373    }
374
375    /// The workload-root node — the single child of the session root
376    /// (node 0). One per execution; owns the outer workload kernel.
377    /// Falls back to the root if (degenerately) there is no workload
378    /// layer.
379    pub fn workload_root_idx(&self) -> ScopeNodeIdx {
380        self.nodes[0].children.first().copied().unwrap_or(0)
381    }
382
383    /// The scenario-layer node — the single child of the workload root
384    /// (node 0). The walker seeds its scope cursor here so the top-level
385    /// scenario nodes resolve **positionally** against this node's children
386    /// (one scope-tree child per scenario node, in order — see
387    /// `Self::append_subtree`). Falls back to the root if (degenerately)
388    /// there is no scenario layer.
389    pub fn scenario_root_idx(&self) -> ScopeNodeIdx {
390        // Session(0) → Workload → Scenario. Walk two layers down.
391        let workload = self.workload_root_idx();
392        self.nodes[workload]
393            .children
394            .first()
395            .copied()
396            .unwrap_or(workload)
397    }
398
399    /// Append the subtree rooted at `node` as a child of `parent_idx`.
400    /// Recursive — control-flow nodes pull in their own children.
401    fn append_subtree(&mut self, parent_idx: ScopeNodeIdx, node: &ScenarioNode) {
402        let parent_depth = self.nodes[parent_idx].depth;
403        let depth = parent_depth + 1;
404
405        match node {
406            ScenarioNode::Phase(name) => {
407                let idx = self.add_node(ScopeNode {
408                    kind: ScopeKind::Phase { name: name.clone() },
409                    parent: Some(parent_idx),
410                    children: Vec::new(),
411                    depth,
412                    pragmas: PragmaSet::default(),
413                    cached_kernel: std::sync::OnceLock::new(),
414                    materialised: None,
415                    logical_name: String::new(),
416                });
417                self.nodes[parent_idx].children.push(idx);
418            }
419            ScenarioNode::Comprehension {
420                comprehension,
421                children,
422                ..
423            } => {
424                let idx = self.add_node(ScopeNode {
425                    kind: ScopeKind::Comprehension {
426                        comprehension: comprehension.clone(),
427                    },
428                    parent: Some(parent_idx),
429                    children: Vec::new(),
430                    depth,
431                    pragmas: PragmaSet::default(),
432                    cached_kernel: std::sync::OnceLock::new(),
433                    materialised: None,
434                    logical_name: String::new(),
435                });
436                self.nodes[parent_idx].children.push(idx);
437                for child in children {
438                    self.append_subtree(idx, child);
439                }
440            }
441            ScenarioNode::IncludedScenario { name, children } => {
442                let idx = self.add_node(ScopeNode {
443                    kind: ScopeKind::IncludedScenario { name: name.clone() },
444                    parent: Some(parent_idx),
445                    children: Vec::new(),
446                    depth,
447                    pragmas: PragmaSet::default(),
448                    cached_kernel: std::sync::OnceLock::new(),
449                    materialised: None,
450                    logical_name: String::new(),
451                });
452                self.nodes[parent_idx].children.push(idx);
453                for child in children {
454                    self.append_subtree(idx, child);
455                }
456            }
457            ScenarioNode::DoWhile {
458                condition,
459                counter,
460                children,
461            } => {
462                let idx = self.add_node(ScopeNode {
463                    kind: ScopeKind::DoWhile {
464                        condition: condition.clone(),
465                        counter: counter.clone(),
466                    },
467                    parent: Some(parent_idx),
468                    children: Vec::new(),
469                    depth,
470                    pragmas: PragmaSet::default(),
471                    cached_kernel: std::sync::OnceLock::new(),
472                    materialised: None,
473                    logical_name: String::new(),
474                });
475                self.nodes[parent_idx].children.push(idx);
476                for child in children {
477                    self.append_subtree(idx, child);
478                }
479            }
480            ScenarioNode::DoUntil {
481                condition,
482                counter,
483                children,
484            } => {
485                let idx = self.add_node(ScopeNode {
486                    kind: ScopeKind::DoUntil {
487                        condition: condition.clone(),
488                        counter: counter.clone(),
489                    },
490                    parent: Some(parent_idx),
491                    children: Vec::new(),
492                    depth,
493                    pragmas: PragmaSet::default(),
494                    cached_kernel: std::sync::OnceLock::new(),
495                    materialised: None,
496                    logical_name: String::new(),
497                });
498                self.nodes[parent_idx].children.push(idx);
499                for child in children {
500                    self.append_subtree(idx, child);
501                }
502            }
503            ScenarioNode::Bindings { source, children } => {
504                let idx = self.add_node(ScopeNode {
505                    kind: ScopeKind::Bindings {
506                        source: source.clone(),
507                    },
508                    parent: Some(parent_idx),
509                    children: Vec::new(),
510                    depth,
511                    pragmas: PragmaSet::default(),
512                    cached_kernel: std::sync::OnceLock::new(),
513                    materialised: None,
514                    logical_name: String::new(),
515                });
516                self.nodes[parent_idx].children.push(idx);
517                for child in children {
518                    self.append_subtree(idx, child);
519                }
520            }
521        }
522    }
523
524    fn add_node(&mut self, node: ScopeNode) -> ScopeNodeIdx {
525        let idx = self.nodes.len();
526        self.nodes.push(node);
527        idx
528    }
529
530    /// SRD-13d Phase 6 — extend every `Phase` scope node with
531    /// `OpTemplate` children (one per op declared in the
532    /// phase). Two-step build: `ScopeTree::build` produces
533    /// the scenario-shaped skeleton (phases as leaves);
534    /// this method adds the op-template tier on top by
535    /// consulting the workload's per-phase `WorkloadPhase`
536    /// records.
537    ///
538    /// Idempotent: a phase whose `OpTemplate` children are
539    /// already present is left alone (the post-build pre-walk
540    /// can run before or after this without double-adding).
541    /// Run before `mark_scope_elision` so the per-op
542    /// classification gets the chance to elide / materialise
543    /// each op-template tier.
544    pub fn extend_with_op_templates(
545        &mut self,
546        phases: &std::collections::HashMap<String, nmbrs_workload::model::WorkloadPhase>,
547    ) {
548        // Snapshot the indices first — we'll mutate `nodes`
549        // during the loop.
550        let phase_nodes: Vec<(ScopeNodeIdx, String, usize)> = self
551            .nodes
552            .iter()
553            .enumerate()
554            .filter_map(|(i, n)| match &n.kind {
555                ScopeKind::Phase { name } => Some((i, name.clone(), n.depth)),
556                _ => None,
557            })
558            .collect();
559
560        for (phase_idx, phase_name, phase_depth) in phase_nodes {
561            // Skip phases that already have OpTemplate children.
562            let already_has_ops = self.nodes[phase_idx]
563                .children
564                .iter()
565                .any(|&c| matches!(self.nodes[c].kind, ScopeKind::OpTemplate { .. }));
566            if already_has_ops {
567                continue;
568            }
569            // Look up the phase's op list. Phases referenced
570            // by name with no entry in `phases` (e.g. the
571            // `default` scenario including a phase that's
572            // declared elsewhere) just get no op children —
573            // not a structural error.
574            let Some(phase) = phases.get(&phase_name) else {
575                continue;
576            };
577            for op in &phase.ops {
578                let op_idx = self.add_node(ScopeNode {
579                    kind: ScopeKind::OpTemplate {
580                        name: op.name.clone(),
581                    },
582                    parent: Some(phase_idx),
583                    children: Vec::new(),
584                    depth: phase_depth + 1,
585                    pragmas: PragmaSet::default(),
586                    cached_kernel: std::sync::OnceLock::new(),
587                    materialised: None,
588                    logical_name: String::new(),
589                });
590                self.nodes[phase_idx].children.push(op_idx);
591            }
592        }
593    }
594
595    /// SRD-13d §3.3 — pre-walk every scope-tree node and mark
596    /// it `materialised` (own kernel) or elided (descendants
597    /// bind through parent). Also assigns the SRD-13d §5.3
598    /// logical kernel name, which is the fully-qualified
599    /// scope-tree path. Run once at workload-load; premap and
600    /// runtime read the marks afterward.
601    ///
602    /// `is_materialising` is the predicate the pre-walk
603    /// applies per node — typically a closure that consults
604    /// the AST node's `HasPolydatMatter` classification (None /
605    /// Readonly ⇒ elide; Definitions ⇒ check program-hash
606    /// equivalence with the parent and decide). The walker is
607    /// agnostic to the exact predicate; SRD-13d §3.3 fixes
608    /// the order.
609    ///
610    /// The workload root is **always** materialised (see
611    /// SRD-13d §5.1) so the walk terminates at a materialised
612    /// ancestor regardless of how aggressively descendants
613    /// elide.
614    pub fn mark_scope_elision<F>(&mut self, mut is_materialising: F)
615    where
616        F: FnMut(&ScopeKind, ScopeNodeIdx) -> bool,
617    {
618        // Walk in DFS order; logical names depend on parent
619        // names being assigned first, which DFS pre-order
620        // guarantees (root → scenario → … → leaf).
621        let order: Vec<ScopeNodeIdx> = self.iter_dfs().map(|(idx, _)| idx).collect();
622        for idx in order {
623            // Root: the session — always materialised, contributes NO
624            // logical-path segment (SRD-88; the workload child below
625            // owns the `workload` segment, keeping paths
626            // `workload.scenario.…`).
627            if idx == self.root {
628                self.nodes[idx].materialised = Some(true);
629                self.nodes[idx].logical_name = String::new();
630                continue;
631            }
632            let kind = self.nodes[idx].kind.clone();
633            // The workload node always materialises — it owns the
634            // installed workload kernel (SRD-88: it's the per-execution
635            // root beneath the session, the old always-materialised
636            // root's role). Descendants elide INTO it as before.
637            let materialise = matches!(kind, ScopeKind::Workload) || is_materialising(&kind, idx);
638            self.nodes[idx].materialised = Some(materialise);
639
640            // Logical name = parent's logical name + "."
641            // + per-kind segment. The segment shape follows
642            // SRD-13d §5.3's table (`phase.<n>`,
643            // `for_each.<var>`, `op.<o>`).
644            let parent_name = self.nodes[idx]
645                .parent
646                .map(|p| self.nodes[p].logical_name.clone())
647                .unwrap_or_default();
648            let segment = match &kind {
649                // SRD-88 — the session is the always-present implicit root;
650                // it contributes NO logical-path segment, so addressable
651                // paths stay `workload.scenario.…` (the workload/execution
652                // is what varies and addresses the path). The session tier
653                // is still visible structurally via `kind.label()`.
654                ScopeKind::Session => String::new(),
655                ScopeKind::Workload => "workload".to_string(),
656                ScopeKind::Scenario { name } => format!("scenario.{name}"),
657                ScopeKind::Phase { name } => format!("phase.{name}"),
658                ScopeKind::OpTemplate { name } => format!("op.{name}"),
659                ScopeKind::Comprehension { .. } => "for_each".to_string(),
660                ScopeKind::IncludedScenario { name } => format!("include.{name}"),
661                ScopeKind::DoWhile { .. } => "do_while".to_string(),
662                ScopeKind::DoUntil { .. } => "do_until".to_string(),
663                ScopeKind::Bindings { source } => {
664                    // First `final NAME` / `NAME :=` in the
665                    // source distinguishes this scope-tree node
666                    // in the logical-name path. For sugar from
667                    // `set: { mode: verbose }` the source starts
668                    // with `const mode := …` so the segment is
669                    // `bindings.mode`. Sources with no clear
670                    // first name fall back to a positional tag.
671                    let first_name = source
672                        .lines()
673                        .map(str::trim)
674                        .find(|l| !l.is_empty())
675                        .and_then(|line| {
676                            let after_kw = line
677                                .strip_prefix("const ")
678                                .or_else(|| line.strip_prefix("final "))
679                                .or_else(|| line.strip_prefix("init "))
680                                .or_else(|| line.strip_prefix("shared "))
681                                .unwrap_or(line);
682                            after_kw
683                                .split([' ', ':'])
684                                .next()
685                                .filter(|s| !s.is_empty())
686                                .map(str::to_string)
687                        })
688                        .unwrap_or_else(|| "anon".to_string());
689                    format!("bindings.{first_name}")
690                }
691            };
692            self.nodes[idx].logical_name = if parent_name.is_empty() {
693                segment
694            } else {
695                format!("{parent_name}.{segment}")
696            };
697        }
698    }
699
700    /// SRD-13d §5.1 — walk past elided scope tiers to the
701    /// nearest materialised ancestor (or self, when this
702    /// node is itself materialised). Every consumer that
703    /// needs a kernel handle (cache lookups, bind-outer-
704    /// scope, diagnostics) routes through this — it's the
705    /// single point that knows about elision; nothing
706    /// else does.
707    ///
708    /// The workload root is always materialised, so this
709    /// always terminates with `Some(idx)`. Returns `None`
710    /// only if [`Self::mark_scope_elision`] hasn't been run.
711    pub fn nearest_materialised(&self, idx: ScopeNodeIdx) -> Option<ScopeNodeIdx> {
712        let mut cur = idx;
713        loop {
714            match self.nodes[cur].materialised? {
715                true => return Some(cur),
716                false => match self.nodes[cur].parent {
717                    Some(p) => cur = p,
718                    None => return Some(cur), // root by construction
719                },
720            }
721        }
722    }
723
724    /// Iterate every scope node in depth-first pre-order. The
725    /// scheduler's default walk and the canonical display
726    /// linearisation both consume this.
727    pub fn iter_dfs(&self) -> DfsIter<'_> {
728        DfsIter {
729            tree: self,
730            stack: vec![self.root],
731        }
732    }
733
734    /// Walk from `idx` up through its ancestors to the root,
735    /// inclusive of `idx` itself. Use this to compute effective
736    /// pragmas or to render a path label.
737    pub fn ancestors(&self, idx: ScopeNodeIdx) -> AncestorsIter<'_> {
738        AncestorsIter {
739            tree: self,
740            cursor: Some(idx),
741        }
742    }
743
744    /// First scope-tree node whose kind is `Phase { name }`
745    /// matching the given name. Returns `None` if the scenario
746    /// doesn't reference this phase. When a single phase is
747    /// invoked from multiple scenario sites (rare; most workloads
748    /// reference a phase exactly once), this returns the first
749    /// occurrence in depth-first order — sufficient for current
750    /// callers, who use the result to fetch the chain-walked
751    /// `PragmaSet`.
752    pub fn phase_node_by_name(&self, name: &str) -> Option<ScopeNodeIdx> {
753        self.iter_dfs().find_map(|(idx, node)| match &node.kind {
754            ScopeKind::Phase { name: n } if n == name => Some(idx),
755            _ => None,
756        })
757    }
758
759    /// Op-template kernel programs for every materialised
760    /// op-template that's a child of `phase_idx`. Keyed by the
761    /// op's name. Used by the executor to thread per-op-template
762    /// programs into the activity so each `MetricsDispenser`
763    /// builds its `ScopeFixture` against the correct scope
764    /// (SRD-13d Phase 9 §"per-dispenser kernel instancing").
765    /// Flattened op-templates (`materialised != Some(true)`) are
766    /// omitted from the map; their dispensers reach the parent
767    /// kernel through the standard `nearest_materialised`
768    /// fall-through.
769    ///
770    /// Rule 2 write-through bindings ride on the program itself
771    /// (baked in by the SRD-67 builder's finalize step). Any
772    /// kernel built from the program inherits them automatically
773    /// when bound (`ScopeKernel::bind_under`) — no side channel.
774    pub fn op_template_programs_for_phase(
775        &self,
776        phase_idx: ScopeNodeIdx,
777    ) -> std::collections::HashMap<String, std::sync::Arc<polydat::kernel::PolydatProgram>> {
778        let mut out = std::collections::HashMap::new();
779        for &child_idx in &self.nodes[phase_idx].children {
780            let child = &self.nodes[child_idx];
781            let ScopeKind::OpTemplate { name } = &child.kind else {
782                continue;
783            };
784            if child.materialised != Some(true) {
785                continue;
786            }
787            if let Some(kernel) = child.cached_kernel.get() {
788                out.insert(name.clone(), kernel.program().clone());
789            }
790        }
791        out
792    }
793
794    /// The op-template scope modules of `phase_idx`'s materialised
795    /// op-template children, keyed by op name: what each fiber
796    /// instantiates its per-op kernels from on the fiber engine
797    /// ([`crate::fiber_engine`]).
798    pub fn op_template_modules_for_phase(
799        &self,
800        phase_idx: ScopeNodeIdx,
801    ) -> Vec<(
802        String,
803        std::sync::Arc<crate::fiber_engine::OpTemplateModule>,
804    )> {
805        self.nodes[phase_idx]
806            .children
807            .iter()
808            .filter_map(|&child_idx| {
809                let child = &self.nodes[child_idx];
810                let ScopeKind::OpTemplate { name } = &child.kind else {
811                    return None;
812                };
813                if child.materialised != Some(true) {
814                    return None;
815                }
816                let module = child.cached_kernel.get()?.module()?;
817                Some((name.clone(), module.clone()))
818            })
819            .collect()
820    }
821
822    /// All phase-leaf indices in depth-first order. Equivalent
823    /// to filtering `iter_dfs()` to `ScopeKind::Phase` — the
824    /// helper exists because it's the most common consumer
825    /// query (TUI tree pre-mapping, dryrun=phase).
826    pub fn phase_leaves(&self) -> Vec<ScopeNodeIdx> {
827        self.iter_dfs()
828            .filter_map(|(idx, node)| matches!(node.kind, ScopeKind::Phase { .. }).then_some(idx))
829            .collect()
830    }
831
832    /// Walk ancestors of `idx` looking for the nearest scope
833    /// node that has a kernel installed. Used at routing time
834    /// to find the kernel a for_each scope's `materialize_wiring_from_outer`
835    /// should chain from. Workload root always has a kernel
836    /// installed (per M3.1), so this never returns `None` for
837    /// any descendant of the root.
838    pub fn nearest_installed_ancestor_kernel(
839        &self,
840        idx: ScopeNodeIdx,
841    ) -> Option<std::sync::Arc<crate::scope_kernel::ScopeKernel>> {
842        let mut cursor = self.nodes.get(idx)?.parent;
843        while let Some(p) = cursor {
844            if let Some(k) = self.nodes[p].cached_kernel.get() {
845                return Some(k.clone());
846            }
847            cursor = self.nodes[p].parent;
848        }
849        None
850    }
851
852    /// Collect every installed ancestor kernel of `idx`,
853    /// innermost first (immediate parent → workload root).
854    /// Skips ancestor levels whose `cached_kernel` is empty
855    /// (intermediate nodes that don't own their own kernel).
856    /// Used by the checkpoint identity path to feed
857    /// [`polydat::kernel::PolydatProgram::instance_hash`]
858    /// (SRD-44 §"Identity matching at resume" + project
859    /// memory `program_vs_instance_hash`).
860    pub fn ancestor_kernels(
861        &self,
862        idx: ScopeNodeIdx,
863    ) -> Vec<std::sync::Arc<crate::scope_kernel::ScopeKernel>> {
864        let mut out = Vec::new();
865        let mut cursor = self.nodes.get(idx).and_then(|n| n.parent);
866        while let Some(p) = cursor {
867            if let Some(k) = self.nodes[p].cached_kernel.get() {
868                out.push(k.clone());
869            }
870            cursor = self.nodes[p].parent;
871        }
872        out
873    }
874
875    /// [`Self::ancestor_kernels`] split at the session boundary
876    /// (SRD-107): `(below, session)` where `below` is every
877    /// installed ancestor kernel from the immediate parent up
878    /// through the workload root, and `session` is the
879    /// session-node kernel (the workload-params module) when one
880    /// is installed. The provenance base hash covers `below`
881    /// only; param values are covered per-phase by the
882    /// consumed-params digest instead.
883    pub fn ancestor_kernels_split(
884        &self,
885        idx: ScopeNodeIdx,
886    ) -> (
887        Vec<std::sync::Arc<crate::scope_kernel::ScopeKernel>>,
888        Option<std::sync::Arc<crate::scope_kernel::ScopeKernel>>,
889    ) {
890        let mut below = Vec::new();
891        let mut session = None;
892        let mut cursor = self.nodes.get(idx).and_then(|n| n.parent);
893        while let Some(p) = cursor {
894            if let Some(k) = self.nodes[p].cached_kernel.get() {
895                if matches!(self.nodes[p].kind, ScopeKind::Session) {
896                    session = Some(k.clone());
897                } else {
898                    below.push(k.clone());
899                }
900            }
901            cursor = self.nodes[p].parent;
902        }
903        (below, session)
904    }
905
906    /// Find a `Comprehension` scope by structural-equality match
907    /// against its [`Comprehension`] AST. Returns the **first**
908    /// DFS-pre-order match.
909    pub fn find_comprehension_scope(&self, comprehension: &Comprehension) -> Option<ScopeNodeIdx> {
910        self.iter_dfs().find_map(|(idx, node)| match &node.kind {
911            ScopeKind::Comprehension { comprehension: c } if c == comprehension => Some(idx),
912            _ => None,
913        })
914    }
915
916    /// First scope-tree node whose kind is
917    /// `ScopeKind::Bindings { source }` matching exactly,
918    /// searched globally from root in DFS pre-order.
919    ///
920    /// **Prefer [`Self::find_bindings_scope_under`]** when the
921    /// executor's current scope position is known — see that
922    /// method's doc for why a global content-only lookup is
923    /// currently unsafe.
924    pub fn find_bindings_scope(&self, source: &str) -> Option<ScopeNodeIdx> {
925        self.iter_dfs().find_map(|(idx, node)| match &node.kind {
926            ScopeKind::Bindings { source: s } if s == source => Some(idx),
927            _ => None,
928        })
929    }
930
931    /// **TRANSITIONAL WORKAROUND** — see task #19 for the
932    /// canonical end-state plan. Constrains the lookup of a
933    /// `Bindings` scope to descendants of `parent` so that two
934    /// `Bindings` nodes sharing source text at different scope-
935    /// tree positions resolve to the right one based on the
936    /// executor's current position.
937    ///
938    /// The deeper problem: today the AST/source we use as the
939    /// lookup key is LOSSY — two scope-tree nodes that produce
940    /// semantically-distinct installed kernels (different
941    /// cascaded externs from different parent chains) can share
942    /// AST/source. Per SRD-13d §"Op-template scope synthesis" +
943    /// SRD-13f §"The read invariant", installed kernels are
944    /// determined by their PARENT chain, not by their own
945    /// content alone. The current scope-aware lookup adds the
946    /// missing context (parent subtree) at the call site to
947    /// disambiguate.
948    ///
949    /// **Future direction:** make the AST/source self-
950    /// identifying so that semantically-distinct kernels never
951    /// share matter (embed parent-chain signature, encode
952    /// scenario-tree path, or some equivalent invariant). Once
953    /// that lands, content-only `find_bindings_scope` is
954    /// correct again and this `_under` variant can be retired.
955    pub fn find_bindings_scope_under(
956        &self,
957        parent: ScopeNodeIdx,
958        source: &str,
959    ) -> Option<ScopeNodeIdx> {
960        self.find_descendant_matching(parent, &mut |node| match &node.kind {
961            ScopeKind::Bindings { source: s } => s == source,
962            _ => false,
963        })
964    }
965
966    /// **TRANSITIONAL WORKAROUND** — see
967    /// [`Self::find_bindings_scope_under`] for the underlying
968    /// principle and task #19 for the canonical end-state plan.
969    /// Retired once the AST becomes self-identifying.
970    pub fn find_comprehension_scope_under(
971        &self,
972        parent: ScopeNodeIdx,
973        comprehension: &Comprehension,
974    ) -> Option<ScopeNodeIdx> {
975        self.find_descendant_matching(parent, &mut |node| match &node.kind {
976            ScopeKind::Comprehension { comprehension: c } => c == comprehension,
977            _ => false,
978        })
979    }
980
981    /// DFS pre-order search through the descendants of `parent`
982    /// (excluding `parent` itself). Returns the first node whose
983    /// predicate returns true.
984    fn find_descendant_matching(
985        &self,
986        parent: ScopeNodeIdx,
987        predicate: &mut dyn FnMut(&ScopeNode) -> bool,
988    ) -> Option<ScopeNodeIdx> {
989        let mut stack: Vec<ScopeNodeIdx> =
990            self.nodes[parent].children.iter().rev().copied().collect();
991        while let Some(idx) = stack.pop() {
992            if predicate(&self.nodes[idx]) {
993                return Some(idx);
994            }
995            for &child in self.nodes[idx].children.iter().rev() {
996                stack.push(child);
997            }
998        }
999        None
1000    }
1001
1002    /// Validate iteration-variable name uniqueness against the
1003    /// surrounding scope chain.
1004    ///
1005    /// An iter-var name (`for_each: "X in ..."`,
1006    /// `for_combinations: "X in ..., Y in ..."`,
1007    /// `for_each_union: ...`, do-loop counters) **must not**
1008    /// shadow:
1009    /// - a workload param,
1010    /// - an iter var declared by an enclosing scope.
1011    ///
1012    /// Aliasing creates a name that can't unambiguously resolve
1013    /// at spec-evaluation time (the iter var is being defined
1014    /// from a value that uses the same name; the runtime can't
1015    /// tell whether `{X}` means the iter var or the shadowed
1016    /// outer name). Rather than try to disambiguate, the build
1017    /// rejects it up-front with a clear error so the user
1018    /// renames the iter var.
1019    ///
1020    /// Returns `Ok(())` if every iter-var name is unique. Returns
1021    /// `Err(...)` with the offending name and which kind of
1022    /// collision (workload param vs ancestor iter var) the user
1023    /// has on the first violation found.
1024    pub fn validate_iter_var_uniqueness(
1025        &self,
1026        workload_params: &std::collections::HashSet<String>,
1027    ) -> Result<(), String> {
1028        fn walk(
1029            tree: &ScopeTree,
1030            idx: ScopeNodeIdx,
1031            ancestor_iter_vars: &std::collections::HashSet<String>,
1032            workload_params: &std::collections::HashSet<String>,
1033        ) -> Result<(), String> {
1034            let node = &tree.nodes[idx];
1035            // Collect the iter vars declared at this node.
1036            // Algebra's `coordinate_names()` returns owned
1037            // strings (operator-tree walks need fresh strings
1038            // — there's no single backing slice to borrow
1039            // from), so this block is owned-string throughout.
1040            let own_iter_vars: Vec<String> = match &node.kind {
1041                ScopeKind::Comprehension { comprehension } => comprehension.coordinate_names(),
1042                ScopeKind::DoWhile {
1043                    counter: Some(c), ..
1044                }
1045                | ScopeKind::DoUntil {
1046                    counter: Some(c), ..
1047                } => vec![c.clone()],
1048                _ => Vec::new(),
1049            };
1050            for var in &own_iter_vars {
1051                if workload_params.contains(var) {
1052                    return Err(format!(
1053                        "iter-var '{var}' aliases workload param '{var}'. \
1054                         A for_each / for_combinations / for_each_union iter \
1055                         variable cannot share a name with a workload param — \
1056                         spec evaluation can't disambiguate `{{{var}}}` between \
1057                         the iter var and the param. Rename one of them."
1058                    ));
1059                }
1060                if ancestor_iter_vars.contains(var) {
1061                    return Err(format!(
1062                        "iter-var '{var}' aliases an iter var declared by an \
1063                         enclosing scope. Inner iter vars must use distinct \
1064                         names from outer iter vars."
1065                    ));
1066                }
1067            }
1068            // Extend the ancestor set for descent.
1069            let mut next_ancestors = ancestor_iter_vars.clone();
1070            for v in &own_iter_vars {
1071                next_ancestors.insert(v.clone());
1072            }
1073            for &child in &node.children {
1074                walk(tree, child, &next_ancestors, workload_params)?;
1075            }
1076            Ok(())
1077        }
1078        walk(
1079            self,
1080            self.root,
1081            &std::collections::HashSet::new(),
1082            workload_params,
1083        )
1084    }
1085
1086    /// Install the canonical compiled kernel for `scope_idx`.
1087    ///
1088    /// Called at pre-map time after compiling the scope's
1089    /// `PolydatProgram`. Once installed, the kernel is the *single*
1090    /// authoritative answer for "what is `<name>` at this
1091    /// scope?" — every name visible at this scope (own outputs
1092    /// plus parent-inherited values bound via
1093    /// [`ScopeKernel::synthesize_under`](crate::scope_kernel::ScopeKernel::synthesize_under)) resolves through the
1094    /// standard Polydat API on this one kernel. Callers don't walk
1095    /// the scope tree to do name resolution; Polydat's auto-extern +
1096    /// outer-scope wiring already encapsulates the layering.
1097    ///
1098    /// Idempotent only by virtue of `OnceLock`: a second install
1099    /// silently no-ops, returning `false`. Returns `true` on
1100    /// fresh install. Callers that need to detect a duplicate
1101    /// install should check the boolean.
1102    pub fn install_kernel(
1103        &self,
1104        scope_idx: ScopeNodeIdx,
1105        kernel: std::sync::Arc<crate::scope_kernel::ScopeKernel>,
1106    ) -> bool {
1107        match self.nodes.get(scope_idx) {
1108            Some(node) => {
1109                let inserted = node.cached_kernel.set(kernel.clone()).is_ok();
1110                // Ride-along visitor hook (SRD planning-walk
1111                // dryrun=kernels surface). Fires exactly once
1112                // per scope's fresh install — the OnceLock
1113                // semantics above guarantee no duplicate calls.
1114                if inserted {
1115                    notify_kernel_installed(node, scope_idx, &kernel);
1116                }
1117                inserted
1118            }
1119            None => false,
1120        }
1121    }
1122
1123    /// Populate `pragmas` on every phase-leaf scope by scanning
1124    /// each phase's `BindingsDef::PolydatSource` strings for `pragma`
1125    /// statements, then walk the tree so each scope's set holds its
1126    /// ancestors' pragmas followed by its own, as polydat nests a
1127    /// scope's pragmas (`PragmaSet::nested`). After this call,
1128    /// `node.pragmas.strict_values()` answers for every pragma in force
1129    /// at the node.
1130    ///
1131    /// SRD 18b §"Pragma chain along the scope tree". Idempotent
1132    /// per call (replaces any prior `pragmas` content).
1133    pub fn populate_pragmas(
1134        &mut self,
1135        phases: &std::collections::HashMap<String, nmbrs_workload::model::WorkloadPhase>,
1136    ) {
1137        // Pass 1: extract phase-local pragmas. Iterate by
1138        // `phase_leaves` (which already does the kind filter)
1139        // and walk each phase's ops for Polydat source strings to
1140        // parse.
1141        let leaves = self.phase_leaves();
1142        for idx in leaves {
1143            let name = match &self.nodes[idx].kind {
1144                ScopeKind::Phase { name } => name.clone(),
1145                _ => continue,
1146            };
1147            if let Some(phase) = phases.get(&name) {
1148                self.nodes[idx].pragmas = extract_phase_pragmas(phase);
1149            }
1150        }
1151
1152        // Pass 2: nest each scope in its parent. Walk in depth order
1153        // so a parent's set is complete before its children take it.
1154        let order: Vec<ScopeNodeIdx> = self.iter_dfs().map(|(i, _)| i).collect();
1155        for idx in order {
1156            if let Some(parent) = self.nodes[idx].parent {
1157                let local = std::mem::take(&mut self.nodes[idx].pragmas.entries);
1158                let mut entries = self.nodes[parent].pragmas.entries.clone();
1159                entries.extend(local);
1160                self.nodes[idx].pragmas = PragmaSet { entries };
1161            }
1162        }
1163    }
1164}
1165
1166/// Extract pragmas from a phase's source by walking every op's
1167/// `BindingsDef::PolydatSource` and collecting `Statement::Pragma`s.
1168/// A phase has multiple ops; their bindings can each declare
1169/// pragmas. Today the convention is one pragma block at the
1170/// phase head; multi-op phases that put pragmas on individual
1171/// ops still get them aggregated here.
1172fn extract_phase_pragmas(phase: &nmbrs_workload::model::WorkloadPhase) -> PragmaSet {
1173    use nmbrs_workload::model::BindingsDef;
1174    let mut entries = Vec::new();
1175    for op in &phase.ops {
1176        let src = match &op.bindings {
1177            BindingsDef::PolydatSource(s) => s.as_str(),
1178            _ => continue,
1179        };
1180        // Lex/parse to AST to surface `Statement::Pragma`s. If
1181        // the source is malformed, skip — the real phase compile
1182        // will report a clean parse error later.
1183        let tokens = match polydat::dsl::lexer::lex(src) {
1184            Ok(t) => t,
1185            Err(_) => continue,
1186        };
1187        let ast = match polydat::dsl::parser::parse(tokens) {
1188            Ok(a) => a,
1189            Err(_) => continue,
1190        };
1191        let local = polydat::dsl::pragmas::collect_from_ast(&ast);
1192        entries.extend(local.entries);
1193    }
1194    PragmaSet { entries }
1195}
1196
1197/// Ride-along visitor for kernel-installation events. Set by
1198/// the runner when `dryrun=kernels` is requested so each
1199/// `install_kernel` fires the printer as the planning walk
1200/// encounters the scope. `None` (the default) keeps install
1201/// a no-cost hot path.
1202pub type KernelInstallVisitor =
1203    Box<dyn Fn(&ScopeNode, ScopeNodeIdx, &crate::scope_kernel::ScopeKernel) + Send + Sync>;
1204
1205static KERNEL_INSTALL_VISITOR: std::sync::OnceLock<std::sync::Mutex<Option<KernelInstallVisitor>>> =
1206    std::sync::OnceLock::new();
1207
1208fn visitor_slot() -> &'static std::sync::Mutex<Option<KernelInstallVisitor>> {
1209    KERNEL_INSTALL_VISITOR.get_or_init(|| std::sync::Mutex::new(None))
1210}
1211
1212/// Register a visitor that fires on every `install_kernel`
1213/// call. Replaces any prior visitor; pass `None` to clear.
1214/// Called by the runner at session start when
1215/// `dryrun=kernels` is set.
1216pub fn set_kernel_install_visitor(v: Option<KernelInstallVisitor>) {
1217    if let Ok(mut slot) = visitor_slot().lock() {
1218        *slot = v;
1219    }
1220}
1221
1222fn notify_kernel_installed(
1223    node: &ScopeNode,
1224    idx: ScopeNodeIdx,
1225    kernel: &crate::scope_kernel::ScopeKernel,
1226) {
1227    if let Ok(slot) = visitor_slot().lock()
1228        && let Some(visitor) = slot.as_ref()
1229    {
1230        visitor(node, idx, kernel);
1231    }
1232}
1233
1234/// Depth-first pre-order iterator over `(idx, &ScopeNode)`.
1235pub struct DfsIter<'a> {
1236    tree: &'a ScopeTree,
1237    stack: Vec<ScopeNodeIdx>,
1238}
1239
1240impl<'a> Iterator for DfsIter<'a> {
1241    type Item = (ScopeNodeIdx, &'a ScopeNode);
1242    fn next(&mut self) -> Option<Self::Item> {
1243        let idx = self.stack.pop()?;
1244        let node = &self.tree.nodes[idx];
1245        // Push children in reverse so the leftmost child comes
1246        // out of the stack first (pre-order).
1247        for &child in node.children.iter().rev() {
1248            self.stack.push(child);
1249        }
1250        Some((idx, node))
1251    }
1252}
1253
1254/// Walk from a node up through its ancestors to the root.
1255pub struct AncestorsIter<'a> {
1256    tree: &'a ScopeTree,
1257    cursor: Option<ScopeNodeIdx>,
1258}
1259
1260impl<'a> Iterator for AncestorsIter<'a> {
1261    type Item = (ScopeNodeIdx, &'a ScopeNode);
1262    fn next(&mut self) -> Option<Self::Item> {
1263        let idx = self.cursor?;
1264        let node = &self.tree.nodes[idx];
1265        self.cursor = node.parent;
1266        Some((idx, node))
1267    }
1268}
1269
1270/// One-line display label for a scenario-level `bindings:` scope.
1271///
1272/// Summarizes the names the scope DEFINES (`x := …`, `shared y := …`,
1273/// `extern z: T = …`, `input w: T`) instead of echoing raw source —
1274/// the first source line is often a comment, which read as an
1275/// unnatural, repeating emission in the scenario-tree readout.
1276/// Comment-only / empty sources degrade to a bare `bindings:`.
1277pub fn bindings_label(source: &str) -> String {
1278    let mut names: Vec<&str> = Vec::new();
1279    for line in source.lines() {
1280        let t = line.trim();
1281        if t.is_empty() || t.starts_with('#') {
1282            continue;
1283        }
1284        let t = t
1285            .strip_prefix("shared ")
1286            .or_else(|| t.strip_prefix("volatile "))
1287            .or_else(|| t.strip_prefix("const "))
1288            .or_else(|| t.strip_prefix("final "))
1289            .unwrap_or(t);
1290        let t = t
1291            .strip_prefix("extern ")
1292            .or_else(|| t.strip_prefix("input "))
1293            .unwrap_or(t);
1294        let ident_end = t
1295            .find(|c: char| !(c.is_alphanumeric() || c == '_'))
1296            .unwrap_or(t.len());
1297        if ident_end == 0 {
1298            continue;
1299        }
1300        let rest = t[ident_end..].trim_start();
1301        if rest.starts_with(":=") || rest.starts_with(':') {
1302            let name = &t[..ident_end];
1303            if !names.contains(&name) {
1304                names.push(name);
1305            }
1306        }
1307    }
1308    match names.len() {
1309        0 => "bindings:".to_string(),
1310        1..=4 => format!("bindings: {}", names.join(", ")),
1311        n => format!("bindings: {} (+{} more)", names[..4].join(", "), n - 4),
1312    }
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317    use super::*;
1318
1319    fn phase(name: &str) -> ScenarioNode {
1320        ScenarioNode::Phase(name.into())
1321    }
1322    fn for_each(spec: &str, children: Vec<ScenarioNode>) -> ScenarioNode {
1323        use polydat::iteration::comprehension::spec::{ComprehensionSpec, ForSpec};
1324        let comprehension = ComprehensionSpec {
1325            r#for: ForSpec::Inline(spec.to_string()),
1326            r#where: None,
1327            order: None,
1328        }
1329        .into_algebra()
1330        .unwrap();
1331        ScenarioNode::Comprehension {
1332            comprehension,
1333            children,
1334            continue_if: None,
1335            anchor: None,
1336        }
1337    }
1338
1339    #[test]
1340    fn workload_and_scenario_always_present() {
1341        let tree = ScopeTree::build("default", &[]);
1342        // Even with no children, session + workload + scenario layers
1343        // survive so observer code doesn't special-case empty scenarios.
1344        assert_eq!(tree.nodes.len(), 3);
1345        assert!(matches!(tree.nodes[0].kind, ScopeKind::Session));
1346        assert!(matches!(tree.nodes[1].kind, ScopeKind::Workload));
1347        assert!(matches!(&tree.nodes[2].kind, ScopeKind::Scenario { name } if name == "default"));
1348        assert_eq!(tree.nodes[1].depth, 1);
1349        assert_eq!(tree.nodes[2].depth, 2);
1350    }
1351
1352    #[test]
1353    fn flat_phases_under_scenario() {
1354        let tree = ScopeTree::build("default", &[phase("setup"), phase("run")]);
1355        assert_eq!(tree.nodes.len(), 5);
1356        let scenario = &tree.nodes[2];
1357        assert_eq!(scenario.children.len(), 2);
1358        for &c in &scenario.children {
1359            assert!(matches!(tree.nodes[c].kind, ScopeKind::Phase { .. }));
1360            assert_eq!(tree.nodes[c].depth, 3);
1361            assert_eq!(tree.nodes[c].parent, Some(2));
1362        }
1363    }
1364
1365    #[test]
1366    fn nested_for_each_preserves_depth() {
1367        // for_each x in xs { for_each y in ys { phase P } }
1368        let tree = ScopeTree::build(
1369            "default",
1370            &[for_each(
1371                "x in xs",
1372                vec![for_each("y in ys", vec![phase("P")])],
1373            )],
1374        );
1375        // session(0) → workload(1) → scenario(2) → for_each_x(3) → for_each_y(4) → phase_P(5)
1376        assert_eq!(tree.nodes.len(), 6);
1377        assert_eq!(tree.nodes[3].depth, 3);
1378        assert_eq!(tree.nodes[4].depth, 4);
1379        assert_eq!(tree.nodes[5].depth, 5);
1380        assert!(matches!(
1381            &tree.nodes[3].kind,
1382            ScopeKind::Comprehension { comprehension }
1383                if comprehension.coordinate_names() == vec!["x"]
1384        ));
1385        assert!(matches!(
1386            &tree.nodes[4].kind,
1387            ScopeKind::Comprehension { comprehension }
1388                if comprehension.coordinate_names() == vec!["y"]
1389        ));
1390    }
1391
1392    #[test]
1393    fn dfs_pre_order_matches_authored_order() {
1394        let tree = ScopeTree::build(
1395            "default",
1396            &[
1397                for_each("x in xs", vec![phase("a"), phase("b")]),
1398                phase("c"),
1399            ],
1400        );
1401        let names: Vec<String> = tree.iter_dfs().map(|(_, n)| n.kind.label()).collect();
1402        assert_eq!(
1403            names,
1404            vec![
1405                "session".to_string(),
1406                "workload".into(),
1407                "scenario 'default'".into(),
1408                "each x".into(),
1409                "phase 'a'".into(),
1410                "phase 'b'".into(),
1411                "phase 'c'".into(),
1412            ]
1413        );
1414    }
1415
1416    #[test]
1417    fn ancestors_walk_to_root() {
1418        let tree = ScopeTree::build("default", &[for_each("x in xs", vec![phase("a")])]);
1419        let phase_idx = tree.phase_leaves()[0];
1420        let ancestors: Vec<String> = tree
1421            .ancestors(phase_idx)
1422            .map(|(_, n)| n.kind.label())
1423            .collect();
1424        assert_eq!(
1425            ancestors,
1426            vec![
1427                "phase 'a'".to_string(),
1428                "each x".into(),
1429                "scenario 'default'".into(),
1430                "workload".into(),
1431                "session".into(),
1432            ]
1433        );
1434    }
1435
1436    #[test]
1437    fn phase_leaves_returns_only_phases() {
1438        let tree = ScopeTree::build(
1439            "default",
1440            &[
1441                for_each("x in xs", vec![phase("a"), phase("b")]),
1442                phase("c"),
1443            ],
1444        );
1445        let leaves = tree.phase_leaves();
1446        assert_eq!(leaves.len(), 3);
1447        for idx in leaves {
1448            assert!(matches!(tree.nodes[idx].kind, ScopeKind::Phase { .. }));
1449        }
1450    }
1451
1452    fn make_phase_with_source(src: &str) -> nmbrs_workload::model::WorkloadPhase {
1453        use nmbrs_workload::model::{BindingsDef, ParsedOp, WorkloadPhase};
1454        let mut op = ParsedOp::simple("op", "noop");
1455        op.bindings = BindingsDef::PolydatSource(src.into());
1456        WorkloadPhase {
1457            key_metrics: Vec::new(),
1458            cycles: None,
1459            concurrency: None,
1460            rate: None,
1461            adapter: None,
1462            errors: None,
1463            tags: None,
1464            ops: vec![op],
1465            for_each: None,
1466            ..Default::default()
1467        }
1468    }
1469
1470    #[test]
1471    fn populate_pragmas_propagates_through_chain() {
1472        // Phase has `pragma strict_values` in its source. After
1473        // populate_pragmas + attach, an inner for_each scope (no
1474        // own pragmas) should still resolve `strict_values()` true
1475        // through its parent chain back to… wait. Phase is the
1476        // *leaf*, not the parent. The propagation we care about is
1477        // "phase's pragmas propagate up", but the chain is parent
1478        // → child. Let's flip: put the pragma in a phase, and the
1479        // assertion is "the phase scope sees its own pragmas." A
1480        // future test will demonstrate cross-scope propagation
1481        // once non-phase scopes can declare pragmas.
1482        let phases = std::collections::HashMap::from([(
1483            "p".to_string(),
1484            make_phase_with_source("pragma strict_values\n id := cycle\n"),
1485        )]);
1486        let mut tree = ScopeTree::build("default", &[phase("p")]);
1487        tree.populate_pragmas(&phases);
1488        let phase_idx = tree.phase_leaves()[0];
1489        assert!(tree.nodes[phase_idx].pragmas.strict_values());
1490    }
1491
1492    #[test]
1493    fn populate_pragmas_chain_walk_through_attach() {
1494        // Build a small tree where the phase, nested in a for_each,
1495        // declares strict and verify the nested set resolves it.
1496        let phases = std::collections::HashMap::from([(
1497            "p".to_string(),
1498            make_phase_with_source("pragma strict\n id := cycle\n"),
1499        )]);
1500        let mut tree = ScopeTree::build("default", &[for_each("x in xs", vec![phase("p")])]);
1501        tree.populate_pragmas(&phases);
1502        let phase_idx = tree.phase_leaves()[0];
1503        // Phase declares strict (alias for both). Confirm:
1504        assert!(tree.nodes[phase_idx].pragmas.strict_types());
1505        assert!(tree.nodes[phase_idx].pragmas.strict_values());
1506    }
1507
1508    // ---- M3.1: kernel install primitive ----
1509
1510    /// Compile a tiny Polydat source into a kernel for use as a
1511    /// scope's canonical instance. A one-line `name := <const>`
1512    /// suffices to populate `output_map` so `get_constant`
1513    /// returns the folded value.
1514    fn compile_kernel(source: &str) -> std::sync::Arc<crate::scope_kernel::ScopeKernel> {
1515        let kernel = crate::bindings::compile_scope_kernel(source, &Default::default())
1516            .expect("test source should compile");
1517        std::sync::Arc::new(kernel)
1518    }
1519
1520    #[test]
1521    fn install_kernel_seeds_canonical_state() {
1522        // After install, the cached kernel answers the name via
1523        // the standard Polydat API. No tree-walking on the caller
1524        // side — the kernel encapsulates its own scope, and
1525        // composition (auto-extern + materialize_wiring_from_outer) is what
1526        // makes parent values reachable. This test only verifies
1527        // the install primitive; the Polydat side already has its own
1528        // tests for composition.
1529        let tree = ScopeTree::build("default", &[phase("p")]);
1530        let workload_kernel = compile_kernel("const dataset := \"example\"\n");
1531        assert!(tree.install_kernel(0, workload_kernel));
1532
1533        let cached = tree.nodes[0]
1534            .cached_kernel
1535            .get()
1536            .expect("install populated the slot");
1537        match cached.lookup("dataset") {
1538            Some(polydat::ast::Value::Str(s)) => assert_eq!(&*s, "example"),
1539            other => panic!("expected Str(\"example\"), got {other:?}"),
1540        }
1541    }
1542
1543    #[test]
1544    fn for_each_scope_kernel_inherits_parent_via_materialize_wiring_from_outer() {
1545        // M3.2 end-to-end: build a parent kernel that exposes a
1546        // workload-style param as an output, synthesize a
1547        // for_each scope kernel that references that param plus
1548        // its own iter var, bind from parent, then verify both
1549        // values are reachable on the synthesized kernel via
1550        // standard Polydat API. Validates the chain inheritance
1551        // path without any caller-side scope walking.
1552        use std::sync::Arc;
1553
1554        // Parent: a workload-shaped kernel exposing `k_values`.
1555        let parent_src = "const k_values := \"1, 10\"\n";
1556        let parent = Arc::new(crate::scope_kernel::ScopeKernel::compile(parent_src).unwrap());
1557
1558        // Build the for_each scope kernel as the runner would.
1559        let parent_manifest = crate::runner::extract_manifest(parent.program());
1560        let kernel = crate::scope_synth::build_for_each_scope_kernel(
1561            &[("k".to_string(), "{k_values}".to_string())],
1562            &parent_manifest,
1563            &parent,
1564            &std::collections::HashMap::new(),
1565            Vec::new(),
1566            None,
1567            false,
1568            "test",
1569            None,
1570        )
1571        .expect("synthesis should succeed");
1572
1573        // After `materialize_wiring_from_outer` (called inside the helper),
1574        // the inherited extern is populated with the parent's
1575        // value.
1576        match kernel.lookup("k_values") {
1577            Some(polydat::ast::Value::Str(s)) => assert_eq!(&*s, "1, 10"),
1578            other => panic!("expected Str(\"1, 10\"), got {other:?}"),
1579        }
1580
1581        // The iter var `k` is also visible as an extern; not
1582        // yet set by the runtime, so its current value is the
1583        // default for String externs.
1584        // (Runtime semantics test belongs in executor.rs once
1585        // M3.4 wires this up; M3.2 only verifies the install +
1586        // chain mechanics.)
1587        assert!(
1588            kernel.program().find_input("k").is_some(),
1589            "iter var should be declared as an extern input"
1590        );
1591
1592        // Polydat's `extern` declaration auto-installs a passthrough
1593        // node that exposes the name as an output too — so
1594        // children's `materialize_wiring_from_outer(this_scope)` sees both
1595        // `k_values` and `k` in this scope's manifest and the
1596        // chain inheritance flows through standard Polydat API
1597        // without any caller-side scope walking.
1598        let manifest = crate::runner::extract_manifest(kernel.program());
1599        let output_names: std::collections::HashSet<_> =
1600            manifest.iter().map(|e| e.name.as_str()).collect();
1601        assert!(
1602            output_names.contains("k_values"),
1603            "inherited name appears as output via extern's auto-passthrough"
1604        );
1605        assert!(
1606            output_names.contains("k"),
1607            "iter var appears as output via extern's auto-passthrough"
1608        );
1609    }
1610
1611    #[test]
1612    fn for_each_scope_kernel_uses_native_type_for_numeric_iter_var() {
1613        // Single-clause for_each over a numeric workload param.
1614        // Pre-eval at synthesis detects U64 from "1, 10" and
1615        // declares `extern k: u64` instead of `extern k: str`.
1616        // Per SRD-18b "native types as the general rule".
1617        use std::sync::Arc;
1618
1619        let parent_src = "const k_values := \"1, 10\"\n";
1620        let parent = Arc::new(crate::scope_kernel::ScopeKernel::compile(parent_src).unwrap());
1621        let parent_manifest = crate::runner::extract_manifest(parent.program());
1622
1623        let kernel = crate::scope_synth::build_for_each_scope_kernel(
1624            &[("k".to_string(), "{k_values}".to_string())],
1625            &parent_manifest,
1626            &parent,
1627            &std::collections::HashMap::new(),
1628            Vec::new(),
1629            None,
1630            false,
1631            "test",
1632            None,
1633        )
1634        .expect("synthesis should succeed");
1635
1636        // Assert k's input port is u64-typed, not String.
1637        let manifest = crate::runner::extract_manifest(kernel.program());
1638        let k_entry = manifest
1639            .iter()
1640            .find(|e| e.name == "k")
1641            .expect("k must appear in manifest");
1642        assert_eq!(
1643            k_entry.port_type,
1644            polydat::ast::PortType::U64,
1645            "iter var over numeric values should be typed u64, not String"
1646        );
1647    }
1648
1649    #[test]
1650    fn for_each_scope_kernel_recursive_probe_for_dependent_clause() {
1651        // Multi-clause dependent: clause 2's spec text references
1652        // clause 1's iter var via `{k}`. Pre-eval probes clause 1
1653        // (k_values = "1, 10" → first value 1, type U64). Then
1654        // for clause 2's spec `{k_{k}_limits}`, the probe
1655        // substitutes {k}→1, leaving `{k_1_limits}`, which
1656        // resolves to "1, 2, 4, 8" via parent's manifest. First
1657        // value is 1, type U64.
1658        use std::sync::Arc;
1659
1660        let parent_src = concat!(
1661            "const k_values := \"1, 10\"\n",
1662            "const k_1_limits := \"1, 2, 4, 8\"\n",
1663            "const k_10_limits := \"10, 20, 30\"\n",
1664        );
1665        let parent = Arc::new(crate::scope_kernel::ScopeKernel::compile(parent_src).unwrap());
1666        let parent_manifest = crate::runner::extract_manifest(parent.program());
1667
1668        let kernel = crate::scope_synth::build_for_each_scope_kernel(
1669            &[
1670                ("k".to_string(), "{k_values}".to_string()),
1671                ("limit".to_string(), "{k_{k}_limits}".to_string()),
1672            ],
1673            &parent_manifest,
1674            &parent,
1675            &std::collections::HashMap::new(),
1676            Vec::new(),
1677            None,
1678            false,
1679            "test",
1680            None,
1681        )
1682        .expect("synthesis should succeed");
1683
1684        let manifest = crate::runner::extract_manifest(kernel.program());
1685        let k_entry = manifest.iter().find(|e| e.name == "k").unwrap();
1686        let limit_entry = manifest.iter().find(|e| e.name == "limit").unwrap();
1687        assert_eq!(
1688            k_entry.port_type,
1689            polydat::ast::PortType::U64,
1690            "k typed u64 from k_values pre-eval"
1691        );
1692        assert_eq!(
1693            limit_entry.port_type,
1694            polydat::ast::PortType::U64,
1695            "limit typed u64 via recursive probe k=1 → k_1_limits → \"1, 2, 4, 8\""
1696        );
1697    }
1698
1699    // ── SRD-13d Phase 4 + 5: scope elision marks ──
1700
1701    #[test]
1702    fn mark_scope_elision_assigns_logical_names() {
1703        let mut tree = ScopeTree::build("default", &[phase("p")]);
1704        // All-materialise predicate so every node gets a name.
1705        tree.mark_scope_elision(|_kind, _idx| true);
1706        // Session root contributes no path segment (SRD-88).
1707        assert_eq!(tree.nodes[0].logical_name, "");
1708        assert_eq!(tree.nodes[0].materialised, Some(true));
1709        // Workload child owns the "workload" segment.
1710        let workload_idx = tree.nodes[0].children[0];
1711        assert_eq!(tree.nodes[workload_idx].logical_name, "workload");
1712        // Scenario is named after its scenario tag.
1713        let scenario_idx = tree.nodes[workload_idx].children[0];
1714        assert_eq!(
1715            tree.nodes[scenario_idx].logical_name,
1716            "workload.scenario.default"
1717        );
1718        // Phase descends from scenario.
1719        let phase_idx = tree.nodes[scenario_idx].children[0];
1720        assert_eq!(
1721            tree.nodes[phase_idx].logical_name,
1722            "workload.scenario.default.phase.p"
1723        );
1724    }
1725
1726    #[test]
1727    fn mark_scope_elision_records_predicate_decisions() {
1728        let mut tree = ScopeTree::build("default", &[phase("p")]);
1729        // Predicate: only Phase scopes materialise.
1730        tree.mark_scope_elision(|kind, _idx| matches!(kind, ScopeKind::Phase { .. }));
1731        let workload_idx = tree.nodes[0].children[0];
1732        let scenario_idx = tree.nodes[workload_idx].children[0];
1733        let phase_idx = tree.nodes[scenario_idx].children[0];
1734        assert_eq!(tree.nodes[scenario_idx].materialised, Some(false));
1735        assert_eq!(tree.nodes[phase_idx].materialised, Some(true));
1736    }
1737
1738    #[test]
1739    fn nearest_materialised_walks_past_elided_layers() {
1740        let mut tree = ScopeTree::build("default", &[phase("p")]);
1741        // Predicate: only the workload tier materialises.
1742        tree.mark_scope_elision(|kind, _idx| matches!(kind, ScopeKind::Workload));
1743        let workload_idx = tree.nodes[0].children[0];
1744        let scenario_idx = tree.nodes[workload_idx].children[0];
1745        let phase_idx = tree.nodes[scenario_idx].children[0];
1746        // Phase's nearest materialised ancestor is the workload node.
1747        assert_eq!(tree.nearest_materialised(phase_idx), Some(workload_idx));
1748        assert_eq!(tree.nearest_materialised(scenario_idx), Some(workload_idx));
1749        // The session root always self-materialises.
1750        assert_eq!(tree.nearest_materialised(0), Some(0));
1751    }
1752
1753    #[test]
1754    fn nearest_materialised_returns_self_when_node_materialises() {
1755        let mut tree = ScopeTree::build("default", &[phase("p")]);
1756        tree.mark_scope_elision(|_kind, _idx| true);
1757        let phase_idx = tree.nodes[tree.nodes[0].children[0]].children[0];
1758        assert_eq!(tree.nearest_materialised(phase_idx), Some(phase_idx));
1759    }
1760
1761    #[test]
1762    fn nearest_materialised_none_before_pre_walk() {
1763        // Pre-walk hasn't run — every node's `materialised` is
1764        // None — so the walker can't terminate. Returns None.
1765        let tree = ScopeTree::build("default", &[phase("p")]);
1766        assert_eq!(tree.nearest_materialised(0), None);
1767    }
1768
1769    #[test]
1770    fn workload_root_always_materialises_regardless_of_predicate() {
1771        // Even an "always elide" predicate can't elide the
1772        // root — SRD-13d §5.1 mandates the root is the
1773        // termination point of nearest_materialised walks.
1774        let mut tree = ScopeTree::build("default", &[phase("p")]);
1775        tree.mark_scope_elision(|_kind, _idx| false);
1776        assert_eq!(tree.nodes[0].materialised, Some(true));
1777    }
1778
1779    // ── SRD-13d Phase 6: op-template tier ──
1780
1781    #[test]
1782    fn extend_with_op_templates_adds_one_child_per_op() {
1783        use nmbrs_workload::model::{BindingsDef, ParsedOp, WorkloadPhase};
1784        use std::collections::HashMap;
1785        let mut tree = ScopeTree::build("default", &[phase("p")]);
1786        let mut phases = HashMap::new();
1787        phases.insert(
1788            "p".into(),
1789            WorkloadPhase {
1790                key_metrics: Vec::new(),
1791                dimensions: Default::default(),
1792                cycles: None,
1793                concurrency: None,
1794                rate: None,
1795                daemon: false,
1796                adapter: None,
1797                errors: None,
1798                tries: None,
1799                tries_backoff: None,
1800                interval: None,
1801                repeat: None,
1802                error_rate_max: None,
1803                timeout: None,
1804                stop_when: Vec::new(),
1805                throttle: None,
1806                tags: None,
1807                ops: vec![
1808                    ParsedOp::simple("alpha", "noop"),
1809                    ParsedOp::simple("beta", "noop"),
1810                ],
1811                for_each: None,
1812                continue_if: None,
1813                loop_scope: None,
1814                iter_scope: None,
1815                checkpoint: None,
1816                status_metrics: vec![],
1817                metrics: Default::default(),
1818                poll: None,
1819                bindings: BindingsDef::default(),
1820                optimize: None,
1821            },
1822        );
1823        tree.extend_with_op_templates(&phases);
1824        let workload_idx = tree.nodes[0].children[0];
1825        let scenario_idx = tree.nodes[workload_idx].children[0];
1826        let phase_idx = tree.nodes[scenario_idx].children[0];
1827        // Phase now has 2 op-template children.
1828        assert_eq!(tree.nodes[phase_idx].children.len(), 2);
1829        let op_a_idx = tree.nodes[phase_idx].children[0];
1830        let op_b_idx = tree.nodes[phase_idx].children[1];
1831        assert!(matches!(&tree.nodes[op_a_idx].kind,
1832            ScopeKind::OpTemplate { name } if name == "alpha"));
1833        assert!(matches!(&tree.nodes[op_b_idx].kind,
1834            ScopeKind::OpTemplate { name } if name == "beta"));
1835        // Depth = phase depth + 1.
1836        assert_eq!(tree.nodes[op_a_idx].depth, tree.nodes[phase_idx].depth + 1);
1837    }
1838
1839    #[test]
1840    fn extend_with_op_templates_is_idempotent() {
1841        use nmbrs_workload::model::{BindingsDef, ParsedOp, WorkloadPhase};
1842        use std::collections::HashMap;
1843        let mut tree = ScopeTree::build("default", &[phase("p")]);
1844        let mut phases = HashMap::new();
1845        phases.insert(
1846            "p".into(),
1847            WorkloadPhase {
1848                key_metrics: Vec::new(),
1849                dimensions: Default::default(),
1850                cycles: None,
1851                concurrency: None,
1852                rate: None,
1853                daemon: false,
1854                adapter: None,
1855                errors: None,
1856                tries: None,
1857                tries_backoff: None,
1858                interval: None,
1859                repeat: None,
1860                error_rate_max: None,
1861                timeout: None,
1862                stop_when: Vec::new(),
1863                throttle: None,
1864                tags: None,
1865                ops: vec![ParsedOp::simple("only", "noop")],
1866                for_each: None,
1867                continue_if: None,
1868                loop_scope: None,
1869                iter_scope: None,
1870                checkpoint: None,
1871                status_metrics: vec![],
1872                metrics: Default::default(),
1873                poll: None,
1874                bindings: BindingsDef::default(),
1875                optimize: None,
1876            },
1877        );
1878        tree.extend_with_op_templates(&phases);
1879        let n_after_first = tree.nodes.len();
1880        tree.extend_with_op_templates(&phases); // Second call.
1881        assert_eq!(
1882            tree.nodes.len(),
1883            n_after_first,
1884            "second call should not add nodes"
1885        );
1886    }
1887
1888    #[test]
1889    fn op_template_logical_name_uses_op_segment() {
1890        use nmbrs_workload::model::{BindingsDef, ParsedOp, WorkloadPhase};
1891        use std::collections::HashMap;
1892        let mut tree = ScopeTree::build("default", &[phase("p")]);
1893        let mut phases = HashMap::new();
1894        phases.insert(
1895            "p".into(),
1896            WorkloadPhase {
1897                key_metrics: Vec::new(),
1898                dimensions: Default::default(),
1899                cycles: None,
1900                concurrency: None,
1901                rate: None,
1902                daemon: false,
1903                adapter: None,
1904                errors: None,
1905                tries: None,
1906                tries_backoff: None,
1907                interval: None,
1908                repeat: None,
1909                error_rate_max: None,
1910                timeout: None,
1911                stop_when: Vec::new(),
1912                throttle: None,
1913                tags: None,
1914                ops: vec![ParsedOp::simple("foo", "noop")],
1915                for_each: None,
1916                continue_if: None,
1917                loop_scope: None,
1918                iter_scope: None,
1919                checkpoint: None,
1920                status_metrics: vec![],
1921                metrics: Default::default(),
1922                poll: None,
1923                bindings: BindingsDef::default(),
1924                optimize: None,
1925            },
1926        );
1927        tree.extend_with_op_templates(&phases);
1928        tree.mark_scope_elision(|_kind, _idx| true);
1929        // Find the op node and check its logical name.
1930        let op_idx = tree
1931            .iter_dfs()
1932            .find(|(_, n)| matches!(&n.kind, ScopeKind::OpTemplate { name } if name == "foo"))
1933            .map(|(i, _)| i)
1934            .expect("op-template node");
1935        assert_eq!(
1936            tree.nodes[op_idx].logical_name,
1937            "workload.scenario.default.phase.p.op.foo"
1938        );
1939    }
1940
1941    #[test]
1942    fn install_is_idempotent_via_oncelock() {
1943        // OnceLock semantics: first install wins; subsequent
1944        // installs silently no-op. The boolean return lets
1945        // callers detect duplicate installs (likely a logic bug
1946        // in the runner) without panicking.
1947        let tree = ScopeTree::build("default", &[phase("p")]);
1948        let k1 = compile_kernel("const x := 1\n");
1949        let k2 = compile_kernel("const x := 2\n");
1950        assert!(tree.install_kernel(0, k1), "first install succeeds");
1951        assert!(!tree.install_kernel(0, k2), "second install no-ops");
1952
1953        let cached = tree.nodes[0].cached_kernel.get().unwrap();
1954        match cached.lookup("x") {
1955            Some(polydat::ast::Value::U64(n)) => assert_eq!(n, 1),
1956            other => panic!("expected U64(1), got {other:?}"),
1957        }
1958    }
1959
1960    /// **WORKAROUND-PINNING TEST — retire when AST becomes
1961    /// self-identifying** (task #19).
1962    ///
1963    /// Today's lookup key (raw Comprehension AST) is LOSSY:
1964    /// two scope-tree positions produce semantically-distinct
1965    /// installed kernels (different cascaded externs from
1966    /// different parent chains) but can share AST. The
1967    /// `_under(parent_idx, ...)` lookup adds the missing
1968    /// context — parent-subtree restriction — at the call
1969    /// site to disambiguate. This test pins that behavior in
1970    /// place.
1971    ///
1972    /// When the AST becomes self-identifying (so two
1973    /// distinct kernels never share matter), `find_comprehension_scope`
1974    /// is correct again, `find_comprehension_scope_under` can
1975    /// be retired, and this test should be deleted along with
1976    /// it.
1977    ///
1978    /// Workload shape modeled here:
1979    ///
1980    /// ```text
1981    /// for_each "a in [1]" {       // outer A
1982    ///   for_each "x in xs" { P }  // x-comprehension #1, under A
1983    /// }
1984    /// for_each "b in [2]" {       // outer B
1985    ///   for_each "x in xs" { P }  // x-comprehension #2, under B
1986    /// }
1987    /// ```
1988    ///
1989    /// Both `for_each "x in xs"` blocks have IDENTICAL AST.
1990    /// Under the lossy-AST model, `find_comprehension_scope_under(B_idx,
1991    /// x_comp)` MUST return #2's idx, not #1's, because the
1992    /// installed kernels at #1 and #2 differ in their cascade
1993    /// even though the AST does not. When AST becomes
1994    /// self-identifying the two `for_each "x in xs"` blocks
1995    /// will no longer share AST — they will carry distinct
1996    /// context — and the global lookup will work.
1997    #[test]
1998    fn find_comprehension_scope_under_disambiguates_identical_ast() {
1999        let tree = ScopeTree::build(
2000            "default",
2001            &[
2002                for_each("a in [1]", vec![for_each("x in xs", vec![phase("P")])]),
2003                for_each("b in [2]", vec![for_each("x in xs", vec![phase("P")])]),
2004            ],
2005        );
2006        // Tree layout (DFS):
2007        //   0 session
2008        //   1 workload
2009        //   2 scenario
2010        //   3 for_each(a)
2011        //   4   for_each(x) #1
2012        //   5     phase(P)
2013        //   6 for_each(b)
2014        //   7   for_each(x) #2
2015        //   8     phase(P)
2016        //
2017        // Build the x-comprehension AST that both inner scopes
2018        // share, then verify the path-aware lookup picks the
2019        // right one from each side.
2020        let x_comp = polydat::iteration::comprehension::spec::ComprehensionSpec {
2021            r#for: polydat::iteration::comprehension::spec::ForSpec::Inline("x in xs".to_string()),
2022            r#where: None,
2023            order: None,
2024        }
2025        .into_algebra()
2026        .unwrap();
2027
2028        // Sanity: the legacy global lookup picks #1 (first DFS
2029        // match) for both — this is the buggy behavior.
2030        assert_eq!(
2031            tree.find_comprehension_scope(&x_comp),
2032            Some(4),
2033            "legacy lookup returns FIRST match — documented bug"
2034        );
2035
2036        // The fix: searching under the A outer (idx 3) returns
2037        // #1 (idx 4); searching under the B outer (idx 6)
2038        // returns #2 (idx 7). The same x AST resolves to
2039        // different scope idx based on the parent context.
2040        assert_eq!(
2041            tree.find_comprehension_scope_under(3, &x_comp),
2042            Some(4),
2043            "under A outer, x-comprehension is the descendant at idx 4"
2044        );
2045        assert_eq!(
2046            tree.find_comprehension_scope_under(6, &x_comp),
2047            Some(7),
2048            "under B outer, x-comprehension is the descendant at idx 7"
2049        );
2050
2051        // Cross-search: looking for x under the OTHER side's
2052        // sub-tree should return None (the comprehension isn't
2053        // a descendant).
2054        assert_eq!(
2055            tree.find_comprehension_scope_under(4, &x_comp),
2056            None,
2057            "x-comp is not a descendant of itself"
2058        );
2059    }
2060
2061    /// **WORKAROUND-PINNING TEST — retire when AST becomes
2062    /// self-identifying** (task #19). See
2063    /// [`find_comprehension_scope_under_disambiguates_identical_ast`]
2064    /// for the architectural framing. Same shape applied to
2065    /// `Bindings` nodes whose source text matches at different
2066    /// scope-tree positions.
2067    #[test]
2068    fn find_bindings_scope_under_disambiguates_identical_source() {
2069        let bindings_source = "const k := 1\n".to_string();
2070        let bindings_node = || ScenarioNode::Bindings {
2071            source: bindings_source.clone(),
2072            children: vec![phase("P")],
2073        };
2074        let tree = ScopeTree::build(
2075            "default",
2076            &[
2077                for_each("a in [1]", vec![bindings_node()]),
2078                for_each("b in [2]", vec![bindings_node()]),
2079            ],
2080        );
2081        // Layout:
2082        //   0 session
2083        //   1 workload
2084        //   2 scenario
2085        //   3 for_each(a)
2086        //   4   bindings #1
2087        //   5     phase(P)
2088        //   6 for_each(b)
2089        //   7   bindings #2
2090        //   8     phase(P)
2091
2092        // Legacy: FIRST match (bug).
2093        assert_eq!(tree.find_bindings_scope(&bindings_source), Some(4));
2094
2095        // Fix: scoped lookup picks the right descendant.
2096        assert_eq!(tree.find_bindings_scope_under(3, &bindings_source), Some(4));
2097        assert_eq!(tree.find_bindings_scope_under(6, &bindings_source), Some(7));
2098    }
2099}