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/// The text is divided by `nmbrs_workload::op_text::pieces`, and
575/// this is the reader that produces final text:
576/// - `\{` / `\}` — written as the brace alone.
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/// - a brace that opens a quoted map (`{'class': …}`, `{"a": 1}`)
584///   is literal, and a bind point inside the map is resolved.
585/// - a group whose body is not a name passes through unchanged. A
586///   workload cannot write one (the bind-point scanner refuses it at
587///   load); it reaches here only inside a value an earlier pass wrote
588///   into the text.
589///
590/// Returns `Err` with a descriptive message when a bare `{name}`
591/// reference doesn't resolve through `wires` — SRD-68 invariant
592/// I-1 forbids silent fallback. Callers (typically the cycle
593/// dispatch error path) surface this as a phase-stopping
594/// diagnostic.
595pub fn substitute_via_wires(template: &str, wires: &dyn WireSource) -> Result<String, String> {
596    use nmbrs_workload::op_text::Piece;
597
598    let mut out = String::with_capacity(template.len());
599    for piece in nmbrs_workload::op_text::pieces(template) {
600        let (raw, body) = match piece {
601            Piece::Text(text) => {
602                out.push_str(text);
603                continue;
604            }
605            Piece::Brace(brace) => {
606                out.push(brace);
607                continue;
608            }
609            Piece::Inline { raw, .. } => {
610                out.push_str(raw);
611                continue;
612            }
613            Piece::Group { raw, body } => (raw, body),
614        };
615        // Qualifier-prefixed form (`{bind:name}`, `{capture:name}`,
616        // `{input:name}`) — SRD-68 Push 5 contract is bare names
617        // only at cycle time.
618        if body.contains(':') {
619            return Err(format!(
620                "qualifier-prefixed bind point `{{{body}}}` is not supported \
621                 at cycle time; only bare `{{name}}` references are answered \
622                 by the dispenser's WireSource"
623            ));
624        }
625        // Bare identifiers resolve as-is. Dotted identifiers
626        // (`q.cursor.idx`) follow the field-access wire
627        // convention and resolve through their flattened
628        // spelling (`q__cursor__idx`) — same rule the DSL
629        // compiler and kernel lookup apply.
630        let wire_name: std::borrow::Cow<'_, str> = if is_bare_ident(body) {
631            std::borrow::Cow::Borrowed(body)
632        } else if is_dotted_ident(body) {
633            std::borrow::Cow::Owned(body.replace('.', "__"))
634        } else {
635            out.push_str(raw);
636            continue;
637        };
638        let body = wire_name.as_ref();
639        // Bare identifier — wires.get resolves or errors.
640        //
641        // SRD-74 Rule 3 (strict render): `Value::None` reaching the
642        // wire-protocol substitution surface is an error, NOT a
643        // silent empty string. The display-strict primitive returns
644        // `None` for `Value::None` so we can surface a clear
645        // diagnostic. The catch-all `to_display_string` legacy
646        // (which maps None to "") stays in place for log /
647        // diagnostic contexts where empty is acceptable; render
648        // sites use the strict form.
649        match wires.get(body) {
650            Some(v) => {
651                // Binary-natural type guard. A wire holding VecF32 /
652                // VecI32 / Handle / Bytes has no meaningful
653                // text-spliced form for a wire-protocol field —
654                // decimal-stringifying a 128-element f32 vector to
655                // embed in a CQL INSERT is always the wrong path
656                // (it forces format-then-reparse on every cycle and
657                // bypasses the adapter's typed-binding API). Detect
658                // here so the cost — and the design violation — are
659                // surfaced as a clear error instead of silently
660                // burned on every cycle.
661                //
662                // The escape hatch for typed values that genuinely
663                // belong in a field is the "pure-token" form (case 2
664                // in `resolve_op_fields_via_wires`): the entire
665                // field value is exactly `{wire_name}` with no
666                // surrounding text, and the typed `Value` is handed
667                // to the adapter intact.
668                if is_binary_natural(v.port_type()) {
669                    return Err(format!(
670                        "wire `{body}` holds {} which has no text-spliced \
671                         representation suitable for a wire-protocol field. \
672                         Either use the pure-token form (the entire field \
673                         value is exactly `{{{body}}}` with no surrounding \
674                         text) so the adapter binds the typed value via \
675                         its parameter API, or split the field so the \
676                         wire is bound as a typed parameter alongside a \
677                         text template containing placeholders (e.g. CQL \
678                         `?`).",
679                        v.port_type()
680                    ));
681                }
682                match v.to_display_strict() {
683                    Some(s) => out.push_str(&s),
684                    None => {
685                        return Err(format!(
686                            "unresolved bind point `{{{body}}}`: wire \
687                             `{body}` resolved to `Value::None` (no value \
688                             bound in the dispenser's Polydat context chain). \
689                             Set a workload-param default for `{body}`, \
690                             bind it via `bindings:` / `set:`, or mark \
691                             the bind-point as optional once SRD-74 \
692                             Rule 2 syntax lands."
693                        ));
694                    }
695                }
696            }
697            None => {
698                return Err(format!(
699                    "unresolved bind point `{{{body}}}`: no wire named \
700                     `{body}` in the dispenser's Polydat context"
701                ));
702            }
703        }
704    }
705    Ok(out)
706}
707
708/// Resolve a list of op-template field entries through the generic
709/// wires API. Each entry is `(field_name, json_value_from_template)`;
710/// the helper returns name+value pairs an adapter can hand to its
711/// renderer, with no synthesis-layer involvement.
712///
713/// The four-case rule, in order of dispatch:
714///
715/// 1. **Non-string YAML scalar / list / object**: passes through as
716///    `Value::Str(json.to_string())`. Adapters that need richer
717///    typing for a JSON-shaped field can downcast through
718///    `ResolvedFields` and parse, but the default projection keeps
719///    the legacy "everything renders to a string" contract.
720///
721/// 2. **Pure-token typed-reference**: the entire string (trimmed)
722///    is exactly `{name}` where `name` is a bare identifier. The
723///    field's value becomes `wires.get(name).clone()` — typed
724///    `Value` preserved. Used by CQL prepared-param bindings,
725///    vector args, and anywhere an adapter needs the native typed
726///    value rather than its display string. An unresolved name
727///    here is a hard error (no silent fallback).
728///
729/// 3. **Text template with placeholders**: any string containing
730///    `{name}` placeholders embedded in surrounding text, or
731///    `{{ expr }}` inline-GK escapes. Renders through
732///    `substitute_via_wires` to produce a `Value::Str` with each
733///    placeholder replaced by its wire's display-string form.
734///    Inline-expression `{{ … }}` placeholders are evaluated then
735///    stringified.
736///
737/// 4. **Bare-string literal**: a string with no `{…}` markers
738///    passes through unchanged as `Value::Str(s.clone())`. This is
739///    the most common case for SQL stmts, URIs, and headers.
740///
741/// **Why not "bare-name as wire reference"?** A workload author
742/// writing `stmt: "SELECT * FROM users"` doesn't expect `users` to
743/// resolve as a Polydat wire. The pure-token form (case 2) is the
744/// explicit opt-in for typed references; bare strings stay
745/// literal. Per-adapter typed-field metadata (a future enhancement)
746/// would let specific fields opt into bare-name-as-reference; the
747/// current contract doesn't require it.
748///
749/// Returns the SRD-68 standard error message on the first
750/// unresolved bind point (single resolution surface, no fallback).
751pub fn resolve_op_fields_via_wires(
752    op_fields: &[(String, serde_json::Value)],
753    wires: &dyn WireSource,
754) -> Result<crate::adapter::ResolvedFields, String> {
755    use polydat::ast::Value;
756    let mut names = Vec::with_capacity(op_fields.len());
757    let mut values = Vec::with_capacity(op_fields.len());
758    for (key, json_value) in op_fields {
759        names.push(key.clone());
760        let serde_json::Value::String(s) = json_value else {
761            values.push(Value::Str(json_value.to_string().into()));
762            continue;
763        };
764        let trimmed = s.trim();
765        let pure_token = trimmed.starts_with('{')
766            && trimmed.ends_with('}')
767            && !trimmed.starts_with("{{")
768            && trimmed.len() >= 2
769            && trimmed[1..trimmed.len() - 1]
770                .chars()
771                .all(|c| c != '{' && c != '}');
772        if pure_token {
773            let body = trimmed[1..trimmed.len() - 1].trim();
774            let bare = match body.split_once(':') {
775                Some((_, n)) => n,
776                None => body,
777            };
778            if is_bare_ident(bare) {
779                match wires.get(bare) {
780                    Some(v) => {
781                        values.push(v);
782                        continue;
783                    }
784                    None => {
785                        return Err(format!(
786                            "unresolved bind point `{{{bare}}}` in field '{key}': \
787                             no wire named `{bare}` in the dispenser's Polydat context"
788                        ));
789                    }
790                }
791            }
792        }
793        let rendered = substitute_via_wires(s, wires).map_err(|e| format!("field '{key}': {e}"))?;
794        values.push(Value::Str(rendered.into()));
795    }
796    Ok(crate::adapter::ResolvedFields::new(names, values))
797}
798
799/// Wire types that have no meaningful text-spliced representation
800/// in a wire-protocol field. Embedding `{wire}` for one of these
801/// inside a larger string template (CQL prepared text, HTTP body,
802/// etc.) is always a workload-shape bug: the typed value should
803/// flow through the adapter's typed-binding API, not be
804/// decimal-stringified into the SQL/JSON/body text and reparsed
805/// downstream.
806///
807/// Used by [`substitute_via_wires`] to refuse the splice and by
808/// the future op-template construction-time guard (init-time
809/// shape check) to reject equivalent misuse before any cycle runs.
810fn is_binary_natural(t: PortType) -> bool {
811    matches!(
812        t,
813        PortType::VecF32
814            | PortType::VecI32
815            | PortType::VecF64
816            | PortType::VecI64
817            | PortType::VecF16
818            | PortType::VecI16
819            | PortType::Handle
820            | PortType::Bytes
821            | PortType::Forms
822            | PortType::Fragment
823            | PortType::AdmittedRows
824    )
825}
826
827/// Same identifier discipline as the core `resolve_placeholders_in_string`
828/// validator in `crate::scope`: ASCII-alpha-or-underscore start,
829/// remainder ASCII-alphanumeric-or-underscore. Anything else is
830/// not a bare identifier and passes through.
831fn is_bare_ident(s: &str) -> bool {
832    let mut chars = s.chars();
833    match chars.next() {
834        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
835        _ => return false,
836    }
837    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
838}
839
840/// A dotted identifier chain (`q.cursor.idx`): two or more
841/// bare-identifier segments joined by single dots. These follow
842/// the field-access wire convention and resolve through the
843/// `__`-flattened spelling.
844fn is_dotted_ident(s: &str) -> bool {
845    let segments: Vec<&str> = s.split('.').collect();
846    segments.len() >= 2 && segments.iter().all(|seg| is_bare_ident(seg))
847}
848
849#[cfg(test)]
850mod tests {
851    use super::*;
852    use polydat::dsl::compile::compile_polydat_interpreter;
853
854    #[test]
855    fn scope_kernel_get_resolves_inputs_and_constants() {
856        // `lookup` (and therefore Push 1's WireSource) covers
857        // input slots and scope-init constants — the names available
858        // without a memoizing pull. `folded := 42` lands as a
859        // compile-folded constant; `cycle` is a coordinate input.
860        let mut k = crate::scope_kernel::ScopeKernel::compile(
861            "input cycle: u64\n\
862             folded := 42\n",
863        )
864        .unwrap();
865        k.set_inputs(&[7]);
866        let wires: &dyn WireSource = &k;
867        assert_eq!(wires.get("folded").map(|v| v.as_u64()), Some(42));
868        assert_eq!(wires.get("cycle").map(|v| v.as_u64()), Some(7));
869    }
870
871    #[test]
872    fn scope_kernel_get_returns_none_for_pull_only_outputs_in_push_1() {
873        // Push 1 baseline: outputs that require a memoizing
874        // `pull(&mut state, …)` evaluation are NOT served by the
875        // `&ScopeKernel` impl. Push 2 introduces the kernel-owning
876        // wires impl that can pull outputs. This test pins the
877        // current contract so the Push 2 change is visible as a
878        // diff.
879        let mut k = crate::scope_kernel::ScopeKernel::compile(
880            "input cycle: u64\n\
881             cyc_dep := hash(cycle)\n",
882        )
883        .unwrap();
884        k.set_inputs(&[7]);
885        let wires: &dyn WireSource = &k;
886        assert!(wires.get("cyc_dep").is_none());
887    }
888
889    #[test]
890    fn scope_kernel_get_returns_none_for_unknown_name() {
891        let k = crate::scope_kernel::ScopeKernel::compile("input cycle: u64\nx := 1\n").unwrap();
892        let wires: &dyn WireSource = &k;
893        assert!(wires.get("not_a_real_name").is_none());
894    }
895
896    #[test]
897    fn scope_kernel_names_lists_declared_outputs_and_inputs() {
898        let k =
899            crate::scope_kernel::ScopeKernel::compile("input cycle: u64\nfolded := 42\n").unwrap();
900        let wires: &dyn WireSource = &k;
901        let names: Vec<String> = wires.names().collect();
902        assert!(
903            names.iter().any(|n| n == "folded"),
904            "folded should appear: {names:?}"
905        );
906        assert!(
907            names.iter().any(|n| n == "cycle"),
908            "cycle should appear: {names:?}"
909        );
910    }
911
912    #[test]
913    fn null_wires_returns_none_and_empty() {
914        let wires: &dyn WireSource = &NULL_WIRES;
915        assert!(wires.get("anything").is_none());
916        assert_eq!(wires.names().count(), 0);
917    }
918
919    #[test]
920    fn cycle_wires_pulls_outputs() {
921        // CycleWires (Push 4) covers the memoizing-pull path that
922        // the bare `&ScopeKernel` impl can't reach. `cyc_dep` is a
923        // computed output — pulling it requires `&mut state` to
924        // fire the eval cone and cache the result.
925        let mut k = crate::scope_kernel::ScopeKernel::compile(
926            "input cycle: u64\n\
927             folded := 42\n\
928             cyc_dep := hash(cycle)\n",
929        )
930        .unwrap();
931        k.set_inputs(&[7]);
932        let cw = CycleWires::new(&mut k);
933        let wires: &dyn WireSource = &cw;
934        // Output pull works through CycleWires.
935        let v = wires.get("cyc_dep").expect("cyc_dep should resolve");
936        assert!(v.as_u64() != 0, "hash result should be non-zero");
937        // Folded constant still resolves.
938        assert_eq!(wires.get("folded").map(|v| v.as_u64()), Some(42));
939        // Coordinate input still resolves.
940        assert_eq!(wires.get("cycle").map(|v| v.as_u64()), Some(7));
941    }
942
943    /// SRD-93-era fold totality: `reset` restores a wire to its
944    /// DECLARED initial value — the author's identity element — so an
945    /// empty min/max fold never parks `Value::None` on a typed slot
946    /// and never leaves a stale prior reading.
947    #[test]
948    fn cycle_wires_reset_restores_declared_default() {
949        let mut k = compile_polydat_interpreter(
950            "input cycle: u64\nextern pressure: u64 = 7\nx := pressure + 1\n",
951        )
952        .unwrap();
953        let cw = CycleWires::new(&mut k);
954        let wires: &dyn WireSource = &cw;
955
956        assert_eq!(
957            wires.write("pressure", Value::U64(42)),
958            WriteOutcome::Stored
959        );
960        assert_eq!(wires.get("pressure").map(|v| v.as_u64()), Some(42));
961
962        assert_eq!(
963            wires.reset("pressure"),
964            WriteOutcome::Stored,
965            "reset writes the declared default through the typed boundary"
966        );
967        assert_eq!(
968            wires.get("pressure").map(|v| v.as_u64()),
969            Some(7),
970            "the wire returns to its declared initial value, not to None/0"
971        );
972
973        assert_eq!(wires.reset("nonesuch"), WriteOutcome::NoSlot);
974    }
975
976    #[test]
977    fn cycle_wires_returns_none_for_unknown_name() {
978        let mut k = compile_polydat_interpreter("input cycle: u64\nx := 1\n").unwrap();
979        let cw = CycleWires::new(&mut k);
980        let wires: &dyn WireSource = &cw;
981        assert!(wires.get("not_a_real_name").is_none());
982    }
983
984    #[test]
985    fn cycle_wires_resolves_phase_binding_lhs_names() {
986        // SRD-68 Push 4b sanity check: a workload's phase
987        // binding (e.g. `target_index_table := pick(...)`) becomes
988        // an output on the per-op canonical kernel after
989        // `OpBuilder::canonical_kernel_for_op`. Per-fiber
990        // instances built from it via `build_subscope` carry that
991        // output. Wrapping such a per-fiber kernel in `CycleWires`
992        // and calling `wires.get(phase_binding_name)` returns the
993        // computed value — no text substitution required at
994        // adapter cycle time.
995        //
996        // This unit test simulates the shape directly via
997        // `compile_polydat_interpreter` rather than spinning up the full activity
998        // pipeline; it pins the contract that `wires.get` answers
999        // for any name the program declares as an output.
1000        let mut k = compile_polydat_interpreter(
1001            "input cycle: u64\n\
1002             keyspace := \"baselines\"\n\
1003             table := \"vec_label_00\"\n\
1004             # `pick`-equivalent with constant booleans for testability:\n\
1005             # take the first value when its selector is true.\n\
1006             target_index_table := \"system_views.sai_column_indexes\"\n",
1007        )
1008        .unwrap();
1009        k.set_inputs(&[0]);
1010        let cw = CycleWires::new(&mut k);
1011        let wires: &dyn WireSource = &cw;
1012        assert_eq!(
1013            wires
1014                .get("target_index_table")
1015                .map(|v| v.as_str().to_string()),
1016            Some("system_views.sai_column_indexes".to_string()),
1017            "phase-binding LHS should resolve through CycleWires",
1018        );
1019        assert_eq!(
1020            wires.get("keyspace").map(|v| v.as_str().to_string()),
1021            Some("baselines".to_string()),
1022        );
1023    }
1024
1025    #[test]
1026    fn substitute_via_wires_resolves_bare_names() {
1027        let mut k = compile_polydat_interpreter(
1028            "input cycle: u64\n\
1029             keyspace := \"baselines\"\n\
1030             table := \"vec_label_00\"\n",
1031        )
1032        .unwrap();
1033        let cw = CycleWires::new(&mut k);
1034        let resolved =
1035            substitute_via_wires("SELECT * FROM {keyspace}.{table} WHERE x = 1", &cw).unwrap();
1036        assert_eq!(resolved, "SELECT * FROM baselines.vec_label_00 WHERE x = 1");
1037    }
1038
1039    #[test]
1040    fn substitute_via_wires_passes_through_literal_braces() {
1041        let mut k = compile_polydat_interpreter(
1042            "input cycle: u64\n\
1043             ks := \"baselines\"\n",
1044        )
1045        .unwrap();
1046        let cw = CycleWires::new(&mut k);
1047        // CQL map literal: brace bodies starting with quotes are
1048        // not bare identifiers, pass through verbatim.
1049        let resolved = substitute_via_wires(
1050            "CREATE KEYSPACE {ks} WITH replication = {'class': 'SimpleStrategy'}",
1051            &cw,
1052        )
1053        .unwrap();
1054        assert_eq!(
1055            resolved,
1056            "CREATE KEYSPACE baselines WITH replication = {'class': 'SimpleStrategy'}",
1057        );
1058    }
1059
1060    /// Binary-natural type guard. A wire holding `VecF32` (or any
1061    /// other type with no meaningful text-spliced form) must not be
1062    /// silently decimal-stringified into the field text — that's a
1063    /// workload-shape bug (the value belongs in a typed-binding
1064    /// path, not the text template). The substitution layer
1065    /// rejects with a clear diagnostic pointing at the wire and
1066    /// suggesting both fixes (pure-token form / bindvars split).
1067    ///
1068    /// Regression guard: dropping this check would silently burn
1069    /// per-element Grisu float formatting (≈55% of cycle CPU on
1070    /// the fknn_rampup_data shape) on every cycle.
1071    #[test]
1072    fn substitute_via_wires_rejects_vec_f32_in_text_template() {
1073        use polydat::ast::SliceArc;
1074        struct VecWire;
1075        impl WireSource for VecWire {
1076            fn get(&self, name: &str) -> Option<Value> {
1077                match name {
1078                    "id" => Some(Value::U64(7)),
1079                    "vec" => Some(Value::VecF32(SliceArc::from_vec(vec![0.1_f32, 0.2, 0.3]))),
1080                    _ => None,
1081                }
1082            }
1083            fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
1084                Box::new(["id", "vec"].iter().map(|s| s.to_string()))
1085            }
1086        }
1087        let err = substitute_via_wires("INSERT ... VALUES ('{id}', {vec})", &VecWire)
1088            .expect_err("VecF32 splice into text template must error");
1089        assert!(
1090            err.contains("vec"),
1091            "diagnostic should name the offending wire: {err}"
1092        );
1093        assert!(
1094            err.contains("vec_f32") || err.contains("VecF32"),
1095            "diagnostic should name the offending type: {err}"
1096        );
1097        assert!(
1098            err.contains("pure-token") || err.contains("typed"),
1099            "diagnostic should point at the fix: {err}"
1100        );
1101    }
1102
1103    /// The escape hatch: a field whose entire value is a pure
1104    /// token `{wire}` (no surrounding text) routes through case 2
1105    /// in `resolve_op_fields_via_wires` — typed Value preserved,
1106    /// no substitution. `substitute_via_wires` itself is only
1107    /// invoked on text-template fields, so the rejection above
1108    /// fires only when the binary-natural wire is genuinely being
1109    /// spliced into surrounding text. Pin that: a VecI32 wire
1110    /// triggers the same rejection (catches the broader contract,
1111    /// not a VecF32-only special case).
1112    #[test]
1113    fn substitute_via_wires_rejects_vec_i32_in_text_template() {
1114        use polydat::ast::SliceArc;
1115        struct VecI32Wire;
1116        impl WireSource for VecI32Wire {
1117            fn get(&self, name: &str) -> Option<Value> {
1118                if name == "vec" {
1119                    Some(Value::VecI32(SliceArc::from_vec(vec![1_i32, 2, 3])))
1120                } else {
1121                    None
1122                }
1123            }
1124            fn names(&self) -> Box<dyn Iterator<Item = String> + '_> {
1125                Box::new(std::iter::once("vec".to_string()))
1126            }
1127        }
1128        let err = substitute_via_wires("x = {vec}", &VecI32Wire).unwrap_err();
1129        assert!(
1130            err.contains("vec_i32") || err.contains("VecI32"),
1131            "VecI32 should also be rejected: {err}"
1132        );
1133    }
1134
1135    #[test]
1136    fn substitute_via_wires_errors_on_unresolved_name() {
1137        let mut k = compile_polydat_interpreter("input cycle: u64\nx := \"a\"\n").unwrap();
1138        let cw = CycleWires::new(&mut k);
1139        let err = substitute_via_wires("hi {nonexistent}", &cw).unwrap_err();
1140        assert!(
1141            err.contains("nonexistent"),
1142            "diagnostic should name the wire: {err}"
1143        );
1144        assert!(
1145            err.contains("unresolved"),
1146            "diagnostic should call out unresolved: {err}"
1147        );
1148    }
1149
1150    #[test]
1151    fn substitute_via_wires_errors_when_wire_resolves_to_none() {
1152        // SRD-74 Rule 3 strict render: a wire that EXISTS but
1153        // resolves to `Value::None` (e.g. a `const X := "{undef}"`
1154        // whose RHS interpolation propagated None per Rule 1, then
1155        // the conditional-shadow chain found no upstream binding
1156        // either) must error at substitution time — NOT silently
1157        // render as `""`. Empty string is a real value; absent is
1158        // not the same thing, and conflating them was the
1159        // wire-protocol corruption class this SRD closes.
1160        let mut k = compile_polydat_interpreter(
1161            "input cycle: u64\n\
1162             extern undef: str\n\
1163             const x := \"{undef}\"\n",
1164        )
1165        .unwrap();
1166        let cw = CycleWires::new(&mut k);
1167        let err = substitute_via_wires("source_model='{x}'", &cw).unwrap_err();
1168        assert!(
1169            err.contains("`{x}`"),
1170            "diagnostic should name the bind-point: {err}"
1171        );
1172        assert!(
1173            err.contains("Value::None") || err.contains("no value bound"),
1174            "diagnostic should explain the None resolution: {err}"
1175        );
1176    }
1177
1178    #[test]
1179    fn to_display_strict_returns_none_for_value_none() {
1180        // The strict primitive itself; render sites consume it.
1181        use polydat::ast::Value;
1182        assert_eq!(Value::None.to_display_strict(), None);
1183        assert_eq!(
1184            Value::Str("hello".into()).to_display_strict(),
1185            Some("hello".to_string())
1186        );
1187        assert_eq!(Value::U64(42).to_display_strict(), Some("42".to_string()));
1188    }
1189
1190    #[test]
1191    fn substitute_via_wires_resolves_inside_cql_options_map() {
1192        // Pin the failure shape that surfaced in
1193        // `full_cql_vector.yaml`: a CQL `WITH OPTIONS = {'k':
1194        // '{value}'}` map. The earlier substitution algorithm
1195        // truncated the body at the first `}` (the inner
1196        // placeholder's `}`), then treated the outer `{...}`
1197        // as one literal-content body — so inner `{value}`
1198        // placeholders inside the map were never resolved.
1199        // The fix mirrors `nmbrs_workload::bindpoints::extract_bind_points`:
1200        // when `{` is followed by `'` or `"`, treat it as a CQL
1201        // map opener (emit the brace, continue scanning).
1202        let mut k = compile_polydat_interpreter(
1203            "input cycle: u64\n\
1204             optimize_for := \"RECALL\"\n\
1205             similarity_function := \"EUCLIDEAN\"\n",
1206        )
1207        .unwrap();
1208        let cw = CycleWires::new(&mut k);
1209        let resolved = substitute_via_wires(
1210            "WITH OPTIONS = {'optimize_for': '{optimize_for}', 'similarity_function': '{similarity_function}'}",
1211            &cw,
1212        ).unwrap();
1213        assert_eq!(
1214            resolved,
1215            "WITH OPTIONS = {'optimize_for': 'RECALL', 'similarity_function': 'EUCLIDEAN'}",
1216            "nested `{{name}}` placeholders inside CQL map literals must resolve"
1217        );
1218    }
1219
1220    #[test]
1221    fn substitute_via_wires_errors_on_qualifier_prefix() {
1222        let mut k = compile_polydat_interpreter("input cycle: u64\nx := \"a\"\n").unwrap();
1223        let cw = CycleWires::new(&mut k);
1224        let err = substitute_via_wires("hi {bind:x}", &cw).unwrap_err();
1225        assert!(
1226            err.contains("bind:x"),
1227            "diagnostic should name the qualifier form: {err}"
1228        );
1229    }
1230
1231    #[test]
1232    fn substitute_via_wires_passes_through_inline_expr() {
1233        let mut k = compile_polydat_interpreter("input cycle: u64\nx := \"a\"\n").unwrap();
1234        let cw = CycleWires::new(&mut k);
1235        let resolved = substitute_via_wires("v = {{x + 1}}", &cw).unwrap();
1236        // `{{...}}` is reserved for the inline-expression desugar
1237        // surface (compiled into bindings before reaching cycle
1238        // time); cycle-time substitute_via_wires passes it
1239        // through unchanged.
1240        assert_eq!(resolved, "v = {{x + 1}}");
1241    }
1242
1243    #[test]
1244    fn cycle_wires_resolves_iter_var_through_subscope_chain() {
1245        // SRD-68 invariant from user: "the Polydat context visible after
1246        // initialization in each scope is designed to and required
1247        // to provide all of the values which should be visible
1248        // including those which are populated at logical closure
1249        // boundaries based on comprehensions."
1250        //
1251        // Concretely: a for_each scope kernel populates iter vars
1252        // on its INPUT slots (per `for_iteration`). The phase
1253        // scope kernel then inherits them via `build_subscope`.
1254        // The op-template canonical (built via `build_subscope`
1255        // again) MUST also carry the iter var values so cycle-time
1256        // `wires.get(iter_var_name)` answers correctly.
1257        //
1258        // This test mirrors that chain: parent kernel has
1259        // `optimize_for` as an extern input declaration with a
1260        // populated value; child kernel declares the same name;
1261        // verify the value propagates when the child is bound under
1262        // the parent, as every scope is, and is visible via
1263        // `CycleWires::get`.
1264        use polydat::ast::Value;
1265
1266        // Parent: declares `optimize_for` as extern + auto-passthrough
1267        // output via `final` — same pattern the phase synthesizer
1268        // uses for iter-var cascade.
1269        let mut parent = crate::scope_kernel::ScopeKernel::compile(
1270            "input cycle: u64\n\
1271             extern optimize_for: str\n",
1272        )
1273        .unwrap();
1274        // Populate the input slot the way the phase kernel does
1275        // after binding under the for_each bound_kernel.
1276        let opt_idx = parent
1277            .program()
1278            .find_input("optimize_for")
1279            .expect("optimize_for input slot");
1280        parent
1281            .set_input_at(opt_idx, Value::Str("RECALL".into()))
1282            .expect("write optimize_for");
1283
1284        // Child: program declares the same name as an extern.
1285        // Mimics the per-op canonical the dispenser owns.
1286        let child_scope = crate::scope_kernel::ScopeKernel::compile(
1287            "input cycle: u64\n\
1288             extern optimize_for: str\n",
1289        )
1290        .unwrap();
1291        let mut child = child_scope
1292            .bind_under(parent.kernel(), &[])
1293            .expect("the child binds under the parent");
1294
1295        let cw = CycleWires::new(&mut child);
1296        let wires: &dyn WireSource = &cw;
1297        // The architectural contract: child's CycleWires resolves
1298        // `optimize_for` through the inheritance chain. If this
1299        // assertion fails, the chain isn't propagating iter vars
1300        // and we need the gap fix at the Polydat Kernel layer.
1301        assert_eq!(
1302            wires.get("optimize_for").map(|v| v.as_str().to_string()),
1303            Some("RECALL".to_string()),
1304            "iter-var input populated on parent should propagate \
1305             through binding to child's WireSource",
1306        );
1307    }
1308
1309    #[test]
1310    fn extern_decl_only_produces_input_no_output() {
1311        // Diagnostic: an `extern <name>: <type>` declaration by
1312        // itself creates an INPUT but does NOT publish a matching
1313        // output. So `materialize_wiring_from_outer` (which walks outer's
1314        // outputs) wouldn't find this name and wouldn't propagate
1315        // it to descendants. The synthesis pipeline avoids this by
1316        // also calling `mark_inherited_outputs` on the kernel
1317        // post-build, but a plain `extern` line doesn't.
1318        //
1319        // Pinning this so the next person reading the source isn't
1320        // surprised — `cycle_wires_resolves_iter_var_through_subscope_chain`
1321        // passes only because the `str` extern's auto-passthrough
1322        // output (added by the compiler when the name appears in the
1323        // body) gives materialize_wiring_from_outer something to walk. With ONLY
1324        // an extern decl, there's no body reference, no auto-passthrough,
1325        // and the chain breaks.
1326        use polydat::dsl::compile::compile_polydat_interpreter;
1327        let k = compile_polydat_interpreter(
1328            "input cycle: u64\n\
1329             extern optimize_for: str\n",
1330        )
1331        .unwrap();
1332        let outputs: Vec<&str> = k.program().output_names().to_vec();
1333        // If this assertion fails (i.e. `optimize_for` IS in
1334        // outputs), then the chain test above was a no-op and we
1335        // need to revisit the architectural question.
1336        // Document whichever is true.
1337        eprintln!("DBG outputs from `extern optimize_for: str`: {outputs:?}");
1338    }
1339
1340    #[test]
1341    fn cycle_wires_advance_drives_per_row_pulls() {
1342        // SRD-68 batch contract: `advance(coord)` mutates the
1343        // underlying kernel's coord input so subsequent `get`
1344        // calls produce values for that coord. Verify by pulling
1345        // a coord-dependent output before and after advance.
1346        let mut k = compile_polydat_interpreter(
1347            "input cycle: u64\n\
1348             id := format_u64(cycle, 10)\n",
1349        )
1350        .unwrap();
1351        k.set_inputs(&[0]);
1352        let cw = CycleWires::new(&mut k);
1353        let wires: &dyn WireSource = &cw;
1354        // First read at cycle=0.
1355        assert_eq!(
1356            wires.get("id").map(|v| v.as_str().to_string()),
1357            Some("0".to_string())
1358        );
1359        // Advance and re-read.
1360        wires.advance(42);
1361        assert_eq!(
1362            wires.get("id").map(|v| v.as_str().to_string()),
1363            Some("42".to_string())
1364        );
1365        wires.advance(7);
1366        assert_eq!(
1367            wires.get("id").map(|v| v.as_str().to_string()),
1368            Some("7".to_string())
1369        );
1370    }
1371
1372    #[test]
1373    fn null_wires_advance_is_noop() {
1374        // Default `advance` impl on `NullWireSource` does nothing;
1375        // useful as a sanity check that advance on a non-batch-
1376        // capable wires doesn't panic.
1377        let wires: &dyn WireSource = &NULL_WIRES;
1378        wires.advance(0);
1379        wires.advance(123);
1380        assert!(wires.get("anything").is_none());
1381    }
1382
1383    #[test]
1384    fn cycle_wires_write_lands_on_input_slot_visible_to_get() {
1385        // SRD-66 capture flow: ResultDispenser writes a magic-extern
1386        // input (e.g. `count`), then a later wrapper or the eval
1387        // cone reads it. `wires.write` lands the value; `wires.get`
1388        // returns it on the next read.
1389        let mut k = compile_polydat_interpreter(
1390            "input cycle: u64\n\
1391             extern count: u64\n\
1392             extern body: json\n",
1393        )
1394        .unwrap();
1395        k.set_inputs(&[0]);
1396        let cw = CycleWires::new(&mut k);
1397        let wires: &dyn WireSource = &cw;
1398
1399        assert_eq!(wires.write("count", Value::U64(42)), WriteOutcome::Stored);
1400        assert_eq!(wires.get("count").map(|v| v.as_u64()), Some(42));
1401
1402        // Overwrite — the new value supersedes the old.
1403        assert_eq!(wires.write("count", Value::U64(7)), WriteOutcome::Stored);
1404        assert_eq!(wires.get("count").map(|v| v.as_u64()), Some(7));
1405    }
1406
1407    #[test]
1408    fn cycle_wires_write_returns_no_slot_for_unknown_name() {
1409        // The closure-binding economy's DCE signal: no slot, value
1410        // silently dropped. Caller is unaffected.
1411        let mut k = compile_polydat_interpreter("input cycle: u64\nx := 1\n").unwrap();
1412        let cw = CycleWires::new(&mut k);
1413        let wires: &dyn WireSource = &cw;
1414        assert_eq!(wires.write("nope", Value::U64(99)), WriteOutcome::NoSlot);
1415    }
1416
1417    #[test]
1418    fn cycle_wires_write_feeds_eval_cone_through_get() {
1419        // The full capture-then-pull flow: write a magic-extern
1420        // input, read an output that depends on it through the
1421        // eval cone. This is the metrics-wrapper-reading-row_count
1422        // scenario from the design memo.
1423        let mut k = compile_polydat_interpreter(
1424            "input cycle: u64\n\
1425             extern count: u64\n\
1426             row_count := count\n",
1427        )
1428        .unwrap();
1429        k.set_inputs(&[0]);
1430        let cw = CycleWires::new(&mut k);
1431        let wires: &dyn WireSource = &cw;
1432
1433        // Before the write, `count` is at its default and
1434        // `row_count` reflects that.
1435        assert_eq!(wires.write("count", Value::U64(123)), WriteOutcome::Stored);
1436        // The pull through `row_count` (an output) reads the
1437        // freshly-written `count` (an input).
1438        assert_eq!(wires.get("row_count").map(|v| v.as_u64()), Some(123));
1439    }
1440
1441    #[test]
1442    fn null_wires_write_returns_no_slot() {
1443        let wires: &dyn WireSource = &NULL_WIRES;
1444        assert_eq!(wires.write("anything", Value::U64(1)), WriteOutcome::NoSlot);
1445    }
1446
1447    #[test]
1448    fn resolve_op_fields_four_case_dispatch() {
1449        // Pin the four-case dispatch contract for op-field resolution.
1450        // See `resolve_op_fields_via_wires` doc for the cases.
1451        let mut k = compile_polydat_interpreter(
1452            "input cycle: u64\n\
1453             table := \"users\"\n\
1454             count := 42\n",
1455        )
1456        .unwrap();
1457        let cw = CycleWires::new(&mut k);
1458
1459        let fields: Vec<(String, serde_json::Value)> = vec![
1460            // Case 1: non-string JSON scalar — stringified.
1461            ("limit_num".into(), serde_json::json!(100)),
1462            // Case 2: pure-token — typed wire reference, count is U64(42).
1463            (
1464                "typed_ref".into(),
1465                serde_json::Value::String("{count}".into()),
1466            ),
1467            // Case 3: text template — wires.get(table).to_display_string()
1468            //          interpolated into the surrounding text.
1469            (
1470                "templated".into(),
1471                serde_json::Value::String("SELECT * FROM {table} WHERE x = 1".into()),
1472            ),
1473            // Case 4: bare-string literal — no placeholders, passes through.
1474            (
1475                "literal_stmt".into(),
1476                serde_json::Value::String("SELECT 1".into()),
1477            ),
1478        ];
1479
1480        let resolved = resolve_op_fields_via_wires(&fields, &cw).expect("four-case dispatch");
1481
1482        // Case 1: stringified — exact form is implementation-defined,
1483        // verify the value contains the digits.
1484        assert!(
1485            matches!(resolved.get_value("limit_num"),
1486            Some(polydat::ast::Value::Str(s)) if s.contains("100")),
1487            "case 1: got {:?}",
1488            resolved.get_value("limit_num")
1489        );
1490        // Case 2: typed U64.
1491        assert_eq!(
1492            resolved.get_value("typed_ref").map(|v| v.as_u64()),
1493            Some(42),
1494            "case 2: typed wire ref preserves U64"
1495        );
1496        // Case 3: interpolated string.
1497        assert_eq!(
1498            resolved.get_str("templated"),
1499            Some("SELECT * FROM users WHERE x = 1"),
1500            "case 3: text template"
1501        );
1502        // Case 4: literal pass-through.
1503        assert_eq!(
1504            resolved.get_str("literal_stmt"),
1505            Some("SELECT 1"),
1506            "case 4: bare string literal"
1507        );
1508    }
1509
1510    #[test]
1511    fn cycle_wires_caches_across_repeated_gets() {
1512        // Pull memoizes; a second get of the same name reads the
1513        // cached value off state, not re-runs the eval cone. We
1514        // can't directly observe memoization but we CAN observe
1515        // that two reads of the same cycle produce the same value
1516        // (hash is deterministic per coordinate, but the kernel's
1517        // dirty-tracking would require a state mutation to
1518        // re-fire — the property still holds).
1519        let mut k = compile_polydat_interpreter("input cycle: u64\nh := hash(cycle)\n").unwrap();
1520        k.set_inputs(&[42]);
1521        let cw = CycleWires::new(&mut k);
1522        let wires: &dyn WireSource = &cw;
1523        let v1 = wires.get("h").unwrap().as_u64();
1524        let v2 = wires.get("h").unwrap().as_u64();
1525        assert_eq!(v1, v2);
1526    }
1527}