Skip to main content

nmbrs_runtime/
wires.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! `WireSource` — narrow read trait for op-template name resolution.
5//!
6//! SRD-68 §"The narrow trait" specifies the wall between adapter
7//! code and `crate::scope_kernel::ScopeKernel` internals: a dispenser
8//! at cycle time accesses its bound Polydat context only through this
9//! trait's `get` (value lookup by name) and `names` (declared-name
10//! iteration for diagnostics). No `program()`, no `state()`, no
11//! `scope_coordinates()` — adapter code is sealed off from kernel
12//! mechanics.
13//!
14//! Two implementations ship here:
15//! - `ScopeKernel` itself, via the kernel's existing `lookup` chain
16//!   (input slots, outputs, inherited scope state). Single
17//!   resolution surface — name resolves where SRD-67 places it,
18//!   no fallback (SRD-68 invariant I-1).
19//! - `NullWireSource`, a unit type that returns `None` for every
20//!   name. Used as the default value in `ExecCtx::new` during the
21//!   SRD-68 migration so call sites that don't yet have a kernel
22//!   handle don't break — adapters opt in via
23//!   `ExecCtx::with_wires` once they own a kernel reference.
24//!
25//! See `docs/SRD/68_dispenser_owned_polydat_context.md`.
26
27use std::sync::OnceLock;
28
29use crate::scope_kernel::ScopeKernel;
30use polydat::ast::{PortType, Value};
31use polydat::kernel::WriteError;
32
33/// Cached `NMBRS_DIRTY_DEBUG=true` switch. Per-cycle env reads cost
34/// ~30% of CPU on single-fiber benches; the OnceLock makes the gate
35/// a single atomic load.
36fn nmbrs_dirty_debug_enabled() -> bool {
37    static FLAG: OnceLock<bool> = OnceLock::new();
38    *FLAG.get_or_init(|| crate::debug_env::debug_flag("NMBRS_DIRTY_DEBUG"))
39}
40
41/// Cached `NMBRS_DEBUG_WIRES=true` switch (read on every wire write).
42fn nmbrs_debug_wires_enabled() -> bool {
43    static FLAG: OnceLock<bool> = OnceLock::new();
44    *FLAG.get_or_init(|| crate::debug_env::debug_flag("NMBRS_DEBUG_WIRES"))
45}
46
47/// Result of a [`WireSource::write`] call.
48///
49/// `Stored` means the value landed on a real input slot in the
50/// underlying kernel and is visible to subsequent pulls.
51///
52/// `NoSlot` means the kernel's program has no input slot named
53/// `name`. Under [`KernelOptLevel::Release`] this is the
54/// closure-binding economy's DCE signal — nothing in the body
55/// referenced the name, so the value is silently dropped. Under
56/// [`KernelOptLevel::Diagnostic`] every magic extern and
57/// result-binding LHS gets a slot, so `NoSlot` indicates a
58/// genuinely-unknown name (caller error or a name outside the
59/// kernel's scope).
60///
61/// Callers don't need to branch on the outcome to maintain
62/// correctness — the kernel either has a slot for the name or it
63/// doesn't, and `NoSlot` is the same as "the workload doesn't
64/// reference this value." Diagnostics (`debug_nodes_enabled()`,
65/// audit log) can log the outcome to make DCE visible.
66///
67/// [`KernelOptLevel::Release`]: polydat::kernel::KernelOptLevel::Release
68/// [`KernelOptLevel::Diagnostic`]: polydat::kernel::KernelOptLevel::Diagnostic
69#[derive(Clone, Debug, PartialEq, Eq)]
70pub enum WriteOutcome {
71    /// Value written to a real input slot.
72    Stored,
73    /// No input slot named `name` in this kernel's program.
74    NoSlot,
75    /// The slot exists but the value is not of the slot's declared
76    /// `PortType` and polydat's conversion catalog has no conversion
77    /// to it (or the conversion failed). The typed-write contract
78    /// rejects this rather than silently corrupting downstream reads;
79    /// the `reason` field carries the polydat-side diagnostic for
80    /// surfacing to the operator.
81    TypeMismatch { reason: String },
82    /// The slot is a coordinate. Coordinates advance with the cycle
83    /// (`set_inputs`), never by a named write, so the kernel refuses
84    /// the write to keep the coordinate prefix in step with the cycle
85    /// a pull is about to read. `reason` is polydat's diagnostic.
86    Coordinate { reason: String },
87    /// The slot holds a `const`'s captured value, which only kernel
88    /// initialization writes: a const changes when the inputs it reads
89    /// change and the kernel is re-initialized, never by a write to its
90    /// own slot. `reason` is polydat's diagnostic.
91    Const { reason: String },
92}
93
94/// Why a [`write_input`] did not land.
95#[derive(Debug)]
96pub enum HostWriteError {
97    /// The kernel refused the typed write.
98    Write(WriteError),
99    /// The value could not be converted to the slot's declared type.
100    Convert {
101        /// The input written.
102        slot: String,
103        /// polydat's reason.
104        error: polydat::convert::ConvertError,
105    },
106}
107
108impl std::fmt::Display for HostWriteError {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        match self {
111            HostWriteError::Write(e) => write!(f, "{e}"),
112            HostWriteError::Convert { slot, error } => write!(f, "'{slot}': {error}"),
113        }
114    }
115}
116
117impl From<HostWriteError> for WriteOutcome {
118    fn from(e: HostWriteError) -> Self {
119        let reason = e.to_string();
120        match e {
121            HostWriteError::Write(WriteError::UnknownWire { .. }) => WriteOutcome::NoSlot,
122            HostWriteError::Write(WriteError::CoordinateSlot { .. }) => {
123                WriteOutcome::Coordinate { reason }
124            }
125            HostWriteError::Write(WriteError::ConstSlot { .. }) => WriteOutcome::Const { reason },
126            HostWriteError::Write(WriteError::TypeMismatch { .. })
127            | HostWriteError::Write(WriteError::FromParent { .. })
128            | HostWriteError::Convert { .. } => WriteOutcome::TypeMismatch { reason },
129        }
130    }
131}
132
133/// nmbrs's one rule for writing a host value into a kernel input.
134///
135/// polydat 0.5 never converts at the write, so a value that may not be
136/// of the slot's declared type is converted first through
137/// `polydat::convert::to_port`, the catalog a converter node uses, and
138/// then written with the typed `set_input_at`. A value already of the
139/// slot's type passes through unconverted. `index` is `name`'s position
140/// in the kernel's inputs; the name is taken too so the per-cycle
141/// callers, which already hold it, pay no index-to-name lookup.
142pub fn write_input(
143    kernel: &mut dyn polydat::Kernel,
144    index: usize,
145    name: &str,
146    value: Value,
147) -> Result<(), HostWriteError> {
148    let value = match kernel.input_port_type(name) {
149        Some(port) => {
150            polydat::convert::to_port(value, port).map_err(|error| HostWriteError::Convert {
151                slot: name.to_string(),
152                error,
153            })?
154        }
155        None => value,
156    };
157    kernel
158        .set_input_at(index, value)
159        .map_err(HostWriteError::Write)
160}
161
162/// Cycle-time read surface a dispenser uses to resolve names from
163/// its bound Polydat context.
164///
165/// `get(name)` returns the current value of the named wire in the
166/// dispenser's kernel. A `None` return indicates the name isn't
167/// declared in this scope — callers MUST treat that as a
168/// resolution error, not a fallback opportunity (SRD-68 I-1).
169///
170/// `names` enumerates declared names for validators and
171/// `describe_resolved`-style introspection. Not for hot-path cycle
172/// reads; cycle reads use `get`.
173pub trait WireSource: Send + Sync {
174    /// Look up `name` in this kernel's scope. Returns the current
175    /// value (cloned, owned) or `None` when the name is not
176    /// declared here. Callers do not retry against another kernel
177    /// — a `None` is the resolution result, full stop.
178    fn get(&self, name: &str) -> Option<Value>;
179
180    /// Iterate declared names. Order is implementation-defined.
181    /// Used by validators and diagnostic renderers.
182    fn names(&self) -> Box<dyn Iterator<Item = String> + '_>;
183
184    /// Write `value` into the named input slot of this kernel.
185    /// Returns [`WriteOutcome::Stored`] when the slot exists and
186    /// the value was written, [`WriteOutcome::NoSlot`] when the
187    /// kernel's program has no input slot named `name`.
188    ///
189    /// This is the canonical cycle-time capture path used by
190    /// `ResultDispenser` and `TraversingDispenser` after their
191    /// inner stack returns. Writes land on the kernel directly —
192    /// no HashMap intermediary, no post-stack pump in the
193    /// activity loop. Subsequent `wires.get` calls (e.g. from a
194    /// later wrapper like `MetricsDispenser`) see fresh values.
195    ///
196    /// Default impl returns `NoSlot` — appropriate for read-only
197    /// implementations like `NullWireSource` and the bare
198    /// `&ScopeKernel` baseline (which has no `&mut` handle to mutate
199    /// state). `CycleWires` overrides with the real write path
200    /// through the wrapped kernel's `set_input`.
201    fn write(&self, _name: &str, _value: Value) -> WriteOutcome {
202        WriteOutcome::NoSlot
203    }
204
205    /// Reset the named input slot to its DECLARED initial value —
206    /// the author's identity element for that wire. The capture
207    /// layer uses this for min/max-of-nothing (SRD-93-era fold
208    /// totality): an empty measurement restores the wire to its
209    /// declared unit rather than parking `Value::None` on a typed
210    /// slot, where every downstream consumer would have to be
211    /// None-aware. Default impl returns `NoSlot` (read-only
212    /// sources have nothing to reset).
213    fn reset(&self, _name: &str) -> WriteOutcome {
214        WriteOutcome::NoSlot
215    }
216
217    /// Advance the underlying kernel state to coordinate `coord`
218    /// and invalidate any memoized pulls so subsequent `get`
219    /// calls produce values for this coord.
220    ///
221    /// Used by batch dispensers per the SRD-68 invariant:
222    /// > "Within the batch view, each iteration of the batch is
223    /// > considered another pull, just as if the operation
224    /// > inside the batch were separate. It is simply an
225    /// > iteration container."
226    ///
227    /// The default impl is a no-op — `NullWireSource` and
228    /// adapters that don't drive batch iteration leave it alone.
229    /// `CycleWires` overrides to mutate the wrapped kernel's
230    /// coord input. Calling `advance` on a `WireSource` that
231    /// has no kernel handle (e.g. `NullWireSource`) is a no-op,
232    /// not an error — the dispenser's own `wires.get` calls
233    /// will resolve correctly against whatever read surface the
234    /// adapter has bound.
235    fn advance(&self, _coord: u64) {}
236}
237
238/// Read-only `WireSource` over a kernel of any engine: the names a scope
239/// lookup answers (`KernelLookup` — a const's value, an input, a folded
240/// value), as the `ScopeKernel` impl below does for the interpreter.
241/// Computed outputs that need a pull are not covered; `CycleWires` is
242/// the surface that pulls. What an adapter's canonical kernel offers a
243/// wrap-time reader.
244pub struct KernelWires<'a>(pub &'a dyn polydat::Kernel);
245
246impl WireSource for KernelWires<'_> {
247    fn get(&self, name: &str) -> Option<Value> {
248        use polydat::kernel::interp::Lookup as _;
249        polydat::kernel::interp::KernelLookup::new(self.0).lookup(name)
250    }
251
252    fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
253        let outputs = self.0.output_names();
254        let inputs_only: Vec<String> = self
255            .0
256            .input_names()
257            .into_iter()
258            .filter(|n| !outputs.contains(n))
259            .collect();
260        Box::new(outputs.into_iter().chain(inputs_only))
261    }
262}
263
264/// `WireSource` over `&ScopeKernel` — covers names that the kernel's
265/// `lookup` API already exposes (inputs, scope-init constants,
266/// shared-cell-backed values). Computed outputs that require a
267/// memoizing `pull(&mut state, …)` evaluation are NOT covered here
268/// and return `None` from `get`; the SRD-68 Push 2 work introduces a
269/// richer `WireSource` impl that owns the per-fiber kernel handle
270/// with interior mutability and can pull outputs at cycle time.
271///
272/// For Push 1 this `&ScopeKernel` impl is the additive baseline: every
273/// existing call site that gets handed a `NullWireSource` continues
274/// working unchanged, and code that wants kernel-side reads via the
275/// trait can use it for the names `lookup` already answers.
276impl WireSource for ScopeKernel {
277    fn get(&self, name: &str) -> Option<Value> {
278        self.lookup(name)
279    }
280
281    fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
282        // Outputs come first (the canonical declared-name surface),
283        // followed by input names not also published as outputs.
284        // Ordering is stable for a given program; consumers should
285        // not assume a particular order between the two groups.
286        let program = self.program();
287        let outputs: Vec<String> = program
288            .output_names()
289            .iter()
290            .map(|s| s.to_string())
291            .collect();
292        let inputs_only: Vec<String> = program
293            .input_names()
294            .iter()
295            .filter(|n| !outputs.contains(n))
296            .cloned()
297            .collect();
298        Box::new(outputs.into_iter().chain(inputs_only))
299    }
300}
301
302/// A kernel that carries the interpreter program its names resolve on:
303/// a scope kernel, or an interpreter kernel.
304pub trait ProgramKernel {
305    /// The running kernel and its program.
306    fn split_program(
307        &mut self,
308    ) -> (
309        &mut dyn polydat::Kernel,
310        std::sync::Arc<polydat::kernel::PolydatProgram>,
311    );
312}
313
314impl ProgramKernel for ScopeKernel {
315    fn split_program(
316        &mut self,
317    ) -> (
318        &mut dyn polydat::Kernel,
319        std::sync::Arc<polydat::kernel::PolydatProgram>,
320    ) {
321        let program = self.program().clone();
322        (self.kernel_mut(), program)
323    }
324}
325
326impl ProgramKernel for polydat::kernel::PolydatKernel {
327    fn split_program(
328        &mut self,
329    ) -> (
330        &mut dyn polydat::Kernel,
331        std::sync::Arc<polydat::kernel::PolydatProgram>,
332    ) {
333        let program = self.program().clone();
334        (self, program)
335    }
336}
337
338/// `WireSource` over a per-fiber kernel handle that supports the
339/// full read surface — inputs, scope-init constants, AND computed
340/// outputs (which need a memoizing `pull(&mut state, …)` to fire
341/// the eval cone). Wraps a `&mut ScopeKernel` in a `Mutex` so the
342/// trait stays `&self`-callable (and `Sync`) while still permitting
343/// pull's `&mut` requirement.
344///
345/// The `Mutex` is uncontended in practice: per-fiber-per-cycle
346/// dispatch is single-threaded by construction (the fiber owns
347/// the kernel slot exclusively for the duration of the cycle),
348/// so `lock()` always succeeds without spinning. Using `Mutex`
349/// rather than `RefCell` is a `Sync` requirement — async futures
350/// returned by `OpDispenser::execute` are Send, which means
351/// `&ExecCtx` (and through it `&dyn WireSource`) must be Send,
352/// which means `dyn WireSource` must be Sync.
353///
354/// Cells held here have the lifetime of one cycle dispatch —
355/// constructed at cycle entry from the firing dispenser's
356/// per-fiber kernel slot, dropped after the dispenser returns.
357///
358/// Resolution order on `get(name)`:
359/// 1. Output (memoizing pull through the eval cone).
360/// 2. Input slot (cell-aware read).
361/// 3. Scope-init constant.
362///
363/// `None` when the name doesn't appear on this kernel — callers
364/// surface as an unresolved-bindpoint error per SRD-68 I-1.
365///
366/// The kernel may be on any engine. Names resolve on `program`, the
367/// interpreter program the kernel runs or was imaged from, whose
368/// indices it shares (`fiber_engine::agrees`); the kernel is then
369/// driven by index, so a compiled kernel pays no name lookup.
370///
371/// One value per name per cycle: an output read is kept for the life of
372/// these wires — one cycle's dispatch — so an op that references a
373/// `volatile` binding twice renders one reading, although polydat
374/// re-evaluates a volatile step on every pull. A write, a reset, or an
375/// advance forgets every kept reading, so a read after one sees the
376/// kernel as it is now.
377pub struct CycleWires<'a> {
378    kernel: std::sync::Mutex<&'a mut dyn polydat::Kernel>,
379    /// Where names resolve: the interpreter program the kernel shares
380    /// indices with, or `None` to ask the kernel itself.
381    program: Option<std::sync::Arc<polydat::kernel::PolydatProgram>>,
382    readings: std::sync::Mutex<std::collections::HashMap<usize, Value>>,
383}
384
385impl<'a> CycleWires<'a> {
386    /// Wrap a scope kernel (or an interpreter kernel) for cycle-time
387    /// reads; names resolve on its program. The caller holds the only
388    /// outstanding borrow on the kernel for the duration of this cycle.
389    pub fn new<K: ProgramKernel + ?Sized>(kernel: &'a mut K) -> Self {
390        let (kernel, program) = kernel.split_program();
391        Self::over(kernel, program)
392    }
393
394    /// Wrap a kernel of any engine whose inputs and outputs are
395    /// `program`'s, in the same order.
396    pub fn over(
397        kernel: &'a mut dyn polydat::Kernel,
398        program: std::sync::Arc<polydat::kernel::PolydatProgram>,
399    ) -> Self {
400        Self {
401            kernel: std::sync::Mutex::new(kernel),
402            program: Some(program),
403            readings: std::sync::Mutex::new(std::collections::HashMap::new()),
404        }
405    }
406
407    /// Wrap a kernel of any engine, resolving names on the kernel
408    /// itself. For a holder with no interpreter program in hand — an
409    /// adapter probing a fork of its `Arc<dyn Kernel>` parent; a
410    /// compiled kernel's name lookup is a scan, so a per-cycle path
411    /// uses [`Self::over`].
412    pub fn of(kernel: &'a mut dyn polydat::Kernel) -> Self {
413        Self {
414            kernel: std::sync::Mutex::new(kernel),
415            program: None,
416            readings: std::sync::Mutex::new(std::collections::HashMap::new()),
417        }
418    }
419
420    fn output_index(&self, k: &dyn polydat::Kernel, name: &str) -> Option<usize> {
421        match &self.program {
422            Some(p) => p.output_index(name),
423            None => k.output_index(name),
424        }
425    }
426
427    fn input_index(&self, k: &dyn polydat::Kernel, name: &str) -> Option<usize> {
428        match &self.program {
429            Some(p) => p.find_input(name),
430            None => k.input_index(name),
431        }
432    }
433
434    /// Forget every reading kept this cycle: the kernel's inputs moved.
435    fn forget_readings(&self) {
436        self.readings
437            .lock()
438            .expect("CycleWires readings poisoned")
439            .clear();
440    }
441}
442
443impl<'a> WireSource for CycleWires<'a> {
444    fn get(&self, name: &str) -> Option<Value> {
445        let mut k = self.kernel.lock().expect("CycleWires mutex poisoned");
446        // Output pull first: a name declared by the program's
447        // bindings is an output; the pull memoizes through the
448        // eval cone. Fall through to the scope lookup for inputs
449        // and scope-init constants. No external chain composition —
450        // construction-time wiring set up every visible wire
451        // (SRD-13f).
452        if let Some(output_idx) = self.output_index(&**k, name) {
453            let mut readings = self.readings.lock().expect("CycleWires readings poisoned");
454            let v = readings
455                .entry(output_idx)
456                .or_insert_with(|| k.pull_at(output_idx))
457                .clone();
458            if nmbrs_dirty_debug_enabled() && name == "query" {
459                let s = v.to_display_string();
460                let head: String = s.chars().take(64).collect();
461                eprintln!("DIRTY: wires.get(query) OUTPUT head=\"{head}\"");
462            }
463            return Some(v);
464        }
465        let v = {
466            use polydat::kernel::interp::Lookup as _;
467            polydat::kernel::interp::KernelLookup::new(&**k).lookup(name)
468        };
469        if nmbrs_dirty_debug_enabled() && name == "query" {
470            let head = v
471                .as_ref()
472                .map(|x| x.to_display_string().chars().take(64).collect::<String>())
473                .unwrap_or_else(|| "<none>".into());
474            eprintln!("DIRTY: wires.get(query) INPUT/CONST head=\"{head}\"");
475        }
476        v
477    }
478
479    fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
480        let (outputs, inputs): (Vec<String>, Vec<String>) = match &self.program {
481            Some(p) => (
482                p.output_names().iter().map(|s| s.to_string()).collect(),
483                p.input_names(),
484            ),
485            None => {
486                let k = self.kernel.lock().expect("CycleWires mutex poisoned");
487                (k.output_names(), k.input_names())
488            }
489        };
490        let inputs_only: Vec<String> = inputs
491            .into_iter()
492            .filter(|n| !outputs.contains(n))
493            .collect();
494        Box::new(outputs.into_iter().chain(inputs_only))
495    }
496
497    fn reset(&self, name: &str) -> WriteOutcome {
498        let mut k = self.kernel.lock().expect("CycleWires mutex poisoned");
499        self.forget_readings();
500        let Some(idx) = self.input_index(&**k, name) else {
501            return WriteOutcome::NoSlot;
502        };
503        // The declared default is by construction the slot's own
504        // type, so this write cannot mismatch; the typed boundary
505        // is still used rather than poking state directly.
506        let Some(default) = k.input_default_at(idx) else {
507            return WriteOutcome::NoSlot;
508        };
509        match write_input(&mut **k, idx, name, default) {
510            Ok(()) => WriteOutcome::Stored,
511            Err(e) => e.into(),
512        }
513    }
514
515    fn write(&self, name: &str, value: Value) -> WriteOutcome {
516        let mut k = self.kernel.lock().expect("CycleWires mutex poisoned");
517        self.forget_readings();
518        let found = self.input_index(&**k, name);
519        if nmbrs_debug_wires_enabled() {
520            let cells: Vec<String> = k.cells_in_scope().iter().map(|c| c.name.clone()).collect();
521            let slot_cell = found.map(|idx| k.input_is_cell_bound(idx));
522            eprintln!(
523                "WIRES.write name={name} value={value:?} slot_cell_bound={slot_cell:?} cells_in_scope={cells:?}"
524            );
525        }
526        // Result and capture values arrive typed by the adapter, not
527        // by the slot, so they go through the converting write.
528        let Some(idx) = found else {
529            return WriteOutcome::NoSlot;
530        };
531        match write_input(&mut **k, idx, name, value) {
532            Ok(()) => WriteOutcome::Stored,
533            Err(e) => e.into(),
534        }
535    }
536
537    fn advance(&self, coord: u64) {
538        let mut k = self.kernel.lock().expect("CycleWires mutex poisoned");
539        self.forget_readings();
540        if k.coord_count() > 0 {
541            k.set_inputs(&[coord]);
542        }
543    }
544}
545
546/// Empty `WireSource` — every `get` returns `None`, `names` is
547/// empty. Used as the default for `ExecCtx::new` so callers that
548/// don't yet have a kernel handle don't need to construct a
549/// real implementation. Migration call sites switch to
550/// `ExecCtx::with_wires` when they own a kernel reference (see
551/// SRD-68 Push 2 and beyond).
552pub struct NullWireSource;
553
554impl WireSource for NullWireSource {
555    fn get(&self, _name: &str) -> Option<Value> {
556        None
557    }
558    fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
559        Box::new(std::iter::empty())
560    }
561}
562
563/// Static `&'static dyn WireSource` for use as the default in
564/// `ExecCtx::new`. Avoids per-call allocation; the unit struct has
565/// no state to differ.
566pub static NULL_WIRES: NullWireSource = NullWireSource;
567
568/// Render `template` by substituting each `{name}` placeholder
569/// with `wires.get(name)`'s display-string form. The single
570/// resolution-via-wires entry point adapters use at cycle time
571/// per SRD-68 Push 5 — replaces the synthesis-layer
572/// `substitute_bind_points*` text-mutation pass.
573///
574/// Honors the standard placeholder escape rules established by
575/// `nmbrs_workload::bindpoints`:
576/// - `\{` / `\}` — literal brace, passes through unchanged.
577/// - `{{...}}` — inline-expression form, reserved for the
578///   `{{<polydat-expr>}}` desugar surface; passes through unchanged
579///   (compiled into bindings before reaching cycle time).
580/// - Qualifier-prefixed forms (`{bind:name}` / `{capture:name}`
581///   / `{input:name}`) — the current Push 5 contract is bare
582///   `{name}` only; qualifier-prefixed references error.
583/// - `{` followed by non-identifier text — passes through (CQL
584///   map literals like `{'class': 'SimpleStrategy'}`, JSON object
585///   literals like `{"a": 1}`, format specs like `{:5.2}`).
586///
587/// Returns `Err` with a descriptive message when a bare `{name}`
588/// reference doesn't resolve through `wires` — SRD-68 invariant
589/// I-1 forbids silent fallback. Callers (typically the cycle
590/// dispatch error path) surface this as a phase-stopping
591/// diagnostic.
592pub fn substitute_via_wires(template: &str, wires: &dyn WireSource) -> Result<String, String> {
593    // Mirror the brace-handling algorithm of
594    // `nmbrs_workload::bindpoints::extract_bind_points`: when `{` is
595    // followed by a literal-start character (`'` or `"`), emit the
596    // brace and continue scanning so nested `{name}` placeholders
597    // INSIDE CQL map / JSON object literals still get resolved.
598    // Track brace depth so a top-level `{name}` whose body itself
599    // contains balanced braces (rare) isn't truncated at the first
600    // closing brace.
601    let chars: Vec<char> = template.chars().collect();
602    let n = chars.len();
603    let mut out = String::with_capacity(template.len());
604    let mut i = 0;
605    while i < n {
606        // `\{` / `\}` — pass through, two chars.
607        if chars[i] == '\\' && i + 1 < n && (chars[i + 1] == '{' || chars[i + 1] == '}') {
608            out.push(chars[i]);
609            out.push(chars[i + 1]);
610            i += 2;
611            continue;
612        }
613        // `{{ ... }}` — inline-expression form. Reserved for the
614        // Polydat desugar surface; passes through unchanged at cycle
615        // time (compiled into bindings before reaching this
616        // path).
617        if i + 1 < n && chars[i] == '{' && chars[i + 1] == '{' {
618            let start = i;
619            let mut j = i + 2;
620            while j + 1 < n && !(chars[j] == '}' && chars[j + 1] == '}') {
621                j += 1;
622            }
623            let end = (j + 2).min(n);
624            out.extend(&chars[start..end]);
625            i = end;
626            continue;
627        }
628        if chars[i] != '{' {
629            out.push(chars[i]);
630            i += 1;
631            continue;
632        }
633        // CQL map / JSON object literal: `{` followed by
634        // (whitespace?) `'`/`"`. Emit just the `{` and
635        // continue scanning so any nested `{name}` placeholders
636        // inside still resolve. Whitespace tolerance covers
637        // multi-line CQL maps written with the opening brace
638        // on its own line (e.g. `compaction = {\n  'class':
639        // …\n}`).
640        let next_nonspace = chars[i + 1..].iter().find(|c| !c.is_whitespace()).copied();
641        if matches!(next_nonspace, Some('\'') | Some('"')) {
642            out.push('{');
643            i += 1;
644            continue;
645        }
646        // Single `{...}` form: depth-track to find the matching
647        // `}` so balanced inner braces don't truncate the body.
648        let body_start = i + 1;
649        let mut j = body_start;
650        let mut depth: u32 = 1;
651        while j < n {
652            if chars[j] == '{' {
653                depth += 1;
654            }
655            if chars[j] == '}' {
656                depth -= 1;
657                if depth == 0 {
658                    break;
659                }
660            }
661            j += 1;
662        }
663        if j >= n {
664            // Unterminated — treat as literal char.
665            out.push('{');
666            i += 1;
667            continue;
668        }
669        let body: String = chars[body_start..j].iter().collect();
670        let body = body.trim();
671        let after = j + 1;
672        // Empty body — pass through.
673        if body.is_empty() {
674            out.push('{');
675            out.push('}');
676            i = after;
677            continue;
678        }
679        // Qualifier-prefixed form (`{bind:name}`, `{capture:name}`,
680        // `{input:name}`) — SRD-68 Push 5 contract is bare names
681        // only at cycle time.
682        if body.contains(':') {
683            return Err(format!(
684                "qualifier-prefixed bind point `{{{body}}}` is not supported \
685                 at cycle time; only bare `{{name}}` references are answered \
686                 by the dispenser's WireSource"
687            ));
688        }
689        // Bare identifiers resolve as-is. Dotted identifiers
690        // (`q.cursor.idx`) follow the field-access wire
691        // convention and resolve through their flattened
692        // spelling (`q__cursor__idx`) — same rule the DSL
693        // compiler and kernel lookup apply. Everything else
694        // (format specs `{:5.2}`, expressions `{a+b}`, etc.)
695        // passes through unchanged.
696        let wire_name: std::borrow::Cow<'_, str> = if is_bare_ident(body) {
697            std::borrow::Cow::Borrowed(body)
698        } else if is_dotted_ident(body) {
699            std::borrow::Cow::Owned(body.replace('.', "__"))
700        } else {
701            out.push('{');
702            out.push_str(body);
703            out.push('}');
704            i = after;
705            continue;
706        };
707        let body = wire_name.as_ref();
708        // Bare identifier — wires.get resolves or errors.
709        //
710        // SRD-74 Rule 3 (strict render): `Value::None` reaching the
711        // wire-protocol substitution surface is an error, NOT a
712        // silent empty string. The display-strict primitive returns
713        // `None` for `Value::None` so we can surface a clear
714        // diagnostic. The catch-all `to_display_string` legacy
715        // (which maps None to "") stays in place for log /
716        // diagnostic contexts where empty is acceptable; render
717        // sites use the strict form.
718        match wires.get(body) {
719            Some(v) => {
720                // Binary-natural type guard. A wire holding VecF32 /
721                // VecI32 / Handle / Bytes has no meaningful
722                // text-spliced form for a wire-protocol field —
723                // decimal-stringifying a 128-element f32 vector to
724                // embed in a CQL INSERT is always the wrong path
725                // (it forces format-then-reparse on every cycle and
726                // bypasses the adapter's typed-binding API). Detect
727                // here so the cost — and the design violation — are
728                // surfaced as a clear error instead of silently
729                // burned on every cycle.
730                //
731                // The escape hatch for typed values that genuinely
732                // belong in a field is the "pure-token" form (case 2
733                // in `resolve_op_fields_via_wires`): the entire
734                // field value is exactly `{wire_name}` with no
735                // surrounding text, and the typed `Value` is handed
736                // to the adapter intact.
737                if is_binary_natural(v.port_type()) {
738                    return Err(format!(
739                        "wire `{body}` holds {} which has no text-spliced \
740                         representation suitable for a wire-protocol field. \
741                         Either use the pure-token form (the entire field \
742                         value is exactly `{{{body}}}` with no surrounding \
743                         text) so the adapter binds the typed value via \
744                         its parameter API, or split the field so the \
745                         wire is bound as a typed parameter alongside a \
746                         text template containing placeholders (e.g. CQL \
747                         `?`).",
748                        v.port_type()
749                    ));
750                }
751                match v.to_display_strict() {
752                    Some(s) => out.push_str(&s),
753                    None => {
754                        return Err(format!(
755                            "unresolved bind point `{{{body}}}`: wire \
756                             `{body}` resolved to `Value::None` (no value \
757                             bound in the dispenser's Polydat context chain). \
758                             Set a workload-param default for `{body}`, \
759                             bind it via `bindings:` / `set:`, or mark \
760                             the bind-point as optional once SRD-74 \
761                             Rule 2 syntax lands."
762                        ));
763                    }
764                }
765            }
766            None => {
767                return Err(format!(
768                    "unresolved bind point `{{{body}}}`: no wire named \
769                     `{body}` in the dispenser's Polydat context"
770                ));
771            }
772        }
773        i = after;
774    }
775    Ok(out)
776}
777
778/// Resolve a list of op-template field entries through the generic
779/// wires API. Each entry is `(field_name, json_value_from_template)`;
780/// the helper returns name+value pairs an adapter can hand to its
781/// renderer, with no synthesis-layer involvement.
782///
783/// The four-case rule, in order of dispatch:
784///
785/// 1. **Non-string YAML scalar / list / object**: passes through as
786///    `Value::Str(json.to_string())`. Adapters that need richer
787///    typing for a JSON-shaped field can downcast through
788///    `ResolvedFields` and parse, but the default projection keeps
789///    the legacy "everything renders to a string" contract.
790///
791/// 2. **Pure-token typed-reference**: the entire string (trimmed)
792///    is exactly `{name}` where `name` is a bare identifier. The
793///    field's value becomes `wires.get(name).clone()` — typed
794///    `Value` preserved. Used by CQL prepared-param bindings,
795///    vector args, and anywhere an adapter needs the native typed
796///    value rather than its display string. An unresolved name
797///    here is a hard error (no silent fallback).
798///
799/// 3. **Text template with placeholders**: any string containing
800///    `{name}` placeholders embedded in surrounding text, or
801///    `{{ expr }}` inline-GK escapes. Renders through
802///    `substitute_via_wires` to produce a `Value::Str` with each
803///    placeholder replaced by its wire's display-string form.
804///    Inline-expression `{{ … }}` placeholders are evaluated then
805///    stringified.
806///
807/// 4. **Bare-string literal**: a string with no `{…}` markers
808///    passes through unchanged as `Value::Str(s.clone())`. This is
809///    the most common case for SQL stmts, URIs, and headers.
810///
811/// **Why not "bare-name as wire reference"?** A workload author
812/// writing `stmt: "SELECT * FROM users"` doesn't expect `users` to
813/// resolve as a Polydat wire. The pure-token form (case 2) is the
814/// explicit opt-in for typed references; bare strings stay
815/// literal. Per-adapter typed-field metadata (a future enhancement)
816/// would let specific fields opt into bare-name-as-reference; the
817/// current contract doesn't require it.
818///
819/// Returns the SRD-68 standard error message on the first
820/// unresolved bind point (single resolution surface, no fallback).
821pub fn resolve_op_fields_via_wires(
822    op_fields: &[(String, serde_json::Value)],
823    wires: &dyn WireSource,
824) -> Result<crate::adapter::ResolvedFields, String> {
825    use polydat::ast::Value;
826    let mut names = Vec::with_capacity(op_fields.len());
827    let mut values = Vec::with_capacity(op_fields.len());
828    for (key, json_value) in op_fields {
829        names.push(key.clone());
830        let serde_json::Value::String(s) = json_value else {
831            values.push(Value::Str(json_value.to_string().into()));
832            continue;
833        };
834        let trimmed = s.trim();
835        let pure_token = trimmed.starts_with('{')
836            && trimmed.ends_with('}')
837            && !trimmed.starts_with("{{")
838            && trimmed.len() >= 2
839            && trimmed[1..trimmed.len() - 1]
840                .chars()
841                .all(|c| c != '{' && c != '}');
842        if pure_token {
843            let body = trimmed[1..trimmed.len() - 1].trim();
844            let bare = match body.split_once(':') {
845                Some((_, n)) => n,
846                None => body,
847            };
848            if is_bare_ident(bare) {
849                match wires.get(bare) {
850                    Some(v) => {
851                        values.push(v);
852                        continue;
853                    }
854                    None => {
855                        return Err(format!(
856                            "unresolved bind point `{{{bare}}}` in field '{key}': \
857                             no wire named `{bare}` in the dispenser's Polydat context"
858                        ));
859                    }
860                }
861            }
862        }
863        let rendered = substitute_via_wires(s, wires).map_err(|e| format!("field '{key}': {e}"))?;
864        values.push(Value::Str(rendered.into()));
865    }
866    Ok(crate::adapter::ResolvedFields::new(names, values))
867}
868
869/// Wire types that have no meaningful text-spliced representation
870/// in a wire-protocol field. Embedding `{wire}` for one of these
871/// inside a larger string template (CQL prepared text, HTTP body,
872/// etc.) is always a workload-shape bug: the typed value should
873/// flow through the adapter's typed-binding API, not be
874/// decimal-stringified into the SQL/JSON/body text and reparsed
875/// downstream.
876///
877/// Used by [`substitute_via_wires`] to refuse the splice and by
878/// the future op-template construction-time guard (init-time
879/// shape check) to reject equivalent misuse before any cycle runs.
880fn is_binary_natural(t: PortType) -> bool {
881    matches!(
882        t,
883        PortType::VecF32
884            | PortType::VecI32
885            | PortType::VecF64
886            | PortType::VecI64
887            | PortType::VecF16
888            | PortType::VecI16
889            | PortType::Handle
890            | PortType::Bytes
891    )
892}
893
894/// Same identifier discipline as the core `resolve_placeholders_in_string`
895/// validator in `crate::scope`: ASCII-alpha-or-underscore start,
896/// remainder ASCII-alphanumeric-or-underscore. Anything else is
897/// not a bare identifier and passes through.
898fn is_bare_ident(s: &str) -> bool {
899    let mut chars = s.chars();
900    match chars.next() {
901        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
902        _ => return false,
903    }
904    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
905}
906
907/// A dotted identifier chain (`q.cursor.idx`): two or more
908/// bare-identifier segments joined by single dots. These follow
909/// the field-access wire convention and resolve through the
910/// `__`-flattened spelling.
911fn is_dotted_ident(s: &str) -> bool {
912    let segments: Vec<&str> = s.split('.').collect();
913    segments.len() >= 2 && segments.iter().all(|seg| is_bare_ident(seg))
914}
915
916#[cfg(test)]
917mod tests {
918    use super::*;
919    use polydat::dsl::compile::compile_polydat_interpreter;
920
921    #[test]
922    fn scope_kernel_get_resolves_inputs_and_constants() {
923        // `lookup` (and therefore Push 1's WireSource) covers
924        // input slots and scope-init constants — the names available
925        // without a memoizing pull. `folded := 42` lands as a
926        // compile-folded constant; `cycle` is a coordinate input.
927        let mut k = crate::scope_kernel::ScopeKernel::compile(
928            "input cycle: u64\n\
929             folded := 42\n",
930        )
931        .unwrap();
932        k.set_inputs(&[7]);
933        let wires: &dyn WireSource = &k;
934        assert_eq!(wires.get("folded").map(|v| v.as_u64()), Some(42));
935        assert_eq!(wires.get("cycle").map(|v| v.as_u64()), Some(7));
936    }
937
938    #[test]
939    fn scope_kernel_get_returns_none_for_pull_only_outputs_in_push_1() {
940        // Push 1 baseline: outputs that require a memoizing
941        // `pull(&mut state, …)` evaluation are NOT served by the
942        // `&ScopeKernel` impl. Push 2 introduces the kernel-owning
943        // wires impl that can pull outputs. This test pins the
944        // current contract so the Push 2 change is visible as a
945        // diff.
946        let mut k = crate::scope_kernel::ScopeKernel::compile(
947            "input cycle: u64\n\
948             cyc_dep := hash(cycle)\n",
949        )
950        .unwrap();
951        k.set_inputs(&[7]);
952        let wires: &dyn WireSource = &k;
953        assert!(wires.get("cyc_dep").is_none());
954    }
955
956    #[test]
957    fn scope_kernel_get_returns_none_for_unknown_name() {
958        let k = crate::scope_kernel::ScopeKernel::compile("input cycle: u64\nx := 1\n").unwrap();
959        let wires: &dyn WireSource = &k;
960        assert!(wires.get("not_a_real_name").is_none());
961    }
962
963    #[test]
964    fn scope_kernel_names_lists_declared_outputs_and_inputs() {
965        let k =
966            crate::scope_kernel::ScopeKernel::compile("input cycle: u64\nfolded := 42\n").unwrap();
967        let wires: &dyn WireSource = &k;
968        let names: Vec<String> = wires.names().collect();
969        assert!(
970            names.iter().any(|n| n == "folded"),
971            "folded should appear: {names:?}"
972        );
973        assert!(
974            names.iter().any(|n| n == "cycle"),
975            "cycle should appear: {names:?}"
976        );
977    }
978
979    #[test]
980    fn null_wires_returns_none_and_empty() {
981        let wires: &dyn WireSource = &NULL_WIRES;
982        assert!(wires.get("anything").is_none());
983        assert_eq!(wires.names().count(), 0);
984    }
985
986    #[test]
987    fn cycle_wires_pulls_outputs() {
988        // CycleWires (Push 4) covers the memoizing-pull path that
989        // the bare `&ScopeKernel` impl can't reach. `cyc_dep` is a
990        // computed output — pulling it requires `&mut state` to
991        // fire the eval cone and cache the result.
992        let mut k = crate::scope_kernel::ScopeKernel::compile(
993            "input cycle: u64\n\
994             folded := 42\n\
995             cyc_dep := hash(cycle)\n",
996        )
997        .unwrap();
998        k.set_inputs(&[7]);
999        let cw = CycleWires::new(&mut k);
1000        let wires: &dyn WireSource = &cw;
1001        // Output pull works through CycleWires.
1002        let v = wires.get("cyc_dep").expect("cyc_dep should resolve");
1003        assert!(v.as_u64() != 0, "hash result should be non-zero");
1004        // Folded constant still resolves.
1005        assert_eq!(wires.get("folded").map(|v| v.as_u64()), Some(42));
1006        // Coordinate input still resolves.
1007        assert_eq!(wires.get("cycle").map(|v| v.as_u64()), Some(7));
1008    }
1009
1010    /// SRD-93-era fold totality: `reset` restores a wire to its
1011    /// DECLARED initial value — the author's identity element — so an
1012    /// empty min/max fold never parks `Value::None` on a typed slot
1013    /// and never leaves a stale prior reading.
1014    #[test]
1015    fn cycle_wires_reset_restores_declared_default() {
1016        let mut k = compile_polydat_interpreter(
1017            "input cycle: u64\nextern pressure: u64 = 7\nx := pressure + 1\n",
1018        )
1019        .unwrap();
1020        let cw = CycleWires::new(&mut k);
1021        let wires: &dyn WireSource = &cw;
1022
1023        assert_eq!(
1024            wires.write("pressure", Value::U64(42)),
1025            WriteOutcome::Stored
1026        );
1027        assert_eq!(wires.get("pressure").map(|v| v.as_u64()), Some(42));
1028
1029        assert_eq!(
1030            wires.reset("pressure"),
1031            WriteOutcome::Stored,
1032            "reset writes the declared default through the typed boundary"
1033        );
1034        assert_eq!(
1035            wires.get("pressure").map(|v| v.as_u64()),
1036            Some(7),
1037            "the wire returns to its declared initial value, not to None/0"
1038        );
1039
1040        assert_eq!(wires.reset("nonesuch"), WriteOutcome::NoSlot);
1041    }
1042
1043    #[test]
1044    fn cycle_wires_returns_none_for_unknown_name() {
1045        let mut k = compile_polydat_interpreter("input cycle: u64\nx := 1\n").unwrap();
1046        let cw = CycleWires::new(&mut k);
1047        let wires: &dyn WireSource = &cw;
1048        assert!(wires.get("not_a_real_name").is_none());
1049    }
1050
1051    #[test]
1052    fn cycle_wires_resolves_phase_binding_lhs_names() {
1053        // SRD-68 Push 4b sanity check: a workload's phase
1054        // binding (e.g. `target_index_table := pick(...)`) becomes
1055        // an output on the per-op canonical kernel after
1056        // `OpBuilder::canonical_kernel_for_op`. Per-fiber
1057        // instances built from it via `build_subscope` carry that
1058        // output. Wrapping such a per-fiber kernel in `CycleWires`
1059        // and calling `wires.get(phase_binding_name)` returns the
1060        // computed value — no text substitution required at
1061        // adapter cycle time.
1062        //
1063        // This unit test simulates the shape directly via
1064        // `compile_polydat_interpreter` rather than spinning up the full activity
1065        // pipeline; it pins the contract that `wires.get` answers
1066        // for any name the program declares as an output.
1067        let mut k = compile_polydat_interpreter(
1068            "input cycle: u64\n\
1069             keyspace := \"baselines\"\n\
1070             table := \"vec_label_00\"\n\
1071             # `pick`-equivalent with constant booleans for testability:\n\
1072             # take the first value when its selector is true.\n\
1073             target_index_table := \"system_views.sai_column_indexes\"\n",
1074        )
1075        .unwrap();
1076        k.set_inputs(&[0]);
1077        let cw = CycleWires::new(&mut k);
1078        let wires: &dyn WireSource = &cw;
1079        assert_eq!(
1080            wires
1081                .get("target_index_table")
1082                .map(|v| v.as_str().to_string()),
1083            Some("system_views.sai_column_indexes".to_string()),
1084            "phase-binding LHS should resolve through CycleWires",
1085        );
1086        assert_eq!(
1087            wires.get("keyspace").map(|v| v.as_str().to_string()),
1088            Some("baselines".to_string()),
1089        );
1090    }
1091
1092    #[test]
1093    fn substitute_via_wires_resolves_bare_names() {
1094        let mut k = compile_polydat_interpreter(
1095            "input cycle: u64\n\
1096             keyspace := \"baselines\"\n\
1097             table := \"vec_label_00\"\n",
1098        )
1099        .unwrap();
1100        let cw = CycleWires::new(&mut k);
1101        let resolved =
1102            substitute_via_wires("SELECT * FROM {keyspace}.{table} WHERE x = 1", &cw).unwrap();
1103        assert_eq!(resolved, "SELECT * FROM baselines.vec_label_00 WHERE x = 1");
1104    }
1105
1106    #[test]
1107    fn substitute_via_wires_passes_through_literal_braces() {
1108        let mut k = compile_polydat_interpreter(
1109            "input cycle: u64\n\
1110             ks := \"baselines\"\n",
1111        )
1112        .unwrap();
1113        let cw = CycleWires::new(&mut k);
1114        // CQL map literal: brace bodies starting with quotes are
1115        // not bare identifiers, pass through verbatim.
1116        let resolved = substitute_via_wires(
1117            "CREATE KEYSPACE {ks} WITH replication = {'class': 'SimpleStrategy'}",
1118            &cw,
1119        )
1120        .unwrap();
1121        assert_eq!(
1122            resolved,
1123            "CREATE KEYSPACE baselines WITH replication = {'class': 'SimpleStrategy'}",
1124        );
1125    }
1126
1127    /// Binary-natural type guard. A wire holding `VecF32` (or any
1128    /// other type with no meaningful text-spliced form) must not be
1129    /// silently decimal-stringified into the field text — that's a
1130    /// workload-shape bug (the value belongs in a typed-binding
1131    /// path, not the text template). The substitution layer
1132    /// rejects with a clear diagnostic pointing at the wire and
1133    /// suggesting both fixes (pure-token form / bindvars split).
1134    ///
1135    /// Regression guard: dropping this check would silently burn
1136    /// per-element Grisu float formatting (≈55% of cycle CPU on
1137    /// the fknn_rampup_data shape) on every cycle.
1138    #[test]
1139    fn substitute_via_wires_rejects_vec_f32_in_text_template() {
1140        use polydat::ast::SliceArc;
1141        struct VecWire;
1142        impl WireSource for VecWire {
1143            fn get(&self, name: &str) -> Option<Value> {
1144                match name {
1145                    "id" => Some(Value::U64(7)),
1146                    "vec" => Some(Value::VecF32(SliceArc::from_vec(vec![0.1_f32, 0.2, 0.3]))),
1147                    _ => None,
1148                }
1149            }
1150            fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
1151                Box::new(["id", "vec"].iter().map(|s| s.to_string()))
1152            }
1153        }
1154        let err = substitute_via_wires("INSERT ... VALUES ('{id}', {vec})", &VecWire)
1155            .expect_err("VecF32 splice into text template must error");
1156        assert!(
1157            err.contains("vec"),
1158            "diagnostic should name the offending wire: {err}"
1159        );
1160        assert!(
1161            err.contains("vec_f32") || err.contains("VecF32"),
1162            "diagnostic should name the offending type: {err}"
1163        );
1164        assert!(
1165            err.contains("pure-token") || err.contains("typed"),
1166            "diagnostic should point at the fix: {err}"
1167        );
1168    }
1169
1170    /// The escape hatch: a field whose entire value is a pure
1171    /// token `{wire}` (no surrounding text) routes through case 2
1172    /// in `resolve_op_fields_via_wires` — typed Value preserved,
1173    /// no substitution. `substitute_via_wires` itself is only
1174    /// invoked on text-template fields, so the rejection above
1175    /// fires only when the binary-natural wire is genuinely being
1176    /// spliced into surrounding text. Pin that: a VecI32 wire
1177    /// triggers the same rejection (catches the broader contract,
1178    /// not a VecF32-only special case).
1179    #[test]
1180    fn substitute_via_wires_rejects_vec_i32_in_text_template() {
1181        use polydat::ast::SliceArc;
1182        struct VecI32Wire;
1183        impl WireSource for VecI32Wire {
1184            fn get(&self, name: &str) -> Option<Value> {
1185                if name == "vec" {
1186                    Some(Value::VecI32(SliceArc::from_vec(vec![1_i32, 2, 3])))
1187                } else {
1188                    None
1189                }
1190            }
1191            fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
1192                Box::new(std::iter::once("vec".to_string()))
1193            }
1194        }
1195        let err = substitute_via_wires("x = {vec}", &VecI32Wire).unwrap_err();
1196        assert!(
1197            err.contains("vec_i32") || err.contains("VecI32"),
1198            "VecI32 should also be rejected: {err}"
1199        );
1200    }
1201
1202    #[test]
1203    fn substitute_via_wires_errors_on_unresolved_name() {
1204        let mut k = compile_polydat_interpreter("input cycle: u64\nx := \"a\"\n").unwrap();
1205        let cw = CycleWires::new(&mut k);
1206        let err = substitute_via_wires("hi {nonexistent}", &cw).unwrap_err();
1207        assert!(
1208            err.contains("nonexistent"),
1209            "diagnostic should name the wire: {err}"
1210        );
1211        assert!(
1212            err.contains("unresolved"),
1213            "diagnostic should call out unresolved: {err}"
1214        );
1215    }
1216
1217    #[test]
1218    fn substitute_via_wires_errors_when_wire_resolves_to_none() {
1219        // SRD-74 Rule 3 strict render: a wire that EXISTS but
1220        // resolves to `Value::None` (e.g. a `const X := "{undef}"`
1221        // whose RHS interpolation propagated None per Rule 1, then
1222        // the conditional-shadow chain found no upstream binding
1223        // either) must error at substitution time — NOT silently
1224        // render as `""`. Empty string is a real value; absent is
1225        // not the same thing, and conflating them was the
1226        // wire-protocol corruption class this SRD closes.
1227        let mut k = compile_polydat_interpreter(
1228            "input cycle: u64\n\
1229             extern undef: str\n\
1230             const x := \"{undef}\"\n",
1231        )
1232        .unwrap();
1233        let cw = CycleWires::new(&mut k);
1234        let err = substitute_via_wires("source_model='{x}'", &cw).unwrap_err();
1235        assert!(
1236            err.contains("`{x}`"),
1237            "diagnostic should name the bind-point: {err}"
1238        );
1239        assert!(
1240            err.contains("Value::None") || err.contains("no value bound"),
1241            "diagnostic should explain the None resolution: {err}"
1242        );
1243    }
1244
1245    #[test]
1246    fn to_display_strict_returns_none_for_value_none() {
1247        // The strict primitive itself; render sites consume it.
1248        use polydat::ast::Value;
1249        assert_eq!(Value::None.to_display_strict(), None);
1250        assert_eq!(
1251            Value::Str("hello".into()).to_display_strict(),
1252            Some("hello".to_string())
1253        );
1254        assert_eq!(Value::U64(42).to_display_strict(), Some("42".to_string()));
1255    }
1256
1257    #[test]
1258    fn substitute_via_wires_resolves_inside_cql_options_map() {
1259        // Pin the failure shape that surfaced in
1260        // `full_cql_vector.yaml`: a CQL `WITH OPTIONS = {'k':
1261        // '{value}'}` map. The earlier substitution algorithm
1262        // truncated the body at the first `}` (the inner
1263        // placeholder's `}`), then treated the outer `{...}`
1264        // as one literal-content body — so inner `{value}`
1265        // placeholders inside the map were never resolved.
1266        // The fix mirrors `nmbrs_workload::bindpoints::extract_bind_points`:
1267        // when `{` is followed by `'` or `"`, treat it as a CQL
1268        // map opener (emit the brace, continue scanning).
1269        let mut k = compile_polydat_interpreter(
1270            "input cycle: u64\n\
1271             optimize_for := \"RECALL\"\n\
1272             similarity_function := \"EUCLIDEAN\"\n",
1273        )
1274        .unwrap();
1275        let cw = CycleWires::new(&mut k);
1276        let resolved = substitute_via_wires(
1277            "WITH OPTIONS = {'optimize_for': '{optimize_for}', 'similarity_function': '{similarity_function}'}",
1278            &cw,
1279        ).unwrap();
1280        assert_eq!(
1281            resolved,
1282            "WITH OPTIONS = {'optimize_for': 'RECALL', 'similarity_function': 'EUCLIDEAN'}",
1283            "nested `{{name}}` placeholders inside CQL map literals must resolve"
1284        );
1285    }
1286
1287    #[test]
1288    fn substitute_via_wires_errors_on_qualifier_prefix() {
1289        let mut k = compile_polydat_interpreter("input cycle: u64\nx := \"a\"\n").unwrap();
1290        let cw = CycleWires::new(&mut k);
1291        let err = substitute_via_wires("hi {bind:x}", &cw).unwrap_err();
1292        assert!(
1293            err.contains("bind:x"),
1294            "diagnostic should name the qualifier form: {err}"
1295        );
1296    }
1297
1298    #[test]
1299    fn substitute_via_wires_passes_through_inline_expr() {
1300        let mut k = compile_polydat_interpreter("input cycle: u64\nx := \"a\"\n").unwrap();
1301        let cw = CycleWires::new(&mut k);
1302        let resolved = substitute_via_wires("v = {{x + 1}}", &cw).unwrap();
1303        // `{{...}}` is reserved for the inline-expression desugar
1304        // surface (compiled into bindings before reaching cycle
1305        // time); cycle-time substitute_via_wires passes it
1306        // through unchanged.
1307        assert_eq!(resolved, "v = {{x + 1}}");
1308    }
1309
1310    #[test]
1311    fn cycle_wires_resolves_iter_var_through_subscope_chain() {
1312        // SRD-68 invariant from user: "the Polydat context visible after
1313        // initialization in each scope is designed to and required
1314        // to provide all of the values which should be visible
1315        // including those which are populated at logical closure
1316        // boundaries based on comprehensions."
1317        //
1318        // Concretely: a for_each scope kernel populates iter vars
1319        // on its INPUT slots (per `for_iteration`). The phase
1320        // scope kernel then inherits them via `build_subscope`.
1321        // The op-template canonical (built via `build_subscope`
1322        // again) MUST also carry the iter var values so cycle-time
1323        // `wires.get(iter_var_name)` answers correctly.
1324        //
1325        // This test mirrors that chain: parent kernel has
1326        // `optimize_for` as an extern input declaration with a
1327        // populated value; child kernel declares the same name;
1328        // verify the value propagates when the child is bound under
1329        // the parent, as every scope is, and is visible via
1330        // `CycleWires::get`.
1331        use polydat::ast::Value;
1332
1333        // Parent: declares `optimize_for` as extern + auto-passthrough
1334        // output via `final` — same pattern the phase synthesizer
1335        // uses for iter-var cascade.
1336        let mut parent = crate::scope_kernel::ScopeKernel::compile(
1337            "input cycle: u64\n\
1338             extern optimize_for: str\n",
1339        )
1340        .unwrap();
1341        // Populate the input slot the way the phase kernel does
1342        // after binding under the for_each bound_kernel.
1343        let opt_idx = parent
1344            .program()
1345            .find_input("optimize_for")
1346            .expect("optimize_for input slot");
1347        parent
1348            .set_input_at(opt_idx, Value::Str("RECALL".into()))
1349            .expect("write optimize_for");
1350
1351        // Child: program declares the same name as an extern.
1352        // Mimics the per-op canonical the dispenser owns.
1353        let child_scope = crate::scope_kernel::ScopeKernel::compile(
1354            "input cycle: u64\n\
1355             extern optimize_for: str\n",
1356        )
1357        .unwrap();
1358        let mut child = child_scope
1359            .bind_under(parent.kernel(), &[])
1360            .expect("the child binds under the parent");
1361
1362        let cw = CycleWires::new(&mut child);
1363        let wires: &dyn WireSource = &cw;
1364        // The architectural contract: child's CycleWires resolves
1365        // `optimize_for` through the inheritance chain. If this
1366        // assertion fails, the chain isn't propagating iter vars
1367        // and we need the gap fix at the Polydat Kernel layer.
1368        assert_eq!(
1369            wires.get("optimize_for").map(|v| v.as_str().to_string()),
1370            Some("RECALL".to_string()),
1371            "iter-var input populated on parent should propagate \
1372             through binding to child's WireSource",
1373        );
1374    }
1375
1376    #[test]
1377    fn extern_decl_only_produces_input_no_output() {
1378        // Diagnostic: an `extern <name>: <type>` declaration by
1379        // itself creates an INPUT but does NOT publish a matching
1380        // output. So `materialize_wiring_from_outer` (which walks outer's
1381        // outputs) wouldn't find this name and wouldn't propagate
1382        // it to descendants. The synthesis pipeline avoids this by
1383        // also calling `mark_inherited_outputs` on the kernel
1384        // post-build, but a plain `extern` line doesn't.
1385        //
1386        // Pinning this so the next person reading the source isn't
1387        // surprised — `cycle_wires_resolves_iter_var_through_subscope_chain`
1388        // passes only because the `str` extern's auto-passthrough
1389        // output (added by the compiler when the name appears in the
1390        // body) gives materialize_wiring_from_outer something to walk. With ONLY
1391        // an extern decl, there's no body reference, no auto-passthrough,
1392        // and the chain breaks.
1393        use polydat::dsl::compile::compile_polydat_interpreter;
1394        let k = compile_polydat_interpreter(
1395            "input cycle: u64\n\
1396             extern optimize_for: str\n",
1397        )
1398        .unwrap();
1399        let outputs: Vec<&str> = k.program().output_names().to_vec();
1400        // If this assertion fails (i.e. `optimize_for` IS in
1401        // outputs), then the chain test above was a no-op and we
1402        // need to revisit the architectural question.
1403        // Document whichever is true.
1404        eprintln!("DBG outputs from `extern optimize_for: str`: {outputs:?}");
1405    }
1406
1407    #[test]
1408    fn cycle_wires_advance_drives_per_row_pulls() {
1409        // SRD-68 batch contract: `advance(coord)` mutates the
1410        // underlying kernel's coord input so subsequent `get`
1411        // calls produce values for that coord. Verify by pulling
1412        // a coord-dependent output before and after advance.
1413        let mut k = compile_polydat_interpreter(
1414            "input cycle: u64\n\
1415             id := format_u64(cycle, 10)\n",
1416        )
1417        .unwrap();
1418        k.set_inputs(&[0]);
1419        let cw = CycleWires::new(&mut k);
1420        let wires: &dyn WireSource = &cw;
1421        // First read at cycle=0.
1422        assert_eq!(
1423            wires.get("id").map(|v| v.as_str().to_string()),
1424            Some("0".to_string())
1425        );
1426        // Advance and re-read.
1427        wires.advance(42);
1428        assert_eq!(
1429            wires.get("id").map(|v| v.as_str().to_string()),
1430            Some("42".to_string())
1431        );
1432        wires.advance(7);
1433        assert_eq!(
1434            wires.get("id").map(|v| v.as_str().to_string()),
1435            Some("7".to_string())
1436        );
1437    }
1438
1439    #[test]
1440    fn null_wires_advance_is_noop() {
1441        // Default `advance` impl on `NullWireSource` does nothing;
1442        // useful as a sanity check that advance on a non-batch-
1443        // capable wires doesn't panic.
1444        let wires: &dyn WireSource = &NULL_WIRES;
1445        wires.advance(0);
1446        wires.advance(123);
1447        assert!(wires.get("anything").is_none());
1448    }
1449
1450    #[test]
1451    fn cycle_wires_write_lands_on_input_slot_visible_to_get() {
1452        // SRD-66 capture flow: ResultDispenser writes a magic-extern
1453        // input (e.g. `count`), then a later wrapper or the eval
1454        // cone reads it. `wires.write` lands the value; `wires.get`
1455        // returns it on the next read.
1456        let mut k = compile_polydat_interpreter(
1457            "input cycle: u64\n\
1458             extern count: u64\n\
1459             extern body: json\n",
1460        )
1461        .unwrap();
1462        k.set_inputs(&[0]);
1463        let cw = CycleWires::new(&mut k);
1464        let wires: &dyn WireSource = &cw;
1465
1466        assert_eq!(wires.write("count", Value::U64(42)), WriteOutcome::Stored);
1467        assert_eq!(wires.get("count").map(|v| v.as_u64()), Some(42));
1468
1469        // Overwrite — the new value supersedes the old.
1470        assert_eq!(wires.write("count", Value::U64(7)), WriteOutcome::Stored);
1471        assert_eq!(wires.get("count").map(|v| v.as_u64()), Some(7));
1472    }
1473
1474    #[test]
1475    fn cycle_wires_write_returns_no_slot_for_unknown_name() {
1476        // The closure-binding economy's DCE signal: no slot, value
1477        // silently dropped. Caller is unaffected.
1478        let mut k = compile_polydat_interpreter("input cycle: u64\nx := 1\n").unwrap();
1479        let cw = CycleWires::new(&mut k);
1480        let wires: &dyn WireSource = &cw;
1481        assert_eq!(wires.write("nope", Value::U64(99)), WriteOutcome::NoSlot);
1482    }
1483
1484    #[test]
1485    fn cycle_wires_write_feeds_eval_cone_through_get() {
1486        // The full capture-then-pull flow: write a magic-extern
1487        // input, read an output that depends on it through the
1488        // eval cone. This is the metrics-wrapper-reading-row_count
1489        // scenario from the design memo.
1490        let mut k = compile_polydat_interpreter(
1491            "input cycle: u64\n\
1492             extern count: u64\n\
1493             row_count := count\n",
1494        )
1495        .unwrap();
1496        k.set_inputs(&[0]);
1497        let cw = CycleWires::new(&mut k);
1498        let wires: &dyn WireSource = &cw;
1499
1500        // Before the write, `count` is at its default and
1501        // `row_count` reflects that.
1502        assert_eq!(wires.write("count", Value::U64(123)), WriteOutcome::Stored);
1503        // The pull through `row_count` (an output) reads the
1504        // freshly-written `count` (an input).
1505        assert_eq!(wires.get("row_count").map(|v| v.as_u64()), Some(123));
1506    }
1507
1508    #[test]
1509    fn null_wires_write_returns_no_slot() {
1510        let wires: &dyn WireSource = &NULL_WIRES;
1511        assert_eq!(wires.write("anything", Value::U64(1)), WriteOutcome::NoSlot);
1512    }
1513
1514    #[test]
1515    fn resolve_op_fields_four_case_dispatch() {
1516        // Pin the four-case dispatch contract for op-field resolution.
1517        // See `resolve_op_fields_via_wires` doc for the cases.
1518        let mut k = compile_polydat_interpreter(
1519            "input cycle: u64\n\
1520             table := \"users\"\n\
1521             count := 42\n",
1522        )
1523        .unwrap();
1524        let cw = CycleWires::new(&mut k);
1525
1526        let fields: Vec<(String, serde_json::Value)> = vec![
1527            // Case 1: non-string JSON scalar — stringified.
1528            ("limit_num".into(), serde_json::json!(100)),
1529            // Case 2: pure-token — typed wire reference, count is U64(42).
1530            (
1531                "typed_ref".into(),
1532                serde_json::Value::String("{count}".into()),
1533            ),
1534            // Case 3: text template — wires.get(table).to_display_string()
1535            //          interpolated into the surrounding text.
1536            (
1537                "templated".into(),
1538                serde_json::Value::String("SELECT * FROM {table} WHERE x = 1".into()),
1539            ),
1540            // Case 4: bare-string literal — no placeholders, passes through.
1541            (
1542                "literal_stmt".into(),
1543                serde_json::Value::String("SELECT 1".into()),
1544            ),
1545        ];
1546
1547        let resolved = resolve_op_fields_via_wires(&fields, &cw).expect("four-case dispatch");
1548
1549        // Case 1: stringified — exact form is implementation-defined,
1550        // verify the value contains the digits.
1551        assert!(
1552            matches!(resolved.get_value("limit_num"),
1553            Some(polydat::ast::Value::Str(s)) if s.contains("100")),
1554            "case 1: got {:?}",
1555            resolved.get_value("limit_num")
1556        );
1557        // Case 2: typed U64.
1558        assert_eq!(
1559            resolved.get_value("typed_ref").map(|v| v.as_u64()),
1560            Some(42),
1561            "case 2: typed wire ref preserves U64"
1562        );
1563        // Case 3: interpolated string.
1564        assert_eq!(
1565            resolved.get_str("templated"),
1566            Some("SELECT * FROM users WHERE x = 1"),
1567            "case 3: text template"
1568        );
1569        // Case 4: literal pass-through.
1570        assert_eq!(
1571            resolved.get_str("literal_stmt"),
1572            Some("SELECT 1"),
1573            "case 4: bare string literal"
1574        );
1575    }
1576
1577    #[test]
1578    fn cycle_wires_caches_across_repeated_gets() {
1579        // Pull memoizes; a second get of the same name reads the
1580        // cached value off state, not re-runs the eval cone. We
1581        // can't directly observe memoization but we CAN observe
1582        // that two reads of the same cycle produce the same value
1583        // (hash is deterministic per coordinate, but the kernel's
1584        // dirty-tracking would require a state mutation to
1585        // re-fire — the property still holds).
1586        let mut k = compile_polydat_interpreter("input cycle: u64\nh := hash(cycle)\n").unwrap();
1587        k.set_inputs(&[42]);
1588        let cw = CycleWires::new(&mut k);
1589        let wires: &dyn WireSource = &cw;
1590        let v1 = wires.get("h").unwrap().as_u64();
1591        let v2 = wires.get("h").unwrap().as_u64();
1592        assert_eq!(v1, v2);
1593    }
1594}