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    if let Some(rel) = op.params.get("relevancy").and_then(|v| v.as_object()) {
1662        for key in &["actual", "expected", "k", "r"] {
1663            let Some(val) = rel.get(*key).and_then(|v| v.as_str()) else {
1664                continue;
1665            };
1666            let trimmed = val
1667                .trim()
1668                .trim_start_matches('{')
1669                .trim_end_matches('}')
1670                .trim();
1671            if trimmed.is_empty() {
1672                continue;
1673            }
1674            // Skip numeric literals — `k: 10` is a constant, not a
1675            // wire ref.
1676            if trimmed.parse::<i64>().is_ok() {
1677                continue;
1678            }
1679            // Bare-identifier check matches the validator's
1680            // `is_bare_ident` rule.
1681            let bare = trimmed
1682                .chars()
1683                .next()
1684                .map(|c| c.is_ascii_alphabetic() || c == '_')
1685                .unwrap_or(false)
1686                && trimmed
1687                    .chars()
1688                    .all(|c| c.is_ascii_alphanumeric() || c == '_');
1689            if !bare {
1690                continue;
1691            }
1692            if !body_locally_declared.contains(trimmed) && !referenced.iter().any(|r| r == trimmed)
1693            {
1694                referenced.push(trimmed.to_string());
1695            }
1696        }
1697    }
1698
1699    // SRD-66 result-bindings: every LHS name a result-binding
1700    // declares needs an input slot on this op-template kernel so
1701    // the Rule 2 write-through can wire to the parent's SHARED
1702    // cell. Without this, the cell-bound slot is never declared,
1703    // `add_result_bindings` falls back to PortType::U64 (the
1704    // "couldn't classify" default) for the export, and the write-
1705    // through stores into a U64-typed view of what's actually a
1706    // Bool/Str/etc. cell — surfaces downstream as a "non-bool
1707    // type" pick panic.
1708    //
1709    // String-shape fragments carry full Polydat source whose LHS we
1710    // extract via `scan_locally_declared_idents`. Map-shape
1711    // fragments give the name directly.
1712    if let Some(rb) = op.result.as_ref() {
1713        rb.walk_fragments(|frag| match frag {
1714            nmbrs_workload::model::ResultFragment::Source(s) => {
1715                for n in scan_locally_declared_idents(s) {
1716                    if !body_locally_declared.contains(&n) && !referenced.iter().any(|r| r == &n) {
1717                        referenced.push(n);
1718                    }
1719                }
1720            }
1721            nmbrs_workload::model::ResultFragment::Named { name, .. } => {
1722                let n = name.to_string();
1723                if !body_locally_declared.contains(&n) && !referenced.iter().any(|r| r == &n) {
1724                    referenced.push(n);
1725                }
1726            }
1727        });
1728    }
1729
1730    // SRD-13f: parent-ref classification no longer gates
1731    // extern emission. The legacy "DynamicOutput without
1732    // shared" rejection assumed snapshot semantics for
1733    // non-shared cross-scope reads (SRD-13c §"Default:
1734    // Immutable Propagation"). SRD-13f reframes that rule:
1735    // the read invariant is uniform across all visible
1736    // parent outputs — inner reads return outer's current
1737    // value — and the construction-time wiring (cell
1738    // attachment for shared, per-cycle refresh for non-shared
1739    // pending the full cell mechanism in Push B.2) keeps the
1740    // invariant intact. No external pre-check needed.
1741
1742    // Emit extern decls only for names the op references and
1743    // that the parent provides. Lazy cascade — keeps the
1744    // op-template kernel narrow and makes the contract check
1745    // above crisp.
1746    for name in &referenced {
1747        if emitted.contains(name) {
1748            continue;
1749        }
1750        if body_locally_declared.contains(name) {
1751            continue;
1752        }
1753        // Names that are *Coordinate* inputs in the parent (the
1754        // implicit `cycle` and friends) must stay Coordinate in
1755        // the inner kernel too, so `set_inputs` propagates them
1756        // per cycle. An explicit `extern` declaration would force
1757        // IterationExtern classification and break propagation —
1758        // skip the explicit emit and let the inner kernel's auto-
1759        // extern path re-classify as Coordinate.
1760        let is_parent_coord = parent_kernel
1761            .program()
1762            .find_input(name)
1763            .and_then(|idx| parent_kernel.program().input_kind(idx))
1764            .is_some_and(|k| matches!(k, polydat::kernel::InputKind::Coordinate));
1765        if is_parent_coord {
1766            // The cascade still needs to record this as an
1767            // inherited name so `mark_inherited_outputs` includes
1768            // it — the inner kernel will re-publish it as an
1769            // (auto-extern) input/output and materialize_wiring_from_outer
1770            // will value-copy at construction time.
1771            inherited_names.push(name.clone());
1772            continue;
1773        }
1774        // Workload-param check goes BEFORE manifest cascade: a
1775        // workload param ALSO appears in the parent's manifest
1776        // (cascaded as an auto-output of an `extern <name>: …`
1777        // line in the for_each scope synthesiser), but op-template
1778        // bodies need it as a `final` literal so `init <name> =
1779        // <expr-using-param>` folds at compile time. Routing
1780        // through the manifest path emits `extern`, leaves init
1781        // unfolded, and the runtime sees `Value::None` in the
1782        // input slot — exactly the surface the Phase-9 op-template
1783        // kernel was hitting on dataset_prebuffer / query_count.
1784        if let Some(value) = workload_params.get(name) {
1785            // Chain-aware: a `set:` / `bindings:` scope above
1786            // us may have shadowed the workload-param default.
1787            // This was the root cause of the CQL prepared-
1788            // statement regression where `{ann_opts}` got
1789            // emitted as a `?` bind point — the op-template
1790            // kernel's local `const rerank_mode := "default"`
1791            // masked the SetParam shadow, and the downstream
1792            // `const ann_opts := select_str(str_eq(
1793            // rerank_mode, "pinned"), …)` folded against the
1794            // wrong rerank_mode value.
1795            crate::scope_synth::emit_workload_param_chain_aware(
1796                name,
1797                value,
1798                parent_kernel,
1799                &mut source,
1800                &mut emitted,
1801                None,
1802            );
1803        } else if let Some(entry) = manifest_by_name.get(name.as_str()) {
1804            let type_name = entry.port_type.to_keyword();
1805            source.push_str(&format!("extern {name}: {type_name}\n"));
1806            emitted.insert(name.clone());
1807            inherited_names.push(name.clone());
1808        } else if let Some(parent_idx) = parent_kernel.program().find_input(name) {
1809            // Parent INPUT — for non-Coordinate inputs (iteration
1810            // vars, external-write ports) emit an explicit `extern` so the
1811            // inner kernel's input classification matches the
1812            // parent's, and materialize_wiring_from_outer can value-copy or
1813            // shared-cell-attach. For Coordinate inputs (e.g. the
1814            // implicit `cycle` coord), DON'T emit — let the GK
1815            // auto-extern path classify them as Coordinate too,
1816            // so per-cycle `set_inputs` propagates to the inner
1817            // kernel. An explicit `extern` would force
1818            // IterationExtern and break that propagation.
1819            let kind = parent_kernel.program().input_kind(parent_idx);
1820            if !matches!(kind, Some(polydat::kernel::InputKind::Coordinate)) {
1821                let port_type = parent_kernel
1822                    .program()
1823                    .input_port_type(name)
1824                    .ok_or_else(|| {
1825                        format!(
1826                            "scope synthesis: parent input '{name}' has no \
1827                         declared PortType (find_input returned index {parent_idx} \
1828                         but input_port_type returned None — kernel program shape \
1829                         broken)"
1830                        )
1831                    })
1832                    .expect("input index just resolved must have a port type");
1833                let type_name = port_type.to_keyword();
1834                source.push_str(&format!("extern {name}: {type_name}\n"));
1835                emitted.insert(name.clone());
1836                inherited_names.push(name.clone());
1837            }
1838        }
1839    }
1840
1841    // SRD-13f Push A: workload params are root-level context
1842    // wires — they must appear on every scope's kernel program
1843    // as inlined constants (materialization gradient §"Inlined
1844    // constant"). The per-name loop above emits them as `final`
1845    // for body-referenced params; this cascade catches the rest
1846    // so every workload param lands on this op-template kernel
1847    // as a folded constant. The previous emission shape
1848    // (`extern X: type`) was wrong — it forced a runtime input
1849    // slot, which (a) prevented `const` bindings from folding
1850    // against the param's value at compile time and (b) routed
1851    // a compile-time-constant value through the runtime input
1852    // path. `final` is the correct materialization.
1853    for (name, value) in workload_params {
1854        // Chain-aware emission: honors any `set:` / `bindings:`
1855        // scope shadow above us. Without it, the op-template's
1856        // local `const NAME := <hashmap-default>` would mask
1857        // the shadow and break SRD-21's single-resolution-
1858        // surface invariant.
1859        crate::scope_synth::emit_workload_param_chain_aware(
1860            name,
1861            value,
1862            parent_kernel,
1863            &mut source,
1864            &mut emitted,
1865            None,
1866        );
1867    }
1868    if body_text.trim().is_empty() {
1869        // No own bindings — the kernel just re-exports parent.
1870        // The flatten-elision logic upstream should have caught
1871        // this, but defensively keep the kernel non-empty.
1872        if source.is_empty() {
1873            source.push_str("const __empty := 0\n");
1874        }
1875    } else {
1876        if !source.ends_with('\n') && !source.is_empty() {
1877            source.push('\n');
1878        }
1879        source.push_str(&body_text);
1880        if !source.ends_with('\n') {
1881            source.push('\n');
1882        }
1883    }
1884
1885    // SRD-67 Phase 3 — route op-template scope synthesis through
1886    // the SubcontextBuilder bridge. The Phase-9 op-template
1887    // kernel needs the same `compile_polydat_with_libs` knobs the
1888    // legacy direct call took (lib paths, strict, source dir,
1889    // context label); those flow through `CompileOptions`. The
1890    // bridge applies `mark_inherited_outputs` and
1891    // `materialize_wiring_from_outer` against the live parent so per-cycle
1892    // values reach the inner kernel's input slots; the trailing
1893    // `polydat::kernel::propagate_inputs` keeps cascade-extern'd inputs
1894    // flowing through (until Rule 4 / Rule 5 absorb them).
1895    let compile_options = polydat::kernel::subcontext::CompileOptions {
1896        workload_dir: workload_dir.map(|p| p.to_path_buf()),
1897        polydat_lib_paths,
1898        strict,
1899        required_outputs: Vec::new(),
1900        context_label: Some(context.to_string()),
1901        cursor_limit: None,
1902        kernel_opt,
1903        ..Default::default()
1904    };
1905
1906    // SRD-67 Phase 5 — fold the SRD-66 `result:` source through
1907    // `add_result_bindings`. The builder walks the source's free
1908    // identifiers, injects magic externs (`body` / `count` /
1909    // `ok`) it actually references, and registers each LHS as
1910    // an export. Rule 2 in finalize rewrites any LHS that
1911    // collides with a parent `shared` export into a write-
1912    // through; the kernel carries the bindings forward via
1913    // `set_write_throughs` so the per-cycle dispenser can
1914    // commit. Map-shape entries (already flattened to
1915    // `<name> := <source>` in the workload model) flow
1916    // through unchanged; path expressions surface as unbound-
1917    // identifier compile errors with the SRD-66 deferred-
1918    // structural-body-wire diagnostic.
1919    // SRD-66 result bindings + post-SRD-68 metric-value bindings.
1920    // Both routes feed the same closure-binding-economy walker
1921    // (`add_result_bindings`) which injects magic externs
1922    // (body/count/ok) for any of those names referenced from
1923    // either RHS. The walker then registers each LHS as a kernel
1924    // output the metrics wrapper / evaluator reads at cycle time
1925    // via `wires.get`.
1926    //
1927    // Metric-driven bindings use the `__metric_<name>` prefix so
1928    // they don't collide with user-declared output names and so
1929    // diagnostic output can filter them as internal. MetricsDispenser
1930    // reads the same `__metric_<name>` form at cycle time —
1931    // `synthesize_metric_binding_name` is the single source of
1932    // truth for the naming convention.
1933    let mut result_source: String = op
1934        .result
1935        .as_ref()
1936        .map(collect_result_bindings_source)
1937        .unwrap_or_default();
1938    if !op.metrics.is_empty() {
1939        // Stable ordering — matches `MetricsDispenser::wrap`'s
1940        // sort-by-name so synthesis order is reproducible.
1941        let mut entries: Vec<_> = op.metrics.iter().collect();
1942        entries.sort_by(|a, b| a.0.cmp(b.0));
1943        for (name, spec) in entries {
1944            let binding = synthesize_metric_binding_name(name);
1945            result_source.push_str(&format!("{binding} := {expr}\n", expr = spec.value));
1946            // Cell coordinates are reified the same way the value is: as
1947            // compiled kernel bindings walked by `add_result_bindings`, so a
1948            // coordinate expression gets its magic-extern slots and is
1949            // type-checked, rather than being a string assembled at runtime.
1950            // `BTreeMap` iteration keeps the emission order stable.
1951            for (dim, expr) in &spec.cell {
1952                let cell_binding = synthesize_cell_binding_name(name, dim);
1953                result_source.push_str(&format!("{cell_binding} := {expr}\n"));
1954            }
1955        }
1956    }
1957    // Poll predicate. `poll.until:` lowers to the SAME binding name the
1958    // phase-level poll uses (`condition::UNTIL_BINDING`), in the op's own
1959    // kernel — so the poll wrapper reads one wire and never asks which kind of
1960    // node it is running under. Ordinary scoping does the rest: an op's
1961    // predicate shadows its phase's, as any other wire would.
1962    if let Some(until) = template_poll_until(op) {
1963        result_source.push_str(&format!(
1964            "{} := {until}\n",
1965            crate::wrappers::condition::UNTIL_BINDING,
1966        ));
1967    }
1968    // While-wrapper predicate. Synthesised as `__while := <expr>`
1969    // so `add_result_bindings` walks the expression, injects
1970    // magic externs for any captured wires it references, and
1971    // registers `__while` as a kernel output the WhileWrapper
1972    // reads at cycle time via the canonical pull plan.
1973    if let Some(while_expr) = op.while_cond.as_ref() {
1974        result_source.push_str(&format!(
1975            "{} := {expr}\n",
1976            crate::wrappers::r#while::BINDING_NAME,
1977            expr = while_expr,
1978        ));
1979    }
1980    let result_source: Option<String> = Some(result_source).filter(|s| !s.trim().is_empty());
1981
1982    if debug_scope_synth_enabled() {
1983        eprintln!(
1984            "=== OP SYNTH [{context}] inherited={inherited_names:?} parent_has_xval_input={:?} parent_manifest_has_xval={} ===\n{source}\n=== END ===",
1985            parent_kernel.program().find_input("xval"),
1986            manifest_by_name.contains_key("xval")
1987        );
1988    }
1989    // Built under the parent from source matter; the scope keeps the
1990    // finalized module, from which each fiber instantiates its per-op
1991    // kernel with the module's write-throughs. Strict mode refuses a
1992    // scope-init const that fell through to `None`
1993    // (composition_substrate.md L2.f).
1994    let synthesis_error = |e: String| format!("{context}: op-template scope synthesis: {e}");
1995    let mut matter = crate::scope_kernel::SourceMatter::source(context, source, compile_options)
1996        .inherited(inherited_names);
1997    if let Some(rb) = result_source {
1998        matter = matter.results(rb);
1999    }
2000    let kernel = crate::scope_kernel::ScopeKernel::synthesize_under(parent_kernel, matter)
2001        .map_err(synthesis_error)?;
2002
2003    // SRD-108 Part B — the interface's TYPE PROOF, at the same
2004    // place every other wire is type-checked: pre-map synthesis,
2005    // against the compiled op-template program. Load-time binder
2006    // checks were the early named errors; this is enforcement.
2007    if let Some(iface) = op.abstract_interface.as_ref() {
2008        verify_op_interface(iface, kernel.program().as_ref(), context)?;
2009    }
2010    Ok(kernel)
2011}
2012
2013/// SRD-108 Part B — verify a bound slot's interface against its
2014/// compiled op-template program:
2015///
2016/// - every `yields` name must exist on the program (a capture
2017///   extern slot or a declared output) with the declared type;
2018/// - every `needs` name the program declares as a slot must
2019///   carry the declared type (a need consumed only through
2020///   textual bind points declares no slot — the parent-chain
2021///   resolution type-checks those as usual).
2022///
2023/// Runs during pre-map synthesis — an interface violation fails
2024/// workload init, never a runtime critical section.
2025fn verify_op_interface(
2026    iface: &nmbrs_workload::model::OpInterface,
2027    program: &polydat::kernel::PolydatProgram,
2028    context: &str,
2029) -> Result<(), String> {
2030    let type_of = |name: &str| -> Option<polydat::ast::PortType> {
2031        program
2032            .input_port_type(name)
2033            .or_else(|| program.output_port_type(name))
2034    };
2035    // Yields: PRESENCE is the binder's load-time check (a capture
2036    // `as`-name); captures deliver through the wrapper stack's
2037    // wire writes, so a capture-only yield may hold no slot on
2038    // the op-template program itself. When a slot DOES
2039    // materialize (declared cast, binding reference), its type
2040    // must match the interface.
2041    for (name, declared) in &iface.yields {
2042        if let Some(actual) = type_of(name)
2043            && actual != *declared
2044        {
2045            return Err(format!(
2046                "{context}: interface yield '{name}' declares type \
2047                 {declared}, but the compiled op template carries \
2048                 {actual}"
2049            ));
2050        }
2051    }
2052    for (name, declared) in &iface.needs {
2053        if let Some(actual) = type_of(name)
2054            && actual != *declared
2055        {
2056            return Err(format!(
2057                "{context}: interface need '{name}' declares type \
2058                 {declared}, but the compiled op template carries \
2059                 {actual}"
2060            ));
2061        }
2062    }
2063    // Results (SRD-109 Part 3): the projection wire's slot is
2064    // DECLARED from the interface type at op-template build (see
2065    // the result-binding declaration pass), so the check here is
2066    // agreement when the slot materialized — a mismatch means
2067    // something else (a binding, a cast) claimed the name at a
2068    // different type.
2069    for (name, declared) in &iface.results {
2070        if let Some(actual) = type_of(name)
2071            && actual != *declared
2072        {
2073            return Err(format!(
2074                "{context}: interface results wire '{name}' declares \
2075                 type {declared}, but the compiled op template carries \
2076                 {actual}"
2077            ));
2078        }
2079    }
2080    Ok(())
2081}
2082
2083/// Internal binding name for a workload-declared metric's `value:`
2084/// expression. The metric's `value:` source is synthesised into the
2085/// op-template kernel as `<binding> := <expr>` so a single
2086/// closure-binding-economy walker handles slot allocation for
2087/// magic-extern references in both result-bindings AND
2088/// metric-value expressions. MetricsDispenser reads the same name
2089/// at cycle time via `ctx.wires.get` — the prefix keeps these
2090/// internal bindings from colliding with workload-declared output
2091/// names and lets diagnostic surfaces filter them out by prefix.
2092/// The `until:` expression from an op's `poll:` map, if it declared one.
2093///
2094/// Returns `None` for the `mode: await_empty` form, which waits for an
2095/// empty result.
2096fn template_poll_until(op: &nmbrs_workload::model::ParsedOp) -> Option<String> {
2097    op.params
2098        .get("poll")?
2099        .as_object()?
2100        .get("until")?
2101        .as_str()
2102        .map(|s| s.trim().to_string())
2103        .filter(|s| !s.is_empty())
2104}
2105
2106pub fn synthesize_metric_binding_name(metric_name: &str) -> String {
2107    format!("__metric_{metric_name}")
2108}
2109
2110/// The kernel wire a metric's cell COORDINATE is lowered to, per
2111/// (metric, dimension).
2112///
2113/// Keyed by metric as well as dimension because two metrics in one scope may
2114/// place into the same dimension by different expressions — `bytes_out` from
2115/// one captured column and `bytes_in` from another. A per-dimension name would
2116/// collide and one placement would silently win.
2117///
2118/// Same `__` convention as [`synthesize_metric_binding_name`]: it cannot
2119/// collide with an author-declared output, and diagnostics can filter it as
2120/// internal.
2121pub fn synthesize_cell_binding_name(metric_name: &str, dimension: &str) -> String {
2122    format!("__cell_{metric_name}__{dimension}")
2123}
2124
2125/// The phase-kernel wire an **inline objective expression** is lowered to
2126/// (SRD-86). `optimize.objective` is either a bare wire reference (read
2127/// directly off the phase kernel) or an inline expression;
2128/// [`synthesize_phase_scope_bindings`] lowers the latter to
2129/// `volatile __objective := <expr>` so the optimizer reads exactly one wire
2130/// regardless of which form the author wrote. The `__` prefix keeps it from
2131/// colliding with author-declared outputs (same convention as
2132/// [`synthesize_metric_binding_name`]).
2133pub const OBJECTIVE_WIRE: &str = "__objective";
2134
2135/// Whether an `optimize.objective` value is a **bare wire reference** — a
2136/// single identifier read directly off the phase kernel — versus an **inline
2137/// expression** (operators, calls, dots, whitespace) that must be synthesized.
2138/// A bare reference is left untouched (no synthesis, current behavior); an
2139/// expression is lowered to [`OBJECTIVE_WIRE`].
2140pub fn objective_is_bare_wire(objective: &str) -> bool {
2141    let s = objective.trim();
2142    !s.is_empty()
2143        && s.chars()
2144            .next()
2145            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
2146        && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
2147}
2148
2149/// The phase-kernel wire the optimizer reads for `objective`: the bare name
2150/// itself, or the synthesized [`OBJECTIVE_WIRE`] for an inline expression.
2151/// Pairs with [`synthesize_phase_scope_bindings`], which emits the
2152/// `__objective` binding for the expression case — the two agree by sharing
2153/// [`objective_is_bare_wire`].
2154pub fn objective_wire(objective: &str) -> &str {
2155    if objective_is_bare_wire(objective) {
2156        objective.trim()
2157    } else {
2158        OBJECTIVE_WIRE
2159    }
2160}
2161
2162/// Flatten a [`nmbrs_workload::model::ResultSpec`] into a single
2163/// Polydat source string suitable for
2164/// [`polydat::kernel::subcontext::SubcontextBuilder::add_result_bindings`].
2165/// String-shape entries pass through verbatim; map-shape entries
2166/// emit `<name> := <source>` lines (the same projection the
2167/// SRD-66 schema specifies); list-shape entries recurse.
2168///
2169/// Path-expression and built-in short forms (`count` / `ok`) in
2170/// map-shape entries land as bare Polydat expressions — `count` and
2171/// `ok` resolve to the magic-extern wires
2172/// [`SubcontextBuilder::add_result_bindings`] injects, while
2173/// path expressions like `rows[0].field` produce an unbound-
2174/// identifier compile error. The latter surfaces SRD-66's
2175/// "path expressions deferred until structural-body wire lands"
2176/// diagnostic.
2177fn collect_result_bindings_source(spec: &nmbrs_workload::model::ResultSpec) -> String {
2178    let mut out = String::new();
2179    spec.walk_fragments(|frag| match frag {
2180        nmbrs_workload::model::ResultFragment::Source(src) => {
2181            out.push_str(src);
2182            if !src.ends_with('\n') {
2183                out.push('\n');
2184            }
2185        }
2186        nmbrs_workload::model::ResultFragment::Named { name, source } => {
2187            // Path expressions (`rows[*].key`, `result[0].id`) are
2188            // dispenser-evaluated (SRD-70) — they are not polydat
2189            // source and would fail the result-bindings compile.
2190            // Only `count` / `ok` (magic-extern references) and
2191            // polydat-call entries compile into the kernel.
2192            let s = source.trim();
2193            if s == "count" || s == "ok" || s.contains('(') {
2194                out.push_str(&format!("{name} := {source}\n"));
2195            }
2196        }
2197    });
2198    out
2199}
2200
2201// reason: cohesive scope builder — each argument is a distinct compile input
2202// (ops, iteration vars, outer manifest, workload params, …); grouping them
2203// into a struct would only relocate the same fields without adding clarity.
2204#[allow(clippy::too_many_arguments)]
2205pub fn build_scope(
2206    ops: &[ParsedOp],
2207    iteration_vars: &HashMap<String, String>,
2208    outer_manifest: &[crate::runner::ManifestEntry],
2209    workload_params: &HashMap<String, String>,
2210    phases: &HashMap<String, nmbrs_workload::model::WorkloadPhase>,
2211    phase_cycles: Option<&str>,
2212    exclude: &[String],
2213    // SRD-13f §"Wire-reference classification" — the parent
2214    // scope's compiled kernel. The synthesizer reads its
2215    // retained AST (for case 3 local-inclusion walks) and its
2216    // folded constant state (for case 1 promoted-final
2217    // emission). `None` for the workload-root build (it IS the
2218    // root; no parent).
2219    parent_kernel: Option<&crate::scope_kernel::ScopeKernel>,
2220) -> Result<BindingScope, String> {
2221    let mut scope = BindingScope::new();
2222
2223    // --- Step 1: Classify op bindings by origin ---
2224    //
2225    // The first op's PolydatSource is the "base" (inherited/phase-level).
2226    // Subsequent ops: if their PolydatSource matches the base exactly,
2227    // they're inherited duplicates. If different, they're op-level
2228    // augmentations carrying new bindings.
2229    let mut base_source: Option<String> = None;
2230
2231    for op in ops {
2232        if let BindingsDef::PolydatSource(src) = &op.bindings {
2233            let src = src.trim();
2234            if src.is_empty() {
2235                continue;
2236            }
2237
2238            match &base_source {
2239                None => {
2240                    // First op's source becomes the base — classified as Inherited
2241                    base_source = Some(src.to_string());
2242                    scope.ingest_polydat_source(src, BindingOrigin::Inherited);
2243                }
2244                Some(base) => {
2245                    if src == base.as_str() {
2246                        // Identical to base — inherited duplicate, skip.
2247                        // validate() and emit() handle dedup.
2248                    } else {
2249                        // Different from base — this op has its own bindings.
2250                        // Ingest the DIFFERENCE (lines not in base) as Op origin,
2251                        // and the shared lines as Inherited. Compare by
2252                        // *logical* lines so multi-line expressions
2253                        // (function calls broken over several physical
2254                        // lines) stay intact instead of being split at
2255                        // the paren and ingested piecewise.
2256                        let base_logical: Vec<String> = logical_lines(base)
2257                            .into_iter()
2258                            .map(|l| l.trim().to_string())
2259                            .filter(|l| !l.is_empty())
2260                            .collect();
2261                        for line in logical_lines(src) {
2262                            let trimmed = line.trim();
2263                            if trimmed.is_empty() {
2264                                continue;
2265                            }
2266                            if base_logical.iter().any(|b| b == trimmed) {
2267                                // This line is inherited — already ingested from base
2268                            } else {
2269                                // This line is op-specific
2270                                scope.ingest_polydat_source(
2271                                    trimmed,
2272                                    BindingOrigin::Op(op.name.clone()),
2273                                );
2274                            }
2275                        }
2276                    }
2277                }
2278            }
2279        }
2280    }
2281
2282    // --- Step 2: Add iteration variables ---
2283    //
2284    // Iter vars (own + cascade-inherited) are part of the
2285    // **scope's contract** — they're names a phase or a child
2286    // scope is allowed to consume. Mark them required so the
2287    // compiler's DCE keeps the auto-passthrough output that
2288    // `extern <name>` produces. Without this, an iter var
2289    // referenced only from a deeper structure (e.g. a relevancy
2290    // `k:` field, or a downstream do-while condition) would be
2291    // pruned and pull-by-name would fail.
2292    for (var, val) in iteration_vars {
2293        scope.add_iteration_var(var, val);
2294        scope.add_required_output(var);
2295    }
2296
2297    // --- Step 3: Generate auto-externs ---
2298    //
2299    // Names referenced in op templates but not defined in the scope
2300    // need extern declarations to wire to the outer kernel.
2301    let defined = scope.defined_names();
2302    let extern_names = scope.extern_names();
2303
2304    // Collect all referenced names from op templates AND
2305    // binding source RHS. Names referenced in either need
2306    // extern declarations so the Polydat compile path can wire
2307    // them. Without scanning bindings, a phase whose binding
2308    // RHS uses `{outer_name}` (e.g. `dim := vector_dim(
2309    // "{dataset}:{profile}")`) wouldn't get extern declarations
2310    // for `dataset` and `profile`, leaving the Polydat string
2311    // interpolation desugar to fail at compile time.
2312    let mut referenced: HashSet<String> = HashSet::new();
2313    for op in ops {
2314        for value in op.op.values() {
2315            if let Some(s) = value.as_str() {
2316                for name in nmbrs_workload::bindpoints::referenced_bindings(s)? {
2317                    referenced.insert(name);
2318                }
2319            }
2320        }
2321        if let Some(ref cond) = op.condition {
2322            let bare = cond
2323                .trim()
2324                .strip_prefix('{')
2325                .and_then(|s| s.strip_suffix('}'))
2326                .unwrap_or(cond.trim());
2327            referenced.insert(bare.to_string());
2328        }
2329        // `delay:` accepts the same shapes as `if:` — a bare
2330        // wire name (`delay: think_time`) or a `{...}` inline
2331        // expression. Both consume a binding and need to land
2332        // in `referenced` so the auto-extern + DCE-keepalive
2333        // passes provision them.
2334        if let Some(ref delay_spec) = op.delay {
2335            for raw in delay_spec.names() {
2336                let bare = raw
2337                    .trim()
2338                    .strip_prefix('{')
2339                    .and_then(|s| s.strip_suffix('}'))
2340                    .unwrap_or(raw.trim());
2341                referenced.insert(bare.to_string());
2342            }
2343        }
2344        // Bindings: scan Polydat source for `{name}` placeholders
2345        // that the Polydat string-interpolation desugar will treat
2346        // as wire references.
2347        if let BindingsDef::PolydatSource(src) = &op.bindings {
2348            collect_string_interp_refs(src, &mut referenced);
2349            // Also scan for bare identifiers used in binding
2350            // RHSs (e.g. `if(optimize_for == "LATENCY", …)`).
2351            // Without this, names like `optimize_for` flow
2352            // through to the Polydat compiler unresolved and get
2353            // auto-externed at the compiler's default type
2354            // (u64); `materialize_wiring_from_outer` then writes the
2355            // parent's Str value into the u64-typed slot, and
2356            // a `__u64_to_string` adapter inserted by type
2357            // dispatch panics at runtime on `as_u64()`. The
2358            // local-binding filter below mirrors the
2359            // build_op_template_scope_kernel cascade — names
2360            // declared by THIS scope's own bindings are
2361            // resolved locally, not externed.
2362            let body_locally_declared = scan_locally_declared_idents(src);
2363            for ident in scan_idents_in_polydat_source(src) {
2364                if !body_locally_declared.contains(&ident) {
2365                    referenced.insert(ident);
2366                }
2367            }
2368        }
2369        // Op params (`evaluations:`/`relevancy:`/`verify:`/...
2370        // hoisted by the workload parser) carry `{name}` bind-
2371        // point references too — `relevancy: { k: "{k}" }` is
2372        // a real consumer of the wire `k`, even though `k`
2373        // isn't on the op-template wire path. Without scanning
2374        // these, an iter var referenced *only* from param
2375        // config would fail to auto-extern from the parent
2376        // manifest, and runtime `pull(name)` calls for that
2377        // wire (e.g. `parse_count_param` on relevancy `k:`)
2378        // would panic with "unknown output variate".
2379        let mut param_refs: Vec<String> = Vec::new();
2380        crate::bindings::collect_param_bindings_into(&op.params, &[], &mut param_refs)?;
2381        for name in param_refs {
2382            referenced.insert(name);
2383        }
2384    }
2385
2386    // Check for final shadowing violations
2387    for entry in outer_manifest {
2388        if entry.modifier == polydat::dsl::ast::BindingModifier::CONST
2389            && defined.contains(&entry.name)
2390        {
2391            return Err(format!(
2392                "cannot shadow 'final' binding '{}' from outer scope",
2393                entry.name
2394            ));
2395        }
2396    }
2397
2398    // SRD-13f §"Wire-reference classification" — case 3 (local
2399    // matter inclusion). When the parent program is available
2400    // (AST mode), promote non-final referenced names from
2401    // cascade-via-extern (case 2) to inline-as-Inherited.
2402    //
2403    // Rules:
2404    // - `final` / `shared` outputs stay cascaded (case 2-like
2405    //   for now; promoted-final optimization is a follow-up).
2406    // - Cycle bindings / init bindings whose body lives in the
2407    //   parent's retained AST get pretty-printed and ingested as
2408    //   Inherited. Transitive dependencies (RHS Ident refs)
2409    //   walk the same rule via `local_inclusion_chain`.
2410    // - Names defined by `extern` ports in the parent stay
2411    //   cascaded.
2412    //
2413    // The auto-extern loop below then runs as-is and fills the
2414    // gap for names that didn't have an AST body to pull in.
2415    if let Some(parent_kernel_ref) = parent_kernel {
2416        let parent_prog = parent_kernel_ref.program();
2417        // Propagate the parent's coordinate input names into this
2418        // scope when it doesn't already have an `input ...: u64`
2419        // declaration of its own. Without this, an included
2420        // binding like `trip := testkit_throw_at(cycle, threshold, ...)`
2421        // references `cycle` but the auto-extern loop emits
2422        // `extern cycle: u64` (extern, not coord); set_inputs
2423        // propagation then skips it and per-cycle ticking dies.
2424        //
2425        // Coord names are just wire names the parent declared as
2426        // inputs; the child propagates them by declaring the
2427        // same `input ...: u64` line. Nothing special about any
2428        // specific name here.
2429        if scope.coordinates.is_none() {
2430            let coord_count = parent_prog.coord_count();
2431            if coord_count > 0 {
2432                let input_names = parent_prog.input_names();
2433                let coords: Vec<String> = input_names.into_iter().take(coord_count).collect();
2434                scope.coordinates = Some(format_input_decl_line(&coords).trim_end().to_string());
2435            }
2436        }
2437
2438        // Names already accounted for: defined locally, declared
2439        // extern in subscope, or iter-vars. The inclusion-chain
2440        // walker uses this as its termination boundary so it
2441        // doesn't re-emit names the scope already satisfies.
2442        // (Coord input names like the one the workload author
2443        // declared via `input ...: u64` are not special — the
2444        // chain walker's `binding_ast_for` returns `None` for
2445        // coord inputs since they aren't binding statements, so
2446        // they self-terminate without explicit handling here.)
2447        let mut already_satisfied: HashSet<String> = HashSet::new();
2448        already_satisfied.extend(defined.iter().cloned());
2449        already_satisfied.extend(extern_names.iter().cloned());
2450        for var in iteration_vars.keys() {
2451            already_satisfied.insert(var.clone());
2452        }
2453
2454        // Sort for determinism — HashSet iteration is randomised.
2455        // Clone names so the loop body can mutate `referenced`
2456        // (collecting transitive refs from included bindings).
2457        let mut refs_sorted: Vec<String> = referenced.iter().cloned().collect();
2458        refs_sorted.sort();
2459        for name in &refs_sorted {
2460            let name = name.as_str();
2461            if already_satisfied.contains(name) {
2462                continue;
2463            }
2464            let manifest_modifier = outer_manifest
2465                .iter()
2466                .find(|e| e.name == name)
2467                .map(|e| e.modifier);
2468            let is_workload_param = workload_params.contains_key(name);
2469            if let Some(m) = manifest_modifier {
2470                use polydat::dsl::ast::BindingModifier;
2471                if m == BindingModifier::SHARED {
2472                    // SHARED stays in the cascade path — cells
2473                    // synchronise across kernels at runtime via
2474                    // SharedCell, not via const inlining.
2475                    continue;
2476                }
2477                if m == BindingModifier::CONST {
2478                    // SRD-13f §"Materialization gradient" — inline
2479                    // as `const NAME := <literal>` only when the
2480                    // upstream value is **statically known**. Per
2481                    // SRD-11 §"Two Evaluation Lifecycles", the
2482                    // `const` modifier has two implementation
2483                    // paths: compile-fold (the producing node is
2484                    // replaced with a leaf const node, value is
2485                    // part of the compiled artifact and identical
2486                    // across every activation) vs. scope-init pull
2487                    // (when the binding's wire chain touches
2488                    // iteration externs, the producing node stays
2489                    // as the original computation node; the value
2490                    // is computed per scope activation and lives
2491                    // only for that activation per SRD-13c
2492                    // §"const").
2493                    //
2494                    // The cascaded source built here gets compiled
2495                    // and cached on the phase scope-tree node, so
2496                    // its lifetime is the workload run — longer
2497                    // than any single activation. Inlining a
2498                    // scope-init-pulled value would freeze the
2499                    // first activation's value into the cached
2500                    // program forever, breaking every subsequent
2501                    // iteration of an enclosing comprehension
2502                    // (the symptom: `const mode := sm` inside a
2503                    // `for_each sm in alpha, beta` reads `alpha`
2504                    // for both iters).
2505                    //
2506                    // SRD-11 §"Provenance-Based Invalidation"
2507                    // gives the discriminator at zero cost: a
2508                    // truly statically-known node has empty input
2509                    // provenance (it depends on no graph inputs);
2510                    // a passthrough or computation node has bits
2511                    // set for the input slots it reads. We inline
2512                    // only when provenance is empty; otherwise we
2513                    // fall through to the auto-extern cascade
2514                    // below so each activation re-pulls the value
2515                    // through the chain via
2516                    // `materialize_wiring_from_outer` Step 3.
2517                    let statically_known = parent_kernel_ref
2518                        .program()
2519                        .output_index(name)
2520                        .map(|out_idx| {
2521                            let (node_idx, _) =
2522                                parent_kernel_ref.program().resolve_output_by_index(out_idx);
2523                            parent_kernel_ref
2524                                .program()
2525                                .input_provenance_for(node_idx)
2526                                .is_none_or(|p| p.is_zero())
2527                        })
2528                        .unwrap_or(true);
2529                    if statically_known
2530                        && let Some(value) = parent_kernel_ref.lookup(name)
2531                        && let Some(natural) = value_to_param_string(&value)
2532                    {
2533                        scope.add_param_binding(name, &natural);
2534                        already_satisfied.insert(name.to_string());
2535                        continue;
2536                    }
2537                    continue;
2538                }
2539            }
2540            // SRD-21 §"Where workload-param values live in the
2541            // kernel chain" — workload params are stable for the
2542            // run but live in the params-kernel as folded
2543            // constants, not in the workload-root program itself.
2544            // `parent_kernel.lookup(name)` reads through the
2545            // chain-wired input slot value, so this promotion
2546            // gives us const-folded workload-param values inside
2547            // every descendant scope's program — same
2548            // effective semantics as the pre-SRD-21 design
2549            // without poisoning the workload-root with `final`
2550            // constants that would block scenario-tree
2551            // shadowing.
2552            if is_workload_param
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            // Pull the inclusion chain. If the name isn't in the
2561            // parent's AST (or it's a final/shared binding in
2562            // the AST), the chain is empty — the auto-extern
2563            // loop below handles those.
2564            let chain = parent_prog.local_inclusion_chain(name, &already_satisfied);
2565            if chain.is_empty() {
2566                continue;
2567            }
2568            // Pretty-print each Statement in topological order
2569            // and ingest as Inherited. Track bound names so the
2570            // chain walker and the auto-extern loop see them
2571            // satisfied locally. Walk each binding's RHS to
2572            // collect transitive refs into `referenced` — these
2573            // are the names the included binding's expression
2574            // mentions but doesn't define (e.g. parent `final`
2575            // values like `dataset`); the auto-extern loop below
2576            // then emits externs for them.
2577            for stmt in chain {
2578                let line = polydat::dsl::pprint::pp_statement(stmt);
2579                scope.ingest_polydat_source(&line, BindingOrigin::Inherited);
2580                let body = match stmt {
2581                    polydat::dsl::ast::Statement::Binding(b) => Some(&b.value),
2582                    _ => None,
2583                };
2584                if let Some(expr) = body {
2585                    polydat::dsl::collect_expr_references(expr, &mut referenced);
2586                }
2587                if let polydat::dsl::ast::Statement::Binding(b) = stmt {
2588                    for t in &b.targets {
2589                        already_satisfied.insert(t.clone());
2590                    }
2591                }
2592            }
2593        }
2594    }
2595
2596    // Refresh `defined` set after AST-mode inclusion may have
2597    // added Inherited bindings. The auto-extern loop below uses
2598    // this updated set to skip names now satisfied locally.
2599    let defined = scope.defined_names();
2600
2601    // Generate extern declarations for referenced-but-undefined names
2602    for entry in outer_manifest {
2603        let is_iter_var = iteration_vars.contains_key(&entry.name);
2604        if referenced.contains(&entry.name)
2605            && !defined.contains(&entry.name)
2606            && !extern_names.contains(&entry.name)
2607            && !is_iter_var
2608        {
2609            scope.add_extern(&entry.name, entry.port_type);
2610        }
2611    }
2612
2613    // SRD-13f §"Wire-reference classification" — case 4:
2614    // unresolved → synthesizer-level validation error. Fires
2615    // only on descendant scopes (parent_kernel is Some). The
2616    // workload-root build skips this check; the Polydat compiler's
2617    // auto-input-inference path handles unresolved refs there.
2618    //
2619    // A reference is resolved if any of: defined locally,
2620    // declared extern (in subscope or auto-extern'd from outer
2621    // manifest), an iteration variable, a workload param key,
2622    // a coord name on this scope, or in the outer manifest at
2623    // all. Anything else is a typo or missing upstream binding.
2624    if parent_kernel.is_some() {
2625        let defined_now = scope.defined_names();
2626        let extern_now = scope.extern_names();
2627        let mut satisfied: HashSet<String> = HashSet::new();
2628        satisfied.extend(defined_now);
2629        satisfied.extend(extern_now);
2630        for var in iteration_vars.keys() {
2631            satisfied.insert(var.clone());
2632        }
2633        for name in workload_params.keys() {
2634            satisfied.insert(name.clone());
2635        }
2636        for entry in outer_manifest {
2637            satisfied.insert(entry.name.clone());
2638        }
2639        // Coord names from this scope's `input ...: u64` line.
2640        if let Some(coords_line) = &scope.coordinates
2641            && let Some(rhs) = coords_line.split(":=").nth(1)
2642        {
2643            let inner = rhs.trim().trim_start_matches('(').trim_end_matches(')');
2644            for n in inner.split(',') {
2645                let n = n.trim();
2646                if !n.is_empty() {
2647                    satisfied.insert(n.to_string());
2648                }
2649            }
2650        }
2651        // `referenced` is built from a textual scan that catches
2652        // both wire refs and bare identifiers — including GK
2653        // function names like `mod`, `hash`, `range` that
2654        // appear in binding RHS as call heads. Filter those out
2655        // via `lookup`, which also answers for an overloaded
2656        // name such as `vec_dot`; only true wire references
2657        // should surface as unresolved.
2658        let mut unresolved: Vec<&String> = referenced
2659            .iter()
2660            .filter(|n| !satisfied.contains(n.as_str()))
2661            // Dotted names follow the field-access wire
2662            // convention (`q.cursor.idx` reads the wire
2663            // `q__cursor__idx`) — check the flattened spelling
2664            // the same way kernel lookup does.
2665            .filter(|n| !n.contains('.') || !satisfied.contains(n.replace('.', "__").as_str()))
2666            .filter(|n| !n.starts_with("__"))
2667            .filter(|n| polydat::dsl::registry::lookup(n).is_none())
2668            .collect();
2669        unresolved.sort();
2670        if !unresolved.is_empty() {
2671            let names: Vec<&str> = unresolved.iter().map(|s| s.as_str()).collect();
2672            let mut visible: Vec<&str> = satisfied.iter().map(|s| s.as_str()).collect();
2673            visible.sort();
2674            return Err(format!(
2675                "unresolved wire reference(s) {names:?}: not declared locally, \
2676                 not in parent manifest, not a workload param. \
2677                 Visible names in this scope: {visible:?}"
2678            ));
2679        }
2680    }
2681
2682    // --- Step 4: Workload param cascade as extern slots ---
2683    //
2684    // Workload params are not the workload-root's authority — the
2685    // params-kernel sits one level above this scope and owns the
2686    // `const NAME := <literal>` declarations. The workload-root
2687    // program declares each param as `extern NAME: T`, and the
2688    // materialize-wiring-from-outer step at kernel construction
2689    // time copies the value out of the params-kernel's output
2690    // into this scope's input slot. Lookup for a param at the
2691    // workload-root then resolves via the input slot rather than
2692    // an own-folded constant — which is precisely what makes a
2693    // SetParam scope-tree node inserted between params-kernel
2694    // and workload-root able to shadow the value: its own
2695    // `const NAME := <override>` becomes the closer
2696    // materialize-source. If we baked `const NAME := <literal>`
2697    // here at the workload-root, that local constant would mask
2698    // the input slot via the get_constant fast-path in
2699    // PolydatKernel::lookup, and no scope-tree-level shadow could
2700    // get through.
2701    //
2702    // Author-declared `final` in the workload's `bindings:`
2703    // block is unaffected — that source goes through
2704    // workload_level_polydat ingestion in build_workload_root_kernel
2705    // and keeps whatever modifier the author wrote. Only the
2706    // auto-cascade of the workload `params:` block changes
2707    // shape.
2708    //
2709    // Phase-level build_scope callers pass an empty
2710    // `workload_params`; their workload params arrive via the
2711    // parent-scope kernel's manifest auto-extern pass.
2712    //
2713    // SRD-13f Push D: sort by name so program build order is
2714    // deterministic across processes. HashMap iteration is
2715    // randomized per process (Rust default hasher).
2716    let defined = scope.defined_names(); // refresh after externs
2717    let mut params_sorted: Vec<(&String, &String)> = workload_params.iter().collect();
2718    params_sorted.sort_by(|a, b| a.0.cmp(b.0));
2719    for (name, value) in params_sorted {
2720        if defined.contains(name) {
2721            // Author already declared `name` in the workload's
2722            // own bindings block. Honor the author's declaration
2723            // (it carries whatever modifier they wrote) and skip
2724            // the auto-extern — declaring an extern with the
2725            // same name as a local binding would be a compile
2726            // error.
2727            continue;
2728        }
2729        scope.add_extern(name, workload_param_port_type(value));
2730        // Mark as required so DCE keeps the auto-passthrough
2731        // output. Descendant scopes auto-extern the param via
2732        // the workload-root manifest; if the workload-root's
2733        // own program prunes the param away, that cascade
2734        // breaks.
2735        scope.add_required_output(name);
2736    }
2737    // Also check phase config values for param refs
2738    for phase in phases.values() {
2739        if let Some(ref c) = phase.cycles
2740            && c.starts_with('{')
2741            && c.ends_with('}')
2742        {
2743            let name = &c[1..c.len() - 1];
2744            if workload_params.contains_key(name) && !scope.defined_names().contains(name) {
2745                scope.add_param_binding(name, &workload_params[name]);
2746            }
2747        }
2748    }
2749
2750    // --- Step 5: Inline expression extraction ---
2751    //
2752    // {{expr}} in op templates becomes __expr_N bindings.
2753    // (Note: the op template rewriting happens separately in the caller
2754    // since it mutates op fields, not the scope.)
2755    let mut inline_idx = 0usize;
2756    let mut expr_to_name: HashMap<String, String> = HashMap::new();
2757    let mut collect = |s: &str| -> Result<(), String> {
2758        for bp in nmbrs_workload::bindpoints::extract_bind_points(s)? {
2759            if let nmbrs_workload::bindpoints::BindPoint::InlineDefinition(ref expr) = bp
2760                && !expr_to_name.contains_key(expr)
2761            {
2762                let name = format!("__expr_{inline_idx}");
2763                inline_idx += 1;
2764                expr_to_name.insert(expr.clone(), name);
2765            }
2766        }
2767        Ok(())
2768    };
2769    for op in ops {
2770        for value in op.op.values() {
2771            if let Some(s) = value.as_str() {
2772                collect(s)?;
2773            }
2774        }
2775        // Inline expressions in `if:` and `delay:` count too —
2776        // those get hoisted out of `op.op` by the parser into
2777        // dedicated fields on `ParsedOp`.
2778        if let Some(s) = &op.condition {
2779            collect(s)?;
2780        }
2781        if let Some(spec) = &op.delay {
2782            for name in spec.names() {
2783                collect(name)?;
2784            }
2785        }
2786    }
2787    for (expr, name) in &expr_to_name {
2788        scope.add_inline_expr(name, expr);
2789    }
2790
2791    // --- Step 6: Collect required outputs ---
2792    for op in ops {
2793        for value in op.op.values() {
2794            if let Some(s) = value.as_str() {
2795                for name in nmbrs_workload::bindpoints::referenced_bindings(s)? {
2796                    if !exclude.contains(&name) {
2797                        scope.add_required_output(&name);
2798                    }
2799                }
2800            }
2801        }
2802        // Required-output collection for `if:` and `delay:`.
2803        //
2804        // The condition / delay value may be one of:
2805        //   1. `{{expr}}` — inline expression. Step 5 above
2806        //      synthesised a `__expr_N := expr` binding; the
2807        //      required output is that synthesised name.
2808        //   2. `{name}` — a single-brace binding reference.
2809        //   3. A bare identifier — legacy "name a binding"
2810        //      form, no braces.
2811        // The previous strip-one-pair-of-braces logic only
2812        // handled forms 2 and 3; for `{{expr}}` it produced a
2813        // half-stripped string `{expr}` that didn't match any
2814        // binding and let DCE drop the synthesised
2815        // `__expr_N`. Walk through `extract_bind_points` so
2816        // every form resolves to the right output name.
2817        let mut collect_required = |s: &str| -> Result<(), String> {
2818            let trimmed = s.trim();
2819            // Bracketed forms: `{{expr}}`, `{:=expr:=}`,
2820            // `{name}`, `{expr-with-operators}`.
2821            let bps = nmbrs_workload::bindpoints::extract_bind_points(trimmed)?;
2822            if !bps.is_empty() {
2823                for bp in bps {
2824                    match bp {
2825                        nmbrs_workload::bindpoints::BindPoint::InlineDefinition(expr) => {
2826                            if let Some(name) = expr_to_name.get(&expr)
2827                                && !exclude.contains(name)
2828                            {
2829                                scope.add_required_output(name);
2830                            }
2831                        }
2832                        nmbrs_workload::bindpoints::BindPoint::Reference { name, .. } => {
2833                            if !exclude.contains(&name) {
2834                                scope.add_required_output(&name);
2835                            }
2836                        }
2837                    }
2838                }
2839                return Ok(());
2840            }
2841            // Bare-identifier form (no braces) — legacy.
2842            if !trimmed.is_empty() && !exclude.contains(&trimmed.to_string()) {
2843                scope.add_required_output(trimmed);
2844            }
2845            Ok(())
2846        };
2847        if let Some(ref cond) = op.condition {
2848            collect_required(cond)?;
2849        }
2850        if let Some(ref delay_spec) = op.delay {
2851            for name in delay_spec.names() {
2852                collect_required(name)?;
2853            }
2854        }
2855        // SRD-40b §6: synthetic-metric `value:` references must
2856        // survive DCE so the dispenser's Polydat pull plan can resolve
2857        // them. Bare-name values (the SRD-40b §1 canonical form)
2858        // refer to a wire produced somewhere in scope; non-bare
2859        // expressions are deferred to Phase 9 elsewhere — for the
2860        // bare-name case we mark the wire required.
2861        for spec in op.metrics.values() {
2862            let trimmed = spec.value.trim();
2863            let bare =
2864                !trimmed.is_empty() && trimmed.chars().all(|c| c.is_alphanumeric() || c == '_');
2865            if bare && !exclude.contains(&trimmed.to_string()) {
2866                scope.add_required_output(trimmed);
2867            }
2868        }
2869        // SRD-40b §5 result-as-GK: each `result:` wire reads a
2870        // path expression off the response body and exposes it as
2871        // a Polydat wire. The wire's *name* is what subsequent
2872        // wrappers (metrics, validation) pull against — mark each
2873        // declared result wire as required so the kernel exposes
2874        // an extern slot for it on the post-execute write path.
2875        // SRD-66: result-wire names are already declared as
2876        // wires through the op's `bindings:` block (when the
2877        // workload uses `extern X: T` for shared-cell writes)
2878        // or are independent of the op-template kernel (when
2879        // the wire is consumed only by the result dispenser's
2880        // capture map). Marking them as required outputs here
2881        // would double-declare the `__port_*` for any name
2882        // that's also an extern, so the kernel-synthesis-side
2883        // wiring is left to Push 2's full kernel-driven path
2884        // (the SRD-66 §"Compilation lifecycle" closure-binding
2885        // rule). This branch intentionally does nothing for now.
2886        let _ = op.result.as_ref();
2887        crate::bindings::collect_param_bindings_into(
2888            &op.params,
2889            exclude,
2890            &mut scope.required_outputs,
2891        )?;
2892    }
2893
2894    // Config refs (from cycles={expr})
2895    if let Some(cycles_spec) = phase_cycles
2896        && cycles_spec.starts_with('{')
2897        && cycles_spec.ends_with('}')
2898    {
2899        let mut inner = cycles_spec[1..cycles_spec.len() - 1].to_string();
2900        for (v, val) in iteration_vars {
2901            inner = inner.replace(&format!("{{{v}}}"), val);
2902        }
2903        inner = crate::runner::expand_workload_params(&inner, workload_params);
2904        scope.add_config_ref(&inner);
2905    }
2906
2907    Ok(scope)
2908}
2909
2910/// Apply iteration-variable substitution to *op-template
2911/// strings only* — `raw:`, `prepared:`, `stmt:`, etc.
2912///
2913/// Iter vars flow into Polydat binding source as wires (declared as
2914/// externs by `BindingScope::add_iteration_var` and bound at
2915/// runtime via the standard input mechanism), so this helper
2916/// **does not** touch `op.bindings`. It only rewrites the
2917/// op-template field values, where `{var}` placeholders refer
2918/// to structural elements (table names, keyspace names,
2919/// optimize-for hints) that adapters need as literal text —
2920/// not as bind variables. CQL's `prepared:` form, for example,
2921/// converts every remaining `{name}` in the statement to a `?`
2922/// bind marker; iter vars in structural positions (`INSERT
2923/// INTO ks.{table} ...`) must be substituted away before that
2924/// conversion runs, since CQL doesn't permit `?` for table
2925/// names.
2926/// SRD-68 Push 5c — validate-only walk. Covers the same
2927/// placeholders as the substitution described above but DOES NOT
2928/// mutate the op strings. Walks every `{name}` placeholder in the ops' op fields
2929/// and op-level params, accumulating diagnostics for unresolved
2930/// references; returns `Result<(), String>` describing any
2931/// unresolved bindpoints.
2932///
2933/// Used at phase activation as the single workload-load-time
2934/// validation step. Adapters now do their own cycle-time
2935/// resolution (CQL: construction-time structural via
2936/// `canonical_kernel.lookup` + cycle-time per-cycle via
2937/// `WireSource::get`; non-CQL: cycle-time via
2938/// `synthesis::resolve_cached →
2939/// substitute_bind_points_with_state` against `main_kernel`).
2940/// Mutation of the workload model is no longer load-bearing —
2941/// only the diagnostic surface is.
2942///
2943/// `enclosing` are the programs of the scopes around the phase — the
2944/// current parent and every installed ancestor. A name one of them
2945/// BINDS (a per-cycle workload or scenario binding, not a folded
2946/// constant) resolves nowhere now, yet the phase scope pulls its
2947/// binding in as local matter (`local_inclusion_chain`, SRD-13f case
2948/// 3), so it is per-cycle here exactly like a phase-declared one.
2949pub fn validate_placeholders_via_kernel(
2950    ops: &[ParsedOp],
2951    kernel: &dyn polydat::Kernel,
2952    enclosing: &[&polydat::kernel::PolydatProgram],
2953) -> Result<(), String> {
2954    let mut per_cycle_names = collect_phase_binding_lhs_names(ops);
2955    let nothing_excluded = HashSet::new();
2956    for name in collect_op_placeholder_names(ops)? {
2957        if !per_cycle_names.contains(&name)
2958            && enclosing.iter().any(|program| {
2959                !program
2960                    .local_inclusion_chain(&name, &nothing_excluded)
2961                    .is_empty()
2962            })
2963        {
2964            per_cycle_names.push(name);
2965        }
2966    }
2967
2968    let mut errors: Vec<String> = Vec::new();
2969    let in_scope = || -> Vec<String> {
2970        let mut names: Vec<String> = kernel.output_names();
2971        for n in kernel.input_names() {
2972            if !names.contains(&n) {
2973                names.push(n);
2974            }
2975        }
2976        names.sort();
2977        names
2978    };
2979    for op in ops.iter() {
2980        let op_name = op.name.clone();
2981        for (key, value) in op.op.iter() {
2982            let path = format!("op '{op_name}' field '{key}'");
2983            // Clone-then-discard: `resolve_placeholders_in_json`
2984            // requires `&mut serde_json::Value` but we don't
2985            // care about its mutations — only the `errors` it
2986            // accumulates. The clone is shallow per JSON value
2987            // and runs once per field at workload-load time.
2988            let mut throwaway = value.clone();
2989            resolve_placeholders_in_json(
2990                &mut throwaway,
2991                kernel,
2992                &per_cycle_names,
2993                &path,
2994                &mut errors,
2995            );
2996        }
2997        for (key, value) in op.params.iter() {
2998            if key == "gutter" {
2999                continue; // runtime-resolved templates (see the mutable pass below)
3000            }
3001            let path = format!("op '{op_name}' param '{key}'");
3002            let mut throwaway = value.clone();
3003            resolve_placeholders_in_json(
3004                &mut throwaway,
3005                kernel,
3006                &per_cycle_names,
3007                &path,
3008                &mut errors,
3009            );
3010        }
3011    }
3012
3013    if errors.is_empty() {
3014        return Ok(());
3015    }
3016    let in_scope_str = in_scope().join(", ");
3017    let mut out =
3018        String::from("placeholder resolution failed (single read path: Polydat Kernel lookup):\n");
3019    for e in &errors {
3020        out.push_str("  - ");
3021        out.push_str(e);
3022        out.push('\n');
3023    }
3024    out.push_str(&format!(
3025        "  in-scope names at this kernel: [{in_scope_str}]"
3026    ));
3027    Err(out)
3028}
3029
3030/// SRD-68 Push 5c — resolve `{name}` placeholders in a single
3031/// op's `params` against `kernel`. Used by validation wrappers
3032/// at construction time to pre-resolve config like `relevancy.k`
3033/// = `"{k}"` against their dispenser's canonical kernel, so the
3034/// downstream spec parsers see a literal value (`10`) rather
3035/// than a surviving placeholder string.
3036///
3037/// Per-cycle binding LHS names pass through unchanged — the
3038/// wrapper resolves those via wires at cycle time (e.g.
3039/// `relevancy.expected = "{ground_truth}"` stays as-is so the
3040/// wrapper can register it on the fixture's pull plan and
3041/// read it per cycle).
3042///
3043/// Single-op variant of the legacy bulk-mutation pass; the
3044/// per-template granularity lets each wrapper resolve against
3045/// its own dispenser's canonical kernel rather than a shared
3046/// activity-layer parent.
3047pub fn resolve_placeholders_in_op_params(
3048    op: &mut ParsedOp,
3049    kernel: &dyn polydat::Kernel,
3050) -> Result<(), String> {
3051    let per_cycle_names = collect_phase_binding_lhs_names(std::slice::from_ref(op));
3052
3053    let mut errors: Vec<String> = Vec::new();
3054    let in_scope = || -> Vec<String> {
3055        let mut names: Vec<String> = kernel.output_names();
3056        for n in kernel.input_names() {
3057            if !names.contains(&n) {
3058                names.push(n);
3059            }
3060        }
3061        names.sort();
3062        names
3063    };
3064    let op_name = op.name.clone();
3065    for (key, value) in op.params.iter_mut() {
3066        // `gutter:` templates resolve at RUNTIME — during-forms per op
3067        // completion on the fiber wires, `final:` at phase end with a
3068        // status-metric fallback (`{recall}`, `{latency_p50}`) that has
3069        // no kernel presence here. Unresolved names degrade to visible
3070        // literal text in the cell, so the strict pre-resolution pass
3071        // must not reject them.
3072        if key == "gutter" {
3073            continue;
3074        }
3075        let path = format!("op '{op_name}' param '{key}'");
3076        resolve_placeholders_in_json(value, kernel, &per_cycle_names, &path, &mut errors);
3077    }
3078    if errors.is_empty() {
3079        return Ok(());
3080    }
3081    let in_scope_str = in_scope().join(", ");
3082    let mut out = String::from("param-placeholder resolution failed:\n");
3083    for e in &errors {
3084        out.push_str("  - ");
3085        out.push_str(e);
3086        out.push('\n');
3087    }
3088    out.push_str(&format!(
3089        "  in-scope names at this kernel: [{in_scope_str}]"
3090    ));
3091    Err(out)
3092}
3093
3094// SRD-68 Push 5 cleanup: the legacy
3095// `resolve_placeholders_via_kernel` (op-field text mutation) and
3096// `resolve_placeholders_in_params_only` (bulk op-params mutation)
3097// are both retired. The executor calls
3098// [`validate_placeholders_via_kernel`] (pure walker) at workload
3099// load to surface unresolved-bindpoint diagnostics; adapters
3100// resolve op-field placeholders themselves at construction (CQL
3101// prepared via `resolve_structural_and_mark_remaining`) or at
3102// cycle time (CQL raw via `substitute_via_wires`); validation
3103// wrappers resolve their own op.params at construction via
3104// [`resolve_placeholders_in_op_params`] against the dispenser's
3105// own canonical kernel. The workload model is no longer mutated
3106// — `OpDispenser::describe()` returns pristine yaml.
3107
3108/// Scan `ops`' `bindings:` text for the LHS names that get
3109/// produced as per-cycle wires. The scan is intentionally
3110/// liberal (LHS can be `cursor q = …`, `init x = …`, `name :=
3111/// expr`, `extern n: type`, `const n := expr`, `shared n := expr`,
3112/// destructured `(a, b) := …`). Anything that survives the LHS
3113/// strip becomes a known name; the substitution path uses this
3114/// set to distinguish "per-cycle wire — leave for the dispenser"
3115/// from "typo or missing cascade — error."
3116/// Every `{name}` placeholder the ops' fields and params reference.
3117/// Fails on a malformed bind point.
3118fn collect_op_placeholder_names(ops: &[ParsedOp]) -> Result<Vec<String>, String> {
3119    fn walk(value: &serde_json::Value, out: &mut Vec<String>) -> Result<(), String> {
3120        match value {
3121            serde_json::Value::String(s) => {
3122                for name in nmbrs_workload::bindpoints::referenced_bindings(s)? {
3123                    if !out.contains(&name) {
3124                        out.push(name);
3125                    }
3126                }
3127                Ok(())
3128            }
3129            serde_json::Value::Array(items) => items.iter().try_for_each(|v| walk(v, out)),
3130            serde_json::Value::Object(map) => map.values().try_for_each(|v| walk(v, out)),
3131            _ => Ok(()),
3132        }
3133    }
3134    let mut out = Vec::new();
3135    for op in ops {
3136        op.op
3137            .values()
3138            .chain(op.params.values())
3139            .try_for_each(|v| walk(v, &mut out))
3140            .map_err(|e| format!("op '{}': {e}", op.name))?;
3141    }
3142    Ok(out)
3143}
3144
3145fn collect_phase_binding_lhs_names(ops: &[ParsedOp]) -> Vec<String> {
3146    let mut out: Vec<String> = Vec::new();
3147    for op in ops {
3148        if let BindingsDef::PolydatSource(src) = &op.bindings {
3149            for line in logical_lines(src) {
3150                let trimmed = line.trim();
3151                if trimmed.is_empty() || trimmed.starts_with('#') {
3152                    continue;
3153                }
3154                // `input` declarations declare per-cycle wire names
3155                // by definition — the runtime sets them per
3156                // iteration. Both surface forms are handled:
3157                //   input cycle: u64
3158                //   input (cycle: u64, q: f64)
3159                // Without this, `{cycle}` in op templates would
3160                // resolve at compile time against the kernel's
3161                // initial value (0) instead of being deferred to
3162                // per-iteration substitution.
3163                if let Some(rest) = trimmed.strip_prefix("input ") {
3164                    let rest = rest.trim();
3165                    if let Some(inner) = rest.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
3166                        for piece in inner.split(',') {
3167                            let n = piece.trim().split(':').next().unwrap_or("").trim();
3168                            if is_bare_ident(n) && !out.contains(&n.to_string()) {
3169                                out.push(n.to_string());
3170                            }
3171                        }
3172                    } else {
3173                        let n = rest.split(':').next().unwrap_or("").trim();
3174                        if is_bare_ident(n) && !out.contains(&n.to_string()) {
3175                            out.push(n.to_string());
3176                        }
3177                    }
3178                    continue;
3179                }
3180                let lhs_end = trimmed
3181                    .find(":=")
3182                    .or_else(|| trimmed.find('='))
3183                    .unwrap_or(trimmed.len());
3184                let mut lhs = &trimmed[..lhs_end];
3185                // Strip ALL leading wire-coloring modifiers in
3186                // any order. `volatile final` and `final shared`
3187                // both need their bare name extracted, and any
3188                // future modifier added to the SRD-10 set must
3189                // appear here too.
3190                loop {
3191                    let mut matched = false;
3192                    for prefix in [
3193                        "cursor ",
3194                        "init ",
3195                        "extern ",
3196                        "const ",
3197                        "final ",
3198                        "shared ",
3199                        "volatile ",
3200                        "private ",
3201                    ] {
3202                        if let Some(stripped) = lhs.strip_prefix(prefix) {
3203                            lhs = stripped.trim();
3204                            matched = true;
3205                            break;
3206                        }
3207                    }
3208                    if !matched {
3209                        break;
3210                    }
3211                }
3212                let lhs = lhs.trim();
3213                // Destructured tuple LHS: (a, b, c) := ...
3214                if let Some(inner) = lhs.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
3215                    for piece in inner.split(',') {
3216                        let n = piece.trim().trim_end_matches(':').trim();
3217                        if is_bare_ident(n) && !out.contains(&n.to_string()) {
3218                            out.push(n.to_string());
3219                        }
3220                    }
3221                    continue;
3222                }
3223                // Type-annotated single LHS: `name: type`.
3224                let bare = lhs.split(':').next().unwrap_or(lhs).trim();
3225                if is_bare_ident(bare) && !out.contains(&bare.to_string()) {
3226                    out.push(bare.to_string());
3227                }
3228            }
3229        }
3230    }
3231    out
3232}
3233
3234fn is_bare_ident(s: &str) -> bool {
3235    let mut chars = s.chars();
3236    match chars.next() {
3237        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
3238        _ => return false,
3239    }
3240    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
3241}
3242
3243/// True iff `s` is a polydat string literal — opens with `"`,
3244/// closes with `"`, and (conservatively) contains no
3245/// unescaped closing quote in the middle. This is the shape
3246/// `format_jval_as_polydat_literal` produces for YAML strings
3247/// (`"hello"`) so the param-binding classifier can pass it
3248/// through without re-quoting.
3249fn is_polydat_quoted_string(s: &str) -> bool {
3250    if s.len() < 2 {
3251        return false;
3252    }
3253    if !s.starts_with('"') || !s.ends_with('"') {
3254        return false;
3255    }
3256    // Walk the inner span; reject if we find an unescaped `"`
3257    // before the final character (which would mean the outer
3258    // quotes don't actually pair).
3259    let bytes = s.as_bytes();
3260    let mut i = 1;
3261    let last = bytes.len() - 1;
3262    while i < last {
3263        if bytes[i] == b'\\' {
3264            i += 2;
3265            continue;
3266        }
3267        if bytes[i] == b'"' {
3268            return false;
3269        }
3270        i += 1;
3271    }
3272    true
3273}
3274
3275/// True iff `s` looks like a polydat array literal: `[` …
3276/// matched brackets … `]`. Conservative — we don't validate
3277/// the elements here; the polydat parser handles that when
3278/// the `const X := [...]` line compiles. The check just
3279/// distinguishes "this is already polydat array syntax" from
3280/// "this is a raw string that happens to contain brackets".
3281fn is_polydat_array_literal(s: &str) -> bool {
3282    if !s.starts_with('[') || !s.ends_with(']') {
3283        return false;
3284    }
3285    let mut depth: i32 = 0;
3286    let mut in_string = false;
3287    let mut escape = false;
3288    for c in s.chars() {
3289        if escape {
3290            escape = false;
3291            continue;
3292        }
3293        if in_string {
3294            if c == '\\' {
3295                escape = true;
3296            } else if c == '"' {
3297                in_string = false;
3298            }
3299            continue;
3300        }
3301        match c {
3302            '"' => in_string = true,
3303            '[' => depth += 1,
3304            ']' => {
3305                depth -= 1;
3306                if depth < 0 {
3307                    return false;
3308                }
3309            }
3310            _ => {}
3311        }
3312    }
3313    depth == 0
3314}
3315
3316#[cfg(test)]
3317mod polydat_param_classifier_tests {
3318    use super::*;
3319
3320    #[test]
3321    fn scan_idents_skips_hash_comments() {
3322        // `#` is a YAML-style line comment in Polydat (dsl/lexer.rs).
3323        // The ident scanner must skip it too, or comment words leak in
3324        // as phantom wire references (regression: finalize_index's
3325        // bindings comments).
3326        let src = "# Forwarding bindings: allow-list = bindings + params\n\
3327                   pct := mul(active, 2)  # trailing comment with words\n";
3328        let idents = scan_idents_in_polydat_source(src);
3329        assert!(
3330            idents.contains("active"),
3331            "real ident must be found: {idents:?}"
3332        );
3333        for word in [
3334            "Forwarding",
3335            "bindings",
3336            "allow",
3337            "list",
3338            "params",
3339            "trailing",
3340            "comment",
3341            "words",
3342        ] {
3343            assert!(
3344                !idents.contains(word),
3345                "comment word '{word}' must not be scanned as a wire ref: {idents:?}"
3346            );
3347        }
3348    }
3349
3350    #[test]
3351    fn scan_idents_skips_block_conditional_keywords() {
3352        // Block-form conditional selection puts bare `if` / `else` in expression
3353        // position. This scanner is textual, so without the keyword entries they were
3354        // emitted as wire references and the phase failed with
3355        // `unresolved wire reference(s) ["else", "if"]` (regression: finalize_index's
3356        // seg_mib_mean binding).
3357        let src = "seg_mib_mean := if segments > 0 { total / max(segments, 1) } else { 0 }\n";
3358        let idents = scan_idents_in_polydat_source(src);
3359        assert!(
3360            idents.contains("segments"),
3361            "real wire must still be found: {idents:?}"
3362        );
3363        assert!(
3364            idents.contains("total"),
3365            "real wire must still be found: {idents:?}"
3366        );
3367        for kw in ["if", "else"] {
3368            assert!(
3369                !idents.contains(kw),
3370                "conditional keyword '{kw}' must not scan as a wire ref: {idents:?}"
3371            );
3372        }
3373    }
3374
3375    #[test]
3376    fn scan_locally_declared_skips_hash_comment_lines() {
3377        let src = "# total = sum of parts\n\
3378                   shared sstables := 0\n";
3379        let decls = scan_locally_declared_idents(src);
3380        assert!(decls.contains("sstables"));
3381        // `# total = ...` has an `=`; it must not be parsed as a decl.
3382        assert!(
3383            !decls.contains("total"),
3384            "comment LHS must not declare: {decls:?}"
3385        );
3386    }
3387
3388    #[test]
3389    fn bare_identifier_classifier_accepts_idents_and_rejects_other_shapes() {
3390        assert!(is_bare_ident("sm"));
3391        assert!(is_bare_ident("source_model"));
3392        assert!(is_bare_ident("k_values"));
3393        assert!(is_bare_ident("_underscore"));
3394        assert!(is_bare_ident("a1"));
3395        // Rejects strings that don't fit the ident grammar.
3396        assert!(!is_bare_ident(""));
3397        assert!(!is_bare_ident("1abc"), "ident can't start with digit");
3398        assert!(!is_bare_ident("foo bar"), "no spaces");
3399        assert!(!is_bare_ident("[a, b]"));
3400        assert!(!is_bare_ident("\"quoted\""));
3401        assert!(!is_bare_ident("foo+bar"));
3402        // Reserved-ish keywords stay valid as identifiers here;
3403        // the polydat parser is the authority on what's
3404        // reserved.
3405        assert!(is_bare_ident("true"));
3406        assert!(is_bare_ident("false"));
3407    }
3408
3409    #[test]
3410    fn polydat_quoted_string_accepts_paired_quotes_only() {
3411        assert!(is_polydat_quoted_string("\"hello\""));
3412        assert!(is_polydat_quoted_string("\"\""));
3413        assert!(is_polydat_quoted_string("\"with \\\"escaped\\\" inner\""));
3414        // Rejects shapes that aren't paired-quote.
3415        assert!(!is_polydat_quoted_string("hello"));
3416        assert!(!is_polydat_quoted_string("\"open-only"));
3417        assert!(!is_polydat_quoted_string("close-only\""));
3418        assert!(!is_polydat_quoted_string(""));
3419        assert!(!is_polydat_quoted_string("\""));
3420    }
3421
3422    #[test]
3423    fn polydat_array_literal_balances_brackets() {
3424        assert!(is_polydat_array_literal("[1, 2, 3]"));
3425        assert!(is_polydat_array_literal("[]"));
3426        assert!(
3427            is_polydat_array_literal("[[1, 2], [3, 4]]"),
3428            "nested arrays balance"
3429        );
3430        assert!(is_polydat_array_literal("[\"a\", \"b\"]"));
3431        // Strings containing `]` don't break the count.
3432        assert!(is_polydat_array_literal("[\"a]b\", \"c\"]"));
3433        // Rejects unbalanced shapes.
3434        assert!(!is_polydat_array_literal("[1, 2"));
3435        assert!(!is_polydat_array_literal("1, 2]"));
3436        // `[1][2]` passes the conservative shape check (depth
3437        // returns to zero) — polydat's parser rejects it
3438        // downstream as invalid syntax. The classifier is a
3439        // routing heuristic, not a validator.
3440    }
3441}
3442
3443/// Recursively walk a JSON value and resolve every `{name}`
3444/// placeholder via [`KernelLookup`](polydat::kernel::interp::KernelLookup). Non-resolving names
3445/// that are in the per-cycle binding set stay as-is (the
3446/// dispenser will resolve them at execute time); anything else
3447/// gets pushed onto `errors`.
3448///
3449/// Object keys are *not* rewritten — keys are the closed-vocab
3450/// field name surface, distinct from the value-bearing
3451/// placeholders.
3452fn resolve_placeholders_in_json(
3453    value: &mut serde_json::Value,
3454    kernel: &dyn polydat::Kernel,
3455    per_cycle_names: &[String],
3456    field_path: &str,
3457    errors: &mut Vec<String>,
3458) {
3459    match value {
3460        serde_json::Value::String(s) => {
3461            match resolve_placeholders_in_string(s, kernel, per_cycle_names, field_path) {
3462                Ok(out) => *value = serde_json::Value::String(out),
3463                Err(es) => errors.extend(es),
3464            }
3465        }
3466        serde_json::Value::Array(arr) => {
3467            for (i, v) in arr.iter_mut().enumerate() {
3468                let p = format!("{field_path}[{i}]");
3469                resolve_placeholders_in_json(v, kernel, per_cycle_names, &p, errors);
3470            }
3471        }
3472        serde_json::Value::Object(map) => {
3473            for (k, v) in map.iter_mut() {
3474                let p = format!("{field_path}.{k}");
3475                resolve_placeholders_in_json(v, kernel, per_cycle_names, &p, errors);
3476            }
3477        }
3478        _ => {}
3479    }
3480}
3481
3482/// Walk one string, replace each `{name}` placeholder with the
3483/// kernel's `lookup` result for `name`. Bare-ident-only — the
3484/// qualified `{bind:…}` / `{capture:…}` / `{input:…}` /
3485/// `{param:…}` shapes and the inline `{{expr}}` shape pass
3486/// through untouched (consumed downstream by the dispenser /
3487/// inline-expression desugar). Names that fall through to the
3488/// per-cycle binding set also pass through. Anything else is
3489/// returned as an error in the `Err` Vec, with the field path
3490/// for context.
3491fn resolve_placeholders_in_string(
3492    s: &str,
3493    kernel: &dyn polydat::Kernel,
3494    per_cycle_names: &[String],
3495    field_path: &str,
3496) -> Result<String, Vec<String>> {
3497    let bytes = s.as_bytes();
3498    let n = bytes.len();
3499    let mut out = String::with_capacity(n);
3500    let mut errors: Vec<String> = Vec::new();
3501    let mut i = 0;
3502    while i < n {
3503        // `\{` and `\}` are escapes — passthrough one char.
3504        if bytes[i] == b'\\' && i + 1 < n && (bytes[i + 1] == b'{' || bytes[i + 1] == b'}') {
3505            out.push(bytes[i] as char);
3506            out.push(bytes[i + 1] as char);
3507            i += 2;
3508            continue;
3509        }
3510        // `{{ ... }}` is an inline expression — passthrough.
3511        if i + 1 < n && bytes[i] == b'{' && bytes[i + 1] == b'{' {
3512            // Find the matching `}}`.
3513            let start = i;
3514            let mut j = i + 2;
3515            while j + 1 < n && !(bytes[j] == b'}' && bytes[j + 1] == b'}') {
3516                j += 1;
3517            }
3518            let end = (j + 2).min(n);
3519            out.push_str(&s[start..end]);
3520            i = end;
3521            continue;
3522        }
3523        if bytes[i] != b'{' {
3524            out.push(bytes[i] as char);
3525            i += 1;
3526            continue;
3527        }
3528        // Find the matching `}` for this `{`.
3529        let body_start = i + 1;
3530        let mut j = body_start;
3531        while j < n && bytes[j] != b'}' {
3532            j += 1;
3533        }
3534        if j >= n {
3535            // Unterminated `{` — treat as literal char and move on.
3536            out.push('{');
3537            i += 1;
3538            continue;
3539        }
3540        let body = &s[body_start..j];
3541        let after = j + 1;
3542
3543        // Qualified references stay as-is for downstream.
3544        if body.contains(':') {
3545            out.push('{');
3546            out.push_str(body);
3547            out.push('}');
3548            i = after;
3549            continue;
3550        }
3551
3552        // Empty body — leave as-is, validator catches.
3553        if body.is_empty() {
3554            out.push('{');
3555            out.push_str(body);
3556            out.push('}');
3557            i = after;
3558            continue;
3559        }
3560
3561        // Not a bare identifier — pass through (could be a format spec).
3562        if !is_bare_ident(body) {
3563            out.push('{');
3564            out.push_str(body);
3565            out.push('}');
3566            i = after;
3567            continue;
3568        }
3569
3570        // Names that are per-cycle (coordinates declared via
3571        // `input (cycle: u64, ...: u64)`, or LHS of phase bindings)
3572        // MUST be deferred to per-cycle resolution. Their value
3573        // varies per iteration; pre-resolving against the parent
3574        // kernel here would bake in iteration 0's value (0) and
3575        // every subsequent iteration would emit the same string.
3576        if per_cycle_names.iter().any(|n| n == body) {
3577            out.push('{');
3578            out.push_str(body);
3579            out.push('}');
3580            i = after;
3581            continue;
3582        }
3583        // Bare ident — try kernel lookup. Computed outputs
3584        // (node-backed) aren't found by `lookup` (it only reads
3585        // input slots + constants), but they ARE valid wires
3586        // visible at this scope — accept them by checking
3587        // `resolve_output`. Per-cycle resolution at dispenser
3588        // time handles the actual pull.
3589        match polydat::kernel::interp::Lookup::lookup(
3590            &polydat::kernel::interp::KernelLookup::new(kernel),
3591            body,
3592        ) {
3593            Some(v) => out.push_str(&v.to_display_string()),
3594            None if kernel.output_index(body).is_some() => {
3595                // Defer to per-cycle resolution. Emit the
3596                // placeholder unchanged.
3597                out.push('{');
3598                out.push_str(body);
3599                out.push('}');
3600            }
3601            None => {
3602                errors.push(format!(
3603                    "{field_path}: '{{{body}}}' did not resolve in scope and is \
3604                     not a per-cycle binding declared by this phase"
3605                ));
3606                // Still push the placeholder as-is so the rest of
3607                // the string remains parseable for further error
3608                // collection on the same field.
3609                out.push('{');
3610                out.push_str(body);
3611                out.push('}');
3612            }
3613        }
3614        i = after;
3615    }
3616
3617    if errors.is_empty() {
3618        Ok(out)
3619    } else {
3620        Err(errors)
3621    }
3622}
3623
3624/// Rewrite inline expressions (`{{expr}}`) in op template strings to
3625/// use named binding references (`{__expr_N}`).
3626///
3627/// Returns the expression-to-name map for the caller to know what
3628/// was rewritten. Fails on a malformed bind point, naming the op.
3629pub fn rewrite_inline_exprs(ops: &mut [ParsedOp]) -> Result<HashMap<String, String>, String> {
3630    // SRD-13d: each op template is its own Polydat scope. Inline
3631    // `{{<expr>}}` rewrites are Polydat matter that belongs to the
3632    // op-template scope, not to the shared phase scope. So each
3633    // op gets its OWN expression-to-name mapping, with
3634    // op-locally unique synth names — no cross-op dedup. Two ops
3635    // with textually identical inline expressions
3636    // (`if: cql_dialect == 'vendor'` on both `indexes_present_vendor`
3637    // and `indexes_built_vendor`) now get distinct
3638    // `__expr_N`/`__expr_M` names. Without this, both ops
3639    // injected the same `__expr_1 := cql_dialect == 'vendor'`
3640    // line into their bindings; the phase-scope ingest then saw
3641    // two ops each declaring `__expr_1` and tripped the
3642    // ride-along-uniqueness check (SRD-13c §"Op overriding op
3643    // shadow").
3644    //
3645    // The global `inline_idx` counter still increments
3646    // monotonically so synth names are workload-wide unique;
3647    // the per-op MAP keeps within-op dedup (same expression in
3648    // multiple fields of one op — `if: x == 1` and
3649    // `metric: x == 1` — collapses to a single `__expr_N` for
3650    // that op).
3651    let mut inline_idx = 0usize;
3652    let mut per_op_expr_to_name: Vec<HashMap<String, String>> =
3653        (0..ops.len()).map(|_| HashMap::new()).collect();
3654    let collect_from =
3655        |s: &str, idx: &mut usize, op_map: &mut HashMap<String, String>| -> Result<(), String> {
3656            for bp in nmbrs_workload::bindpoints::extract_bind_points(s)? {
3657                if let nmbrs_workload::bindpoints::BindPoint::InlineDefinition(ref expr) = bp {
3658                    op_map.entry(expr.clone()).or_insert_with(|| {
3659                        let n = format!("__expr_{idx}");
3660                        *idx += 1;
3661                        n
3662                    });
3663                }
3664            }
3665            Ok(())
3666        };
3667    for (op_index, op) in ops.iter().enumerate() {
3668        let op_map = &mut per_op_expr_to_name[op_index];
3669        for value in op.op.values() {
3670            if let Some(s) = value.as_str() {
3671                collect_from(s, &mut inline_idx, op_map)
3672                    .map_err(|e| format!("op '{}': {e}", op.name))?;
3673            }
3674        }
3675        if let Some(s) = &op.condition {
3676            collect_from(s, &mut inline_idx, op_map)
3677                .map_err(|e| format!("op '{}': {e}", op.name))?;
3678        }
3679        if let Some(spec) = &op.delay {
3680            for name in spec.names() {
3681                collect_from(name, &mut inline_idx, op_map)
3682                    .map_err(|e| format!("op '{}': {e}", op.name))?;
3683            }
3684        }
3685    }
3686    // For diagnostics + downstream: the legacy single
3687    // `expr_to_name` return value flattens the per-op maps.
3688    // Names are unique across ops because the inline_idx
3689    // counter is global, so the union is collision-free.
3690    let expr_to_name: HashMap<String, String> = per_op_expr_to_name
3691        .iter()
3692        .flat_map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())))
3693        .collect();
3694
3695    // Inject the synthesised `__expr_N := expr` bindings into
3696    // the first op's Polydat bindings source so `build_scope`'s
3697    // normal ingestion pass picks them up. Without this the
3698    // op fields get rewritten to reference `{__expr_N}` but
3699    // no binding declaring `__expr_N` ever lands in the
3700    // scope, so compilation fails with "unresolved bind
3701    // point '{__expr_N}'". Callers used to discard the
3702    // returned `expr_to_name` mapping and trust some other
3703    // path to install the bindings — there isn't one. Doing
3704    // the injection here keeps `rewrite_inline_exprs`
3705    // self-contained: every output rewrite has a matching
3706    // binding emitted.
3707    // Inject + rewrite per op. Each op uses ONLY its own
3708    // expr_to_name mapping (per_op_expr_to_name[op_index]).
3709    // Synth lines land in that op's bindings; field rewrites
3710    // see only that op's expression names. SRD-13d: the
3711    // op-template scope owns its own Polydat matter, including
3712    // synth bindings from inline expressions.
3713    if expr_to_name.is_empty() {
3714        return Ok(expr_to_name);
3715    }
3716    use nmbrs_workload::model::BindingsDef;
3717    for (op_index, op) in ops.iter_mut().enumerate() {
3718        let op_map = &per_op_expr_to_name[op_index];
3719        if op_map.is_empty() {
3720            continue;
3721        }
3722
3723        // Build synth lines for this op, deterministically
3724        // ordered by synth name.
3725        let mut entries: Vec<(&String, &String)> = op_map.iter().collect();
3726        entries.sort_by(|a, b| a.1.cmp(b.1));
3727        let mut synth_lines = String::new();
3728        for (expr, name) in &entries {
3729            synth_lines.push_str(&format!("\n{name} := {expr}"));
3730        }
3731
3732        // Inject into op.bindings. Map → PolydatSource conversion
3733        // mirrors the existing scope-source assembly path.
3734        match &mut op.bindings {
3735            BindingsDef::PolydatSource(s) => {
3736                if s.trim().is_empty() {
3737                    *s = synth_lines.trim_start_matches('\n').to_string();
3738                } else {
3739                    s.push_str(&synth_lines);
3740                }
3741            }
3742            BindingsDef::Map(_) => {
3743                if let BindingsDef::Map(map) = &op.bindings {
3744                    let mut existing = String::new();
3745                    for (k, v) in map.iter() {
3746                        existing.push_str(&format!("{k} := {v}\n"));
3747                    }
3748                    op.bindings = BindingsDef::PolydatSource(format!("{existing}{synth_lines}"));
3749                }
3750            }
3751        }
3752
3753        // Rewrite this op's fields using its own mapping only.
3754        let rewrite = |s: &str| -> String {
3755            let mut rewritten = s.to_string();
3756            for (expr, name) in op_map {
3757                rewritten = rewritten.replace(&format!("{{{{{expr}}}}}"), &format!("{{{name}}}"));
3758                rewritten = rewritten.replace(&format!("{{:={expr}:=}}"), &format!("{{{name}}}"));
3759                rewritten = rewritten.replace(&format!("{{:={expr}}}"), &format!("{{{name}}}"));
3760                rewritten = rewritten.replace(&format!("{{{expr}}}"), &format!("{{{name}}}"));
3761            }
3762            rewritten
3763        };
3764        for value in op.op.values_mut() {
3765            if let Some(s) = value.as_str() {
3766                *value = serde_json::Value::String(rewrite(s));
3767            }
3768        }
3769        if let Some(s) = &op.condition {
3770            op.condition = Some(rewrite(s));
3771        }
3772        if let Some(spec) = &op.delay {
3773            // Rewrite each binding name in place, preserving
3774            // the spec's enum shape (Before vs BeforeAfter).
3775            op.delay = Some(match spec {
3776                nmbrs_workload::model::DelaySpec::Before(name) => {
3777                    nmbrs_workload::model::DelaySpec::Before(rewrite(name))
3778                }
3779                nmbrs_workload::model::DelaySpec::BeforeAfter { before, after } => {
3780                    nmbrs_workload::model::DelaySpec::BeforeAfter {
3781                        before: before.as_deref().map(rewrite),
3782                        after: after.as_deref().map(rewrite),
3783                    }
3784                }
3785            });
3786        }
3787    }
3788
3789    Ok(expr_to_name)
3790}
3791
3792/// Cached `NMBRS_DEBUG_SCOPE_SYNTH=true` switch (one read, one
3793/// warning on a non-boolean value).
3794fn debug_scope_synth_enabled() -> bool {
3795    static FLAG: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3796    *FLAG.get_or_init(|| crate::debug_env::debug_flag("NMBRS_DEBUG_SCOPE_SYNTH"))
3797}
3798
3799#[cfg(test)]
3800mod tests {
3801    use super::*;
3802
3803    fn make_polydat_op(name: &str, stmt: &str, bindings: &str) -> ParsedOp {
3804        let mut op = ParsedOp::simple(name, stmt);
3805        op.bindings = BindingsDef::PolydatSource(bindings.to_string());
3806        op
3807    }
3808
3809    #[test]
3810    fn objective_bare_wire_vs_inline_expression() {
3811        // Bare identifiers are read directly off the phase kernel.
3812        assert!(objective_is_bare_wire("score"));
3813        assert!(objective_is_bare_wire("err_rate"));
3814        assert!(objective_is_bare_wire("_objective"));
3815        assert!(objective_is_bare_wire("  recall99  ")); // trimmed
3816        assert_eq!(objective_wire("score"), "score");
3817        assert_eq!(objective_wire("  recall99  "), "recall99");
3818
3819        // Anything with operators / calls / dots / spaces is an inline
3820        // expression → synthesized to the `__objective` wire.
3821        assert!(!objective_is_bare_wire("0 - err_rate"));
3822        assert!(!objective_is_bare_wire("metricsql_scalar(\"x\")"));
3823        assert!(!objective_is_bare_wire("a - b"));
3824        assert!(!objective_is_bare_wire("q.cursor.depth"));
3825        assert!(!objective_is_bare_wire(""));
3826        assert_eq!(objective_wire("0 - err_rate"), OBJECTIVE_WIRE);
3827        assert_eq!(objective_wire("metricsql_scalar(\"x\")"), OBJECTIVE_WIRE);
3828    }
3829
3830    #[test]
3831    fn inline_objective_synthesizes_volatile_objective_binding() {
3832        use nmbrs_workload::model::{BindingsDef, OptimizeBlock, WorkloadPhase};
3833        let phase = WorkloadPhase {
3834            for_each: Some("rate in 1000, 2000".to_string()),
3835            bindings: BindingsDef::PolydatSource("input cycle: u64\n".to_string()),
3836            optimize: Some(OptimizeBlock {
3837                method: "sweep".to_string(),
3838                objective: "0 - metricsql_scalar(\"sum(rate(errors_total[3s]))\")".to_string(),
3839                servo: vec!["rate".to_string()],
3840                max_evals: 10,
3841                seed: 0,
3842                params: Default::default(),
3843            }),
3844            ..Default::default()
3845        };
3846        let out = synthesize_phase_scope_bindings(&phase).expect("synthesis ok");
3847        let src = match out {
3848            BindingsDef::PolydatSource(s) => s,
3849            other => panic!("expected PolydatSource, got {other:?}"),
3850        };
3851        assert!(
3852            src.contains("volatile __objective := 0 - metricsql_scalar("),
3853            "inline objective must be lowered to a `__objective` binding:\n{src}"
3854        );
3855
3856        // A bare-name objective is NOT synthesized — read directly.
3857        let mut bare = phase.clone();
3858        bare.optimize.as_mut().unwrap().objective = "score".to_string();
3859        let bare_out = synthesize_phase_scope_bindings(&bare).expect("synthesis ok");
3860        if let BindingsDef::PolydatSource(s) = bare_out {
3861            assert!(
3862                !s.contains("__objective"),
3863                "bare objective must not synthesize:\n{s}"
3864            );
3865        }
3866    }
3867
3868    #[test]
3869    fn inherited_bindings_dedup_across_ops() {
3870        let bindings = "input cycle: u64\nprofiles := matching_profiles(\"example\", \"label\")";
3871        let ops = vec![
3872            make_polydat_op("op_a", "{profiles}", bindings),
3873            make_polydat_op("op_b", "{profiles}", bindings),
3874        ];
3875        let scope = build_scope(
3876            &ops,
3877            &HashMap::new(),
3878            &[],
3879            &HashMap::new(),
3880            &HashMap::new(),
3881            None,
3882            &[],
3883            None,
3884        )
3885        .unwrap();
3886        scope.validate().unwrap();
3887        let emitted = scope.emit();
3888        // 'profiles' should appear exactly once
3889        let count = emitted.matches("profiles :=").count();
3890        assert_eq!(
3891            count, 1,
3892            "expected exactly 1 'profiles :=' in emitted scope, got {count}:\n{emitted}"
3893        );
3894    }
3895
3896    #[test]
3897    fn iteration_vars_dont_conflict_with_inherited() {
3898        let bindings = "input cycle: u64\nprofiles := matching_profiles(\"example\", \"label\")";
3899        let ops = vec![
3900            make_polydat_op("op_a", "{profiles} {table}", bindings),
3901            make_polydat_op("op_b", "{profiles} {table}", bindings),
3902        ];
3903        let mut iter_vars = HashMap::new();
3904        iter_vars.insert("table".to_string(), "vec_default".to_string());
3905
3906        let scope = build_scope(
3907            &ops,
3908            &iter_vars,
3909            &[],
3910            &HashMap::new(),
3911            &HashMap::new(),
3912            None,
3913            &[],
3914            None,
3915        )
3916        .unwrap();
3917        scope.validate().unwrap();
3918        let emitted = scope.emit();
3919        // Iteration variables now declare as `extern <name>:
3920        // <Type>` so the runtime can populate them per iteration
3921        // without recompiling (SRD 18b §"Iteration variables as
3922        // scope outputs"). Type is inferred from the value;
3923        // "vec_default" doesn't parse numerically → str.
3924        assert!(
3925            emitted.contains("extern table: str"),
3926            "expected extern table declaration in:\n{emitted}"
3927        );
3928        assert!(
3929            emitted.contains("profiles :="),
3930            "expected profiles in:\n{emitted}"
3931        );
3932    }
3933
3934    #[test]
3935    fn op_augmentation_adds_new_names() {
3936        let base = "input cycle: u64\nfoo := hash(cycle)";
3937        let augmented = "input cycle: u64\nfoo := hash(cycle)\nbar := mod(cycle, 100)";
3938        let ops = vec![
3939            make_polydat_op("op_a", "{foo}", base),
3940            make_polydat_op("op_b", "{foo} {bar}", augmented),
3941        ];
3942        let scope = build_scope(
3943            &ops,
3944            &HashMap::new(),
3945            &[],
3946            &HashMap::new(),
3947            &HashMap::new(),
3948            None,
3949            &[],
3950            None,
3951        )
3952        .unwrap();
3953        scope.validate().unwrap();
3954        let emitted = scope.emit();
3955        assert!(emitted.contains("foo := hash(cycle)"), "missing foo");
3956        assert!(emitted.contains("bar := mod(cycle, 100)"), "missing bar");
3957    }
3958
3959    #[test]
3960    fn real_shadow_is_caught() {
3961        let base = "input cycle: u64\nfoo := hash(cycle)";
3962        let shadow = "input cycle: u64\nfoo := mod(cycle, 100)";
3963        let ops = vec![
3964            make_polydat_op("op_a", "{foo}", base),
3965            make_polydat_op("op_b", "{foo}", shadow),
3966        ];
3967        let scope = build_scope(
3968            &ops,
3969            &HashMap::new(),
3970            &[],
3971            &HashMap::new(),
3972            &HashMap::new(),
3973            None,
3974            &[],
3975            None,
3976        )
3977        .unwrap();
3978        let result = scope.validate();
3979        assert!(result.is_err(), "expected shadow error");
3980        let err = result.unwrap_err();
3981        assert!(
3982            err.contains("shadows"),
3983            "expected 'shadows' in error: {err}"
3984        );
3985        assert!(err.contains("op_b"), "expected op name in error: {err}");
3986    }
3987
3988    #[test]
3989    fn original_bug_repro_no_false_shadow() {
3990        // The original bug: workload-level bindings with profiles,
3991        // inherited by a phase with for_each iteration vars.
3992        // Two ops share identical inherited bindings.
3993        // The init injection used to make them differ, causing false shadow.
3994        let bindings = "input cycle: u64\nprofiles := matching_profiles(\"example\", \"label\")";
3995        let ops = vec![
3996            make_polydat_op(
3997                "drop_metadata_index",
3998                "DROP INDEX {table}_meta_idx",
3999                bindings,
4000            ),
4001            make_polydat_op("drop_vector_index", "DROP INDEX {table}_idx", bindings),
4002            make_polydat_op("drop_table", "DROP TABLE {table}", bindings),
4003        ];
4004        let mut iter_vars = HashMap::new();
4005        iter_vars.insert("table".to_string(), "fknn_default".to_string());
4006        iter_vars.insert("spec".to_string(), "example:default".to_string());
4007        iter_vars.insert("optimize_for".to_string(), "RECALL".to_string());
4008
4009        let scope = build_scope(
4010            &ops,
4011            &iter_vars,
4012            &[],
4013            &HashMap::new(),
4014            &HashMap::new(),
4015            None,
4016            &[],
4017            None,
4018        )
4019        .unwrap();
4020        // This was the bug: validate() used to fail with false shadow error
4021        scope.validate().unwrap();
4022        let emitted = scope.emit();
4023        // Iter vars now declare as extern (SRD 18b). The original
4024        // bug — false-shadow detection — is unchanged regardless
4025        // of how the iter var materialises.
4026        assert!(
4027            emitted.contains("extern table: str"),
4028            "missing extern table in:\n{emitted}"
4029        );
4030        assert!(emitted.contains("profiles :="), "missing profiles");
4031        // profiles should appear exactly once
4032        let count = emitted.matches("profiles :=").count();
4033        assert_eq!(count, 1, "profiles duplicated in:\n{emitted}");
4034    }
4035
4036    // ── SRD-13d Phase 9 cross-scope contract check ──────────
4037
4038    fn parent_kernel_with_load() -> crate::scope_kernel::ScopeKernel {
4039        // Parent has `cycle` input, a folded constant `dim`, a
4040        // shared output `budget`, and a dynamic output `load`
4041        // (cycle-dependent, no modifier). Each shape exercises
4042        // a different `ParentRefKind` arm.
4043        crate::bindings::compile_scope_kernel(
4044            "input cycle: u64\n\
4045             const dim := 128\n\
4046             shared budget := 100\n\
4047             load := add(cycle, 1)\n",
4048            &Default::default(),
4049        )
4050        .expect("compile parent")
4051    }
4052
4053    fn op_with_body(name: &str, body: &str) -> ParsedOp {
4054        let mut op = ParsedOp::simple(name, "noop");
4055        op.bindings = BindingsDef::PolydatSource(body.into());
4056        op
4057    }
4058
4059    #[test]
4060    fn op_template_referencing_cycle_input_is_accepted() {
4061        let parent = parent_kernel_with_load();
4062        let manifest = polydat::kernel::extract_manifest(parent.program())
4063            .into_iter()
4064            .map(|e| crate::runner::ManifestEntry {
4065                name: e.name,
4066                port_type: e.port_type,
4067                modifier: e.modifier,
4068            })
4069            .collect::<Vec<_>>();
4070        let op = op_with_body("step_op", "step := add(cycle, 1)\n");
4071        let result = build_op_template_scope_kernel(
4072            &op,
4073            &manifest,
4074            &parent,
4075            &HashMap::new(),
4076            Vec::new(),
4077            None,
4078            false,
4079            polydat::kernel::KernelOptLevel::Release,
4080            "test",
4081        );
4082        assert!(
4083            result.is_ok(),
4084            "cycle is a parent input — should be accepted. err: {:?}",
4085            result.err()
4086        );
4087    }
4088
4089    /// Localises the metric-wiring defect: when an op-template kernel is
4090    /// materialised, does the synthesised `__metric_<name>` binding surface as
4091    /// an output on THAT kernel? The metrics wrapper reads it through
4092    /// `ctx.wires`, so if it is absent the wrapper reports
4093    /// "did not resolve through ctx.wires".
4094    #[test]
4095    fn op_template_kernel_exposes_synthesised_metric_bindings() {
4096        use nmbrs_workload::model::MetricSpec;
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        let mut op = op_with_body("m_op", "measured := add(cycle, 1)\n");
4107        op.metrics.insert(
4108            "bytes_out".to_string(),
4109            MetricSpec {
4110                value: "measured".into(),
4111                family: None,
4112                kind: None,
4113                unit: None,
4114                format: None,
4115                cell: Default::default(),
4116            },
4117        );
4118        let kernel = build_op_template_scope_kernel(
4119            &op,
4120            &manifest,
4121            &parent,
4122            &HashMap::new(),
4123            Vec::new(),
4124            None,
4125            false,
4126            polydat::kernel::KernelOptLevel::Release,
4127            "test",
4128        )
4129        .expect("op-template kernel builds");
4130        let outs = kernel.program().output_names();
4131        assert!(
4132            outs.contains(&"__metric_bytes_out"),
4133            "the synthesised metric binding must be an output of the \
4134             op-template kernel; outputs: {outs:?}"
4135        );
4136    }
4137
4138    #[test]
4139    fn op_template_referencing_constant_output_is_accepted() {
4140        let parent = parent_kernel_with_load();
4141        let manifest = polydat::kernel::extract_manifest(parent.program())
4142            .into_iter()
4143            .map(|e| crate::runner::ManifestEntry {
4144                name: e.name,
4145                port_type: e.port_type,
4146                modifier: e.modifier,
4147            })
4148            .collect::<Vec<_>>();
4149        // `dim` is a `final` (folded) output — snapshot is final,
4150        // per-cycle changes are impossible by construction.
4151        let op = op_with_body("calc_op", "scaled := mul(dim, 2)\n");
4152        let result = build_op_template_scope_kernel(
4153            &op,
4154            &manifest,
4155            &parent,
4156            &HashMap::new(),
4157            Vec::new(),
4158            None,
4159            false,
4160            polydat::kernel::KernelOptLevel::Release,
4161            "test",
4162        );
4163        assert!(
4164            result.is_ok(),
4165            "final/folded output should be accepted. err: {:?}",
4166            result.err()
4167        );
4168    }
4169
4170    #[test]
4171    fn op_template_referencing_shared_output_is_accepted() {
4172        let parent = parent_kernel_with_load();
4173        let manifest = polydat::kernel::extract_manifest(parent.program())
4174            .into_iter()
4175            .map(|e| crate::runner::ManifestEntry {
4176                name: e.name,
4177                port_type: e.port_type,
4178                modifier: e.modifier,
4179            })
4180            .collect::<Vec<_>>();
4181        // `budget` is `shared` — SharedCell carries live updates.
4182        let op = op_with_body("budget_op", "remaining := add(budget, 1)\n");
4183        let result = build_op_template_scope_kernel(
4184            &op,
4185            &manifest,
4186            &parent,
4187            &HashMap::new(),
4188            Vec::new(),
4189            None,
4190            false,
4191            polydat::kernel::KernelOptLevel::Release,
4192            "test",
4193        );
4194        assert!(
4195            result.is_ok(),
4196            "shared output should be accepted. err: {:?}",
4197            result.err()
4198        );
4199    }
4200
4201    #[test]
4202    fn op_template_referencing_dynamic_output_accepted_per_srd_13f() {
4203        // SRD-13f retires SRD-13c's "DynamicOutput without
4204        // shared" rejection. The read invariant is uniform —
4205        // inner reads of cross-scope wires return outer's
4206        // current value via construction-time wiring (cells
4207        // for shared, per-cycle refresh / planned cell
4208        // mechanism for non-shared). The op-template
4209        // synthesiser accepts the reference; the wiring keeps
4210        // the invariant intact at cycle time.
4211        let parent = parent_kernel_with_load();
4212        let manifest = polydat::kernel::extract_manifest(parent.program())
4213            .into_iter()
4214            .map(|e| crate::runner::ManifestEntry {
4215                name: e.name,
4216                port_type: e.port_type,
4217                modifier: e.modifier,
4218            })
4219            .collect::<Vec<_>>();
4220        let op = op_with_body("forecast_op", "forecast := mul(load, 2)\n");
4221        let kernel = build_op_template_scope_kernel(
4222            &op,
4223            &manifest,
4224            &parent,
4225            &HashMap::new(),
4226            Vec::new(),
4227            None,
4228            false,
4229            polydat::kernel::KernelOptLevel::Release,
4230            "test",
4231        )
4232        .expect("op-template kernel synth should accept dynamic parent ref");
4233        // The op-template kernel carries `load` as an extern
4234        // input — the construction-time wiring set up the slot;
4235        // per-cycle refresh keeps it current with outer.
4236        assert!(
4237            kernel.program().find_input("load").is_some(),
4238            "extern load slot should land on op-template kernel"
4239        );
4240        // And `forecast`, the op-local binding, is an output.
4241        assert!(
4242            kernel.program().output_names().contains(&"forecast"),
4243            "op-local binding should be an output"
4244        );
4245    }
4246
4247    #[test]
4248    fn op_template_pvs_query_full_shape_with_workload_params() {
4249        // Closer to the actual full_cql_vector.yaml shape: the
4250        // op carries `prepared:` text with `{keyspace}.{table}`
4251        // / `{predicate}` / `{query_vector}` / `{limit}` interp
4252        // bind-points, plus a `metrics: overscan: {value:
4253        // overscan}` declaration. workload_params carries
4254        // dataset/profile/keyspace via `final` injection. The
4255        // op-template synthesiser must emit the latency_factor /
4256        // recall_factor / overscan bindings as outputs so the
4257        // metrics fixture's `register_pull("overscan")`
4258        // resolves.
4259        use nmbrs_workload::model::MetricSpec;
4260        let parent_src = r#"
4261extern k: u64
4262extern limit: u64
4263extern optimize_for: str
4264extern table: str
4265"#;
4266        let parent = crate::bindings::compile_scope_kernel(
4267            parent_src,
4268            &polydat::dsl::compile::CompileOptions {
4269                context: "parent".to_string(),
4270                ..Default::default()
4271            },
4272        )
4273        .expect("parent compile");
4274        let manifest: Vec<crate::runner::ManifestEntry> =
4275            polydat::kernel::extract_manifest(parent.program())
4276                .into_iter()
4277                .map(|e| crate::runner::ManifestEntry {
4278                    name: e.name,
4279                    port_type: e.port_type,
4280                    modifier: e.modifier,
4281                })
4282                .collect();
4283        let body = "const prebuffered := dataset_prebuffer(\"{dataset}:{profile}\")\n\
4284            const query_counts := query_count(prebuffered)\n\
4285            cursor q = range(0, query_counts * 10)\n\
4286            query_vector := query_vector_at(prebuffered, q % query_counts)\n\
4287            predicate := predicate_value_at(prebuffered, q % query_counts)\n\
4288            ground_truth := filtered_neighbor_indices_at(prebuffered, q % query_counts)\n\
4289            latency_factor := 0.979 + 4.021 * pow(limit, -0.761)\n\
4290            recall_factor  := 0.509 + 9.491 * pow(limit, -0.402)\n\
4291            overscan := if(optimize_for == \"LATENCY\", latency_factor, recall_factor)\n";
4292        let mut op = op_with_body("select_ann", body);
4293        // Mirror op fields the YAML carries.
4294        op.op.insert(
4295            "prepared".into(),
4296            serde_json::json!(
4297                "SELECT key,value FROM {keyspace}.{table} \
4298             WHERE metadata = {predicate} \
4299             ORDER BY value ANN OF {query_vector} LIMIT {limit}"
4300            ),
4301        );
4302        op.metrics.insert(
4303            "overscan".into(),
4304            MetricSpec {
4305                value: "overscan".into(),
4306                family: None,
4307                kind: None,
4308                unit: None,
4309                format: None,
4310                cell: Default::default(),
4311            },
4312        );
4313        let mut workload_params = HashMap::new();
4314        workload_params.insert("dataset".into(), "example".into());
4315        workload_params.insert("profile".into(), "label_00".into());
4316        workload_params.insert("keyspace".into(), "baselines".into());
4317        let kernel = build_op_template_scope_kernel(
4318            &op,
4319            &manifest,
4320            &parent,
4321            &workload_params,
4322            vec![],
4323            None,
4324            false,
4325            polydat::kernel::KernelOptLevel::Release,
4326            "pvs_query.select_ann",
4327        )
4328        .expect("op-template kernel synth");
4329        let outs: Vec<String> = kernel
4330            .program()
4331            .output_names()
4332            .iter()
4333            .map(|s| s.to_string())
4334            .collect();
4335        for required in &["overscan", "latency_factor", "recall_factor"] {
4336            assert!(
4337                outs.iter().any(|o| o == required),
4338                "op-template kernel missing '{required}'; outputs: {outs:?}"
4339            );
4340        }
4341        // Workload params must be folded in as `final` constants
4342        // (not externs) so `init prebuffered =
4343        // dataset_prebuffer("{dataset}:{profile}")` folds at
4344        // compile time. If they cascade through as externs the
4345        // init binding stays unfolded, the per-fiber state never
4346        // gets the seeded Handle, and downstream nodes (like
4347        // `neighbor_indices_at(prebuffered, q)`) panic at runtime
4348        // with `expected Handle, got None/U64`.
4349        for param in &["dataset", "profile", "keyspace"] {
4350            // The param either folds out completely (no input
4351            // slot) or appears as a folded constant — both
4352            // are fine. What's NOT fine is showing up as an
4353            // input on the inner kernel.
4354            assert!(
4355                kernel.program().find_input(param).is_none(),
4356                "workload param '{param}' must NOT be an extern input \
4357                 on the op-template kernel — cascade should emit \
4358                 it as `final` so init bindings fold. Inputs: {:?}",
4359                kernel.program().input_names(),
4360            );
4361        }
4362    }
4363
4364    #[test]
4365    fn op_template_with_pow_and_if_keeps_all_outputs() {
4366        // Mirror the shape of full_cql_vector.yaml's pvs_query
4367        // phase body (after parser merge): init+cursor+:= ladder
4368        // ending with `pow()` + `if()` bindings. The op-template
4369        // kernel must expose every `:=` binding as an output;
4370        // a missing `overscan` is what triggers the
4371        // `register_pull("overscan")` failure at MetricsDispenser
4372        // wrap time.
4373        let parent_src = r#"
4374extern k: u64
4375extern limit: u64
4376extern optimize_for: str
4377extern table: str
4378extern dataset: str
4379extern profile: str
4380extern keyspace: str
4381"#;
4382        let parent = crate::bindings::compile_scope_kernel(
4383            parent_src,
4384            &polydat::dsl::compile::CompileOptions {
4385                context: "parent".to_string(),
4386                ..Default::default()
4387            },
4388        )
4389        .expect("parent compile");
4390        let manifest: Vec<crate::runner::ManifestEntry> =
4391            polydat::kernel::extract_manifest(parent.program())
4392                .into_iter()
4393                .map(|e| crate::runner::ManifestEntry {
4394                    name: e.name,
4395                    port_type: e.port_type,
4396                    modifier: e.modifier,
4397                })
4398                .collect();
4399        let body = "const prebuffered := dataset_prebuffer(\"dummy:default\")\n\
4400            const query_counts := query_count(prebuffered)\n\
4401            cursor q = range(0, query_counts * 10)\n\
4402            query_vector := query_vector_at(prebuffered, q % query_counts)\n\
4403            predicate := predicate_value_at(prebuffered, q % query_counts)\n\
4404            ground_truth := filtered_neighbor_indices_at(prebuffered, q % query_counts)\n\
4405            latency_factor := 0.979 + 4.021 * pow(limit, -0.761)\n\
4406            recall_factor  := 0.509 + 9.491 * pow(limit, -0.402)\n\
4407            overscan := if(optimize_for == \"LATENCY\", latency_factor, recall_factor)\n";
4408        let op = op_with_body("select_ann", body);
4409        let kernel = build_op_template_scope_kernel(
4410            &op,
4411            &manifest,
4412            &parent,
4413            &HashMap::new(),
4414            Vec::new(),
4415            None,
4416            false,
4417            polydat::kernel::KernelOptLevel::Release,
4418            "pvs_query.select_ann",
4419        )
4420        .expect("op-template kernel synth");
4421        let outs: Vec<String> = kernel
4422            .program()
4423            .output_names()
4424            .iter()
4425            .map(|s| s.to_string())
4426            .collect();
4427        for required in &[
4428            "query_vector",
4429            "predicate",
4430            "ground_truth",
4431            "latency_factor",
4432            "recall_factor",
4433            "overscan",
4434        ] {
4435            assert!(
4436                outs.iter().any(|o| o == required),
4437                "op-template kernel missing '{required}'; outputs: {outs:?}"
4438            );
4439        }
4440    }
4441
4442    #[test]
4443    fn op_template_relevancy_k_r_bare_wire_names_cascade() {
4444        // Post-SRD-68 follow-up: `evaluations.relevancy.{k, r,
4445        // expected, actual}` accept bare wire-name forms. The
4446        // op-template synthesiser must include those names in its
4447        // cascaded-extern set so the dispenser's canonical kernel
4448        // can resolve them at wrap-time (where parse_count_param
4449        // calls wires.get(name)).
4450        let parent = parent_kernel_with_load();
4451        let manifest = polydat::kernel::extract_manifest(parent.program())
4452            .into_iter()
4453            .map(|e| crate::runner::ManifestEntry {
4454                name: e.name,
4455                port_type: e.port_type,
4456                modifier: e.modifier,
4457            })
4458            .collect::<Vec<_>>();
4459        let mut op = ParsedOp::simple("read", "noop");
4460        op.bindings = BindingsDef::PolydatSource("".into());
4461        op.params.insert(
4462            "relevancy".into(),
4463            serde_json::json!({
4464                "actual": "rows",
4465                "expected": "ground_truth",
4466                "k": "k_value",
4467                "r": "limit_value",
4468                "functions": ["recall"],
4469            }),
4470        );
4471        // Parent has `cycle` as the coord input. The relevancy
4472        // wire names (rows, ground_truth, k_value, limit_value)
4473        // aren't on the parent; the synthesiser should still add
4474        // them to the cascade-extern set so the op-template kernel
4475        // *declares* them (errors only fire at wrap-time when the
4476        // canonical kernel actually tries to resolve them).
4477        //
4478        // For this unit test we just confirm the synthesiser
4479        // doesn't error AND that the input/output names list
4480        // includes each relevancy wire name — meaning the
4481        // referenced-cascade walker picked them up. We pick names
4482        // the parent doesn't have so the auto-extern path fires
4483        // and the resulting kernel has them as inputs.
4484        let _ = manifest;
4485        // Use the public synthesis entry point to construct the
4486        // op-template kernel under a parent that *does* have the
4487        // referenced wires (so the cascade succeeds).
4488        let kernel_src = "\
4489            input cycle: u64\n\
4490            const rows := 10\n\
4491            const ground_truth := \"1,2,3\"\n\
4492            const k_value := 5\n\
4493            const limit_value := 100\n";
4494        let real_parent =
4495            crate::scope_kernel::ScopeKernel::compile(kernel_src).expect("parent compile");
4496        let real_manifest = polydat::kernel::extract_manifest(real_parent.program())
4497            .into_iter()
4498            .map(|e| crate::runner::ManifestEntry {
4499                name: e.name,
4500                port_type: e.port_type,
4501                modifier: e.modifier,
4502            })
4503            .collect::<Vec<_>>();
4504        let kernel = build_op_template_scope_kernel(
4505            &op,
4506            &real_manifest,
4507            &real_parent,
4508            &HashMap::new(),
4509            Vec::new(),
4510            None,
4511            false,
4512            polydat::kernel::KernelOptLevel::Release,
4513            "relevancy-cascade-test",
4514        )
4515        .expect("op-template kernel synth");
4516
4517        // Each bare-name relevancy wire should resolve through the
4518        // op-template kernel's lookup — the same path validation.rs
4519        // takes at wrap-time via canonical_kernel().lookup(name).
4520        for name in &["rows", "ground_truth", "k_value", "limit_value"] {
4521            assert!(
4522                kernel.lookup(name).is_some(),
4523                "relevancy wire '{name}' should be visible on the \
4524                 op-template kernel (cascaded extern); kernel had \
4525                 outputs: {outs:?}",
4526                outs = kernel.program().output_names()
4527            );
4528        }
4529    }
4530
4531    #[test]
4532    fn op_template_metric_value_count_allocates_magic_extern_slot() {
4533        // Post-SRD-68 follow-up: a metric `value:` expression is a
4534        // use site for any names it references. The op-template
4535        // kernel synthesiser appends `__metric_<name> := <value_expr>`
4536        // to the result-bindings source, so the closure-binding
4537        // economy's free-identifier walker sees `count` and injects
4538        // an `extern count: u64` slot — no throw-away result-binding
4539        // needed.
4540        //
4541        // Verifies: a workload with NO `result:` block but a
4542        // `metrics: rows_per_op: { value: count }` declaration ends
4543        // up with a `count` INPUT slot on the kernel.
4544        let parent = parent_kernel_with_load();
4545        let manifest = polydat::kernel::extract_manifest(parent.program())
4546            .into_iter()
4547            .map(|e| crate::runner::ManifestEntry {
4548                name: e.name,
4549                port_type: e.port_type,
4550                modifier: e.modifier,
4551            })
4552            .collect::<Vec<_>>();
4553        let mut op = ParsedOp::simple("read", "noop");
4554        op.bindings = BindingsDef::PolydatSource("".into());
4555        op.metrics.insert(
4556            "rows_per_op".into(),
4557            nmbrs_workload::model::MetricSpec {
4558                value: "count".into(),
4559                family: None,
4560                kind: Some(nmbrs_workload::model::MetricKind::Gauge),
4561                unit: None,
4562                format: None,
4563                cell: Default::default(),
4564            },
4565        );
4566        let kernel = build_op_template_scope_kernel(
4567            &op,
4568            &manifest,
4569            &parent,
4570            &HashMap::new(),
4571            Vec::new(),
4572            None,
4573            false,
4574            polydat::kernel::KernelOptLevel::Release,
4575            "metric-walker-test",
4576        )
4577        .expect("op-template kernel synth");
4578        let inputs = kernel.program().input_names();
4579        assert!(
4580            inputs.iter().any(|i| i == "count"),
4581            "metric `value: count` should force the `count` magic-extern \
4582             input slot to be allocated under Release opt level; \
4583             inputs were: {inputs:?}"
4584        );
4585        // And the synthesised binding shows up as an output the
4586        // MetricsDispenser will read at cycle time.
4587        let outs = kernel.program().output_names();
4588        let synth = synthesize_metric_binding_name("rows_per_op");
4589        assert!(
4590            outs.iter().any(|o| o == &synth),
4591            "synthesised `{synth}` binding should be a kernel output; \
4592             outputs were: {outs:?}"
4593        );
4594    }
4595
4596    #[test]
4597    fn promoted_final_emits_inline_literal_for_str() {
4598        // SRD-13f case 1 — when a referenced name is `final`
4599        // upstream and a Str, the synthesizer emits
4600        // `const name := "value"` in the child's source rather
4601        // than auto-externing it.
4602        let parent = crate::scope_kernel::ScopeKernel::compile(
4603            "input cycle: u64\nconst dataset := \"example\"\n",
4604        )
4605        .expect("compile parent");
4606        let manifest: Vec<crate::runner::ManifestEntry> =
4607            polydat::kernel::extract_manifest(parent.program())
4608                .into_iter()
4609                .map(|e| crate::runner::ManifestEntry {
4610                    name: e.name,
4611                    port_type: e.port_type,
4612                    modifier: e.modifier,
4613                })
4614                .collect();
4615        let ops = vec![make_polydat_op("step", "x={dataset}", "input cycle: u64")];
4616        let scope = build_scope(
4617            &ops,
4618            &HashMap::new(),
4619            &manifest,
4620            &HashMap::new(),
4621            &HashMap::new(),
4622            None,
4623            &[],
4624            Some(&parent),
4625        )
4626        .expect("build_scope");
4627        let emitted = scope.emit();
4628        assert!(
4629            emitted.contains("const dataset := \"example\""),
4630            "expected promoted-final emission, got:\n{emitted}"
4631        );
4632        assert!(
4633            !emitted.contains("extern dataset"),
4634            "expected no extern for promoted-final dataset, got:\n{emitted}"
4635        );
4636    }
4637
4638    #[test]
4639    fn promoted_final_emits_inline_literal_for_u64() {
4640        let parent =
4641            crate::scope_kernel::ScopeKernel::compile("input cycle: u64\nconst count := 42\n")
4642                .expect("compile parent");
4643        let manifest: Vec<crate::runner::ManifestEntry> =
4644            polydat::kernel::extract_manifest(parent.program())
4645                .into_iter()
4646                .map(|e| crate::runner::ManifestEntry {
4647                    name: e.name,
4648                    port_type: e.port_type,
4649                    modifier: e.modifier,
4650                })
4651                .collect();
4652        let ops = vec![make_polydat_op("step", "n={count}", "input cycle: u64")];
4653        let scope = build_scope(
4654            &ops,
4655            &HashMap::new(),
4656            &manifest,
4657            &HashMap::new(),
4658            &HashMap::new(),
4659            None,
4660            &[],
4661            Some(&parent),
4662        )
4663        .expect("build_scope");
4664        let emitted = scope.emit();
4665        assert!(
4666            emitted.contains("const count := 42"),
4667            "expected promoted-final u64 emission, got:\n{emitted}"
4668        );
4669    }
4670
4671    #[test]
4672    fn unresolved_wire_reference_surfaces_validation_error() {
4673        // SRD-13f case 4 — a typo in a `{...}` placeholder (here
4674        // `{tirp}` instead of the declared `trip`) is rejected
4675        // at the synthesizer level with a structured error,
4676        // not via a downstream Polydat compiler error.
4677        let parent = crate::scope_kernel::ScopeKernel::compile(
4678            "input cycle: u64\nconst dataset := \"example\"\n",
4679        )
4680        .expect("compile parent");
4681        let manifest: Vec<crate::runner::ManifestEntry> =
4682            polydat::kernel::extract_manifest(parent.program())
4683                .into_iter()
4684                .map(|e| crate::runner::ManifestEntry {
4685                    name: e.name,
4686                    port_type: e.port_type,
4687                    modifier: e.modifier,
4688                })
4689                .collect();
4690        let ops = vec![make_polydat_op("step", "x={tirp}", "input cycle: u64")];
4691        let err = match build_scope(
4692            &ops,
4693            &HashMap::new(),
4694            &manifest,
4695            &HashMap::new(),
4696            &HashMap::new(),
4697            None,
4698            &[],
4699            Some(&parent),
4700        ) {
4701            Ok(_) => panic!("expected unresolved-wire error, got Ok"),
4702            Err(e) => e,
4703        };
4704        assert!(err.contains("unresolved wire"), "wrong error: {err}");
4705        assert!(
4706            err.contains("tirp"),
4707            "error should mention the typoed name: {err}"
4708        );
4709        assert!(
4710            err.contains("Visible names"),
4711            "error should list visible names: {err}"
4712        );
4713    }
4714
4715    #[test]
4716    fn overloaded_call_head_is_not_an_unresolved_wire() {
4717        // `vec_norm` is an overloaded name: the registry lists only its
4718        // typed forms (`vec_norm_f32`, `vec_norm_f64`), so a check that
4719        // asks the registry for the bare name alone would report the
4720        // call head as an unresolved wire.
4721        let parent = crate::scope_kernel::ScopeKernel::compile("input cycle: u64\n")
4722            .expect("compile parent");
4723        let manifest: Vec<crate::runner::ManifestEntry> =
4724            polydat::kernel::extract_manifest(parent.program())
4725                .into_iter()
4726                .map(|e| crate::runner::ManifestEntry {
4727                    name: e.name,
4728                    port_type: e.port_type,
4729                    modifier: e.modifier,
4730                })
4731                .collect();
4732        let ops = vec![make_polydat_op(
4733            "step",
4734            "x={n}",
4735            "input cycle: u64\nv := str_to_vec_f32(\"[3.0, 4.0]\")\nn := vec_norm(v)",
4736        )];
4737        if let Err(err) = build_scope(
4738            &ops,
4739            &HashMap::new(),
4740            &manifest,
4741            &HashMap::new(),
4742            &HashMap::new(),
4743            None,
4744            &[],
4745            Some(&parent),
4746        ) {
4747            panic!("an overloaded call head must resolve as a function: {err}");
4748        }
4749    }
4750
4751    #[test]
4752    fn ingest_preserves_bindings_when_comment_contains_apostrophe() {
4753        // Regression: Polydat grammar uses only `"`-delimited string
4754        // literals. `logical_lines` previously treated `'` as a
4755        // string delimiter too, which meant an unmatched
4756        // apostrophe in a `#` comment (e.g. "the workload's
4757        // bindings") put the splitter into a string state that
4758        // never closed. The entire rest of the source was
4759        // accreted into one logical "line" starting with `#`,
4760        // which then got dropped as a comment by the per-line
4761        // parser — silently discarding every binding that
4762        // followed.
4763        //
4764        // This was the actual root cause of the full_cql_vector
4765        // `await_index` failure: the workload's
4766        // `bindings:` block began with a multi-line comment
4767        // containing the apostrophe in "full_cql_vector's", so
4768        // the `shared has_X := false` declarations never made
4769        // it into the workload-root program. Descendant
4770        // synthesizers then couldn't cascade has_X as Bool
4771        // externs; the compile inferred has_X as Coordinate
4772        // U64 inputs from unbound references, and the
4773        // per-cycle `set_inputs(&[u64])` clobbered the
4774        // SharedCell with `Value::U64(cycle)`.
4775        let mut scope = BindingScope::new();
4776        let src_with_apostrophe_comment = "# full_cql_vector's bindings block\n\
4777                                           shared has_a := true\n\
4778                                           shared has_b := false\n";
4779        scope.ingest_polydat_source(src_with_apostrophe_comment, BindingOrigin::Inherited);
4780        let defined = scope.defined_names();
4781        assert!(
4782            defined.contains("has_a"),
4783            "comment with apostrophe must NOT consume subsequent bindings; \
4784             expected has_a in defined names, got {defined:?}"
4785        );
4786        assert!(
4787            defined.contains("has_b"),
4788            "expected has_b in defined names, got {defined:?}"
4789        );
4790
4791        let emitted = scope.emit();
4792        assert!(
4793            emitted.contains("shared has_a := true"),
4794            "scope.emit() must include the shared bindings; got:\n{emitted}"
4795        );
4796        assert!(
4797            emitted.contains("shared has_b := false"),
4798            "scope.emit() must include the shared bindings; got:\n{emitted}"
4799        );
4800    }
4801
4802    #[test]
4803    fn ingest_then_compile_preserves_shared_modifier() {
4804        // Mirrors the workload-root compile path in
4805        // `compile_bindings_with_libs_excluding`: workload-level
4806        // bindings (`shared has_X := false`) get ingested via
4807        // `scope.ingest_polydat_source(..., Inherited)` before emit.
4808        // The resulting source then compiles via the
4809        // standard pipeline.
4810        //
4811        // SRD-13c §"Shared Mutable": `shared X := <literal>`
4812        // compiles to an input slot + passthrough output marked
4813        // SHARED. The workload-root program's `shared_outputs()`
4814        // must include the SHARED-modifier outputs so
4815        // `seed_shared_cells` creates a `SharedCell` for each
4816        // and descendant kernels can cell-attach via
4817        // `materialize_wiring_from_outer`.
4818        let mut scope = BindingScope::new();
4819        let workload_polydat = "shared has_sai_column_indexes := false\n\
4820                          shared has_indexes := false\n";
4821        scope.ingest_polydat_source(workload_polydat, BindingOrigin::Inherited);
4822        let source = scope.emit();
4823        let kernel = crate::scope_kernel::ScopeKernel::compile(&source)
4824            .unwrap_or_else(|e| panic!("compile failed for source:\n{source}\nerror: {e}"));
4825        let shared = kernel.program().shared_outputs();
4826        assert!(
4827            shared.contains(&"has_sai_column_indexes"),
4828            "expected `has_sai_column_indexes` in shared_outputs after scope-ingest/emit/compile;\n\
4829             got shared_outputs={shared:?}\nemitted source:\n{source}",
4830        );
4831        assert!(
4832            shared.contains(&"has_indexes"),
4833            "expected `has_indexes` in shared_outputs after scope-ingest/emit/compile;\n\
4834             got shared_outputs={shared:?}\nemitted source:\n{source}",
4835        );
4836    }
4837
4838    /// SRD-75 Push 2: `synthesize_phase_scope_bindings`
4839    /// returns the original bindings unchanged when
4840    /// `phase.poll` is `None`. The function is a no-op for
4841    /// non-poll phases; their synthesis path is unaffected.
4842    #[test]
4843    fn synthesize_phase_scope_bindings_passthrough_when_no_poll() {
4844        use nmbrs_workload::model::{BindingsDef, WorkloadPhase};
4845        let phase = WorkloadPhase {
4846            bindings: BindingsDef::PolydatSource("k := 5\n".into()),
4847            poll: None,
4848            ..Default::default()
4849        };
4850        let out = synthesize_phase_scope_bindings(&phase).expect("no-poll synthesis is a no-op");
4851        match out {
4852            BindingsDef::PolydatSource(s) => assert_eq!(
4853                s, "k := 5\n",
4854                "no-poll should return the original bindings unchanged"
4855            ),
4856            other => panic!("expected PolydatSource, got {other:?}"),
4857        }
4858    }
4859
4860    /// A metric's `cell:` is reified as a compiled kernel binding beside its
4861    /// value — the whole point of the design. If this did not compile, a
4862    /// coordinate would have to be a runtime string, which is the
4863    /// unvalidatable shape the proposal exists to avoid.
4864    #[test]
4865    fn phase_metrics_reify_cell_coordinates_as_kernel_bindings() {
4866        use nmbrs_workload::model::{BindingsDef, MetricSpec, WorkloadPhase};
4867        let mut metrics = std::collections::HashMap::new();
4868        let mut cell = std::collections::BTreeMap::new();
4869        cell.insert("tier".to_string(), "tier_name".to_string());
4870        metrics.insert(
4871            "bytes_out".to_string(),
4872            MetricSpec {
4873                value: "history_bytes_out".into(),
4874                family: None,
4875                kind: None,
4876                unit: None,
4877                format: None,
4878                cell,
4879            },
4880        );
4881        let phase = WorkloadPhase {
4882            bindings: BindingsDef::PolydatSource(
4883                "extern tier_name: str = \"\"\n\
4884                 extern history_bytes_out: u64 = 0\n"
4885                    .into(),
4886            ),
4887            metrics,
4888            poll: None,
4889            ..Default::default()
4890        };
4891        let out = synthesize_phase_scope_bindings(&phase).expect("synthesis");
4892        let src = match out {
4893            BindingsDef::PolydatSource(s) => s,
4894            other => panic!("expected PolydatSource, got {other:?}"),
4895        };
4896        assert!(
4897            src.contains("volatile __cell_bytes_out__tier := tier_name"),
4898            "coordinate must be emitted as a volatile binding; got:\n{src}"
4899        );
4900        assert!(
4901            src.contains("volatile __metric_bytes_out := history_bytes_out"),
4902            "the value binding must still be emitted; got:\n{src}"
4903        );
4904    }
4905
4906    /// Per (metric, dimension), not per dimension: two metrics placing into
4907    /// one dimension by different expressions must not collide on a wire name
4908    /// and silently let one placement win.
4909    #[test]
4910    fn two_metrics_in_one_dimension_get_distinct_coordinate_wires() {
4911        assert_eq!(
4912            synthesize_cell_binding_name("bytes_out", "tier"),
4913            "__cell_bytes_out__tier"
4914        );
4915        assert_ne!(
4916            synthesize_cell_binding_name("bytes_out", "tier"),
4917            synthesize_cell_binding_name("bytes_in", "tier")
4918        );
4919    }
4920
4921    /// A phase with a `metrics:` block (and no poll) synthesises a
4922    /// `volatile phase_start := phase_start_millis()` origin binding plus one
4923    /// `volatile __metric_<name> := <value>` per metric. The phase's own
4924    /// bindings are appended verbatim.
4925    ///
4926    /// `phase_start` was an `extern … = 0` filled by the executor at the
4927    /// completion-time pull, which meant anything reading it while the phase
4928    /// ran got the default.
4929    #[test]
4930    fn synthesize_phase_scope_bindings_emits_metric_bindings() {
4931        use nmbrs_workload::model::{BindingsDef, MetricSpec, WorkloadPhase};
4932        let mut metrics = std::collections::HashMap::new();
4933        metrics.insert(
4934            "time_to_index".to_string(),
4935            MetricSpec {
4936                value: "current_epoch_millis() - phase_start".into(),
4937                family: None,
4938                kind: None,
4939                unit: None,
4940                format: None,
4941                cell: Default::default(),
4942            },
4943        );
4944        let phase = WorkloadPhase {
4945            bindings: BindingsDef::default(),
4946            metrics,
4947            poll: None,
4948            ..Default::default()
4949        };
4950        let out = synthesize_phase_scope_bindings(&phase).expect("metrics synthesis");
4951        let src = match out {
4952            BindingsDef::PolydatSource(s) => s,
4953            other => panic!("expected PolydatSource, got {other:?}"),
4954        };
4955        // Bound to the runtime's phase clock, NOT an extern: as an extern it
4956        // was filled only at the completion-time pull, so anything reading it
4957        // while the phase ran (an op) got the 0 default and computed against
4958        // the epoch.
4959        assert!(
4960            src.contains("volatile phase_start := phase_start_millis()"),
4961            "must bind phase_start to the phase-scoped clock; got:\n{src}"
4962        );
4963        assert!(
4964            !src.contains("extern phase_start"),
4965            "the fill-me-in extern must be gone; got:\n{src}"
4966        );
4967        assert!(
4968            src.contains("volatile __metric_time_to_index := current_epoch_millis() - phase_start"),
4969            "must emit the volatile metric binding; got:\n{src}"
4970        );
4971        // The emitted source must compile as a phase kernel body, with
4972        // `__metric_time_to_index` surfacing as an output.
4973        let kernel = crate::scope_kernel::ScopeKernel::compile(&src)
4974            .unwrap_or_else(|e| panic!("compile failed:\n{src}\nerror: {e}"));
4975        assert!(
4976            kernel
4977                .program()
4978                .output_names()
4979                .contains(&"__metric_time_to_index"),
4980            "metric binding must be a kernel output; outputs: {:?}",
4981            kernel.program().output_names()
4982        );
4983    }
4984
4985    /// SRD-75 Push 2: when a phase has `poll:` and ops with
4986    /// declared captures, the synthesized source carries one
4987    /// `shared <name>: u64 := 0` declaration per capture
4988    /// followed by the predicate binding `__poll_until :=
4989    /// <until>`. The original phase bindings (if any) are
4990    /// appended verbatim between the captures and the
4991    /// predicate.
4992    #[test]
4993    fn synthesize_phase_scope_bindings_emits_shared_captures_and_predicate() {
4994        use nmbrs_workload::bindpoints::CapturePoint;
4995        use nmbrs_workload::model::{BindingsDef, ParsedOp, PhasePollSpec, WorkloadPhase};
4996        let mut op = ParsedOp::simple("read_state", "noop");
4997        op.captures = vec![
4998            CapturePoint {
4999                row_filter: None,
5000                source_name: "sstables".into(),
5001                as_name: "sstables".into(),
5002                cast_type: None,
5003                slurp: false,
5004                path: Some("/0/value".into()),
5005                count: false,
5006                agg: None,
5007            },
5008            CapturePoint {
5009                row_filter: None,
5010                source_name: "active_for_cf".into(),
5011                as_name: "active_for_cf".into(),
5012                cast_type: None,
5013                slurp: false,
5014                path: Some("/1/value".into()),
5015                count: true,
5016                agg: None,
5017            },
5018        ];
5019        let phase = WorkloadPhase {
5020            ops: vec![op],
5021            bindings: BindingsDef::PolydatSource("dummy := 1\n".into()),
5022            poll: Some(PhasePollSpec {
5023                until: "sstables == 1 && active_for_cf == 0".into(),
5024                ..Default::default()
5025            }),
5026            ..Default::default()
5027        };
5028        let out = synthesize_phase_scope_bindings(&phase).expect("poll synthesis should succeed");
5029        let src = match out {
5030            BindingsDef::PolydatSource(s) => s,
5031            other => panic!("expected PolydatSource, got {other:?}"),
5032        };
5033        assert!(
5034            src.contains("shared sstables := 0"),
5035            "missing shared declaration for sstables; source:\n{src}"
5036        );
5037        assert!(
5038            src.contains("shared active_for_cf := 0"),
5039            "missing shared declaration for active_for_cf; source:\n{src}"
5040        );
5041        assert!(
5042            src.contains("dummy := 1"),
5043            "original phase bindings should appear verbatim; source:\n{src}"
5044        );
5045        assert!(
5046            src.contains("__poll_until := sstables == 1 && active_for_cf == 0"),
5047            "missing __poll_until predicate binding; source:\n{src}"
5048        );
5049        // Order matters: captures first (so the predicate's
5050        // RHS references resolve through the local shared
5051        // declarations before the dynamic binding evaluates).
5052        let shared_pos = src
5053            .find("shared sstables")
5054            .expect("shared sstables present");
5055        let until_binding = crate::wrappers::condition::UNTIL_BINDING;
5056        let until_pos = src
5057            .find(until_binding)
5058            .expect("poll predicate binding present");
5059        assert!(
5060            shared_pos < until_pos,
5061            "shared captures must precede __poll_until in the synthesized source"
5062        );
5063    }
5064
5065    /// SRD-75 Push 2: a capture name that collides with an
5066    /// author-declared phase binding is a workload bug —
5067    /// the synthesizer surfaces the collision rather than
5068    /// silently shadowing.
5069    #[test]
5070    fn synthesize_phase_scope_bindings_rejects_capture_name_collision() {
5071        use nmbrs_workload::bindpoints::CapturePoint;
5072        use nmbrs_workload::model::{BindingsDef, ParsedOp, PhasePollSpec, WorkloadPhase};
5073        let mut op = ParsedOp::simple("read_state", "noop");
5074        op.captures = vec![CapturePoint {
5075            row_filter: None,
5076            source_name: "sstables".into(),
5077            as_name: "sstables".into(),
5078            cast_type: None,
5079            slurp: false,
5080            path: Some("/0/value".into()),
5081            count: false,
5082            agg: None,
5083        }];
5084        // Phase author also declared `sstables := …` —
5085        // collision is the bug.
5086        let phase = WorkloadPhase {
5087            ops: vec![op],
5088            bindings: BindingsDef::PolydatSource("sstables := 7\n".into()),
5089            poll: Some(PhasePollSpec {
5090                until: "sstables == 1".into(),
5091                ..Default::default()
5092            }),
5093            ..Default::default()
5094        };
5095        let err =
5096            synthesize_phase_scope_bindings(&phase).expect_err("colliding capture name must error");
5097        assert!(
5098            err.contains("sstables") && err.contains("collision"),
5099            "expected error to name 'sstables' and 'collision'; got: {err}"
5100        );
5101    }
5102
5103    #[test]
5104    fn build_phase_scope_kernel_with_mod_in_binding_over_partition_iter_var() {
5105        // Matches the production workload shape:
5106        //   for: "p in partitions(\"linear:3\")"
5107        //   phases.walk.bindings: n := mod_in(cycle, p)
5108        //
5109        // The phase compile must see `p` as Ext so mod_in's
5110        // second arg (Partition input) type-checks. Reproduces
5111        // the integration error "u64 ─▶ ext expects ext".
5112        let parent_kernel = crate::scope_synth::build_for_each_scope_kernel(
5113            &[("p".to_string(), "partitions(\"linear:3\")".to_string())],
5114            &[],
5115            &crate::scope_kernel::ScopeKernel::compile("\n").unwrap(),
5116            &HashMap::new(),
5117            Vec::new(),
5118            None,
5119            false,
5120            "test_for_each",
5121            None,
5122        )
5123        .expect("for-each scope synthesis");
5124
5125        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5126            "n := mod_in(cycle, p)\n".to_string(),
5127        );
5128        let phase_kernel = build_phase_scope_kernel(
5129            &phase_bindings,
5130            &[],
5131            &parent_kernel,
5132            &HashMap::new(),
5133            Vec::new(),
5134            None,
5135            false,
5136            "test_phase",
5137        )
5138        .expect("phase kernel build with mod_in(cycle, p) binding");
5139
5140        // Sanity: phase has p as Ext-typed input slot.
5141        assert_eq!(
5142            phase_kernel.program().input_port_type("p"),
5143            Some(polydat::ast::PortType::Ext),
5144            "phase kernel's `p` must be Ext-typed",
5145        );
5146        // Sanity: phase has `n` as an output (the mod_in result).
5147        assert!(
5148            phase_kernel.program().output_names().contains(&"n"),
5149            "phase kernel should expose `n` as an output"
5150        );
5151    }
5152
5153    #[test]
5154    fn build_phase_scope_kernel_cascades_partition_iter_var_as_extern_ext() {
5155        // SRD-71: when a for-each scope iterates a PartitionList
5156        // and binds an iter-var `p`, descendant phases must see
5157        // `p` as `extern p: ext` — NOT cast to str / u64 by
5158        // the cascade. The phase body's `over p` clause then
5159        // resolves `p` as a partition-typed wire.
5160        //
5161        // Reproduces the integration failure where the phase's
5162        // build_phase_scope_kernel cascade was emitting
5163        // `extern p: u64` (or Str fallback) because the
5164        // type-name lookup didn't handle PortType::Ext.
5165        let parent_kernel = crate::scope_synth::build_for_each_scope_kernel(
5166            &[("p".to_string(), "partitions(\"linear:3\")".to_string())],
5167            &[], // empty parent_manifest is fine; for_each scope only
5168            // cascades names it actually references.
5169            &crate::scope_kernel::ScopeKernel::compile("\n").unwrap(),
5170            &HashMap::new(),
5171            Vec::new(),
5172            None,
5173            false,
5174            "test_for_each",
5175            None,
5176        )
5177        .expect("for-each scope synthesis");
5178
5179        // Sanity: the for-each scope's iter-var p is Ext-typed.
5180        assert_eq!(
5181            parent_kernel.program().input_port_type("p"),
5182            Some(polydat::ast::PortType::Ext),
5183            "for-each scope's iter-var `p` must declare as Ext",
5184        );
5185
5186        // Now build a phase under it that references `p` in a
5187        // cursor's `over` clause.
5188        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5189            "cursor row = range(0, 1000) over p\n".to_string(),
5190        );
5191        let phase_kernel = build_phase_scope_kernel(
5192            &phase_bindings,
5193            &[],
5194            &parent_kernel,
5195            &HashMap::new(),
5196            Vec::new(),
5197            None,
5198            false,
5199            "test_phase",
5200        )
5201        .expect("phase kernel build");
5202
5203        // The phase kernel must see `p` as Ext-typed.
5204        let port_type = phase_kernel.program().input_port_type("p");
5205        assert_eq!(
5206            port_type,
5207            Some(polydat::ast::PortType::Ext),
5208            "phase kernel's `p` slot must be Ext (preserved through cascade), got {port_type:?}"
5209        );
5210    }
5211
5212    #[test]
5213    fn build_phase_scope_kernel_cascades_shared_bool_as_extern_bool() {
5214        // SRD-13d §1: "The kernel auto-externs every name it
5215        // doesn't declare locally; those externs resolve up
5216        // through the phase kernel and beyond per the standard
5217        // SRD-13c chain."
5218        //
5219        // SRD-66 §"Surface 2": a workload-root `shared X :=
5220        // <literal>` becomes a `SharedCell`-backed slot at the
5221        // root. Descendant phases declare `extern X: bool` (or
5222        // auto-extern emits it); bind_outer_scope cell-attaches
5223        // the slot.
5224        //
5225        // SRD-13c §"Shared Mutable" step 1: `shared X := <literal>`
5226        // produces an input slot Bool (kind=ExternalWrite) plus a
5227        // passthrough output Bool, modifier SHARED.
5228        //
5229        // This unit-test verifies the documented type-preservation
5230        // contract: a phase scope built via build_phase_scope_kernel
5231        // against a parent kernel carrying a SHARED Bool output
5232        // must produce a phase-scope kernel whose has_X input slot
5233        // is type Bool, NOT typed U64 / not classified Coordinate.
5234        // Without this property, the SharedCell that bind_outer_scope
5235        // attaches gets a slot whose declared type doesn't match
5236        // the cell's actual Value variant — downstream consumers
5237        // (e.g. pick) see the runtime variant and reject it.
5238        let parent = crate::scope_kernel::ScopeKernel::compile(
5239            "input cycle: u64\nshared has_sai_column_indexes := false\n\
5240             shared has_indexes := false\n",
5241        )
5242        .expect("parent compile");
5243        // The phase has its own bindings block (the await_index shape).
5244        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5245            "target_index_table := pick(has_sai_column_indexes, has_indexes, \
5246             \"a\", \"b\")\n"
5247                .to_string(),
5248        );
5249        let phase_kernel = build_phase_scope_kernel(
5250            &phase_bindings,
5251            &[], // outer_manifest (would be populated in real runner, but builder doesn't strictly need it)
5252            &parent,
5253            &HashMap::new(),
5254            Vec::new(),
5255            None,
5256            false,
5257            "test_phase",
5258        )
5259        .expect("phase kernel build");
5260
5261        // The phase kernel must have has_X as an input slot.
5262        let idx_sai = phase_kernel.program().find_input("has_sai_column_indexes");
5263        assert!(
5264            idx_sai.is_some(),
5265            "phase kernel must have `has_sai_column_indexes` input slot"
5266        );
5267        let idx = idx_sai.unwrap();
5268
5269        // Type must be Bool (per SRD-13c §"Shared Mutable" step 1
5270        // + SRD-66 §"Reading from a downstream phase").
5271        let port_type = phase_kernel
5272            .program()
5273            .input_port_type("has_sai_column_indexes");
5274        assert_eq!(
5275            port_type,
5276            Some(polydat::ast::PortType::Bool),
5277            "phase kernel's has_sai_column_indexes slot must be Bool, got {port_type:?}"
5278        );
5279
5280        // Kind must NOT be Coordinate — cascaded names are IterationExtern
5281        // (or ExternalWrite), not Coordinate. Coordinate would put the slot
5282        // in the set_inputs(&[u64]) propagation, breaking the cell-bound
5283        // contract per SRD-13c §"Shared Mutable" step 3.
5284        let kind = phase_kernel.program().input_kind(idx);
5285        assert_ne!(
5286            kind,
5287            Some(polydat::kernel::InputKind::Coordinate),
5288            "phase kernel's has_sai_column_indexes slot must NOT be Coordinate; got {kind:?}"
5289        );
5290    }
5291
5292    #[test]
5293    fn executor_build_scope_emits_extern_bool_for_cell_backed_shared_wire() {
5294        // Reproduces the executor's specific build_scope call
5295        // sequence for the consume phase:
5296        //
5297        //   1. Build the phase scope kernel via build_phase_scope_kernel
5298        //      (this is what the runner's install pass does).
5299        //   2. Call build_scope(ops, ..., parent_kernel=phase_scope)
5300        //      with phase_scope as classifier_kernel — this is
5301        //      what executor.rs:1429 does at run_phase time.
5302        //   3. compile_from_scope(scope, ...) — produces the
5303        //      iter_op_builder kernel that dryrun=wiring dumps.
5304        //
5305        // The integration test
5306        // `shared_bool_through_for_each_into_consumer_phase_bindings`
5307        // proves this whole sequence produces a kernel with has_X
5308        // as `coordinate` U64. This unit test reproduces it without
5309        // a subprocess so we can inspect every intermediate state.
5310        use polydat::kernel::extract_manifest;
5311
5312        // ── workload root ──
5313        let root = crate::scope_kernel::ScopeKernel::compile(
5314            "shared has_a := true\n\
5315             shared has_b := false\n\
5316             selector := mod(cycle, 1)\n",
5317        )
5318        .expect("workload root compile");
5319
5320        // ── for_each scope ──
5321        let for_each = crate::scope_synth::build_for_each_scope_kernel(
5322            &[("outer".to_string(), "p1,p2".to_string())],
5323            &extract_manifest(root.program()),
5324            &root,
5325            &HashMap::new(),
5326            Vec::new(),
5327            None,
5328            false,
5329            "test_for_each",
5330            None,
5331        )
5332        .expect("for_each synth");
5333
5334        // ── phase scope kernel (cached_kernel) ──
5335        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5336            "chosen := pick(has_a, has_b, \"alpha\", \"beta\")\n".to_string(),
5337        );
5338        let phase_scope = build_phase_scope_kernel(
5339            &phase_bindings,
5340            &[],
5341            &for_each,
5342            &HashMap::new(),
5343            Vec::new(),
5344            None,
5345            false,
5346            "test_phase",
5347        )
5348        .expect("phase scope synth");
5349
5350        // ── executor's build_scope call ──
5351        let op = ParsedOp::simple("report", "consume chosen={chosen}");
5352        let ops = vec![op];
5353        let effective_manifest: Vec<crate::runner::ManifestEntry> =
5354            extract_manifest(phase_scope.program())
5355                .into_iter()
5356                .map(|e| crate::runner::ManifestEntry {
5357                    name: e.name,
5358                    port_type: e.port_type,
5359                    modifier: e.modifier,
5360                })
5361                .collect();
5362        let scope = build_scope(
5363            &ops,
5364            &HashMap::new(),
5365            &effective_manifest,
5366            &HashMap::new(),
5367            &HashMap::new(),
5368            None,
5369            &[],
5370            Some(&phase_scope),
5371        )
5372        .expect("executor build_scope");
5373
5374        // ── inspect what build_scope emits ──
5375        let emitted = scope.emit();
5376
5377        // ── compile_from_scope equivalent — uses the SAME compile
5378        // path the executor takes (compile_polydat_interpreter_with_options with
5379        // the scope's required_outputs filter).
5380        let required = scope.required_outputs();
5381        let executor_kernel = polydat::dsl::compile::compile_polydat_interpreter_with_options(
5382            &emitted,
5383            &polydat::dsl::compile::CompileOptions {
5384                required_outputs: required.clone(),
5385                context: "test".to_string(),
5386                ..Default::default()
5387            },
5388            None,
5389        )
5390        .unwrap_or_else(|e| {
5391            panic!("compile failed: {e}\nemitted source:\n{emitted}\nrequired: {required:?}")
5392        });
5393
5394        // The executor's kernel must have has_a as Bool (or absent
5395        // entirely if not referenced). It MUST NOT be Coordinate U64.
5396        if let Some(idx) = executor_kernel.program().find_input("has_a") {
5397            let typ = executor_kernel.program().input_port_type("has_a");
5398            assert_eq!(
5399                typ,
5400                Some(polydat::ast::PortType::Bool),
5401                "executor kernel's has_a slot must be Bool;\n\
5402                 got {typ:?}\n\
5403                 emitted source:\n{emitted}\n\
5404                 input names: {:?}\n\
5405                 coord_count: {}",
5406                executor_kernel.program().input_names(),
5407                executor_kernel.program().coord_count()
5408            );
5409            let kind = executor_kernel.program().input_kind(idx);
5410            assert_ne!(
5411                kind,
5412                Some(polydat::kernel::InputKind::Coordinate),
5413                "executor kernel's has_a slot must NOT be Coordinate;\n\
5414                 got {kind:?}\n\
5415                 emitted source:\n{emitted}\n\
5416                 input names: {:?}\n\
5417                 coord_count: {}",
5418                executor_kernel.program().input_names(),
5419                executor_kernel.program().coord_count()
5420            );
5421        }
5422    }
5423
5424    #[test]
5425    fn full_chain_workload_to_executor_scope_preserves_shared_bool() {
5426        // Chains through every layer the failing integration test
5427        // touches, in-process, with the same shape that triggers
5428        // the failure:
5429        //
5430        //   1. params kernel (workload params as `const` bindings).
5431        //   2. workload-root kernel via the `compile_bindings_with_libs_excluding`-style
5432        //      flow: build_scope + scope.ingest_polydat_source + parent.build_subscope.
5433        //   3. for_each scope kernel (outer iter var).
5434        //   4. for_each scope kernel (inner with multi-iter clause).
5435        //   5. phase scope kernel via build_phase_scope_kernel (consume).
5436        //   6. executor's build_scope + compile_polydat_with_libs_and_limit.
5437        //
5438        // Verifies at the END that the consumer phase's executor-
5439        // compiled kernel has has_a as Bool/non-Coordinate.
5440        use nmbrs_workload::model::ParsedOp;
5441        use polydat::kernel::extract_manifest;
5442
5443        // Step 1: params kernel.
5444        let mut workload_params: HashMap<String, String> = HashMap::new();
5445        workload_params.insert("dataset".to_string(), "example_dataset".to_string());
5446        workload_params.insert("prefix".to_string(), "px_".to_string());
5447        let mut sorted: Vec<&String> = workload_params.keys().collect();
5448        sorted.sort();
5449        let mut params_source = String::new();
5450        for k in sorted {
5451            params_source.push_str(&format!("const {k} := \"{}\"\n", workload_params[k]));
5452        }
5453        let params_kernel =
5454            crate::scope_kernel::ScopeKernel::compile(&params_source).expect("params compile");
5455
5456        // Step 2: workload-root kernel.
5457        let mut scope = build_scope(
5458            &[] as &[ParsedOp],
5459            &HashMap::new(),
5460            &[],
5461            &workload_params,
5462            &HashMap::new(),
5463            None,
5464            &[],
5465            None,
5466        )
5467        .expect("workload root build_scope");
5468        // KEY: the binding RHS uses string interpolation against
5469        // workload params. This is what triggers the chain
5470        // corruption — without it, the test passes; with it, the
5471        // integration test fails.
5472        let workload_level_polydat = "combo_label := str_concat(\"{dataset}\", \"{prefix}\")\n\
5473                                 shared has_a := true\n\
5474                                 shared has_b := false\n";
5475        scope.ingest_polydat_source(workload_level_polydat, BindingOrigin::Inherited);
5476        let root_source = scope.emit();
5477        let root = crate::scope_kernel::ScopeKernel::build_under(
5478            params_kernel.kernel(),
5479            crate::scope_kernel::SourceMatter::source(
5480                "test_root",
5481                root_source.clone(),
5482                polydat::kernel::subcontext::CompileOptions {
5483                    workload_dir: None,
5484                    polydat_lib_paths: Vec::new(),
5485                    strict: false,
5486                    required_outputs: scope.required_outputs(),
5487                    context_label: Some("test_root".to_string()),
5488                    cursor_limit: None,
5489                    ..Default::default()
5490                },
5491            ),
5492        )
5493        .expect("root build");
5494
5495        // Sanity: has_a SHARED at root.
5496        let shared = root.program().shared_outputs();
5497        assert!(
5498            shared.contains(&"has_a"),
5499            "root should have has_a as SHARED output; got {shared:?}"
5500        );
5501
5502        // Step 3: outer for_each scope.
5503        let outer_fe = crate::scope_synth::build_for_each_scope_kernel(
5504            &[("outer".to_string(), "p1,p2".to_string())],
5505            &extract_manifest(root.program()),
5506            &root,
5507            &workload_params,
5508            Vec::new(),
5509            None,
5510            false,
5511            "test_outer_fe",
5512            None,
5513        )
5514        .expect("outer for_each synth");
5515
5516        // Step 4: inner for_each scope (dependent multi-iter).
5517        let inner_fe = crate::scope_synth::build_for_each_scope_kernel(
5518            &[
5519                ("inner".to_string(), "lo,hi".to_string()),
5520                ("label".to_string(), "tag_p1_lo,tag_p1_hi".to_string()),
5521            ],
5522            &extract_manifest(outer_fe.program()),
5523            &outer_fe,
5524            &workload_params,
5525            Vec::new(),
5526            None,
5527            false,
5528            "test_inner_fe",
5529            None,
5530        )
5531        .expect("inner for_each synth");
5532
5533        // Step 5: phase scope kernel for consume.
5534        let phase_bindings = BindingsDef::PolydatSource(
5535            "chosen := pick(has_a, has_b, \"alpha\", \"beta\")\n".to_string(),
5536        );
5537        let phase_scope = build_phase_scope_kernel(
5538            &phase_bindings,
5539            &[],
5540            &inner_fe,
5541            &workload_params,
5542            Vec::new(),
5543            None,
5544            false,
5545            "test_consume_phase",
5546        )
5547        .expect("consume phase synth");
5548
5549        // Step 6: executor's build_scope on the consume phase.
5550        let op = ParsedOp::simple("report", "spc/consume chosen={chosen}");
5551        let ops = vec![op];
5552        let effective_manifest: Vec<crate::runner::ManifestEntry> =
5553            extract_manifest(phase_scope.program())
5554                .into_iter()
5555                .map(|e| crate::runner::ManifestEntry {
5556                    name: e.name,
5557                    port_type: e.port_type,
5558                    modifier: e.modifier,
5559                })
5560                .collect();
5561        let exec_scope = build_scope(
5562            &ops,
5563            &HashMap::new(),
5564            &effective_manifest,
5565            &HashMap::new(),
5566            &HashMap::new(),
5567            None,
5568            &[],
5569            Some(&phase_scope),
5570        )
5571        .expect("executor build_scope");
5572
5573        let exec_source = exec_scope.emit();
5574        let exec_kernel = polydat::dsl::compile::compile_polydat_interpreter_with_options(
5575            &exec_source,
5576            &polydat::dsl::compile::CompileOptions {
5577                required_outputs: exec_scope.required_outputs(),
5578                context: "test_executor".to_string(),
5579                ..Default::default()
5580            },
5581            None,
5582        )
5583        .unwrap_or_else(|e| panic!("exec compile failed: {e}\nexec source:\n{exec_source}"));
5584
5585        // The final kernel — what the dryrun=wiring dumps — must
5586        // have has_a as Bool/non-Coordinate.
5587        if let Some(idx) = exec_kernel.program().find_input("has_a") {
5588            let typ = exec_kernel.program().input_port_type("has_a");
5589            assert_eq!(
5590                typ,
5591                Some(polydat::ast::PortType::Bool),
5592                "FINAL kernel has_a must be Bool, got {typ:?}\n\
5593                 exec source:\n{exec_source}\n\
5594                 exec input_names: {:?}\n\
5595                 exec coord_count: {}",
5596                exec_kernel.program().input_names(),
5597                exec_kernel.program().coord_count()
5598            );
5599            let kind = exec_kernel.program().input_kind(idx);
5600            assert_ne!(
5601                kind,
5602                Some(polydat::kernel::InputKind::Coordinate),
5603                "FINAL kernel has_a must NOT be Coordinate, got {kind:?}\n\
5604                 exec source:\n{exec_source}\n\
5605                 exec input_names: {:?}\n\
5606                 exec coord_count: {}",
5607                exec_kernel.program().input_names(),
5608                exec_kernel.program().coord_count()
5609            );
5610        }
5611    }
5612
5613    #[test]
5614    fn workload_root_via_compile_bindings_preserves_shared_bool_type() {
5615        // Mirrors the runner's WORKLOAD-ROOT build flow:
5616        //   compile_bindings_with_libs_excluding(
5617        //     parent=params_kernel,
5618        //     ops=all_ops,
5619        //     workload_params=<non-empty>,
5620        //     workload_level_polydat=Some(<the bindings: block>),
5621        //   )
5622        //
5623        // The actual function takes a complex set of args; here
5624        // we replicate the essential moves to expose what differs
5625        // from a direct `compile_polydat_interpreter(source)` invocation.
5626        //
5627        // SRD-13c §"Shared Mutable" requires has_a to be ExternalWrite
5628        // kind, Bool type on the workload-root program. The
5629        // dryrun=wiring output of the failing integration test shows
5630        // the downstream phase has has_a as Coordinate U64, so
5631        // either the workload-root or a downstream synthesizer
5632        // emits the wrong source for it.
5633        use nmbrs_workload::model::ParsedOp;
5634
5635        let mut workload_params: HashMap<String, String> = HashMap::new();
5636        workload_params.insert("dataset".to_string(), "example_dataset".to_string());
5637        workload_params.insert("prefix".to_string(), "px_".to_string());
5638        workload_params.insert("keyspace".to_string(), "ks1".to_string());
5639        workload_params.insert("inner_options".to_string(), "lo,hi".to_string());
5640
5641        // Workload params reach the root via a sibling params
5642        // kernel. Construct one with each param as a final binding.
5643        let mut params_source = String::new();
5644        let mut sorted: Vec<&String> = workload_params.keys().collect();
5645        sorted.sort();
5646        for k in sorted {
5647            let v = &workload_params[k];
5648            params_source.push_str(&format!("const {k} := \"{v}\"\n"));
5649        }
5650        let params_kernel =
5651            crate::scope_kernel::ScopeKernel::compile(&params_source).expect("params compile");
5652
5653        // The workload's `bindings:` block. The trigger.
5654        let workload_level_polydat = "selector := mod(cycle, 1)\n\
5655                                 shared has_a := true\n\
5656                                 shared has_b := false\n";
5657
5658        // Build the workload-root scope as compile_bindings_with_libs_excluding does.
5659        let mut scope = build_scope(
5660            &[] as &[ParsedOp],
5661            &HashMap::new(),
5662            &[],
5663            &workload_params,
5664            &HashMap::new(),
5665            None,
5666            &[],
5667            None,
5668        )
5669        .expect("build_scope");
5670        scope.ingest_polydat_source(workload_level_polydat, BindingOrigin::Inherited);
5671
5672        // The actual workload-root compile goes through
5673        // parent.build_subscope. Build the matter and finalize.
5674        let source = scope.emit();
5675        let opts = polydat::kernel::subcontext::CompileOptions {
5676            workload_dir: None,
5677            polydat_lib_paths: Vec::new(),
5678            strict: false,
5679            required_outputs: scope.required_outputs(),
5680            context_label: Some("test_workload_root".to_string()),
5681            cursor_limit: None,
5682            ..Default::default()
5683        };
5684        let root = crate::scope_kernel::ScopeKernel::build_under(
5685            params_kernel.kernel(),
5686            crate::scope_kernel::SourceMatter::source("test_workload_root", source.clone(), opts),
5687        )
5688        .expect("workload root build");
5689
5690        // The workload-root program must have has_a:
5691        //   - present as an input slot,
5692        //   - typed Bool (SRD-13c §"Shared Mutable" step 1),
5693        //   - kind ExternalWrite (NOT Coordinate),
5694        //   - marked SHARED in output_modifier (so seed_shared_cells fires).
5695        let has_a_idx = root.program().find_input("has_a").unwrap_or_else(|| {
5696            panic!(
5697                "workload root missing has_a input;\n\
5698                 emitted scope source:\n{source}\n\
5699                 input names: {:?}",
5700                root.program().input_names()
5701            )
5702        });
5703
5704        let typ = root.program().input_port_type("has_a");
5705        assert_eq!(
5706            typ,
5707            Some(polydat::ast::PortType::Bool),
5708            "workload root has_a must be Bool;\n\
5709             got {typ:?}\n\
5710             emitted source:\n{source}\n\
5711             input names: {:?}\n\
5712             coord_count: {}",
5713            root.program().input_names(),
5714            root.program().coord_count()
5715        );
5716
5717        let kind = root.program().input_kind(has_a_idx);
5718        assert_ne!(
5719            kind,
5720            Some(polydat::kernel::InputKind::Coordinate),
5721            "workload root has_a must NOT be Coordinate;\n\
5722             got {kind:?}\n\
5723             emitted source:\n{source}\n\
5724             input names: {:?}\n\
5725             coord_count: {}",
5726            root.program().input_names(),
5727            root.program().coord_count()
5728        );
5729
5730        let modifier = root.program().output_modifier("has_a");
5731        assert_eq!(
5732            modifier,
5733            polydat::dsl::ast::BindingModifier::SHARED,
5734            "workload root has_a output must have SHARED modifier;\n\
5735             got {modifier:?}"
5736        );
5737
5738        let shared = root.program().shared_outputs();
5739        assert!(
5740            shared.contains(&"has_a"),
5741            "workload root must have has_a in shared_outputs (so seed_shared_cells creates a cell);\n\
5742             got shared_outputs={shared:?}"
5743        );
5744    }
5745
5746    #[test]
5747    fn shared_bool_survives_when_workload_root_also_has_cycle_binding() {
5748        // BISECTED INTEGRATION FAILURE: adding any non-shared
5749        // workload-level binding that references `cycle`
5750        // (e.g. `selector := mod(cycle, 1)`) alongside the
5751        // SHARED bool wires causes the consumer phase's phase
5752        // scope kernel to have has_X classified as Coordinate
5753        // input slots typed U64 instead of cascaded externs
5754        // typed Bool.
5755        //
5756        // Manifests at runtime as: per-cycle `set_inputs(&[u64])`
5757        // clobbers the shared cells with `Value::U64(cycle)`,
5758        // and `pick(has_X, …)` panics with "non-bool type U64".
5759        //
5760        // This unit test walks the same scope chain
5761        // programmatically and pins the contract at each hop:
5762        //   workload root (shared bool + cycle-referencing binding)
5763        //     → for_each scope (synthesize_for_each_scope)
5764        //       → phase scope (build_phase_scope_kernel)
5765        // Asserts has_a stays Bool + non-Coordinate kind at every
5766        // layer.
5767        use polydat::kernel::extract_manifest;
5768
5769        // Step 1: workload root with shared bool AND a
5770        // non-shared cycle binding. The trigger.
5771        let root = crate::scope_kernel::ScopeKernel::compile(
5772            "shared has_a := true\n\
5773             shared has_b := false\n\
5774             selector := mod(cycle, 1)\n",
5775        )
5776        .expect("workload root compile");
5777
5778        // Workload-root contract: has_a is Bool ExternalWrite slot
5779        // (SRD-13c §"Shared Mutable" step 1).
5780        let root_has_a_idx = root
5781            .program()
5782            .find_input("has_a")
5783            .expect("workload root has_a slot");
5784        let root_has_a_type = root.program().input_port_type("has_a");
5785        assert_eq!(
5786            root_has_a_type,
5787            Some(polydat::ast::PortType::Bool),
5788            "workload root has_a must be Bool"
5789        );
5790        let root_has_a_kind = root.program().input_kind(root_has_a_idx);
5791        assert_ne!(
5792            root_has_a_kind,
5793            Some(polydat::kernel::InputKind::Coordinate),
5794            "workload root has_a must NOT be Coordinate; got {root_has_a_kind:?}"
5795        );
5796
5797        // Step 2: for_each scope.
5798        let for_each = crate::scope_synth::build_for_each_scope_kernel(
5799            &[("outer".to_string(), "p1,p2".to_string())],
5800            &extract_manifest(root.program()),
5801            &root,
5802            &HashMap::new(),
5803            Vec::new(),
5804            None,
5805            false,
5806            "test_for_each",
5807            None,
5808        )
5809        .expect("for_each synth");
5810
5811        let fe_has_a_idx = for_each
5812            .program()
5813            .find_input("has_a")
5814            .expect("for_each has_a slot");
5815        let fe_has_a_type = for_each.program().input_port_type("has_a");
5816        assert_eq!(
5817            fe_has_a_type,
5818            Some(polydat::ast::PortType::Bool),
5819            "for_each has_a must be Bool, got {fe_has_a_type:?}"
5820        );
5821        let fe_has_a_kind = for_each.program().input_kind(fe_has_a_idx);
5822        assert_ne!(
5823            fe_has_a_kind,
5824            Some(polydat::kernel::InputKind::Coordinate),
5825            "for_each has_a must NOT be Coordinate; got {fe_has_a_kind:?}"
5826        );
5827
5828        // Step 3: phase scope with its own bindings via pick.
5829        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5830            "chosen := pick(has_a, has_b, \"alpha\", \"beta\")\n".to_string(),
5831        );
5832        let phase = build_phase_scope_kernel(
5833            &phase_bindings,
5834            &[],
5835            &for_each,
5836            &HashMap::new(),
5837            Vec::new(),
5838            None,
5839            false,
5840            "test_phase",
5841        )
5842        .expect("phase scope synth");
5843
5844        let phase_has_a_idx = phase
5845            .program()
5846            .find_input("has_a")
5847            .expect("phase has_a slot");
5848        let phase_has_a_type = phase.program().input_port_type("has_a");
5849        assert_eq!(
5850            phase_has_a_type,
5851            Some(polydat::ast::PortType::Bool),
5852            "phase has_a must be Bool; got {phase_has_a_type:?}\n\
5853             phase input names: {:?}",
5854            phase.program().input_names()
5855        );
5856        let phase_has_a_kind = phase.program().input_kind(phase_has_a_idx);
5857        assert_ne!(
5858            phase_has_a_kind,
5859            Some(polydat::kernel::InputKind::Coordinate),
5860            "phase has_a must NOT be Coordinate; got {phase_has_a_kind:?}\n\
5861             phase input names: {:?}\n\
5862             coord_count: {}",
5863            phase.program().input_names(),
5864            phase.program().coord_count()
5865        );
5866    }
5867
5868    #[test]
5869    fn for_each_then_phase_preserves_shared_bool_through_chain() {
5870        // The full chain the workload exercises:
5871        //   workload root (shared has_X := false)
5872        //     → for_each scope (cascades has_X via synthesize_for_each_scope)
5873        //       → phase scope await_index (cascades has_X via build_phase_scope_kernel)
5874        //
5875        // SRD-13c §"Shared Mutable" + SRD-13d §1: at every cascade
5876        // hop, has_X stays Bool-typed and non-Coordinate.
5877        // bind_outer_scope then cell-attaches at each level so
5878        // the original SharedCell reaches the leaf.
5879        use polydat::kernel::extract_manifest;
5880        let root = crate::scope_kernel::ScopeKernel::compile(
5881            "input cycle: u64\nshared has_sai_column_indexes := false\n\
5882             shared has_indexes := false\n",
5883        )
5884        .expect("root compile");
5885
5886        // for_each scope synthesised via the comprehension
5887        // synthesizer (the path runner.rs uses for ForComprehension
5888        // install specs). Iter vars are a placeholder so the
5889        // builder runs.
5890        let for_each_kernel = crate::scope_synth::build_for_each_scope_kernel(
5891            &[("dummy_var".to_string(), "1,2".to_string())],
5892            &extract_manifest(root.program()),
5893            &root,
5894            &HashMap::new(), // workload_params
5895            Vec::new(),      // polydat_lib_paths
5896            None,            // workload_dir
5897            false,           // strict
5898            "test_for_each",
5899            None, // phase_bindings
5900        )
5901        .expect("for_each kernel synth");
5902
5903        // for_each's program must carry has_X as a Bool slot too.
5904        let fe_type = for_each_kernel
5905            .program()
5906            .input_port_type("has_sai_column_indexes");
5907        assert_eq!(
5908            fe_type,
5909            Some(polydat::ast::PortType::Bool),
5910            "for_each scope's has_sai_column_indexes must be Bool, got {fe_type:?}"
5911        );
5912        let fe_idx = for_each_kernel
5913            .program()
5914            .find_input("has_sai_column_indexes")
5915            .expect("for_each has has_sai_column_indexes input");
5916        let fe_kind = for_each_kernel.program().input_kind(fe_idx);
5917        assert_ne!(
5918            fe_kind,
5919            Some(polydat::kernel::InputKind::Coordinate),
5920            "for_each scope's has_sai_column_indexes must NOT be Coordinate; got {fe_kind:?}"
5921        );
5922
5923        // Now build await_index's phase scope under for_each
5924        // (the real scope-tree shape).
5925        let phase_bindings = nmbrs_workload::model::BindingsDef::PolydatSource(
5926            "target_index_table := pick(has_sai_column_indexes, has_indexes, \
5927             \"a\", \"b\")\n"
5928                .to_string(),
5929        );
5930        let phase_kernel = build_phase_scope_kernel(
5931            &phase_bindings,
5932            &[],
5933            &for_each_kernel,
5934            &HashMap::new(),
5935            Vec::new(),
5936            None,
5937            false,
5938            "test_await_index",
5939        )
5940        .expect("phase kernel synth");
5941
5942        let phase_type = phase_kernel
5943            .program()
5944            .input_port_type("has_sai_column_indexes");
5945        assert_eq!(
5946            phase_type,
5947            Some(polydat::ast::PortType::Bool),
5948            "phase scope's has_sai_column_indexes must be Bool, got {phase_type:?}"
5949        );
5950        let phase_idx = phase_kernel
5951            .program()
5952            .find_input("has_sai_column_indexes")
5953            .expect("phase has has_sai_column_indexes input");
5954        let phase_kind = phase_kernel.program().input_kind(phase_idx);
5955        assert_ne!(
5956            phase_kind,
5957            Some(polydat::kernel::InputKind::Coordinate),
5958            "phase scope's has_sai_column_indexes must NOT be Coordinate; got {phase_kind:?}"
5959        );
5960    }
5961}
5962
5963/// Strict mode reaches every synthesized scope, and each still compiles:
5964/// strict refuses a source with no `input` declaration, and a synthesized
5965/// scope's coordinates are its parent's, so they are declared for it.
5966#[cfg(test)]
5967mod strict_synthesis_tests {
5968    use super::*;
5969
5970    fn parent() -> crate::scope_kernel::ScopeKernel {
5971        crate::scope_kernel::ScopeKernel::compile("input cycle: u64\nconst k_values := \"1, 10\"\n")
5972            .expect("parent scope")
5973    }
5974
5975    #[test]
5976    fn a_phase_scope_compiles_under_strict() {
5977        let parent = parent();
5978        let manifest = crate::runner::extract_manifest(parent.program());
5979        let kernel = build_phase_scope_kernel(
5980            &nmbrs_workload::model::BindingsDef::PolydatSource("x := cycle + 1\n".into()),
5981            &manifest,
5982            &parent,
5983            &HashMap::new(),
5984            Vec::new(),
5985            None,
5986            true,
5987            "strict phase",
5988        )
5989        .expect("a phase scope compiles under strict");
5990        assert!(kernel.input_names().iter().any(|n| n == "cycle"));
5991    }
5992
5993    #[test]
5994    fn a_do_loop_scope_compiles_under_strict() {
5995        let parent = parent();
5996        let manifest = crate::runner::extract_manifest(parent.program());
5997        build_do_loop_scope_kernel(
5998            Some("i"),
5999            "{i} < 3",
6000            &manifest,
6001            &parent,
6002            &HashMap::new(),
6003            Vec::new(),
6004            None,
6005            true,
6006            "strict do-loop",
6007        )
6008        .expect("a do-loop scope compiles under strict");
6009    }
6010
6011    #[test]
6012    fn a_for_each_scope_compiles_under_strict() {
6013        let parent = parent();
6014        let manifest = crate::runner::extract_manifest(parent.program());
6015        crate::scope_synth::build_for_each_scope_kernel(
6016            &[("k".to_string(), "{k_values}".to_string())],
6017            &manifest,
6018            &parent,
6019            &HashMap::new(),
6020            Vec::new(),
6021            None,
6022            true,
6023            "strict for_each",
6024            None,
6025        )
6026        .expect("a for_each scope compiles under strict");
6027    }
6028}