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.
3514///
3515/// The text is divided by `nmbrs_workload::op_text::pieces`. A later
3516/// reader renders what this one returns, so `\{` and `\}` are kept
3517/// as written.
3518fn resolve_placeholders_in_string(
3519    s: &str,
3520    kernel: &dyn polydat::Kernel,
3521    per_cycle_names: &[String],
3522    field_path: &str,
3523) -> Result<String, Vec<String>> {
3524    use nmbrs_workload::op_text::Piece;
3525
3526    let mut out = String::with_capacity(s.len());
3527    let mut errors: Vec<String> = Vec::new();
3528    for piece in nmbrs_workload::op_text::pieces(s) {
3529        let Piece::Group { raw, body } = piece else {
3530            piece.as_written(&mut out);
3531            continue;
3532        };
3533        // Qualified references, composed names and expressions stay
3534        // as written for the readers downstream.
3535        if !is_bare_ident(body) {
3536            out.push_str(raw);
3537            continue;
3538        }
3539
3540        // Names that are per-cycle (coordinates declared via
3541        // `input (cycle: u64, ...: u64)`, or LHS of phase bindings)
3542        // MUST be deferred to per-cycle resolution. Their value
3543        // varies per iteration; pre-resolving against the parent
3544        // kernel here would bake in iteration 0's value (0) and
3545        // every subsequent iteration would emit the same string.
3546        if per_cycle_names.iter().any(|n| n == body) {
3547            out.push_str(raw);
3548            continue;
3549        }
3550        // Bare ident — try kernel lookup. Computed outputs
3551        // (node-backed) aren't found by `lookup` (it only reads
3552        // input slots + constants), but they ARE valid wires
3553        // visible at this scope — accept them by checking
3554        // `resolve_output`. Per-cycle resolution at dispenser
3555        // time handles the actual pull.
3556        match polydat::kernel::interp::Lookup::lookup(
3557            &polydat::kernel::interp::KernelLookup::new(kernel),
3558            body,
3559        ) {
3560            Some(v) => out.push_str(&v.to_display_string()),
3561            None if kernel.output_index(body).is_some() => {
3562                // Defer to per-cycle resolution. Emit the
3563                // placeholder unchanged.
3564                out.push_str(raw);
3565            }
3566            None => {
3567                errors.push(format!(
3568                    "{field_path}: '{{{body}}}' did not resolve in scope and is \
3569                     not a per-cycle binding declared by this phase"
3570                ));
3571                // Still push the placeholder as-is so the rest of
3572                // the string remains parseable for further error
3573                // collection on the same field.
3574                out.push_str(raw);
3575            }
3576        }
3577    }
3578
3579    if errors.is_empty() {
3580        Ok(out)
3581    } else {
3582        Err(errors)
3583    }
3584}
3585
3586/// Rewrite inline expressions (`{{expr}}`) in op template strings to
3587/// use named binding references (`{__expr_N}`).
3588///
3589/// Returns the expression-to-name map for the caller to know what
3590/// was rewritten. Fails on a malformed bind point, naming the op.
3591pub fn rewrite_inline_exprs(ops: &mut [ParsedOp]) -> Result<HashMap<String, String>, String> {
3592    // SRD-13d: each op template is its own Polydat scope. Inline
3593    // `{{<expr>}}` rewrites are Polydat matter that belongs to the
3594    // op-template scope, not to the shared phase scope. So each
3595    // op gets its OWN expression-to-name mapping, with
3596    // op-locally unique synth names — no cross-op dedup. Two ops
3597    // with textually identical inline expressions
3598    // (`if: cql_dialect == 'vendor'` on both `indexes_present_vendor`
3599    // and `indexes_built_vendor`) now get distinct
3600    // `__expr_N`/`__expr_M` names. Without this, both ops
3601    // injected the same `__expr_1 := cql_dialect == 'vendor'`
3602    // line into their bindings; the phase-scope ingest then saw
3603    // two ops each declaring `__expr_1` and tripped the
3604    // ride-along-uniqueness check (SRD-13c §"Op overriding op
3605    // shadow").
3606    //
3607    // The global `inline_idx` counter still increments
3608    // monotonically so synth names are workload-wide unique;
3609    // the per-op MAP keeps within-op dedup (same expression in
3610    // multiple fields of one op — `if: x == 1` and
3611    // `metric: x == 1` — collapses to a single `__expr_N` for
3612    // that op).
3613    let mut inline_idx = 0usize;
3614    let mut per_op_expr_to_name: Vec<HashMap<String, String>> =
3615        (0..ops.len()).map(|_| HashMap::new()).collect();
3616    let collect_from =
3617        |s: &str, idx: &mut usize, op_map: &mut HashMap<String, String>| -> Result<(), String> {
3618            for bp in nmbrs_workload::bindpoints::extract_bind_points(s)? {
3619                if let nmbrs_workload::bindpoints::BindPoint::InlineDefinition(ref expr) = bp {
3620                    op_map.entry(expr.clone()).or_insert_with(|| {
3621                        let n = format!("__expr_{idx}");
3622                        *idx += 1;
3623                        n
3624                    });
3625                }
3626            }
3627            Ok(())
3628        };
3629    for (op_index, op) in ops.iter().enumerate() {
3630        let op_map = &mut per_op_expr_to_name[op_index];
3631        for value in op.op.values() {
3632            if let Some(s) = value.as_str() {
3633                collect_from(s, &mut inline_idx, op_map)
3634                    .map_err(|e| format!("op '{}': {e}", op.name))?;
3635            }
3636        }
3637        if let Some(s) = &op.condition {
3638            collect_from(s, &mut inline_idx, op_map)
3639                .map_err(|e| format!("op '{}': {e}", op.name))?;
3640        }
3641        if let Some(spec) = &op.delay {
3642            for name in spec.names() {
3643                collect_from(name, &mut inline_idx, op_map)
3644                    .map_err(|e| format!("op '{}': {e}", op.name))?;
3645            }
3646        }
3647    }
3648    // For diagnostics + downstream: the legacy single
3649    // `expr_to_name` return value flattens the per-op maps.
3650    // Names are unique across ops because the inline_idx
3651    // counter is global, so the union is collision-free.
3652    let expr_to_name: HashMap<String, String> = per_op_expr_to_name
3653        .iter()
3654        .flat_map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())))
3655        .collect();
3656
3657    // Inject the synthesised `__expr_N := expr` bindings into
3658    // the first op's Polydat bindings source so `build_scope`'s
3659    // normal ingestion pass picks them up. Without this the
3660    // op fields get rewritten to reference `{__expr_N}` but
3661    // no binding declaring `__expr_N` ever lands in the
3662    // scope, so compilation fails with "unresolved bind
3663    // point '{__expr_N}'". Callers used to discard the
3664    // returned `expr_to_name` mapping and trust some other
3665    // path to install the bindings — there isn't one. Doing
3666    // the injection here keeps `rewrite_inline_exprs`
3667    // self-contained: every output rewrite has a matching
3668    // binding emitted.
3669    // Inject + rewrite per op. Each op uses ONLY its own
3670    // expr_to_name mapping (per_op_expr_to_name[op_index]).
3671    // Synth lines land in that op's bindings; field rewrites
3672    // see only that op's expression names. SRD-13d: the
3673    // op-template scope owns its own Polydat matter, including
3674    // synth bindings from inline expressions.
3675    if expr_to_name.is_empty() {
3676        return Ok(expr_to_name);
3677    }
3678    use nmbrs_workload::model::BindingsDef;
3679    for (op_index, op) in ops.iter_mut().enumerate() {
3680        let op_map = &per_op_expr_to_name[op_index];
3681        if op_map.is_empty() {
3682            continue;
3683        }
3684
3685        // Build synth lines for this op, deterministically
3686        // ordered by synth name.
3687        let mut entries: Vec<(&String, &String)> = op_map.iter().collect();
3688        entries.sort_by(|a, b| a.1.cmp(b.1));
3689        let mut synth_lines = String::new();
3690        for (expr, name) in &entries {
3691            synth_lines.push_str(&format!("\n{name} := {expr}"));
3692        }
3693
3694        // Inject into op.bindings. Map → PolydatSource conversion
3695        // mirrors the existing scope-source assembly path.
3696        match &mut op.bindings {
3697            BindingsDef::PolydatSource(s) => {
3698                if s.trim().is_empty() {
3699                    *s = synth_lines.trim_start_matches('\n').to_string();
3700                } else {
3701                    s.push_str(&synth_lines);
3702                }
3703            }
3704            BindingsDef::Map(_) => {
3705                if let BindingsDef::Map(map) = &op.bindings {
3706                    let mut existing = String::new();
3707                    for (k, v) in map.iter() {
3708                        existing.push_str(&format!("{k} := {v}\n"));
3709                    }
3710                    op.bindings = BindingsDef::PolydatSource(format!("{existing}{synth_lines}"));
3711                }
3712            }
3713        }
3714
3715        // Rewrite this op's fields using its own mapping only.
3716        let rewrite = |s: &str| -> String {
3717            nmbrs_workload::bindpoints::rewrite_inline_definitions(s, |expr| {
3718                op_map.get(expr).cloned()
3719            })
3720        };
3721        for value in op.op.values_mut() {
3722            if let Some(s) = value.as_str() {
3723                *value = serde_json::Value::String(rewrite(s));
3724            }
3725        }
3726        if let Some(s) = &op.condition {
3727            op.condition = Some(rewrite(s));
3728        }
3729        if let Some(spec) = &op.delay {
3730            // Rewrite each binding name in place, preserving
3731            // the spec's enum shape (Before vs BeforeAfter).
3732            op.delay = Some(match spec {
3733                nmbrs_workload::model::DelaySpec::Before(name) => {
3734                    nmbrs_workload::model::DelaySpec::Before(rewrite(name))
3735                }
3736                nmbrs_workload::model::DelaySpec::BeforeAfter { before, after } => {
3737                    nmbrs_workload::model::DelaySpec::BeforeAfter {
3738                        before: before.as_deref().map(rewrite),
3739                        after: after.as_deref().map(rewrite),
3740                    }
3741                }
3742            });
3743        }
3744    }
3745
3746    Ok(expr_to_name)
3747}
3748
3749/// Cached `NMBRS_DEBUG_SCOPE_SYNTH=true` switch (one read, one
3750/// warning on a non-boolean value).
3751fn debug_scope_synth_enabled() -> bool {
3752    static FLAG: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3753    *FLAG.get_or_init(|| crate::debug_env::debug_flag("NMBRS_DEBUG_SCOPE_SYNTH"))
3754}
3755
3756#[cfg(test)]
3757mod tests {
3758    use super::*;
3759
3760    fn make_polydat_op(name: &str, stmt: &str, bindings: &str) -> ParsedOp {
3761        let mut op = ParsedOp::simple(name, stmt);
3762        op.bindings = BindingsDef::PolydatSource(bindings.to_string());
3763        op
3764    }
3765
3766    #[test]
3767    fn objective_bare_wire_vs_inline_expression() {
3768        // Bare identifiers are read directly off the phase kernel.
3769        assert!(objective_is_bare_wire("score"));
3770        assert!(objective_is_bare_wire("err_rate"));
3771        assert!(objective_is_bare_wire("_objective"));
3772        assert!(objective_is_bare_wire("  recall99  ")); // trimmed
3773        assert_eq!(objective_wire("score"), "score");
3774        assert_eq!(objective_wire("  recall99  "), "recall99");
3775
3776        // Anything with operators / calls / dots / spaces is an inline
3777        // expression → synthesized to the `__objective` wire.
3778        assert!(!objective_is_bare_wire("0 - err_rate"));
3779        assert!(!objective_is_bare_wire("metricsql_scalar(\"x\")"));
3780        assert!(!objective_is_bare_wire("a - b"));
3781        assert!(!objective_is_bare_wire("q.cursor.depth"));
3782        assert!(!objective_is_bare_wire(""));
3783        assert_eq!(objective_wire("0 - err_rate"), OBJECTIVE_WIRE);
3784        assert_eq!(objective_wire("metricsql_scalar(\"x\")"), OBJECTIVE_WIRE);
3785    }
3786
3787    #[test]
3788    fn inline_objective_synthesizes_volatile_objective_binding() {
3789        use nmbrs_workload::model::{BindingsDef, OptimizeBlock, WorkloadPhase};
3790        let phase = WorkloadPhase {
3791            for_each: Some("rate in 1000, 2000".to_string()),
3792            bindings: BindingsDef::PolydatSource("input cycle: u64\n".to_string()),
3793            optimize: Some(OptimizeBlock {
3794                method: "sweep".to_string(),
3795                objective: "0 - metricsql_scalar(\"sum(rate(errors_total[3s]))\")".to_string(),
3796                servo: vec!["rate".to_string()],
3797                max_evals: 10,
3798                seed: 0,
3799                params: Default::default(),
3800            }),
3801            ..Default::default()
3802        };
3803        let out = synthesize_phase_scope_bindings(&phase).expect("synthesis ok");
3804        let src = match out {
3805            BindingsDef::PolydatSource(s) => s,
3806            other => panic!("expected PolydatSource, got {other:?}"),
3807        };
3808        assert!(
3809            src.contains("volatile __objective := 0 - metricsql_scalar("),
3810            "inline objective must be lowered to a `__objective` binding:\n{src}"
3811        );
3812
3813        // A bare-name objective is NOT synthesized — read directly.
3814        let mut bare = phase.clone();
3815        bare.optimize.as_mut().unwrap().objective = "score".to_string();
3816        let bare_out = synthesize_phase_scope_bindings(&bare).expect("synthesis ok");
3817        if let BindingsDef::PolydatSource(s) = bare_out {
3818            assert!(
3819                !s.contains("__objective"),
3820                "bare objective must not synthesize:\n{s}"
3821            );
3822        }
3823    }
3824
3825    #[test]
3826    fn inherited_bindings_dedup_across_ops() {
3827        let bindings = "input cycle: u64\nprofiles := matching_profiles(\"example\", \"label\")";
3828        let ops = vec![
3829            make_polydat_op("op_a", "{profiles}", bindings),
3830            make_polydat_op("op_b", "{profiles}", bindings),
3831        ];
3832        let scope = build_scope(
3833            &ops,
3834            &HashMap::new(),
3835            &[],
3836            &HashMap::new(),
3837            &HashMap::new(),
3838            None,
3839            &[],
3840            None,
3841        )
3842        .unwrap();
3843        scope.validate().unwrap();
3844        let emitted = scope.emit();
3845        // 'profiles' should appear exactly once
3846        let count = emitted.matches("profiles :=").count();
3847        assert_eq!(
3848            count, 1,
3849            "expected exactly 1 'profiles :=' in emitted scope, got {count}:\n{emitted}"
3850        );
3851    }
3852
3853    #[test]
3854    fn iteration_vars_dont_conflict_with_inherited() {
3855        let bindings = "input cycle: u64\nprofiles := matching_profiles(\"example\", \"label\")";
3856        let ops = vec![
3857            make_polydat_op("op_a", "{profiles} {table}", bindings),
3858            make_polydat_op("op_b", "{profiles} {table}", bindings),
3859        ];
3860        let mut iter_vars = HashMap::new();
3861        iter_vars.insert("table".to_string(), "vec_default".to_string());
3862
3863        let scope = build_scope(
3864            &ops,
3865            &iter_vars,
3866            &[],
3867            &HashMap::new(),
3868            &HashMap::new(),
3869            None,
3870            &[],
3871            None,
3872        )
3873        .unwrap();
3874        scope.validate().unwrap();
3875        let emitted = scope.emit();
3876        // Iteration variables now declare as `extern <name>:
3877        // <Type>` so the runtime can populate them per iteration
3878        // without recompiling (SRD 18b §"Iteration variables as
3879        // scope outputs"). Type is inferred from the value;
3880        // "vec_default" doesn't parse numerically → str.
3881        assert!(
3882            emitted.contains("extern table: str"),
3883            "expected extern table declaration in:\n{emitted}"
3884        );
3885        assert!(
3886            emitted.contains("profiles :="),
3887            "expected profiles in:\n{emitted}"
3888        );
3889    }
3890
3891    #[test]
3892    fn op_augmentation_adds_new_names() {
3893        let base = "input cycle: u64\nfoo := hash(cycle)";
3894        let augmented = "input cycle: u64\nfoo := hash(cycle)\nbar := mod(cycle, 100)";
3895        let ops = vec![
3896            make_polydat_op("op_a", "{foo}", base),
3897            make_polydat_op("op_b", "{foo} {bar}", augmented),
3898        ];
3899        let scope = build_scope(
3900            &ops,
3901            &HashMap::new(),
3902            &[],
3903            &HashMap::new(),
3904            &HashMap::new(),
3905            None,
3906            &[],
3907            None,
3908        )
3909        .unwrap();
3910        scope.validate().unwrap();
3911        let emitted = scope.emit();
3912        assert!(emitted.contains("foo := hash(cycle)"), "missing foo");
3913        assert!(emitted.contains("bar := mod(cycle, 100)"), "missing bar");
3914    }
3915
3916    #[test]
3917    fn real_shadow_is_caught() {
3918        let base = "input cycle: u64\nfoo := hash(cycle)";
3919        let shadow = "input cycle: u64\nfoo := mod(cycle, 100)";
3920        let ops = vec![
3921            make_polydat_op("op_a", "{foo}", base),
3922            make_polydat_op("op_b", "{foo}", shadow),
3923        ];
3924        let scope = build_scope(
3925            &ops,
3926            &HashMap::new(),
3927            &[],
3928            &HashMap::new(),
3929            &HashMap::new(),
3930            None,
3931            &[],
3932            None,
3933        )
3934        .unwrap();
3935        let result = scope.validate();
3936        assert!(result.is_err(), "expected shadow error");
3937        let err = result.unwrap_err();
3938        assert!(
3939            err.contains("shadows"),
3940            "expected 'shadows' in error: {err}"
3941        );
3942        assert!(err.contains("op_b"), "expected op name in error: {err}");
3943    }
3944
3945    #[test]
3946    fn original_bug_repro_no_false_shadow() {
3947        // The original bug: workload-level bindings with profiles,
3948        // inherited by a phase with for_each iteration vars.
3949        // Two ops share identical inherited bindings.
3950        // The init injection used to make them differ, causing false shadow.
3951        let bindings = "input cycle: u64\nprofiles := matching_profiles(\"example\", \"label\")";
3952        let ops = vec![
3953            make_polydat_op(
3954                "drop_metadata_index",
3955                "DROP INDEX {table}_meta_idx",
3956                bindings,
3957            ),
3958            make_polydat_op("drop_vector_index", "DROP INDEX {table}_idx", bindings),
3959            make_polydat_op("drop_table", "DROP TABLE {table}", bindings),
3960        ];
3961        let mut iter_vars = HashMap::new();
3962        iter_vars.insert("table".to_string(), "fknn_default".to_string());
3963        iter_vars.insert("spec".to_string(), "example:default".to_string());
3964        iter_vars.insert("optimize_for".to_string(), "RECALL".to_string());
3965
3966        let scope = build_scope(
3967            &ops,
3968            &iter_vars,
3969            &[],
3970            &HashMap::new(),
3971            &HashMap::new(),
3972            None,
3973            &[],
3974            None,
3975        )
3976        .unwrap();
3977        // This was the bug: validate() used to fail with false shadow error
3978        scope.validate().unwrap();
3979        let emitted = scope.emit();
3980        // Iter vars now declare as extern (SRD 18b). The original
3981        // bug — false-shadow detection — is unchanged regardless
3982        // of how the iter var materialises.
3983        assert!(
3984            emitted.contains("extern table: str"),
3985            "missing extern table in:\n{emitted}"
3986        );
3987        assert!(emitted.contains("profiles :="), "missing profiles");
3988        // profiles should appear exactly once
3989        let count = emitted.matches("profiles :=").count();
3990        assert_eq!(count, 1, "profiles duplicated in:\n{emitted}");
3991    }
3992
3993    // ── SRD-13d Phase 9 cross-scope contract check ──────────
3994
3995    fn parent_kernel_with_load() -> crate::scope_kernel::ScopeKernel {
3996        // Parent has `cycle` input, a folded constant `dim`, a
3997        // shared output `budget`, and a dynamic output `load`
3998        // (cycle-dependent, no modifier). Each shape exercises
3999        // a different `ParentRefKind` arm.
4000        crate::bindings::compile_scope_kernel(
4001            "input cycle: u64\n\
4002             const dim := 128\n\
4003             shared budget := 100\n\
4004             load := add(cycle, 1)\n",
4005            &Default::default(),
4006        )
4007        .expect("compile parent")
4008    }
4009
4010    fn op_with_body(name: &str, body: &str) -> ParsedOp {
4011        let mut op = ParsedOp::simple(name, "noop");
4012        op.bindings = BindingsDef::PolydatSource(body.into());
4013        op
4014    }
4015
4016    #[test]
4017    fn op_template_referencing_cycle_input_is_accepted() {
4018        let parent = parent_kernel_with_load();
4019        let manifest = polydat::kernel::extract_manifest(parent.program())
4020            .into_iter()
4021            .map(|e| crate::runner::ManifestEntry {
4022                name: e.name,
4023                port_type: e.port_type,
4024                modifier: e.modifier,
4025            })
4026            .collect::<Vec<_>>();
4027        let op = op_with_body("step_op", "step := add(cycle, 1)\n");
4028        let result = build_op_template_scope_kernel(
4029            &op,
4030            &manifest,
4031            &parent,
4032            &HashMap::new(),
4033            Vec::new(),
4034            None,
4035            false,
4036            polydat::kernel::KernelOptLevel::Release,
4037            "test",
4038        );
4039        assert!(
4040            result.is_ok(),
4041            "cycle is a parent input — should be accepted. err: {:?}",
4042            result.err()
4043        );
4044    }
4045
4046    /// Localises the metric-wiring defect: when an op-template kernel is
4047    /// materialised, does the synthesised `__metric_<name>` binding surface as
4048    /// an output on THAT kernel? The metrics wrapper reads it through
4049    /// `ctx.wires`, so if it is absent the wrapper reports
4050    /// "did not resolve through ctx.wires".
4051    #[test]
4052    fn op_template_kernel_exposes_synthesised_metric_bindings() {
4053        use nmbrs_workload::model::MetricSpec;
4054        let parent = parent_kernel_with_load();
4055        let manifest = polydat::kernel::extract_manifest(parent.program())
4056            .into_iter()
4057            .map(|e| crate::runner::ManifestEntry {
4058                name: e.name,
4059                port_type: e.port_type,
4060                modifier: e.modifier,
4061            })
4062            .collect::<Vec<_>>();
4063        let mut op = op_with_body("m_op", "measured := add(cycle, 1)\n");
4064        op.metrics.insert(
4065            "bytes_out".to_string(),
4066            MetricSpec {
4067                value: "measured".into(),
4068                family: None,
4069                kind: None,
4070                unit: None,
4071                format: None,
4072                cell: Default::default(),
4073            },
4074        );
4075        let kernel = build_op_template_scope_kernel(
4076            &op,
4077            &manifest,
4078            &parent,
4079            &HashMap::new(),
4080            Vec::new(),
4081            None,
4082            false,
4083            polydat::kernel::KernelOptLevel::Release,
4084            "test",
4085        )
4086        .expect("op-template kernel builds");
4087        let outs = kernel.program().output_names();
4088        assert!(
4089            outs.contains(&"__metric_bytes_out"),
4090            "the synthesised metric binding must be an output of the \
4091             op-template kernel; outputs: {outs:?}"
4092        );
4093    }
4094
4095    #[test]
4096    fn op_template_referencing_constant_output_is_accepted() {
4097        let parent = parent_kernel_with_load();
4098        let manifest = polydat::kernel::extract_manifest(parent.program())
4099            .into_iter()
4100            .map(|e| crate::runner::ManifestEntry {
4101                name: e.name,
4102                port_type: e.port_type,
4103                modifier: e.modifier,
4104            })
4105            .collect::<Vec<_>>();
4106        // `dim` is a `final` (folded) output — snapshot is final,
4107        // per-cycle changes are impossible by construction.
4108        let op = op_with_body("calc_op", "scaled := mul(dim, 2)\n");
4109        let result = build_op_template_scope_kernel(
4110            &op,
4111            &manifest,
4112            &parent,
4113            &HashMap::new(),
4114            Vec::new(),
4115            None,
4116            false,
4117            polydat::kernel::KernelOptLevel::Release,
4118            "test",
4119        );
4120        assert!(
4121            result.is_ok(),
4122            "final/folded output should be accepted. err: {:?}",
4123            result.err()
4124        );
4125    }
4126
4127    #[test]
4128    fn op_template_referencing_shared_output_is_accepted() {
4129        let parent = parent_kernel_with_load();
4130        let manifest = polydat::kernel::extract_manifest(parent.program())
4131            .into_iter()
4132            .map(|e| crate::runner::ManifestEntry {
4133                name: e.name,
4134                port_type: e.port_type,
4135                modifier: e.modifier,
4136            })
4137            .collect::<Vec<_>>();
4138        // `budget` is `shared` — SharedCell carries live updates.
4139        let op = op_with_body("budget_op", "remaining := add(budget, 1)\n");
4140        let result = build_op_template_scope_kernel(
4141            &op,
4142            &manifest,
4143            &parent,
4144            &HashMap::new(),
4145            Vec::new(),
4146            None,
4147            false,
4148            polydat::kernel::KernelOptLevel::Release,
4149            "test",
4150        );
4151        assert!(
4152            result.is_ok(),
4153            "shared output should be accepted. err: {:?}",
4154            result.err()
4155        );
4156    }
4157
4158    #[test]
4159    fn op_template_referencing_dynamic_output_accepted_per_srd_13f() {
4160        // SRD-13f retires SRD-13c's "DynamicOutput without
4161        // shared" rejection. The read invariant is uniform —
4162        // inner reads of cross-scope wires return outer's
4163        // current value via construction-time wiring (cells
4164        // for shared, per-cycle refresh / planned cell
4165        // mechanism for non-shared). The op-template
4166        // synthesiser accepts the reference; the wiring keeps
4167        // the invariant intact at cycle time.
4168        let parent = parent_kernel_with_load();
4169        let manifest = polydat::kernel::extract_manifest(parent.program())
4170            .into_iter()
4171            .map(|e| crate::runner::ManifestEntry {
4172                name: e.name,
4173                port_type: e.port_type,
4174                modifier: e.modifier,
4175            })
4176            .collect::<Vec<_>>();
4177        let op = op_with_body("forecast_op", "forecast := mul(load, 2)\n");
4178        let kernel = build_op_template_scope_kernel(
4179            &op,
4180            &manifest,
4181            &parent,
4182            &HashMap::new(),
4183            Vec::new(),
4184            None,
4185            false,
4186            polydat::kernel::KernelOptLevel::Release,
4187            "test",
4188        )
4189        .expect("op-template kernel synth should accept dynamic parent ref");
4190        // The op-template kernel carries `load` as an extern
4191        // input — the construction-time wiring set up the slot;
4192        // per-cycle refresh keeps it current with outer.
4193        assert!(
4194            kernel.program().find_input("load").is_some(),
4195            "extern load slot should land on op-template kernel"
4196        );
4197        // And `forecast`, the op-local binding, is an output.
4198        assert!(
4199            kernel.program().output_names().contains(&"forecast"),
4200            "op-local binding should be an output"
4201        );
4202    }
4203
4204    #[test]
4205    fn op_template_pvs_query_full_shape_with_workload_params() {
4206        // Closer to the actual full_cql_vector.yaml shape: the
4207        // op carries `prepared:` text with `{keyspace}.{table}`
4208        // / `{predicate}` / `{query_vector}` / `{limit}` interp
4209        // bind-points, plus a `metrics: overscan: {value:
4210        // overscan}` declaration. workload_params carries
4211        // dataset/profile/keyspace via `final` injection. The
4212        // op-template synthesiser must emit the latency_factor /
4213        // recall_factor / overscan bindings as outputs so the
4214        // metrics fixture's `register_pull("overscan")`
4215        // resolves.
4216        use nmbrs_workload::model::MetricSpec;
4217        let parent_src = r#"
4218extern k: u64
4219extern limit: u64
4220extern optimize_for: str
4221extern table: str
4222"#;
4223        let parent = crate::bindings::compile_scope_kernel(
4224            parent_src,
4225            &polydat::dsl::compile::CompileOptions {
4226                context: "parent".to_string(),
4227                ..Default::default()
4228            },
4229        )
4230        .expect("parent compile");
4231        let manifest: Vec<crate::runner::ManifestEntry> =
4232            polydat::kernel::extract_manifest(parent.program())
4233                .into_iter()
4234                .map(|e| crate::runner::ManifestEntry {
4235                    name: e.name,
4236                    port_type: e.port_type,
4237                    modifier: e.modifier,
4238                })
4239                .collect();
4240        let body = "const prebuffered := dataset_prebuffer(\"{dataset}:{profile}\")\n\
4241            const query_counts := query_count(prebuffered)\n\
4242            cursor q = range(0, query_counts * 10)\n\
4243            query_vector := query_vector_at(prebuffered, q % query_counts)\n\
4244            predicate := predicate_value_at(prebuffered, q % query_counts)\n\
4245            ground_truth := filtered_neighbor_indices_at(prebuffered, q % query_counts)\n\
4246            latency_factor := 0.979 + 4.021 * pow(limit, -0.761)\n\
4247            recall_factor  := 0.509 + 9.491 * pow(limit, -0.402)\n\
4248            overscan := if(optimize_for == \"LATENCY\", latency_factor, recall_factor)\n";
4249        let mut op = op_with_body("select_ann", body);
4250        // Mirror op fields the YAML carries.
4251        op.op.insert(
4252            "prepared".into(),
4253            serde_json::json!(
4254                "SELECT key,value FROM {keyspace}.{table} \
4255             WHERE metadata = {predicate} \
4256             ORDER BY value ANN OF {query_vector} LIMIT {limit}"
4257            ),
4258        );
4259        op.metrics.insert(
4260            "overscan".into(),
4261            MetricSpec {
4262                value: "overscan".into(),
4263                family: None,
4264                kind: None,
4265                unit: None,
4266                format: None,
4267                cell: Default::default(),
4268            },
4269        );
4270        let mut workload_params = HashMap::new();
4271        workload_params.insert("dataset".into(), "example".into());
4272        workload_params.insert("profile".into(), "label_00".into());
4273        workload_params.insert("keyspace".into(), "baselines".into());
4274        let kernel = build_op_template_scope_kernel(
4275            &op,
4276            &manifest,
4277            &parent,
4278            &workload_params,
4279            vec![],
4280            None,
4281            false,
4282            polydat::kernel::KernelOptLevel::Release,
4283            "pvs_query.select_ann",
4284        )
4285        .expect("op-template kernel synth");
4286        let outs: Vec<String> = kernel
4287            .program()
4288            .output_names()
4289            .iter()
4290            .map(|s| s.to_string())
4291            .collect();
4292        for required in &["overscan", "latency_factor", "recall_factor"] {
4293            assert!(
4294                outs.iter().any(|o| o == required),
4295                "op-template kernel missing '{required}'; outputs: {outs:?}"
4296            );
4297        }
4298        // Workload params must be folded in as `final` constants
4299        // (not externs) so `init prebuffered =
4300        // dataset_prebuffer("{dataset}:{profile}")` folds at
4301        // compile time. If they cascade through as externs the
4302        // init binding stays unfolded, the per-fiber state never
4303        // gets the seeded Handle, and downstream nodes (like
4304        // `neighbor_indices_at(prebuffered, q)`) panic at runtime
4305        // with `expected Handle, got None/U64`.
4306        for param in &["dataset", "profile", "keyspace"] {
4307            // The param either folds out completely (no input
4308            // slot) or appears as a folded constant — both
4309            // are fine. What's NOT fine is showing up as an
4310            // input on the inner kernel.
4311            assert!(
4312                kernel.program().find_input(param).is_none(),
4313                "workload param '{param}' must NOT be an extern input \
4314                 on the op-template kernel — cascade should emit \
4315                 it as `final` so init bindings fold. Inputs: {:?}",
4316                kernel.program().input_names(),
4317            );
4318        }
4319    }
4320
4321    #[test]
4322    fn op_template_with_pow_and_if_keeps_all_outputs() {
4323        // Mirror the shape of full_cql_vector.yaml's pvs_query
4324        // phase body (after parser merge): init+cursor+:= ladder
4325        // ending with `pow()` + `if()` bindings. The op-template
4326        // kernel must expose every `:=` binding as an output;
4327        // a missing `overscan` is what triggers the
4328        // `register_pull("overscan")` failure at MetricsDispenser
4329        // wrap time.
4330        let parent_src = r#"
4331extern k: u64
4332extern limit: u64
4333extern optimize_for: str
4334extern table: str
4335extern dataset: str
4336extern profile: str
4337extern keyspace: str
4338"#;
4339        let parent = crate::bindings::compile_scope_kernel(
4340            parent_src,
4341            &polydat::dsl::compile::CompileOptions {
4342                context: "parent".to_string(),
4343                ..Default::default()
4344            },
4345        )
4346        .expect("parent compile");
4347        let manifest: Vec<crate::runner::ManifestEntry> =
4348            polydat::kernel::extract_manifest(parent.program())
4349                .into_iter()
4350                .map(|e| crate::runner::ManifestEntry {
4351                    name: e.name,
4352                    port_type: e.port_type,
4353                    modifier: e.modifier,
4354                })
4355                .collect();
4356        let body = "const prebuffered := dataset_prebuffer(\"dummy:default\")\n\
4357            const query_counts := query_count(prebuffered)\n\
4358            cursor q = range(0, query_counts * 10)\n\
4359            query_vector := query_vector_at(prebuffered, q % query_counts)\n\
4360            predicate := predicate_value_at(prebuffered, q % query_counts)\n\
4361            ground_truth := filtered_neighbor_indices_at(prebuffered, q % query_counts)\n\
4362            latency_factor := 0.979 + 4.021 * pow(limit, -0.761)\n\
4363            recall_factor  := 0.509 + 9.491 * pow(limit, -0.402)\n\
4364            overscan := if(optimize_for == \"LATENCY\", latency_factor, recall_factor)\n";
4365        let op = op_with_body("select_ann", body);
4366        let kernel = build_op_template_scope_kernel(
4367            &op,
4368            &manifest,
4369            &parent,
4370            &HashMap::new(),
4371            Vec::new(),
4372            None,
4373            false,
4374            polydat::kernel::KernelOptLevel::Release,
4375            "pvs_query.select_ann",
4376        )
4377        .expect("op-template kernel synth");
4378        let outs: Vec<String> = kernel
4379            .program()
4380            .output_names()
4381            .iter()
4382            .map(|s| s.to_string())
4383            .collect();
4384        for required in &[
4385            "query_vector",
4386            "predicate",
4387            "ground_truth",
4388            "latency_factor",
4389            "recall_factor",
4390            "overscan",
4391        ] {
4392            assert!(
4393                outs.iter().any(|o| o == required),
4394                "op-template kernel missing '{required}'; outputs: {outs:?}"
4395            );
4396        }
4397    }
4398
4399    #[test]
4400    fn op_template_relevancy_k_r_bare_wire_names_cascade() {
4401        // Post-SRD-68 follow-up: `evaluations.relevancy.{k, r,
4402        // expected, actual}` accept bare wire-name forms. The
4403        // op-template synthesiser must include those names in its
4404        // cascaded-extern set so the dispenser's canonical kernel
4405        // can resolve them at wrap-time (where parse_count_param
4406        // calls wires.get(name)).
4407        let parent = parent_kernel_with_load();
4408        let manifest = polydat::kernel::extract_manifest(parent.program())
4409            .into_iter()
4410            .map(|e| crate::runner::ManifestEntry {
4411                name: e.name,
4412                port_type: e.port_type,
4413                modifier: e.modifier,
4414            })
4415            .collect::<Vec<_>>();
4416        let mut op = ParsedOp::simple("read", "noop");
4417        op.bindings = BindingsDef::PolydatSource("".into());
4418        op.params.insert(
4419            "relevancy".into(),
4420            serde_json::json!({
4421                "actual": "rows",
4422                "expected": "ground_truth",
4423                "k": "k_value",
4424                "r": "limit_value",
4425                "functions": ["recall"],
4426            }),
4427        );
4428        // Parent has `cycle` as the coord input. The relevancy
4429        // wire names (rows, ground_truth, k_value, limit_value)
4430        // aren't on the parent; the synthesiser should still add
4431        // them to the cascade-extern set so the op-template kernel
4432        // *declares* them (errors only fire at wrap-time when the
4433        // canonical kernel actually tries to resolve them).
4434        //
4435        // For this unit test we just confirm the synthesiser
4436        // doesn't error AND that the input/output names list
4437        // includes each relevancy wire name — meaning the
4438        // referenced-cascade walker picked them up. We pick names
4439        // the parent doesn't have so the auto-extern path fires
4440        // and the resulting kernel has them as inputs.
4441        let _ = manifest;
4442        // Use the public synthesis entry point to construct the
4443        // op-template kernel under a parent that *does* have the
4444        // referenced wires (so the cascade succeeds).
4445        let kernel_src = "\
4446            input cycle: u64\n\
4447            const rows := 10\n\
4448            const ground_truth := \"1,2,3\"\n\
4449            const k_value := 5\n\
4450            const limit_value := 100\n";
4451        let real_parent =
4452            crate::scope_kernel::ScopeKernel::compile(kernel_src).expect("parent compile");
4453        let real_manifest = polydat::kernel::extract_manifest(real_parent.program())
4454            .into_iter()
4455            .map(|e| crate::runner::ManifestEntry {
4456                name: e.name,
4457                port_type: e.port_type,
4458                modifier: e.modifier,
4459            })
4460            .collect::<Vec<_>>();
4461        let kernel = build_op_template_scope_kernel(
4462            &op,
4463            &real_manifest,
4464            &real_parent,
4465            &HashMap::new(),
4466            Vec::new(),
4467            None,
4468            false,
4469            polydat::kernel::KernelOptLevel::Release,
4470            "relevancy-cascade-test",
4471        )
4472        .expect("op-template kernel synth");
4473
4474        // Each bare-name relevancy wire should resolve through the
4475        // op-template kernel's lookup — the same path validation.rs
4476        // takes at wrap-time via canonical_kernel().lookup(name).
4477        for name in &["rows", "ground_truth", "k_value", "limit_value"] {
4478            assert!(
4479                kernel.lookup(name).is_some(),
4480                "relevancy wire '{name}' should be visible on the \
4481                 op-template kernel (cascaded extern); kernel had \
4482                 outputs: {outs:?}",
4483                outs = kernel.program().output_names()
4484            );
4485        }
4486    }
4487
4488    #[test]
4489    fn op_template_metric_value_count_allocates_magic_extern_slot() {
4490        // Post-SRD-68 follow-up: a metric `value:` expression is a
4491        // use site for any names it references. The op-template
4492        // kernel synthesiser appends `__metric_<name> := <value_expr>`
4493        // to the result-bindings source, so the closure-binding
4494        // economy's free-identifier walker sees `count` and injects
4495        // an `extern count: u64` slot — no throw-away result-binding
4496        // needed.
4497        //
4498        // Verifies: a workload with NO `result:` block but a
4499        // `metrics: rows_per_op: { value: count }` declaration ends
4500        // up with a `count` INPUT slot on the kernel.
4501        let parent = parent_kernel_with_load();
4502        let manifest = polydat::kernel::extract_manifest(parent.program())
4503            .into_iter()
4504            .map(|e| crate::runner::ManifestEntry {
4505                name: e.name,
4506                port_type: e.port_type,
4507                modifier: e.modifier,
4508            })
4509            .collect::<Vec<_>>();
4510        let mut op = ParsedOp::simple("read", "noop");
4511        op.bindings = BindingsDef::PolydatSource("".into());
4512        op.metrics.insert(
4513            "rows_per_op".into(),
4514            nmbrs_workload::model::MetricSpec {
4515                value: "count".into(),
4516                family: None,
4517                kind: Some(nmbrs_workload::model::MetricKind::Gauge),
4518                unit: None,
4519                format: None,
4520                cell: Default::default(),
4521            },
4522        );
4523        let kernel = build_op_template_scope_kernel(
4524            &op,
4525            &manifest,
4526            &parent,
4527            &HashMap::new(),
4528            Vec::new(),
4529            None,
4530            false,
4531            polydat::kernel::KernelOptLevel::Release,
4532            "metric-walker-test",
4533        )
4534        .expect("op-template kernel synth");
4535        let inputs = kernel.program().input_names();
4536        assert!(
4537            inputs.iter().any(|i| i == "count"),
4538            "metric `value: count` should force the `count` magic-extern \
4539             input slot to be allocated under Release opt level; \
4540             inputs were: {inputs:?}"
4541        );
4542        // And the synthesised binding shows up as an output the
4543        // MetricsDispenser will read at cycle time.
4544        let outs = kernel.program().output_names();
4545        let synth = synthesize_metric_binding_name("rows_per_op");
4546        assert!(
4547            outs.iter().any(|o| o == &synth),
4548            "synthesised `{synth}` binding should be a kernel output; \
4549             outputs were: {outs:?}"
4550        );
4551    }
4552
4553    #[test]
4554    fn promoted_final_emits_inline_literal_for_str() {
4555        // SRD-13f case 1 — when a referenced name is `final`
4556        // upstream and a Str, the synthesizer emits
4557        // `const name := "value"` in the child's source rather
4558        // than auto-externing it.
4559        let parent = crate::scope_kernel::ScopeKernel::compile(
4560            "input cycle: u64\nconst dataset := \"example\"\n",
4561        )
4562        .expect("compile parent");
4563        let manifest: Vec<crate::runner::ManifestEntry> =
4564            polydat::kernel::extract_manifest(parent.program())
4565                .into_iter()
4566                .map(|e| crate::runner::ManifestEntry {
4567                    name: e.name,
4568                    port_type: e.port_type,
4569                    modifier: e.modifier,
4570                })
4571                .collect();
4572        let ops = vec![make_polydat_op("step", "x={dataset}", "input cycle: u64")];
4573        let scope = build_scope(
4574            &ops,
4575            &HashMap::new(),
4576            &manifest,
4577            &HashMap::new(),
4578            &HashMap::new(),
4579            None,
4580            &[],
4581            Some(&parent),
4582        )
4583        .expect("build_scope");
4584        let emitted = scope.emit();
4585        assert!(
4586            emitted.contains("const dataset := \"example\""),
4587            "expected promoted-final emission, got:\n{emitted}"
4588        );
4589        assert!(
4590            !emitted.contains("extern dataset"),
4591            "expected no extern for promoted-final dataset, got:\n{emitted}"
4592        );
4593    }
4594
4595    #[test]
4596    fn promoted_final_emits_inline_literal_for_u64() {
4597        let parent =
4598            crate::scope_kernel::ScopeKernel::compile("input cycle: u64\nconst count := 42\n")
4599                .expect("compile parent");
4600        let manifest: Vec<crate::runner::ManifestEntry> =
4601            polydat::kernel::extract_manifest(parent.program())
4602                .into_iter()
4603                .map(|e| crate::runner::ManifestEntry {
4604                    name: e.name,
4605                    port_type: e.port_type,
4606                    modifier: e.modifier,
4607                })
4608                .collect();
4609        let ops = vec![make_polydat_op("step", "n={count}", "input cycle: u64")];
4610        let scope = build_scope(
4611            &ops,
4612            &HashMap::new(),
4613            &manifest,
4614            &HashMap::new(),
4615            &HashMap::new(),
4616            None,
4617            &[],
4618            Some(&parent),
4619        )
4620        .expect("build_scope");
4621        let emitted = scope.emit();
4622        assert!(
4623            emitted.contains("const count := 42"),
4624            "expected promoted-final u64 emission, got:\n{emitted}"
4625        );
4626    }
4627
4628    #[test]
4629    fn unresolved_wire_reference_surfaces_validation_error() {
4630        // SRD-13f case 4 — a typo in a `{...}` placeholder (here
4631        // `{tirp}` instead of the declared `trip`) is rejected
4632        // at the synthesizer level with a structured error,
4633        // not via a downstream Polydat compiler error.
4634        let parent = crate::scope_kernel::ScopeKernel::compile(
4635            "input cycle: u64\nconst dataset := \"example\"\n",
4636        )
4637        .expect("compile parent");
4638        let manifest: Vec<crate::runner::ManifestEntry> =
4639            polydat::kernel::extract_manifest(parent.program())
4640                .into_iter()
4641                .map(|e| crate::runner::ManifestEntry {
4642                    name: e.name,
4643                    port_type: e.port_type,
4644                    modifier: e.modifier,
4645                })
4646                .collect();
4647        let ops = vec![make_polydat_op("step", "x={tirp}", "input cycle: u64")];
4648        let err = match build_scope(
4649            &ops,
4650            &HashMap::new(),
4651            &manifest,
4652            &HashMap::new(),
4653            &HashMap::new(),
4654            None,
4655            &[],
4656            Some(&parent),
4657        ) {
4658            Ok(_) => panic!("expected unresolved-wire error, got Ok"),
4659            Err(e) => e,
4660        };
4661        assert!(err.contains("unresolved wire"), "wrong error: {err}");
4662        assert!(
4663            err.contains("tirp"),
4664            "error should mention the typoed name: {err}"
4665        );
4666        assert!(
4667            err.contains("Visible names"),
4668            "error should list visible names: {err}"
4669        );
4670    }
4671
4672    #[test]
4673    fn overloaded_call_head_is_not_an_unresolved_wire() {
4674        // `vec_norm` is an overloaded name: the registry lists only its
4675        // typed forms (`vec_norm_f32`, `vec_norm_f64`), so a check that
4676        // asks the registry for the bare name alone would report the
4677        // call head as an unresolved wire.
4678        let parent = crate::scope_kernel::ScopeKernel::compile("input cycle: u64\n")
4679            .expect("compile parent");
4680        let manifest: Vec<crate::runner::ManifestEntry> =
4681            polydat::kernel::extract_manifest(parent.program())
4682                .into_iter()
4683                .map(|e| crate::runner::ManifestEntry {
4684                    name: e.name,
4685                    port_type: e.port_type,
4686                    modifier: e.modifier,
4687                })
4688                .collect();
4689        let ops = vec![make_polydat_op(
4690            "step",
4691            "x={n}",
4692            "input cycle: u64\nv := str_to_vec_f32(\"[3.0, 4.0]\")\nn := vec_norm(v)",
4693        )];
4694        if let Err(err) = build_scope(
4695            &ops,
4696            &HashMap::new(),
4697            &manifest,
4698            &HashMap::new(),
4699            &HashMap::new(),
4700            None,
4701            &[],
4702            Some(&parent),
4703        ) {
4704            panic!("an overloaded call head must resolve as a function: {err}");
4705        }
4706    }
4707
4708    #[test]
4709    fn ingest_preserves_bindings_when_comment_contains_apostrophe() {
4710        // Regression: Polydat grammar uses only `"`-delimited string
4711        // literals. `logical_lines` previously treated `'` as a
4712        // string delimiter too, which meant an unmatched
4713        // apostrophe in a `#` comment (e.g. "the workload's
4714        // bindings") put the splitter into a string state that
4715        // never closed. The entire rest of the source was
4716        // accreted into one logical "line" starting with `#`,
4717        // which then got dropped as a comment by the per-line
4718        // parser — silently discarding every binding that
4719        // followed.
4720        //
4721        // This was the actual root cause of the full_cql_vector
4722        // `await_index` failure: the workload's
4723        // `bindings:` block began with a multi-line comment
4724        // containing the apostrophe in "full_cql_vector's", so
4725        // the `shared has_X := false` declarations never made
4726        // it into the workload-root program. Descendant
4727        // synthesizers then couldn't cascade has_X as Bool
4728        // externs; the compile inferred has_X as Coordinate
4729        // U64 inputs from unbound references, and the
4730        // per-cycle `set_inputs(&[u64])` clobbered the
4731        // SharedCell with `Value::U64(cycle)`.
4732        let mut scope = BindingScope::new();
4733        let src_with_apostrophe_comment = "# full_cql_vector's bindings block\n\
4734                                           shared has_a := true\n\
4735                                           shared has_b := false\n";
4736        scope.ingest_polydat_source(src_with_apostrophe_comment, BindingOrigin::Inherited);
4737        let defined = scope.defined_names();
4738        assert!(
4739            defined.contains("has_a"),
4740            "comment with apostrophe must NOT consume subsequent bindings; \
4741             expected has_a in defined names, got {defined:?}"
4742        );
4743        assert!(
4744            defined.contains("has_b"),
4745            "expected has_b in defined names, got {defined:?}"
4746        );
4747
4748        let emitted = scope.emit();
4749        assert!(
4750            emitted.contains("shared has_a := true"),
4751            "scope.emit() must include the shared bindings; got:\n{emitted}"
4752        );
4753        assert!(
4754            emitted.contains("shared has_b := false"),
4755            "scope.emit() must include the shared bindings; got:\n{emitted}"
4756        );
4757    }
4758
4759    #[test]
4760    fn ingest_then_compile_preserves_shared_modifier() {
4761        // Mirrors the workload-root compile path in
4762        // `compile_bindings_with_libs_excluding`: workload-level
4763        // bindings (`shared has_X := false`) get ingested via
4764        // `scope.ingest_polydat_source(..., Inherited)` before emit.
4765        // The resulting source then compiles via the
4766        // standard pipeline.
4767        //
4768        // SRD-13c §"Shared Mutable": `shared X := <literal>`
4769        // compiles to an input slot + passthrough output marked
4770        // SHARED. The workload-root program's `shared_outputs()`
4771        // must include the SHARED-modifier outputs so
4772        // `seed_shared_cells` creates a `SharedCell` for each
4773        // and descendant kernels can cell-attach via
4774        // `materialize_wiring_from_outer`.
4775        let mut scope = BindingScope::new();
4776        let workload_polydat = "shared has_sai_column_indexes := false\n\
4777                          shared has_indexes := false\n";
4778        scope.ingest_polydat_source(workload_polydat, BindingOrigin::Inherited);
4779        let source = scope.emit();
4780        let kernel = crate::scope_kernel::ScopeKernel::compile(&source)
4781            .unwrap_or_else(|e| panic!("compile failed for source:\n{source}\nerror: {e}"));
4782        let shared = kernel.program().shared_outputs();
4783        assert!(
4784            shared.contains(&"has_sai_column_indexes"),
4785            "expected `has_sai_column_indexes` in shared_outputs after scope-ingest/emit/compile;\n\
4786             got shared_outputs={shared:?}\nemitted source:\n{source}",
4787        );
4788        assert!(
4789            shared.contains(&"has_indexes"),
4790            "expected `has_indexes` in shared_outputs after scope-ingest/emit/compile;\n\
4791             got shared_outputs={shared:?}\nemitted source:\n{source}",
4792        );
4793    }
4794
4795    /// SRD-75 Push 2: `synthesize_phase_scope_bindings`
4796    /// returns the original bindings unchanged when
4797    /// `phase.poll` is `None`. The function is a no-op for
4798    /// non-poll phases; their synthesis path is unaffected.
4799    #[test]
4800    fn synthesize_phase_scope_bindings_passthrough_when_no_poll() {
4801        use nmbrs_workload::model::{BindingsDef, WorkloadPhase};
4802        let phase = WorkloadPhase {
4803            bindings: BindingsDef::PolydatSource("k := 5\n".into()),
4804            poll: None,
4805            ..Default::default()
4806        };
4807        let out = synthesize_phase_scope_bindings(&phase).expect("no-poll synthesis is a no-op");
4808        match out {
4809            BindingsDef::PolydatSource(s) => assert_eq!(
4810                s, "k := 5\n",
4811                "no-poll should return the original bindings unchanged"
4812            ),
4813            other => panic!("expected PolydatSource, got {other:?}"),
4814        }
4815    }
4816
4817    /// A metric's `cell:` is reified as a compiled kernel binding beside its
4818    /// value — the whole point of the design. If this did not compile, a
4819    /// coordinate would have to be a runtime string, which is the
4820    /// unvalidatable shape the proposal exists to avoid.
4821    #[test]
4822    fn phase_metrics_reify_cell_coordinates_as_kernel_bindings() {
4823        use nmbrs_workload::model::{BindingsDef, MetricSpec, WorkloadPhase};
4824        let mut metrics = std::collections::HashMap::new();
4825        let mut cell = std::collections::BTreeMap::new();
4826        cell.insert("tier".to_string(), "tier_name".to_string());
4827        metrics.insert(
4828            "bytes_out".to_string(),
4829            MetricSpec {
4830                value: "history_bytes_out".into(),
4831                family: None,
4832                kind: None,
4833                unit: None,
4834                format: None,
4835                cell,
4836            },
4837        );
4838        let phase = WorkloadPhase {
4839            bindings: BindingsDef::PolydatSource(
4840                "extern tier_name: str = \"\"\n\
4841                 extern history_bytes_out: u64 = 0\n"
4842                    .into(),
4843            ),
4844            metrics,
4845            poll: None,
4846            ..Default::default()
4847        };
4848        let out = synthesize_phase_scope_bindings(&phase).expect("synthesis");
4849        let src = match out {
4850            BindingsDef::PolydatSource(s) => s,
4851            other => panic!("expected PolydatSource, got {other:?}"),
4852        };
4853        assert!(
4854            src.contains("volatile __cell_bytes_out__tier := tier_name"),
4855            "coordinate must be emitted as a volatile binding; got:\n{src}"
4856        );
4857        assert!(
4858            src.contains("volatile __metric_bytes_out := history_bytes_out"),
4859            "the value binding must still be emitted; got:\n{src}"
4860        );
4861    }
4862
4863    /// Per (metric, dimension), not per dimension: two metrics placing into
4864    /// one dimension by different expressions must not collide on a wire name
4865    /// and silently let one placement win.
4866    #[test]
4867    fn two_metrics_in_one_dimension_get_distinct_coordinate_wires() {
4868        assert_eq!(
4869            synthesize_cell_binding_name("bytes_out", "tier"),
4870            "__cell_bytes_out__tier"
4871        );
4872        assert_ne!(
4873            synthesize_cell_binding_name("bytes_out", "tier"),
4874            synthesize_cell_binding_name("bytes_in", "tier")
4875        );
4876    }
4877
4878    /// A phase with a `metrics:` block (and no poll) synthesises a
4879    /// `volatile phase_start := phase_start_millis()` origin binding plus one
4880    /// `volatile __metric_<name> := <value>` per metric. The phase's own
4881    /// bindings are appended verbatim.
4882    ///
4883    /// `phase_start` was an `extern … = 0` filled by the executor at the
4884    /// completion-time pull, which meant anything reading it while the phase
4885    /// ran got the default.
4886    #[test]
4887    fn synthesize_phase_scope_bindings_emits_metric_bindings() {
4888        use nmbrs_workload::model::{BindingsDef, MetricSpec, WorkloadPhase};
4889        let mut metrics = std::collections::HashMap::new();
4890        metrics.insert(
4891            "time_to_index".to_string(),
4892            MetricSpec {
4893                value: "current_epoch_millis() - phase_start".into(),
4894                family: None,
4895                kind: None,
4896                unit: None,
4897                format: None,
4898                cell: Default::default(),
4899            },
4900        );
4901        let phase = WorkloadPhase {
4902            bindings: BindingsDef::default(),
4903            metrics,
4904            poll: None,
4905            ..Default::default()
4906        };
4907        let out = synthesize_phase_scope_bindings(&phase).expect("metrics synthesis");
4908        let src = match out {
4909            BindingsDef::PolydatSource(s) => s,
4910            other => panic!("expected PolydatSource, got {other:?}"),
4911        };
4912        // Bound to the runtime's phase clock, NOT an extern: as an extern it
4913        // was filled only at the completion-time pull, so anything reading it
4914        // while the phase ran (an op) got the 0 default and computed against
4915        // the epoch.
4916        assert!(
4917            src.contains("volatile phase_start := phase_start_millis()"),
4918            "must bind phase_start to the phase-scoped clock; got:\n{src}"
4919        );
4920        assert!(
4921            !src.contains("extern phase_start"),
4922            "the fill-me-in extern must be gone; got:\n{src}"
4923        );
4924        assert!(
4925            src.contains("volatile __metric_time_to_index := current_epoch_millis() - phase_start"),
4926            "must emit the volatile metric binding; got:\n{src}"
4927        );
4928        // The emitted source must compile as a phase kernel body, with
4929        // `__metric_time_to_index` surfacing as an output.
4930        let kernel = crate::scope_kernel::ScopeKernel::compile(&src)
4931            .unwrap_or_else(|e| panic!("compile failed:\n{src}\nerror: {e}"));
4932        assert!(
4933            kernel
4934                .program()
4935                .output_names()
4936                .contains(&"__metric_time_to_index"),
4937            "metric binding must be a kernel output; outputs: {:?}",
4938            kernel.program().output_names()
4939        );
4940    }
4941
4942    /// SRD-75 Push 2: when a phase has `poll:` and ops with
4943    /// declared captures, the synthesized source carries one
4944    /// `shared <name>: u64 := 0` declaration per capture
4945    /// followed by the predicate binding `__poll_until :=
4946    /// <until>`. The original phase bindings (if any) are
4947    /// appended verbatim between the captures and the
4948    /// predicate.
4949    #[test]
4950    fn synthesize_phase_scope_bindings_emits_shared_captures_and_predicate() {
4951        use nmbrs_workload::bindpoints::CapturePoint;
4952        use nmbrs_workload::model::{BindingsDef, ParsedOp, PhasePollSpec, WorkloadPhase};
4953        let mut op = ParsedOp::simple("read_state", "noop");
4954        op.captures = vec![
4955            CapturePoint {
4956                row_filter: None,
4957                source_name: "sstables".into(),
4958                as_name: "sstables".into(),
4959                cast_type: None,
4960                slurp: false,
4961                path: Some("/0/value".into()),
4962                count: false,
4963                agg: None,
4964            },
4965            CapturePoint {
4966                row_filter: None,
4967                source_name: "active_for_cf".into(),
4968                as_name: "active_for_cf".into(),
4969                cast_type: None,
4970                slurp: false,
4971                path: Some("/1/value".into()),
4972                count: true,
4973                agg: None,
4974            },
4975        ];
4976        let phase = WorkloadPhase {
4977            ops: vec![op],
4978            bindings: BindingsDef::PolydatSource("dummy := 1\n".into()),
4979            poll: Some(PhasePollSpec {
4980                until: "sstables == 1 && active_for_cf == 0".into(),
4981                ..Default::default()
4982            }),
4983            ..Default::default()
4984        };
4985        let out = synthesize_phase_scope_bindings(&phase).expect("poll synthesis should succeed");
4986        let src = match out {
4987            BindingsDef::PolydatSource(s) => s,
4988            other => panic!("expected PolydatSource, got {other:?}"),
4989        };
4990        assert!(
4991            src.contains("shared sstables := 0"),
4992            "missing shared declaration for sstables; source:\n{src}"
4993        );
4994        assert!(
4995            src.contains("shared active_for_cf := 0"),
4996            "missing shared declaration for active_for_cf; source:\n{src}"
4997        );
4998        assert!(
4999            src.contains("dummy := 1"),
5000            "original phase bindings should appear verbatim; source:\n{src}"
5001        );
5002        assert!(
5003            src.contains("__poll_until := sstables == 1 && active_for_cf == 0"),
5004            "missing __poll_until predicate binding; source:\n{src}"
5005        );
5006        // Order matters: captures first (so the predicate's
5007        // RHS references resolve through the local shared
5008        // declarations before the dynamic binding evaluates).
5009        let shared_pos = src
5010            .find("shared sstables")
5011            .expect("shared sstables present");
5012        let until_binding = crate::wrappers::condition::UNTIL_BINDING;
5013        let until_pos = src
5014            .find(until_binding)
5015            .expect("poll predicate binding present");
5016        assert!(
5017            shared_pos < until_pos,
5018            "shared captures must precede __poll_until in the synthesized source"
5019        );
5020    }
5021
5022    /// SRD-75 Push 2: a capture name that collides with an
5023    /// author-declared phase binding is a workload bug —
5024    /// the synthesizer surfaces the collision rather than
5025    /// silently shadowing.
5026    #[test]
5027    fn synthesize_phase_scope_bindings_rejects_capture_name_collision() {
5028        use nmbrs_workload::bindpoints::CapturePoint;
5029        use nmbrs_workload::model::{BindingsDef, ParsedOp, PhasePollSpec, WorkloadPhase};
5030        let mut op = ParsedOp::simple("read_state", "noop");
5031        op.captures = vec![CapturePoint {
5032            row_filter: None,
5033            source_name: "sstables".into(),
5034            as_name: "sstables".into(),
5035            cast_type: None,
5036            slurp: false,
5037            path: Some("/0/value".into()),
5038            count: false,
5039            agg: None,
5040        }];
5041        // Phase author also declared `sstables := …` —
5042        // collision is the bug.
5043        let phase = WorkloadPhase {
5044            ops: vec![op],
5045            bindings: BindingsDef::PolydatSource("sstables := 7\n".into()),
5046            poll: Some(PhasePollSpec {
5047                until: "sstables == 1".into(),
5048                ..Default::default()
5049            }),
5050            ..Default::default()
5051        };
5052        let err =
5053            synthesize_phase_scope_bindings(&phase).expect_err("colliding capture name must error");
5054        assert!(
5055            err.contains("sstables") && err.contains("collision"),
5056            "expected error to name 'sstables' and 'collision'; got: {err}"
5057        );
5058    }
5059
5060    #[test]
5061    fn build_phase_scope_kernel_with_mod_in_binding_over_partition_iter_var() {
5062        // Matches the production workload shape:
5063        //   for: "p in partitions(\"linear:3\")"
5064        //   phases.walk.bindings: n := mod_in(cycle, p)
5065        //
5066        // The phase compile must see `p` as Ext so mod_in's
5067        // second arg (Partition input) type-checks. Reproduces
5068        // the integration error "u64 ─▶ ext expects ext".
5069        let parent_kernel = crate::scope_synth::build_for_each_scope_kernel(
5070            &[("p".to_string(), "partitions(\"linear:3\")".to_string())],
5071            &[],
5072            &crate::scope_kernel::ScopeKernel::compile("\n").unwrap(),
5073            &HashMap::new(),
5074            Vec::new(),
5075            None,
5076            false,
5077            "test_for_each",
5078            None,
5079        )
5080        .expect("for-each scope synthesis");
5081
5082        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5083            "n := mod_in(cycle, p)\n".to_string(),
5084        );
5085        let phase_kernel = build_phase_scope_kernel(
5086            &phase_bindings,
5087            &[],
5088            &parent_kernel,
5089            &HashMap::new(),
5090            Vec::new(),
5091            None,
5092            false,
5093            "test_phase",
5094        )
5095        .expect("phase kernel build with mod_in(cycle, p) binding");
5096
5097        // Sanity: phase has p as Ext-typed input slot.
5098        assert_eq!(
5099            phase_kernel.program().input_port_type("p"),
5100            Some(polydat::ast::PortType::Ext),
5101            "phase kernel's `p` must be Ext-typed",
5102        );
5103        // Sanity: phase has `n` as an output (the mod_in result).
5104        assert!(
5105            phase_kernel.program().output_names().contains(&"n"),
5106            "phase kernel should expose `n` as an output"
5107        );
5108    }
5109
5110    #[test]
5111    fn build_phase_scope_kernel_cascades_partition_iter_var_as_extern_ext() {
5112        // SRD-71: when a for-each scope iterates a PartitionList
5113        // and binds an iter-var `p`, descendant phases must see
5114        // `p` as `extern p: ext` — NOT cast to str / u64 by
5115        // the cascade. The phase body's `over p` clause then
5116        // resolves `p` as a partition-typed wire.
5117        //
5118        // Reproduces the integration failure where the phase's
5119        // build_phase_scope_kernel cascade was emitting
5120        // `extern p: u64` (or Str fallback) because the
5121        // type-name lookup didn't handle PortType::Ext.
5122        let parent_kernel = crate::scope_synth::build_for_each_scope_kernel(
5123            &[("p".to_string(), "partitions(\"linear:3\")".to_string())],
5124            &[], // empty parent_manifest is fine; for_each scope only
5125            // cascades names it actually references.
5126            &crate::scope_kernel::ScopeKernel::compile("\n").unwrap(),
5127            &HashMap::new(),
5128            Vec::new(),
5129            None,
5130            false,
5131            "test_for_each",
5132            None,
5133        )
5134        .expect("for-each scope synthesis");
5135
5136        // Sanity: the for-each scope's iter-var p is Ext-typed.
5137        assert_eq!(
5138            parent_kernel.program().input_port_type("p"),
5139            Some(polydat::ast::PortType::Ext),
5140            "for-each scope's iter-var `p` must declare as Ext",
5141        );
5142
5143        // Now build a phase under it that references `p` in a
5144        // cursor's `over` clause.
5145        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5146            "cursor row = range(0, 1000) over p\n".to_string(),
5147        );
5148        let phase_kernel = build_phase_scope_kernel(
5149            &phase_bindings,
5150            &[],
5151            &parent_kernel,
5152            &HashMap::new(),
5153            Vec::new(),
5154            None,
5155            false,
5156            "test_phase",
5157        )
5158        .expect("phase kernel build");
5159
5160        // The phase kernel must see `p` as Ext-typed.
5161        let port_type = phase_kernel.program().input_port_type("p");
5162        assert_eq!(
5163            port_type,
5164            Some(polydat::ast::PortType::Ext),
5165            "phase kernel's `p` slot must be Ext (preserved through cascade), got {port_type:?}"
5166        );
5167    }
5168
5169    #[test]
5170    fn build_phase_scope_kernel_cascades_shared_bool_as_extern_bool() {
5171        // SRD-13d §1: "The kernel auto-externs every name it
5172        // doesn't declare locally; those externs resolve up
5173        // through the phase kernel and beyond per the standard
5174        // SRD-13c chain."
5175        //
5176        // SRD-66 §"Surface 2": a workload-root `shared X :=
5177        // <literal>` becomes a `SharedCell`-backed slot at the
5178        // root. Descendant phases declare `extern X: bool` (or
5179        // auto-extern emits it); bind_outer_scope cell-attaches
5180        // the slot.
5181        //
5182        // SRD-13c §"Shared Mutable" step 1: `shared X := <literal>`
5183        // produces an input slot Bool (kind=ExternalWrite) plus a
5184        // passthrough output Bool, modifier SHARED.
5185        //
5186        // This unit-test verifies the documented type-preservation
5187        // contract: a phase scope built via build_phase_scope_kernel
5188        // against a parent kernel carrying a SHARED Bool output
5189        // must produce a phase-scope kernel whose has_X input slot
5190        // is type Bool, NOT typed U64 / not classified Coordinate.
5191        // Without this property, the SharedCell that bind_outer_scope
5192        // attaches gets a slot whose declared type doesn't match
5193        // the cell's actual Value variant — downstream consumers
5194        // (e.g. pick) see the runtime variant and reject it.
5195        let parent = crate::scope_kernel::ScopeKernel::compile(
5196            "input cycle: u64\nshared has_sai_column_indexes := false\n\
5197             shared has_indexes := false\n",
5198        )
5199        .expect("parent compile");
5200        // The phase has its own bindings block (the await_index shape).
5201        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5202            "target_index_table := pick(has_sai_column_indexes, has_indexes, \
5203             \"a\", \"b\")\n"
5204                .to_string(),
5205        );
5206        let phase_kernel = build_phase_scope_kernel(
5207            &phase_bindings,
5208            &[], // outer_manifest (would be populated in real runner, but builder doesn't strictly need it)
5209            &parent,
5210            &HashMap::new(),
5211            Vec::new(),
5212            None,
5213            false,
5214            "test_phase",
5215        )
5216        .expect("phase kernel build");
5217
5218        // The phase kernel must have has_X as an input slot.
5219        let idx_sai = phase_kernel.program().find_input("has_sai_column_indexes");
5220        assert!(
5221            idx_sai.is_some(),
5222            "phase kernel must have `has_sai_column_indexes` input slot"
5223        );
5224        let idx = idx_sai.unwrap();
5225
5226        // Type must be Bool (per SRD-13c §"Shared Mutable" step 1
5227        // + SRD-66 §"Reading from a downstream phase").
5228        let port_type = phase_kernel
5229            .program()
5230            .input_port_type("has_sai_column_indexes");
5231        assert_eq!(
5232            port_type,
5233            Some(polydat::ast::PortType::Bool),
5234            "phase kernel's has_sai_column_indexes slot must be Bool, got {port_type:?}"
5235        );
5236
5237        // Kind must NOT be Coordinate — cascaded names are IterationExtern
5238        // (or ExternalWrite), not Coordinate. Coordinate would put the slot
5239        // in the set_inputs(&[u64]) propagation, breaking the cell-bound
5240        // contract per SRD-13c §"Shared Mutable" step 3.
5241        let kind = phase_kernel.program().input_kind(idx);
5242        assert_ne!(
5243            kind,
5244            Some(polydat::kernel::InputKind::Coordinate),
5245            "phase kernel's has_sai_column_indexes slot must NOT be Coordinate; got {kind:?}"
5246        );
5247    }
5248
5249    #[test]
5250    fn executor_build_scope_emits_extern_bool_for_cell_backed_shared_wire() {
5251        // Reproduces the executor's specific build_scope call
5252        // sequence for the consume phase:
5253        //
5254        //   1. Build the phase scope kernel via build_phase_scope_kernel
5255        //      (this is what the runner's install pass does).
5256        //   2. Call build_scope(ops, ..., parent_kernel=phase_scope)
5257        //      with phase_scope as classifier_kernel — this is
5258        //      what executor.rs:1429 does at run_phase time.
5259        //   3. compile_from_scope(scope, ...) — produces the
5260        //      iter_op_builder kernel that dryrun=wiring dumps.
5261        //
5262        // The integration test
5263        // `shared_bool_through_for_each_into_consumer_phase_bindings`
5264        // proves this whole sequence produces a kernel with has_X
5265        // as `coordinate` U64. This unit test reproduces it without
5266        // a subprocess so we can inspect every intermediate state.
5267        use polydat::kernel::extract_manifest;
5268
5269        // ── workload root ──
5270        let root = crate::scope_kernel::ScopeKernel::compile(
5271            "shared has_a := true\n\
5272             shared has_b := false\n\
5273             selector := mod(cycle, 1)\n",
5274        )
5275        .expect("workload root compile");
5276
5277        // ── for_each scope ──
5278        let for_each = crate::scope_synth::build_for_each_scope_kernel(
5279            &[("outer".to_string(), "p1,p2".to_string())],
5280            &extract_manifest(root.program()),
5281            &root,
5282            &HashMap::new(),
5283            Vec::new(),
5284            None,
5285            false,
5286            "test_for_each",
5287            None,
5288        )
5289        .expect("for_each synth");
5290
5291        // ── phase scope kernel (cached_kernel) ──
5292        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5293            "chosen := pick(has_a, has_b, \"alpha\", \"beta\")\n".to_string(),
5294        );
5295        let phase_scope = build_phase_scope_kernel(
5296            &phase_bindings,
5297            &[],
5298            &for_each,
5299            &HashMap::new(),
5300            Vec::new(),
5301            None,
5302            false,
5303            "test_phase",
5304        )
5305        .expect("phase scope synth");
5306
5307        // ── executor's build_scope call ──
5308        let op = ParsedOp::simple("report", "consume chosen={chosen}");
5309        let ops = vec![op];
5310        let effective_manifest: Vec<crate::runner::ManifestEntry> =
5311            extract_manifest(phase_scope.program())
5312                .into_iter()
5313                .map(|e| crate::runner::ManifestEntry {
5314                    name: e.name,
5315                    port_type: e.port_type,
5316                    modifier: e.modifier,
5317                })
5318                .collect();
5319        let scope = build_scope(
5320            &ops,
5321            &HashMap::new(),
5322            &effective_manifest,
5323            &HashMap::new(),
5324            &HashMap::new(),
5325            None,
5326            &[],
5327            Some(&phase_scope),
5328        )
5329        .expect("executor build_scope");
5330
5331        // ── inspect what build_scope emits ──
5332        let emitted = scope.emit();
5333
5334        // ── compile_from_scope equivalent — uses the SAME compile
5335        // path the executor takes (compile_polydat_interpreter_with_options with
5336        // the scope's required_outputs filter).
5337        let required = scope.required_outputs();
5338        let executor_kernel = polydat::dsl::compile::compile_polydat_interpreter_with_options(
5339            &emitted,
5340            &polydat::dsl::compile::CompileOptions {
5341                required_outputs: required.clone(),
5342                context: "test".to_string(),
5343                ..Default::default()
5344            },
5345            None,
5346        )
5347        .unwrap_or_else(|e| {
5348            panic!("compile failed: {e}\nemitted source:\n{emitted}\nrequired: {required:?}")
5349        });
5350
5351        // The executor's kernel must have has_a as Bool (or absent
5352        // entirely if not referenced). It MUST NOT be Coordinate U64.
5353        if let Some(idx) = executor_kernel.program().find_input("has_a") {
5354            let typ = executor_kernel.program().input_port_type("has_a");
5355            assert_eq!(
5356                typ,
5357                Some(polydat::ast::PortType::Bool),
5358                "executor kernel's has_a slot must be Bool;\n\
5359                 got {typ:?}\n\
5360                 emitted source:\n{emitted}\n\
5361                 input names: {:?}\n\
5362                 coord_count: {}",
5363                executor_kernel.program().input_names(),
5364                executor_kernel.program().coord_count()
5365            );
5366            let kind = executor_kernel.program().input_kind(idx);
5367            assert_ne!(
5368                kind,
5369                Some(polydat::kernel::InputKind::Coordinate),
5370                "executor kernel's has_a slot must NOT be Coordinate;\n\
5371                 got {kind:?}\n\
5372                 emitted source:\n{emitted}\n\
5373                 input names: {:?}\n\
5374                 coord_count: {}",
5375                executor_kernel.program().input_names(),
5376                executor_kernel.program().coord_count()
5377            );
5378        }
5379    }
5380
5381    #[test]
5382    fn full_chain_workload_to_executor_scope_preserves_shared_bool() {
5383        // Chains through every layer the failing integration test
5384        // touches, in-process, with the same shape that triggers
5385        // the failure:
5386        //
5387        //   1. params kernel (workload params as `const` bindings).
5388        //   2. workload-root kernel via the `compile_bindings_with_libs_excluding`-style
5389        //      flow: build_scope + scope.ingest_polydat_source + parent.build_subscope.
5390        //   3. for_each scope kernel (outer iter var).
5391        //   4. for_each scope kernel (inner with multi-iter clause).
5392        //   5. phase scope kernel via build_phase_scope_kernel (consume).
5393        //   6. executor's build_scope + compile_polydat_with_libs_and_limit.
5394        //
5395        // Verifies at the END that the consumer phase's executor-
5396        // compiled kernel has has_a as Bool/non-Coordinate.
5397        use nmbrs_workload::model::ParsedOp;
5398        use polydat::kernel::extract_manifest;
5399
5400        // Step 1: params kernel.
5401        let mut workload_params: HashMap<String, String> = HashMap::new();
5402        workload_params.insert("dataset".to_string(), "example_dataset".to_string());
5403        workload_params.insert("prefix".to_string(), "px_".to_string());
5404        let mut sorted: Vec<&String> = workload_params.keys().collect();
5405        sorted.sort();
5406        let mut params_source = String::new();
5407        for k in sorted {
5408            params_source.push_str(&format!("const {k} := \"{}\"\n", workload_params[k]));
5409        }
5410        let params_kernel =
5411            crate::scope_kernel::ScopeKernel::compile(&params_source).expect("params compile");
5412
5413        // Step 2: workload-root kernel.
5414        let mut scope = build_scope(
5415            &[] as &[ParsedOp],
5416            &HashMap::new(),
5417            &[],
5418            &workload_params,
5419            &HashMap::new(),
5420            None,
5421            &[],
5422            None,
5423        )
5424        .expect("workload root build_scope");
5425        // KEY: the binding RHS uses string interpolation against
5426        // workload params. This is what triggers the chain
5427        // corruption — without it, the test passes; with it, the
5428        // integration test fails.
5429        let workload_level_polydat = "combo_label := str_concat(\"{dataset}\", \"{prefix}\")\n\
5430                                 shared has_a := true\n\
5431                                 shared has_b := false\n";
5432        scope.ingest_polydat_source(workload_level_polydat, BindingOrigin::Inherited);
5433        let root_source = scope.emit();
5434        let root = crate::scope_kernel::ScopeKernel::build_under(
5435            params_kernel.kernel(),
5436            crate::scope_kernel::SourceMatter::source(
5437                "test_root",
5438                root_source.clone(),
5439                polydat::kernel::subcontext::CompileOptions {
5440                    workload_dir: None,
5441                    polydat_lib_paths: Vec::new(),
5442                    strict: false,
5443                    required_outputs: scope.required_outputs(),
5444                    context_label: Some("test_root".to_string()),
5445                    cursor_limit: None,
5446                    ..Default::default()
5447                },
5448            ),
5449        )
5450        .expect("root build");
5451
5452        // Sanity: has_a SHARED at root.
5453        let shared = root.program().shared_outputs();
5454        assert!(
5455            shared.contains(&"has_a"),
5456            "root should have has_a as SHARED output; got {shared:?}"
5457        );
5458
5459        // Step 3: outer for_each scope.
5460        let outer_fe = crate::scope_synth::build_for_each_scope_kernel(
5461            &[("outer".to_string(), "p1,p2".to_string())],
5462            &extract_manifest(root.program()),
5463            &root,
5464            &workload_params,
5465            Vec::new(),
5466            None,
5467            false,
5468            "test_outer_fe",
5469            None,
5470        )
5471        .expect("outer for_each synth");
5472
5473        // Step 4: inner for_each scope (dependent multi-iter).
5474        let inner_fe = crate::scope_synth::build_for_each_scope_kernel(
5475            &[
5476                ("inner".to_string(), "lo,hi".to_string()),
5477                ("label".to_string(), "tag_p1_lo,tag_p1_hi".to_string()),
5478            ],
5479            &extract_manifest(outer_fe.program()),
5480            &outer_fe,
5481            &workload_params,
5482            Vec::new(),
5483            None,
5484            false,
5485            "test_inner_fe",
5486            None,
5487        )
5488        .expect("inner for_each synth");
5489
5490        // Step 5: phase scope kernel for consume.
5491        let phase_bindings = BindingsDef::PolydatSource(
5492            "chosen := pick(has_a, has_b, \"alpha\", \"beta\")\n".to_string(),
5493        );
5494        let phase_scope = build_phase_scope_kernel(
5495            &phase_bindings,
5496            &[],
5497            &inner_fe,
5498            &workload_params,
5499            Vec::new(),
5500            None,
5501            false,
5502            "test_consume_phase",
5503        )
5504        .expect("consume phase synth");
5505
5506        // Step 6: executor's build_scope on the consume phase.
5507        let op = ParsedOp::simple("report", "spc/consume chosen={chosen}");
5508        let ops = vec![op];
5509        let effective_manifest: Vec<crate::runner::ManifestEntry> =
5510            extract_manifest(phase_scope.program())
5511                .into_iter()
5512                .map(|e| crate::runner::ManifestEntry {
5513                    name: e.name,
5514                    port_type: e.port_type,
5515                    modifier: e.modifier,
5516                })
5517                .collect();
5518        let exec_scope = build_scope(
5519            &ops,
5520            &HashMap::new(),
5521            &effective_manifest,
5522            &HashMap::new(),
5523            &HashMap::new(),
5524            None,
5525            &[],
5526            Some(&phase_scope),
5527        )
5528        .expect("executor build_scope");
5529
5530        let exec_source = exec_scope.emit();
5531        let exec_kernel = polydat::dsl::compile::compile_polydat_interpreter_with_options(
5532            &exec_source,
5533            &polydat::dsl::compile::CompileOptions {
5534                required_outputs: exec_scope.required_outputs(),
5535                context: "test_executor".to_string(),
5536                ..Default::default()
5537            },
5538            None,
5539        )
5540        .unwrap_or_else(|e| panic!("exec compile failed: {e}\nexec source:\n{exec_source}"));
5541
5542        // The final kernel — what the dryrun=wiring dumps — must
5543        // have has_a as Bool/non-Coordinate.
5544        if let Some(idx) = exec_kernel.program().find_input("has_a") {
5545            let typ = exec_kernel.program().input_port_type("has_a");
5546            assert_eq!(
5547                typ,
5548                Some(polydat::ast::PortType::Bool),
5549                "FINAL kernel has_a must be Bool, got {typ:?}\n\
5550                 exec source:\n{exec_source}\n\
5551                 exec input_names: {:?}\n\
5552                 exec coord_count: {}",
5553                exec_kernel.program().input_names(),
5554                exec_kernel.program().coord_count()
5555            );
5556            let kind = exec_kernel.program().input_kind(idx);
5557            assert_ne!(
5558                kind,
5559                Some(polydat::kernel::InputKind::Coordinate),
5560                "FINAL kernel has_a must NOT be Coordinate, got {kind:?}\n\
5561                 exec source:\n{exec_source}\n\
5562                 exec input_names: {:?}\n\
5563                 exec coord_count: {}",
5564                exec_kernel.program().input_names(),
5565                exec_kernel.program().coord_count()
5566            );
5567        }
5568    }
5569
5570    #[test]
5571    fn workload_root_via_compile_bindings_preserves_shared_bool_type() {
5572        // Mirrors the runner's WORKLOAD-ROOT build flow:
5573        //   compile_bindings_with_libs_excluding(
5574        //     parent=params_kernel,
5575        //     ops=all_ops,
5576        //     workload_params=<non-empty>,
5577        //     workload_level_polydat=Some(<the bindings: block>),
5578        //   )
5579        //
5580        // The actual function takes a complex set of args; here
5581        // we replicate the essential moves to expose what differs
5582        // from a direct `compile_polydat_interpreter(source)` invocation.
5583        //
5584        // SRD-13c §"Shared Mutable" requires has_a to be ExternalWrite
5585        // kind, Bool type on the workload-root program. The
5586        // dryrun=wiring output of the failing integration test shows
5587        // the downstream phase has has_a as Coordinate U64, so
5588        // either the workload-root or a downstream synthesizer
5589        // emits the wrong source for it.
5590        use nmbrs_workload::model::ParsedOp;
5591
5592        let mut workload_params: HashMap<String, String> = HashMap::new();
5593        workload_params.insert("dataset".to_string(), "example_dataset".to_string());
5594        workload_params.insert("prefix".to_string(), "px_".to_string());
5595        workload_params.insert("keyspace".to_string(), "ks1".to_string());
5596        workload_params.insert("inner_options".to_string(), "lo,hi".to_string());
5597
5598        // Workload params reach the root via a sibling params
5599        // kernel. Construct one with each param as a final binding.
5600        let mut params_source = String::new();
5601        let mut sorted: Vec<&String> = workload_params.keys().collect();
5602        sorted.sort();
5603        for k in sorted {
5604            let v = &workload_params[k];
5605            params_source.push_str(&format!("const {k} := \"{v}\"\n"));
5606        }
5607        let params_kernel =
5608            crate::scope_kernel::ScopeKernel::compile(&params_source).expect("params compile");
5609
5610        // The workload's `bindings:` block. The trigger.
5611        let workload_level_polydat = "selector := mod(cycle, 1)\n\
5612                                 shared has_a := true\n\
5613                                 shared has_b := false\n";
5614
5615        // Build the workload-root scope as compile_bindings_with_libs_excluding does.
5616        let mut scope = build_scope(
5617            &[] as &[ParsedOp],
5618            &HashMap::new(),
5619            &[],
5620            &workload_params,
5621            &HashMap::new(),
5622            None,
5623            &[],
5624            None,
5625        )
5626        .expect("build_scope");
5627        scope.ingest_polydat_source(workload_level_polydat, BindingOrigin::Inherited);
5628
5629        // The actual workload-root compile goes through
5630        // parent.build_subscope. Build the matter and finalize.
5631        let source = scope.emit();
5632        let opts = polydat::kernel::subcontext::CompileOptions {
5633            workload_dir: None,
5634            polydat_lib_paths: Vec::new(),
5635            strict: false,
5636            required_outputs: scope.required_outputs(),
5637            context_label: Some("test_workload_root".to_string()),
5638            cursor_limit: None,
5639            ..Default::default()
5640        };
5641        let root = crate::scope_kernel::ScopeKernel::build_under(
5642            params_kernel.kernel(),
5643            crate::scope_kernel::SourceMatter::source("test_workload_root", source.clone(), opts),
5644        )
5645        .expect("workload root build");
5646
5647        // The workload-root program must have has_a:
5648        //   - present as an input slot,
5649        //   - typed Bool (SRD-13c §"Shared Mutable" step 1),
5650        //   - kind ExternalWrite (NOT Coordinate),
5651        //   - marked SHARED in output_modifier (so seed_shared_cells fires).
5652        let has_a_idx = root.program().find_input("has_a").unwrap_or_else(|| {
5653            panic!(
5654                "workload root missing has_a input;\n\
5655                 emitted scope source:\n{source}\n\
5656                 input names: {:?}",
5657                root.program().input_names()
5658            )
5659        });
5660
5661        let typ = root.program().input_port_type("has_a");
5662        assert_eq!(
5663            typ,
5664            Some(polydat::ast::PortType::Bool),
5665            "workload root has_a must be Bool;\n\
5666             got {typ:?}\n\
5667             emitted source:\n{source}\n\
5668             input names: {:?}\n\
5669             coord_count: {}",
5670            root.program().input_names(),
5671            root.program().coord_count()
5672        );
5673
5674        let kind = root.program().input_kind(has_a_idx);
5675        assert_ne!(
5676            kind,
5677            Some(polydat::kernel::InputKind::Coordinate),
5678            "workload root has_a must NOT be Coordinate;\n\
5679             got {kind:?}\n\
5680             emitted source:\n{source}\n\
5681             input names: {:?}\n\
5682             coord_count: {}",
5683            root.program().input_names(),
5684            root.program().coord_count()
5685        );
5686
5687        let modifier = root.program().output_modifier("has_a");
5688        assert_eq!(
5689            modifier,
5690            polydat::dsl::ast::BindingModifier::SHARED,
5691            "workload root has_a output must have SHARED modifier;\n\
5692             got {modifier:?}"
5693        );
5694
5695        let shared = root.program().shared_outputs();
5696        assert!(
5697            shared.contains(&"has_a"),
5698            "workload root must have has_a in shared_outputs (so seed_shared_cells creates a cell);\n\
5699             got shared_outputs={shared:?}"
5700        );
5701    }
5702
5703    #[test]
5704    fn shared_bool_survives_when_workload_root_also_has_cycle_binding() {
5705        // BISECTED INTEGRATION FAILURE: adding any non-shared
5706        // workload-level binding that references `cycle`
5707        // (e.g. `selector := mod(cycle, 1)`) alongside the
5708        // SHARED bool wires causes the consumer phase's phase
5709        // scope kernel to have has_X classified as Coordinate
5710        // input slots typed U64 instead of cascaded externs
5711        // typed Bool.
5712        //
5713        // Manifests at runtime as: per-cycle `set_inputs(&[u64])`
5714        // clobbers the shared cells with `Value::U64(cycle)`,
5715        // and `pick(has_X, …)` panics with "non-bool type U64".
5716        //
5717        // This unit test walks the same scope chain
5718        // programmatically and pins the contract at each hop:
5719        //   workload root (shared bool + cycle-referencing binding)
5720        //     → for_each scope (synthesize_for_each_scope)
5721        //       → phase scope (build_phase_scope_kernel)
5722        // Asserts has_a stays Bool + non-Coordinate kind at every
5723        // layer.
5724        use polydat::kernel::extract_manifest;
5725
5726        // Step 1: workload root with shared bool AND a
5727        // non-shared cycle binding. The trigger.
5728        let root = crate::scope_kernel::ScopeKernel::compile(
5729            "shared has_a := true\n\
5730             shared has_b := false\n\
5731             selector := mod(cycle, 1)\n",
5732        )
5733        .expect("workload root compile");
5734
5735        // Workload-root contract: has_a is Bool ExternalWrite slot
5736        // (SRD-13c §"Shared Mutable" step 1).
5737        let root_has_a_idx = root
5738            .program()
5739            .find_input("has_a")
5740            .expect("workload root has_a slot");
5741        let root_has_a_type = root.program().input_port_type("has_a");
5742        assert_eq!(
5743            root_has_a_type,
5744            Some(polydat::ast::PortType::Bool),
5745            "workload root has_a must be Bool"
5746        );
5747        let root_has_a_kind = root.program().input_kind(root_has_a_idx);
5748        assert_ne!(
5749            root_has_a_kind,
5750            Some(polydat::kernel::InputKind::Coordinate),
5751            "workload root has_a must NOT be Coordinate; got {root_has_a_kind:?}"
5752        );
5753
5754        // Step 2: for_each scope.
5755        let for_each = crate::scope_synth::build_for_each_scope_kernel(
5756            &[("outer".to_string(), "p1,p2".to_string())],
5757            &extract_manifest(root.program()),
5758            &root,
5759            &HashMap::new(),
5760            Vec::new(),
5761            None,
5762            false,
5763            "test_for_each",
5764            None,
5765        )
5766        .expect("for_each synth");
5767
5768        let fe_has_a_idx = for_each
5769            .program()
5770            .find_input("has_a")
5771            .expect("for_each has_a slot");
5772        let fe_has_a_type = for_each.program().input_port_type("has_a");
5773        assert_eq!(
5774            fe_has_a_type,
5775            Some(polydat::ast::PortType::Bool),
5776            "for_each has_a must be Bool, got {fe_has_a_type:?}"
5777        );
5778        let fe_has_a_kind = for_each.program().input_kind(fe_has_a_idx);
5779        assert_ne!(
5780            fe_has_a_kind,
5781            Some(polydat::kernel::InputKind::Coordinate),
5782            "for_each has_a must NOT be Coordinate; got {fe_has_a_kind:?}"
5783        );
5784
5785        // Step 3: phase scope with its own bindings via pick.
5786        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5787            "chosen := pick(has_a, has_b, \"alpha\", \"beta\")\n".to_string(),
5788        );
5789        let phase = build_phase_scope_kernel(
5790            &phase_bindings,
5791            &[],
5792            &for_each,
5793            &HashMap::new(),
5794            Vec::new(),
5795            None,
5796            false,
5797            "test_phase",
5798        )
5799        .expect("phase scope synth");
5800
5801        let phase_has_a_idx = phase
5802            .program()
5803            .find_input("has_a")
5804            .expect("phase has_a slot");
5805        let phase_has_a_type = phase.program().input_port_type("has_a");
5806        assert_eq!(
5807            phase_has_a_type,
5808            Some(polydat::ast::PortType::Bool),
5809            "phase has_a must be Bool; got {phase_has_a_type:?}\n\
5810             phase input names: {:?}",
5811            phase.program().input_names()
5812        );
5813        let phase_has_a_kind = phase.program().input_kind(phase_has_a_idx);
5814        assert_ne!(
5815            phase_has_a_kind,
5816            Some(polydat::kernel::InputKind::Coordinate),
5817            "phase has_a must NOT be Coordinate; got {phase_has_a_kind:?}\n\
5818             phase input names: {:?}\n\
5819             coord_count: {}",
5820            phase.program().input_names(),
5821            phase.program().coord_count()
5822        );
5823    }
5824
5825    #[test]
5826    fn for_each_then_phase_preserves_shared_bool_through_chain() {
5827        // The full chain the workload exercises:
5828        //   workload root (shared has_X := false)
5829        //     → for_each scope (cascades has_X via synthesize_for_each_scope)
5830        //       → phase scope await_index (cascades has_X via build_phase_scope_kernel)
5831        //
5832        // SRD-13c §"Shared Mutable" + SRD-13d §1: at every cascade
5833        // hop, has_X stays Bool-typed and non-Coordinate.
5834        // bind_outer_scope then cell-attaches at each level so
5835        // the original SharedCell reaches the leaf.
5836        use polydat::kernel::extract_manifest;
5837        let root = crate::scope_kernel::ScopeKernel::compile(
5838            "input cycle: u64\nshared has_sai_column_indexes := false\n\
5839             shared has_indexes := false\n",
5840        )
5841        .expect("root compile");
5842
5843        // for_each scope synthesised via the comprehension
5844        // synthesizer (the path runner.rs uses for ForComprehension
5845        // install specs). Iter vars are a placeholder so the
5846        // builder runs.
5847        let for_each_kernel = crate::scope_synth::build_for_each_scope_kernel(
5848            &[("dummy_var".to_string(), "1,2".to_string())],
5849            &extract_manifest(root.program()),
5850            &root,
5851            &HashMap::new(), // workload_params
5852            Vec::new(),      // polydat_lib_paths
5853            None,            // workload_dir
5854            false,           // strict
5855            "test_for_each",
5856            None, // phase_bindings
5857        )
5858        .expect("for_each kernel synth");
5859
5860        // for_each's program must carry has_X as a Bool slot too.
5861        let fe_type = for_each_kernel
5862            .program()
5863            .input_port_type("has_sai_column_indexes");
5864        assert_eq!(
5865            fe_type,
5866            Some(polydat::ast::PortType::Bool),
5867            "for_each scope's has_sai_column_indexes must be Bool, got {fe_type:?}"
5868        );
5869        let fe_idx = for_each_kernel
5870            .program()
5871            .find_input("has_sai_column_indexes")
5872            .expect("for_each has has_sai_column_indexes input");
5873        let fe_kind = for_each_kernel.program().input_kind(fe_idx);
5874        assert_ne!(
5875            fe_kind,
5876            Some(polydat::kernel::InputKind::Coordinate),
5877            "for_each scope's has_sai_column_indexes must NOT be Coordinate; got {fe_kind:?}"
5878        );
5879
5880        // Now build await_index's phase scope under for_each
5881        // (the real scope-tree shape).
5882        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5883            "target_index_table := pick(has_sai_column_indexes, has_indexes, \
5884             \"a\", \"b\")\n"
5885                .to_string(),
5886        );
5887        let phase_kernel = build_phase_scope_kernel(
5888            &phase_bindings,
5889            &[],
5890            &for_each_kernel,
5891            &HashMap::new(),
5892            Vec::new(),
5893            None,
5894            false,
5895            "test_await_index",
5896        )
5897        .expect("phase kernel synth");
5898
5899        let phase_type = phase_kernel
5900            .program()
5901            .input_port_type("has_sai_column_indexes");
5902        assert_eq!(
5903            phase_type,
5904            Some(polydat::ast::PortType::Bool),
5905            "phase scope's has_sai_column_indexes must be Bool, got {phase_type:?}"
5906        );
5907        let phase_idx = phase_kernel
5908            .program()
5909            .find_input("has_sai_column_indexes")
5910            .expect("phase has has_sai_column_indexes input");
5911        let phase_kind = phase_kernel.program().input_kind(phase_idx);
5912        assert_ne!(
5913            phase_kind,
5914            Some(polydat::kernel::InputKind::Coordinate),
5915            "phase scope's has_sai_column_indexes must NOT be Coordinate; got {phase_kind:?}"
5916        );
5917    }
5918}
5919
5920/// Strict mode reaches every synthesized scope, and each still compiles:
5921/// strict refuses a source with no `input` declaration, and a synthesized
5922/// scope's coordinates are its parent's, so they are declared for it.
5923#[cfg(test)]
5924mod strict_synthesis_tests {
5925    use super::*;
5926
5927    fn parent() -> crate::scope_kernel::ScopeKernel {
5928        crate::scope_kernel::ScopeKernel::compile("input cycle: u64\nconst k_values := \"1, 10\"\n")
5929            .expect("parent scope")
5930    }
5931
5932    #[test]
5933    fn a_phase_scope_compiles_under_strict() {
5934        let parent = parent();
5935        let manifest = crate::runner::extract_manifest(parent.program());
5936        let kernel = build_phase_scope_kernel(
5937            &nmbrs_workload::model::BindingsDef::PolydatSource("x := cycle + 1\n".into()),
5938            &manifest,
5939            &parent,
5940            &HashMap::new(),
5941            Vec::new(),
5942            None,
5943            true,
5944            "strict phase",
5945        )
5946        .expect("a phase scope compiles under strict");
5947        assert!(kernel.input_names().iter().any(|n| n == "cycle"));
5948    }
5949
5950    #[test]
5951    fn a_do_loop_scope_compiles_under_strict() {
5952        let parent = parent();
5953        let manifest = crate::runner::extract_manifest(parent.program());
5954        build_do_loop_scope_kernel(
5955            Some("i"),
5956            "{i} < 3",
5957            &manifest,
5958            &parent,
5959            &HashMap::new(),
5960            Vec::new(),
5961            None,
5962            true,
5963            "strict do-loop",
5964        )
5965        .expect("a do-loop scope compiles under strict");
5966    }
5967
5968    #[test]
5969    fn a_for_each_scope_compiles_under_strict() {
5970        let parent = parent();
5971        let manifest = crate::runner::extract_manifest(parent.program());
5972        crate::scope_synth::build_for_each_scope_kernel(
5973            &[("k".to_string(), "{k_values}".to_string())],
5974            &manifest,
5975            &parent,
5976            &HashMap::new(),
5977            Vec::new(),
5978            None,
5979            true,
5980            "strict for_each",
5981            None,
5982        )
5983        .expect("a for_each scope compiles under strict");
5984    }
5985}