Skip to main content

polydat_core/kernel/
api_impl.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Trait implementations on the interpreter kernel: the
5//! engine-independent [`Kernel`](crate::kernel::Kernel) surface every
6//! engine shares, and the three interpreter-only traits ([`Metadata`],
7//! [`Dataflow`], [`Construction`]).
8
9use crate::ast::{PortType, Value};
10use crate::kernel::{Construction, Dataflow, Metadata, PolydatKernel};
11
12impl Metadata for PolydatKernel {
13    #[inline]
14    fn find_input(&self, name: &str) -> Option<usize> {
15        self.program().find_input(name)
16    }
17
18    #[inline]
19    fn input_names(&self) -> Vec<String> {
20        self.program().input_names()
21    }
22
23    #[inline]
24    fn output_names(&self) -> Vec<String> {
25        self.program()
26            .output_names()
27            .iter()
28            .map(|s| s.to_string())
29            .collect()
30    }
31
32    #[inline]
33    fn coord_count(&self) -> usize {
34        self.program().coord_count()
35    }
36
37    #[inline]
38    fn input_port_type(&self, name: &str) -> Option<PortType> {
39        self.program().input_port_type(name)
40    }
41
42    #[inline]
43    fn input_port_type_by_idx(&self, idx: usize) -> Option<PortType> {
44        self.program().input_port_type_by_idx(idx)
45    }
46
47    #[inline]
48    fn output_port_type(&self, name: &str) -> Option<PortType> {
49        self.program().output_port_type(name)
50    }
51}
52
53impl Dataflow for PolydatKernel {
54    #[inline]
55    fn get_wire_idx(&self, idx: usize) -> Value {
56        self.state_ref().get_input(idx)
57    }
58}
59
60impl Construction for PolydatKernel {
61    type Error = crate::kernel::subcontext::ContractViolation;
62
63    fn root(matter: crate::kernel::subcontext::PolydatMatter<'_>) -> Result<Self, Self::Error> {
64        use crate::kernel::subcontext::PolydatMatterInner;
65        match matter.inner {
66            PolydatMatterInner::Source(s) => {
67                let options = crate::dsl::compile::CompileOptions {
68                    source_dir: s.options.workload_dir.clone(),
69                    lib_paths: s.options.polydat_lib_paths,
70                    required_outputs: s.options.required_outputs.clone(),
71                    strict: s.options.strict,
72                    context: s
73                        .options
74                        .context_label
75                        .clone()
76                        .unwrap_or_else(|| s.label.clone()),
77                    cursor_limit: s.options.cursor_limit,
78                    input_variance: s.options.input_variance,
79                    inferred_externs: Vec::new(),
80                    ledger: None,
81                    resources: None,
82                    engine: crate::Engine::default(),
83                };
84                crate::dsl::compile::compile_polydat_interpreter_with_options(
85                    &s.body, &options, None,
86                )
87                .map_err(|e| crate::kernel::subcontext::ContractViolation::Compile(e.to_string()))
88            }
89            PolydatMatterInner::Statements(s) => {
90                // Pre-parsed AST — go through the compile-from-AST
91                // path. The `PolydatFile` AST root takes the statements
92                // verbatim; the same options surface as the source
93                // path.
94                let file = crate::dsl::ast::PolydatFile {
95                    statements: s.statements,
96                };
97                let options = crate::dsl::compile::CompileOptions {
98                    source_dir: s.options.workload_dir.clone(),
99                    lib_paths: s.options.polydat_lib_paths,
100                    required_outputs: s.options.required_outputs.clone(),
101                    strict: s.options.strict,
102                    context: s
103                        .options
104                        .context_label
105                        .clone()
106                        .unwrap_or_else(|| s.label.clone()),
107                    cursor_limit: None,
108                    input_variance: s.options.input_variance,
109                    inferred_externs: Vec::new(),
110                    ledger: None,
111                    resources: None,
112                    engine: crate::Engine::default(),
113                };
114                crate::dsl::compile::compile_ast_interpreter_with_options(&file, "", &options, None)
115                    .map_err(|e| {
116                        crate::kernel::subcontext::ContractViolation::Compile(e.to_string())
117                    })
118            }
119            PolydatMatterInner::Program(p) => {
120                let engine = p.program.engine();
121                let program = p.program.as_interpreter().ok_or_else(|| {
122                    crate::kernel::subcontext::ContractViolation::Compile(format!(
123                        "a root interpreter kernel needs an interpreter program; this one is \
124                         on the {engine} engine, whose `create_kernel` makes its root"
125                    ))
126                })?;
127                let mut k = PolydatKernel::from_program(program);
128                for (var, value) in p.iter_bindings {
129                    if let Some(idx) = k.program().find_input(var) {
130                        k.state().set_input(idx, value.clone());
131                    }
132                }
133                Ok(k)
134            }
135        }
136    }
137
138    fn subscope(
139        &self,
140        matter: crate::kernel::subcontext::PolydatMatter<'_>,
141    ) -> Result<Box<dyn crate::kernel::Kernel>, Self::Error> {
142        matter.build_under(self)
143    }
144}
145
146// ── The interpreter kernel on the engine-independent surface ────────
147
148impl crate::kernel::Kernel for PolydatKernel {
149    fn engine(&self) -> crate::compile::select::Engine {
150        crate::compile::select::Engine::Interpreter(self.program().cone_mode())
151    }
152    fn set_inputs(&mut self, coords: &[u64]) {
153        PolydatKernel::set_inputs(self, coords);
154    }
155    fn set_input(&mut self, name: &str, value: Value) -> Result<(), crate::kernel::WriteError> {
156        PolydatKernel::set_input(self, name, value)
157    }
158    fn set_cursor(
159        &mut self,
160        name: &str,
161        partition: &crate::iteration::cursor_partition::Partition,
162    ) -> Result<(), crate::kernel::WriteError> {
163        PolydatKernel::set_cursor(self, name, partition)
164    }
165    /// Every output is pulled, so what a side channel observes is what
166    /// it observes on a compiled kernel's run.
167    fn eval(&mut self) {
168        PolydatKernel::eval_read(self);
169    }
170    fn pull(&mut self, name: &str) -> Value {
171        PolydatKernel::pull_ref(self, name).clone()
172    }
173    fn input_names(&self) -> Vec<String> {
174        Metadata::input_names(self)
175    }
176    fn output_names(&self) -> Vec<String> {
177        Metadata::output_names(self)
178    }
179    fn output_type(&self, name: &str) -> Option<PortType> {
180        Metadata::output_port_type(self, name)
181    }
182    fn dataset_sources(&self, name: &str) -> Option<crate::kernel::DatasetSources> {
183        self.program().dataset_sources(name)
184    }
185    fn externs(&self) -> Vec<(String, PortType)> {
186        let program = self.program();
187        Metadata::input_names(self)
188            .into_iter()
189            .enumerate()
190            .filter(|(i, _)| program.input_kind(*i) != Some(crate::kernel::InputKind::Coordinate))
191            .filter_map(|(i, name)| Metadata::input_port_type_by_idx(self, i).map(|t| (name, t)))
192            .collect()
193    }
194    fn cursor_schemas(&self) -> &[crate::iteration::source::SourceSchema] {
195        self.program().cursor_schemas()
196    }
197    fn input_value(&self, name: &str) -> Option<Value> {
198        let idx = self.program().find_input(name)?;
199        Some(self.state_ref().get_input(idx))
200    }
201    fn input_index(&self, name: &str) -> Option<usize> {
202        self.program().find_input(name)
203    }
204    fn set_input_at(
205        &mut self,
206        index: usize,
207        value: Value,
208    ) -> Result<(), crate::kernel::WriteError> {
209        PolydatKernel::set_input_at(self, index, value)
210    }
211    fn output_index(&self, name: &str) -> Option<usize> {
212        self.program().output_index(name)
213    }
214    fn const_inits(&self) -> &[crate::kernel::ConstInit] {
215        self.program().const_inits()
216    }
217    fn init_input_at(
218        &mut self,
219        index: usize,
220        value: Value,
221    ) -> Result<(), crate::kernel::WriteError> {
222        PolydatKernel::init_input_at(self, index, value)
223    }
224    fn pull_at(&mut self, index: usize) -> Value {
225        PolydatKernel::pull_ref_at(self, index).clone()
226    }
227    fn traversals(&self) -> &[crate::dsl::traversal::Traversal] {
228        self.program().traversals()
229    }
230    fn plan(&self) -> crate::EnginePlan {
231        self.program().engine_plan()
232    }
233    fn traverse(&mut self, index: usize) -> Result<crate::kernel::TraversalStream, String> {
234        PolydatKernel::traverse(self, index)
235    }
236    fn invalidate_all(&mut self) {
237        self.state().invalidate_all();
238    }
239    fn shared_cells(&self) -> Vec<crate::kernel::SharedCellEntry> {
240        self.shared_cells_in_scope()
241    }
242    fn output_cell(&self, name: &str) -> Option<crate::kernel::SharedCell> {
243        // Seeded for every output at construction, so this is a read.
244        self.state_ref().core.output_cell(self.program(), name)
245    }
246    fn output_modifier(&self, name: &str) -> crate::dsl::ast::BindingModifier {
247        self.program().output_modifier(name)
248    }
249    fn cells_in_scope(&self) -> Vec<crate::kernel::SharedCellEntry> {
250        // The interpreter's own enumeration already walks its slots and
251        // its transit list together.
252        self.shared_cells_in_scope()
253    }
254    fn set_transit_cells(&mut self, cells: Vec<crate::kernel::SharedCellEntry>) {
255        self.replace_transit_cells(cells);
256    }
257    fn scope_coordinates(&self) -> &[crate::kernel::ScopeCoord] {
258        PolydatKernel::scope_coordinates(self)
259    }
260    fn extend_scope_coordinates(&mut self, outer: &[crate::kernel::ScopeCoord]) {
261        PolydatKernel::extend_scope_coordinates(self, outer);
262    }
263    fn input_port_type(&self, name: &str) -> Option<crate::ast::PortType> {
264        self.program().input_port_type(name)
265    }
266    fn bind_input_cell(&mut self, name: &str, cell: crate::kernel::SharedCell) -> bool {
267        // The state's own attach does not require the slot to be
268        // `shared`: the filter is on the host-facing
269        // `attach_shared_cell` above, and the binder binds through
270        // here.
271        let Some(idx) = self.program().find_input(name) else {
272            return false;
273        };
274        self.state().attach_shared_cell(idx, cell);
275        true
276    }
277    fn attach_shared_cell(
278        &mut self,
279        name: &str,
280        cell: crate::kernel::SharedCell,
281    ) -> Result<(), String> {
282        let program = self.program().clone();
283        let shared = program.shared_outputs();
284        let idx = program.find_input(name).filter(|_| shared.contains(&name));
285        let Some(idx) = idx else {
286            return Err(format!(
287                "no `shared` binding named '{name}'; this kernel's shared bindings are {shared:?}"
288            ));
289        };
290        self.state().attach_shared_cell(idx, cell);
291        Ok(())
292    }
293    fn into_program(self: Box<Self>) -> std::sync::Arc<dyn crate::kernel::KernelProgram> {
294        PolydatKernel::into_program(*self)
295    }
296    fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
297        self.program().ledger()
298    }
299    fn resources(&self) -> &crate::resource::ResourceScope {
300        self.program().resources()
301    }
302    fn canonical_hash(&self) -> [u8; 32] {
303        self.program().canonical_hash()
304    }
305    fn coord_count(&self) -> usize {
306        self.program().coord_count()
307    }
308    fn input_value_at(&self, index: usize) -> Option<Value> {
309        (index < self.state_ref().core.inputs.len())
310            .then(|| self.state_ref().read_input_value(index))
311    }
312    fn input_default_at(&self, index: usize) -> Option<Value> {
313        self.program().input_default_by_idx(index).cloned()
314    }
315    fn input_is_cell_bound(&self, index: usize) -> bool {
316        self.state_ref().shared_cell(index).is_some()
317    }
318    fn reset_inputs(&mut self) {
319        let from = self.program().coord_count();
320        self.state().reset_inputs_from(from);
321    }
322    fn fork(&self) -> Box<dyn crate::kernel::Kernel> {
323        Box::new(self.fork_kernel())
324    }
325    fn publish_broadcasts(&mut self) {
326        self.advance_broadcasts();
327    }
328    fn commit_write_throughs(&mut self) -> Result<(), String> {
329        PolydatKernel::commit_write_throughs(self)
330    }
331    fn program_id(&self) -> crate::kernel::ProgramId {
332        crate::kernel::ProgramId(std::sync::Arc::as_ptr(self.program()) as *const () as usize)
333    }
334    fn input_type_origin(&self, name: &str) -> Option<crate::kernel::TypeOrigin> {
335        self.program().input_type_origin(name)
336    }
337    fn as_interpreter(&self) -> Option<&PolydatKernel> {
338        Some(self)
339    }
340    fn as_interpreter_mut(&mut self) -> Option<&mut PolydatKernel> {
341        Some(self)
342    }
343}
344
345impl crate::kernel::KernelInternals for PolydatKernel {
346    fn set_inherited_outputs(&mut self, names: Vec<String>) {
347        PolydatKernel::mark_inherited_outputs(self, names);
348    }
349    fn set_write_throughs(&mut self, pairs: Vec<(String, String)>) {
350        PolydatKernel::set_write_throughs(
351            self,
352            pairs
353                .into_iter()
354                .map(
355                    |(export_name, source_output)| crate::kernel::KernelWriteThrough {
356                        export_name,
357                        source_output,
358                    },
359                )
360                .collect(),
361        );
362    }
363    fn set_traversals(
364        &mut self,
365        traversals: Vec<crate::dsl::traversal::Traversal>,
366        producers: Vec<crate::dsl::traversal::Producer>,
367    ) {
368        PolydatKernel::set_traversals(self, traversals, producers);
369    }
370    /// Only for an output fixed for the kernel's life: a computed output's
371    /// buffer holds its last pulled value, which is not the scope's.
372    fn folded_value(&self, name: &str) -> Option<Value> {
373        if !self.program().is_fixed_output(name) {
374            return None;
375        }
376        self.get_constant(name).cloned()
377    }
378    fn set_cursor_extent(&mut self, index: usize, extent: u64) {
379        let mut schemas = self.program().cursor_schemas().to_vec();
380        if let Some(schema) = schemas.get_mut(index) {
381            schema.extent = Some(extent);
382            self.set_cursor_schemas(schemas);
383        }
384    }
385}
386
387impl crate::kernel::KernelProgram for crate::kernel::PolydatProgram {
388    fn engine(&self) -> crate::compile::select::Engine {
389        crate::compile::select::Engine::Interpreter(self.cone_mode())
390    }
391    fn as_interpreter(self: std::sync::Arc<Self>) -> Option<std::sync::Arc<Self>> {
392        Some(self)
393    }
394    fn create_uninitialized(self: std::sync::Arc<Self>) -> Box<dyn crate::kernel::Kernel> {
395        Box::new(PolydatKernel::from_program(self))
396    }
397    fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
398        crate::kernel::PolydatProgram::ledger(self)
399    }
400    fn resources(&self) -> &crate::resource::ResourceScope {
401        crate::kernel::PolydatProgram::resources(self)
402    }
403    fn canonical_hash(&self) -> [u8; 32] {
404        crate::kernel::PolydatProgram::canonical_hash(self)
405    }
406    fn program_id(&self) -> crate::kernel::ProgramId {
407        crate::kernel::ProgramId(self as *const Self as *const () as usize)
408    }
409}
410
411#[cfg(test)]
412mod tests {
413    use super::*;
414    use crate::dsl::compile::compile_polydat_interpreter;
415
416    /// Indexed wire access reads what the coordinates were set to.
417    #[test]
418    fn dataflow_indexed_get() {
419        let mut k = compile_polydat_interpreter("input cycle: u64\nconst x := 7\n").unwrap();
420        // cycle is index 0
421        k.set_inputs(&[42]);
422        assert_eq!(k.get_wire(0_usize), Some(Value::U64(42)));
423    }
424
425    /// Named wire access resolves through metadata.
426    #[test]
427    fn dataflow_named_set_get() {
428        let mut k = compile_polydat_interpreter("input cycle: u64\nextern n: u64\n").unwrap();
429        k.set_input("n", Value::U64(5)).expect("typed write");
430        match k.get_wire("n") {
431            Some(Value::U64(5)) => {}
432            other => panic!("expected U64(5), got {other:?}"),
433        }
434    }
435
436    /// String key works alongside &str.
437    #[test]
438    fn dataflow_string_key() {
439        let mut k = compile_polydat_interpreter("input cycle: u64\nextern n: u64\n").unwrap();
440        let name = String::from("n");
441        k.set_input(&name, Value::U64(99)).expect("typed write");
442        assert_eq!(k.get_wire(&name), Some(Value::U64(99)));
443        assert_eq!(k.get_wire(name.clone()), Some(Value::U64(99)));
444    }
445
446    /// Unknown name returns Err(UnknownWire) / None — no panic.
447    #[test]
448    fn dataflow_unknown_name_safe() {
449        let mut k = compile_polydat_interpreter("input cycle: u64\n").unwrap();
450        let err = k.set_input("nonexistent", Value::U64(1)).unwrap_err();
451        assert!(matches!(
452            err,
453            crate::kernel::api::WriteError::UnknownWire { .. }
454        ));
455        assert!(k.get_wire("nonexistent").is_none());
456    }
457
458    /// S4 type-check: writing the wrong Value variant to a typed
459    /// slot returns Err(TypeMismatch).
460    #[test]
461    fn dataflow_type_mismatch_rejected() {
462        let mut k = compile_polydat_interpreter("input cycle: u64\nextern n: u64\n").unwrap();
463        let err = k
464            .set_input(
465                "n",
466                Value::VecF32(crate::ast::SliceArc::from_vec(vec![1.0_f32, 2.0])),
467            )
468            .unwrap_err();
469        match err {
470            crate::kernel::api::WriteError::TypeMismatch {
471                slot,
472                expected,
473                got,
474            } => {
475                assert_eq!(slot, "n");
476                assert_eq!(expected, PortType::U64);
477                assert_eq!(got, PortType::VecF32);
478            }
479            other => panic!("expected TypeMismatch, got {other:?}"),
480        }
481    }
482
483    /// The `WriteError::TypeMismatch` Display impl includes a
484    /// vec → scalar hint naming the reduction the program needs
485    /// when the rejected `got` is a Vec type and the `expected` is
486    /// not a collection-compatible type.
487    #[test]
488    fn vec_to_scalar_diagnostic_mentions_explicit_helpers() {
489        let err = crate::kernel::api::WriteError::TypeMismatch {
490            slot: "score".into(),
491            expected: PortType::F64,
492            got: PortType::VecF32,
493        };
494        let msg = err.to_string();
495        assert!(
496            msg.contains("reduction node"),
497            "missing reduction hint: {msg}"
498        );
499        assert!(msg.contains("vec_dot"), "missing vec_dot hint: {msg}");
500    }
501
502    /// A write is never converted: a `u64` into an `f64` extern is
503    /// refused, and the host converts it first with `convert::to_port`.
504    #[test]
505    fn typed_write_converts_through_to_port() {
506        let mut k = compile_polydat_interpreter("input cycle: u64\nextern x: f64\n").unwrap();
507        assert!(matches!(
508            k.set_input("x", Value::U64(42)),
509            Err(crate::kernel::api::WriteError::TypeMismatch { .. })
510        ));
511        let converted =
512            crate::convert::to_port(Value::U64(42), PortType::F64).expect("u64 converts to f64");
513        k.set_input("x", converted).expect("converted value");
514        match k.get_wire("x") {
515            Some(Value::F64(42.0)) => {}
516            other => panic!("expected converted F64(42.0), got {other:?}"),
517        }
518    }
519
520    /// S4 None pass-through: Value::None is the absent sentinel
521    /// and always permitted at the boundary regardless of slot
522    /// type (per none_semantics.md).
523    #[test]
524    fn dataflow_none_passes_through_any_slot() {
525        let mut k = compile_polydat_interpreter("input cycle: u64\nextern n: u64\n").unwrap();
526        k.set_input("n", Value::None)
527            .expect("None always permitted");
528    }
529
530    /// Metadata trait surfaces names + types.
531    #[test]
532    fn metadata_listings() {
533        let k = compile_polydat_interpreter(
534            "input (cycle: u64, thread: u64)\nextern n: u64\nconst x := 7\n",
535        )
536        .unwrap();
537        let inputs: Vec<String> = k.input_names();
538        assert!(inputs.iter().any(|s| s == "cycle"));
539        assert!(inputs.iter().any(|s| s == "n"));
540        assert_eq!(k.coord_count(), 2); // cycle + thread
541        assert!(k.find_input("n").is_some());
542        assert_eq!(k.input_port_type("n"), Some(PortType::U64));
543    }
544
545    /// Construction trait — both paths take the same polydat
546    /// matter type. Verify symmetry: root from source, then
547    /// subscope from source against the root.
548    #[test]
549    fn construction_symmetric_paths() {
550        let root_opts = crate::kernel::subcontext::CompileOptions {
551            workload_dir: None,
552            polydat_lib_paths: Vec::new(),
553            strict: false,
554            required_outputs: Vec::new(),
555            context_label: Some("root".to_string()),
556            cursor_limit: None,
557            ..Default::default()
558        };
559        let root_matter = crate::kernel::subcontext::PolydatMatter::builder()
560            .label("root")
561            .source("input cycle: u64\nshared flag := 0\n")
562            .options(root_opts)
563            .build()
564            .expect("matter build");
565        let root =
566            <PolydatKernel as Construction>::root(root_matter).expect("root from source matter");
567
568        let sub_opts = crate::kernel::subcontext::CompileOptions {
569            workload_dir: None,
570            polydat_lib_paths: Vec::new(),
571            strict: false,
572            required_outputs: Vec::new(),
573            context_label: Some("sub".to_string()),
574            cursor_limit: None,
575            ..Default::default()
576        };
577        let sub_matter = crate::kernel::subcontext::PolydatMatter::builder()
578            .label("sub")
579            .source("input cycle: u64\n")
580            .options(sub_opts)
581            .build()
582            .expect("matter build");
583        let _sub = root
584            .subscope(sub_matter)
585            .expect("subscope from source matter");
586    }
587
588    /// Root construction also accepts pre-compiled program
589    /// matter (re-instance with fresh state). Verifies via
590    /// the input slot — `n` is an extern input.
591    #[test]
592    fn construction_root_from_program() {
593        let template = compile_polydat_interpreter("input cycle: u64\nextern n: u64\n").unwrap();
594        let program = template.program().clone();
595        let matter = crate::kernel::subcontext::PolydatMatter::builder()
596            .program(program)
597            .build()
598            .expect("matter build");
599        let mut root =
600            <PolydatKernel as Construction>::root(matter).expect("root from program matter");
601        root.set_input("n", Value::U64(13)).expect("set_input");
602        assert_eq!(root.get_wire("n"), Some(Value::U64(13)));
603    }
604
605    /// Builder rejects ambiguous matter (multiple input forms).
606    #[test]
607    fn builder_rejects_multiple_forms() {
608        let template = compile_polydat_interpreter("input cycle: u64\n").unwrap();
609        match crate::kernel::subcontext::PolydatMatter::builder()
610            .source("input cycle: u64\n")
611            .program(template.program().clone())
612            .build()
613        {
614            Err(msg) => assert!(
615                msg.contains("multiple"),
616                "expected multiple-forms error, got: {msg}"
617            ),
618            Ok(_) => panic!("multiple forms must error"),
619        }
620    }
621
622    /// Builder rejects empty matter.
623    #[test]
624    fn builder_rejects_empty() {
625        match crate::kernel::subcontext::PolydatMatter::builder().build() {
626            Err(msg) => assert!(
627                msg.contains("no input form"),
628                "expected no-form error, got: {msg}"
629            ),
630            Ok(_) => panic!("empty matter must error"),
631        }
632    }
633}