Skip to main content

nmbrs_runtime/
synthesis.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Per-fiber Polydat Kernel construction.
5//!
6//! `OpBuilder` owns the activity's source kernel and seeds each
7//! per-fiber [`FiberBuilder`] with a kernel bound under it, on the
8//! fiber engine where it has an image ([`crate::fiber_engine`]), plus
9//! the named scope overrides. The
10//! adapter-facing cycle-time bind-point resolution path
11//! historically lived here too, but SRD-68 Push 5 retired it in
12//! favour of the generic [`crate::wires::WireSource`] surface;
13//! this module now scopes to fiber construction and bind-point
14//! validation.
15//!
16//! See `docs/SRD/68_dispenser_owned_polydat_context.md` for the
17//! resolution model.
18
19use std::sync::{Arc, OnceLock};
20
21use crate::fiber_engine::OpTemplateModule;
22use crate::scope_kernel::ScopeKernel;
23use nmbrs_workload::bindpoints::{self, BindPoint, BindQualifier};
24use nmbrs_workload::model::ParsedOp;
25use polydat::Kernel;
26use polydat::ast::Value;
27use polydat::kernel::{KernelProgram, PolydatProgram};
28
29/// Cached `NMBRS_DIRTY_DEBUG=true` switch — per-cycle `std::env::var`
30/// reads measured at ~30% of single-fiber CPU; the OnceLock
31/// makes the gate a single atomic load on the hot path. See
32/// the matching helper in `wires.rs`.
33fn nmbrs_dirty_debug_enabled() -> bool {
34    static FLAG: OnceLock<bool> = OnceLock::new();
35    *FLAG.get_or_init(|| crate::debug_env::debug_flag("NMBRS_DIRTY_DEBUG"))
36}
37
38/// Shared op builder that distributes per-fiber builders.
39///
40/// Holds the activity's source kernel (immutable, shared). Each
41/// executor fiber calls `create_fiber_builder()` to get its own
42/// `FiberBuilder` with private kernels — no locks, no contention on
43/// the hot path.
44pub struct OpBuilder {
45    /// Name-keyed scope values (per SRD-13c), written into every new
46    /// fiber's kernels. Stored by name rather than `(input_idx, value)`
47    /// because each kernel — the fiber main kernel, every per-op-template
48    /// kernel — owns its own input layout, and an index captured against
49    /// the source kernel doesn't translate. The previous
50    /// `Vec<(usize, Value)>` shape silently mis-routed writes across
51    /// kernels (e.g. `table` value landing in the `profile` slot of an
52    /// op-template kernel whose extern declaration order differed from
53    /// the phase scope).
54    scope_values: Vec<(String, Value)>,
55    /// The source kernel — the activity's own kernel that each
56    /// per-fiber `FiberBuilder` binds its main kernel under. Owning the
57    /// kernel (not just its program) carries the activity's full cell
58    /// state — own input-slot cells plus transit cells inherited from
59    /// ancestors — to every fiber's main kernel.
60    source_kernel: Arc<ScopeKernel>,
61    /// SRD-13d Phase 9 — per-op-template kernel programs keyed
62    /// by op name. Populated by [`Self::with_op_template_programs`]
63    /// when the runner has materialised op-template kernels in
64    /// the scope tree. Wrappers (e.g. `MetricsDispenser`) look up
65    /// the program for their template via [`Self::program_for_op`]
66    /// and build their `ScopeFixture` against it; flattened
67    /// op-templates fall through to the activity-wide `program`.
68    op_template_programs: std::collections::HashMap<String, Arc<PolydatProgram>>,
69    /// What each canonical kernel this builder hands out stands for,
70    /// keyed by its `program_id`: a dispenser's canonical may be on any
71    /// engine, and each fiber finds here the interpreter program that
72    /// resolves its indices and the module it instantiates the per-op
73    /// kernel from.
74    canonicals: Canonicals,
75}
76
77/// What a canonical kernel's program is to a fiber: the interpreter
78/// program that resolves its indices (the analysis program; a native
79/// image of it shares its indices, `fiber_engine::agrees`), and the
80/// op-template module a per-op kernel is instantiated from on the fiber
81/// engine, when it has one, or else the image a per-op kernel is bound
82/// from — the scope's own engine program, the interpreter program when
83/// nothing better stands in for it.
84#[derive(Clone)]
85struct CanonicalSource {
86    program: Arc<PolydatProgram>,
87    image: Arc<dyn KernelProgram>,
88    module: Option<Arc<OpTemplateModule>>,
89}
90
91impl CanonicalSource {
92    /// A program with no other image: per-op kernels bind it on the
93    /// interpreter.
94    fn interpreted(program: Arc<PolydatProgram>) -> Self {
95        Self {
96            image: program.clone(),
97            program,
98            module: None,
99        }
100    }
101}
102
103/// Canonical sources by the `program_id` of every kernel that stands for
104/// them.
105type Canonicals = Arc<std::collections::HashMap<polydat::kernel::ProgramId, CanonicalSource>>;
106
107/// The identity an interpreter program's kernels report.
108fn program_id_of(program: &Arc<PolydatProgram>) -> polydat::kernel::ProgramId {
109    KernelProgram::program_id(program.as_ref())
110}
111
112impl OpBuilder {
113    /// Create an OpBuilder from a kernel.
114    ///
115    /// If the kernel has scope values (set via `materialize_wiring_from_outer`
116    /// or directly via `kernel.state().set_input`), they are
117    /// captured and propagated into every fiber's kernels.
118    pub fn new(kernel: impl crate::scope_kernel::IntoSharedScope) -> Self {
119        let kernel: Arc<ScopeKernel> = kernel.into_shared_scope();
120        // Scope values seed PLAIN slots only. A CELL-BOUND slot's value
121        // is the live shared cell — snapshotting it here freezes the
122        // cell's activity-start value, and every downstream
123        // re-application (fiber seeding, the stanza-boundary
124        // `reset_captures`) would `set_input` that stale snapshot
125        // THROUGH the cell, clobbering later writes for every kernel
126        // sharing it. Same exclusion `reset_inputs` documents:
127        // cells are cross-kernel shared state with their own
128        // lifecycle.
129        let scope_values: Vec<(String, Value)> = kernel
130            .scope_values()
131            .into_iter()
132            .filter(|(name, _)| {
133                kernel
134                    .program()
135                    .find_input(name)
136                    .map(|idx| !kernel.input_is_cell_bound(idx))
137                    .unwrap_or(true)
138            })
139            .collect();
140        // The source kernel is the canonical of every flattened op.
141        let canonicals = std::iter::once((
142            kernel.program_id(),
143            CanonicalSource {
144                program: kernel.program().clone(),
145                image: kernel.image().clone(),
146                module: None,
147            },
148        ))
149        .collect();
150        Self {
151            scope_values,
152            source_kernel: kernel,
153            op_template_programs: std::collections::HashMap::new(),
154            canonicals: Arc::new(canonicals),
155        }
156    }
157
158    /// Install per-op-template kernel programs (SRD-13d Phase 9).
159    /// The runner builds these from the scope tree's
160    /// `cached_kernel` slots for materialised op-template scopes
161    /// and threads them here so wrappers can look up the right
162    /// program when constructing their fixtures.
163    pub fn with_op_template_programs(
164        mut self,
165        programs: std::collections::HashMap<String, Arc<PolydatProgram>>,
166    ) -> Self {
167        let canonicals = Arc::make_mut(&mut self.canonicals);
168        for program in programs.values() {
169            canonicals
170                .entry(program_id_of(program))
171                .or_insert_with(|| CanonicalSource::interpreted(program.clone()));
172        }
173        self.op_template_programs = programs;
174        self
175    }
176
177    /// Instantiate per-op kernels from `modules`, the op-template scope
178    /// modules of this phase. A module whose fiber-engine image
179    /// disagrees with its program is left out, and its per-op kernels
180    /// stay on the interpreter.
181    pub fn with_op_template_modules(
182        mut self,
183        modules: impl IntoIterator<Item = (String, Arc<OpTemplateModule>)>,
184    ) -> Self {
185        let canonicals = Arc::make_mut(&mut self.canonicals);
186        for (name, module) in modules {
187            let Some(image) =
188                crate::fiber_engine::module_image(&module, &format!("op template '{name}'"))
189            else {
190                continue;
191            };
192            let source = CanonicalSource {
193                program: module.program().clone(),
194                image: image.clone(),
195                module: Some(module.clone()),
196            };
197            // Both the interpreter program and its native image stand
198            // for the module: a canonical kernel reports either.
199            canonicals.insert(program_id_of(module.program()), source.clone());
200            canonicals.insert(image.program_id(), source);
201        }
202        self
203    }
204
205    /// Look up the kernel program for op `name`. Returns the
206    /// per-op-template program if Phase 9 produced one for this
207    /// op (i.e. `materialised` and bindings non-empty); otherwise
208    /// returns the activity-wide program (the flatten path).
209    pub fn program_for_op(&self, name: &str) -> Arc<PolydatProgram> {
210        self.op_template_programs
211            .get(name)
212            .cloned()
213            .unwrap_or_else(|| self.source_kernel.program().clone())
214    }
215
216    /// The activity-wide kernel program. Used by callers that
217    /// need the source program shape (output names, manifest)
218    /// without rebuilding a fresh kernel.
219    pub fn program(&self) -> Arc<PolydatProgram> {
220        self.source_kernel.program().clone()
221    }
222
223    /// The activity-wide source kernel — the Polydat context every
224    /// op-template subscope is built upon. Adapters' `map_op`
225    /// implementations receive a kernel of this scope (see
226    /// [`Self::canonical_kernel_for_op`]) as the `parent` argument, to
227    /// bind their own canonical op-template kernel under (SRD-68
228    /// invariant I-3) or to retain when their op has no matter to add.
229    pub fn source_kernel(&self) -> &Arc<ScopeKernel> {
230        &self.source_kernel
231    }
232
233    /// Build the canonical op-template kernel for `op_name` —
234    /// the Polydat context the dispenser owns and that per-fiber
235    /// instances are materialised from (SRD-68 invariants I-3,
236    /// I-4). Built once at dispenser construction time.
237    ///
238    /// When `op_name` has a registered op-template program (phase
239    /// `bindings:`, op-level `bindings:`, `result:` block — the
240    /// matter assembled by the synthesis pipeline before the
241    /// activity runs), the canonical is that program bound under
242    /// `source_kernel`: instantiated from its module on the fiber
243    /// engine when it has one, on the interpreter otherwise.
244    /// Otherwise the canonical is a fork of the source kernel (its
245    /// program, state and cells), which covers the flattened-op-template
246    /// path (no per-op matter). Either way the adapter holds a kernel of any
247    /// engine, whose `program_id` this builder recognizes.
248    pub fn canonical_kernel_for_op(&self, op_name: &str) -> Arc<dyn Kernel> {
249        let Some(program) = self.op_template_programs.get(op_name) else {
250            return Arc::from(self.source_kernel.fork().into_kernel());
251        };
252        let module = self
253            .canonicals
254            .get(&program_id_of(program))
255            .and_then(|source| source.module.clone());
256        match module {
257            Some(module) => Arc::from(
258                module
259                    .instantiate_under(
260                        self.source_kernel.kernel(),
261                        crate::fiber_engine::fiber_engine(),
262                        &[],
263                    )
264                    .unwrap_or_else(|e| {
265                        panic!("op '{op_name}': canonical kernel failed to instantiate: {e}")
266                    }),
267            ),
268            None => Arc::from(
269                polydat::kernel::bind_under(
270                    self.source_kernel.kernel(),
271                    program.clone() as Arc<dyn KernelProgram>,
272                    &[],
273                )
274                .unwrap_or_else(|e| panic!("op '{op_name}': canonical kernel failed to bind: {e}")),
275            ),
276        }
277    }
278
279    /// Create a per-fiber builder. No locks, no sharing — the fiber
280    /// owns its kernels exclusively. Scope values (per-iteration
281    /// inputs from `for_each` / `for_combinations` / outer scope
282    /// constants) are written into the main kernel's inputs and
283    /// remembered on the builder so `reset_captures` (called at
284    /// stanza boundaries) can re-apply them — otherwise the
285    /// blanket "reset all non-coord inputs" pass would clobber
286    /// the iteration's bound values.
287    pub fn create_fiber_builder(&self) -> FiberBuilder {
288        // The fiber's main kernel is bound under the activity's source
289        // kernel: cells, transit cells, and value-copy bindings flow in
290        // automatically, and the scope-init constants materialize, so
291        // the fiber observes the same cell handles as the workload-root
292        // through the chain.
293        //
294        // Scope values are bound with it, as iteration bindings, so the
295        // main kernel's consts initialize from them (a const is fixed at
296        // init). The indices cached here feed the per-cycle
297        // `reset_captures` re-application.
298        let mut fb = FiberBuilder::with_scope(&self.source_kernel, None, self.scope_values.clone());
299        fb.canonicals = self.canonicals.clone();
300        // SRD-68: per-fiber op-template kernels are populated by
301        // `attach_dispenser_kernels`, which runs right after this
302        // function returns (see executor cycle dispatch), each from
303        // the firing dispenser's `OpDispenser::canonical_kernel()`.
304        fb
305    }
306}
307
308/// The input a scope value is written to on `program`, or `None` when
309/// the program has no such input or it is a coordinate. A coordinate
310/// (the `cycle` a scope carries among its values) advances with every
311/// cycle through `set_inputs` and is never written by name; the stanza
312/// reset leaves it untouched, so there is nothing to re-apply.
313fn scope_value_index(program: &PolydatProgram, name: &str) -> Option<usize> {
314    let idx = program.find_input(name)?;
315    (program.input_kind(idx) != Some(polydat::kernel::InputKind::Coordinate)).then_some(idx)
316}
317
318/// The scope values a kernel of `program` takes, as the `iter_bindings`
319/// its binder writes before the kernel's consts are initialized: each
320/// value converted to its slot's declared type, skipping the values
321/// `program` has no (non-coordinate) input for.
322///
323/// # Panics
324/// On a scope value its slot's type cannot take, converted or not: a
325/// fail-loud condition, since it would otherwise corrupt every read.
326fn scope_bindings(
327    program: &PolydatProgram,
328    scope_values: &[(String, Value)],
329) -> Vec<(String, Value)> {
330    scope_values
331        .iter()
332        .filter(|(name, _)| scope_value_index(program, name).is_some())
333        .map(|(name, value)| {
334            let value = match program.input_port_type(name) {
335                Some(port) => polydat::convert::to_port(value.clone(), port).unwrap_or_else(|e| {
336                    panic!("scope value '{name}' failed typed write at scope-init: {e}")
337                }),
338                None => value.clone(),
339            };
340            (name.clone(), value)
341        })
342        .collect()
343}
344
345/// Per-fiber op builder. Owns its own kernels.
346/// No locks, no synchronization, no contention.
347///
348/// Created via `OpBuilder::create_fiber_builder()` at fiber startup.
349///
350/// Every kernel here may be on any engine: the main kernel and the
351/// per-op kernels run on the fiber engine where an image is available
352/// ([`crate::fiber_engine`]) and on the interpreter otherwise. Each is
353/// paired with the interpreter program it runs or was imaged from,
354/// which shares its input and output indices: names resolve on the
355/// program once, and the kernel is driven by index.
356pub struct FiberBuilder {
357    /// The fiber's main kernel — typically the activity-wide
358    /// (workload / phase) program.
359    main_kernel: Box<dyn Kernel>,
360    /// The interpreter program [`Self::main_kernel`] runs or was
361    /// imaged from.
362    main_program: Arc<PolydatProgram>,
363    /// Scope-bound input values (per-iteration extern bindings)
364    /// that should persist across stanza-level `reset_inputs`
365    /// resets. Empty for a builder created via plain
366    /// [`FiberBuilder::new`]; populated by
367    /// [`OpBuilder::create_fiber_builder`].
368    scope_values: Vec<(String, Value)>,
369    /// SRD-68 invariant I-4 — per-fiber kernel instances, indexed
370    /// parallel to the activity's dispenser registry. Each entry
371    /// is the corresponding dispenser's canonical program bound under
372    /// [`Self::main_kernel`]; `None` for dispensers that don't expose
373    /// a canonical kernel (adapters with no Polydat needs, or wrappers
374    /// that delegate). Populated by
375    /// [`Self::attach_dispenser_kernels`] right after fiber spawn,
376    /// before any cycles run; read at cycle dispatch to populate
377    /// `ExecCtx::wires` for the firing dispenser.
378    per_op_kernels: Vec<Option<Box<dyn Kernel>>>,
379    /// The interpreter program each per-op kernel runs or was imaged
380    /// from, parallel to [`Self::per_op_kernels`].
381    per_op_programs: Vec<Option<Arc<PolydatProgram>>>,
382    /// Per-op-kernel side-effecting output indices (parallels
383    /// [`Self::per_op_kernels`]). The subset of each op-template
384    /// kernel's outputs whose cone contains a `Purity::SideChannel`
385    /// node — the only outputs the per-cycle "fire side effects" pass
386    /// pulls. Computed once at [`Self::attach_dispenser_kernels`] so
387    /// volatile metric-reader outputs (the objective bindings) are NOT
388    /// re-evaluated every cycle just to fire a non-existent effect.
389    per_op_side_effecting: Vec<Vec<usize>>,
390    /// Pre-resolved input indices for each entry in
391    /// [`Self::scope_values`] against [`Self::main_kernel`].
392    /// `None` slots are scope values the main program doesn't
393    /// declare, or declares as a coordinate (silently skipped at
394    /// write time — matches the historical name-based-skip semantics).
395    scope_value_main_idx: Vec<Option<usize>>,
396    /// Per-op-kernel mirror of [`Self::scope_value_main_idx`].
397    /// Outer Vec parallels [`Self::per_op_kernels`]; inner Vec
398    /// parallels [`Self::scope_values`]. `None` outer slots
399    /// match per_op_kernels' `None` entries.
400    scope_value_per_op_idx: Vec<Option<Vec<Option<usize>>>>,
401    /// Whether some per-op kernel runs a program other than the main
402    /// kernel's, and so reads the main kernel's outputs through its
403    /// broadcast cells (see [`Self::set_source_item`]).
404    needs_broadcast: bool,
405    /// What each dispenser's canonical kernel stands for — its
406    /// interpreter program and op-template module — by the kernel's
407    /// `program_id` (see [`OpBuilder::canonical_kernel_for_op`]).
408    canonicals: Canonicals,
409}
410
411/// Validate that all bind points in op templates can be resolved.
412///
413/// Called at init time. Warns for each unresolvable `{name}` reference.
414/// A bind point is resolvable if it matches a Polydat output, input name,
415/// or a known capture declaration from another op. Workload params are
416/// injected into the Polydat source as constant bindings before compilation,
417/// so they resolve as Polydat outputs.
418/// Validate that all bind points in op templates can be resolved.
419///
420/// Returns `Err` with a descriptive message if any bind point is
421/// unresolvable. Callers should treat this as a fatal error —
422/// unresolved bind points produce broken ops at runtime.
423pub fn validate_bind_points(
424    templates: &[ParsedOp],
425    program_for_op: &dyn Fn(&str) -> Arc<PolydatProgram>,
426) -> Result<(), String> {
427    // Collect all capture declarations across templates. Captures
428    // are extracted at workload-parse time and live on
429    // `ParsedOp.captures`; the op-text fields have brackets
430    // stripped by then, so re-parsing the text wouldn't surface
431    // them.
432    let mut capture_names: std::collections::HashSet<String> = std::collections::HashSet::new();
433    for template in templates {
434        for cap in &template.captures {
435            capture_names.insert(cap.as_name.clone());
436        }
437    }
438
439    let mut errors: Vec<String> = Vec::new();
440
441    for template in templates {
442        // THIS op's program, not the activity-wide one. An op that owns a
443        // kernel (its own `bindings:`, or an adapter that materialises one)
444        // has its bindings in that program and nowhere else, so validating
445        // every template against the activity kernel reported an op's own
446        // binding as unresolvable — `{x}` in `stmt:`/`raw:` failed at RUNTIME
447        // while the same name still rendered fine in `memo:`/`gutter:`, which
448        // read the live wires instead of this check.
449        let program = program_for_op(&template.name);
450        for (field_name, value) in &template.op {
451            if let serde_json::Value::String(s) = value {
452                let bps = bindpoints::extract_bind_points(s)
453                    .map_err(|e| format!("op '{}' field '{field_name}': {e}", template.name))?;
454                for bp in &bps {
455                    if let BindPoint::Reference {
456                        name, qualifier, ..
457                    } = bp
458                    {
459                        let resolvable = match qualifier {
460                            BindQualifier::Bind => program.resolve_output(name).is_some(),
461                            BindQualifier::Capture => capture_names.contains(name),
462                            BindQualifier::Input => {
463                                program.input_names().contains(&name.to_string())
464                            }
465                            BindQualifier::None => {
466                                program.resolve_output(name).is_some()
467                                    || capture_names.contains(name)
468                                    || program.input_names().contains(&name.to_string())
469                            }
470                        };
471                        if !resolvable {
472                            errors.push(format!(
473                                "unresolved bind point '{{{name}}}' in op '{}' field '{field_name}'. \
474                                 Not found in Polydat bindings, captures, or inputs.",
475                                template.name
476                            ));
477                        }
478                    }
479                }
480            }
481        }
482    }
483
484    if errors.is_empty() {
485        Ok(())
486    } else {
487        for e in &errors {
488            crate::observer::log(crate::observer::LogLevel::Error, &format!("error: {e}"));
489        }
490        Err(format!("{} unresolved bind point(s)", errors.len()))
491    }
492}
493
494impl FiberBuilder {
495    /// Create a new fiber builder whose main kernel is the parent's own
496    /// image bound under the parent, on the parent's engine.
497    pub fn new(parent: &ScopeKernel) -> Self {
498        Self::with_image(parent, None)
499    }
500
501    /// Create a new fiber builder whose main kernel runs `image` — the
502    /// fiber engine's image of `parent`'s program — bound under
503    /// `parent`; the parent's own image when `image` is `None`.
504    /// Per-fiber state is fresh; cell handles are Arc-shared with the
505    /// parent so writes propagate to the workload-root through the
506    /// cascade.
507    pub fn with_image(parent: &ScopeKernel, image: Option<Arc<dyn KernelProgram>>) -> Self {
508        Self::with_scope(parent, image, Vec::new())
509    }
510
511    /// [`Self::with_image`], binding `scope_values` into the main kernel
512    /// as it is built, before its consts initialize, and remembering
513    /// them for the stanza-boundary [`Self::reset_captures`].
514    pub fn with_scope(
515        parent: &ScopeKernel,
516        image: Option<Arc<dyn KernelProgram>>,
517        scope_values: Vec<(String, Value)>,
518    ) -> Self {
519        let main_program = parent.program().clone();
520        let image: Arc<dyn KernelProgram> = image.unwrap_or_else(|| parent.image().clone());
521        let bindings = scope_bindings(&main_program, &scope_values);
522        let main_kernel = polydat::kernel::bind_under(parent.kernel(), image, &bindings)
523            .unwrap_or_else(|e| panic!("a fiber's main kernel failed to bind: {e}"));
524        let scope_value_main_idx = scope_values
525            .iter()
526            .map(|(name, _)| scope_value_index(&main_program, name))
527            .collect();
528        // Standing alone, the fiber knows one canonical: its parent's own
529        // program, the flattened op's. `OpBuilder::create_fiber_builder`
530        // replaces this with the activity's full set.
531        let canonicals = std::iter::once((
532            parent.program_id(),
533            CanonicalSource {
534                program: main_program.clone(),
535                image: parent.image().clone(),
536                module: None,
537            },
538        ))
539        .collect();
540        Self {
541            main_kernel,
542            main_program,
543            scope_values,
544            per_op_kernels: Vec::new(),
545            per_op_programs: Vec::new(),
546            per_op_side_effecting: Vec::new(),
547            scope_value_main_idx,
548            scope_value_per_op_idx: Vec::new(),
549            needs_broadcast: false,
550            canonicals: Arc::new(canonicals),
551        }
552    }
553
554    /// SRD-68 Push 3 — populate this fiber's per-op kernel slots
555    /// from the activity's dispenser registry. Walks each
556    /// dispenser, calls `dispenser.canonical_kernel()` to get the
557    /// dispenser-owned canonical kernel (when present), and binds a
558    /// per-fiber kernel of its program under this fiber's main kernel.
559    /// Slot positions match the dispenser registry's order so
560    /// cycle-time dispatch can index by `template_idx`. Dispensers
561    /// that return `None` (no GK needs) get a `None` slot —
562    /// `ExecCtx::wires` falls back to the `NullWireSource` baseline
563    /// for those cycles.
564    ///
565    /// A per-op kernel is instantiated from its op-template module on
566    /// the fiber engine when the fiber has one for the canonical's
567    /// program, carrying the module's `result:` write-throughs; any
568    /// other canonical program runs on the interpreter.
569    ///
570    /// Called once per fiber, right after spawn, before any cycles
571    /// run. Idempotent: re-attaching with the same registry is
572    /// a no-op since canonical kernels are stable across phase
573    /// activation.
574    pub fn attach_dispenser_kernels(
575        &mut self,
576        dispensers: &[std::sync::Arc<dyn crate::adapter::OpDispenser>],
577    ) {
578        let scope_values = self.scope_values.clone();
579        // SRD-13f Stage 1: per-op kernels descend from
580        // `fiber.main_kernel` (this fiber's per-fiber scope kernel for
581        // the current phase), NOT from the dispenser's shared
582        // `canonical_kernel`. The dispenser's canonical_kernel becomes
583        // a *program source*, so there is one consistent per-fiber
584        // chain:
585        //     fiber.main_kernel → per_op_kernel
586        // Computed outputs on main_kernel are reachable from
587        // per_op_kernel via the standard scope-chain mechanism;
588        // per-fiber state (cycle, scope values) propagates
589        // correctly without external refresh.
590        // A canonical kernel may be on any engine: what it stands for —
591        // the interpreter program resolving its indices, and the module
592        // a per-op kernel is instantiated from — is looked up by its
593        // program's identity. A canonical this activity's builder did
594        // not hand out — an adapter's own kernel — stands for its
595        // interpreter program when it has one; a compiled one stands for
596        // nothing it can bind, and its dispenser runs against the fiber's
597        // main kernel.
598        let sources: Vec<Option<CanonicalSource>> = dispensers
599            .iter()
600            .map(|d| {
601                let kernel = d.canonical_kernel()?;
602                if let Some(source) = self.canonicals.get(&kernel.program_id()) {
603                    return Some(source.clone());
604                }
605                let program = kernel.fork().into_program().as_interpreter();
606                if program.is_none() {
607                    crate::diag!(
608                        crate::observer::LogLevel::Warn,
609                        "a dispenser's canonical kernel ({}) was not built by this \
610                         activity; its op reads the fiber's main kernel",
611                        kernel.engine()
612                    );
613                }
614                program.map(CanonicalSource::interpreted)
615            })
616            .collect();
617        let dispenser_programs: Vec<Option<Arc<PolydatProgram>>> = sources
618            .iter()
619            .map(|s| s.as_ref().map(|s| s.program.clone()))
620            .collect();
621        let mut per_op_kernels: Vec<Option<Box<dyn Kernel>>> =
622            Vec::with_capacity(dispenser_programs.len());
623        let mut per_op_idx: Vec<Option<Vec<Option<usize>>>> =
624            Vec::with_capacity(dispenser_programs.len());
625        let mut per_op_side_effecting: Vec<Vec<usize>> =
626            Vec::with_capacity(dispenser_programs.len());
627        for maybe_source in &sources {
628            let Some(CanonicalSource {
629                program,
630                image,
631                module,
632            }) = maybe_source
633            else {
634                per_op_kernels.push(None);
635                per_op_idx.push(None);
636                per_op_side_effecting.push(Vec::new());
637                continue;
638            };
639            // Scope values are bound with the kernel, before its consts
640            // initialize; the indices are cached for `reset_captures`.
641            let bindings = scope_bindings(program, &scope_values);
642            let mut op_kernel = match module {
643                Some(module) => module
644                    .instantiate_under(
645                        self.main_kernel.as_ref(),
646                        crate::fiber_engine::fiber_engine(),
647                        &bindings,
648                    )
649                    .unwrap_or_else(|e| panic!("per-op kernel failed to instantiate: {e}")),
650                None => {
651                    polydat::kernel::bind_under(self.main_kernel.as_ref(), image.clone(), &bindings)
652                        .unwrap_or_else(|e| panic!("per-op kernel failed to bind: {e}"))
653                }
654            };
655            let idx_vec: Vec<Option<usize>> = scope_values
656                .iter()
657                .map(|(name, _)| scope_value_index(program, name))
658                .collect();
659            for init_name in program.const_outputs() {
660                let Some(idx) = program.output_index(init_name) else {
661                    continue;
662                };
663                // Const warmup is best-effort: a const whose freeze
664                // fails here stays dirty and re-evals (or fails
665                // visibly) at its first per-cycle use. But the failure
666                // is never discarded silently — the enriched payload
667                // goes to the session log so a broken const is
668                // diagnosable before the per-cycle path trips over it.
669                if let Err(payload) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
670                    op_kernel.pull_at(idx);
671                })) {
672                    let msg = payload
673                        .downcast_ref::<&'static str>()
674                        .map(|s| (*s).to_string())
675                        .or_else(|| payload.downcast_ref::<String>().cloned())
676                        .unwrap_or_else(|| "<non-string panic payload>".into());
677                    crate::diag!(
678                        crate::observer::LogLevel::Warn,
679                        "const warmup pull '{init_name}' panicked during \
680                         op-template kernel init (deferring to first \
681                         per-cycle use): {msg}"
682                    );
683                }
684            }
685            let side_effecting = program
686                .outputs_with_side_effects()
687                .iter()
688                .filter_map(|name| program.output_index(name))
689                .collect();
690            per_op_kernels.push(Some(op_kernel));
691            per_op_idx.push(Some(idx_vec));
692            per_op_side_effecting.push(side_effecting);
693        }
694        // SRD-13f Push D: the main kernel publishes its outputs through
695        // broadcast cells only when a per-op kernel has a *different*
696        // program from it. When the per-op kernel reuses the main
697        // program (the flattened-op-template path — no per-op matter),
698        // evaluating outputs on main is both redundant (the descendant
699        // evaluates the same wires locally) and harmful (side-effecting
700        // nodes like `testkit_throw_at` fire outside the per-op cascade
701        // surface, losing the panic-to-error pipeline). A per-op kernel
702        // with its own program carries `extern <name>` slots for
703        // cross-scope wires it doesn't replicate locally; those slots
704        // need main to compute and broadcast the values through the
705        // cell.
706        self.needs_broadcast = dispenser_programs
707            .iter()
708            .flatten()
709            .any(|p| !Arc::ptr_eq(p, &self.main_program));
710        self.per_op_kernels = per_op_kernels;
711        self.per_op_programs = dispenser_programs;
712        self.per_op_side_effecting = per_op_side_effecting;
713        self.scope_value_per_op_idx = per_op_idx;
714    }
715
716    /// The cycle-time wire surface for the firing dispenser at
717    /// `template_idx`: its per-fiber kernel, or this fiber's main
718    /// kernel when the dispenser exposes no canonical kernel (the
719    /// flattened path).
720    pub fn cycle_wires(&mut self, template_idx: usize) -> crate::wires::CycleWires<'_> {
721        let program = self
722            .per_op_programs
723            .get(template_idx)
724            .and_then(|p| p.clone());
725        match (
726            self.per_op_kernels
727                .get_mut(template_idx)
728                .and_then(|s| s.as_mut()),
729            program,
730        ) {
731            (Some(kernel), Some(program)) => {
732                crate::wires::CycleWires::over(kernel.as_mut(), program)
733            }
734            _ => {
735                crate::wires::CycleWires::over(self.main_kernel.as_mut(), self.main_program.clone())
736            }
737        }
738    }
739
740    /// The cycle-time wire surface over this fiber's main kernel.
741    pub fn main_wires(&mut self) -> crate::wires::CycleWires<'_> {
742        crate::wires::CycleWires::over(self.main_kernel.as_mut(), self.main_program.clone())
743    }
744
745    /// Get the per-fiber kernel for the firing dispenser at
746    /// `template_idx`. Returns `None` when the dispenser exposes
747    /// no canonical kernel (adapters with no Polydat needs); callers
748    /// fall back to the `NullWireSource` baseline.
749    pub fn per_op_kernel(&self, template_idx: usize) -> Option<&dyn Kernel> {
750        self.per_op_kernels
751            .get(template_idx)
752            .and_then(|s| s.as_deref())
753    }
754
755    /// This fiber's main kernel.
756    pub fn main_kernel(&self) -> &dyn Kernel {
757        self.main_kernel.as_ref()
758    }
759
760    /// The interpreter program this fiber's main kernel runs or was
761    /// imaged from.
762    pub fn program(&self) -> &Arc<PolydatProgram> {
763        &self.main_program
764    }
765
766    /// Set coordinates and begin a new evaluation scope.
767    ///
768    /// Bounded by each kernel's coordinate count: the slice is
769    /// truncated to the program's declared coordinate count
770    /// before being written. A phase kernel with no
771    /// coordinates (e.g. all bindings are invariant within the
772    /// stanza, only externs declared) has `coord_count = 0`,
773    /// so this becomes a no-op rather than clobbering the
774    /// extern slots that follow.
775    ///
776    /// SRD-13d Phase 9: the same coordinates are also written to
777    /// every per-op-template kernel that declares them as
778    /// coords. Each kernel binds its own input slot for `cycle`
779    /// (cascaded from parent) so per-cycle propagation is a
780    /// per-kernel `set_inputs`, not a chain walk.
781    pub fn set_inputs(&mut self, coords: &[u64]) {
782        let main_n = coords.len().min(self.main_kernel.coord_count());
783        if main_n > 0 {
784            self.main_kernel.set_inputs(&coords[..main_n]);
785        }
786        for kernel in self.per_op_kernels.iter_mut().flatten() {
787            let n = coords.len().min(kernel.coord_count());
788            if n > 0 {
789                kernel.set_inputs(&coords[..n]);
790            }
791        }
792    }
793
794    /// Feed a source item into the fiber's kernels.
795    ///
796    /// Sets the ordinal as the coordinate input and injects field
797    /// projections into the appropriate input slots (e.g.
798    /// `base__ordinal`, `base__vector`). The ordinal write is
799    /// skipped by kernels whose programs declare no coordinates
800    /// (only externs and stanza-invariant bindings) rather than
801    /// clobbering an extern slot. Field projections always write by
802    /// name, so they're safe regardless of coordinate count.
803    ///
804    /// SRD-13d Phase 9: ordinal + fields propagate to every
805    /// op-template kernel that declares matching slots.
806    pub fn set_source_item(&mut self, item: &polydat::iteration::source::SourceItem) {
807        if self.main_kernel.coord_count() > 0 {
808            self.main_kernel.set_inputs(&[item.ordinal]);
809        }
810        // Source items carry typed values from their upstream
811        // DataSource; one the slot's type cannot take, converted or
812        // not, means the source produced an incompatible value, which
813        // is a fail-loud condition.
814        for (name, value) in &item.fields {
815            if let Some(idx) = self.main_program.find_input(name) {
816                crate::wires::write_input(self.main_kernel.as_mut(), idx, name, value.clone())
817                    .unwrap_or_else(|e| {
818                        panic!("source item field '{name}' failed typed write: {e}")
819                    });
820            }
821        }
822        // Cell-bound cross-fiber visibility is substrate-owned via the
823        // per-cell revision counter + per-scope intent-dirty vector
824        // (polydat/docs/design/cross_fiber_invalidation.md): ancestor
825        // writes through a `SharedCell` bump the cell's revision and
826        // set its intent bit, and the evaluator re-checks both before
827        // serving a memoized result. No host-side refresh call needed.
828        for (kernel, program) in self
829            .per_op_kernels
830            .iter_mut()
831            .zip(self.per_op_programs.iter())
832        {
833            let (Some(kernel), Some(program)) = (kernel, program) else {
834                continue;
835            };
836            if kernel.coord_count() > 0 {
837                kernel.set_inputs(&[item.ordinal]);
838            }
839            for (name, value) in &item.fields {
840                if let Some(idx) = program.find_input(name) {
841                    crate::wires::write_input(kernel.as_mut(), idx, name, value.clone())
842                        .unwrap_or_else(|e| {
843                            panic!("source item field '{name}' failed typed write: {e}")
844                        });
845                }
846            }
847        }
848        if self.needs_broadcast {
849            self.main_kernel.publish_broadcasts();
850        }
851    }
852
853    /// Reset capture inputs to defaults. Called at stanza
854    /// boundaries to prevent capture leakage across stanzas.
855    /// Coordinates and cell-bound slots are not reset. Scope-bound
856    /// iter-var inputs (set by [`OpBuilder::create_fiber_builder`])
857    /// are re-applied after the reset so the iteration's bound
858    /// values survive the boundary.
859    pub fn reset_captures(&mut self) {
860        self.main_kernel.reset_inputs();
861        for ((name, value), idx_opt) in self
862            .scope_values
863            .iter()
864            .zip(self.scope_value_main_idx.iter())
865        {
866            if let Some(idx) = idx_opt {
867                crate::wires::write_input(self.main_kernel.as_mut(), *idx, name, value.clone())
868                    .unwrap_or_else(|e| panic!("scope value '{name}' failed typed write: {e}"));
869            }
870        }
871        for (slot, idx_slot) in self
872            .per_op_kernels
873            .iter_mut()
874            .zip(self.scope_value_per_op_idx.iter())
875        {
876            if let (Some(kernel), Some(idx_vec)) = (slot, idx_slot) {
877                kernel.reset_inputs();
878                for ((name, value), idx_opt) in self.scope_values.iter().zip(idx_vec.iter()) {
879                    if let Some(idx) = idx_opt {
880                        crate::wires::write_input(kernel.as_mut(), *idx, name, value.clone())
881                            .unwrap_or_else(|e| {
882                                panic!("scope value '{name}' failed typed write: {e}")
883                            });
884                    }
885                }
886            }
887        }
888    }
889
890    /// Invalidate all state: every step, a side channel included,
891    /// runs again when next pulled. Provides "clean slate" semantics.
892    pub fn invalidate_all(&mut self) {
893        self.main_kernel.invalidate_all();
894        for kernel in self.per_op_kernels.iter_mut().flatten() {
895            kernel.invalidate_all();
896        }
897    }
898
899    /// Store a captured value into the main kernel's input slot `name`.
900    /// Returns `true` when the slot exists and took the value, `false`
901    /// when the program has no such input or the value could not be
902    /// converted to its type (value dropped).
903    pub fn capture(&mut self, name: &str, value: Value) -> bool {
904        match self.main_program.find_input(name) {
905            Some(idx) => {
906                crate::wires::write_input(self.main_kernel.as_mut(), idx, name, value).is_ok()
907            }
908            None => false,
909        }
910    }
911
912    /// SRD-68 Push 5d: position-indexed write into the per-fiber
913    /// op-template kernel slot. Used by the cycle dispatch's
914    /// post-execute capture flow to feed result-binding inputs
915    /// (`body` / `count` / `ok` and any captures) into the kernel
916    /// before [`Self::commit_op_template_write_throughs_for_idx`]
917    /// fans the computed values up through parent `shared` cells.
918    ///
919    /// No-op returning `false` when (a) the op didn't materialise a
920    /// kernel (flattened op-template), or (b) the kernel doesn't
921    /// declare an input slot for `name` (the closure-binding economy
922    /// dropped it because the source doesn't reference it), or (c)
923    /// the value could not be converted to the slot's type.
924    pub fn write_op_template_input_for_idx(
925        &mut self,
926        template_idx: usize,
927        name: &str,
928        value: Value,
929    ) -> bool {
930        let (Some(Some(kernel)), Some(Some(program))) = (
931            self.per_op_kernels.get_mut(template_idx),
932            self.per_op_programs.get(template_idx),
933        ) else {
934            if nmbrs_dirty_debug_enabled() && name == "body" {
935                eprintln!("DIRTY: write body template={template_idx} NO_KERNEL");
936            }
937            return false;
938        };
939        let Some(idx) = program.find_input(name) else {
940            if nmbrs_dirty_debug_enabled() && name == "body" {
941                let inputs = program.input_names();
942                eprintln!(
943                    "DIRTY: write body template={template_idx} NO_SLOT in_count={} names={:?}",
944                    inputs.len(),
945                    inputs
946                );
947            }
948            return false;
949        };
950        if nmbrs_dirty_debug_enabled() && name == "body" {
951            let display = value.to_display_string();
952            let head: String = display.chars().take(48).collect();
953            eprintln!(
954                "DIRTY: write body template={template_idx} idx={idx} in_count={} \
955                 head=\"{head}\"",
956                program.input_names().len()
957            );
958        }
959        crate::wires::write_input(kernel.as_mut(), idx, name, value).is_ok()
960    }
961
962    /// SRD-68 Push 5d: position-indexed Rule 2 write-through commit.
963    /// Pulls every `__write_<X>` and stores its value through the
964    /// cell-bound input slot for `<X>`, propagating each result-
965    /// binding LHS value to the parent's `SharedCell` (and from
966    /// there to any sibling phase that imports the same name).
967    /// No-op when the kernel carries no write-throughs (typical
968    /// for ops without `result:`).
969    ///
970    /// Errors when a write-through violates cell type stability
971    /// (scope_model.md §"Type stability") — surfaced by the fiber
972    /// loop as a phase-stopping workload bug (it is deterministic:
973    /// every subsequent cycle would repeat it).
974    pub fn commit_op_template_write_throughs_for_idx(
975        &mut self,
976        template_idx: usize,
977    ) -> Result<(), String> {
978        let debug = polydat::library::debug_nodes_enabled();
979        let Some(kernel) = self
980            .per_op_kernels
981            .get_mut(template_idx)
982            .and_then(|s| s.as_mut())
983        else {
984            if debug {
985                crate::observer::log(
986                    crate::observer::LogLevel::Debug,
987                    &format!(
988                        "commit_op_template_write_throughs_for_idx: template_idx {template_idx} \
989                         has no per-fiber kernel slot"
990                    ),
991                );
992            }
993            return Ok(());
994        };
995        if debug {
996            crate::observer::log(
997                crate::observer::LogLevel::Debug,
998                &format!(
999                    "commit_op_template_write_throughs_for_idx: idx {template_idx} kernel found"
1000                ),
1001            );
1002        }
1003        kernel.commit_write_throughs()
1004    }
1005
1006    /// Per-cycle: pull the op-template kernel's **side-effecting**
1007    /// outputs at `template_idx` so side-effecting nodes (`log_info`
1008    /// and friends) actually evaluate. Without this, captured wires
1009    /// whose only consumer is a write-through are pulled by
1010    /// `commit_write_throughs`, but captured wires that aren't shared
1011    /// with a parent never get pulled — their compute chain (including
1012    /// any side-effecting nodes inside it) stays dormant, and the
1013    /// diagnostic the workload asked for never fires.
1014    ///
1015    /// Only outputs whose cone contains a `Purity::SideChannel` node are
1016    /// pulled (the set is precomputed at attach time,
1017    /// [`PolydatProgram::outputs_with_side_effects`]). A side-effect-free
1018    /// output is **not** pulled here: re-evaluating it would do nothing,
1019    /// and for a volatile metric reader (a `metricsql_*` / `metric`
1020    /// objective binding) it would issue a live metrics query *every
1021    /// cycle*. Such values are evaluated only when actually consumed.
1022    /// No-op when the kernel has no side-effecting outputs.
1023    pub fn pull_all_op_template_outputs_for_idx(&mut self, template_idx: usize) {
1024        let (Some(indices), Some(Some(kernel))) = (
1025            self.per_op_side_effecting.get(template_idx),
1026            self.per_op_kernels.get_mut(template_idx),
1027        ) else {
1028            return;
1029        };
1030        for &idx in indices {
1031            let _ = kernel.pull_at(idx);
1032        }
1033    }
1034
1035    /// Materialize a [`PullPlan`] against this fiber's main kernel.
1036    /// O(plan_len) on the hot path, no name hashing — the plan
1037    /// holds pre-resolved indices.
1038    ///
1039    /// This is the cycle-time read path used by every wrapper that
1040    /// holds [`PullHandle`]s registered into the corresponding
1041    /// [`ScopeFixture`] at init (SRD 31 §"Pull plan vs bind plan",
1042    /// SRD 32 §"Init-Time Fixture and Consumer Self-Registration").
1043    ///
1044    /// [`PullPlan`]: crate::fixture::PullPlan
1045    /// [`PullHandle`]: crate::fixture::PullHandle
1046    /// [`ScopeFixture`]: crate::fixture::ScopeFixture
1047    pub fn resolve_pulls(
1048        &mut self,
1049        plan: &crate::fixture::PullPlan,
1050    ) -> crate::fixture::ResolvedPulls {
1051        plan.resolve(self.main_kernel.as_mut())
1052    }
1053
1054    /// SRD-68 Push 5d resolve path — picks the right kernel for the
1055    /// dispenser at `template_idx` and resolves the plan against it.
1056    /// When a per-fiber op-template kernel was instanced for that
1057    /// position (every adapter exposes `canonical_kernel()` so this is
1058    /// the typical case), it is used; otherwise the plan resolves
1059    /// against the fiber's main kernel (the flattened op-template path).
1060    /// Either way the plan is checked against the interpreter program
1061    /// the kernel was imaged from, whose indices it holds.
1062    pub fn resolve_pulls_for_idx(
1063        &mut self,
1064        template_idx: usize,
1065        plan: &crate::fixture::PullPlan,
1066    ) -> crate::fixture::ResolvedPulls {
1067        let program = self
1068            .per_op_programs
1069            .get(template_idx)
1070            .and_then(|p| p.clone());
1071        match (
1072            self.per_op_kernels
1073                .get_mut(template_idx)
1074                .and_then(|s| s.as_mut()),
1075            program,
1076        ) {
1077            (Some(kernel), Some(program)) => {
1078                plan.check_program_match(&program, template_idx);
1079                plan.resolve(kernel.as_mut())
1080            }
1081            _ => {
1082                plan.check_program_match(&self.main_program, template_idx);
1083                plan.resolve(self.main_kernel.as_mut())
1084            }
1085        }
1086    }
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091    use super::*;
1092    use polydat::compile::assembly::{PolydatAssembler, WireRef};
1093    use polydat::library::arithmetic::Mod;
1094    use polydat::library::hash::Hash;
1095
1096    fn make_kernel() -> ScopeKernel {
1097        let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
1098        asm.add_node(
1099            "hashed",
1100            Box::new(Hash::new()),
1101            vec![WireRef::input("cycle")],
1102        );
1103        asm.add_node(
1104            "user_id",
1105            Box::new(Mod::new(1_000_000)),
1106            vec![WireRef::node("hashed")],
1107        );
1108        asm.add_output("user_id", WireRef::node("user_id"));
1109        asm.add_output("hashed", WireRef::node("hashed"));
1110        asm.compile().unwrap().into()
1111    }
1112
1113    /// SRD-13f Stage 1 gate — verify that the per-fiber
1114    /// kernel chain is a single linear descent. The
1115    /// op-template (per-op) kernel must be built as a
1116    /// subscope of the fiber's main kernel, NOT of a
1117    /// separate shared canonical. Inner reads of cross-scope
1118    /// wires depend on this being a per-fiber-consistent
1119    /// chain so cell-attached values reach inner via outer's
1120    /// per-fiber pull writes.
1121    #[test]
1122    fn per_fiber_chain_is_linear_and_unshared() {
1123        use crate::adapter::OpDispenser;
1124        // The structural property under test: when a fiber
1125        // attaches per-op kernels from a dispenser-shaped
1126        // canonical, each per-op kernel must be a NEW
1127        // per-fiber instance (subscope of the fiber's main
1128        // kernel), not the shared canonical kernel itself.
1129        //
1130        // Two fibers attaching against the same canonical
1131        // must produce different per-op kernel instances.
1132        let workload_kernel = make_kernel();
1133        let builder = OpBuilder::new(workload_kernel);
1134
1135        // Stand up a shared canonical via the public API.
1136        let workload_src = "input cycle: u64\nfolded := 42\n";
1137        let canonical_program = polydat::dsl::compile::compile_polydat_interpreter(workload_src)
1138            .expect("compile probe canonical")
1139            .program()
1140            .clone();
1141        let canonical_kernel: std::sync::Arc<dyn polydat::Kernel> =
1142            builder.canonical_kernel_for_op("nonexistent");
1143        // For this probe we only need the canonical to expose
1144        // a program; reuse builder's source_kernel program.
1145        let _ = canonical_program;
1146
1147        struct ProbeDispenser(std::sync::Arc<dyn polydat::Kernel>);
1148        impl OpDispenser for ProbeDispenser {
1149            fn canonical_kernel(&self) -> Option<&std::sync::Arc<dyn polydat::Kernel>> {
1150                Some(&self.0)
1151            }
1152            fn execute<'a>(
1153                &'a self,
1154                _cycle: u64,
1155                _ctx: &'a crate::fixture::ExecCtx<'a>,
1156            ) -> std::pin::Pin<
1157                Box<
1158                    dyn std::future::Future<
1159                            Output = Result<
1160                                crate::adapter::OpResult,
1161                                crate::adapter::ExecutionError,
1162                            >,
1163                        > + Send
1164                        + 'a,
1165                >,
1166            > {
1167                Box::pin(async move { Ok(crate::adapter::OpResult::default()) })
1168            }
1169        }
1170        let dispensers: Vec<std::sync::Arc<dyn OpDispenser>> = vec![std::sync::Arc::new(
1171            ProbeDispenser(canonical_kernel.clone()),
1172        )];
1173
1174        let mut fiber_a = builder.create_fiber_builder();
1175        fiber_a.attach_dispenser_kernels(&dispensers);
1176        let mut fiber_b = builder.create_fiber_builder();
1177        fiber_b.attach_dispenser_kernels(&dispensers);
1178
1179        let per_op_a = fiber_a.per_op_kernel(0).expect("per-op A attached");
1180        let per_op_b = fiber_b.per_op_kernel(0).expect("per-op B attached");
1181
1182        // SRD-13f invariant: each fiber's per-op kernel is a
1183        // distinct per-fiber instance, neither of them
1184        // pointing to the shared canonical kernel.
1185        assert!(
1186            !std::ptr::eq(
1187                per_op_a as *const dyn Kernel as *const (),
1188                canonical_kernel.as_ref() as *const dyn polydat::Kernel as *const ()
1189            ),
1190            "per_op_a must be a distinct per-fiber instance, \
1191             not the shared canonical",
1192        );
1193        assert!(
1194            !std::ptr::eq(
1195                per_op_b as *const dyn Kernel as *const (),
1196                canonical_kernel.as_ref() as *const dyn polydat::Kernel as *const ()
1197            ),
1198            "per_op_b must be a distinct per-fiber instance, \
1199             not the shared canonical",
1200        );
1201        assert!(
1202            !std::ptr::eq(
1203                per_op_a as *const dyn Kernel as *const (),
1204                per_op_b as *const dyn Kernel as *const ()
1205            ),
1206            "fiber A and fiber B must each have their own \
1207             per-op kernel instance",
1208        );
1209    }
1210
1211    /// SRD 11 §"Init Binding Contract" Plan B verification:
1212    /// after the activation kernel pulls an init binding, the
1213    /// pulled value must propagate to every fiber via
1214    /// `init_overrides`, and per-fiber pulls must read the seeded
1215    /// buffer rather than re-firing the eval.
1216    #[test]
1217    fn init_binding_fires_once_across_many_fibers() {
1218        use std::sync::Arc as StdArc;
1219        use std::sync::atomic::{AtomicU64, Ordering};
1220
1221        // Counting custom node: bumps a shared counter on every
1222        // eval call, returns U64(42). Tracks how many times its
1223        // eval body actually runs across the test.
1224        struct CountingNode {
1225            meta: polydat::ast::NodeMeta,
1226            calls: StdArc<AtomicU64>,
1227        }
1228        impl polydat::ast::PolydatNode for CountingNode {
1229            fn meta(&self) -> &polydat::ast::NodeMeta {
1230                &self.meta
1231            }
1232            fn eval(&self, _inputs: &[Value], outputs: &mut [Value]) {
1233                self.calls.fetch_add(1, Ordering::Relaxed);
1234                outputs[0] = Value::U64(42);
1235            }
1236        }
1237
1238        let calls = StdArc::new(AtomicU64::new(0));
1239        let mut asm = PolydatAssembler::new(vec!["cycle".into()]);
1240        // Compile-const seed expression — wires empty.
1241        asm.add_node(
1242            "ticks",
1243            Box::new(CountingNode {
1244                meta: polydat::ast::NodeMeta {
1245                    name: "ticks".into(),
1246                    outs: vec![polydat::ast::Port::new(
1247                        "output",
1248                        polydat::ast::PortType::U64,
1249                    )],
1250                    ins: vec![],
1251                },
1252                calls: calls.clone(),
1253            }),
1254            vec![],
1255        );
1256        asm.add_output("ticks", WireRef::node("ticks"));
1257        asm.mark_const_output("ticks");
1258
1259        let mut kernel = asm.compile().expect("compile");
1260        // Plan B normally runs in the executor; for this unit test
1261        // we simulate it by pulling the init binding once on the
1262        // activation kernel.
1263        let v = kernel.pull_ref("ticks").clone();
1264        assert_eq!(v, Value::U64(42));
1265        let after_pull = calls.load(Ordering::Relaxed);
1266        // The fold pass evaluates the node once, then ConstU64
1267        // replaces it (init binding is pure compile-const here),
1268        // so subsequent state pulls return the leaf const without
1269        // re-eval. Assert the call count never grows from here.
1270        let builder = OpBuilder::new(kernel);
1271
1272        // Spawn many fibers, each pulls the init binding. None
1273        // should trigger an eval — the post-fold leaf-const path
1274        // returns the constant directly.
1275        for _ in 0..32 {
1276            let mut fiber = builder.create_fiber_builder();
1277            fiber.set_inputs(&[0]);
1278            let pulled = {
1279                use crate::wires::WireSource as _;
1280                fiber.main_wires().get("ticks").expect("ticks resolves")
1281            };
1282            assert_eq!(pulled, Value::U64(42));
1283        }
1284        let after_fibers = calls.load(Ordering::Relaxed);
1285        assert_eq!(
1286            after_pull, after_fibers,
1287            "init binding 'ticks' eval must not re-fire across fibers \
1288             (eval calls before fibers: {after_pull}, after 32 fibers: {after_fibers})"
1289        );
1290        // Independent: confirm the eval ran at most once during
1291        // compile-time fold + the activation pull.
1292        assert!(
1293            after_fibers <= 1,
1294            "expected at most one eval across compile fold + activation pull, got {after_fibers}"
1295        );
1296    }
1297
1298    /// The fiber engine carries the scope tree: the phase scope, a
1299    /// fiber's main kernel bound under it, and a per-op kernel
1300    /// instantiated from its op-template module all run off the
1301    /// interpreter — and every value they compute is the interpreter's.
1302    #[test]
1303    fn fiber_kernels_run_on_the_fiber_engine_with_interpreter_values() {
1304        use crate::adapter::OpDispenser;
1305        use crate::wires::WireSource as _;
1306        use polydat::kernel::subcontext::{BodyFragment, SubcontextBuilder};
1307
1308        let phase_src = "input cycle: u64
1309h := mod(hash(cycle), 1000)
1310";
1311        let phase = Arc::new(ScopeKernel::compile(phase_src).expect("phase"));
1312        let reference_phase = Arc::new(ScopeKernel::from(
1313            polydat::dsl::compile::compile_polydat_interpreter(phase_src).expect("reference phase"),
1314        ));
1315
1316        let mut op = SubcontextBuilder::under(phase.kernel());
1317        op.body(BodyFragment::PolydatSource(
1318            "extern h: u64
1319scaled := h * 3 + 1
1320"
1321            .into(),
1322        ));
1323        let module = Arc::new(op.finalize().expect("op-template module"));
1324        let canonical: Arc<dyn polydat::Kernel> = Arc::from(
1325            polydat::kernel::bind_under(phase.kernel(), module.program().clone(), &[])
1326                .expect("canonical per-op kernel"),
1327        );
1328
1329        struct Probe(Arc<dyn polydat::Kernel>);
1330        impl OpDispenser for Probe {
1331            fn canonical_kernel(&self) -> Option<&Arc<dyn polydat::Kernel>> {
1332                Some(&self.0)
1333            }
1334            fn execute<'a>(
1335                &'a self,
1336                _cycle: u64,
1337                _ctx: &'a crate::fixture::ExecCtx<'a>,
1338            ) -> std::pin::Pin<
1339                Box<
1340                    dyn std::future::Future<
1341                            Output = Result<
1342                                crate::adapter::OpResult,
1343                                crate::adapter::ExecutionError,
1344                            >,
1345                        > + Send
1346                        + 'a,
1347                >,
1348            > {
1349                Box::pin(async move { Ok(crate::adapter::OpResult::default()) })
1350            }
1351        }
1352        let dispensers: Vec<Arc<dyn OpDispenser>> = vec![Arc::new(Probe(canonical))];
1353
1354        let native =
1355            OpBuilder::new(phase.clone()).with_op_template_modules([("op".to_string(), module)]);
1356        let interpreted = OpBuilder::new(reference_phase);
1357        let mut fiber = native.create_fiber_builder();
1358        fiber.attach_dispenser_kernels(&dispensers);
1359        let mut reference = interpreted.create_fiber_builder();
1360        reference.attach_dispenser_kernels(&dispensers);
1361
1362        let on_interpreter = |k: &dyn Kernel| matches!(k.engine(), polydat::Engine::Interpreter(_));
1363        assert!(
1364            !on_interpreter(phase.kernel()),
1365            "phase scope on {}",
1366            phase.engine()
1367        );
1368        assert!(
1369            !on_interpreter(fiber.main_kernel()),
1370            "main kernel on {}",
1371            fiber.main_kernel().engine()
1372        );
1373        let per_op = fiber.per_op_kernel(0).expect("per-op kernel attached");
1374        assert!(
1375            !on_interpreter(per_op),
1376            "per-op kernel on {}",
1377            per_op.engine()
1378        );
1379        assert!(on_interpreter(reference.main_kernel()));
1380        assert!(on_interpreter(
1381            reference.per_op_kernel(0).expect("reference per-op")
1382        ));
1383
1384        for cycle in [0, 1, 7, 1_000_003] {
1385            fiber.set_inputs(&[cycle]);
1386            reference.set_inputs(&[cycle]);
1387            fiber.set_source_item(&polydat::iteration::source::SourceItem {
1388                ordinal: cycle,
1389                fields: Vec::new(),
1390            });
1391            reference.set_source_item(&polydat::iteration::source::SourceItem {
1392                ordinal: cycle,
1393                fields: Vec::new(),
1394            });
1395            for name in ["h", "scaled"] {
1396                assert_eq!(
1397                    fiber.cycle_wires(0).get(name),
1398                    reference.cycle_wires(0).get(name),
1399                    "'{name}' at cycle {cycle}"
1400                );
1401            }
1402        }
1403    }
1404}