Skip to main content

nmbrs_runtime/
scope.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Typed binding scope model for Polydat Kernel compilation.
5//!
6//! A `BindingScope` is the structured intermediate representation
7//! that replaces raw string manipulation for scope composition.
8//! Every binding carries its provenance (`BindingOrigin`), its
9//! modifier, and its definition text. Scope rules are checked
10//! against this typed structure, and a single deduplicated GK
11//! source string is emitted at the end.
12
13use std::collections::{HashMap, HashSet};
14
15use crate::scope_synth::{
16    collect_leaf_placeholders, value_to_param_string, workload_param_port_type,
17};
18use nmbrs_workload::model::{BindingsDef, ParsedOp};
19use polydat::kernel::interp::collect_string_interp_refs;
20
21/// Where a binding was declared — its provenance in the scope chain.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum BindingOrigin {
24    /// Declared at a YAML level outside the op (today only block
25    /// sugar, since SRD-13f Push D retired the workload/phase
26    /// parser-merge into ops). Reaches the op via
27    /// `inline_block_sugar_into_op` during YAML parsing.
28    Inherited,
29    /// Declared at phase level (the phase has its own `bindings:` block).
30    Phase,
31    /// Declared at op level (op-specific augmentation).
32    Op(String),
33    /// Injected as a `for_each` iteration variable.
34    IterationVar,
35    /// Generated as an `extern` from the outer scope manifest.
36    AutoExtern,
37    /// Injected from workload param expansion.
38    ParamExpansion,
39    /// Generated from inline expression extraction (`{{expr}}`).
40    InlineExpr,
41}
42
43impl std::fmt::Display for BindingOrigin {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        match self {
46            Self::Inherited => write!(f, "inherited"),
47            Self::Phase => write!(f, "phase"),
48            Self::Op(name) => write!(f, "op '{name}'"),
49            Self::IterationVar => write!(f, "iteration variable"),
50            Self::AutoExtern => write!(f, "auto-extern"),
51            Self::ParamExpansion => write!(f, "param expansion"),
52            Self::InlineExpr => write!(f, "inline expression"),
53        }
54    }
55}
56
57/// The modifier on a binding declaration. Mirrors the
58/// `BindingModifier` flag set in polydat' Polydat AST plus
59/// the binding-kind keywords (`init`, `cursor`) that
60/// nmbrs-runtime's text-level scope assembly cares about.
61///
62/// Wire-coloring modifiers (`final`, `shared`, `volatile`)
63/// could in principle combine, but the scope assembly path
64/// historically only needs to know "is this final?" /
65/// "is this shared?" for shadow checks; combinations get
66/// reduced here to the most-distinctive single tag. The full
67/// flag set is preserved in the eventual Polydat AST when the
68/// scope-emitted source compiles.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum ScopeModifier {
71    None,
72    Init,
73    Shared,
74    Final,
75    Volatile,
76    Cursor,
77}
78
79/// A single binding declaration with provenance.
80#[derive(Debug, Clone)]
81pub struct ScopedBinding {
82    /// The binding name (LHS of `:=`).
83    pub name: String,
84    /// The full declaration line as Polydat source text.
85    /// For regular bindings: `"name := expr"`
86    /// For init: `"const name := \"value\""`
87    /// For externs: `"extern name: Type"`
88    pub line: String,
89    /// Where this binding came from.
90    pub origin: BindingOrigin,
91    /// Modifier on the declaration.
92    pub modifier: ScopeModifier,
93}
94
95/// A typed extern declaration.
96#[derive(Debug, Clone)]
97pub struct ExternDecl {
98    pub name: String,
99    pub type_name: String,
100}
101
102/// Typed scope for a phase's Polydat Kernel compilation.
103///
104/// Built by the executor from structured inputs, validated for
105/// scope rules, then emitted as a single Polydat source string.
106pub struct BindingScope {
107    /// The coordinate declaration (e.g., `"input cycle: u64"`).
108    coordinates: Option<String>,
109    /// All bindings in insertion order.
110    bindings: Vec<ScopedBinding>,
111    /// Extern declarations.
112    externs: Vec<ExternDecl>,
113    /// Names referenced by op templates (for DCE).
114    required_outputs: Vec<String>,
115    /// Extra required outputs from config expressions.
116    config_refs: Vec<String>,
117}
118
119impl Default for BindingScope {
120    fn default() -> Self {
121        Self::new()
122    }
123}
124
125impl BindingScope {
126    /// Create an empty scope.
127    pub fn new() -> Self {
128        Self {
129            coordinates: None,
130            bindings: Vec::new(),
131            externs: Vec::new(),
132            required_outputs: Vec::new(),
133            config_refs: Vec::new(),
134        }
135    }
136
137    /// Ingest bindings from a `BindingsDef::PolydatSource`, classifying each
138    /// line by the given origin. Extracts coordinates and handles all
139    /// Polydat declaration forms (init, shared, final, cursor, extern, plain).
140    ///
141    /// A "line" here is a *logical* line: physical newlines inside
142    /// unbalanced `()`/`[]`/`{}` or inside a string literal are
143    /// absorbed into the current binding. This is what lets multi-line
144    /// expressions like
145    ///
146    /// ```polydat
147    /// rate_adjust := control_set("rate",
148    ///                            to_f64(control_u64("rate")) * 1.05)
149    /// ```
150    ///
151    /// survive the later split-on-`\n` in [`Self::emit`]: we rejoin
152    /// them onto one physical line so the downstream parser sees a
153    /// complete expression.
154    pub fn ingest_polydat_source(&mut self, source: &str, origin: BindingOrigin) {
155        for line in logical_lines(source) {
156            let trimmed = line.trim();
157            if trimmed.is_empty() || trimmed.starts_with("//") || trimmed.starts_with('#') {
158                continue;
159            }
160
161            // `input` declarations: `input <name>[: <type>]` (bare) or
162            // `input (<name>[: <type>], ...)` (tuple). Stored verbatim
163            // on the scope's `coordinates` slot — the synthesizer
164            // re-emits this line into the per-scope Polydat source so the
165            // compiler can pick up the declared inputs.
166            if trimmed.starts_with("input ") {
167                self.coordinates = Some(trimmed.to_string());
168                continue;
169            }
170
171            // Cursor declarations use `=` not `:=`:
172            //   cursor row = range(0, vector_count("example"))
173            //   const prebuffer := dataset_prebuffer("example")
174            // These are Polydat statements that the compiler handles directly.
175            // Pass them through as bindings so they survive emission.
176            if (trimmed.starts_with("cursor ") || trimmed.starts_with("init "))
177                && let Some(eq_pos) = trimmed.find('=')
178            {
179                // Check it's `=` not `:=`
180                let before_eq = &trimmed[..eq_pos];
181                if !before_eq.ends_with(':') {
182                    // cursor/init with bare `=` — pass through as-is
183                    let lhs = before_eq.trim();
184                    let (modifier, name) = parse_modifier_and_name(lhs);
185                    self.bindings.push(ScopedBinding {
186                        name: name.to_string(),
187                        line: trimmed.to_string(),
188                        origin: origin.clone(),
189                        modifier,
190                    });
191                    continue;
192                }
193            }
194
195            if let Some(pos) = trimmed.find(":=") {
196                let lhs = trimmed[..pos].trim();
197
198                // Extern declarations
199                if lhs.starts_with("extern") {
200                    // Already handled via add_extern; skip inline externs
201                    // from inherited sources
202                    continue;
203                }
204
205                // Determine modifier and extract bare name
206                let (modifier, name) = parse_modifier_and_name(lhs);
207
208                self.bindings.push(ScopedBinding {
209                    name: name.to_string(),
210                    line: trimmed.to_string(),
211                    origin: origin.clone(),
212                    modifier,
213                });
214            } else if trimmed.starts_with("extern ") {
215                // `extern name: Type` (no `:=`)
216                if let Some(colon_pos) = trimmed.find(':') {
217                    let name = trimmed["extern ".len()..colon_pos].trim();
218                    let type_name = trimmed[colon_pos + 1..].trim();
219                    self.externs.push(ExternDecl {
220                        name: name.to_string(),
221                        type_name: type_name.to_string(),
222                    });
223                }
224            }
225            // Lines that don't match any pattern are silently skipped.
226            // Comments and blank lines are already filtered above.
227        }
228    }
229
230    /// Add an iteration variable from `for_each`.
231    ///
232    /// Iteration variables are declared as `extern` ports rather
233    /// than init-time bindings (SRD 18b §"Iteration variables as
234    /// scope outputs"). The runtime sets the extern's value
235    /// before the leaf kernel executes, so we no longer
236    /// text-substitute literal values into the Polydat source. The
237    /// type is inferred from the current iteration's value:
238    /// numeric strings get `u64`/`f64`, anything else is `str`.
239    pub fn add_iteration_var(&mut self, name: &str, value: &str) {
240        let port_type = if value.parse::<u64>().is_ok() {
241            polydat::ast::PortType::U64
242        } else if value.parse::<f64>().is_ok() {
243            polydat::ast::PortType::F64
244        } else {
245            polydat::ast::PortType::Str
246        };
247        self.add_extern(name, port_type);
248    }
249
250    /// Add an auto-extern declaration at `port_type`, written into
251    /// the scope's source as the type's keyword.
252    pub fn add_extern(&mut self, name: &str, port_type: polydat::ast::PortType) {
253        self.externs.push(ExternDecl {
254            name: name.to_string(),
255            type_name: port_type.to_keyword().to_string(),
256        });
257    }
258
259    /// Add a workload param binding as a `final` (compile-time
260    /// constant) binding so the compiler folds the literal value
261    /// and the assembler treats references as const args rather
262    /// than wire inputs. The `const` modifier matches the M3.6
263    /// contract: workload params are immutable for the run, so
264    /// downstream nodes consume them as constants.
265    ///
266    /// String values are emitted as quoted Polydat string literals
267    /// with embedded `"` and `\` escaped, so JSON-shaped param
268    /// values (`{"a": 1}`, `{'class': 'SimpleStrategy'}`,
269    /// arbitrary nested quotes) round-trip through GK
270    /// compilation unchanged. Numeric and boolean values are
271    /// emitted as bare literals.
272    pub fn add_param_binding(&mut self, name: &str, value: &str) {
273        // Param-binding emission used by scope synth when
274        // cascading workload-root values into descendant
275        // scopes. Values arrive already-typed (raw workload-
276        // param text OR `value_to_param_string` output from a
277        // parent kernel constant). Workload-root semantics
278        // apply: bare strings lower to polydat string literals
279        // (legacy), NOT references. The `set:` block parser
280        // in nmbrs-workload uses a DIFFERENT classifier that
281        // does treat bare identifiers as references — that's
282        // the entry point where the operator IS in a scope
283        // context with visible wires to reference.
284        let trimmed = value.trim();
285        // A bare numeric/bool literal, or an already-quoted polydat
286        // string / array literal, passes through verbatim; anything else
287        // is wrapped as a quoted polydat string. (Both pass-through cases
288        // yield the same text, so they share one arm.)
289        let literal = if trimmed.parse::<u64>().is_ok()
290            || trimmed.parse::<f64>().is_ok()
291            || trimmed == "true"
292            || trimmed == "false"
293            || is_polydat_quoted_string(trimmed)
294            || is_polydat_array_literal(trimmed)
295        {
296            trimmed.to_string()
297        } else {
298            let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
299            format!("\"{escaped}\"")
300        };
301        self.bindings.push(ScopedBinding {
302            name: name.to_string(),
303            line: format!("const {name} := {literal}"),
304            origin: BindingOrigin::ParamExpansion,
305            modifier: ScopeModifier::Final,
306        });
307    }
308
309    /// Add an inline expression binding.
310    pub fn add_inline_expr(&mut self, name: &str, expr: &str) {
311        self.bindings.push(ScopedBinding {
312            name: name.to_string(),
313            line: format!("{name} := {expr}"),
314            origin: BindingOrigin::InlineExpr,
315            modifier: ScopeModifier::None,
316        });
317    }
318
319    /// Register a name referenced by an op template (for DCE).
320    pub fn add_required_output(&mut self, name: &str) {
321        if !self.required_outputs.contains(&name.to_string()) {
322            self.required_outputs.push(name.to_string());
323        }
324    }
325
326    /// Register a config expression reference (for DCE).
327    pub fn add_config_ref(&mut self, name: &str) {
328        if !self.config_refs.contains(&name.to_string()) {
329            self.config_refs.push(name.to_string());
330        }
331    }
332
333    /// All names defined in this scope (all origins).
334    pub fn defined_names(&self) -> HashSet<String> {
335        self.bindings.iter().map(|b| b.name.clone()).collect()
336    }
337
338    /// All extern names in this scope.
339    pub fn extern_names(&self) -> HashSet<String> {
340        self.externs.iter().map(|e| e.name.clone()).collect()
341    }
342
343    /// The combined required outputs (template refs + config refs).
344    pub fn required_outputs(&self) -> Vec<String> {
345        let mut all = self.required_outputs.clone();
346        for name in &self.config_refs {
347            if !all.contains(name) {
348                all.push(name.clone());
349            }
350        }
351        all
352    }
353
354    /// Validate scope rules. Returns `Ok(())` if valid, or a
355    /// descriptive error explaining the violation and its provenance.
356    pub fn validate(&self) -> Result<(), String> {
357        // Build a map of name → first binding for each origin tier.
358        // The tier order determines precedence: earlier tiers own the name.
359        let mut owned: HashMap<String, &ScopedBinding> = HashMap::new();
360
361        for binding in &self.bindings {
362            if let Some(prior) = owned.get(&binding.name) {
363                // Same name appears twice. Check if this is allowed.
364                match (&prior.origin, &binding.origin) {
365                    // Inherited + Inherited: duplicate from multiple ops
366                    // sharing the same workload bindings. Allowed if
367                    // definitions are identical.
368                    (BindingOrigin::Inherited, BindingOrigin::Inherited) => {
369                        if prior.line != binding.line {
370                            return Err(format!(
371                                "binding '{}' has conflicting inherited definitions:\n  \
372                                 first:  {}\n  second: {}",
373                                binding.name, prior.line, binding.line
374                            ));
375                        }
376                        // Duplicate with same definition — will be deduplicated at emit
377                    }
378
379                    // Phase + Phase: same check as inherited
380                    (BindingOrigin::Phase, BindingOrigin::Phase) => {
381                        if prior.line != binding.line {
382                            return Err(format!(
383                                "binding '{}' has conflicting phase-level definitions:\n  \
384                                 first:  {}\n  second: {}",
385                                binding.name, prior.line, binding.line
386                            ));
387                        }
388                    }
389
390                    // Op overriding Inherited/Phase/IterationVar with a
391                    // DIFFERENT definition: real shadow, error.
392                    (
393                        BindingOrigin::Inherited
394                        | BindingOrigin::Phase
395                        | BindingOrigin::IterationVar,
396                        BindingOrigin::Op(op_name),
397                    ) => {
398                        if prior.line != binding.line {
399                            return Err(format!(
400                                "op '{}' binding '{}' shadows a name from {} origin \
401                                 with a different definition.\n  \
402                                 scope: {}\n  op:    {}\n\
403                                 Ops augment the scope DAG but cannot override it. \
404                                 Use a separate phase for different bindings.",
405                                op_name, binding.name, prior.origin, prior.line, binding.line
406                            ));
407                        }
408                        // Same definition from inheritance — dedup at emit
409                    }
410
411                    // Op redefining an op binding from a DIFFERENT op
412                    (BindingOrigin::Op(prior_op), BindingOrigin::Op(this_op)) => {
413                        if prior_op != this_op {
414                            return Err(format!(
415                                "op '{}' binding '{}' is already defined by op '{}'. \
416                                 Each ride-along binding name must be unique across \
417                                 all ops in the scope.",
418                                this_op, binding.name, prior_op
419                            ));
420                        }
421                        // Same op, same name — shouldn't happen, but tolerate if same def
422                    }
423
424                    // IterationVar replacing Inherited/Phase: iteration
425                    // variables are injected before inherited bindings
426                    // in the emission order, so Polydat sees them first.
427                    // This is intentional — for_each vars override params.
428                    (
429                        BindingOrigin::IterationVar,
430                        BindingOrigin::Inherited | BindingOrigin::Phase,
431                    )
432                    | (
433                        BindingOrigin::Inherited | BindingOrigin::Phase,
434                        BindingOrigin::IterationVar,
435                    ) => {
436                        // Allowed: iteration vars intentionally override inherited names
437                    }
438
439                    // ParamExpansion: these are only added when the name
440                    // is NOT already defined. The caller checks. But if
441                    // somehow a duplicate appears, same-def is fine.
442                    (_, BindingOrigin::ParamExpansion) | (BindingOrigin::ParamExpansion, _) => {
443                        // Param expansion is additive; caller skips existing names
444                    }
445
446                    // InlineExpr: synthetic names (__expr_N), shouldn't collide
447                    (_, BindingOrigin::InlineExpr) | (BindingOrigin::InlineExpr, _) => {
448                        // Synthetic names from inline expressions
449                    }
450
451                    // AutoExtern: these go to the extern list, not bindings.
452                    // Shouldn't appear here, but tolerate.
453                    (_, BindingOrigin::AutoExtern) | (BindingOrigin::AutoExtern, _) => {}
454
455                    // Inherited + Op(same def): already covered above.
456                    // Any other combination: flag it.
457                    _ => {
458                        if prior.line != binding.line {
459                            return Err(format!(
460                                "binding '{}' conflicts: {} origin ({}) vs {} origin ({})",
461                                binding.name,
462                                prior.origin,
463                                prior.line,
464                                binding.origin,
465                                binding.line
466                            ));
467                        }
468                    }
469                }
470            } else {
471                owned.insert(binding.name.clone(), binding);
472            }
473        }
474
475        // Check final shadowing: no binding can redefine a name that
476        // appears as Final in the extern list or prior bindings.
477        let final_names: HashSet<String> = self
478            .bindings
479            .iter()
480            .filter(|b| b.modifier == ScopeModifier::Final)
481            .map(|b| b.name.clone())
482            .collect();
483
484        for binding in &self.bindings {
485            if final_names.contains(&binding.name)
486                && binding.modifier != ScopeModifier::Final
487                && binding.origin != BindingOrigin::Inherited
488            {
489                return Err(format!(
490                    "cannot shadow 'final' binding '{}' from outer scope",
491                    binding.name
492                ));
493            }
494        }
495
496        Ok(())
497    }
498
499    /// Emit the validated scope as a single Polydat source string.
500    ///
501    /// Entries are ordered:
502    /// 1. Coordinates declaration
503    /// 2. Extern declarations
504    /// 3. Init declarations (iteration variables)
505    /// 4. Inherited/Phase bindings (deduplicated by name)
506    /// 5. ParamExpansion bindings
507    /// 6. InlineExpr bindings
508    /// 7. Op-level bindings (new names only)
509    ///
510    /// Each name is emitted exactly once. The first occurrence wins;
511    /// subsequent duplicates with the same definition are suppressed.
512    pub fn emit(&self) -> String {
513        let mut lines: Vec<String> = Vec::new();
514        let mut emitted_names: HashSet<String> = HashSet::new();
515
516        // 1. Coordinates — emit only when an ingested source
517        // declared them. The Polydat compiler auto-infers coordinates
518        // from `cycle` references in non-strict mode, so a
519        // workload-level scope built purely from injected
520        // workload params (no op-supplied Polydat source, no `cycle`
521        // references) compiles fine without a synthetic line.
522        if let Some(ref coords) = self.coordinates {
523            lines.push(coords.clone());
524            // Populate `emitted_names` from the declared coordinate
525            // names so the externs pass (and downstream binding
526            // emission) doesn't re-introduce a same-named declaration
527            // that would collide with the input slot. The coord line
528            // is the canonical `input` declaration in either
529            // surface form:
530            //   input <name>[: <type>]               (bare)
531            //   input (<name>[: <type>], ...)        (tuple)
532            scan_input_decl_names(coords.trim(), &mut emitted_names);
533        }
534
535        // 2. Externs
536        for ext in &self.externs {
537            if !emitted_names.contains(&ext.name) {
538                lines.push(format!("extern {}: {}", ext.name, ext.type_name));
539                emitted_names.insert(ext.name.clone());
540            }
541        }
542
543        // 3-7. Bindings in origin order
544        let origin_order: &[fn(&BindingOrigin) -> bool] = &[
545            |o| matches!(o, BindingOrigin::IterationVar),
546            |o| matches!(o, BindingOrigin::Inherited),
547            |o| matches!(o, BindingOrigin::Phase),
548            |o| matches!(o, BindingOrigin::ParamExpansion),
549            |o| matches!(o, BindingOrigin::InlineExpr),
550            |o| matches!(o, BindingOrigin::Op(_)),
551        ];
552
553        for predicate in origin_order {
554            for binding in &self.bindings {
555                if predicate(&binding.origin) && !emitted_names.contains(&binding.name) {
556                    lines.push(binding.line.clone());
557                    emitted_names.insert(binding.name.clone());
558                }
559            }
560        }
561
562        lines.join("\n")
563    }
564}
565
566/// Parse the modifier prefix and bare name from a Polydat LHS.
567///
568/// `"shared foo"` → `(Shared, "foo")`
569/// `"init bar"` → `(Init, "bar")`
570/// `"cursor baz"` → `(Cursor, "baz")`
571/// `"final qux"` → `(Final, "qux")`
572/// `"plain"` → `(None, "plain")`
573/// Split `source` into logical lines, treating newlines inside
574/// unbalanced `()`, `[]`, `{}` or string literals as continuations.
575///
576/// A logical line ends at the first physical newline that sits at
577/// bracket-depth 0 and outside any string. Each returned String has
578/// its interior newlines collapsed to single spaces so the downstream
579/// Polydat parser sees one-expression-per-line, which is all it supports.
580fn logical_lines(source: &str) -> Vec<String> {
581    // Polydat grammar uses ONLY `"`-delimited string literals (see
582    // `polydat/src/dsl/lexer.rs`). Apostrophes (`'`) carry
583    // no special meaning at the lexical level — they appear
584    // verbatim in comments ("the workload's bindings") and
585    // inside double-quoted strings, never as a string delimiter
586    // themselves. Treating `'` as a delimiter here would let a
587    // stray apostrophe in a comment swallow the entire rest of
588    // the source as a single unterminated "string" run, which
589    // then collapses every subsequent binding into one logical
590    // line that the per-line parser sees as a giant comment
591    // and silently drops.
592    //
593    // Comments (`#`-to-EOL and `//`-to-EOL) are NOT skipped at
594    // this level — physical newlines inside them terminate the
595    // logical line uniformly, and the per-line `ingest_polydat_source`
596    // pass skips any `#`/`//`-leading line via `trimmed.starts_with`.
597    // What matters at this level is that bracket/string state
598    // doesn't get confused by content inside comments.
599    let mut out: Vec<String> = Vec::new();
600    let mut buf = String::new();
601    let mut depth: i32 = 0;
602    let mut in_str = false;
603    let mut in_line_comment = false;
604    let mut chars = source.chars().peekable();
605    while let Some(ch) = chars.next() {
606        if in_line_comment {
607            buf.push(ch);
608            if ch == '\n' {
609                in_line_comment = false;
610                // Comments live at depth 0 by definition (they're
611                // line-oriented); the newline always terminates
612                // the logical line.
613                if !buf.is_empty() {
614                    out.push(std::mem::take(&mut buf));
615                }
616            }
617            continue;
618        }
619        if in_str {
620            buf.push(ch);
621            if ch == '\\' {
622                if let Some(nx) = chars.next() {
623                    buf.push(nx);
624                }
625            } else if ch == '"' {
626                in_str = false;
627            }
628            continue;
629        }
630        match ch {
631            '"' => {
632                in_str = true;
633                buf.push(ch);
634            }
635            '#' => {
636                // `#`-to-EOL comment — stop tracking bracket
637                // depth and string state inside it so a stray
638                // apostrophe or `(` in the comment doesn't
639                // imbalance later real-code parsing.
640                in_line_comment = true;
641                buf.push(ch);
642            }
643            '/' if matches!(chars.peek(), Some('/')) => {
644                // `//`-to-EOL comment, same treatment as `#`.
645                in_line_comment = true;
646                buf.push(ch);
647            }
648            '(' | '[' | '{' => {
649                depth += 1;
650                buf.push(ch);
651            }
652            ')' | ']' | '}' => {
653                if depth > 0 {
654                    depth -= 1;
655                }
656                buf.push(ch);
657            }
658            '\n' => {
659                if depth > 0 {
660                    buf.push(' ');
661                } else {
662                    out.push(std::mem::take(&mut buf));
663                }
664            }
665            _ => buf.push(ch),
666        }
667    }
668    if !buf.is_empty() {
669        out.push(buf);
670    }
671    out
672}
673
674/// Format a `Value` as a natural-form string suitable for
675/// passing to [`BindingScope::add_param_binding`]. `add_param_binding`
676/// recognises u64/f64-shaped strings, the literals `true` / `false`,
677/// and quotes everything else.
678///
679/// Returns `None` for value types that can't be represented as a
680/// Polydat source literal (`Bytes`, `Json`, `Ext`, `Handle`, vectors,
681/// `None`). The synthesizer falls back to extern cascade in
682/// those cases, since promoted-final inlining only works when
683/// the value can round-trip through source.
684/// Parse an `input` declaration line and insert each declared
685/// slot name into `out`. Accepts both surface forms:
686///
687/// - `input cycle: u64`       — bare single (with or without type)
688/// - `input (a: u64, b: f64)` — tuple form
689///
690/// The leading `input ` keyword may be present or absent — the
691/// scanner tolerates a coord line stored without the keyword (older
692/// emit paths) by falling back to treating the body as the slot
693/// list. Empty / unparseable input is a no-op.
694pub(crate) fn scan_input_decl_names(line: &str, out: &mut HashSet<String>) {
695    let body = line.trim().strip_prefix("input ").unwrap_or(line.trim());
696    let body = body.trim();
697    if let Some(inner) = body.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
698        for part in inner.split(',') {
699            let name = part.trim().split(':').next().unwrap_or("").trim();
700            if !name.is_empty() {
701                out.insert(name.to_string());
702            }
703        }
704        return;
705    }
706    let name = body.split(':').next().unwrap_or("").trim();
707    if !name.is_empty() {
708        out.insert(name.to_string());
709    }
710}
711
712/// Render an `input` declaration line for one or more slot names,
713/// matching the two surface forms produced by the parser:
714///
715/// - one name           → `input <name>: u64\n`
716/// - multiple names     → `input (<a>: u64, <b>: u64, ...)\n`
717///
718/// All slots default to `u64` here — the runtime emits these for
719/// propagated parent inputs, which are already u64-typed today.
720/// A future port-type-aware pass can plumb the parent's declared
721/// type through if/when non-u64 inputs become common.
722fn format_input_decl_line(names: &[String]) -> String {
723    match names {
724        [] => String::new(),
725        [single] => format!("input {single}: u64\n"),
726        many => {
727            let typed: Vec<String> = many.iter().map(|n| format!("{n}: u64")).collect();
728            format!("input ({})\n", typed.join(", "))
729        }
730    }
731}
732
733fn parse_modifier_and_name(lhs: &str) -> (ScopeModifier, &str) {
734    // Strip every recognised modifier prefix before classifying;
735    // multi-modifier forms like `volatile final` or `final shared`
736    // only see a single ScopeModifier tag at the scope-assembly
737    // level (the most-distinctive one wins), but the bare name
738    // still gets extracted correctly. The eventual Polydat compile
739    // sees the full source line with all keywords intact.
740    let mut rest = lhs;
741    let mut tag = ScopeModifier::None;
742    loop {
743        let prev = rest;
744        if let Some(r) = rest.strip_prefix("shared ") {
745            rest = r.trim();
746            // `final` / `init` / `cursor` are more distinctive
747            // than `shared` for shadow / kind checks; only set
748            // tag if we don't already have a stronger one.
749            if matches!(tag, ScopeModifier::None | ScopeModifier::Volatile) {
750                tag = ScopeModifier::Shared;
751            }
752        } else if let Some(r) = rest.strip_prefix("const ") {
753            // `const` is the current spelling of the Final tier
754            // (init/final retired) — same tag as legacy `final`.
755            rest = r.trim();
756            tag = ScopeModifier::Final;
757        } else if let Some(r) = rest.strip_prefix("final ") {
758            rest = r.trim();
759            tag = ScopeModifier::Final;
760        } else if let Some(r) = rest.strip_prefix("volatile ") {
761            rest = r.trim();
762            if matches!(tag, ScopeModifier::None) {
763                tag = ScopeModifier::Volatile;
764            }
765        } else if let Some(r) = rest.strip_prefix("init ") {
766            rest = r.trim();
767            tag = ScopeModifier::Init;
768            break; // init is a kind-keyword; no modifiers come after it.
769        } else if let Some(r) = rest.strip_prefix("cursor ") {
770            rest = r.trim();
771            tag = ScopeModifier::Cursor;
772            break;
773        }
774        if rest == prev {
775            break;
776        }
777    }
778    (tag, rest)
779}
780
781// Build a `BindingScope` from phase ops and execution context.
782//
783// This is the main entry point that replaces the string mutation
784// pipeline in the executor. It:
785// 1. Classifies each op's bindings by origin (Inherited vs Op)
786// 2. Adds iteration variables
787// 3. Generates auto-externs from the outer manifest
788// 4. Expands workload params
789// 5. Extracts inline expressions
790// 6. Collects required outputs from op templates
791// =========================================================================
792// For-each / comprehension scope kernel synthesis (M3.2)
793// =========================================================================
794//
795// The for_each / for_combinations / for_each_union synthesizer
796// lives in `polydat::iteration::comprehension::synthesis::synthesize_for_each_scope`.
797// Callers in this crate go directly to that entry point; this
798// module retains only the do-loop synthesizer below, since
799// do_while / do_until aren't comprehensions.
800
801/// Build the per-scope Polydat Kernel for a `do_while` / `do_until`
802/// node (SRD 18b). Same composition contract as for_each
803/// (every name visible at this scope resolves through standard
804/// Polydat API on the synthesized kernel) — the difference is the
805/// "scope output" is a `counter: u64` rather than tuple
806/// iteration variables, and there's no value list to pre-eval.
807///
808/// Source shape:
809///
810/// ```text
811///   extern <inherited_name>: <type>      # one per name
812///                                        # referenced in
813///                                        # `condition` text
814///                                        # that exists in
815///                                        # the parent
816///                                        # manifest or
817///                                        # workload params
818///   final <inherited_param> := <literal> # workload-param
819///                                        # injection (M3.3
820///                                        # bridge until M3.6)
821///   extern <counter>: u64                # only when counter
822///                                        # is `Some`
823/// ```
824///
825/// Per iteration the runtime sets `counter` (if present) via
826/// `kernel.state().set_input` and evaluates the condition
827/// expression against the kernel via `interpolate_via_kernel` +
828/// `eval_const_expr`. Children inherit `counter` (and any
829/// inherited names) through standard `materialize_wiring_from_outer`.
830/// Synthesize the Polydat scope kernel for a phase that carries its own
831/// `bindings:` block.
832///
833/// The phase scope owns this kernel as part of its closure lifetime
834/// (per the Polydat builder/walk/instancing protocol): a phase whose YAML
835/// declared `bindings: |` produces matter that the parent kernel's
836/// builds a child scope from (`ScopeKernel::build_under`). Op-template
837/// scopes that descend from this phase find these bindings as
838/// outputs of their parent kernel and `extern` them through the
839/// standard manifest cascade.
840///
841/// Phases without bindings AND without `for_each:` produce no install
842/// spec — their scope-tree node carries an empty `cached_kernel` and
843/// the parent walker resolves through to the nearest ancestor with a
844/// kernel. The closure invariant ("every scope has a kernel
845/// reference") still holds; the reference is just the parent's,
846/// matter-gated as the Polydat APIs prescribe.
847///
848/// Source emitted (in order):
849///
850/// ```text
851///   final <workload_param> := <literal>     # cascaded params
852///   extern <ancestor_output>: <type>        # cascaded outputs/inputs
853///   <phase_bindings_body>                   # phase-declared bindings
854/// ```
855///
856/// The phase's bindings body is appended verbatim so the Polydat compiler
857/// classifies them per the same rules as op-level bindings (init /
858/// shared / final detection, type inference). Iteration coordinate
859/// (`cycle`) cascades from the parent — we never re-declare it here.
860/// Compose a phase scope's bindings source with SRD-75
861/// phase-poll augmentation and/or phase-level `metrics:`
862/// augmentation when applicable. Returns the existing
863/// `BindingsDef` unchanged when the phase has neither `poll:`
864/// nor `metrics:`; otherwise produces a
865/// `BindingsDef::PolydatSource` that, for the poll case:
866///
867/// - **Prepends** `shared <name>: u64 := 0` for each
868///   capture name declared by the phase's ops. The
869///   shared-cell modifier means TraversingDispenser
870///   writes via `ctx.wires.write` propagate to the
871///   phase scope kernel (SRD-13c §"Implementation:
872///   SharedCell-backed input slots" §4 "Write
873///   through"); same cell is observable to other ops'
874///   `if:` reads in the same iteration AND to the
875///   `__poll_until` predicate evaluated on the phase
876///   kernel.
877/// - **Appends** the original `phase.bindings` body
878///   verbatim (the author's bindings shadow synthesized
879///   captures by ident if any name collides — same
880///   shadowing rule as anywhere else in GK; we err out
881///   in that case for clarity).
882/// - **Appends** `__poll_until := <until>` as a regular
883///   cycle binding (dynamic lifecycle per SRD-11 §"Two
884///   Evaluation Lifecycles" — re-evaluates per pull as
885///   capture cells update).
886///
887/// For the metrics case it appends an `extern phase_start: u64
888/// = 0` origin wire (set by the executor at the completion-time
889/// pull) and one `volatile __metric_<name> := <value>` per
890/// declared phase metric. `volatile` on the `__metric_<name>`
891/// binding excludes it from const-fold identity; a value that
892/// reads a clock should declare that read as its own `volatile`
893/// phase binding (e.g. `volatile now_ms := current_epoch_millis()`,
894/// metric `value: now_ms - phase_start`) so the non-deterministic
895/// node is acknowledged directly and the kernel compiles under
896/// `--strict`. The executor pulls each `__metric_<name>` once at
897/// phase completion and records it on the phase component.
898///
899/// Type inference is intentionally narrow in the
900/// initial ship: every capture lands as `u64` (the
901/// shape the canonical synchronizer-pattern workload
902/// uses — `:count` reductions and numeric Jolokia
903/// attribute reads). Non-numeric captures aren't
904/// supported in the phase-poll predicate; the
905/// workload author falls back to a different pattern.
906/// SRD-75 §"Open questions: Capture-type inference
907/// granularity" tracks the refinement.
908pub fn synthesize_phase_scope_bindings(
909    phase: &nmbrs_workload::model::WorkloadPhase,
910) -> Result<nmbrs_workload::model::BindingsDef, String> {
911    use nmbrs_workload::model::BindingsDef;
912    let has_poll = phase.poll.is_some();
913    let has_metrics = !phase.metrics.is_empty();
914    // SRD-86 — an `optimize.objective` that is an inline expression (not a bare
915    // wire reference) is lowered to a synthesized `__objective` binding below.
916    let has_objective_expr = phase
917        .optimize
918        .as_ref()
919        .is_some_and(|o| !objective_is_bare_wire(&o.objective));
920    // No phase-scope augmentation needed — pass the author's bindings
921    // through unchanged so a metrics/poll-free phase keeps its original
922    // (possibly empty) `BindingsDef`. Stop conditions do NOT augment the
923    // matter (they are scope-bound `ScopedPredicate`s built against the phase
924    // kernel), so they don't force synthesis here.
925    if !has_poll && !has_metrics && !has_objective_expr {
926        return Ok(phase.bindings.clone());
927    }
928
929    // Walk every op in the phase, collect declared
930    // capture names. The capture set is the union across
931    // ops in the phase (the synchronizer pattern's
932    // common case: one read-op captures all the state,
933    // a second trigger-op only reads via `if:`). Only
934    // relevant to the poll augmentation; empty otherwise.
935    let mut capture_names: Vec<String> = Vec::new();
936    let mut seen: HashSet<String> = HashSet::new();
937    if has_poll {
938        for op in &phase.ops {
939            for cap in &op.captures {
940                if seen.insert(cap.as_name.clone()) {
941                    capture_names.push(cap.as_name.clone());
942                }
943            }
944        }
945    }
946
947    // Compose the augmented source.
948    let mut source = String::new();
949    if has_poll {
950        source.push_str(
951            "# SRD-75 phase-poll augmentation — synthesized.\n\
952             # Captures land here as shared cells; ops write through via\n\
953             # `ctx.wires.write` on their op-template kernel's import\n\
954             # slots (Rule 1 shared import → cell attached at spawn).\n",
955        );
956        for name in &capture_names {
957            // Polydat's `shared X := <literal>` form infers the type
958            // from the RHS literal (per SRD-13c
959            // §"Implementation: SharedCell-backed input slots"
960            // — `shared X := 0` lands as u64 via literal-fold).
961            // Captures default to u64 with init 0; numeric
962            // predicates compare cleanly, and TraversingDispenser's
963            // json_to_value coerces the response value into the
964            // matching Value variant.
965            source.push_str(&format!("shared {name} := 0\n"));
966        }
967    }
968
969    let original_body: String = match &phase.bindings {
970        BindingsDef::PolydatSource(s) => s.clone(),
971        BindingsDef::Map(m) => {
972            let mut out = String::new();
973            for (n, e) in m {
974                out.push_str(&format!("{n} := {e}\n"));
975            }
976            out
977        }
978    };
979    if !original_body.trim().is_empty() {
980        // Detect collisions between author-declared
981        // bindings and synthesized captures. A collision
982        // is most likely a workload bug (the author
983        // didn't realize the name was being synthesized
984        // by phase-poll); fail loudly per SRD-30 unknown-
985        // field hygiene rather than silently letting one
986        // win.
987        let locally_declared = scan_locally_declared_idents(&original_body);
988        for name in &capture_names {
989            if locally_declared.contains(name) {
990                return Err(format!(
991                    "phase-poll synthesis: capture name '{name}' is also \
992                     declared by the phase's `bindings:` block — pick one. \
993                     SRD-75 synthesizes captures as `shared <name>: u64`; \
994                     re-declaring the same name in bindings is a collision."
995                ));
996            }
997        }
998        source.push_str(&original_body);
999        if !source.ends_with('\n') {
1000            source.push('\n');
1001        }
1002    }
1003
1004    if has_poll {
1005        // The predicate is a regular cycle binding (NOT
1006        // `const` — its upstream depends on per-cycle
1007        // capture writes, so it must re-evaluate per pull).
1008        let poll = phase.poll.as_ref().expect("has_poll");
1009        source.push_str(&format!("__poll_until := {}\n", poll.until));
1010    }
1011
1012    if has_metrics {
1013        // Phase-level `metrics:` — emit one `volatile
1014        // __metric_<name> := <value>` per declared metric, plus the
1015        // executor-injected `phase_start` origin wire. `volatile`
1016        // acknowledges the nondeterminism of clock-reading values
1017        // like `phase_elapsed(phase_start)` so the phase kernel
1018        // compiles in strict mode (and excludes them from const-fold
1019        // identity); for a deterministic value it is harmless. The
1020        // executor pulls each `__metric_<name>` once at phase
1021        // completion — see `executor::emit_phase_metrics`.
1022        // `phase_start` binds the runtime's phase-scoped clock node rather
1023        // than an extern the executor has to remember to fill. As an extern it
1024        // was set ONLY on the completion-time metric pull, on a fresh subscope
1025        // — so anything reading it while the phase was still running (an op,
1026        // most obviously) saw the declared default of 0 and silently computed
1027        // against the epoch. The node reads the phase origin the executor
1028        // scopes in `run_phase`, so the value is correct from the phase's
1029        // first op onward, and `volatile` keeps it out of const-fold identity.
1030        source.push_str(
1031            "# Phase-level metrics — synthesized.\n\
1032             # `phase_start` is the epoch millis at which THIS phase started,\n\
1033             # read from the runtime's phase-scoped clock.\n\
1034             volatile phase_start := phase_start_millis()\n",
1035        );
1036        let mut entries: Vec<_> = phase.metrics.iter().collect();
1037        entries.sort_by(|a, b| a.0.cmp(b.0));
1038        for (name, spec) in entries {
1039            let binding = synthesize_metric_binding_name(name);
1040            source.push_str(&format!(
1041                "volatile {binding} := {expr}\n",
1042                expr = spec.value
1043            ));
1044            // See the op-template path: a coordinate is compiled matter, not a
1045            // runtime string. `volatile` for the same reason the value is —
1046            // a coordinate read from a capture or a clock must not be folded
1047            // into one phase's value.
1048            for (dim, expr) in &spec.cell {
1049                let cell_binding = synthesize_cell_binding_name(name, dim);
1050                source.push_str(&format!("volatile {cell_binding} := {expr}\n"));
1051            }
1052        }
1053    }
1054
1055    if has_objective_expr {
1056        // SRD-86 — lower an inline `optimize.objective` expression to one wire
1057        // the optimizer reads (`__objective`), so an author can write the
1058        // objective inline instead of pre-declaring a `bindings:` entry.
1059        // Emitted LAST so it can reference any author binding or synthesized
1060        // `__metric_<name>` above it. `volatile` lets a metricsql/clock-reading
1061        // objective compile under `--strict` and is harmless for a
1062        // deterministic expression; the settle-vs-one-shot routing keys off
1063        // program-wide reader-node presence, not this flag, so a deterministic
1064        // inline objective still takes the one-shot path.
1065        let objective = &phase
1066            .optimize
1067            .as_ref()
1068            .expect("has_objective_expr")
1069            .objective;
1070        source.push_str(&format!(
1071            "# SRD-86 inline objective — synthesized.\n\
1072             volatile {OBJECTIVE_WIRE} := {objective}\n",
1073        ));
1074    }
1075
1076    // SRD-83 stop conditions are NOT synthesized into the phase matter.
1077    // Each predicate is compiled as a scope-bound `ScopedPredicate`
1078    // (`stop_conditions::compile_stop_condition`) against the *built*
1079    // phase kernel and evaluated per trigger — authored phase bindings
1080    // and evaluated stop predicates stay orthogonal concerns.
1081
1082    Ok(BindingsDef::PolydatSource(source))
1083}
1084
1085/// Synthesize a phase-scope kernel.
1086///
1087/// Pushes the phase's own `bindings:` body verbatim, then drives
1088/// the shared cascade walker to declare every parent-visible
1089/// name the body references plus the standard workload-param +
1090/// parent-output + parent-input cascade.
1091// reason: cohesive scope-kernel constructor — each argument is a distinct
1092// piece of the scope's compile context (bindings, parent kernel, params,
1093// cascade inputs); a parameter struct would only relocate the same fields.
1094#[allow(clippy::too_many_arguments)]
1095pub fn build_phase_scope_kernel(
1096    bindings: &nmbrs_workload::model::BindingsDef,
1097    parent_manifest: &[crate::runner::ManifestEntry],
1098    parent_kernel: &crate::scope_kernel::ScopeKernel,
1099    workload_params: &HashMap<String, String>,
1100    polydat_lib_paths: Vec<std::path::PathBuf>,
1101    workload_dir: Option<&std::path::Path>,
1102    strict: bool,
1103    context: &str,
1104) -> Result<crate::scope_kernel::ScopeKernel, String> {
1105    use nmbrs_workload::model::BindingsDef;
1106
1107    let body_text: String = match bindings {
1108        BindingsDef::PolydatSource(s) => s.clone(),
1109        BindingsDef::Map(m) => {
1110            let mut out = String::new();
1111            for (name, expr) in m {
1112                out.push_str(&format!("{name} := {expr}\n"));
1113            }
1114            out
1115        }
1116    };
1117
1118    let mut source = String::new();
1119    let mut emitted: HashSet<String> = HashSet::new();
1120    let mut inherited_names: Vec<String> = Vec::new();
1121
1122    // Discover the names the phase body references and the
1123    // names it locally declares (which shadow parent-output
1124    // cascade per SRD-13f).
1125    let body_locally_declared = scan_locally_declared_idents(&body_text);
1126    let mut referenced: HashSet<String> = HashSet::new();
1127    collect_string_interp_refs(&body_text, &mut referenced);
1128    for ident in scan_idents_in_polydat_source(&body_text) {
1129        if !body_locally_declared.contains(&ident) {
1130            referenced.insert(ident);
1131        }
1132    }
1133
1134    // Drive the shared cascade walker. The phase body's
1135    // locally-declared idents go into both pre_emitted (so the
1136    // walker doesn't re-cascade them) and shadow_names (so the
1137    // workload-param + parent-output passes also skip them).
1138    crate::scope_synth::cascade_parent_into_source(
1139        crate::scope_synth::CascadeInputs {
1140            parent_kernel,
1141            workload_params,
1142            parent_manifest,
1143            referenced: &referenced,
1144            pre_emitted: &body_locally_declared,
1145            shadow_names: &body_locally_declared,
1146            // Phase opts out: the body may already declare
1147            // referenced names as `input` / `extern` and a
1148            // step-3 emission would collide. Phase relies on
1149            // step 5 (parent-output cascade) and step 6
1150            // (parent-input cascade) to bring in what the body
1151            // doesn't declare locally.
1152            include_referenced_cascade: false,
1153        },
1154        crate::scope_synth::CascadeOutputs {
1155            source: &mut source,
1156            emitted: &mut emitted,
1157            inherited_names: &mut inherited_names,
1158        },
1159    );
1160
1161    // Append the phase's own bindings body verbatim. The GK
1162    // compiler classifies each statement (init / shared / final)
1163    // per the standard rules.
1164    if !source.ends_with('\n') && !source.is_empty() {
1165        source.push('\n');
1166    }
1167    source.push_str(&body_text);
1168    if !source.ends_with('\n') {
1169        source.push('\n');
1170    }
1171
1172    let compile_options = polydat::kernel::subcontext::CompileOptions {
1173        workload_dir: workload_dir.map(|p| p.to_path_buf()),
1174        polydat_lib_paths,
1175        strict,
1176        required_outputs: Vec::new(),
1177        context_label: Some(context.to_string()),
1178        cursor_limit: None,
1179        ..Default::default()
1180    };
1181
1182    if debug_scope_synth_enabled() {
1183        eprintln!(
1184            "=== SCOPE SYNTH [{context}] inherited={inherited_names:?} ===\n{source}\n=== END ==="
1185        );
1186    }
1187    crate::scope_kernel::ScopeKernel::synthesize_under(
1188        parent_kernel,
1189        crate::scope_kernel::SourceMatter::source(context, source, compile_options)
1190            .inherited(inherited_names),
1191    )
1192    .map_err(|e| format!("{context}: phase scope synthesis: {e}"))
1193}
1194
1195// reason: cohesive scope-kernel constructor — each argument is a distinct
1196// piece of the do-loop's compile context (counter, condition, parent kernel,
1197// params, cascade inputs); a parameter struct would only relocate the fields.
1198#[allow(clippy::too_many_arguments)]
1199pub fn build_do_loop_scope_kernel(
1200    counter: Option<&str>,
1201    condition: &str,
1202    parent_manifest: &[crate::runner::ManifestEntry],
1203    parent_kernel: &crate::scope_kernel::ScopeKernel,
1204    workload_params: &HashMap<String, String>,
1205    polydat_lib_paths: Vec<std::path::PathBuf>,
1206    workload_dir: Option<&std::path::Path>,
1207    strict: bool,
1208    context: &str,
1209) -> Result<crate::scope_kernel::ScopeKernel, String> {
1210    // Scope-specific contribution: declare the counter extern
1211    // (if a counter is in play). The counter is the do-loop's
1212    // only own-iter wire; pre-emit it so the shared cascade
1213    // walker doesn't try to type-cascade it from the parent
1214    // (which doesn't know about it).
1215    let mut source = String::new();
1216    let mut emitted: HashSet<String> = HashSet::new();
1217    let mut inherited_names: Vec<String> = Vec::new();
1218
1219    if let Some(c) = counter {
1220        source.push_str(&format!("extern {c}: u64\n"));
1221        emitted.insert(c.to_string());
1222    }
1223
1224    // Drive the shared cascade walker. `referenced` is the set
1225    // of `{name}` placeholders the condition expression
1226    // mentions; pre_emitted is the counter (if any).
1227    let referenced = collect_leaf_placeholders(&[condition.to_string()]);
1228    let pre_emitted: HashSet<String> = counter.iter().map(|c| c.to_string()).collect();
1229    let shadow_names: HashSet<String> = pre_emitted.clone();
1230    crate::scope_synth::cascade_parent_into_source(
1231        crate::scope_synth::CascadeInputs {
1232            parent_kernel,
1233            workload_params,
1234            parent_manifest,
1235            referenced: &referenced,
1236            pre_emitted: &pre_emitted,
1237            shadow_names: &shadow_names,
1238            // do-loop opts in: the condition expression is
1239            // narrowly-scoped Polydat source that references
1240            // names which need extern declarations to be
1241            // resolvable. Step 3 emits those externs against
1242            // parent_manifest's types.
1243            include_referenced_cascade: true,
1244        },
1245        crate::scope_synth::CascadeOutputs {
1246            source: &mut source,
1247            emitted: &mut emitted,
1248            inherited_names: &mut inherited_names,
1249        },
1250    );
1251
1252    if source.is_empty() {
1253        source.push_str("const __empty := 0\n");
1254    }
1255
1256    // The same compile options every synthesized scope takes: the
1257    // workload's library paths and directory, so the condition can call
1258    // library modules and name workload-relative files, and strict mode.
1259    let compile_options = polydat::kernel::subcontext::CompileOptions {
1260        workload_dir: workload_dir.map(|p| p.to_path_buf()),
1261        polydat_lib_paths,
1262        strict,
1263        required_outputs: Vec::new(),
1264        context_label: Some(context.to_string()),
1265        cursor_limit: None,
1266        ..Default::default()
1267    };
1268    crate::scope_kernel::ScopeKernel::synthesize_under(
1269        parent_kernel,
1270        crate::scope_kernel::SourceMatter::source(context, source, compile_options)
1271            .inherited(inherited_names),
1272    )
1273    .map_err(|e| format!("{context}: do-loop scope synthesis: {e}"))
1274}
1275
1276/// Token-shaped identifier scan over Polydat source. Returns every
1277/// alphanumeric/underscore-shaped token that isn't a keyword
1278/// or numeric literal. Used by
1279/// [`build_op_template_scope_kernel`] to discover names the
1280/// op's bindings body references; the Polydat compiler does the
1281/// authoritative parse downstream — this scan is just a
1282/// best-effort first pass for the cross-scope contract check.
1283pub(crate) fn scan_idents_in_polydat_source(src: &str) -> HashSet<String> {
1284    const KEYWORDS: &[&str] = &[
1285        "input", "extern", "const", "final", "init", "shared", "volatile", "cursor", "pragma",
1286        "true", "false", "as", "in", "for",
1287        // Block-form conditional selection: `if <cond> { a } else { b }`. This is a
1288        // TEXTUAL scan, so it cannot tell a keyword from a wire name by position —
1289        // before these were listed, a binding using the block form reported `if` and
1290        // `else` as unresolved wire references. The call form `if(cond, a, b)` was
1291        // unaffected and so did not surface this.
1292        "if", "else",
1293    ];
1294    let mut out = HashSet::new();
1295    let mut chars = src.chars().peekable();
1296    let mut current = String::new();
1297    let mut in_string = false;
1298    let mut in_line_comment = false;
1299    let mut in_block_comment = false;
1300    // Suppress the next ident — set when we just saw a `:` outside
1301    // strings/comments. Lets us skip the type token in declarations
1302    // like `extern x: u64`, `input cycle: u64`, `input (a: u64, b: f64)`,
1303    // and module signatures `foo(p: u64) -> (q: f64)`. A type name
1304    // (`u64`/`f64`/`str`/etc.) is not a wire reference.
1305    let mut suppress_next_ident = false;
1306    while let Some(c) = chars.next() {
1307        if in_line_comment {
1308            if c == '\n' {
1309                in_line_comment = false;
1310            }
1311            continue;
1312        }
1313        if in_block_comment {
1314            if c == '*' && chars.peek() == Some(&'/') {
1315                chars.next();
1316                in_block_comment = false;
1317            }
1318            continue;
1319        }
1320        if in_string {
1321            if c == '\\' {
1322                chars.next();
1323                continue;
1324            }
1325            if c == '"' {
1326                in_string = false;
1327            }
1328            continue;
1329        }
1330        if c == '"' {
1331            in_string = true;
1332            continue;
1333        }
1334        // `#` to end-of-line — YAML-style hash comment, matching the
1335        // Polydat lexer (`dsl/lexer.rs` "Skip hash comments"). Without
1336        // this, comment words inside a `bindings: |` block leak in as
1337        // phantom wire references.
1338        if c == '#' {
1339            in_line_comment = true;
1340            continue;
1341        }
1342        if c == '/' {
1343            if chars.peek() == Some(&'/') {
1344                chars.next();
1345                in_line_comment = true;
1346                continue;
1347            }
1348            if chars.peek() == Some(&'*') {
1349                chars.next();
1350                in_block_comment = true;
1351                continue;
1352            }
1353        }
1354        if c.is_alphanumeric() || c == '_' {
1355            current.push(c);
1356        } else if !current.is_empty() {
1357            // Token boundary — is `current` an ident?
1358            let is_ident = !current
1359                .chars()
1360                .next()
1361                .map(|c| c.is_ascii_digit())
1362                .unwrap_or(true)
1363                && !KEYWORDS.contains(&current.as_str());
1364            if is_ident && !suppress_next_ident {
1365                out.insert(current.clone());
1366            }
1367            current.clear();
1368            suppress_next_ident = false;
1369        }
1370        // Track `:` separately so the next ident is treated as a
1371        // type annotation. Excludes `:=` (the binding operator) by
1372        // peeking ahead.
1373        if c == ':' && chars.peek() != Some(&'=') {
1374            suppress_next_ident = true;
1375        }
1376    }
1377    if !current.is_empty()
1378        && !current
1379            .chars()
1380            .next()
1381            .map(|c| c.is_ascii_digit())
1382            .unwrap_or(true)
1383        && !KEYWORDS.contains(&current.as_str())
1384        && !suppress_next_ident
1385    {
1386        out.insert(current);
1387    }
1388    out
1389}
1390
1391/// Names declared on the LHS of `:=` (or `=` for init bindings)
1392/// in Polydat source. Locally-declared names shadow parent-scope
1393/// references per SRD-13c §"Shadowing", so the cross-scope
1394/// contract check skips them.
1395pub(crate) fn scan_locally_declared_idents(src: &str) -> HashSet<String> {
1396    let mut out = HashSet::new();
1397    for line in src.lines() {
1398        let line = line.trim();
1399        // Skip blanks + line comments. `#` (YAML-style) and `//` are
1400        // both Polydat line-comment forms (`dsl/lexer.rs`); neither
1401        // declares a binding.
1402        if line.is_empty() || line.starts_with("//") || line.starts_with('#') {
1403            continue;
1404        }
1405        // Drop modifier prefixes (`final const x := …`,
1406        // `shared y := …`) so the LHS ident is always the
1407        // last word before `:=` or `=`.
1408        let prefixes = [
1409            "shared const ",
1410            "const ",
1411            "init ",
1412            "shared ",
1413            "final ",
1414            "volatile ",
1415            "extern ",
1416        ];
1417        let mut rest = line;
1418        loop {
1419            let mut stripped = false;
1420            for p in &prefixes {
1421                if let Some(r) = rest.strip_prefix(p) {
1422                    rest = r.trim_start();
1423                    stripped = true;
1424                    break;
1425                }
1426            }
1427            if !stripped {
1428                break;
1429            }
1430        }
1431        // Find `:=` or `=` (but not `==`).
1432        let assign_idx = rest.find(":=").or_else(|| {
1433            rest.find('=')
1434                .filter(|&i| rest.as_bytes().get(i + 1) != Some(&b'='))
1435        });
1436        let Some(idx) = assign_idx else { continue };
1437        let lhs = rest[..idx].trim();
1438        // `extern name: type` — the lhs is "name: type"; strip the type.
1439        let name = lhs.split(':').next().unwrap_or(lhs).trim();
1440        if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
1441            out.insert(name.to_string());
1442        }
1443    }
1444    out
1445}
1446
1447// SRD-13c `ParentRefKind` classification and the
1448// `classify_parent_ref` helper were retired by SRD-13f. The
1449// snapshot-vs-shared contract they enforced is superseded by
1450// uniform construction-time wiring + per-cycle refresh on
1451// non-shared parent outputs (SRD-13f §"Materialization gradient").
1452
1453/// SRD-13d Phase 9 — synthesize a per-op-template kernel for a
1454/// materialised op-template scope.
1455///
1456/// Mirrors [`build_do_loop_scope_kernel`] but uses the op's
1457/// `bindings:` block (which already carries metric `:=` injections
1458/// per SRD-40b §1) as the body. The resulting kernel:
1459///
1460/// 1. Emits an `extern <name>: <type>` for every parent-visible
1461///    name the op explicitly references — and only those, so
1462///    the op-template kernel stays narrow.
1463/// 2. Validates each reference against the SRD-13c cross-scope
1464///    visibility contract: `Input`, `SharedOutput`, or
1465///    `ConstantOutput` are accepted; `DynamicOutput` errors at
1466///    workload-init time with a clear message pointing at the
1467///    `shared` modifier path.
1468/// 3. Emits the op's own bindings.
1469/// 4. Builds the scope under the parent kernel and propagates
1470///    inherited inputs. The scope keeps its module, from which each
1471///    fiber instantiates its per-op kernel with the module's
1472///    `result:` write-throughs ([`crate::fiber_engine`]).
1473// reason: cohesive scope-kernel constructor — each argument is a distinct
1474// piece of the op-template's compile context (op, parent kernel, params,
1475// cascade inputs); a parameter struct would only relocate the same fields.
1476#[allow(clippy::too_many_arguments)]
1477pub fn build_op_template_scope_kernel(
1478    op: &nmbrs_workload::model::ParsedOp,
1479    parent_manifest: &[crate::runner::ManifestEntry],
1480    parent_kernel: &crate::scope_kernel::ScopeKernel,
1481    workload_params: &HashMap<String, String>,
1482    polydat_lib_paths: Vec<std::path::PathBuf>,
1483    workload_dir: Option<&std::path::Path>,
1484    strict: bool,
1485    kernel_opt: polydat::kernel::KernelOptLevel,
1486    context: &str,
1487) -> Result<crate::scope_kernel::ScopeKernel, String> {
1488    use nmbrs_workload::model::BindingsDef;
1489
1490    let manifest_by_name: HashMap<&str, &crate::runner::ManifestEntry> = parent_manifest
1491        .iter()
1492        .map(|e| (e.name.as_str(), e))
1493        .collect();
1494
1495    let mut source = String::new();
1496    let mut emitted: HashSet<String> = HashSet::new();
1497    let mut inherited_names: Vec<String> = Vec::new();
1498
1499    // SRD-13f: every parent-visible wire the op template
1500    // references — whether in body, condition, delay, metric
1501    // values, op fields (`stmt`, `uri`, `body`, etc.), or
1502    // string-interpolation arguments inside the body — gets
1503    // wired into the local op-template kernel at construction.
1504    // Local reads on the op-template kernel then resolve every
1505    // such name through the local read API, with construction-
1506    // time wiring guaranteeing the read invariant (inner reads
1507    // return the value that outer would return — see SRD-13f
1508    // §"The read invariant"). The wires layer takes one kernel
1509    // handle and never composes chains externally.
1510    let body_text: String = match &op.bindings {
1511        BindingsDef::PolydatSource(s) => s.clone(),
1512        BindingsDef::Map(m) => {
1513            let mut out = String::new();
1514            for (name, expr) in m {
1515                out.push_str(&format!("{name} := {expr}\n"));
1516            }
1517            out
1518        }
1519    };
1520
1521    // SRD-13f Push D: declare the parent's coordinate inputs
1522    // (typically just `cycle`) on this op-template kernel.
1523    // Pre-Push-D, the workload-level `input <name>: <type>` line
1524    // was merged into op.bindings and arrived via body_text, so
1525    // the kernel always had a Coordinate slot. After Push D
1526    // body_text no longer carries it, so we emit the declaration
1527    // explicitly — without it the op-template kernel has no
1528    // input slot for cycle and the runtime's per-cycle
1529    // `set_inputs` writes go nowhere.
1530    let body_has_inputs_decl = body_text
1531        .lines()
1532        .any(|line| line.trim_start().starts_with("input "));
1533    if !body_has_inputs_decl {
1534        let parent_coord_names: Vec<String> = parent_kernel
1535            .program()
1536            .input_names()
1537            .into_iter()
1538            .take(parent_kernel.program().coord_count())
1539            .collect();
1540        if !parent_coord_names.is_empty() {
1541            source.push_str(&format_input_decl_line(&parent_coord_names));
1542            for name in &parent_coord_names {
1543                emitted.insert(name.clone());
1544            }
1545        }
1546    }
1547    // SRD-109 Part 3 — `results:` interface wires are dispenser-
1548    // delivered projections (`result:` path entries evaluated by
1549    // the result wrapper); declare each as an explicit extern at
1550    // its interface type so the per-cycle `ctx.wires.write` lands
1551    // on a correctly-typed slot. Emitted before the cascade scan
1552    // so a relevancy/metric reference to the same name doesn't
1553    // try to pull it from the parent.
1554    if let Some(iface) = op.abstract_interface.as_ref() {
1555        for (rname, port_type) in &iface.results {
1556            if !emitted.contains(rname) {
1557                source.push_str(&format!("extern {rname}: {port_type}\n"));
1558                emitted.insert(rname.clone());
1559            }
1560        }
1561    }
1562
1563    let body_idents = scan_idents_in_polydat_source(&body_text);
1564    let body_locally_declared = scan_locally_declared_idents(&body_text);
1565    let mut referenced: Vec<String> = Vec::new();
1566    // Op field references — `stmt`, `uri`, `body`, etc. carry
1567    // `{name}` placeholders the dispenser substitutes at cycle
1568    // time. Those wires must be reachable on the op-template
1569    // kernel so the dispenser's single-kernel-handle wires
1570    // surface resolves them through the local read API.
1571    for value in op.op.values() {
1572        if let Some(s) = value.as_str() {
1573            for n in nmbrs_workload::bindpoints::referenced_bindings(s)
1574                .map_err(|e| format!("{context}: {e}"))?
1575            {
1576                if !body_locally_declared.contains(&n) && !referenced.iter().any(|r| r == &n) {
1577                    referenced.push(n);
1578                }
1579            }
1580        }
1581    }
1582    for ident in &body_idents {
1583        if body_locally_declared.contains(ident) {
1584            continue;
1585        }
1586        if !referenced.iter().any(|r| r == ident) {
1587            referenced.push(ident.clone());
1588        }
1589    }
1590    // String-interpolation references inside the body (e.g.
1591    // `dataset_prebuffer("{dataset}:{profile}")`). The Polydat compiler
1592    // desugars those into wires that need a matching extern;
1593    // without this scan, the cascade misses them and the compiler
1594    // defaults the auto-extern to u64, landing a Str value into a
1595    // u64 slot at bind-time and panicking via an inserted
1596    // `__u64_to_string` adapter.
1597    let mut interp_refs: HashSet<String> = HashSet::new();
1598    collect_string_interp_refs(&body_text, &mut interp_refs);
1599    for ident in interp_refs {
1600        if body_locally_declared.contains(&ident) {
1601            continue;
1602        }
1603        if !referenced.iter().any(|r| r == &ident) {
1604            referenced.push(ident);
1605        }
1606    }
1607    if let Some(ref s) = op.condition {
1608        let n = s.trim().trim_start_matches('{').trim_end_matches('}');
1609        if !n.is_empty() && !body_locally_declared.contains(n) && !referenced.iter().any(|r| r == n)
1610        {
1611            referenced.push(n.to_string());
1612        }
1613    }
1614    // Capture targets are a WRITE usage surface of this op: the
1615    // runtime lands each captured value on this kernel's input slot
1616    // via `ctx.wires.write` (see TraversingDispenser). The name must
1617    // therefore be declared here like any other referenced wire —
1618    // the standard cascade below emits the `extern` (with the
1619    // parent's port type) and the wiring machinery binds it to the
1620    // ancestral `shared` cell when one is in scope, making the
1621    // write visible across phases. Without the declaration a
1622    // capture-only op's write is a silent NoSlot drop, and any
1623    // later phase gating on the cell reads its initializer forever.
1624    for cap in &op.captures {
1625        let n = cap.as_name.as_str();
1626        if !n.is_empty() && !body_locally_declared.contains(n) && !referenced.iter().any(|r| r == n)
1627        {
1628            referenced.push(n.to_string());
1629        }
1630    }
1631    if let Some(ref delay_spec) = op.delay {
1632        for raw in delay_spec.names() {
1633            let n = raw.trim().trim_start_matches('{').trim_end_matches('}');
1634            if !n.is_empty()
1635                && !body_locally_declared.contains(n)
1636                && !referenced.iter().any(|r| r == n)
1637            {
1638                referenced.push(n.to_string());
1639            }
1640        }
1641    }
1642    for spec in op.metrics.values() {
1643        let trimmed = spec.value.trim();
1644        let bare = !trimmed.is_empty() && trimmed.chars().all(|c| c.is_alphanumeric() || c == '_');
1645        if bare
1646            && !body_locally_declared.contains(trimmed)
1647            && !referenced.iter().any(|r| r == trimmed)
1648        {
1649            referenced.push(trimmed.to_string());
1650        }
1651    }
1652
1653    // Wire references inside the relevancy block. The validator
1654    // resolves `actual:`, `expected:`, `k:`, `r:` at wrap-time
1655    // through the dispenser's canonical kernel (parse_count_param
1656    // and the `expected_wire_name` path in `validation.rs`).
1657    // Strings that are bare identifiers OR `{name}` text-templates
1658    // name a wire that must be visible on this op-template kernel;
1659    // numeric / integer-literal values aren't wire references and
1660    // pass through.
1661    // The admission block names wires the same way (SRD-115 §4.8).
1662    let evaluation_wire_refs = [
1663        (
1664            "relevancy",
1665            &["actual", "expected", "k", "r", "admitted"][..],
1666        ),
1667        (crate::admission::PARAM, crate::admission::WIRE_KEYS),
1668    ];
1669    for (rel, key) in evaluation_wire_refs.iter().flat_map(|(block, keys)| {
1670        let rel = op.params.get(*block).and_then(|v| v.as_object());
1671        keys.iter().filter_map(move |key| rel.map(|rel| (rel, key)))
1672    }) {
1673        let Some(val) = rel.get(*key).and_then(|v| v.as_str()) else {
1674            continue;
1675        };
1676        let trimmed = val
1677            .trim()
1678            .trim_start_matches('{')
1679            .trim_end_matches('}')
1680            .trim();
1681        if trimmed.is_empty() {
1682            continue;
1683        }
1684        // Skip numeric literals — `k: 10` is a constant, not a
1685        // wire ref.
1686        if trimmed.parse::<i64>().is_ok() {
1687            continue;
1688        }
1689        // Bare-identifier check matches the validator's
1690        // `is_bare_ident` rule.
1691        let bare = trimmed
1692            .chars()
1693            .next()
1694            .map(|c| c.is_ascii_alphabetic() || c == '_')
1695            .unwrap_or(false)
1696            && trimmed
1697                .chars()
1698                .all(|c| c.is_ascii_alphanumeric() || c == '_');
1699        if !bare {
1700            continue;
1701        }
1702        if !body_locally_declared.contains(trimmed) && !referenced.iter().any(|r| r == trimmed) {
1703            referenced.push(trimmed.to_string());
1704        }
1705    }
1706
1707    // SRD-66 result-bindings: every LHS name a result-binding
1708    // declares needs an input slot on this op-template kernel so
1709    // the Rule 2 write-through can wire to the parent's SHARED
1710    // cell. Without this, the cell-bound slot is never declared,
1711    // `add_result_bindings` falls back to PortType::U64 (the
1712    // "couldn't classify" default) for the export, and the write-
1713    // through stores into a U64-typed view of what's actually a
1714    // Bool/Str/etc. cell — surfaces downstream as a "non-bool
1715    // type" pick panic.
1716    //
1717    // String-shape fragments carry full Polydat source whose LHS we
1718    // extract via `scan_locally_declared_idents`. Map-shape
1719    // fragments give the name directly.
1720    if let Some(rb) = op.result.as_ref() {
1721        rb.walk_fragments(|frag| match frag {
1722            nmbrs_workload::model::ResultFragment::Source(s) => {
1723                for n in scan_locally_declared_idents(s) {
1724                    if !body_locally_declared.contains(&n) && !referenced.iter().any(|r| r == &n) {
1725                        referenced.push(n);
1726                    }
1727                }
1728            }
1729            nmbrs_workload::model::ResultFragment::Named { name, .. } => {
1730                let n = name.to_string();
1731                if !body_locally_declared.contains(&n) && !referenced.iter().any(|r| r == &n) {
1732                    referenced.push(n);
1733                }
1734            }
1735        });
1736    }
1737
1738    // SRD-13f: parent-ref classification no longer gates
1739    // extern emission. The legacy "DynamicOutput without
1740    // shared" rejection assumed snapshot semantics for
1741    // non-shared cross-scope reads (SRD-13c §"Default:
1742    // Immutable Propagation"). SRD-13f reframes that rule:
1743    // the read invariant is uniform across all visible
1744    // parent outputs — inner reads return outer's current
1745    // value — and the construction-time wiring (cell
1746    // attachment for shared, per-cycle refresh for non-shared
1747    // pending the full cell mechanism in Push B.2) keeps the
1748    // invariant intact. No external pre-check needed.
1749
1750    // Emit extern decls only for names the op references and
1751    // that the parent provides. Lazy cascade — keeps the
1752    // op-template kernel narrow and makes the contract check
1753    // above crisp.
1754    for name in &referenced {
1755        if emitted.contains(name) {
1756            continue;
1757        }
1758        if body_locally_declared.contains(name) {
1759            continue;
1760        }
1761        // Names that are *Coordinate* inputs in the parent (the
1762        // implicit `cycle` and friends) must stay Coordinate in
1763        // the inner kernel too, so `set_inputs` propagates them
1764        // per cycle. An explicit `extern` declaration would force
1765        // IterationExtern classification and break propagation —
1766        // skip the explicit emit and let the inner kernel's auto-
1767        // extern path re-classify as Coordinate.
1768        let is_parent_coord = parent_kernel
1769            .program()
1770            .find_input(name)
1771            .and_then(|idx| parent_kernel.program().input_kind(idx))
1772            .is_some_and(|k| matches!(k, polydat::kernel::InputKind::Coordinate));
1773        if is_parent_coord {
1774            // The cascade still needs to record this as an
1775            // inherited name so `mark_inherited_outputs` includes
1776            // it — the inner kernel will re-publish it as an
1777            // (auto-extern) input/output and materialize_wiring_from_outer
1778            // will value-copy at construction time.
1779            inherited_names.push(name.clone());
1780            continue;
1781        }
1782        // Workload-param check goes BEFORE manifest cascade: a
1783        // workload param ALSO appears in the parent's manifest
1784        // (cascaded as an auto-output of an `extern <name>: …`
1785        // line in the for_each scope synthesiser), but op-template
1786        // bodies need it as a `final` literal so `init <name> =
1787        // <expr-using-param>` folds at compile time. Routing
1788        // through the manifest path emits `extern`, leaves init
1789        // unfolded, and the runtime sees `Value::None` in the
1790        // input slot — exactly the surface the Phase-9 op-template
1791        // kernel was hitting on dataset_prebuffer / query_count.
1792        if let Some(value) = workload_params.get(name) {
1793            // Chain-aware: a `set:` / `bindings:` scope above
1794            // us may have shadowed the workload-param default.
1795            // This was the root cause of the CQL prepared-
1796            // statement regression where `{ann_opts}` got
1797            // emitted as a `?` bind point — the op-template
1798            // kernel's local `const rerank_mode := "default"`
1799            // masked the SetParam shadow, and the downstream
1800            // `const ann_opts := select_str(str_eq(
1801            // rerank_mode, "pinned"), …)` folded against the
1802            // wrong rerank_mode value.
1803            crate::scope_synth::emit_workload_param_chain_aware(
1804                name,
1805                value,
1806                parent_kernel,
1807                &mut source,
1808                &mut emitted,
1809                None,
1810            );
1811        } else if let Some(entry) = manifest_by_name.get(name.as_str()) {
1812            let type_name = entry.port_type.to_keyword();
1813            source.push_str(&format!("extern {name}: {type_name}\n"));
1814            emitted.insert(name.clone());
1815            inherited_names.push(name.clone());
1816        } else if let Some(parent_idx) = parent_kernel.program().find_input(name) {
1817            // Parent INPUT — for non-Coordinate inputs (iteration
1818            // vars, external-write ports) emit an explicit `extern` so the
1819            // inner kernel's input classification matches the
1820            // parent's, and materialize_wiring_from_outer can value-copy or
1821            // shared-cell-attach. For Coordinate inputs (e.g. the
1822            // implicit `cycle` coord), DON'T emit — let the GK
1823            // auto-extern path classify them as Coordinate too,
1824            // so per-cycle `set_inputs` propagates to the inner
1825            // kernel. An explicit `extern` would force
1826            // IterationExtern and break that propagation.
1827            let kind = parent_kernel.program().input_kind(parent_idx);
1828            if !matches!(kind, Some(polydat::kernel::InputKind::Coordinate)) {
1829                let port_type = parent_kernel
1830                    .program()
1831                    .input_port_type(name)
1832                    .ok_or_else(|| {
1833                        format!(
1834                            "scope synthesis: parent input '{name}' has no \
1835                         declared PortType (find_input returned index {parent_idx} \
1836                         but input_port_type returned None — kernel program shape \
1837                         broken)"
1838                        )
1839                    })
1840                    .expect("input index just resolved must have a port type");
1841                let type_name = port_type.to_keyword();
1842                source.push_str(&format!("extern {name}: {type_name}\n"));
1843                emitted.insert(name.clone());
1844                inherited_names.push(name.clone());
1845            }
1846        }
1847    }
1848
1849    // SRD-13f Push A: workload params are root-level context
1850    // wires — they must appear on every scope's kernel program
1851    // as inlined constants (materialization gradient §"Inlined
1852    // constant"). The per-name loop above emits them as `final`
1853    // for body-referenced params; this cascade catches the rest
1854    // so every workload param lands on this op-template kernel
1855    // as a folded constant. The previous emission shape
1856    // (`extern X: type`) was wrong — it forced a runtime input
1857    // slot, which (a) prevented `const` bindings from folding
1858    // against the param's value at compile time and (b) routed
1859    // a compile-time-constant value through the runtime input
1860    // path. `final` is the correct materialization.
1861    for (name, value) in workload_params {
1862        // Chain-aware emission: honors any `set:` / `bindings:`
1863        // scope shadow above us. Without it, the op-template's
1864        // local `const NAME := <hashmap-default>` would mask
1865        // the shadow and break SRD-21's single-resolution-
1866        // surface invariant.
1867        crate::scope_synth::emit_workload_param_chain_aware(
1868            name,
1869            value,
1870            parent_kernel,
1871            &mut source,
1872            &mut emitted,
1873            None,
1874        );
1875    }
1876    if body_text.trim().is_empty() {
1877        // No own bindings — the kernel just re-exports parent.
1878        // The flatten-elision logic upstream should have caught
1879        // this, but defensively keep the kernel non-empty.
1880        if source.is_empty() {
1881            source.push_str("const __empty := 0\n");
1882        }
1883    } else {
1884        if !source.ends_with('\n') && !source.is_empty() {
1885            source.push('\n');
1886        }
1887        source.push_str(&body_text);
1888        if !source.ends_with('\n') {
1889            source.push('\n');
1890        }
1891    }
1892
1893    // SRD-67 Phase 3 — route op-template scope synthesis through
1894    // the SubcontextBuilder bridge. The Phase-9 op-template
1895    // kernel needs the same `compile_polydat_with_libs` knobs the
1896    // legacy direct call took (lib paths, strict, source dir,
1897    // context label); those flow through `CompileOptions`. The
1898    // bridge applies `mark_inherited_outputs` and
1899    // `materialize_wiring_from_outer` against the live parent so per-cycle
1900    // values reach the inner kernel's input slots; the trailing
1901    // `polydat::kernel::propagate_inputs` keeps cascade-extern'd inputs
1902    // flowing through (until Rule 4 / Rule 5 absorb them).
1903    let compile_options = polydat::kernel::subcontext::CompileOptions {
1904        workload_dir: workload_dir.map(|p| p.to_path_buf()),
1905        polydat_lib_paths,
1906        strict,
1907        required_outputs: Vec::new(),
1908        context_label: Some(context.to_string()),
1909        cursor_limit: None,
1910        kernel_opt,
1911        ..Default::default()
1912    };
1913
1914    // SRD-67 Phase 5 — fold the SRD-66 `result:` source through
1915    // `add_result_bindings`. The builder walks the source's free
1916    // identifiers, injects magic externs (`body` / `count` /
1917    // `ok`) it actually references, and registers each LHS as
1918    // an export. Rule 2 in finalize rewrites any LHS that
1919    // collides with a parent `shared` export into a write-
1920    // through; the kernel carries the bindings forward via
1921    // `set_write_throughs` so the per-cycle dispenser can
1922    // commit. Map-shape entries (already flattened to
1923    // `<name> := <source>` in the workload model) flow
1924    // through unchanged; path expressions surface as unbound-
1925    // identifier compile errors with the SRD-66 deferred-
1926    // structural-body-wire diagnostic.
1927    // SRD-66 result bindings + post-SRD-68 metric-value bindings.
1928    // Both routes feed the same closure-binding-economy walker
1929    // (`add_result_bindings`) which injects magic externs
1930    // (body/count/ok) for any of those names referenced from
1931    // either RHS. The walker then registers each LHS as a kernel
1932    // output the metrics wrapper / evaluator reads at cycle time
1933    // via `wires.get`.
1934    //
1935    // Metric-driven bindings use the `__metric_<name>` prefix so
1936    // they don't collide with user-declared output names and so
1937    // diagnostic output can filter them as internal. MetricsDispenser
1938    // reads the same `__metric_<name>` form at cycle time —
1939    // `synthesize_metric_binding_name` is the single source of
1940    // truth for the naming convention.
1941    let mut result_source: String = op
1942        .result
1943        .as_ref()
1944        .map(collect_result_bindings_source)
1945        .unwrap_or_default();
1946    if !op.metrics.is_empty() {
1947        // Stable ordering — matches `MetricsDispenser::wrap`'s
1948        // sort-by-name so synthesis order is reproducible.
1949        let mut entries: Vec<_> = op.metrics.iter().collect();
1950        entries.sort_by(|a, b| a.0.cmp(b.0));
1951        for (name, spec) in entries {
1952            let binding = synthesize_metric_binding_name(name);
1953            result_source.push_str(&format!("{binding} := {expr}\n", expr = spec.value));
1954            // Cell coordinates are reified the same way the value is: as
1955            // compiled kernel bindings walked by `add_result_bindings`, so a
1956            // coordinate expression gets its magic-extern slots and is
1957            // type-checked, rather than being a string assembled at runtime.
1958            // `BTreeMap` iteration keeps the emission order stable.
1959            for (dim, expr) in &spec.cell {
1960                let cell_binding = synthesize_cell_binding_name(name, dim);
1961                result_source.push_str(&format!("{cell_binding} := {expr}\n"));
1962            }
1963        }
1964    }
1965    // The op's own placement (`cell:` on the op): one coordinate binding per
1966    // dimension, compiled as a metric's coordinates are.
1967    for (dim, expr) in &op.cell {
1968        let cell_binding = synthesize_op_cell_binding_name(dim);
1969        result_source.push_str(&format!("{cell_binding} := {expr}\n"));
1970    }
1971    // Poll predicate. `poll.until:` lowers to the SAME binding name the
1972    // phase-level poll uses (`condition::UNTIL_BINDING`), in the op's own
1973    // kernel — so the poll wrapper reads one wire and never asks which kind of
1974    // node it is running under. Ordinary scoping does the rest: an op's
1975    // predicate shadows its phase's, as any other wire would.
1976    if let Some(until) = template_poll_until(op) {
1977        result_source.push_str(&format!(
1978            "{} := {until}\n",
1979            crate::wrappers::condition::UNTIL_BINDING,
1980        ));
1981    }
1982    // While-wrapper predicate. Synthesised as `__while := <expr>`
1983    // so `add_result_bindings` walks the expression, injects
1984    // magic externs for any captured wires it references, and
1985    // registers `__while` as a kernel output the WhileWrapper
1986    // reads at cycle time via the canonical pull plan.
1987    if let Some(while_expr) = op.while_cond.as_ref() {
1988        result_source.push_str(&format!(
1989            "{} := {expr}\n",
1990            crate::wrappers::r#while::BINDING_NAME,
1991            expr = while_expr,
1992        ));
1993    }
1994    let result_source: Option<String> = Some(result_source).filter(|s| !s.trim().is_empty());
1995
1996    if debug_scope_synth_enabled() {
1997        eprintln!(
1998            "=== OP SYNTH [{context}] inherited={inherited_names:?} parent_has_xval_input={:?} parent_manifest_has_xval={} ===\n{source}\n=== END ===",
1999            parent_kernel.program().find_input("xval"),
2000            manifest_by_name.contains_key("xval")
2001        );
2002    }
2003    // Built under the parent from source matter; the scope keeps the
2004    // finalized module, from which each fiber instantiates its per-op
2005    // kernel with the module's write-throughs. Strict mode refuses a
2006    // scope-init const that fell through to `None`
2007    // (composition_substrate.md L2.f).
2008    let synthesis_error = |e: String| format!("{context}: op-template scope synthesis: {e}");
2009    let mut matter = crate::scope_kernel::SourceMatter::source(context, source, compile_options)
2010        .inherited(inherited_names);
2011    if let Some(rb) = result_source {
2012        matter = matter.results(rb);
2013    }
2014    let kernel = crate::scope_kernel::ScopeKernel::synthesize_under(parent_kernel, matter)
2015        .map_err(synthesis_error)?;
2016
2017    // SRD-108 Part B — the interface's TYPE PROOF, at the same
2018    // place every other wire is type-checked: pre-map synthesis,
2019    // against the compiled op-template program. Load-time binder
2020    // checks were the early named errors; this is enforcement.
2021    if let Some(iface) = op.abstract_interface.as_ref() {
2022        verify_op_interface(iface, kernel.program().as_ref(), context)?;
2023    }
2024    Ok(kernel)
2025}
2026
2027/// SRD-108 Part B — verify a bound slot's interface against its
2028/// compiled op-template program:
2029///
2030/// - every `yields` name must exist on the program (a capture
2031///   extern slot or a declared output) with the declared type;
2032/// - every `needs` name the program declares as a slot must
2033///   carry the declared type (a need consumed only through
2034///   textual bind points declares no slot — the parent-chain
2035///   resolution type-checks those as usual).
2036///
2037/// Runs during pre-map synthesis — an interface violation fails
2038/// workload init, never a runtime critical section.
2039fn verify_op_interface(
2040    iface: &nmbrs_workload::model::OpInterface,
2041    program: &polydat::kernel::PolydatProgram,
2042    context: &str,
2043) -> Result<(), String> {
2044    let type_of = |name: &str| -> Option<polydat::ast::PortType> {
2045        program
2046            .input_port_type(name)
2047            .or_else(|| program.output_port_type(name))
2048    };
2049    // Yields: PRESENCE is the binder's load-time check (a capture
2050    // `as`-name); captures deliver through the wrapper stack's
2051    // wire writes, so a capture-only yield may hold no slot on
2052    // the op-template program itself. When a slot DOES
2053    // materialize (declared cast, binding reference), its type
2054    // must match the interface.
2055    for (name, declared) in &iface.yields {
2056        if let Some(actual) = type_of(name)
2057            && actual != *declared
2058        {
2059            return Err(format!(
2060                "{context}: interface yield '{name}' declares type \
2061                 {declared}, but the compiled op template carries \
2062                 {actual}"
2063            ));
2064        }
2065    }
2066    for (name, declared) in &iface.needs {
2067        if let Some(actual) = type_of(name)
2068            && actual != *declared
2069        {
2070            return Err(format!(
2071                "{context}: interface need '{name}' declares type \
2072                 {declared}, but the compiled op template carries \
2073                 {actual}"
2074            ));
2075        }
2076    }
2077    // Results (SRD-109 Part 3): the projection wire's slot is
2078    // DECLARED from the interface type at op-template build (see
2079    // the result-binding declaration pass), so the check here is
2080    // agreement when the slot materialized — a mismatch means
2081    // something else (a binding, a cast) claimed the name at a
2082    // different type.
2083    for (name, declared) in &iface.results {
2084        if let Some(actual) = type_of(name)
2085            && actual != *declared
2086        {
2087            return Err(format!(
2088                "{context}: interface results wire '{name}' declares \
2089                 type {declared}, but the compiled op template carries \
2090                 {actual}"
2091            ));
2092        }
2093    }
2094    Ok(())
2095}
2096
2097/// Internal binding name for a workload-declared metric's `value:`
2098/// expression. The metric's `value:` source is synthesised into the
2099/// op-template kernel as `<binding> := <expr>` so a single
2100/// closure-binding-economy walker handles slot allocation for
2101/// magic-extern references in both result-bindings AND
2102/// metric-value expressions. MetricsDispenser reads the same name
2103/// at cycle time via `ctx.wires.get` — the prefix keeps these
2104/// internal bindings from colliding with workload-declared output
2105/// names and lets diagnostic surfaces filter them out by prefix.
2106/// The `until:` expression from an op's `poll:` map, if it declared one.
2107///
2108/// Returns `None` for the `mode: await_empty` form, which waits for an
2109/// empty result.
2110fn template_poll_until(op: &nmbrs_workload::model::ParsedOp) -> Option<String> {
2111    op.params
2112        .get("poll")?
2113        .as_object()?
2114        .get("until")?
2115        .as_str()
2116        .map(|s| s.trim().to_string())
2117        .filter(|s| !s.is_empty())
2118}
2119
2120pub fn synthesize_metric_binding_name(metric_name: &str) -> String {
2121    format!("__metric_{metric_name}")
2122}
2123
2124/// The kernel wire a metric's cell COORDINATE is lowered to, per
2125/// (metric, dimension).
2126///
2127/// Keyed by metric as well as dimension because two metrics in one scope may
2128/// place into the same dimension by different expressions — `bytes_out` from
2129/// one captured column and `bytes_in` from another. A per-dimension name would
2130/// collide and one placement would silently win.
2131///
2132/// Same `__` convention as [`synthesize_metric_binding_name`]: it cannot
2133/// collide with an author-declared output, and diagnostics can filter it as
2134/// internal.
2135pub fn synthesize_cell_binding_name(metric_name: &str, dimension: &str) -> String {
2136    format!("__cell_{metric_name}__{dimension}")
2137}
2138
2139/// The kernel wire an OP's cell coordinate is lowered to, per dimension:
2140/// the placement of the op's own measurements (`cell:` on the op), as
2141/// [`synthesize_cell_binding_name`] is for one declared metric's.
2142///
2143/// A prefix of its own, so no metric name can produce the same wire.
2144pub fn synthesize_op_cell_binding_name(dimension: &str) -> String {
2145    format!("__opcell_{dimension}")
2146}
2147
2148/// The phase-kernel wire an **inline objective expression** is lowered to
2149/// (SRD-86). `optimize.objective` is either a bare wire reference (read
2150/// directly off the phase kernel) or an inline expression;
2151/// [`synthesize_phase_scope_bindings`] lowers the latter to
2152/// `volatile __objective := <expr>` so the optimizer reads exactly one wire
2153/// regardless of which form the author wrote. The `__` prefix keeps it from
2154/// colliding with author-declared outputs (same convention as
2155/// [`synthesize_metric_binding_name`]).
2156pub const OBJECTIVE_WIRE: &str = "__objective";
2157
2158/// Whether an `optimize.objective` value is a **bare wire reference** — a
2159/// single identifier read directly off the phase kernel — versus an **inline
2160/// expression** (operators, calls, dots, whitespace) that must be synthesized.
2161/// A bare reference is left untouched (no synthesis, current behavior); an
2162/// expression is lowered to [`OBJECTIVE_WIRE`].
2163pub fn objective_is_bare_wire(objective: &str) -> bool {
2164    let s = objective.trim();
2165    !s.is_empty()
2166        && s.chars()
2167            .next()
2168            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
2169        && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
2170}
2171
2172/// The phase-kernel wire the optimizer reads for `objective`: the bare name
2173/// itself, or the synthesized [`OBJECTIVE_WIRE`] for an inline expression.
2174/// Pairs with [`synthesize_phase_scope_bindings`], which emits the
2175/// `__objective` binding for the expression case — the two agree by sharing
2176/// [`objective_is_bare_wire`].
2177pub fn objective_wire(objective: &str) -> &str {
2178    if objective_is_bare_wire(objective) {
2179        objective.trim()
2180    } else {
2181        OBJECTIVE_WIRE
2182    }
2183}
2184
2185/// Flatten a [`nmbrs_workload::model::ResultSpec`] into a single
2186/// Polydat source string suitable for
2187/// [`polydat::kernel::subcontext::SubcontextBuilder::add_result_bindings`].
2188/// String-shape entries pass through verbatim; map-shape entries
2189/// emit `<name> := <source>` lines (the same projection the
2190/// SRD-66 schema specifies); list-shape entries recurse.
2191///
2192/// Path-expression and built-in short forms (`count` / `ok`) in
2193/// map-shape entries land as bare Polydat expressions — `count` and
2194/// `ok` resolve to the magic-extern wires
2195/// [`SubcontextBuilder::add_result_bindings`] injects, while
2196/// path expressions like `rows[0].field` produce an unbound-
2197/// identifier compile error. The latter surfaces SRD-66's
2198/// "path expressions deferred until structural-body wire lands"
2199/// diagnostic.
2200fn collect_result_bindings_source(spec: &nmbrs_workload::model::ResultSpec) -> String {
2201    let mut out = String::new();
2202    spec.walk_fragments(|frag| match frag {
2203        nmbrs_workload::model::ResultFragment::Source(src) => {
2204            out.push_str(src);
2205            if !src.ends_with('\n') {
2206                out.push('\n');
2207            }
2208        }
2209        nmbrs_workload::model::ResultFragment::Named { name, source } => {
2210            // Path expressions (`rows[*].key`, `result[0].id`) are
2211            // dispenser-evaluated (SRD-70) — they are not polydat
2212            // source and would fail the result-bindings compile.
2213            // Only `count` / `ok` (magic-extern references) and
2214            // polydat-call entries compile into the kernel.
2215            let s = source.trim();
2216            if s == "count" || s == "ok" || s.contains('(') {
2217                out.push_str(&format!("{name} := {source}\n"));
2218            }
2219        }
2220    });
2221    out
2222}
2223
2224// reason: cohesive scope builder — each argument is a distinct compile input
2225// (ops, iteration vars, outer manifest, workload params, …); grouping them
2226// into a struct would only relocate the same fields without adding clarity.
2227#[allow(clippy::too_many_arguments)]
2228pub fn build_scope(
2229    ops: &[ParsedOp],
2230    iteration_vars: &HashMap<String, String>,
2231    outer_manifest: &[crate::runner::ManifestEntry],
2232    workload_params: &HashMap<String, String>,
2233    phases: &HashMap<String, nmbrs_workload::model::WorkloadPhase>,
2234    phase_cycles: Option<&str>,
2235    exclude: &[String],
2236    // SRD-13f §"Wire-reference classification" — the parent
2237    // scope's compiled kernel. The synthesizer reads its
2238    // retained AST (for case 3 local-inclusion walks) and its
2239    // folded constant state (for case 1 promoted-final
2240    // emission). `None` for the workload-root build (it IS the
2241    // root; no parent).
2242    parent_kernel: Option<&crate::scope_kernel::ScopeKernel>,
2243) -> Result<BindingScope, String> {
2244    let mut scope = BindingScope::new();
2245
2246    // --- Step 1: Classify op bindings by origin ---
2247    //
2248    // The first op's PolydatSource is the "base" (inherited/phase-level).
2249    // Subsequent ops: if their PolydatSource matches the base exactly,
2250    // they're inherited duplicates. If different, they're op-level
2251    // augmentations carrying new bindings.
2252    let mut base_source: Option<String> = None;
2253
2254    for op in ops {
2255        if let BindingsDef::PolydatSource(src) = &op.bindings {
2256            let src = src.trim();
2257            if src.is_empty() {
2258                continue;
2259            }
2260
2261            match &base_source {
2262                None => {
2263                    // First op's source becomes the base — classified as Inherited
2264                    base_source = Some(src.to_string());
2265                    scope.ingest_polydat_source(src, BindingOrigin::Inherited);
2266                }
2267                Some(base) => {
2268                    if src == base.as_str() {
2269                        // Identical to base — inherited duplicate, skip.
2270                        // validate() and emit() handle dedup.
2271                    } else {
2272                        // Different from base — this op has its own bindings.
2273                        // Ingest the DIFFERENCE (lines not in base) as Op origin,
2274                        // and the shared lines as Inherited. Compare by
2275                        // *logical* lines so multi-line expressions
2276                        // (function calls broken over several physical
2277                        // lines) stay intact instead of being split at
2278                        // the paren and ingested piecewise.
2279                        let base_logical: Vec<String> = logical_lines(base)
2280                            .into_iter()
2281                            .map(|l| l.trim().to_string())
2282                            .filter(|l| !l.is_empty())
2283                            .collect();
2284                        for line in logical_lines(src) {
2285                            let trimmed = line.trim();
2286                            if trimmed.is_empty() {
2287                                continue;
2288                            }
2289                            if base_logical.iter().any(|b| b == trimmed) {
2290                                // This line is inherited — already ingested from base
2291                            } else {
2292                                // This line is op-specific
2293                                scope.ingest_polydat_source(
2294                                    trimmed,
2295                                    BindingOrigin::Op(op.name.clone()),
2296                                );
2297                            }
2298                        }
2299                    }
2300                }
2301            }
2302        }
2303    }
2304
2305    // --- Step 2: Add iteration variables ---
2306    //
2307    // Iter vars (own + cascade-inherited) are part of the
2308    // **scope's contract** — they're names a phase or a child
2309    // scope is allowed to consume. Mark them required so the
2310    // compiler's DCE keeps the auto-passthrough output that
2311    // `extern <name>` produces. Without this, an iter var
2312    // referenced only from a deeper structure (e.g. a relevancy
2313    // `k:` field, or a downstream do-while condition) would be
2314    // pruned and pull-by-name would fail.
2315    for (var, val) in iteration_vars {
2316        scope.add_iteration_var(var, val);
2317        scope.add_required_output(var);
2318    }
2319
2320    // --- Step 3: Generate auto-externs ---
2321    //
2322    // Names referenced in op templates but not defined in the scope
2323    // need extern declarations to wire to the outer kernel.
2324    let defined = scope.defined_names();
2325    let extern_names = scope.extern_names();
2326
2327    // Collect all referenced names from op templates AND
2328    // binding source RHS. Names referenced in either need
2329    // extern declarations so the Polydat compile path can wire
2330    // them. Without scanning bindings, a phase whose binding
2331    // RHS uses `{outer_name}` (e.g. `dim := vector_dim(
2332    // "{dataset}:{profile}")`) wouldn't get extern declarations
2333    // for `dataset` and `profile`, leaving the Polydat string
2334    // interpolation desugar to fail at compile time.
2335    let mut referenced: HashSet<String> = HashSet::new();
2336    for op in ops {
2337        for value in op.op.values() {
2338            if let Some(s) = value.as_str() {
2339                for name in nmbrs_workload::bindpoints::referenced_bindings(s)? {
2340                    referenced.insert(name);
2341                }
2342            }
2343        }
2344        if let Some(ref cond) = op.condition {
2345            let bare = cond
2346                .trim()
2347                .strip_prefix('{')
2348                .and_then(|s| s.strip_suffix('}'))
2349                .unwrap_or(cond.trim());
2350            referenced.insert(bare.to_string());
2351        }
2352        // `delay:` accepts the same shapes as `if:` — a bare
2353        // wire name (`delay: think_time`) or a `{...}` inline
2354        // expression. Both consume a binding and need to land
2355        // in `referenced` so the auto-extern + DCE-keepalive
2356        // passes provision them.
2357        if let Some(ref delay_spec) = op.delay {
2358            for raw in delay_spec.names() {
2359                let bare = raw
2360                    .trim()
2361                    .strip_prefix('{')
2362                    .and_then(|s| s.strip_suffix('}'))
2363                    .unwrap_or(raw.trim());
2364                referenced.insert(bare.to_string());
2365            }
2366        }
2367        // Bindings: scan Polydat source for `{name}` placeholders
2368        // that the Polydat string-interpolation desugar will treat
2369        // as wire references.
2370        if let BindingsDef::PolydatSource(src) = &op.bindings {
2371            collect_string_interp_refs(src, &mut referenced);
2372            // Also scan for bare identifiers used in binding
2373            // RHSs (e.g. `if(optimize_for == "LATENCY", …)`).
2374            // Without this, names like `optimize_for` flow
2375            // through to the Polydat compiler unresolved and get
2376            // auto-externed at the compiler's default type
2377            // (u64); `materialize_wiring_from_outer` then writes the
2378            // parent's Str value into the u64-typed slot, and
2379            // a `__u64_to_string` adapter inserted by type
2380            // dispatch panics at runtime on `as_u64()`. The
2381            // local-binding filter below mirrors the
2382            // build_op_template_scope_kernel cascade — names
2383            // declared by THIS scope's own bindings are
2384            // resolved locally, not externed.
2385            let body_locally_declared = scan_locally_declared_idents(src);
2386            for ident in scan_idents_in_polydat_source(src) {
2387                if !body_locally_declared.contains(&ident) {
2388                    referenced.insert(ident);
2389                }
2390            }
2391        }
2392        // Op params (`evaluations:`/`relevancy:`/`verify:`/...
2393        // hoisted by the workload parser) carry `{name}` bind-
2394        // point references too — `relevancy: { k: "{k}" }` is
2395        // a real consumer of the wire `k`, even though `k`
2396        // isn't on the op-template wire path. Without scanning
2397        // these, an iter var referenced *only* from param
2398        // config would fail to auto-extern from the parent
2399        // manifest, and runtime `pull(name)` calls for that
2400        // wire (e.g. `parse_count_param` on relevancy `k:`)
2401        // would panic with "unknown output variate".
2402        let mut param_refs: Vec<String> = Vec::new();
2403        crate::bindings::collect_param_bindings_into(&op.params, &[], &mut param_refs)?;
2404        for name in param_refs {
2405            referenced.insert(name);
2406        }
2407    }
2408
2409    // Check for final shadowing violations
2410    for entry in outer_manifest {
2411        if entry.modifier == polydat::dsl::ast::BindingModifier::CONST
2412            && defined.contains(&entry.name)
2413        {
2414            return Err(format!(
2415                "cannot shadow 'final' binding '{}' from outer scope",
2416                entry.name
2417            ));
2418        }
2419    }
2420
2421    // SRD-13f §"Wire-reference classification" — case 3 (local
2422    // matter inclusion). When the parent program is available
2423    // (AST mode), promote non-final referenced names from
2424    // cascade-via-extern (case 2) to inline-as-Inherited.
2425    //
2426    // Rules:
2427    // - `final` / `shared` outputs stay cascaded (case 2-like
2428    //   for now; promoted-final optimization is a follow-up).
2429    // - Cycle bindings / init bindings whose body lives in the
2430    //   parent's retained AST get pretty-printed and ingested as
2431    //   Inherited. Transitive dependencies (RHS Ident refs)
2432    //   walk the same rule via `local_inclusion_chain`.
2433    // - Names defined by `extern` ports in the parent stay
2434    //   cascaded.
2435    //
2436    // The auto-extern loop below then runs as-is and fills the
2437    // gap for names that didn't have an AST body to pull in.
2438    if let Some(parent_kernel_ref) = parent_kernel {
2439        let parent_prog = parent_kernel_ref.program();
2440        // Propagate the parent's coordinate input names into this
2441        // scope when it doesn't already have an `input ...: u64`
2442        // declaration of its own. Without this, an included
2443        // binding like `trip := testkit_throw_at(cycle, threshold, ...)`
2444        // references `cycle` but the auto-extern loop emits
2445        // `extern cycle: u64` (extern, not coord); set_inputs
2446        // propagation then skips it and per-cycle ticking dies.
2447        //
2448        // Coord names are just wire names the parent declared as
2449        // inputs; the child propagates them by declaring the
2450        // same `input ...: u64` line. Nothing special about any
2451        // specific name here.
2452        if scope.coordinates.is_none() {
2453            let coord_count = parent_prog.coord_count();
2454            if coord_count > 0 {
2455                let input_names = parent_prog.input_names();
2456                let coords: Vec<String> = input_names.into_iter().take(coord_count).collect();
2457                scope.coordinates = Some(format_input_decl_line(&coords).trim_end().to_string());
2458            }
2459        }
2460
2461        // Names already accounted for: defined locally, declared
2462        // extern in subscope, or iter-vars. The inclusion-chain
2463        // walker uses this as its termination boundary so it
2464        // doesn't re-emit names the scope already satisfies.
2465        // (Coord input names like the one the workload author
2466        // declared via `input ...: u64` are not special — the
2467        // chain walker's `binding_ast_for` returns `None` for
2468        // coord inputs since they aren't binding statements, so
2469        // they self-terminate without explicit handling here.)
2470        let mut already_satisfied: HashSet<String> = HashSet::new();
2471        already_satisfied.extend(defined.iter().cloned());
2472        already_satisfied.extend(extern_names.iter().cloned());
2473        for var in iteration_vars.keys() {
2474            already_satisfied.insert(var.clone());
2475        }
2476
2477        // Sort for determinism — HashSet iteration is randomised.
2478        // Clone names so the loop body can mutate `referenced`
2479        // (collecting transitive refs from included bindings).
2480        let mut refs_sorted: Vec<String> = referenced.iter().cloned().collect();
2481        refs_sorted.sort();
2482        for name in &refs_sorted {
2483            let name = name.as_str();
2484            if already_satisfied.contains(name) {
2485                continue;
2486            }
2487            let manifest_modifier = outer_manifest
2488                .iter()
2489                .find(|e| e.name == name)
2490                .map(|e| e.modifier);
2491            let is_workload_param = workload_params.contains_key(name);
2492            if let Some(m) = manifest_modifier {
2493                use polydat::dsl::ast::BindingModifier;
2494                if m == BindingModifier::SHARED {
2495                    // SHARED stays in the cascade path — cells
2496                    // synchronise across kernels at runtime via
2497                    // SharedCell, not via const inlining.
2498                    continue;
2499                }
2500                if m == BindingModifier::CONST {
2501                    // SRD-13f §"Materialization gradient" — inline
2502                    // as `const NAME := <literal>` only when the
2503                    // upstream value is **statically known**. Per
2504                    // SRD-11 §"Two Evaluation Lifecycles", the
2505                    // `const` modifier has two implementation
2506                    // paths: compile-fold (the producing node is
2507                    // replaced with a leaf const node, value is
2508                    // part of the compiled artifact and identical
2509                    // across every activation) vs. scope-init pull
2510                    // (when the binding's wire chain touches
2511                    // iteration externs, the producing node stays
2512                    // as the original computation node; the value
2513                    // is computed per scope activation and lives
2514                    // only for that activation per SRD-13c
2515                    // §"const").
2516                    //
2517                    // The cascaded source built here gets compiled
2518                    // and cached on the phase scope-tree node, so
2519                    // its lifetime is the workload run — longer
2520                    // than any single activation. Inlining a
2521                    // scope-init-pulled value would freeze the
2522                    // first activation's value into the cached
2523                    // program forever, breaking every subsequent
2524                    // iteration of an enclosing comprehension
2525                    // (the symptom: `const mode := sm` inside a
2526                    // `for_each sm in alpha, beta` reads `alpha`
2527                    // for both iters).
2528                    //
2529                    // SRD-11 §"Provenance-Based Invalidation"
2530                    // gives the discriminator at zero cost: a
2531                    // truly statically-known node has empty input
2532                    // provenance (it depends on no graph inputs);
2533                    // a passthrough or computation node has bits
2534                    // set for the input slots it reads. We inline
2535                    // only when provenance is empty; otherwise we
2536                    // fall through to the auto-extern cascade
2537                    // below so each activation re-pulls the value
2538                    // through the chain via
2539                    // `materialize_wiring_from_outer` Step 3.
2540                    let statically_known = parent_kernel_ref
2541                        .program()
2542                        .output_index(name)
2543                        .map(|out_idx| {
2544                            let (node_idx, _) =
2545                                parent_kernel_ref.program().resolve_output_by_index(out_idx);
2546                            parent_kernel_ref
2547                                .program()
2548                                .input_provenance_for(node_idx)
2549                                .is_none_or(|p| p.is_zero())
2550                        })
2551                        .unwrap_or(true);
2552                    if statically_known
2553                        && let Some(value) = parent_kernel_ref.lookup(name)
2554                        && let Some(natural) = value_to_param_string(&value)
2555                    {
2556                        scope.add_param_binding(name, &natural);
2557                        already_satisfied.insert(name.to_string());
2558                        continue;
2559                    }
2560                    continue;
2561                }
2562            }
2563            // SRD-21 §"Where workload-param values live in the
2564            // kernel chain" — workload params are stable for the
2565            // run but live in the params-kernel as folded
2566            // constants, not in the workload-root program itself.
2567            // `parent_kernel.lookup(name)` reads through the
2568            // chain-wired input slot value, so this promotion
2569            // gives us const-folded workload-param values inside
2570            // every descendant scope's program — same
2571            // effective semantics as the pre-SRD-21 design
2572            // without poisoning the workload-root with `final`
2573            // constants that would block scenario-tree
2574            // shadowing.
2575            if is_workload_param
2576                && let Some(value) = parent_kernel_ref.lookup(name)
2577                && let Some(natural) = value_to_param_string(&value)
2578            {
2579                scope.add_param_binding(name, &natural);
2580                already_satisfied.insert(name.to_string());
2581                continue;
2582            }
2583            // Pull the inclusion chain. If the name isn't in the
2584            // parent's AST (or it's a final/shared binding in
2585            // the AST), the chain is empty — the auto-extern
2586            // loop below handles those.
2587            let chain = parent_prog.local_inclusion_chain(name, &already_satisfied);
2588            if chain.is_empty() {
2589                continue;
2590            }
2591            // Pretty-print each Statement in topological order
2592            // and ingest as Inherited. Track bound names so the
2593            // chain walker and the auto-extern loop see them
2594            // satisfied locally. Walk each binding's RHS to
2595            // collect transitive refs into `referenced` — these
2596            // are the names the included binding's expression
2597            // mentions but doesn't define (e.g. parent `final`
2598            // values like `dataset`); the auto-extern loop below
2599            // then emits externs for them.
2600            for stmt in chain {
2601                let line = polydat::dsl::pprint::pp_statement(stmt);
2602                scope.ingest_polydat_source(&line, BindingOrigin::Inherited);
2603                let body = match stmt {
2604                    polydat::dsl::ast::Statement::Binding(b) => Some(&b.value),
2605                    _ => None,
2606                };
2607                if let Some(expr) = body {
2608                    polydat::dsl::collect_expr_references(expr, &mut referenced);
2609                }
2610                if let polydat::dsl::ast::Statement::Binding(b) = stmt {
2611                    for t in &b.targets {
2612                        already_satisfied.insert(t.clone());
2613                    }
2614                }
2615            }
2616        }
2617    }
2618
2619    // Refresh `defined` set after AST-mode inclusion may have
2620    // added Inherited bindings. The auto-extern loop below uses
2621    // this updated set to skip names now satisfied locally.
2622    let defined = scope.defined_names();
2623
2624    // Generate extern declarations for referenced-but-undefined names
2625    for entry in outer_manifest {
2626        let is_iter_var = iteration_vars.contains_key(&entry.name);
2627        if referenced.contains(&entry.name)
2628            && !defined.contains(&entry.name)
2629            && !extern_names.contains(&entry.name)
2630            && !is_iter_var
2631        {
2632            scope.add_extern(&entry.name, entry.port_type);
2633        }
2634    }
2635
2636    // SRD-13f §"Wire-reference classification" — case 4:
2637    // unresolved → synthesizer-level validation error. Fires
2638    // only on descendant scopes (parent_kernel is Some). The
2639    // workload-root build skips this check; the Polydat compiler's
2640    // auto-input-inference path handles unresolved refs there.
2641    //
2642    // A reference is resolved if any of: defined locally,
2643    // declared extern (in subscope or auto-extern'd from outer
2644    // manifest), an iteration variable, a workload param key,
2645    // a coord name on this scope, or in the outer manifest at
2646    // all. Anything else is a typo or missing upstream binding.
2647    if parent_kernel.is_some() {
2648        let defined_now = scope.defined_names();
2649        let extern_now = scope.extern_names();
2650        let mut satisfied: HashSet<String> = HashSet::new();
2651        satisfied.extend(defined_now);
2652        satisfied.extend(extern_now);
2653        for var in iteration_vars.keys() {
2654            satisfied.insert(var.clone());
2655        }
2656        for name in workload_params.keys() {
2657            satisfied.insert(name.clone());
2658        }
2659        for entry in outer_manifest {
2660            satisfied.insert(entry.name.clone());
2661        }
2662        // Coord names from this scope's `input ...: u64` line.
2663        if let Some(coords_line) = &scope.coordinates
2664            && let Some(rhs) = coords_line.split(":=").nth(1)
2665        {
2666            let inner = rhs.trim().trim_start_matches('(').trim_end_matches(')');
2667            for n in inner.split(',') {
2668                let n = n.trim();
2669                if !n.is_empty() {
2670                    satisfied.insert(n.to_string());
2671                }
2672            }
2673        }
2674        // `referenced` is built from a textual scan that catches
2675        // both wire refs and bare identifiers — including GK
2676        // function names like `mod`, `hash`, `range` that
2677        // appear in binding RHS as call heads. Filter those out
2678        // via `lookup`, which also answers for an overloaded
2679        // name such as `vec_dot`; only true wire references
2680        // should surface as unresolved.
2681        let mut unresolved: Vec<&String> = referenced
2682            .iter()
2683            .filter(|n| !satisfied.contains(n.as_str()))
2684            // Dotted names follow the field-access wire
2685            // convention (`q.cursor.idx` reads the wire
2686            // `q__cursor__idx`) — check the flattened spelling
2687            // the same way kernel lookup does.
2688            .filter(|n| !n.contains('.') || !satisfied.contains(n.replace('.', "__").as_str()))
2689            .filter(|n| !n.starts_with("__"))
2690            .filter(|n| polydat::dsl::registry::lookup(n).is_none())
2691            .collect();
2692        unresolved.sort();
2693        if !unresolved.is_empty() {
2694            let names: Vec<&str> = unresolved.iter().map(|s| s.as_str()).collect();
2695            let mut visible: Vec<&str> = satisfied.iter().map(|s| s.as_str()).collect();
2696            visible.sort();
2697            return Err(format!(
2698                "unresolved wire reference(s) {names:?}: not declared locally, \
2699                 not in parent manifest, not a workload param. \
2700                 Visible names in this scope: {visible:?}"
2701            ));
2702        }
2703    }
2704
2705    // --- Step 4: Workload param cascade as extern slots ---
2706    //
2707    // Workload params are not the workload-root's authority — the
2708    // params-kernel sits one level above this scope and owns the
2709    // `const NAME := <literal>` declarations. The workload-root
2710    // program declares each param as `extern NAME: T`, and the
2711    // materialize-wiring-from-outer step at kernel construction
2712    // time copies the value out of the params-kernel's output
2713    // into this scope's input slot. Lookup for a param at the
2714    // workload-root then resolves via the input slot rather than
2715    // an own-folded constant — which is precisely what makes a
2716    // SetParam scope-tree node inserted between params-kernel
2717    // and workload-root able to shadow the value: its own
2718    // `const NAME := <override>` becomes the closer
2719    // materialize-source. If we baked `const NAME := <literal>`
2720    // here at the workload-root, that local constant would mask
2721    // the input slot via the get_constant fast-path in
2722    // PolydatKernel::lookup, and no scope-tree-level shadow could
2723    // get through.
2724    //
2725    // Author-declared `final` in the workload's `bindings:`
2726    // block is unaffected — that source goes through
2727    // workload_level_polydat ingestion in build_workload_root_kernel
2728    // and keeps whatever modifier the author wrote. Only the
2729    // auto-cascade of the workload `params:` block changes
2730    // shape.
2731    //
2732    // Phase-level build_scope callers pass an empty
2733    // `workload_params`; their workload params arrive via the
2734    // parent-scope kernel's manifest auto-extern pass.
2735    //
2736    // SRD-13f Push D: sort by name so program build order is
2737    // deterministic across processes. HashMap iteration is
2738    // randomized per process (Rust default hasher).
2739    let defined = scope.defined_names(); // refresh after externs
2740    let mut params_sorted: Vec<(&String, &String)> = workload_params.iter().collect();
2741    params_sorted.sort_by(|a, b| a.0.cmp(b.0));
2742    for (name, value) in params_sorted {
2743        if defined.contains(name) {
2744            // Author already declared `name` in the workload's
2745            // own bindings block. Honor the author's declaration
2746            // (it carries whatever modifier they wrote) and skip
2747            // the auto-extern — declaring an extern with the
2748            // same name as a local binding would be a compile
2749            // error.
2750            continue;
2751        }
2752        scope.add_extern(name, workload_param_port_type(value));
2753        // Mark as required so DCE keeps the auto-passthrough
2754        // output. Descendant scopes auto-extern the param via
2755        // the workload-root manifest; if the workload-root's
2756        // own program prunes the param away, that cascade
2757        // breaks.
2758        scope.add_required_output(name);
2759    }
2760    // Also check phase config values for param refs
2761    for phase in phases.values() {
2762        if let Some(ref c) = phase.cycles
2763            && c.starts_with('{')
2764            && c.ends_with('}')
2765        {
2766            let name = &c[1..c.len() - 1];
2767            if workload_params.contains_key(name) && !scope.defined_names().contains(name) {
2768                scope.add_param_binding(name, &workload_params[name]);
2769            }
2770        }
2771    }
2772
2773    // --- Step 5: Inline expression extraction ---
2774    //
2775    // {{expr}} in op templates becomes __expr_N bindings.
2776    // (Note: the op template rewriting happens separately in the caller
2777    // since it mutates op fields, not the scope.)
2778    let mut inline_idx = 0usize;
2779    let mut expr_to_name: HashMap<String, String> = HashMap::new();
2780    let mut collect = |s: &str| -> Result<(), String> {
2781        for bp in nmbrs_workload::bindpoints::extract_bind_points(s)? {
2782            if let nmbrs_workload::bindpoints::BindPoint::InlineDefinition(ref expr) = bp
2783                && !expr_to_name.contains_key(expr)
2784            {
2785                let name = format!("__expr_{inline_idx}");
2786                inline_idx += 1;
2787                expr_to_name.insert(expr.clone(), name);
2788            }
2789        }
2790        Ok(())
2791    };
2792    for op in ops {
2793        for value in op.op.values() {
2794            if let Some(s) = value.as_str() {
2795                collect(s)?;
2796            }
2797        }
2798        // Inline expressions in `if:` and `delay:` count too —
2799        // those get hoisted out of `op.op` by the parser into
2800        // dedicated fields on `ParsedOp`.
2801        if let Some(s) = &op.condition {
2802            collect(s)?;
2803        }
2804        if let Some(spec) = &op.delay {
2805            for name in spec.names() {
2806                collect(name)?;
2807            }
2808        }
2809    }
2810    for (expr, name) in &expr_to_name {
2811        scope.add_inline_expr(name, expr);
2812    }
2813
2814    // --- Step 6: Collect required outputs ---
2815    for op in ops {
2816        for value in op.op.values() {
2817            if let Some(s) = value.as_str() {
2818                for name in nmbrs_workload::bindpoints::referenced_bindings(s)? {
2819                    if !exclude.contains(&name) {
2820                        scope.add_required_output(&name);
2821                    }
2822                }
2823            }
2824        }
2825        // Required-output collection for `if:` and `delay:`.
2826        //
2827        // The condition / delay value may be one of:
2828        //   1. `{{expr}}` — inline expression. Step 5 above
2829        //      synthesised a `__expr_N := expr` binding; the
2830        //      required output is that synthesised name.
2831        //   2. `{name}` — a single-brace binding reference.
2832        //   3. A bare identifier — legacy "name a binding"
2833        //      form, no braces.
2834        // The previous strip-one-pair-of-braces logic only
2835        // handled forms 2 and 3; for `{{expr}}` it produced a
2836        // half-stripped string `{expr}` that didn't match any
2837        // binding and let DCE drop the synthesised
2838        // `__expr_N`. Walk through `extract_bind_points` so
2839        // every form resolves to the right output name.
2840        let mut collect_required = |s: &str| -> Result<(), String> {
2841            let trimmed = s.trim();
2842            // Bracketed forms: `{{expr}}`, `{:=expr:=}`,
2843            // `{name}`, `{expr-with-operators}`.
2844            let bps = nmbrs_workload::bindpoints::extract_bind_points(trimmed)?;
2845            if !bps.is_empty() {
2846                for bp in bps {
2847                    match bp {
2848                        nmbrs_workload::bindpoints::BindPoint::InlineDefinition(expr) => {
2849                            if let Some(name) = expr_to_name.get(&expr)
2850                                && !exclude.contains(name)
2851                            {
2852                                scope.add_required_output(name);
2853                            }
2854                        }
2855                        nmbrs_workload::bindpoints::BindPoint::Reference { name, .. } => {
2856                            if !exclude.contains(&name) {
2857                                scope.add_required_output(&name);
2858                            }
2859                        }
2860                    }
2861                }
2862                return Ok(());
2863            }
2864            // Bare-identifier form (no braces) — legacy.
2865            if !trimmed.is_empty() && !exclude.contains(&trimmed.to_string()) {
2866                scope.add_required_output(trimmed);
2867            }
2868            Ok(())
2869        };
2870        if let Some(ref cond) = op.condition {
2871            collect_required(cond)?;
2872        }
2873        if let Some(ref delay_spec) = op.delay {
2874            for name in delay_spec.names() {
2875                collect_required(name)?;
2876            }
2877        }
2878        // SRD-40b §6: synthetic-metric `value:` references must
2879        // survive DCE so the dispenser's Polydat pull plan can resolve
2880        // them. Bare-name values (the SRD-40b §1 canonical form)
2881        // refer to a wire produced somewhere in scope; non-bare
2882        // expressions are deferred to Phase 9 elsewhere — for the
2883        // bare-name case we mark the wire required.
2884        for spec in op.metrics.values() {
2885            let trimmed = spec.value.trim();
2886            let bare =
2887                !trimmed.is_empty() && trimmed.chars().all(|c| c.is_alphanumeric() || c == '_');
2888            if bare && !exclude.contains(&trimmed.to_string()) {
2889                scope.add_required_output(trimmed);
2890            }
2891        }
2892        // SRD-40b §5 result-as-GK: each `result:` wire reads a
2893        // path expression off the response body and exposes it as
2894        // a Polydat wire. The wire's *name* is what subsequent
2895        // wrappers (metrics, validation) pull against — mark each
2896        // declared result wire as required so the kernel exposes
2897        // an extern slot for it on the post-execute write path.
2898        // SRD-66: result-wire names are already declared as
2899        // wires through the op's `bindings:` block (when the
2900        // workload uses `extern X: T` for shared-cell writes)
2901        // or are independent of the op-template kernel (when
2902        // the wire is consumed only by the result dispenser's
2903        // capture map). Marking them as required outputs here
2904        // would double-declare the `__port_*` for any name
2905        // that's also an extern, so the kernel-synthesis-side
2906        // wiring is left to Push 2's full kernel-driven path
2907        // (the SRD-66 §"Compilation lifecycle" closure-binding
2908        // rule). This branch intentionally does nothing for now.
2909        let _ = op.result.as_ref();
2910        crate::bindings::collect_param_bindings_into(
2911            &op.params,
2912            exclude,
2913            &mut scope.required_outputs,
2914        )?;
2915    }
2916
2917    // Config refs (from cycles={expr})
2918    if let Some(cycles_spec) = phase_cycles
2919        && cycles_spec.starts_with('{')
2920        && cycles_spec.ends_with('}')
2921    {
2922        let mut inner = cycles_spec[1..cycles_spec.len() - 1].to_string();
2923        for (v, val) in iteration_vars {
2924            inner = inner.replace(&format!("{{{v}}}"), val);
2925        }
2926        inner = crate::runner::expand_workload_params(&inner, workload_params);
2927        scope.add_config_ref(&inner);
2928    }
2929
2930    Ok(scope)
2931}
2932
2933/// Apply iteration-variable substitution to *op-template
2934/// strings only* — `raw:`, `prepared:`, `stmt:`, etc.
2935///
2936/// Iter vars flow into Polydat binding source as wires (declared as
2937/// externs by `BindingScope::add_iteration_var` and bound at
2938/// runtime via the standard input mechanism), so this helper
2939/// **does not** touch `op.bindings`. It only rewrites the
2940/// op-template field values, where `{var}` placeholders refer
2941/// to structural elements (table names, keyspace names,
2942/// optimize-for hints) that adapters need as literal text —
2943/// not as bind variables. CQL's `prepared:` form, for example,
2944/// converts every remaining `{name}` in the statement to a `?`
2945/// bind marker; iter vars in structural positions (`INSERT
2946/// INTO ks.{table} ...`) must be substituted away before that
2947/// conversion runs, since CQL doesn't permit `?` for table
2948/// names.
2949/// SRD-68 Push 5c — validate-only walk. Covers the same
2950/// placeholders as the substitution described above but DOES NOT
2951/// mutate the op strings. Walks every `{name}` placeholder in the ops' op fields
2952/// and op-level params, accumulating diagnostics for unresolved
2953/// references; returns `Result<(), String>` describing any
2954/// unresolved bindpoints.
2955///
2956/// Used at phase activation as the single workload-load-time
2957/// validation step. Adapters now do their own cycle-time
2958/// resolution (CQL: construction-time structural via
2959/// `canonical_kernel.lookup` + cycle-time per-cycle via
2960/// `WireSource::get`; non-CQL: cycle-time via
2961/// `synthesis::resolve_cached →
2962/// substitute_bind_points_with_state` against `main_kernel`).
2963/// Mutation of the workload model is no longer load-bearing —
2964/// only the diagnostic surface is.
2965///
2966/// `enclosing` are the programs of the scopes around the phase — the
2967/// current parent and every installed ancestor. A name one of them
2968/// BINDS (a per-cycle workload or scenario binding, not a folded
2969/// constant) resolves nowhere now, yet the phase scope pulls its
2970/// binding in as local matter (`local_inclusion_chain`, SRD-13f case
2971/// 3), so it is per-cycle here exactly like a phase-declared one.
2972pub fn validate_placeholders_via_kernel(
2973    ops: &[ParsedOp],
2974    kernel: &dyn polydat::Kernel,
2975    enclosing: &[&polydat::kernel::PolydatProgram],
2976) -> Result<(), String> {
2977    let mut per_cycle_names = collect_phase_binding_lhs_names(ops);
2978    let nothing_excluded = HashSet::new();
2979    for name in collect_op_placeholder_names(ops)? {
2980        if !per_cycle_names.contains(&name)
2981            && enclosing.iter().any(|program| {
2982                !program
2983                    .local_inclusion_chain(&name, &nothing_excluded)
2984                    .is_empty()
2985            })
2986        {
2987            per_cycle_names.push(name);
2988        }
2989    }
2990
2991    let mut errors: Vec<String> = Vec::new();
2992    let in_scope = || -> Vec<String> {
2993        let mut names: Vec<String> = kernel.output_names();
2994        for n in kernel.input_names() {
2995            if !names.contains(&n) {
2996                names.push(n);
2997            }
2998        }
2999        names.sort();
3000        names
3001    };
3002    for op in ops.iter() {
3003        let op_name = op.name.clone();
3004        for (key, value) in op.op.iter() {
3005            let path = format!("op '{op_name}' field '{key}'");
3006            // Clone-then-discard: `resolve_placeholders_in_json`
3007            // requires `&mut serde_json::Value` but we don't
3008            // care about its mutations — only the `errors` it
3009            // accumulates. The clone is shallow per JSON value
3010            // and runs once per field at workload-load time.
3011            let mut throwaway = value.clone();
3012            resolve_placeholders_in_json(
3013                &mut throwaway,
3014                kernel,
3015                &per_cycle_names,
3016                &path,
3017                &mut errors,
3018            );
3019        }
3020        for (key, value) in op.params.iter() {
3021            if key == "gutter" {
3022                continue; // runtime-resolved templates (see the mutable pass below)
3023            }
3024            let path = format!("op '{op_name}' param '{key}'");
3025            let mut throwaway = value.clone();
3026            resolve_placeholders_in_json(
3027                &mut throwaway,
3028                kernel,
3029                &per_cycle_names,
3030                &path,
3031                &mut errors,
3032            );
3033        }
3034    }
3035
3036    if errors.is_empty() {
3037        return Ok(());
3038    }
3039    let in_scope_str = in_scope().join(", ");
3040    let mut out =
3041        String::from("placeholder resolution failed (single read path: Polydat Kernel lookup):\n");
3042    for e in &errors {
3043        out.push_str("  - ");
3044        out.push_str(e);
3045        out.push('\n');
3046    }
3047    out.push_str(&format!(
3048        "  in-scope names at this kernel: [{in_scope_str}]"
3049    ));
3050    Err(out)
3051}
3052
3053/// SRD-68 Push 5c — resolve `{name}` placeholders in a single
3054/// op's `params` against `kernel`. Used by validation wrappers
3055/// at construction time to pre-resolve config like `relevancy.k`
3056/// = `"{k}"` against their dispenser's canonical kernel, so the
3057/// downstream spec parsers see a literal value (`10`) rather
3058/// than a surviving placeholder string.
3059///
3060/// Per-cycle binding LHS names pass through unchanged — the
3061/// wrapper resolves those via wires at cycle time (e.g.
3062/// `relevancy.expected = "{ground_truth}"` stays as-is so the
3063/// wrapper can register it on the fixture's pull plan and
3064/// read it per cycle).
3065///
3066/// Single-op variant of the legacy bulk-mutation pass; the
3067/// per-template granularity lets each wrapper resolve against
3068/// its own dispenser's canonical kernel rather than a shared
3069/// activity-layer parent.
3070pub fn resolve_placeholders_in_op_params(
3071    op: &mut ParsedOp,
3072    kernel: &dyn polydat::Kernel,
3073) -> Result<(), String> {
3074    let per_cycle_names = collect_phase_binding_lhs_names(std::slice::from_ref(op));
3075
3076    let mut errors: Vec<String> = Vec::new();
3077    let in_scope = || -> Vec<String> {
3078        let mut names: Vec<String> = kernel.output_names();
3079        for n in kernel.input_names() {
3080            if !names.contains(&n) {
3081                names.push(n);
3082            }
3083        }
3084        names.sort();
3085        names
3086    };
3087    let op_name = op.name.clone();
3088    for (key, value) in op.params.iter_mut() {
3089        // `gutter:` templates resolve at RUNTIME — during-forms per op
3090        // completion on the fiber wires, `final:` at phase end with a
3091        // status-metric fallback (`{recall}`, `{latency_p50}`) that has
3092        // no kernel presence here. Unresolved names degrade to visible
3093        // literal text in the cell, so the strict pre-resolution pass
3094        // must not reject them.
3095        if key == "gutter" {
3096            continue;
3097        }
3098        let path = format!("op '{op_name}' param '{key}'");
3099        resolve_placeholders_in_json(value, kernel, &per_cycle_names, &path, &mut errors);
3100    }
3101    if errors.is_empty() {
3102        return Ok(());
3103    }
3104    let in_scope_str = in_scope().join(", ");
3105    let mut out = String::from("param-placeholder resolution failed:\n");
3106    for e in &errors {
3107        out.push_str("  - ");
3108        out.push_str(e);
3109        out.push('\n');
3110    }
3111    out.push_str(&format!(
3112        "  in-scope names at this kernel: [{in_scope_str}]"
3113    ));
3114    Err(out)
3115}
3116
3117// SRD-68 Push 5 cleanup: the legacy
3118// `resolve_placeholders_via_kernel` (op-field text mutation) and
3119// `resolve_placeholders_in_params_only` (bulk op-params mutation)
3120// are both retired. The executor calls
3121// [`validate_placeholders_via_kernel`] (pure walker) at workload
3122// load to surface unresolved-bindpoint diagnostics; adapters
3123// resolve op-field placeholders themselves at construction (CQL
3124// prepared via `resolve_structural_and_mark_remaining`) or at
3125// cycle time (CQL raw via `substitute_via_wires`); validation
3126// wrappers resolve their own op.params at construction via
3127// [`resolve_placeholders_in_op_params`] against the dispenser's
3128// own canonical kernel. The workload model is no longer mutated
3129// — `OpDispenser::describe()` returns pristine yaml.
3130
3131/// Scan `ops`' `bindings:` text for the LHS names that get
3132/// produced as per-cycle wires. The scan is intentionally
3133/// liberal (LHS can be `cursor q = …`, `init x = …`, `name :=
3134/// expr`, `extern n: type`, `const n := expr`, `shared n := expr`,
3135/// destructured `(a, b) := …`). Anything that survives the LHS
3136/// strip becomes a known name; the substitution path uses this
3137/// set to distinguish "per-cycle wire — leave for the dispenser"
3138/// from "typo or missing cascade — error."
3139/// Every `{name}` placeholder the ops' fields and params reference.
3140/// Fails on a malformed bind point.
3141fn collect_op_placeholder_names(ops: &[ParsedOp]) -> Result<Vec<String>, String> {
3142    fn walk(value: &serde_json::Value, out: &mut Vec<String>) -> Result<(), String> {
3143        match value {
3144            serde_json::Value::String(s) => {
3145                for name in nmbrs_workload::bindpoints::referenced_bindings(s)? {
3146                    if !out.contains(&name) {
3147                        out.push(name);
3148                    }
3149                }
3150                Ok(())
3151            }
3152            serde_json::Value::Array(items) => items.iter().try_for_each(|v| walk(v, out)),
3153            serde_json::Value::Object(map) => map.values().try_for_each(|v| walk(v, out)),
3154            _ => Ok(()),
3155        }
3156    }
3157    let mut out = Vec::new();
3158    for op in ops {
3159        op.op
3160            .values()
3161            .chain(op.params.values())
3162            .try_for_each(|v| walk(v, &mut out))
3163            .map_err(|e| format!("op '{}': {e}", op.name))?;
3164    }
3165    Ok(out)
3166}
3167
3168fn collect_phase_binding_lhs_names(ops: &[ParsedOp]) -> Vec<String> {
3169    let mut out: Vec<String> = Vec::new();
3170    for op in ops {
3171        if let BindingsDef::PolydatSource(src) = &op.bindings {
3172            for line in logical_lines(src) {
3173                let trimmed = line.trim();
3174                if trimmed.is_empty() || trimmed.starts_with('#') {
3175                    continue;
3176                }
3177                // `input` declarations declare per-cycle wire names
3178                // by definition — the runtime sets them per
3179                // iteration. Both surface forms are handled:
3180                //   input cycle: u64
3181                //   input (cycle: u64, q: f64)
3182                // Without this, `{cycle}` in op templates would
3183                // resolve at compile time against the kernel's
3184                // initial value (0) instead of being deferred to
3185                // per-iteration substitution.
3186                if let Some(rest) = trimmed.strip_prefix("input ") {
3187                    let rest = rest.trim();
3188                    if let Some(inner) = rest.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
3189                        for piece in inner.split(',') {
3190                            let n = piece.trim().split(':').next().unwrap_or("").trim();
3191                            if is_bare_ident(n) && !out.contains(&n.to_string()) {
3192                                out.push(n.to_string());
3193                            }
3194                        }
3195                    } else {
3196                        let n = rest.split(':').next().unwrap_or("").trim();
3197                        if is_bare_ident(n) && !out.contains(&n.to_string()) {
3198                            out.push(n.to_string());
3199                        }
3200                    }
3201                    continue;
3202                }
3203                let lhs_end = trimmed
3204                    .find(":=")
3205                    .or_else(|| trimmed.find('='))
3206                    .unwrap_or(trimmed.len());
3207                let mut lhs = &trimmed[..lhs_end];
3208                // Strip ALL leading wire-coloring modifiers in
3209                // any order. `volatile final` and `final shared`
3210                // both need their bare name extracted, and any
3211                // future modifier added to the SRD-10 set must
3212                // appear here too.
3213                loop {
3214                    let mut matched = false;
3215                    for prefix in [
3216                        "cursor ",
3217                        "init ",
3218                        "extern ",
3219                        "const ",
3220                        "final ",
3221                        "shared ",
3222                        "volatile ",
3223                        "private ",
3224                    ] {
3225                        if let Some(stripped) = lhs.strip_prefix(prefix) {
3226                            lhs = stripped.trim();
3227                            matched = true;
3228                            break;
3229                        }
3230                    }
3231                    if !matched {
3232                        break;
3233                    }
3234                }
3235                let lhs = lhs.trim();
3236                // Destructured tuple LHS: (a, b, c) := ...
3237                if let Some(inner) = lhs.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
3238                    for piece in inner.split(',') {
3239                        let n = piece.trim().trim_end_matches(':').trim();
3240                        if is_bare_ident(n) && !out.contains(&n.to_string()) {
3241                            out.push(n.to_string());
3242                        }
3243                    }
3244                    continue;
3245                }
3246                // Type-annotated single LHS: `name: type`.
3247                let bare = lhs.split(':').next().unwrap_or(lhs).trim();
3248                if is_bare_ident(bare) && !out.contains(&bare.to_string()) {
3249                    out.push(bare.to_string());
3250                }
3251            }
3252        }
3253    }
3254    out
3255}
3256
3257fn is_bare_ident(s: &str) -> bool {
3258    let mut chars = s.chars();
3259    match chars.next() {
3260        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
3261        _ => return false,
3262    }
3263    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
3264}
3265
3266/// True iff `s` is a polydat string literal — opens with `"`,
3267/// closes with `"`, and (conservatively) contains no
3268/// unescaped closing quote in the middle. This is the shape
3269/// `format_jval_as_polydat_literal` produces for YAML strings
3270/// (`"hello"`) so the param-binding classifier can pass it
3271/// through without re-quoting.
3272fn is_polydat_quoted_string(s: &str) -> bool {
3273    if s.len() < 2 {
3274        return false;
3275    }
3276    if !s.starts_with('"') || !s.ends_with('"') {
3277        return false;
3278    }
3279    // Walk the inner span; reject if we find an unescaped `"`
3280    // before the final character (which would mean the outer
3281    // quotes don't actually pair).
3282    let bytes = s.as_bytes();
3283    let mut i = 1;
3284    let last = bytes.len() - 1;
3285    while i < last {
3286        if bytes[i] == b'\\' {
3287            i += 2;
3288            continue;
3289        }
3290        if bytes[i] == b'"' {
3291            return false;
3292        }
3293        i += 1;
3294    }
3295    true
3296}
3297
3298/// True iff `s` looks like a polydat array literal: `[` …
3299/// matched brackets … `]`. Conservative — we don't validate
3300/// the elements here; the polydat parser handles that when
3301/// the `const X := [...]` line compiles. The check just
3302/// distinguishes "this is already polydat array syntax" from
3303/// "this is a raw string that happens to contain brackets".
3304fn is_polydat_array_literal(s: &str) -> bool {
3305    if !s.starts_with('[') || !s.ends_with(']') {
3306        return false;
3307    }
3308    let mut depth: i32 = 0;
3309    let mut in_string = false;
3310    let mut escape = false;
3311    for c in s.chars() {
3312        if escape {
3313            escape = false;
3314            continue;
3315        }
3316        if in_string {
3317            if c == '\\' {
3318                escape = true;
3319            } else if c == '"' {
3320                in_string = false;
3321            }
3322            continue;
3323        }
3324        match c {
3325            '"' => in_string = true,
3326            '[' => depth += 1,
3327            ']' => {
3328                depth -= 1;
3329                if depth < 0 {
3330                    return false;
3331                }
3332            }
3333            _ => {}
3334        }
3335    }
3336    depth == 0
3337}
3338
3339#[cfg(test)]
3340mod polydat_param_classifier_tests {
3341    use super::*;
3342
3343    #[test]
3344    fn scan_idents_skips_hash_comments() {
3345        // `#` is a YAML-style line comment in Polydat (dsl/lexer.rs).
3346        // The ident scanner must skip it too, or comment words leak in
3347        // as phantom wire references (regression: finalize_index's
3348        // bindings comments).
3349        let src = "# Forwarding bindings: allow-list = bindings + params\n\
3350                   pct := mul(active, 2)  # trailing comment with words\n";
3351        let idents = scan_idents_in_polydat_source(src);
3352        assert!(
3353            idents.contains("active"),
3354            "real ident must be found: {idents:?}"
3355        );
3356        for word in [
3357            "Forwarding",
3358            "bindings",
3359            "allow",
3360            "list",
3361            "params",
3362            "trailing",
3363            "comment",
3364            "words",
3365        ] {
3366            assert!(
3367                !idents.contains(word),
3368                "comment word '{word}' must not be scanned as a wire ref: {idents:?}"
3369            );
3370        }
3371    }
3372
3373    #[test]
3374    fn scan_idents_skips_block_conditional_keywords() {
3375        // Block-form conditional selection puts bare `if` / `else` in expression
3376        // position. This scanner is textual, so without the keyword entries they were
3377        // emitted as wire references and the phase failed with
3378        // `unresolved wire reference(s) ["else", "if"]` (regression: finalize_index's
3379        // seg_mib_mean binding).
3380        let src = "seg_mib_mean := if segments > 0 { total / max(segments, 1) } else { 0 }\n";
3381        let idents = scan_idents_in_polydat_source(src);
3382        assert!(
3383            idents.contains("segments"),
3384            "real wire must still be found: {idents:?}"
3385        );
3386        assert!(
3387            idents.contains("total"),
3388            "real wire must still be found: {idents:?}"
3389        );
3390        for kw in ["if", "else"] {
3391            assert!(
3392                !idents.contains(kw),
3393                "conditional keyword '{kw}' must not scan as a wire ref: {idents:?}"
3394            );
3395        }
3396    }
3397
3398    #[test]
3399    fn scan_locally_declared_skips_hash_comment_lines() {
3400        let src = "# total = sum of parts\n\
3401                   shared sstables := 0\n";
3402        let decls = scan_locally_declared_idents(src);
3403        assert!(decls.contains("sstables"));
3404        // `# total = ...` has an `=`; it must not be parsed as a decl.
3405        assert!(
3406            !decls.contains("total"),
3407            "comment LHS must not declare: {decls:?}"
3408        );
3409    }
3410
3411    #[test]
3412    fn bare_identifier_classifier_accepts_idents_and_rejects_other_shapes() {
3413        assert!(is_bare_ident("sm"));
3414        assert!(is_bare_ident("source_model"));
3415        assert!(is_bare_ident("k_values"));
3416        assert!(is_bare_ident("_underscore"));
3417        assert!(is_bare_ident("a1"));
3418        // Rejects strings that don't fit the ident grammar.
3419        assert!(!is_bare_ident(""));
3420        assert!(!is_bare_ident("1abc"), "ident can't start with digit");
3421        assert!(!is_bare_ident("foo bar"), "no spaces");
3422        assert!(!is_bare_ident("[a, b]"));
3423        assert!(!is_bare_ident("\"quoted\""));
3424        assert!(!is_bare_ident("foo+bar"));
3425        // Reserved-ish keywords stay valid as identifiers here;
3426        // the polydat parser is the authority on what's
3427        // reserved.
3428        assert!(is_bare_ident("true"));
3429        assert!(is_bare_ident("false"));
3430    }
3431
3432    #[test]
3433    fn polydat_quoted_string_accepts_paired_quotes_only() {
3434        assert!(is_polydat_quoted_string("\"hello\""));
3435        assert!(is_polydat_quoted_string("\"\""));
3436        assert!(is_polydat_quoted_string("\"with \\\"escaped\\\" inner\""));
3437        // Rejects shapes that aren't paired-quote.
3438        assert!(!is_polydat_quoted_string("hello"));
3439        assert!(!is_polydat_quoted_string("\"open-only"));
3440        assert!(!is_polydat_quoted_string("close-only\""));
3441        assert!(!is_polydat_quoted_string(""));
3442        assert!(!is_polydat_quoted_string("\""));
3443    }
3444
3445    #[test]
3446    fn polydat_array_literal_balances_brackets() {
3447        assert!(is_polydat_array_literal("[1, 2, 3]"));
3448        assert!(is_polydat_array_literal("[]"));
3449        assert!(
3450            is_polydat_array_literal("[[1, 2], [3, 4]]"),
3451            "nested arrays balance"
3452        );
3453        assert!(is_polydat_array_literal("[\"a\", \"b\"]"));
3454        // Strings containing `]` don't break the count.
3455        assert!(is_polydat_array_literal("[\"a]b\", \"c\"]"));
3456        // Rejects unbalanced shapes.
3457        assert!(!is_polydat_array_literal("[1, 2"));
3458        assert!(!is_polydat_array_literal("1, 2]"));
3459        // `[1][2]` passes the conservative shape check (depth
3460        // returns to zero) — polydat's parser rejects it
3461        // downstream as invalid syntax. The classifier is a
3462        // routing heuristic, not a validator.
3463    }
3464}
3465
3466/// Recursively walk a JSON value and resolve every `{name}`
3467/// placeholder via [`KernelLookup`](polydat::kernel::interp::KernelLookup). Non-resolving names
3468/// that are in the per-cycle binding set stay as-is (the
3469/// dispenser will resolve them at execute time); anything else
3470/// gets pushed onto `errors`.
3471///
3472/// Object keys are *not* rewritten — keys are the closed-vocab
3473/// field name surface, distinct from the value-bearing
3474/// placeholders.
3475fn resolve_placeholders_in_json(
3476    value: &mut serde_json::Value,
3477    kernel: &dyn polydat::Kernel,
3478    per_cycle_names: &[String],
3479    field_path: &str,
3480    errors: &mut Vec<String>,
3481) {
3482    match value {
3483        serde_json::Value::String(s) => {
3484            match resolve_placeholders_in_string(s, kernel, per_cycle_names, field_path) {
3485                Ok(out) => *value = serde_json::Value::String(out),
3486                Err(es) => errors.extend(es),
3487            }
3488        }
3489        serde_json::Value::Array(arr) => {
3490            for (i, v) in arr.iter_mut().enumerate() {
3491                let p = format!("{field_path}[{i}]");
3492                resolve_placeholders_in_json(v, kernel, per_cycle_names, &p, errors);
3493            }
3494        }
3495        serde_json::Value::Object(map) => {
3496            for (k, v) in map.iter_mut() {
3497                let p = format!("{field_path}.{k}");
3498                resolve_placeholders_in_json(v, kernel, per_cycle_names, &p, errors);
3499            }
3500        }
3501        _ => {}
3502    }
3503}
3504
3505/// Walk one string, replace each `{name}` placeholder with the
3506/// kernel's `lookup` result for `name`. Bare-ident-only — the
3507/// qualified `{bind:…}` / `{capture:…}` / `{input:…}` /
3508/// `{param:…}` shapes and the inline `{{expr}}` shape pass
3509/// through untouched (consumed downstream by the dispenser /
3510/// inline-expression desugar). Names that fall through to the
3511/// per-cycle binding set also pass through. Anything else is
3512/// returned as an error in the `Err` Vec, with the field path
3513/// for context.
3514fn resolve_placeholders_in_string(
3515    s: &str,
3516    kernel: &dyn polydat::Kernel,
3517    per_cycle_names: &[String],
3518    field_path: &str,
3519) -> Result<String, Vec<String>> {
3520    let bytes = s.as_bytes();
3521    let n = bytes.len();
3522    let mut out = String::with_capacity(n);
3523    let mut errors: Vec<String> = Vec::new();
3524    let mut i = 0;
3525    while i < n {
3526        // `\{` and `\}` are escapes — passthrough one char.
3527        if bytes[i] == b'\\' && i + 1 < n && (bytes[i + 1] == b'{' || bytes[i + 1] == b'}') {
3528            out.push(bytes[i] as char);
3529            out.push(bytes[i + 1] as char);
3530            i += 2;
3531            continue;
3532        }
3533        // `{{ ... }}` is an inline expression — passthrough.
3534        if i + 1 < n && bytes[i] == b'{' && bytes[i + 1] == b'{' {
3535            // Find the matching `}}`.
3536            let start = i;
3537            let mut j = i + 2;
3538            while j + 1 < n && !(bytes[j] == b'}' && bytes[j + 1] == b'}') {
3539                j += 1;
3540            }
3541            let end = (j + 2).min(n);
3542            out.push_str(&s[start..end]);
3543            i = end;
3544            continue;
3545        }
3546        if bytes[i] != b'{' {
3547            out.push(bytes[i] as char);
3548            i += 1;
3549            continue;
3550        }
3551        // Find the matching `}` for this `{`.
3552        let body_start = i + 1;
3553        let mut j = body_start;
3554        while j < n && bytes[j] != b'}' {
3555            j += 1;
3556        }
3557        if j >= n {
3558            // Unterminated `{` — treat as literal char and move on.
3559            out.push('{');
3560            i += 1;
3561            continue;
3562        }
3563        let body = &s[body_start..j];
3564        let after = j + 1;
3565
3566        // Qualified references stay as-is for downstream.
3567        if body.contains(':') {
3568            out.push('{');
3569            out.push_str(body);
3570            out.push('}');
3571            i = after;
3572            continue;
3573        }
3574
3575        // Empty body — leave as-is, validator catches.
3576        if body.is_empty() {
3577            out.push('{');
3578            out.push_str(body);
3579            out.push('}');
3580            i = after;
3581            continue;
3582        }
3583
3584        // Not a bare identifier — pass through (could be a format spec).
3585        if !is_bare_ident(body) {
3586            out.push('{');
3587            out.push_str(body);
3588            out.push('}');
3589            i = after;
3590            continue;
3591        }
3592
3593        // Names that are per-cycle (coordinates declared via
3594        // `input (cycle: u64, ...: u64)`, or LHS of phase bindings)
3595        // MUST be deferred to per-cycle resolution. Their value
3596        // varies per iteration; pre-resolving against the parent
3597        // kernel here would bake in iteration 0's value (0) and
3598        // every subsequent iteration would emit the same string.
3599        if per_cycle_names.iter().any(|n| n == body) {
3600            out.push('{');
3601            out.push_str(body);
3602            out.push('}');
3603            i = after;
3604            continue;
3605        }
3606        // Bare ident — try kernel lookup. Computed outputs
3607        // (node-backed) aren't found by `lookup` (it only reads
3608        // input slots + constants), but they ARE valid wires
3609        // visible at this scope — accept them by checking
3610        // `resolve_output`. Per-cycle resolution at dispenser
3611        // time handles the actual pull.
3612        match polydat::kernel::interp::Lookup::lookup(
3613            &polydat::kernel::interp::KernelLookup::new(kernel),
3614            body,
3615        ) {
3616            Some(v) => out.push_str(&v.to_display_string()),
3617            None if kernel.output_index(body).is_some() => {
3618                // Defer to per-cycle resolution. Emit the
3619                // placeholder unchanged.
3620                out.push('{');
3621                out.push_str(body);
3622                out.push('}');
3623            }
3624            None => {
3625                errors.push(format!(
3626                    "{field_path}: '{{{body}}}' did not resolve in scope and is \
3627                     not a per-cycle binding declared by this phase"
3628                ));
3629                // Still push the placeholder as-is so the rest of
3630                // the string remains parseable for further error
3631                // collection on the same field.
3632                out.push('{');
3633                out.push_str(body);
3634                out.push('}');
3635            }
3636        }
3637        i = after;
3638    }
3639
3640    if errors.is_empty() {
3641        Ok(out)
3642    } else {
3643        Err(errors)
3644    }
3645}
3646
3647/// Rewrite inline expressions (`{{expr}}`) in op template strings to
3648/// use named binding references (`{__expr_N}`).
3649///
3650/// Returns the expression-to-name map for the caller to know what
3651/// was rewritten. Fails on a malformed bind point, naming the op.
3652pub fn rewrite_inline_exprs(ops: &mut [ParsedOp]) -> Result<HashMap<String, String>, String> {
3653    // SRD-13d: each op template is its own Polydat scope. Inline
3654    // `{{<expr>}}` rewrites are Polydat matter that belongs to the
3655    // op-template scope, not to the shared phase scope. So each
3656    // op gets its OWN expression-to-name mapping, with
3657    // op-locally unique synth names — no cross-op dedup. Two ops
3658    // with textually identical inline expressions
3659    // (`if: cql_dialect == 'vendor'` on both `indexes_present_vendor`
3660    // and `indexes_built_vendor`) now get distinct
3661    // `__expr_N`/`__expr_M` names. Without this, both ops
3662    // injected the same `__expr_1 := cql_dialect == 'vendor'`
3663    // line into their bindings; the phase-scope ingest then saw
3664    // two ops each declaring `__expr_1` and tripped the
3665    // ride-along-uniqueness check (SRD-13c §"Op overriding op
3666    // shadow").
3667    //
3668    // The global `inline_idx` counter still increments
3669    // monotonically so synth names are workload-wide unique;
3670    // the per-op MAP keeps within-op dedup (same expression in
3671    // multiple fields of one op — `if: x == 1` and
3672    // `metric: x == 1` — collapses to a single `__expr_N` for
3673    // that op).
3674    let mut inline_idx = 0usize;
3675    let mut per_op_expr_to_name: Vec<HashMap<String, String>> =
3676        (0..ops.len()).map(|_| HashMap::new()).collect();
3677    let collect_from =
3678        |s: &str, idx: &mut usize, op_map: &mut HashMap<String, String>| -> Result<(), String> {
3679            for bp in nmbrs_workload::bindpoints::extract_bind_points(s)? {
3680                if let nmbrs_workload::bindpoints::BindPoint::InlineDefinition(ref expr) = bp {
3681                    op_map.entry(expr.clone()).or_insert_with(|| {
3682                        let n = format!("__expr_{idx}");
3683                        *idx += 1;
3684                        n
3685                    });
3686                }
3687            }
3688            Ok(())
3689        };
3690    for (op_index, op) in ops.iter().enumerate() {
3691        let op_map = &mut per_op_expr_to_name[op_index];
3692        for value in op.op.values() {
3693            if let Some(s) = value.as_str() {
3694                collect_from(s, &mut inline_idx, op_map)
3695                    .map_err(|e| format!("op '{}': {e}", op.name))?;
3696            }
3697        }
3698        if let Some(s) = &op.condition {
3699            collect_from(s, &mut inline_idx, op_map)
3700                .map_err(|e| format!("op '{}': {e}", op.name))?;
3701        }
3702        if let Some(spec) = &op.delay {
3703            for name in spec.names() {
3704                collect_from(name, &mut inline_idx, op_map)
3705                    .map_err(|e| format!("op '{}': {e}", op.name))?;
3706            }
3707        }
3708    }
3709    // For diagnostics + downstream: the legacy single
3710    // `expr_to_name` return value flattens the per-op maps.
3711    // Names are unique across ops because the inline_idx
3712    // counter is global, so the union is collision-free.
3713    let expr_to_name: HashMap<String, String> = per_op_expr_to_name
3714        .iter()
3715        .flat_map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())))
3716        .collect();
3717
3718    // Inject the synthesised `__expr_N := expr` bindings into
3719    // the first op's Polydat bindings source so `build_scope`'s
3720    // normal ingestion pass picks them up. Without this the
3721    // op fields get rewritten to reference `{__expr_N}` but
3722    // no binding declaring `__expr_N` ever lands in the
3723    // scope, so compilation fails with "unresolved bind
3724    // point '{__expr_N}'". Callers used to discard the
3725    // returned `expr_to_name` mapping and trust some other
3726    // path to install the bindings — there isn't one. Doing
3727    // the injection here keeps `rewrite_inline_exprs`
3728    // self-contained: every output rewrite has a matching
3729    // binding emitted.
3730    // Inject + rewrite per op. Each op uses ONLY its own
3731    // expr_to_name mapping (per_op_expr_to_name[op_index]).
3732    // Synth lines land in that op's bindings; field rewrites
3733    // see only that op's expression names. SRD-13d: the
3734    // op-template scope owns its own Polydat matter, including
3735    // synth bindings from inline expressions.
3736    if expr_to_name.is_empty() {
3737        return Ok(expr_to_name);
3738    }
3739    use nmbrs_workload::model::BindingsDef;
3740    for (op_index, op) in ops.iter_mut().enumerate() {
3741        let op_map = &per_op_expr_to_name[op_index];
3742        if op_map.is_empty() {
3743            continue;
3744        }
3745
3746        // Build synth lines for this op, deterministically
3747        // ordered by synth name.
3748        let mut entries: Vec<(&String, &String)> = op_map.iter().collect();
3749        entries.sort_by(|a, b| a.1.cmp(b.1));
3750        let mut synth_lines = String::new();
3751        for (expr, name) in &entries {
3752            synth_lines.push_str(&format!("\n{name} := {expr}"));
3753        }
3754
3755        // Inject into op.bindings. Map → PolydatSource conversion
3756        // mirrors the existing scope-source assembly path.
3757        match &mut op.bindings {
3758            BindingsDef::PolydatSource(s) => {
3759                if s.trim().is_empty() {
3760                    *s = synth_lines.trim_start_matches('\n').to_string();
3761                } else {
3762                    s.push_str(&synth_lines);
3763                }
3764            }
3765            BindingsDef::Map(_) => {
3766                if let BindingsDef::Map(map) = &op.bindings {
3767                    let mut existing = String::new();
3768                    for (k, v) in map.iter() {
3769                        existing.push_str(&format!("{k} := {v}\n"));
3770                    }
3771                    op.bindings = BindingsDef::PolydatSource(format!("{existing}{synth_lines}"));
3772                }
3773            }
3774        }
3775
3776        // Rewrite this op's fields using its own mapping only.
3777        let rewrite = |s: &str| -> String {
3778            let mut rewritten = s.to_string();
3779            for (expr, name) in op_map {
3780                rewritten = rewritten.replace(&format!("{{{{{expr}}}}}"), &format!("{{{name}}}"));
3781                rewritten = rewritten.replace(&format!("{{:={expr}:=}}"), &format!("{{{name}}}"));
3782                rewritten = rewritten.replace(&format!("{{:={expr}}}"), &format!("{{{name}}}"));
3783                rewritten = rewritten.replace(&format!("{{{expr}}}"), &format!("{{{name}}}"));
3784            }
3785            rewritten
3786        };
3787        for value in op.op.values_mut() {
3788            if let Some(s) = value.as_str() {
3789                *value = serde_json::Value::String(rewrite(s));
3790            }
3791        }
3792        if let Some(s) = &op.condition {
3793            op.condition = Some(rewrite(s));
3794        }
3795        if let Some(spec) = &op.delay {
3796            // Rewrite each binding name in place, preserving
3797            // the spec's enum shape (Before vs BeforeAfter).
3798            op.delay = Some(match spec {
3799                nmbrs_workload::model::DelaySpec::Before(name) => {
3800                    nmbrs_workload::model::DelaySpec::Before(rewrite(name))
3801                }
3802                nmbrs_workload::model::DelaySpec::BeforeAfter { before, after } => {
3803                    nmbrs_workload::model::DelaySpec::BeforeAfter {
3804                        before: before.as_deref().map(rewrite),
3805                        after: after.as_deref().map(rewrite),
3806                    }
3807                }
3808            });
3809        }
3810    }
3811
3812    Ok(expr_to_name)
3813}
3814
3815/// Cached `NMBRS_DEBUG_SCOPE_SYNTH=true` switch (one read, one
3816/// warning on a non-boolean value).
3817fn debug_scope_synth_enabled() -> bool {
3818    static FLAG: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3819    *FLAG.get_or_init(|| crate::debug_env::debug_flag("NMBRS_DEBUG_SCOPE_SYNTH"))
3820}
3821
3822#[cfg(test)]
3823mod tests {
3824    use super::*;
3825
3826    fn make_polydat_op(name: &str, stmt: &str, bindings: &str) -> ParsedOp {
3827        let mut op = ParsedOp::simple(name, stmt);
3828        op.bindings = BindingsDef::PolydatSource(bindings.to_string());
3829        op
3830    }
3831
3832    #[test]
3833    fn objective_bare_wire_vs_inline_expression() {
3834        // Bare identifiers are read directly off the phase kernel.
3835        assert!(objective_is_bare_wire("score"));
3836        assert!(objective_is_bare_wire("err_rate"));
3837        assert!(objective_is_bare_wire("_objective"));
3838        assert!(objective_is_bare_wire("  recall99  ")); // trimmed
3839        assert_eq!(objective_wire("score"), "score");
3840        assert_eq!(objective_wire("  recall99  "), "recall99");
3841
3842        // Anything with operators / calls / dots / spaces is an inline
3843        // expression → synthesized to the `__objective` wire.
3844        assert!(!objective_is_bare_wire("0 - err_rate"));
3845        assert!(!objective_is_bare_wire("metricsql_scalar(\"x\")"));
3846        assert!(!objective_is_bare_wire("a - b"));
3847        assert!(!objective_is_bare_wire("q.cursor.depth"));
3848        assert!(!objective_is_bare_wire(""));
3849        assert_eq!(objective_wire("0 - err_rate"), OBJECTIVE_WIRE);
3850        assert_eq!(objective_wire("metricsql_scalar(\"x\")"), OBJECTIVE_WIRE);
3851    }
3852
3853    #[test]
3854    fn inline_objective_synthesizes_volatile_objective_binding() {
3855        use nmbrs_workload::model::{BindingsDef, OptimizeBlock, WorkloadPhase};
3856        let phase = WorkloadPhase {
3857            for_each: Some("rate in 1000, 2000".to_string()),
3858            bindings: BindingsDef::PolydatSource("input cycle: u64\n".to_string()),
3859            optimize: Some(OptimizeBlock {
3860                method: "sweep".to_string(),
3861                objective: "0 - metricsql_scalar(\"sum(rate(errors_total[3s]))\")".to_string(),
3862                servo: vec!["rate".to_string()],
3863                max_evals: 10,
3864                seed: 0,
3865                params: Default::default(),
3866            }),
3867            ..Default::default()
3868        };
3869        let out = synthesize_phase_scope_bindings(&phase).expect("synthesis ok");
3870        let src = match out {
3871            BindingsDef::PolydatSource(s) => s,
3872            other => panic!("expected PolydatSource, got {other:?}"),
3873        };
3874        assert!(
3875            src.contains("volatile __objective := 0 - metricsql_scalar("),
3876            "inline objective must be lowered to a `__objective` binding:\n{src}"
3877        );
3878
3879        // A bare-name objective is NOT synthesized — read directly.
3880        let mut bare = phase.clone();
3881        bare.optimize.as_mut().unwrap().objective = "score".to_string();
3882        let bare_out = synthesize_phase_scope_bindings(&bare).expect("synthesis ok");
3883        if let BindingsDef::PolydatSource(s) = bare_out {
3884            assert!(
3885                !s.contains("__objective"),
3886                "bare objective must not synthesize:\n{s}"
3887            );
3888        }
3889    }
3890
3891    #[test]
3892    fn inherited_bindings_dedup_across_ops() {
3893        let bindings = "input cycle: u64\nprofiles := matching_profiles(\"example\", \"label\")";
3894        let ops = vec![
3895            make_polydat_op("op_a", "{profiles}", bindings),
3896            make_polydat_op("op_b", "{profiles}", bindings),
3897        ];
3898        let scope = build_scope(
3899            &ops,
3900            &HashMap::new(),
3901            &[],
3902            &HashMap::new(),
3903            &HashMap::new(),
3904            None,
3905            &[],
3906            None,
3907        )
3908        .unwrap();
3909        scope.validate().unwrap();
3910        let emitted = scope.emit();
3911        // 'profiles' should appear exactly once
3912        let count = emitted.matches("profiles :=").count();
3913        assert_eq!(
3914            count, 1,
3915            "expected exactly 1 'profiles :=' in emitted scope, got {count}:\n{emitted}"
3916        );
3917    }
3918
3919    #[test]
3920    fn iteration_vars_dont_conflict_with_inherited() {
3921        let bindings = "input cycle: u64\nprofiles := matching_profiles(\"example\", \"label\")";
3922        let ops = vec![
3923            make_polydat_op("op_a", "{profiles} {table}", bindings),
3924            make_polydat_op("op_b", "{profiles} {table}", bindings),
3925        ];
3926        let mut iter_vars = HashMap::new();
3927        iter_vars.insert("table".to_string(), "vec_default".to_string());
3928
3929        let scope = build_scope(
3930            &ops,
3931            &iter_vars,
3932            &[],
3933            &HashMap::new(),
3934            &HashMap::new(),
3935            None,
3936            &[],
3937            None,
3938        )
3939        .unwrap();
3940        scope.validate().unwrap();
3941        let emitted = scope.emit();
3942        // Iteration variables now declare as `extern <name>:
3943        // <Type>` so the runtime can populate them per iteration
3944        // without recompiling (SRD 18b §"Iteration variables as
3945        // scope outputs"). Type is inferred from the value;
3946        // "vec_default" doesn't parse numerically → str.
3947        assert!(
3948            emitted.contains("extern table: str"),
3949            "expected extern table declaration in:\n{emitted}"
3950        );
3951        assert!(
3952            emitted.contains("profiles :="),
3953            "expected profiles in:\n{emitted}"
3954        );
3955    }
3956
3957    #[test]
3958    fn op_augmentation_adds_new_names() {
3959        let base = "input cycle: u64\nfoo := hash(cycle)";
3960        let augmented = "input cycle: u64\nfoo := hash(cycle)\nbar := mod(cycle, 100)";
3961        let ops = vec![
3962            make_polydat_op("op_a", "{foo}", base),
3963            make_polydat_op("op_b", "{foo} {bar}", augmented),
3964        ];
3965        let scope = build_scope(
3966            &ops,
3967            &HashMap::new(),
3968            &[],
3969            &HashMap::new(),
3970            &HashMap::new(),
3971            None,
3972            &[],
3973            None,
3974        )
3975        .unwrap();
3976        scope.validate().unwrap();
3977        let emitted = scope.emit();
3978        assert!(emitted.contains("foo := hash(cycle)"), "missing foo");
3979        assert!(emitted.contains("bar := mod(cycle, 100)"), "missing bar");
3980    }
3981
3982    #[test]
3983    fn real_shadow_is_caught() {
3984        let base = "input cycle: u64\nfoo := hash(cycle)";
3985        let shadow = "input cycle: u64\nfoo := mod(cycle, 100)";
3986        let ops = vec![
3987            make_polydat_op("op_a", "{foo}", base),
3988            make_polydat_op("op_b", "{foo}", shadow),
3989        ];
3990        let scope = build_scope(
3991            &ops,
3992            &HashMap::new(),
3993            &[],
3994            &HashMap::new(),
3995            &HashMap::new(),
3996            None,
3997            &[],
3998            None,
3999        )
4000        .unwrap();
4001        let result = scope.validate();
4002        assert!(result.is_err(), "expected shadow error");
4003        let err = result.unwrap_err();
4004        assert!(
4005            err.contains("shadows"),
4006            "expected 'shadows' in error: {err}"
4007        );
4008        assert!(err.contains("op_b"), "expected op name in error: {err}");
4009    }
4010
4011    #[test]
4012    fn original_bug_repro_no_false_shadow() {
4013        // The original bug: workload-level bindings with profiles,
4014        // inherited by a phase with for_each iteration vars.
4015        // Two ops share identical inherited bindings.
4016        // The init injection used to make them differ, causing false shadow.
4017        let bindings = "input cycle: u64\nprofiles := matching_profiles(\"example\", \"label\")";
4018        let ops = vec![
4019            make_polydat_op(
4020                "drop_metadata_index",
4021                "DROP INDEX {table}_meta_idx",
4022                bindings,
4023            ),
4024            make_polydat_op("drop_vector_index", "DROP INDEX {table}_idx", bindings),
4025            make_polydat_op("drop_table", "DROP TABLE {table}", bindings),
4026        ];
4027        let mut iter_vars = HashMap::new();
4028        iter_vars.insert("table".to_string(), "fknn_default".to_string());
4029        iter_vars.insert("spec".to_string(), "example:default".to_string());
4030        iter_vars.insert("optimize_for".to_string(), "RECALL".to_string());
4031
4032        let scope = build_scope(
4033            &ops,
4034            &iter_vars,
4035            &[],
4036            &HashMap::new(),
4037            &HashMap::new(),
4038            None,
4039            &[],
4040            None,
4041        )
4042        .unwrap();
4043        // This was the bug: validate() used to fail with false shadow error
4044        scope.validate().unwrap();
4045        let emitted = scope.emit();
4046        // Iter vars now declare as extern (SRD 18b). The original
4047        // bug — false-shadow detection — is unchanged regardless
4048        // of how the iter var materialises.
4049        assert!(
4050            emitted.contains("extern table: str"),
4051            "missing extern table in:\n{emitted}"
4052        );
4053        assert!(emitted.contains("profiles :="), "missing profiles");
4054        // profiles should appear exactly once
4055        let count = emitted.matches("profiles :=").count();
4056        assert_eq!(count, 1, "profiles duplicated in:\n{emitted}");
4057    }
4058
4059    // ── SRD-13d Phase 9 cross-scope contract check ──────────
4060
4061    fn parent_kernel_with_load() -> crate::scope_kernel::ScopeKernel {
4062        // Parent has `cycle` input, a folded constant `dim`, a
4063        // shared output `budget`, and a dynamic output `load`
4064        // (cycle-dependent, no modifier). Each shape exercises
4065        // a different `ParentRefKind` arm.
4066        crate::bindings::compile_scope_kernel(
4067            "input cycle: u64\n\
4068             const dim := 128\n\
4069             shared budget := 100\n\
4070             load := add(cycle, 1)\n",
4071            &Default::default(),
4072        )
4073        .expect("compile parent")
4074    }
4075
4076    fn op_with_body(name: &str, body: &str) -> ParsedOp {
4077        let mut op = ParsedOp::simple(name, "noop");
4078        op.bindings = BindingsDef::PolydatSource(body.into());
4079        op
4080    }
4081
4082    #[test]
4083    fn op_template_referencing_cycle_input_is_accepted() {
4084        let parent = parent_kernel_with_load();
4085        let manifest = polydat::kernel::extract_manifest(parent.program())
4086            .into_iter()
4087            .map(|e| crate::runner::ManifestEntry {
4088                name: e.name,
4089                port_type: e.port_type,
4090                modifier: e.modifier,
4091            })
4092            .collect::<Vec<_>>();
4093        let op = op_with_body("step_op", "step := add(cycle, 1)\n");
4094        let result = build_op_template_scope_kernel(
4095            &op,
4096            &manifest,
4097            &parent,
4098            &HashMap::new(),
4099            Vec::new(),
4100            None,
4101            false,
4102            polydat::kernel::KernelOptLevel::Release,
4103            "test",
4104        );
4105        assert!(
4106            result.is_ok(),
4107            "cycle is a parent input — should be accepted. err: {:?}",
4108            result.err()
4109        );
4110    }
4111
4112    /// Localises the metric-wiring defect: when an op-template kernel is
4113    /// materialised, does the synthesised `__metric_<name>` binding surface as
4114    /// an output on THAT kernel? The metrics wrapper reads it through
4115    /// `ctx.wires`, so if it is absent the wrapper reports
4116    /// "did not resolve through ctx.wires".
4117    #[test]
4118    fn op_template_kernel_exposes_synthesised_metric_bindings() {
4119        use nmbrs_workload::model::MetricSpec;
4120        let parent = parent_kernel_with_load();
4121        let manifest = polydat::kernel::extract_manifest(parent.program())
4122            .into_iter()
4123            .map(|e| crate::runner::ManifestEntry {
4124                name: e.name,
4125                port_type: e.port_type,
4126                modifier: e.modifier,
4127            })
4128            .collect::<Vec<_>>();
4129        let mut op = op_with_body("m_op", "measured := add(cycle, 1)\n");
4130        op.metrics.insert(
4131            "bytes_out".to_string(),
4132            MetricSpec {
4133                value: "measured".into(),
4134                family: None,
4135                kind: None,
4136                unit: None,
4137                format: None,
4138                cell: Default::default(),
4139            },
4140        );
4141        let kernel = build_op_template_scope_kernel(
4142            &op,
4143            &manifest,
4144            &parent,
4145            &HashMap::new(),
4146            Vec::new(),
4147            None,
4148            false,
4149            polydat::kernel::KernelOptLevel::Release,
4150            "test",
4151        )
4152        .expect("op-template kernel builds");
4153        let outs = kernel.program().output_names();
4154        assert!(
4155            outs.contains(&"__metric_bytes_out"),
4156            "the synthesised metric binding must be an output of the \
4157             op-template kernel; outputs: {outs:?}"
4158        );
4159    }
4160
4161    #[test]
4162    fn op_template_referencing_constant_output_is_accepted() {
4163        let parent = parent_kernel_with_load();
4164        let manifest = polydat::kernel::extract_manifest(parent.program())
4165            .into_iter()
4166            .map(|e| crate::runner::ManifestEntry {
4167                name: e.name,
4168                port_type: e.port_type,
4169                modifier: e.modifier,
4170            })
4171            .collect::<Vec<_>>();
4172        // `dim` is a `final` (folded) output — snapshot is final,
4173        // per-cycle changes are impossible by construction.
4174        let op = op_with_body("calc_op", "scaled := mul(dim, 2)\n");
4175        let result = build_op_template_scope_kernel(
4176            &op,
4177            &manifest,
4178            &parent,
4179            &HashMap::new(),
4180            Vec::new(),
4181            None,
4182            false,
4183            polydat::kernel::KernelOptLevel::Release,
4184            "test",
4185        );
4186        assert!(
4187            result.is_ok(),
4188            "final/folded output should be accepted. err: {:?}",
4189            result.err()
4190        );
4191    }
4192
4193    #[test]
4194    fn op_template_referencing_shared_output_is_accepted() {
4195        let parent = parent_kernel_with_load();
4196        let manifest = polydat::kernel::extract_manifest(parent.program())
4197            .into_iter()
4198            .map(|e| crate::runner::ManifestEntry {
4199                name: e.name,
4200                port_type: e.port_type,
4201                modifier: e.modifier,
4202            })
4203            .collect::<Vec<_>>();
4204        // `budget` is `shared` — SharedCell carries live updates.
4205        let op = op_with_body("budget_op", "remaining := add(budget, 1)\n");
4206        let result = build_op_template_scope_kernel(
4207            &op,
4208            &manifest,
4209            &parent,
4210            &HashMap::new(),
4211            Vec::new(),
4212            None,
4213            false,
4214            polydat::kernel::KernelOptLevel::Release,
4215            "test",
4216        );
4217        assert!(
4218            result.is_ok(),
4219            "shared output should be accepted. err: {:?}",
4220            result.err()
4221        );
4222    }
4223
4224    #[test]
4225    fn op_template_referencing_dynamic_output_accepted_per_srd_13f() {
4226        // SRD-13f retires SRD-13c's "DynamicOutput without
4227        // shared" rejection. The read invariant is uniform —
4228        // inner reads of cross-scope wires return outer's
4229        // current value via construction-time wiring (cells
4230        // for shared, per-cycle refresh / planned cell
4231        // mechanism for non-shared). The op-template
4232        // synthesiser accepts the reference; the wiring keeps
4233        // the invariant intact at cycle time.
4234        let parent = parent_kernel_with_load();
4235        let manifest = polydat::kernel::extract_manifest(parent.program())
4236            .into_iter()
4237            .map(|e| crate::runner::ManifestEntry {
4238                name: e.name,
4239                port_type: e.port_type,
4240                modifier: e.modifier,
4241            })
4242            .collect::<Vec<_>>();
4243        let op = op_with_body("forecast_op", "forecast := mul(load, 2)\n");
4244        let kernel = build_op_template_scope_kernel(
4245            &op,
4246            &manifest,
4247            &parent,
4248            &HashMap::new(),
4249            Vec::new(),
4250            None,
4251            false,
4252            polydat::kernel::KernelOptLevel::Release,
4253            "test",
4254        )
4255        .expect("op-template kernel synth should accept dynamic parent ref");
4256        // The op-template kernel carries `load` as an extern
4257        // input — the construction-time wiring set up the slot;
4258        // per-cycle refresh keeps it current with outer.
4259        assert!(
4260            kernel.program().find_input("load").is_some(),
4261            "extern load slot should land on op-template kernel"
4262        );
4263        // And `forecast`, the op-local binding, is an output.
4264        assert!(
4265            kernel.program().output_names().contains(&"forecast"),
4266            "op-local binding should be an output"
4267        );
4268    }
4269
4270    #[test]
4271    fn op_template_pvs_query_full_shape_with_workload_params() {
4272        // Closer to the actual full_cql_vector.yaml shape: the
4273        // op carries `prepared:` text with `{keyspace}.{table}`
4274        // / `{predicate}` / `{query_vector}` / `{limit}` interp
4275        // bind-points, plus a `metrics: overscan: {value:
4276        // overscan}` declaration. workload_params carries
4277        // dataset/profile/keyspace via `final` injection. The
4278        // op-template synthesiser must emit the latency_factor /
4279        // recall_factor / overscan bindings as outputs so the
4280        // metrics fixture's `register_pull("overscan")`
4281        // resolves.
4282        use nmbrs_workload::model::MetricSpec;
4283        let parent_src = r#"
4284extern k: u64
4285extern limit: u64
4286extern optimize_for: str
4287extern table: str
4288"#;
4289        let parent = crate::bindings::compile_scope_kernel(
4290            parent_src,
4291            &polydat::dsl::compile::CompileOptions {
4292                context: "parent".to_string(),
4293                ..Default::default()
4294            },
4295        )
4296        .expect("parent compile");
4297        let manifest: Vec<crate::runner::ManifestEntry> =
4298            polydat::kernel::extract_manifest(parent.program())
4299                .into_iter()
4300                .map(|e| crate::runner::ManifestEntry {
4301                    name: e.name,
4302                    port_type: e.port_type,
4303                    modifier: e.modifier,
4304                })
4305                .collect();
4306        let body = "const prebuffered := dataset_prebuffer(\"{dataset}:{profile}\")\n\
4307            const query_counts := query_count(prebuffered)\n\
4308            cursor q = range(0, query_counts * 10)\n\
4309            query_vector := query_vector_at(prebuffered, q % query_counts)\n\
4310            predicate := predicate_value_at(prebuffered, q % query_counts)\n\
4311            ground_truth := filtered_neighbor_indices_at(prebuffered, q % query_counts)\n\
4312            latency_factor := 0.979 + 4.021 * pow(limit, -0.761)\n\
4313            recall_factor  := 0.509 + 9.491 * pow(limit, -0.402)\n\
4314            overscan := if(optimize_for == \"LATENCY\", latency_factor, recall_factor)\n";
4315        let mut op = op_with_body("select_ann", body);
4316        // Mirror op fields the YAML carries.
4317        op.op.insert(
4318            "prepared".into(),
4319            serde_json::json!(
4320                "SELECT key,value FROM {keyspace}.{table} \
4321             WHERE metadata = {predicate} \
4322             ORDER BY value ANN OF {query_vector} LIMIT {limit}"
4323            ),
4324        );
4325        op.metrics.insert(
4326            "overscan".into(),
4327            MetricSpec {
4328                value: "overscan".into(),
4329                family: None,
4330                kind: None,
4331                unit: None,
4332                format: None,
4333                cell: Default::default(),
4334            },
4335        );
4336        let mut workload_params = HashMap::new();
4337        workload_params.insert("dataset".into(), "example".into());
4338        workload_params.insert("profile".into(), "label_00".into());
4339        workload_params.insert("keyspace".into(), "baselines".into());
4340        let kernel = build_op_template_scope_kernel(
4341            &op,
4342            &manifest,
4343            &parent,
4344            &workload_params,
4345            vec![],
4346            None,
4347            false,
4348            polydat::kernel::KernelOptLevel::Release,
4349            "pvs_query.select_ann",
4350        )
4351        .expect("op-template kernel synth");
4352        let outs: Vec<String> = kernel
4353            .program()
4354            .output_names()
4355            .iter()
4356            .map(|s| s.to_string())
4357            .collect();
4358        for required in &["overscan", "latency_factor", "recall_factor"] {
4359            assert!(
4360                outs.iter().any(|o| o == required),
4361                "op-template kernel missing '{required}'; outputs: {outs:?}"
4362            );
4363        }
4364        // Workload params must be folded in as `final` constants
4365        // (not externs) so `init prebuffered =
4366        // dataset_prebuffer("{dataset}:{profile}")` folds at
4367        // compile time. If they cascade through as externs the
4368        // init binding stays unfolded, the per-fiber state never
4369        // gets the seeded Handle, and downstream nodes (like
4370        // `neighbor_indices_at(prebuffered, q)`) panic at runtime
4371        // with `expected Handle, got None/U64`.
4372        for param in &["dataset", "profile", "keyspace"] {
4373            // The param either folds out completely (no input
4374            // slot) or appears as a folded constant — both
4375            // are fine. What's NOT fine is showing up as an
4376            // input on the inner kernel.
4377            assert!(
4378                kernel.program().find_input(param).is_none(),
4379                "workload param '{param}' must NOT be an extern input \
4380                 on the op-template kernel — cascade should emit \
4381                 it as `final` so init bindings fold. Inputs: {:?}",
4382                kernel.program().input_names(),
4383            );
4384        }
4385    }
4386
4387    #[test]
4388    fn op_template_with_pow_and_if_keeps_all_outputs() {
4389        // Mirror the shape of full_cql_vector.yaml's pvs_query
4390        // phase body (after parser merge): init+cursor+:= ladder
4391        // ending with `pow()` + `if()` bindings. The op-template
4392        // kernel must expose every `:=` binding as an output;
4393        // a missing `overscan` is what triggers the
4394        // `register_pull("overscan")` failure at MetricsDispenser
4395        // wrap time.
4396        let parent_src = r#"
4397extern k: u64
4398extern limit: u64
4399extern optimize_for: str
4400extern table: str
4401extern dataset: str
4402extern profile: str
4403extern keyspace: str
4404"#;
4405        let parent = crate::bindings::compile_scope_kernel(
4406            parent_src,
4407            &polydat::dsl::compile::CompileOptions {
4408                context: "parent".to_string(),
4409                ..Default::default()
4410            },
4411        )
4412        .expect("parent compile");
4413        let manifest: Vec<crate::runner::ManifestEntry> =
4414            polydat::kernel::extract_manifest(parent.program())
4415                .into_iter()
4416                .map(|e| crate::runner::ManifestEntry {
4417                    name: e.name,
4418                    port_type: e.port_type,
4419                    modifier: e.modifier,
4420                })
4421                .collect();
4422        let body = "const prebuffered := dataset_prebuffer(\"dummy:default\")\n\
4423            const query_counts := query_count(prebuffered)\n\
4424            cursor q = range(0, query_counts * 10)\n\
4425            query_vector := query_vector_at(prebuffered, q % query_counts)\n\
4426            predicate := predicate_value_at(prebuffered, q % query_counts)\n\
4427            ground_truth := filtered_neighbor_indices_at(prebuffered, q % query_counts)\n\
4428            latency_factor := 0.979 + 4.021 * pow(limit, -0.761)\n\
4429            recall_factor  := 0.509 + 9.491 * pow(limit, -0.402)\n\
4430            overscan := if(optimize_for == \"LATENCY\", latency_factor, recall_factor)\n";
4431        let op = op_with_body("select_ann", body);
4432        let kernel = build_op_template_scope_kernel(
4433            &op,
4434            &manifest,
4435            &parent,
4436            &HashMap::new(),
4437            Vec::new(),
4438            None,
4439            false,
4440            polydat::kernel::KernelOptLevel::Release,
4441            "pvs_query.select_ann",
4442        )
4443        .expect("op-template kernel synth");
4444        let outs: Vec<String> = kernel
4445            .program()
4446            .output_names()
4447            .iter()
4448            .map(|s| s.to_string())
4449            .collect();
4450        for required in &[
4451            "query_vector",
4452            "predicate",
4453            "ground_truth",
4454            "latency_factor",
4455            "recall_factor",
4456            "overscan",
4457        ] {
4458            assert!(
4459                outs.iter().any(|o| o == required),
4460                "op-template kernel missing '{required}'; outputs: {outs:?}"
4461            );
4462        }
4463    }
4464
4465    #[test]
4466    fn op_template_relevancy_k_r_bare_wire_names_cascade() {
4467        // Post-SRD-68 follow-up: `evaluations.relevancy.{k, r,
4468        // expected, actual}` accept bare wire-name forms. The
4469        // op-template synthesiser must include those names in its
4470        // cascaded-extern set so the dispenser's canonical kernel
4471        // can resolve them at wrap-time (where parse_count_param
4472        // calls wires.get(name)).
4473        let parent = parent_kernel_with_load();
4474        let manifest = polydat::kernel::extract_manifest(parent.program())
4475            .into_iter()
4476            .map(|e| crate::runner::ManifestEntry {
4477                name: e.name,
4478                port_type: e.port_type,
4479                modifier: e.modifier,
4480            })
4481            .collect::<Vec<_>>();
4482        let mut op = ParsedOp::simple("read", "noop");
4483        op.bindings = BindingsDef::PolydatSource("".into());
4484        op.params.insert(
4485            "relevancy".into(),
4486            serde_json::json!({
4487                "actual": "rows",
4488                "expected": "ground_truth",
4489                "k": "k_value",
4490                "r": "limit_value",
4491                "functions": ["recall"],
4492            }),
4493        );
4494        // Parent has `cycle` as the coord input. The relevancy
4495        // wire names (rows, ground_truth, k_value, limit_value)
4496        // aren't on the parent; the synthesiser should still add
4497        // them to the cascade-extern set so the op-template kernel
4498        // *declares* them (errors only fire at wrap-time when the
4499        // canonical kernel actually tries to resolve them).
4500        //
4501        // For this unit test we just confirm the synthesiser
4502        // doesn't error AND that the input/output names list
4503        // includes each relevancy wire name — meaning the
4504        // referenced-cascade walker picked them up. We pick names
4505        // the parent doesn't have so the auto-extern path fires
4506        // and the resulting kernel has them as inputs.
4507        let _ = manifest;
4508        // Use the public synthesis entry point to construct the
4509        // op-template kernel under a parent that *does* have the
4510        // referenced wires (so the cascade succeeds).
4511        let kernel_src = "\
4512            input cycle: u64\n\
4513            const rows := 10\n\
4514            const ground_truth := \"1,2,3\"\n\
4515            const k_value := 5\n\
4516            const limit_value := 100\n";
4517        let real_parent =
4518            crate::scope_kernel::ScopeKernel::compile(kernel_src).expect("parent compile");
4519        let real_manifest = polydat::kernel::extract_manifest(real_parent.program())
4520            .into_iter()
4521            .map(|e| crate::runner::ManifestEntry {
4522                name: e.name,
4523                port_type: e.port_type,
4524                modifier: e.modifier,
4525            })
4526            .collect::<Vec<_>>();
4527        let kernel = build_op_template_scope_kernel(
4528            &op,
4529            &real_manifest,
4530            &real_parent,
4531            &HashMap::new(),
4532            Vec::new(),
4533            None,
4534            false,
4535            polydat::kernel::KernelOptLevel::Release,
4536            "relevancy-cascade-test",
4537        )
4538        .expect("op-template kernel synth");
4539
4540        // Each bare-name relevancy wire should resolve through the
4541        // op-template kernel's lookup — the same path validation.rs
4542        // takes at wrap-time via canonical_kernel().lookup(name).
4543        for name in &["rows", "ground_truth", "k_value", "limit_value"] {
4544            assert!(
4545                kernel.lookup(name).is_some(),
4546                "relevancy wire '{name}' should be visible on the \
4547                 op-template kernel (cascaded extern); kernel had \
4548                 outputs: {outs:?}",
4549                outs = kernel.program().output_names()
4550            );
4551        }
4552    }
4553
4554    #[test]
4555    fn op_template_metric_value_count_allocates_magic_extern_slot() {
4556        // Post-SRD-68 follow-up: a metric `value:` expression is a
4557        // use site for any names it references. The op-template
4558        // kernel synthesiser appends `__metric_<name> := <value_expr>`
4559        // to the result-bindings source, so the closure-binding
4560        // economy's free-identifier walker sees `count` and injects
4561        // an `extern count: u64` slot — no throw-away result-binding
4562        // needed.
4563        //
4564        // Verifies: a workload with NO `result:` block but a
4565        // `metrics: rows_per_op: { value: count }` declaration ends
4566        // up with a `count` INPUT slot on the kernel.
4567        let parent = parent_kernel_with_load();
4568        let manifest = polydat::kernel::extract_manifest(parent.program())
4569            .into_iter()
4570            .map(|e| crate::runner::ManifestEntry {
4571                name: e.name,
4572                port_type: e.port_type,
4573                modifier: e.modifier,
4574            })
4575            .collect::<Vec<_>>();
4576        let mut op = ParsedOp::simple("read", "noop");
4577        op.bindings = BindingsDef::PolydatSource("".into());
4578        op.metrics.insert(
4579            "rows_per_op".into(),
4580            nmbrs_workload::model::MetricSpec {
4581                value: "count".into(),
4582                family: None,
4583                kind: Some(nmbrs_workload::model::MetricKind::Gauge),
4584                unit: None,
4585                format: None,
4586                cell: Default::default(),
4587            },
4588        );
4589        let kernel = build_op_template_scope_kernel(
4590            &op,
4591            &manifest,
4592            &parent,
4593            &HashMap::new(),
4594            Vec::new(),
4595            None,
4596            false,
4597            polydat::kernel::KernelOptLevel::Release,
4598            "metric-walker-test",
4599        )
4600        .expect("op-template kernel synth");
4601        let inputs = kernel.program().input_names();
4602        assert!(
4603            inputs.iter().any(|i| i == "count"),
4604            "metric `value: count` should force the `count` magic-extern \
4605             input slot to be allocated under Release opt level; \
4606             inputs were: {inputs:?}"
4607        );
4608        // And the synthesised binding shows up as an output the
4609        // MetricsDispenser will read at cycle time.
4610        let outs = kernel.program().output_names();
4611        let synth = synthesize_metric_binding_name("rows_per_op");
4612        assert!(
4613            outs.iter().any(|o| o == &synth),
4614            "synthesised `{synth}` binding should be a kernel output; \
4615             outputs were: {outs:?}"
4616        );
4617    }
4618
4619    #[test]
4620    fn promoted_final_emits_inline_literal_for_str() {
4621        // SRD-13f case 1 — when a referenced name is `final`
4622        // upstream and a Str, the synthesizer emits
4623        // `const name := "value"` in the child's source rather
4624        // than auto-externing it.
4625        let parent = crate::scope_kernel::ScopeKernel::compile(
4626            "input cycle: u64\nconst dataset := \"example\"\n",
4627        )
4628        .expect("compile parent");
4629        let manifest: Vec<crate::runner::ManifestEntry> =
4630            polydat::kernel::extract_manifest(parent.program())
4631                .into_iter()
4632                .map(|e| crate::runner::ManifestEntry {
4633                    name: e.name,
4634                    port_type: e.port_type,
4635                    modifier: e.modifier,
4636                })
4637                .collect();
4638        let ops = vec![make_polydat_op("step", "x={dataset}", "input cycle: u64")];
4639        let scope = build_scope(
4640            &ops,
4641            &HashMap::new(),
4642            &manifest,
4643            &HashMap::new(),
4644            &HashMap::new(),
4645            None,
4646            &[],
4647            Some(&parent),
4648        )
4649        .expect("build_scope");
4650        let emitted = scope.emit();
4651        assert!(
4652            emitted.contains("const dataset := \"example\""),
4653            "expected promoted-final emission, got:\n{emitted}"
4654        );
4655        assert!(
4656            !emitted.contains("extern dataset"),
4657            "expected no extern for promoted-final dataset, got:\n{emitted}"
4658        );
4659    }
4660
4661    #[test]
4662    fn promoted_final_emits_inline_literal_for_u64() {
4663        let parent =
4664            crate::scope_kernel::ScopeKernel::compile("input cycle: u64\nconst count := 42\n")
4665                .expect("compile parent");
4666        let manifest: Vec<crate::runner::ManifestEntry> =
4667            polydat::kernel::extract_manifest(parent.program())
4668                .into_iter()
4669                .map(|e| crate::runner::ManifestEntry {
4670                    name: e.name,
4671                    port_type: e.port_type,
4672                    modifier: e.modifier,
4673                })
4674                .collect();
4675        let ops = vec![make_polydat_op("step", "n={count}", "input cycle: u64")];
4676        let scope = build_scope(
4677            &ops,
4678            &HashMap::new(),
4679            &manifest,
4680            &HashMap::new(),
4681            &HashMap::new(),
4682            None,
4683            &[],
4684            Some(&parent),
4685        )
4686        .expect("build_scope");
4687        let emitted = scope.emit();
4688        assert!(
4689            emitted.contains("const count := 42"),
4690            "expected promoted-final u64 emission, got:\n{emitted}"
4691        );
4692    }
4693
4694    #[test]
4695    fn unresolved_wire_reference_surfaces_validation_error() {
4696        // SRD-13f case 4 — a typo in a `{...}` placeholder (here
4697        // `{tirp}` instead of the declared `trip`) is rejected
4698        // at the synthesizer level with a structured error,
4699        // not via a downstream Polydat compiler error.
4700        let parent = crate::scope_kernel::ScopeKernel::compile(
4701            "input cycle: u64\nconst dataset := \"example\"\n",
4702        )
4703        .expect("compile parent");
4704        let manifest: Vec<crate::runner::ManifestEntry> =
4705            polydat::kernel::extract_manifest(parent.program())
4706                .into_iter()
4707                .map(|e| crate::runner::ManifestEntry {
4708                    name: e.name,
4709                    port_type: e.port_type,
4710                    modifier: e.modifier,
4711                })
4712                .collect();
4713        let ops = vec![make_polydat_op("step", "x={tirp}", "input cycle: u64")];
4714        let err = match build_scope(
4715            &ops,
4716            &HashMap::new(),
4717            &manifest,
4718            &HashMap::new(),
4719            &HashMap::new(),
4720            None,
4721            &[],
4722            Some(&parent),
4723        ) {
4724            Ok(_) => panic!("expected unresolved-wire error, got Ok"),
4725            Err(e) => e,
4726        };
4727        assert!(err.contains("unresolved wire"), "wrong error: {err}");
4728        assert!(
4729            err.contains("tirp"),
4730            "error should mention the typoed name: {err}"
4731        );
4732        assert!(
4733            err.contains("Visible names"),
4734            "error should list visible names: {err}"
4735        );
4736    }
4737
4738    #[test]
4739    fn overloaded_call_head_is_not_an_unresolved_wire() {
4740        // `vec_norm` is an overloaded name: the registry lists only its
4741        // typed forms (`vec_norm_f32`, `vec_norm_f64`), so a check that
4742        // asks the registry for the bare name alone would report the
4743        // call head as an unresolved wire.
4744        let parent = crate::scope_kernel::ScopeKernel::compile("input cycle: u64\n")
4745            .expect("compile parent");
4746        let manifest: Vec<crate::runner::ManifestEntry> =
4747            polydat::kernel::extract_manifest(parent.program())
4748                .into_iter()
4749                .map(|e| crate::runner::ManifestEntry {
4750                    name: e.name,
4751                    port_type: e.port_type,
4752                    modifier: e.modifier,
4753                })
4754                .collect();
4755        let ops = vec![make_polydat_op(
4756            "step",
4757            "x={n}",
4758            "input cycle: u64\nv := str_to_vec_f32(\"[3.0, 4.0]\")\nn := vec_norm(v)",
4759        )];
4760        if let Err(err) = build_scope(
4761            &ops,
4762            &HashMap::new(),
4763            &manifest,
4764            &HashMap::new(),
4765            &HashMap::new(),
4766            None,
4767            &[],
4768            Some(&parent),
4769        ) {
4770            panic!("an overloaded call head must resolve as a function: {err}");
4771        }
4772    }
4773
4774    #[test]
4775    fn ingest_preserves_bindings_when_comment_contains_apostrophe() {
4776        // Regression: Polydat grammar uses only `"`-delimited string
4777        // literals. `logical_lines` previously treated `'` as a
4778        // string delimiter too, which meant an unmatched
4779        // apostrophe in a `#` comment (e.g. "the workload's
4780        // bindings") put the splitter into a string state that
4781        // never closed. The entire rest of the source was
4782        // accreted into one logical "line" starting with `#`,
4783        // which then got dropped as a comment by the per-line
4784        // parser — silently discarding every binding that
4785        // followed.
4786        //
4787        // This was the actual root cause of the full_cql_vector
4788        // `await_index` failure: the workload's
4789        // `bindings:` block began with a multi-line comment
4790        // containing the apostrophe in "full_cql_vector's", so
4791        // the `shared has_X := false` declarations never made
4792        // it into the workload-root program. Descendant
4793        // synthesizers then couldn't cascade has_X as Bool
4794        // externs; the compile inferred has_X as Coordinate
4795        // U64 inputs from unbound references, and the
4796        // per-cycle `set_inputs(&[u64])` clobbered the
4797        // SharedCell with `Value::U64(cycle)`.
4798        let mut scope = BindingScope::new();
4799        let src_with_apostrophe_comment = "# full_cql_vector's bindings block\n\
4800                                           shared has_a := true\n\
4801                                           shared has_b := false\n";
4802        scope.ingest_polydat_source(src_with_apostrophe_comment, BindingOrigin::Inherited);
4803        let defined = scope.defined_names();
4804        assert!(
4805            defined.contains("has_a"),
4806            "comment with apostrophe must NOT consume subsequent bindings; \
4807             expected has_a in defined names, got {defined:?}"
4808        );
4809        assert!(
4810            defined.contains("has_b"),
4811            "expected has_b in defined names, got {defined:?}"
4812        );
4813
4814        let emitted = scope.emit();
4815        assert!(
4816            emitted.contains("shared has_a := true"),
4817            "scope.emit() must include the shared bindings; got:\n{emitted}"
4818        );
4819        assert!(
4820            emitted.contains("shared has_b := false"),
4821            "scope.emit() must include the shared bindings; got:\n{emitted}"
4822        );
4823    }
4824
4825    #[test]
4826    fn ingest_then_compile_preserves_shared_modifier() {
4827        // Mirrors the workload-root compile path in
4828        // `compile_bindings_with_libs_excluding`: workload-level
4829        // bindings (`shared has_X := false`) get ingested via
4830        // `scope.ingest_polydat_source(..., Inherited)` before emit.
4831        // The resulting source then compiles via the
4832        // standard pipeline.
4833        //
4834        // SRD-13c §"Shared Mutable": `shared X := <literal>`
4835        // compiles to an input slot + passthrough output marked
4836        // SHARED. The workload-root program's `shared_outputs()`
4837        // must include the SHARED-modifier outputs so
4838        // `seed_shared_cells` creates a `SharedCell` for each
4839        // and descendant kernels can cell-attach via
4840        // `materialize_wiring_from_outer`.
4841        let mut scope = BindingScope::new();
4842        let workload_polydat = "shared has_sai_column_indexes := false\n\
4843                          shared has_indexes := false\n";
4844        scope.ingest_polydat_source(workload_polydat, BindingOrigin::Inherited);
4845        let source = scope.emit();
4846        let kernel = crate::scope_kernel::ScopeKernel::compile(&source)
4847            .unwrap_or_else(|e| panic!("compile failed for source:\n{source}\nerror: {e}"));
4848        let shared = kernel.program().shared_outputs();
4849        assert!(
4850            shared.contains(&"has_sai_column_indexes"),
4851            "expected `has_sai_column_indexes` in shared_outputs after scope-ingest/emit/compile;\n\
4852             got shared_outputs={shared:?}\nemitted source:\n{source}",
4853        );
4854        assert!(
4855            shared.contains(&"has_indexes"),
4856            "expected `has_indexes` in shared_outputs after scope-ingest/emit/compile;\n\
4857             got shared_outputs={shared:?}\nemitted source:\n{source}",
4858        );
4859    }
4860
4861    /// SRD-75 Push 2: `synthesize_phase_scope_bindings`
4862    /// returns the original bindings unchanged when
4863    /// `phase.poll` is `None`. The function is a no-op for
4864    /// non-poll phases; their synthesis path is unaffected.
4865    #[test]
4866    fn synthesize_phase_scope_bindings_passthrough_when_no_poll() {
4867        use nmbrs_workload::model::{BindingsDef, WorkloadPhase};
4868        let phase = WorkloadPhase {
4869            bindings: BindingsDef::PolydatSource("k := 5\n".into()),
4870            poll: None,
4871            ..Default::default()
4872        };
4873        let out = synthesize_phase_scope_bindings(&phase).expect("no-poll synthesis is a no-op");
4874        match out {
4875            BindingsDef::PolydatSource(s) => assert_eq!(
4876                s, "k := 5\n",
4877                "no-poll should return the original bindings unchanged"
4878            ),
4879            other => panic!("expected PolydatSource, got {other:?}"),
4880        }
4881    }
4882
4883    /// A metric's `cell:` is reified as a compiled kernel binding beside its
4884    /// value — the whole point of the design. If this did not compile, a
4885    /// coordinate would have to be a runtime string, which is the
4886    /// unvalidatable shape the proposal exists to avoid.
4887    #[test]
4888    fn phase_metrics_reify_cell_coordinates_as_kernel_bindings() {
4889        use nmbrs_workload::model::{BindingsDef, MetricSpec, WorkloadPhase};
4890        let mut metrics = std::collections::HashMap::new();
4891        let mut cell = std::collections::BTreeMap::new();
4892        cell.insert("tier".to_string(), "tier_name".to_string());
4893        metrics.insert(
4894            "bytes_out".to_string(),
4895            MetricSpec {
4896                value: "history_bytes_out".into(),
4897                family: None,
4898                kind: None,
4899                unit: None,
4900                format: None,
4901                cell,
4902            },
4903        );
4904        let phase = WorkloadPhase {
4905            bindings: BindingsDef::PolydatSource(
4906                "extern tier_name: str = \"\"\n\
4907                 extern history_bytes_out: u64 = 0\n"
4908                    .into(),
4909            ),
4910            metrics,
4911            poll: None,
4912            ..Default::default()
4913        };
4914        let out = synthesize_phase_scope_bindings(&phase).expect("synthesis");
4915        let src = match out {
4916            BindingsDef::PolydatSource(s) => s,
4917            other => panic!("expected PolydatSource, got {other:?}"),
4918        };
4919        assert!(
4920            src.contains("volatile __cell_bytes_out__tier := tier_name"),
4921            "coordinate must be emitted as a volatile binding; got:\n{src}"
4922        );
4923        assert!(
4924            src.contains("volatile __metric_bytes_out := history_bytes_out"),
4925            "the value binding must still be emitted; got:\n{src}"
4926        );
4927    }
4928
4929    /// Per (metric, dimension), not per dimension: two metrics placing into
4930    /// one dimension by different expressions must not collide on a wire name
4931    /// and silently let one placement win.
4932    #[test]
4933    fn two_metrics_in_one_dimension_get_distinct_coordinate_wires() {
4934        assert_eq!(
4935            synthesize_cell_binding_name("bytes_out", "tier"),
4936            "__cell_bytes_out__tier"
4937        );
4938        assert_ne!(
4939            synthesize_cell_binding_name("bytes_out", "tier"),
4940            synthesize_cell_binding_name("bytes_in", "tier")
4941        );
4942    }
4943
4944    /// A phase with a `metrics:` block (and no poll) synthesises a
4945    /// `volatile phase_start := phase_start_millis()` origin binding plus one
4946    /// `volatile __metric_<name> := <value>` per metric. The phase's own
4947    /// bindings are appended verbatim.
4948    ///
4949    /// `phase_start` was an `extern … = 0` filled by the executor at the
4950    /// completion-time pull, which meant anything reading it while the phase
4951    /// ran got the default.
4952    #[test]
4953    fn synthesize_phase_scope_bindings_emits_metric_bindings() {
4954        use nmbrs_workload::model::{BindingsDef, MetricSpec, WorkloadPhase};
4955        let mut metrics = std::collections::HashMap::new();
4956        metrics.insert(
4957            "time_to_index".to_string(),
4958            MetricSpec {
4959                value: "current_epoch_millis() - phase_start".into(),
4960                family: None,
4961                kind: None,
4962                unit: None,
4963                format: None,
4964                cell: Default::default(),
4965            },
4966        );
4967        let phase = WorkloadPhase {
4968            bindings: BindingsDef::default(),
4969            metrics,
4970            poll: None,
4971            ..Default::default()
4972        };
4973        let out = synthesize_phase_scope_bindings(&phase).expect("metrics synthesis");
4974        let src = match out {
4975            BindingsDef::PolydatSource(s) => s,
4976            other => panic!("expected PolydatSource, got {other:?}"),
4977        };
4978        // Bound to the runtime's phase clock, NOT an extern: as an extern it
4979        // was filled only at the completion-time pull, so anything reading it
4980        // while the phase ran (an op) got the 0 default and computed against
4981        // the epoch.
4982        assert!(
4983            src.contains("volatile phase_start := phase_start_millis()"),
4984            "must bind phase_start to the phase-scoped clock; got:\n{src}"
4985        );
4986        assert!(
4987            !src.contains("extern phase_start"),
4988            "the fill-me-in extern must be gone; got:\n{src}"
4989        );
4990        assert!(
4991            src.contains("volatile __metric_time_to_index := current_epoch_millis() - phase_start"),
4992            "must emit the volatile metric binding; got:\n{src}"
4993        );
4994        // The emitted source must compile as a phase kernel body, with
4995        // `__metric_time_to_index` surfacing as an output.
4996        let kernel = crate::scope_kernel::ScopeKernel::compile(&src)
4997            .unwrap_or_else(|e| panic!("compile failed:\n{src}\nerror: {e}"));
4998        assert!(
4999            kernel
5000                .program()
5001                .output_names()
5002                .contains(&"__metric_time_to_index"),
5003            "metric binding must be a kernel output; outputs: {:?}",
5004            kernel.program().output_names()
5005        );
5006    }
5007
5008    /// SRD-75 Push 2: when a phase has `poll:` and ops with
5009    /// declared captures, the synthesized source carries one
5010    /// `shared <name>: u64 := 0` declaration per capture
5011    /// followed by the predicate binding `__poll_until :=
5012    /// <until>`. The original phase bindings (if any) are
5013    /// appended verbatim between the captures and the
5014    /// predicate.
5015    #[test]
5016    fn synthesize_phase_scope_bindings_emits_shared_captures_and_predicate() {
5017        use nmbrs_workload::bindpoints::CapturePoint;
5018        use nmbrs_workload::model::{BindingsDef, ParsedOp, PhasePollSpec, WorkloadPhase};
5019        let mut op = ParsedOp::simple("read_state", "noop");
5020        op.captures = vec![
5021            CapturePoint {
5022                row_filter: None,
5023                source_name: "sstables".into(),
5024                as_name: "sstables".into(),
5025                cast_type: None,
5026                slurp: false,
5027                path: Some("/0/value".into()),
5028                count: false,
5029                agg: None,
5030            },
5031            CapturePoint {
5032                row_filter: None,
5033                source_name: "active_for_cf".into(),
5034                as_name: "active_for_cf".into(),
5035                cast_type: None,
5036                slurp: false,
5037                path: Some("/1/value".into()),
5038                count: true,
5039                agg: None,
5040            },
5041        ];
5042        let phase = WorkloadPhase {
5043            ops: vec![op],
5044            bindings: BindingsDef::PolydatSource("dummy := 1\n".into()),
5045            poll: Some(PhasePollSpec {
5046                until: "sstables == 1 && active_for_cf == 0".into(),
5047                ..Default::default()
5048            }),
5049            ..Default::default()
5050        };
5051        let out = synthesize_phase_scope_bindings(&phase).expect("poll synthesis should succeed");
5052        let src = match out {
5053            BindingsDef::PolydatSource(s) => s,
5054            other => panic!("expected PolydatSource, got {other:?}"),
5055        };
5056        assert!(
5057            src.contains("shared sstables := 0"),
5058            "missing shared declaration for sstables; source:\n{src}"
5059        );
5060        assert!(
5061            src.contains("shared active_for_cf := 0"),
5062            "missing shared declaration for active_for_cf; source:\n{src}"
5063        );
5064        assert!(
5065            src.contains("dummy := 1"),
5066            "original phase bindings should appear verbatim; source:\n{src}"
5067        );
5068        assert!(
5069            src.contains("__poll_until := sstables == 1 && active_for_cf == 0"),
5070            "missing __poll_until predicate binding; source:\n{src}"
5071        );
5072        // Order matters: captures first (so the predicate's
5073        // RHS references resolve through the local shared
5074        // declarations before the dynamic binding evaluates).
5075        let shared_pos = src
5076            .find("shared sstables")
5077            .expect("shared sstables present");
5078        let until_binding = crate::wrappers::condition::UNTIL_BINDING;
5079        let until_pos = src
5080            .find(until_binding)
5081            .expect("poll predicate binding present");
5082        assert!(
5083            shared_pos < until_pos,
5084            "shared captures must precede __poll_until in the synthesized source"
5085        );
5086    }
5087
5088    /// SRD-75 Push 2: a capture name that collides with an
5089    /// author-declared phase binding is a workload bug —
5090    /// the synthesizer surfaces the collision rather than
5091    /// silently shadowing.
5092    #[test]
5093    fn synthesize_phase_scope_bindings_rejects_capture_name_collision() {
5094        use nmbrs_workload::bindpoints::CapturePoint;
5095        use nmbrs_workload::model::{BindingsDef, ParsedOp, PhasePollSpec, WorkloadPhase};
5096        let mut op = ParsedOp::simple("read_state", "noop");
5097        op.captures = vec![CapturePoint {
5098            row_filter: None,
5099            source_name: "sstables".into(),
5100            as_name: "sstables".into(),
5101            cast_type: None,
5102            slurp: false,
5103            path: Some("/0/value".into()),
5104            count: false,
5105            agg: None,
5106        }];
5107        // Phase author also declared `sstables := …` —
5108        // collision is the bug.
5109        let phase = WorkloadPhase {
5110            ops: vec![op],
5111            bindings: BindingsDef::PolydatSource("sstables := 7\n".into()),
5112            poll: Some(PhasePollSpec {
5113                until: "sstables == 1".into(),
5114                ..Default::default()
5115            }),
5116            ..Default::default()
5117        };
5118        let err =
5119            synthesize_phase_scope_bindings(&phase).expect_err("colliding capture name must error");
5120        assert!(
5121            err.contains("sstables") && err.contains("collision"),
5122            "expected error to name 'sstables' and 'collision'; got: {err}"
5123        );
5124    }
5125
5126    #[test]
5127    fn build_phase_scope_kernel_with_mod_in_binding_over_partition_iter_var() {
5128        // Matches the production workload shape:
5129        //   for: "p in partitions(\"linear:3\")"
5130        //   phases.walk.bindings: n := mod_in(cycle, p)
5131        //
5132        // The phase compile must see `p` as Ext so mod_in's
5133        // second arg (Partition input) type-checks. Reproduces
5134        // the integration error "u64 ─▶ ext expects ext".
5135        let parent_kernel = crate::scope_synth::build_for_each_scope_kernel(
5136            &[("p".to_string(), "partitions(\"linear:3\")".to_string())],
5137            &[],
5138            &crate::scope_kernel::ScopeKernel::compile("\n").unwrap(),
5139            &HashMap::new(),
5140            Vec::new(),
5141            None,
5142            false,
5143            "test_for_each",
5144            None,
5145        )
5146        .expect("for-each scope synthesis");
5147
5148        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5149            "n := mod_in(cycle, p)\n".to_string(),
5150        );
5151        let phase_kernel = build_phase_scope_kernel(
5152            &phase_bindings,
5153            &[],
5154            &parent_kernel,
5155            &HashMap::new(),
5156            Vec::new(),
5157            None,
5158            false,
5159            "test_phase",
5160        )
5161        .expect("phase kernel build with mod_in(cycle, p) binding");
5162
5163        // Sanity: phase has p as Ext-typed input slot.
5164        assert_eq!(
5165            phase_kernel.program().input_port_type("p"),
5166            Some(polydat::ast::PortType::Ext),
5167            "phase kernel's `p` must be Ext-typed",
5168        );
5169        // Sanity: phase has `n` as an output (the mod_in result).
5170        assert!(
5171            phase_kernel.program().output_names().contains(&"n"),
5172            "phase kernel should expose `n` as an output"
5173        );
5174    }
5175
5176    #[test]
5177    fn build_phase_scope_kernel_cascades_partition_iter_var_as_extern_ext() {
5178        // SRD-71: when a for-each scope iterates a PartitionList
5179        // and binds an iter-var `p`, descendant phases must see
5180        // `p` as `extern p: ext` — NOT cast to str / u64 by
5181        // the cascade. The phase body's `over p` clause then
5182        // resolves `p` as a partition-typed wire.
5183        //
5184        // Reproduces the integration failure where the phase's
5185        // build_phase_scope_kernel cascade was emitting
5186        // `extern p: u64` (or Str fallback) because the
5187        // type-name lookup didn't handle PortType::Ext.
5188        let parent_kernel = crate::scope_synth::build_for_each_scope_kernel(
5189            &[("p".to_string(), "partitions(\"linear:3\")".to_string())],
5190            &[], // empty parent_manifest is fine; for_each scope only
5191            // cascades names it actually references.
5192            &crate::scope_kernel::ScopeKernel::compile("\n").unwrap(),
5193            &HashMap::new(),
5194            Vec::new(),
5195            None,
5196            false,
5197            "test_for_each",
5198            None,
5199        )
5200        .expect("for-each scope synthesis");
5201
5202        // Sanity: the for-each scope's iter-var p is Ext-typed.
5203        assert_eq!(
5204            parent_kernel.program().input_port_type("p"),
5205            Some(polydat::ast::PortType::Ext),
5206            "for-each scope's iter-var `p` must declare as Ext",
5207        );
5208
5209        // Now build a phase under it that references `p` in a
5210        // cursor's `over` clause.
5211        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5212            "cursor row = range(0, 1000) over p\n".to_string(),
5213        );
5214        let phase_kernel = build_phase_scope_kernel(
5215            &phase_bindings,
5216            &[],
5217            &parent_kernel,
5218            &HashMap::new(),
5219            Vec::new(),
5220            None,
5221            false,
5222            "test_phase",
5223        )
5224        .expect("phase kernel build");
5225
5226        // The phase kernel must see `p` as Ext-typed.
5227        let port_type = phase_kernel.program().input_port_type("p");
5228        assert_eq!(
5229            port_type,
5230            Some(polydat::ast::PortType::Ext),
5231            "phase kernel's `p` slot must be Ext (preserved through cascade), got {port_type:?}"
5232        );
5233    }
5234
5235    #[test]
5236    fn build_phase_scope_kernel_cascades_shared_bool_as_extern_bool() {
5237        // SRD-13d §1: "The kernel auto-externs every name it
5238        // doesn't declare locally; those externs resolve up
5239        // through the phase kernel and beyond per the standard
5240        // SRD-13c chain."
5241        //
5242        // SRD-66 §"Surface 2": a workload-root `shared X :=
5243        // <literal>` becomes a `SharedCell`-backed slot at the
5244        // root. Descendant phases declare `extern X: bool` (or
5245        // auto-extern emits it); bind_outer_scope cell-attaches
5246        // the slot.
5247        //
5248        // SRD-13c §"Shared Mutable" step 1: `shared X := <literal>`
5249        // produces an input slot Bool (kind=ExternalWrite) plus a
5250        // passthrough output Bool, modifier SHARED.
5251        //
5252        // This unit-test verifies the documented type-preservation
5253        // contract: a phase scope built via build_phase_scope_kernel
5254        // against a parent kernel carrying a SHARED Bool output
5255        // must produce a phase-scope kernel whose has_X input slot
5256        // is type Bool, NOT typed U64 / not classified Coordinate.
5257        // Without this property, the SharedCell that bind_outer_scope
5258        // attaches gets a slot whose declared type doesn't match
5259        // the cell's actual Value variant — downstream consumers
5260        // (e.g. pick) see the runtime variant and reject it.
5261        let parent = crate::scope_kernel::ScopeKernel::compile(
5262            "input cycle: u64\nshared has_sai_column_indexes := false\n\
5263             shared has_indexes := false\n",
5264        )
5265        .expect("parent compile");
5266        // The phase has its own bindings block (the await_index shape).
5267        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5268            "target_index_table := pick(has_sai_column_indexes, has_indexes, \
5269             \"a\", \"b\")\n"
5270                .to_string(),
5271        );
5272        let phase_kernel = build_phase_scope_kernel(
5273            &phase_bindings,
5274            &[], // outer_manifest (would be populated in real runner, but builder doesn't strictly need it)
5275            &parent,
5276            &HashMap::new(),
5277            Vec::new(),
5278            None,
5279            false,
5280            "test_phase",
5281        )
5282        .expect("phase kernel build");
5283
5284        // The phase kernel must have has_X as an input slot.
5285        let idx_sai = phase_kernel.program().find_input("has_sai_column_indexes");
5286        assert!(
5287            idx_sai.is_some(),
5288            "phase kernel must have `has_sai_column_indexes` input slot"
5289        );
5290        let idx = idx_sai.unwrap();
5291
5292        // Type must be Bool (per SRD-13c §"Shared Mutable" step 1
5293        // + SRD-66 §"Reading from a downstream phase").
5294        let port_type = phase_kernel
5295            .program()
5296            .input_port_type("has_sai_column_indexes");
5297        assert_eq!(
5298            port_type,
5299            Some(polydat::ast::PortType::Bool),
5300            "phase kernel's has_sai_column_indexes slot must be Bool, got {port_type:?}"
5301        );
5302
5303        // Kind must NOT be Coordinate — cascaded names are IterationExtern
5304        // (or ExternalWrite), not Coordinate. Coordinate would put the slot
5305        // in the set_inputs(&[u64]) propagation, breaking the cell-bound
5306        // contract per SRD-13c §"Shared Mutable" step 3.
5307        let kind = phase_kernel.program().input_kind(idx);
5308        assert_ne!(
5309            kind,
5310            Some(polydat::kernel::InputKind::Coordinate),
5311            "phase kernel's has_sai_column_indexes slot must NOT be Coordinate; got {kind:?}"
5312        );
5313    }
5314
5315    #[test]
5316    fn executor_build_scope_emits_extern_bool_for_cell_backed_shared_wire() {
5317        // Reproduces the executor's specific build_scope call
5318        // sequence for the consume phase:
5319        //
5320        //   1. Build the phase scope kernel via build_phase_scope_kernel
5321        //      (this is what the runner's install pass does).
5322        //   2. Call build_scope(ops, ..., parent_kernel=phase_scope)
5323        //      with phase_scope as classifier_kernel — this is
5324        //      what executor.rs:1429 does at run_phase time.
5325        //   3. compile_from_scope(scope, ...) — produces the
5326        //      iter_op_builder kernel that dryrun=wiring dumps.
5327        //
5328        // The integration test
5329        // `shared_bool_through_for_each_into_consumer_phase_bindings`
5330        // proves this whole sequence produces a kernel with has_X
5331        // as `coordinate` U64. This unit test reproduces it without
5332        // a subprocess so we can inspect every intermediate state.
5333        use polydat::kernel::extract_manifest;
5334
5335        // ── workload root ──
5336        let root = crate::scope_kernel::ScopeKernel::compile(
5337            "shared has_a := true\n\
5338             shared has_b := false\n\
5339             selector := mod(cycle, 1)\n",
5340        )
5341        .expect("workload root compile");
5342
5343        // ── for_each scope ──
5344        let for_each = crate::scope_synth::build_for_each_scope_kernel(
5345            &[("outer".to_string(), "p1,p2".to_string())],
5346            &extract_manifest(root.program()),
5347            &root,
5348            &HashMap::new(),
5349            Vec::new(),
5350            None,
5351            false,
5352            "test_for_each",
5353            None,
5354        )
5355        .expect("for_each synth");
5356
5357        // ── phase scope kernel (cached_kernel) ──
5358        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5359            "chosen := pick(has_a, has_b, \"alpha\", \"beta\")\n".to_string(),
5360        );
5361        let phase_scope = build_phase_scope_kernel(
5362            &phase_bindings,
5363            &[],
5364            &for_each,
5365            &HashMap::new(),
5366            Vec::new(),
5367            None,
5368            false,
5369            "test_phase",
5370        )
5371        .expect("phase scope synth");
5372
5373        // ── executor's build_scope call ──
5374        let op = ParsedOp::simple("report", "consume chosen={chosen}");
5375        let ops = vec![op];
5376        let effective_manifest: Vec<crate::runner::ManifestEntry> =
5377            extract_manifest(phase_scope.program())
5378                .into_iter()
5379                .map(|e| crate::runner::ManifestEntry {
5380                    name: e.name,
5381                    port_type: e.port_type,
5382                    modifier: e.modifier,
5383                })
5384                .collect();
5385        let scope = build_scope(
5386            &ops,
5387            &HashMap::new(),
5388            &effective_manifest,
5389            &HashMap::new(),
5390            &HashMap::new(),
5391            None,
5392            &[],
5393            Some(&phase_scope),
5394        )
5395        .expect("executor build_scope");
5396
5397        // ── inspect what build_scope emits ──
5398        let emitted = scope.emit();
5399
5400        // ── compile_from_scope equivalent — uses the SAME compile
5401        // path the executor takes (compile_polydat_interpreter_with_options with
5402        // the scope's required_outputs filter).
5403        let required = scope.required_outputs();
5404        let executor_kernel = polydat::dsl::compile::compile_polydat_interpreter_with_options(
5405            &emitted,
5406            &polydat::dsl::compile::CompileOptions {
5407                required_outputs: required.clone(),
5408                context: "test".to_string(),
5409                ..Default::default()
5410            },
5411            None,
5412        )
5413        .unwrap_or_else(|e| {
5414            panic!("compile failed: {e}\nemitted source:\n{emitted}\nrequired: {required:?}")
5415        });
5416
5417        // The executor's kernel must have has_a as Bool (or absent
5418        // entirely if not referenced). It MUST NOT be Coordinate U64.
5419        if let Some(idx) = executor_kernel.program().find_input("has_a") {
5420            let typ = executor_kernel.program().input_port_type("has_a");
5421            assert_eq!(
5422                typ,
5423                Some(polydat::ast::PortType::Bool),
5424                "executor kernel's has_a slot must be Bool;\n\
5425                 got {typ:?}\n\
5426                 emitted source:\n{emitted}\n\
5427                 input names: {:?}\n\
5428                 coord_count: {}",
5429                executor_kernel.program().input_names(),
5430                executor_kernel.program().coord_count()
5431            );
5432            let kind = executor_kernel.program().input_kind(idx);
5433            assert_ne!(
5434                kind,
5435                Some(polydat::kernel::InputKind::Coordinate),
5436                "executor kernel's has_a slot must NOT be Coordinate;\n\
5437                 got {kind:?}\n\
5438                 emitted source:\n{emitted}\n\
5439                 input names: {:?}\n\
5440                 coord_count: {}",
5441                executor_kernel.program().input_names(),
5442                executor_kernel.program().coord_count()
5443            );
5444        }
5445    }
5446
5447    #[test]
5448    fn full_chain_workload_to_executor_scope_preserves_shared_bool() {
5449        // Chains through every layer the failing integration test
5450        // touches, in-process, with the same shape that triggers
5451        // the failure:
5452        //
5453        //   1. params kernel (workload params as `const` bindings).
5454        //   2. workload-root kernel via the `compile_bindings_with_libs_excluding`-style
5455        //      flow: build_scope + scope.ingest_polydat_source + parent.build_subscope.
5456        //   3. for_each scope kernel (outer iter var).
5457        //   4. for_each scope kernel (inner with multi-iter clause).
5458        //   5. phase scope kernel via build_phase_scope_kernel (consume).
5459        //   6. executor's build_scope + compile_polydat_with_libs_and_limit.
5460        //
5461        // Verifies at the END that the consumer phase's executor-
5462        // compiled kernel has has_a as Bool/non-Coordinate.
5463        use nmbrs_workload::model::ParsedOp;
5464        use polydat::kernel::extract_manifest;
5465
5466        // Step 1: params kernel.
5467        let mut workload_params: HashMap<String, String> = HashMap::new();
5468        workload_params.insert("dataset".to_string(), "example_dataset".to_string());
5469        workload_params.insert("prefix".to_string(), "px_".to_string());
5470        let mut sorted: Vec<&String> = workload_params.keys().collect();
5471        sorted.sort();
5472        let mut params_source = String::new();
5473        for k in sorted {
5474            params_source.push_str(&format!("const {k} := \"{}\"\n", workload_params[k]));
5475        }
5476        let params_kernel =
5477            crate::scope_kernel::ScopeKernel::compile(&params_source).expect("params compile");
5478
5479        // Step 2: workload-root kernel.
5480        let mut scope = build_scope(
5481            &[] as &[ParsedOp],
5482            &HashMap::new(),
5483            &[],
5484            &workload_params,
5485            &HashMap::new(),
5486            None,
5487            &[],
5488            None,
5489        )
5490        .expect("workload root build_scope");
5491        // KEY: the binding RHS uses string interpolation against
5492        // workload params. This is what triggers the chain
5493        // corruption — without it, the test passes; with it, the
5494        // integration test fails.
5495        let workload_level_polydat = "combo_label := str_concat(\"{dataset}\", \"{prefix}\")\n\
5496                                 shared has_a := true\n\
5497                                 shared has_b := false\n";
5498        scope.ingest_polydat_source(workload_level_polydat, BindingOrigin::Inherited);
5499        let root_source = scope.emit();
5500        let root = crate::scope_kernel::ScopeKernel::build_under(
5501            params_kernel.kernel(),
5502            crate::scope_kernel::SourceMatter::source(
5503                "test_root",
5504                root_source.clone(),
5505                polydat::kernel::subcontext::CompileOptions {
5506                    workload_dir: None,
5507                    polydat_lib_paths: Vec::new(),
5508                    strict: false,
5509                    required_outputs: scope.required_outputs(),
5510                    context_label: Some("test_root".to_string()),
5511                    cursor_limit: None,
5512                    ..Default::default()
5513                },
5514            ),
5515        )
5516        .expect("root build");
5517
5518        // Sanity: has_a SHARED at root.
5519        let shared = root.program().shared_outputs();
5520        assert!(
5521            shared.contains(&"has_a"),
5522            "root should have has_a as SHARED output; got {shared:?}"
5523        );
5524
5525        // Step 3: outer for_each scope.
5526        let outer_fe = crate::scope_synth::build_for_each_scope_kernel(
5527            &[("outer".to_string(), "p1,p2".to_string())],
5528            &extract_manifest(root.program()),
5529            &root,
5530            &workload_params,
5531            Vec::new(),
5532            None,
5533            false,
5534            "test_outer_fe",
5535            None,
5536        )
5537        .expect("outer for_each synth");
5538
5539        // Step 4: inner for_each scope (dependent multi-iter).
5540        let inner_fe = crate::scope_synth::build_for_each_scope_kernel(
5541            &[
5542                ("inner".to_string(), "lo,hi".to_string()),
5543                ("label".to_string(), "tag_p1_lo,tag_p1_hi".to_string()),
5544            ],
5545            &extract_manifest(outer_fe.program()),
5546            &outer_fe,
5547            &workload_params,
5548            Vec::new(),
5549            None,
5550            false,
5551            "test_inner_fe",
5552            None,
5553        )
5554        .expect("inner for_each synth");
5555
5556        // Step 5: phase scope kernel for consume.
5557        let phase_bindings = BindingsDef::PolydatSource(
5558            "chosen := pick(has_a, has_b, \"alpha\", \"beta\")\n".to_string(),
5559        );
5560        let phase_scope = build_phase_scope_kernel(
5561            &phase_bindings,
5562            &[],
5563            &inner_fe,
5564            &workload_params,
5565            Vec::new(),
5566            None,
5567            false,
5568            "test_consume_phase",
5569        )
5570        .expect("consume phase synth");
5571
5572        // Step 6: executor's build_scope on the consume phase.
5573        let op = ParsedOp::simple("report", "spc/consume chosen={chosen}");
5574        let ops = vec![op];
5575        let effective_manifest: Vec<crate::runner::ManifestEntry> =
5576            extract_manifest(phase_scope.program())
5577                .into_iter()
5578                .map(|e| crate::runner::ManifestEntry {
5579                    name: e.name,
5580                    port_type: e.port_type,
5581                    modifier: e.modifier,
5582                })
5583                .collect();
5584        let exec_scope = build_scope(
5585            &ops,
5586            &HashMap::new(),
5587            &effective_manifest,
5588            &HashMap::new(),
5589            &HashMap::new(),
5590            None,
5591            &[],
5592            Some(&phase_scope),
5593        )
5594        .expect("executor build_scope");
5595
5596        let exec_source = exec_scope.emit();
5597        let exec_kernel = polydat::dsl::compile::compile_polydat_interpreter_with_options(
5598            &exec_source,
5599            &polydat::dsl::compile::CompileOptions {
5600                required_outputs: exec_scope.required_outputs(),
5601                context: "test_executor".to_string(),
5602                ..Default::default()
5603            },
5604            None,
5605        )
5606        .unwrap_or_else(|e| panic!("exec compile failed: {e}\nexec source:\n{exec_source}"));
5607
5608        // The final kernel — what the dryrun=wiring dumps — must
5609        // have has_a as Bool/non-Coordinate.
5610        if let Some(idx) = exec_kernel.program().find_input("has_a") {
5611            let typ = exec_kernel.program().input_port_type("has_a");
5612            assert_eq!(
5613                typ,
5614                Some(polydat::ast::PortType::Bool),
5615                "FINAL kernel has_a must be Bool, got {typ:?}\n\
5616                 exec source:\n{exec_source}\n\
5617                 exec input_names: {:?}\n\
5618                 exec coord_count: {}",
5619                exec_kernel.program().input_names(),
5620                exec_kernel.program().coord_count()
5621            );
5622            let kind = exec_kernel.program().input_kind(idx);
5623            assert_ne!(
5624                kind,
5625                Some(polydat::kernel::InputKind::Coordinate),
5626                "FINAL kernel has_a must NOT be Coordinate, got {kind:?}\n\
5627                 exec source:\n{exec_source}\n\
5628                 exec input_names: {:?}\n\
5629                 exec coord_count: {}",
5630                exec_kernel.program().input_names(),
5631                exec_kernel.program().coord_count()
5632            );
5633        }
5634    }
5635
5636    #[test]
5637    fn workload_root_via_compile_bindings_preserves_shared_bool_type() {
5638        // Mirrors the runner's WORKLOAD-ROOT build flow:
5639        //   compile_bindings_with_libs_excluding(
5640        //     parent=params_kernel,
5641        //     ops=all_ops,
5642        //     workload_params=<non-empty>,
5643        //     workload_level_polydat=Some(<the bindings: block>),
5644        //   )
5645        //
5646        // The actual function takes a complex set of args; here
5647        // we replicate the essential moves to expose what differs
5648        // from a direct `compile_polydat_interpreter(source)` invocation.
5649        //
5650        // SRD-13c §"Shared Mutable" requires has_a to be ExternalWrite
5651        // kind, Bool type on the workload-root program. The
5652        // dryrun=wiring output of the failing integration test shows
5653        // the downstream phase has has_a as Coordinate U64, so
5654        // either the workload-root or a downstream synthesizer
5655        // emits the wrong source for it.
5656        use nmbrs_workload::model::ParsedOp;
5657
5658        let mut workload_params: HashMap<String, String> = HashMap::new();
5659        workload_params.insert("dataset".to_string(), "example_dataset".to_string());
5660        workload_params.insert("prefix".to_string(), "px_".to_string());
5661        workload_params.insert("keyspace".to_string(), "ks1".to_string());
5662        workload_params.insert("inner_options".to_string(), "lo,hi".to_string());
5663
5664        // Workload params reach the root via a sibling params
5665        // kernel. Construct one with each param as a final binding.
5666        let mut params_source = String::new();
5667        let mut sorted: Vec<&String> = workload_params.keys().collect();
5668        sorted.sort();
5669        for k in sorted {
5670            let v = &workload_params[k];
5671            params_source.push_str(&format!("const {k} := \"{v}\"\n"));
5672        }
5673        let params_kernel =
5674            crate::scope_kernel::ScopeKernel::compile(&params_source).expect("params compile");
5675
5676        // The workload's `bindings:` block. The trigger.
5677        let workload_level_polydat = "selector := mod(cycle, 1)\n\
5678                                 shared has_a := true\n\
5679                                 shared has_b := false\n";
5680
5681        // Build the workload-root scope as compile_bindings_with_libs_excluding does.
5682        let mut scope = build_scope(
5683            &[] as &[ParsedOp],
5684            &HashMap::new(),
5685            &[],
5686            &workload_params,
5687            &HashMap::new(),
5688            None,
5689            &[],
5690            None,
5691        )
5692        .expect("build_scope");
5693        scope.ingest_polydat_source(workload_level_polydat, BindingOrigin::Inherited);
5694
5695        // The actual workload-root compile goes through
5696        // parent.build_subscope. Build the matter and finalize.
5697        let source = scope.emit();
5698        let opts = polydat::kernel::subcontext::CompileOptions {
5699            workload_dir: None,
5700            polydat_lib_paths: Vec::new(),
5701            strict: false,
5702            required_outputs: scope.required_outputs(),
5703            context_label: Some("test_workload_root".to_string()),
5704            cursor_limit: None,
5705            ..Default::default()
5706        };
5707        let root = crate::scope_kernel::ScopeKernel::build_under(
5708            params_kernel.kernel(),
5709            crate::scope_kernel::SourceMatter::source("test_workload_root", source.clone(), opts),
5710        )
5711        .expect("workload root build");
5712
5713        // The workload-root program must have has_a:
5714        //   - present as an input slot,
5715        //   - typed Bool (SRD-13c §"Shared Mutable" step 1),
5716        //   - kind ExternalWrite (NOT Coordinate),
5717        //   - marked SHARED in output_modifier (so seed_shared_cells fires).
5718        let has_a_idx = root.program().find_input("has_a").unwrap_or_else(|| {
5719            panic!(
5720                "workload root missing has_a input;\n\
5721                 emitted scope source:\n{source}\n\
5722                 input names: {:?}",
5723                root.program().input_names()
5724            )
5725        });
5726
5727        let typ = root.program().input_port_type("has_a");
5728        assert_eq!(
5729            typ,
5730            Some(polydat::ast::PortType::Bool),
5731            "workload root has_a must be Bool;\n\
5732             got {typ:?}\n\
5733             emitted source:\n{source}\n\
5734             input names: {:?}\n\
5735             coord_count: {}",
5736            root.program().input_names(),
5737            root.program().coord_count()
5738        );
5739
5740        let kind = root.program().input_kind(has_a_idx);
5741        assert_ne!(
5742            kind,
5743            Some(polydat::kernel::InputKind::Coordinate),
5744            "workload root has_a must NOT be Coordinate;\n\
5745             got {kind:?}\n\
5746             emitted source:\n{source}\n\
5747             input names: {:?}\n\
5748             coord_count: {}",
5749            root.program().input_names(),
5750            root.program().coord_count()
5751        );
5752
5753        let modifier = root.program().output_modifier("has_a");
5754        assert_eq!(
5755            modifier,
5756            polydat::dsl::ast::BindingModifier::SHARED,
5757            "workload root has_a output must have SHARED modifier;\n\
5758             got {modifier:?}"
5759        );
5760
5761        let shared = root.program().shared_outputs();
5762        assert!(
5763            shared.contains(&"has_a"),
5764            "workload root must have has_a in shared_outputs (so seed_shared_cells creates a cell);\n\
5765             got shared_outputs={shared:?}"
5766        );
5767    }
5768
5769    #[test]
5770    fn shared_bool_survives_when_workload_root_also_has_cycle_binding() {
5771        // BISECTED INTEGRATION FAILURE: adding any non-shared
5772        // workload-level binding that references `cycle`
5773        // (e.g. `selector := mod(cycle, 1)`) alongside the
5774        // SHARED bool wires causes the consumer phase's phase
5775        // scope kernel to have has_X classified as Coordinate
5776        // input slots typed U64 instead of cascaded externs
5777        // typed Bool.
5778        //
5779        // Manifests at runtime as: per-cycle `set_inputs(&[u64])`
5780        // clobbers the shared cells with `Value::U64(cycle)`,
5781        // and `pick(has_X, …)` panics with "non-bool type U64".
5782        //
5783        // This unit test walks the same scope chain
5784        // programmatically and pins the contract at each hop:
5785        //   workload root (shared bool + cycle-referencing binding)
5786        //     → for_each scope (synthesize_for_each_scope)
5787        //       → phase scope (build_phase_scope_kernel)
5788        // Asserts has_a stays Bool + non-Coordinate kind at every
5789        // layer.
5790        use polydat::kernel::extract_manifest;
5791
5792        // Step 1: workload root with shared bool AND a
5793        // non-shared cycle binding. The trigger.
5794        let root = crate::scope_kernel::ScopeKernel::compile(
5795            "shared has_a := true\n\
5796             shared has_b := false\n\
5797             selector := mod(cycle, 1)\n",
5798        )
5799        .expect("workload root compile");
5800
5801        // Workload-root contract: has_a is Bool ExternalWrite slot
5802        // (SRD-13c §"Shared Mutable" step 1).
5803        let root_has_a_idx = root
5804            .program()
5805            .find_input("has_a")
5806            .expect("workload root has_a slot");
5807        let root_has_a_type = root.program().input_port_type("has_a");
5808        assert_eq!(
5809            root_has_a_type,
5810            Some(polydat::ast::PortType::Bool),
5811            "workload root has_a must be Bool"
5812        );
5813        let root_has_a_kind = root.program().input_kind(root_has_a_idx);
5814        assert_ne!(
5815            root_has_a_kind,
5816            Some(polydat::kernel::InputKind::Coordinate),
5817            "workload root has_a must NOT be Coordinate; got {root_has_a_kind:?}"
5818        );
5819
5820        // Step 2: for_each scope.
5821        let for_each = crate::scope_synth::build_for_each_scope_kernel(
5822            &[("outer".to_string(), "p1,p2".to_string())],
5823            &extract_manifest(root.program()),
5824            &root,
5825            &HashMap::new(),
5826            Vec::new(),
5827            None,
5828            false,
5829            "test_for_each",
5830            None,
5831        )
5832        .expect("for_each synth");
5833
5834        let fe_has_a_idx = for_each
5835            .program()
5836            .find_input("has_a")
5837            .expect("for_each has_a slot");
5838        let fe_has_a_type = for_each.program().input_port_type("has_a");
5839        assert_eq!(
5840            fe_has_a_type,
5841            Some(polydat::ast::PortType::Bool),
5842            "for_each has_a must be Bool, got {fe_has_a_type:?}"
5843        );
5844        let fe_has_a_kind = for_each.program().input_kind(fe_has_a_idx);
5845        assert_ne!(
5846            fe_has_a_kind,
5847            Some(polydat::kernel::InputKind::Coordinate),
5848            "for_each has_a must NOT be Coordinate; got {fe_has_a_kind:?}"
5849        );
5850
5851        // Step 3: phase scope with its own bindings via pick.
5852        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5853            "chosen := pick(has_a, has_b, \"alpha\", \"beta\")\n".to_string(),
5854        );
5855        let phase = build_phase_scope_kernel(
5856            &phase_bindings,
5857            &[],
5858            &for_each,
5859            &HashMap::new(),
5860            Vec::new(),
5861            None,
5862            false,
5863            "test_phase",
5864        )
5865        .expect("phase scope synth");
5866
5867        let phase_has_a_idx = phase
5868            .program()
5869            .find_input("has_a")
5870            .expect("phase has_a slot");
5871        let phase_has_a_type = phase.program().input_port_type("has_a");
5872        assert_eq!(
5873            phase_has_a_type,
5874            Some(polydat::ast::PortType::Bool),
5875            "phase has_a must be Bool; got {phase_has_a_type:?}\n\
5876             phase input names: {:?}",
5877            phase.program().input_names()
5878        );
5879        let phase_has_a_kind = phase.program().input_kind(phase_has_a_idx);
5880        assert_ne!(
5881            phase_has_a_kind,
5882            Some(polydat::kernel::InputKind::Coordinate),
5883            "phase has_a must NOT be Coordinate; got {phase_has_a_kind:?}\n\
5884             phase input names: {:?}\n\
5885             coord_count: {}",
5886            phase.program().input_names(),
5887            phase.program().coord_count()
5888        );
5889    }
5890
5891    #[test]
5892    fn for_each_then_phase_preserves_shared_bool_through_chain() {
5893        // The full chain the workload exercises:
5894        //   workload root (shared has_X := false)
5895        //     → for_each scope (cascades has_X via synthesize_for_each_scope)
5896        //       → phase scope await_index (cascades has_X via build_phase_scope_kernel)
5897        //
5898        // SRD-13c §"Shared Mutable" + SRD-13d §1: at every cascade
5899        // hop, has_X stays Bool-typed and non-Coordinate.
5900        // bind_outer_scope then cell-attaches at each level so
5901        // the original SharedCell reaches the leaf.
5902        use polydat::kernel::extract_manifest;
5903        let root = crate::scope_kernel::ScopeKernel::compile(
5904            "input cycle: u64\nshared has_sai_column_indexes := false\n\
5905             shared has_indexes := false\n",
5906        )
5907        .expect("root compile");
5908
5909        // for_each scope synthesised via the comprehension
5910        // synthesizer (the path runner.rs uses for ForComprehension
5911        // install specs). Iter vars are a placeholder so the
5912        // builder runs.
5913        let for_each_kernel = crate::scope_synth::build_for_each_scope_kernel(
5914            &[("dummy_var".to_string(), "1,2".to_string())],
5915            &extract_manifest(root.program()),
5916            &root,
5917            &HashMap::new(), // workload_params
5918            Vec::new(),      // polydat_lib_paths
5919            None,            // workload_dir
5920            false,           // strict
5921            "test_for_each",
5922            None, // phase_bindings
5923        )
5924        .expect("for_each kernel synth");
5925
5926        // for_each's program must carry has_X as a Bool slot too.
5927        let fe_type = for_each_kernel
5928            .program()
5929            .input_port_type("has_sai_column_indexes");
5930        assert_eq!(
5931            fe_type,
5932            Some(polydat::ast::PortType::Bool),
5933            "for_each scope's has_sai_column_indexes must be Bool, got {fe_type:?}"
5934        );
5935        let fe_idx = for_each_kernel
5936            .program()
5937            .find_input("has_sai_column_indexes")
5938            .expect("for_each has has_sai_column_indexes input");
5939        let fe_kind = for_each_kernel.program().input_kind(fe_idx);
5940        assert_ne!(
5941            fe_kind,
5942            Some(polydat::kernel::InputKind::Coordinate),
5943            "for_each scope's has_sai_column_indexes must NOT be Coordinate; got {fe_kind:?}"
5944        );
5945
5946        // Now build await_index's phase scope under for_each
5947        // (the real scope-tree shape).
5948        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5949            "target_index_table := pick(has_sai_column_indexes, has_indexes, \
5950             \"a\", \"b\")\n"
5951                .to_string(),
5952        );
5953        let phase_kernel = build_phase_scope_kernel(
5954            &phase_bindings,
5955            &[],
5956            &for_each_kernel,
5957            &HashMap::new(),
5958            Vec::new(),
5959            None,
5960            false,
5961            "test_await_index",
5962        )
5963        .expect("phase kernel synth");
5964
5965        let phase_type = phase_kernel
5966            .program()
5967            .input_port_type("has_sai_column_indexes");
5968        assert_eq!(
5969            phase_type,
5970            Some(polydat::ast::PortType::Bool),
5971            "phase scope's has_sai_column_indexes must be Bool, got {phase_type:?}"
5972        );
5973        let phase_idx = phase_kernel
5974            .program()
5975            .find_input("has_sai_column_indexes")
5976            .expect("phase has has_sai_column_indexes input");
5977        let phase_kind = phase_kernel.program().input_kind(phase_idx);
5978        assert_ne!(
5979            phase_kind,
5980            Some(polydat::kernel::InputKind::Coordinate),
5981            "phase scope's has_sai_column_indexes must NOT be Coordinate; got {phase_kind:?}"
5982        );
5983    }
5984}
5985
5986/// Strict mode reaches every synthesized scope, and each still compiles:
5987/// strict refuses a source with no `input` declaration, and a synthesized
5988/// scope's coordinates are its parent's, so they are declared for it.
5989#[cfg(test)]
5990mod strict_synthesis_tests {
5991    use super::*;
5992
5993    fn parent() -> crate::scope_kernel::ScopeKernel {
5994        crate::scope_kernel::ScopeKernel::compile("input cycle: u64\nconst k_values := \"1, 10\"\n")
5995            .expect("parent scope")
5996    }
5997
5998    #[test]
5999    fn a_phase_scope_compiles_under_strict() {
6000        let parent = parent();
6001        let manifest = crate::runner::extract_manifest(parent.program());
6002        let kernel = build_phase_scope_kernel(
6003            &nmbrs_workload::model::BindingsDef::PolydatSource("x := cycle + 1\n".into()),
6004            &manifest,
6005            &parent,
6006            &HashMap::new(),
6007            Vec::new(),
6008            None,
6009            true,
6010            "strict phase",
6011        )
6012        .expect("a phase scope compiles under strict");
6013        assert!(kernel.input_names().iter().any(|n| n == "cycle"));
6014    }
6015
6016    #[test]
6017    fn a_do_loop_scope_compiles_under_strict() {
6018        let parent = parent();
6019        let manifest = crate::runner::extract_manifest(parent.program());
6020        build_do_loop_scope_kernel(
6021            Some("i"),
6022            "{i} < 3",
6023            &manifest,
6024            &parent,
6025            &HashMap::new(),
6026            Vec::new(),
6027            None,
6028            true,
6029            "strict do-loop",
6030        )
6031        .expect("a do-loop scope compiles under strict");
6032    }
6033
6034    #[test]
6035    fn a_for_each_scope_compiles_under_strict() {
6036        let parent = parent();
6037        let manifest = crate::runner::extract_manifest(parent.program());
6038        crate::scope_synth::build_for_each_scope_kernel(
6039            &[("k".to_string(), "{k_values}".to_string())],
6040            &manifest,
6041            &parent,
6042            &HashMap::new(),
6043            Vec::new(),
6044            None,
6045            true,
6046            "strict for_each",
6047            None,
6048        )
6049        .expect("a for_each scope compiles under strict");
6050    }
6051}