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            | PortType::Forms
892            | PortType::Fragment
893            | PortType::AdmittedRows
894    )
895}
896
897/// Same identifier discipline as the core `resolve_placeholders_in_string`
898/// validator in `crate::scope`: ASCII-alpha-or-underscore start,
899/// remainder ASCII-alphanumeric-or-underscore. Anything else is
900/// not a bare identifier and passes through.
901fn is_bare_ident(s: &str) -> bool {
902    let mut chars = s.chars();
903    match chars.next() {
904        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
905        _ => return false,
906    }
907    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
908}
909
910/// A dotted identifier chain (`q.cursor.idx`): two or more
911/// bare-identifier segments joined by single dots. These follow
912/// the field-access wire convention and resolve through the
913/// `__`-flattened spelling.
914fn is_dotted_ident(s: &str) -> bool {
915    let segments: Vec<&str> = s.split('.').collect();
916    segments.len() >= 2 && segments.iter().all(|seg| is_bare_ident(seg))
917}
918
919#[cfg(test)]
920mod tests {
921    use super::*;
922    use polydat::dsl::compile::compile_polydat_interpreter;
923
924    #[test]
925    fn scope_kernel_get_resolves_inputs_and_constants() {
926        // `lookup` (and therefore Push 1's WireSource) covers
927        // input slots and scope-init constants — the names available
928        // without a memoizing pull. `folded := 42` lands as a
929        // compile-folded constant; `cycle` is a coordinate input.
930        let mut k = crate::scope_kernel::ScopeKernel::compile(
931            "input cycle: u64\n\
932             folded := 42\n",
933        )
934        .unwrap();
935        k.set_inputs(&[7]);
936        let wires: &dyn WireSource = &k;
937        assert_eq!(wires.get("folded").map(|v| v.as_u64()), Some(42));
938        assert_eq!(wires.get("cycle").map(|v| v.as_u64()), Some(7));
939    }
940
941    #[test]
942    fn scope_kernel_get_returns_none_for_pull_only_outputs_in_push_1() {
943        // Push 1 baseline: outputs that require a memoizing
944        // `pull(&mut state, …)` evaluation are NOT served by the
945        // `&ScopeKernel` impl. Push 2 introduces the kernel-owning
946        // wires impl that can pull outputs. This test pins the
947        // current contract so the Push 2 change is visible as a
948        // diff.
949        let mut k = crate::scope_kernel::ScopeKernel::compile(
950            "input cycle: u64\n\
951             cyc_dep := hash(cycle)\n",
952        )
953        .unwrap();
954        k.set_inputs(&[7]);
955        let wires: &dyn WireSource = &k;
956        assert!(wires.get("cyc_dep").is_none());
957    }
958
959    #[test]
960    fn scope_kernel_get_returns_none_for_unknown_name() {
961        let k = crate::scope_kernel::ScopeKernel::compile("input cycle: u64\nx := 1\n").unwrap();
962        let wires: &dyn WireSource = &k;
963        assert!(wires.get("not_a_real_name").is_none());
964    }
965
966    #[test]
967    fn scope_kernel_names_lists_declared_outputs_and_inputs() {
968        let k =
969            crate::scope_kernel::ScopeKernel::compile("input cycle: u64\nfolded := 42\n").unwrap();
970        let wires: &dyn WireSource = &k;
971        let names: Vec<String> = wires.names().collect();
972        assert!(
973            names.iter().any(|n| n == "folded"),
974            "folded should appear: {names:?}"
975        );
976        assert!(
977            names.iter().any(|n| n == "cycle"),
978            "cycle should appear: {names:?}"
979        );
980    }
981
982    #[test]
983    fn null_wires_returns_none_and_empty() {
984        let wires: &dyn WireSource = &NULL_WIRES;
985        assert!(wires.get("anything").is_none());
986        assert_eq!(wires.names().count(), 0);
987    }
988
989    #[test]
990    fn cycle_wires_pulls_outputs() {
991        // CycleWires (Push 4) covers the memoizing-pull path that
992        // the bare `&ScopeKernel` impl can't reach. `cyc_dep` is a
993        // computed output — pulling it requires `&mut state` to
994        // fire the eval cone and cache the result.
995        let mut k = crate::scope_kernel::ScopeKernel::compile(
996            "input cycle: u64\n\
997             folded := 42\n\
998             cyc_dep := hash(cycle)\n",
999        )
1000        .unwrap();
1001        k.set_inputs(&[7]);
1002        let cw = CycleWires::new(&mut k);
1003        let wires: &dyn WireSource = &cw;
1004        // Output pull works through CycleWires.
1005        let v = wires.get("cyc_dep").expect("cyc_dep should resolve");
1006        assert!(v.as_u64() != 0, "hash result should be non-zero");
1007        // Folded constant still resolves.
1008        assert_eq!(wires.get("folded").map(|v| v.as_u64()), Some(42));
1009        // Coordinate input still resolves.
1010        assert_eq!(wires.get("cycle").map(|v| v.as_u64()), Some(7));
1011    }
1012
1013    /// SRD-93-era fold totality: `reset` restores a wire to its
1014    /// DECLARED initial value — the author's identity element — so an
1015    /// empty min/max fold never parks `Value::None` on a typed slot
1016    /// and never leaves a stale prior reading.
1017    #[test]
1018    fn cycle_wires_reset_restores_declared_default() {
1019        let mut k = compile_polydat_interpreter(
1020            "input cycle: u64\nextern pressure: u64 = 7\nx := pressure + 1\n",
1021        )
1022        .unwrap();
1023        let cw = CycleWires::new(&mut k);
1024        let wires: &dyn WireSource = &cw;
1025
1026        assert_eq!(
1027            wires.write("pressure", Value::U64(42)),
1028            WriteOutcome::Stored
1029        );
1030        assert_eq!(wires.get("pressure").map(|v| v.as_u64()), Some(42));
1031
1032        assert_eq!(
1033            wires.reset("pressure"),
1034            WriteOutcome::Stored,
1035            "reset writes the declared default through the typed boundary"
1036        );
1037        assert_eq!(
1038            wires.get("pressure").map(|v| v.as_u64()),
1039            Some(7),
1040            "the wire returns to its declared initial value, not to None/0"
1041        );
1042
1043        assert_eq!(wires.reset("nonesuch"), WriteOutcome::NoSlot);
1044    }
1045
1046    #[test]
1047    fn cycle_wires_returns_none_for_unknown_name() {
1048        let mut k = compile_polydat_interpreter("input cycle: u64\nx := 1\n").unwrap();
1049        let cw = CycleWires::new(&mut k);
1050        let wires: &dyn WireSource = &cw;
1051        assert!(wires.get("not_a_real_name").is_none());
1052    }
1053
1054    #[test]
1055    fn cycle_wires_resolves_phase_binding_lhs_names() {
1056        // SRD-68 Push 4b sanity check: a workload's phase
1057        // binding (e.g. `target_index_table := pick(...)`) becomes
1058        // an output on the per-op canonical kernel after
1059        // `OpBuilder::canonical_kernel_for_op`. Per-fiber
1060        // instances built from it via `build_subscope` carry that
1061        // output. Wrapping such a per-fiber kernel in `CycleWires`
1062        // and calling `wires.get(phase_binding_name)` returns the
1063        // computed value — no text substitution required at
1064        // adapter cycle time.
1065        //
1066        // This unit test simulates the shape directly via
1067        // `compile_polydat_interpreter` rather than spinning up the full activity
1068        // pipeline; it pins the contract that `wires.get` answers
1069        // for any name the program declares as an output.
1070        let mut k = compile_polydat_interpreter(
1071            "input cycle: u64\n\
1072             keyspace := \"baselines\"\n\
1073             table := \"vec_label_00\"\n\
1074             # `pick`-equivalent with constant booleans for testability:\n\
1075             # take the first value when its selector is true.\n\
1076             target_index_table := \"system_views.sai_column_indexes\"\n",
1077        )
1078        .unwrap();
1079        k.set_inputs(&[0]);
1080        let cw = CycleWires::new(&mut k);
1081        let wires: &dyn WireSource = &cw;
1082        assert_eq!(
1083            wires
1084                .get("target_index_table")
1085                .map(|v| v.as_str().to_string()),
1086            Some("system_views.sai_column_indexes".to_string()),
1087            "phase-binding LHS should resolve through CycleWires",
1088        );
1089        assert_eq!(
1090            wires.get("keyspace").map(|v| v.as_str().to_string()),
1091            Some("baselines".to_string()),
1092        );
1093    }
1094
1095    #[test]
1096    fn substitute_via_wires_resolves_bare_names() {
1097        let mut k = compile_polydat_interpreter(
1098            "input cycle: u64\n\
1099             keyspace := \"baselines\"\n\
1100             table := \"vec_label_00\"\n",
1101        )
1102        .unwrap();
1103        let cw = CycleWires::new(&mut k);
1104        let resolved =
1105            substitute_via_wires("SELECT * FROM {keyspace}.{table} WHERE x = 1", &cw).unwrap();
1106        assert_eq!(resolved, "SELECT * FROM baselines.vec_label_00 WHERE x = 1");
1107    }
1108
1109    #[test]
1110    fn substitute_via_wires_passes_through_literal_braces() {
1111        let mut k = compile_polydat_interpreter(
1112            "input cycle: u64\n\
1113             ks := \"baselines\"\n",
1114        )
1115        .unwrap();
1116        let cw = CycleWires::new(&mut k);
1117        // CQL map literal: brace bodies starting with quotes are
1118        // not bare identifiers, pass through verbatim.
1119        let resolved = substitute_via_wires(
1120            "CREATE KEYSPACE {ks} WITH replication = {'class': 'SimpleStrategy'}",
1121            &cw,
1122        )
1123        .unwrap();
1124        assert_eq!(
1125            resolved,
1126            "CREATE KEYSPACE baselines WITH replication = {'class': 'SimpleStrategy'}",
1127        );
1128    }
1129
1130    /// Binary-natural type guard. A wire holding `VecF32` (or any
1131    /// other type with no meaningful text-spliced form) must not be
1132    /// silently decimal-stringified into the field text — that's a
1133    /// workload-shape bug (the value belongs in a typed-binding
1134    /// path, not the text template). The substitution layer
1135    /// rejects with a clear diagnostic pointing at the wire and
1136    /// suggesting both fixes (pure-token form / bindvars split).
1137    ///
1138    /// Regression guard: dropping this check would silently burn
1139    /// per-element Grisu float formatting (≈55% of cycle CPU on
1140    /// the fknn_rampup_data shape) on every cycle.
1141    #[test]
1142    fn substitute_via_wires_rejects_vec_f32_in_text_template() {
1143        use polydat::ast::SliceArc;
1144        struct VecWire;
1145        impl WireSource for VecWire {
1146            fn get(&self, name: &str) -> Option<Value> {
1147                match name {
1148                    "id" => Some(Value::U64(7)),
1149                    "vec" => Some(Value::VecF32(SliceArc::from_vec(vec![0.1_f32, 0.2, 0.3]))),
1150                    _ => None,
1151                }
1152            }
1153            fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
1154                Box::new(["id", "vec"].iter().map(|s| s.to_string()))
1155            }
1156        }
1157        let err = substitute_via_wires("INSERT ... VALUES ('{id}', {vec})", &VecWire)
1158            .expect_err("VecF32 splice into text template must error");
1159        assert!(
1160            err.contains("vec"),
1161            "diagnostic should name the offending wire: {err}"
1162        );
1163        assert!(
1164            err.contains("vec_f32") || err.contains("VecF32"),
1165            "diagnostic should name the offending type: {err}"
1166        );
1167        assert!(
1168            err.contains("pure-token") || err.contains("typed"),
1169            "diagnostic should point at the fix: {err}"
1170        );
1171    }
1172
1173    /// The escape hatch: a field whose entire value is a pure
1174    /// token `{wire}` (no surrounding text) routes through case 2
1175    /// in `resolve_op_fields_via_wires` — typed Value preserved,
1176    /// no substitution. `substitute_via_wires` itself is only
1177    /// invoked on text-template fields, so the rejection above
1178    /// fires only when the binary-natural wire is genuinely being
1179    /// spliced into surrounding text. Pin that: a VecI32 wire
1180    /// triggers the same rejection (catches the broader contract,
1181    /// not a VecF32-only special case).
1182    #[test]
1183    fn substitute_via_wires_rejects_vec_i32_in_text_template() {
1184        use polydat::ast::SliceArc;
1185        struct VecI32Wire;
1186        impl WireSource for VecI32Wire {
1187            fn get(&self, name: &str) -> Option<Value> {
1188                if name == "vec" {
1189                    Some(Value::VecI32(SliceArc::from_vec(vec![1_i32, 2, 3])))
1190                } else {
1191                    None
1192                }
1193            }
1194            fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
1195                Box::new(std::iter::once("vec".to_string()))
1196            }
1197        }
1198        let err = substitute_via_wires("x = {vec}", &VecI32Wire).unwrap_err();
1199        assert!(
1200            err.contains("vec_i32") || err.contains("VecI32"),
1201            "VecI32 should also be rejected: {err}"
1202        );
1203    }
1204
1205    #[test]
1206    fn substitute_via_wires_errors_on_unresolved_name() {
1207        let mut k = compile_polydat_interpreter("input cycle: u64\nx := \"a\"\n").unwrap();
1208        let cw = CycleWires::new(&mut k);
1209        let err = substitute_via_wires("hi {nonexistent}", &cw).unwrap_err();
1210        assert!(
1211            err.contains("nonexistent"),
1212            "diagnostic should name the wire: {err}"
1213        );
1214        assert!(
1215            err.contains("unresolved"),
1216            "diagnostic should call out unresolved: {err}"
1217        );
1218    }
1219
1220    #[test]
1221    fn substitute_via_wires_errors_when_wire_resolves_to_none() {
1222        // SRD-74 Rule 3 strict render: a wire that EXISTS but
1223        // resolves to `Value::None` (e.g. a `const X := "{undef}"`
1224        // whose RHS interpolation propagated None per Rule 1, then
1225        // the conditional-shadow chain found no upstream binding
1226        // either) must error at substitution time — NOT silently
1227        // render as `""`. Empty string is a real value; absent is
1228        // not the same thing, and conflating them was the
1229        // wire-protocol corruption class this SRD closes.
1230        let mut k = compile_polydat_interpreter(
1231            "input cycle: u64\n\
1232             extern undef: str\n\
1233             const x := \"{undef}\"\n",
1234        )
1235        .unwrap();
1236        let cw = CycleWires::new(&mut k);
1237        let err = substitute_via_wires("source_model='{x}'", &cw).unwrap_err();
1238        assert!(
1239            err.contains("`{x}`"),
1240            "diagnostic should name the bind-point: {err}"
1241        );
1242        assert!(
1243            err.contains("Value::None") || err.contains("no value bound"),
1244            "diagnostic should explain the None resolution: {err}"
1245        );
1246    }
1247
1248    #[test]
1249    fn to_display_strict_returns_none_for_value_none() {
1250        // The strict primitive itself; render sites consume it.
1251        use polydat::ast::Value;
1252        assert_eq!(Value::None.to_display_strict(), None);
1253        assert_eq!(
1254            Value::Str("hello".into()).to_display_strict(),
1255            Some("hello".to_string())
1256        );
1257        assert_eq!(Value::U64(42).to_display_strict(), Some("42".to_string()));
1258    }
1259
1260    #[test]
1261    fn substitute_via_wires_resolves_inside_cql_options_map() {
1262        // Pin the failure shape that surfaced in
1263        // `full_cql_vector.yaml`: a CQL `WITH OPTIONS = {'k':
1264        // '{value}'}` map. The earlier substitution algorithm
1265        // truncated the body at the first `}` (the inner
1266        // placeholder's `}`), then treated the outer `{...}`
1267        // as one literal-content body — so inner `{value}`
1268        // placeholders inside the map were never resolved.
1269        // The fix mirrors `nmbrs_workload::bindpoints::extract_bind_points`:
1270        // when `{` is followed by `'` or `"`, treat it as a CQL
1271        // map opener (emit the brace, continue scanning).
1272        let mut k = compile_polydat_interpreter(
1273            "input cycle: u64\n\
1274             optimize_for := \"RECALL\"\n\
1275             similarity_function := \"EUCLIDEAN\"\n",
1276        )
1277        .unwrap();
1278        let cw = CycleWires::new(&mut k);
1279        let resolved = substitute_via_wires(
1280            "WITH OPTIONS = {'optimize_for': '{optimize_for}', 'similarity_function': '{similarity_function}'}",
1281            &cw,
1282        ).unwrap();
1283        assert_eq!(
1284            resolved,
1285            "WITH OPTIONS = {'optimize_for': 'RECALL', 'similarity_function': 'EUCLIDEAN'}",
1286            "nested `{{name}}` placeholders inside CQL map literals must resolve"
1287        );
1288    }
1289
1290    #[test]
1291    fn substitute_via_wires_errors_on_qualifier_prefix() {
1292        let mut k = compile_polydat_interpreter("input cycle: u64\nx := \"a\"\n").unwrap();
1293        let cw = CycleWires::new(&mut k);
1294        let err = substitute_via_wires("hi {bind:x}", &cw).unwrap_err();
1295        assert!(
1296            err.contains("bind:x"),
1297            "diagnostic should name the qualifier form: {err}"
1298        );
1299    }
1300
1301    #[test]
1302    fn substitute_via_wires_passes_through_inline_expr() {
1303        let mut k = compile_polydat_interpreter("input cycle: u64\nx := \"a\"\n").unwrap();
1304        let cw = CycleWires::new(&mut k);
1305        let resolved = substitute_via_wires("v = {{x + 1}}", &cw).unwrap();
1306        // `{{...}}` is reserved for the inline-expression desugar
1307        // surface (compiled into bindings before reaching cycle
1308        // time); cycle-time substitute_via_wires passes it
1309        // through unchanged.
1310        assert_eq!(resolved, "v = {{x + 1}}");
1311    }
1312
1313    #[test]
1314    fn cycle_wires_resolves_iter_var_through_subscope_chain() {
1315        // SRD-68 invariant from user: "the Polydat context visible after
1316        // initialization in each scope is designed to and required
1317        // to provide all of the values which should be visible
1318        // including those which are populated at logical closure
1319        // boundaries based on comprehensions."
1320        //
1321        // Concretely: a for_each scope kernel populates iter vars
1322        // on its INPUT slots (per `for_iteration`). The phase
1323        // scope kernel then inherits them via `build_subscope`.
1324        // The op-template canonical (built via `build_subscope`
1325        // again) MUST also carry the iter var values so cycle-time
1326        // `wires.get(iter_var_name)` answers correctly.
1327        //
1328        // This test mirrors that chain: parent kernel has
1329        // `optimize_for` as an extern input declaration with a
1330        // populated value; child kernel declares the same name;
1331        // verify the value propagates when the child is bound under
1332        // the parent, as every scope is, and is visible via
1333        // `CycleWires::get`.
1334        use polydat::ast::Value;
1335
1336        // Parent: declares `optimize_for` as extern + auto-passthrough
1337        // output via `final` — same pattern the phase synthesizer
1338        // uses for iter-var cascade.
1339        let mut parent = crate::scope_kernel::ScopeKernel::compile(
1340            "input cycle: u64\n\
1341             extern optimize_for: str\n",
1342        )
1343        .unwrap();
1344        // Populate the input slot the way the phase kernel does
1345        // after binding under the for_each bound_kernel.
1346        let opt_idx = parent
1347            .program()
1348            .find_input("optimize_for")
1349            .expect("optimize_for input slot");
1350        parent
1351            .set_input_at(opt_idx, Value::Str("RECALL".into()))
1352            .expect("write optimize_for");
1353
1354        // Child: program declares the same name as an extern.
1355        // Mimics the per-op canonical the dispenser owns.
1356        let child_scope = crate::scope_kernel::ScopeKernel::compile(
1357            "input cycle: u64\n\
1358             extern optimize_for: str\n",
1359        )
1360        .unwrap();
1361        let mut child = child_scope
1362            .bind_under(parent.kernel(), &[])
1363            .expect("the child binds under the parent");
1364
1365        let cw = CycleWires::new(&mut child);
1366        let wires: &dyn WireSource = &cw;
1367        // The architectural contract: child's CycleWires resolves
1368        // `optimize_for` through the inheritance chain. If this
1369        // assertion fails, the chain isn't propagating iter vars
1370        // and we need the gap fix at the Polydat Kernel layer.
1371        assert_eq!(
1372            wires.get("optimize_for").map(|v| v.as_str().to_string()),
1373            Some("RECALL".to_string()),
1374            "iter-var input populated on parent should propagate \
1375             through binding to child's WireSource",
1376        );
1377    }
1378
1379    #[test]
1380    fn extern_decl_only_produces_input_no_output() {
1381        // Diagnostic: an `extern <name>: <type>` declaration by
1382        // itself creates an INPUT but does NOT publish a matching
1383        // output. So `materialize_wiring_from_outer` (which walks outer's
1384        // outputs) wouldn't find this name and wouldn't propagate
1385        // it to descendants. The synthesis pipeline avoids this by
1386        // also calling `mark_inherited_outputs` on the kernel
1387        // post-build, but a plain `extern` line doesn't.
1388        //
1389        // Pinning this so the next person reading the source isn't
1390        // surprised — `cycle_wires_resolves_iter_var_through_subscope_chain`
1391        // passes only because the `str` extern's auto-passthrough
1392        // output (added by the compiler when the name appears in the
1393        // body) gives materialize_wiring_from_outer something to walk. With ONLY
1394        // an extern decl, there's no body reference, no auto-passthrough,
1395        // and the chain breaks.
1396        use polydat::dsl::compile::compile_polydat_interpreter;
1397        let k = compile_polydat_interpreter(
1398            "input cycle: u64\n\
1399             extern optimize_for: str\n",
1400        )
1401        .unwrap();
1402        let outputs: Vec<&str> = k.program().output_names().to_vec();
1403        // If this assertion fails (i.e. `optimize_for` IS in
1404        // outputs), then the chain test above was a no-op and we
1405        // need to revisit the architectural question.
1406        // Document whichever is true.
1407        eprintln!("DBG outputs from `extern optimize_for: str`: {outputs:?}");
1408    }
1409
1410    #[test]
1411    fn cycle_wires_advance_drives_per_row_pulls() {
1412        // SRD-68 batch contract: `advance(coord)` mutates the
1413        // underlying kernel's coord input so subsequent `get`
1414        // calls produce values for that coord. Verify by pulling
1415        // a coord-dependent output before and after advance.
1416        let mut k = compile_polydat_interpreter(
1417            "input cycle: u64\n\
1418             id := format_u64(cycle, 10)\n",
1419        )
1420        .unwrap();
1421        k.set_inputs(&[0]);
1422        let cw = CycleWires::new(&mut k);
1423        let wires: &dyn WireSource = &cw;
1424        // First read at cycle=0.
1425        assert_eq!(
1426            wires.get("id").map(|v| v.as_str().to_string()),
1427            Some("0".to_string())
1428        );
1429        // Advance and re-read.
1430        wires.advance(42);
1431        assert_eq!(
1432            wires.get("id").map(|v| v.as_str().to_string()),
1433            Some("42".to_string())
1434        );
1435        wires.advance(7);
1436        assert_eq!(
1437            wires.get("id").map(|v| v.as_str().to_string()),
1438            Some("7".to_string())
1439        );
1440    }
1441
1442    #[test]
1443    fn null_wires_advance_is_noop() {
1444        // Default `advance` impl on `NullWireSource` does nothing;
1445        // useful as a sanity check that advance on a non-batch-
1446        // capable wires doesn't panic.
1447        let wires: &dyn WireSource = &NULL_WIRES;
1448        wires.advance(0);
1449        wires.advance(123);
1450        assert!(wires.get("anything").is_none());
1451    }
1452
1453    #[test]
1454    fn cycle_wires_write_lands_on_input_slot_visible_to_get() {
1455        // SRD-66 capture flow: ResultDispenser writes a magic-extern
1456        // input (e.g. `count`), then a later wrapper or the eval
1457        // cone reads it. `wires.write` lands the value; `wires.get`
1458        // returns it on the next read.
1459        let mut k = compile_polydat_interpreter(
1460            "input cycle: u64\n\
1461             extern count: u64\n\
1462             extern body: json\n",
1463        )
1464        .unwrap();
1465        k.set_inputs(&[0]);
1466        let cw = CycleWires::new(&mut k);
1467        let wires: &dyn WireSource = &cw;
1468
1469        assert_eq!(wires.write("count", Value::U64(42)), WriteOutcome::Stored);
1470        assert_eq!(wires.get("count").map(|v| v.as_u64()), Some(42));
1471
1472        // Overwrite — the new value supersedes the old.
1473        assert_eq!(wires.write("count", Value::U64(7)), WriteOutcome::Stored);
1474        assert_eq!(wires.get("count").map(|v| v.as_u64()), Some(7));
1475    }
1476
1477    #[test]
1478    fn cycle_wires_write_returns_no_slot_for_unknown_name() {
1479        // The closure-binding economy's DCE signal: no slot, value
1480        // silently dropped. Caller is unaffected.
1481        let mut k = compile_polydat_interpreter("input cycle: u64\nx := 1\n").unwrap();
1482        let cw = CycleWires::new(&mut k);
1483        let wires: &dyn WireSource = &cw;
1484        assert_eq!(wires.write("nope", Value::U64(99)), WriteOutcome::NoSlot);
1485    }
1486
1487    #[test]
1488    fn cycle_wires_write_feeds_eval_cone_through_get() {
1489        // The full capture-then-pull flow: write a magic-extern
1490        // input, read an output that depends on it through the
1491        // eval cone. This is the metrics-wrapper-reading-row_count
1492        // scenario from the design memo.
1493        let mut k = compile_polydat_interpreter(
1494            "input cycle: u64\n\
1495             extern count: u64\n\
1496             row_count := count\n",
1497        )
1498        .unwrap();
1499        k.set_inputs(&[0]);
1500        let cw = CycleWires::new(&mut k);
1501        let wires: &dyn WireSource = &cw;
1502
1503        // Before the write, `count` is at its default and
1504        // `row_count` reflects that.
1505        assert_eq!(wires.write("count", Value::U64(123)), WriteOutcome::Stored);
1506        // The pull through `row_count` (an output) reads the
1507        // freshly-written `count` (an input).
1508        assert_eq!(wires.get("row_count").map(|v| v.as_u64()), Some(123));
1509    }
1510
1511    #[test]
1512    fn null_wires_write_returns_no_slot() {
1513        let wires: &dyn WireSource = &NULL_WIRES;
1514        assert_eq!(wires.write("anything", Value::U64(1)), WriteOutcome::NoSlot);
1515    }
1516
1517    #[test]
1518    fn resolve_op_fields_four_case_dispatch() {
1519        // Pin the four-case dispatch contract for op-field resolution.
1520        // See `resolve_op_fields_via_wires` doc for the cases.
1521        let mut k = compile_polydat_interpreter(
1522            "input cycle: u64\n\
1523             table := \"users\"\n\
1524             count := 42\n",
1525        )
1526        .unwrap();
1527        let cw = CycleWires::new(&mut k);
1528
1529        let fields: Vec<(String, serde_json::Value)> = vec![
1530            // Case 1: non-string JSON scalar — stringified.
1531            ("limit_num".into(), serde_json::json!(100)),
1532            // Case 2: pure-token — typed wire reference, count is U64(42).
1533            (
1534                "typed_ref".into(),
1535                serde_json::Value::String("{count}".into()),
1536            ),
1537            // Case 3: text template — wires.get(table).to_display_string()
1538            //          interpolated into the surrounding text.
1539            (
1540                "templated".into(),
1541                serde_json::Value::String("SELECT * FROM {table} WHERE x = 1".into()),
1542            ),
1543            // Case 4: bare-string literal — no placeholders, passes through.
1544            (
1545                "literal_stmt".into(),
1546                serde_json::Value::String("SELECT 1".into()),
1547            ),
1548        ];
1549
1550        let resolved = resolve_op_fields_via_wires(&fields, &cw).expect("four-case dispatch");
1551
1552        // Case 1: stringified — exact form is implementation-defined,
1553        // verify the value contains the digits.
1554        assert!(
1555            matches!(resolved.get_value("limit_num"),
1556            Some(polydat::ast::Value::Str(s)) if s.contains("100")),
1557            "case 1: got {:?}",
1558            resolved.get_value("limit_num")
1559        );
1560        // Case 2: typed U64.
1561        assert_eq!(
1562            resolved.get_value("typed_ref").map(|v| v.as_u64()),
1563            Some(42),
1564            "case 2: typed wire ref preserves U64"
1565        );
1566        // Case 3: interpolated string.
1567        assert_eq!(
1568            resolved.get_str("templated"),
1569            Some("SELECT * FROM users WHERE x = 1"),
1570            "case 3: text template"
1571        );
1572        // Case 4: literal pass-through.
1573        assert_eq!(
1574            resolved.get_str("literal_stmt"),
1575            Some("SELECT 1"),
1576            "case 4: bare string literal"
1577        );
1578    }
1579
1580    #[test]
1581    fn cycle_wires_caches_across_repeated_gets() {
1582        // Pull memoizes; a second get of the same name reads the
1583        // cached value off state, not re-runs the eval cone. We
1584        // can't directly observe memoization but we CAN observe
1585        // that two reads of the same cycle produce the same value
1586        // (hash is deterministic per coordinate, but the kernel's
1587        // dirty-tracking would require a state mutation to
1588        // re-fire — the property still holds).
1589        let mut k = compile_polydat_interpreter("input cycle: u64\nh := hash(cycle)\n").unwrap();
1590        k.set_inputs(&[42]);
1591        let cw = CycleWires::new(&mut k);
1592        let wires: &dyn WireSource = &cw;
1593        let v1 = wires.get("h").unwrap().as_u64();
1594        let v2 = wires.get("h").unwrap().as_u64();
1595        assert_eq!(v1, v2);
1596    }
1597}