Skip to main content

polydat_core/compile/jit/
kernels.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! JIT kernel types: structs and impls for all four kernel variants.
5//!
6//! `JitCore` holds the shared buffer, slot map, and module handle.
7//! The two kernel structs (`JitKernelRaw` and `JitKernelPushPull`)
8//! wrap a `JitCore` and a
9//! compiled function pointer, providing `eval` and accessor methods.
10
11use std::collections::HashMap;
12
13use cranelift_jit::JITModule;
14
15use crate::ast::PolydatNode;
16use crate::kernel::ProvMask;
17
18/// Finalized native code, shared by every kernel created from one
19/// program. The module's memory is never written after finalization,
20/// so sharing it across threads is sound; the wrapper exists so a
21/// kernel clone is a new state over the same code. The slot kits the
22/// code calls by address live beside it, for as long as it does.
23#[derive(Clone)]
24pub struct JitCode(std::sync::Arc<FinalizedModule>);
25
26/// A JIT module after finalization, which nothing writes again, the
27/// kits its code calls, and whether the code calls anything at all.
28struct FinalizedModule {
29    #[allow(dead_code)]
30    module: JITModule,
31    #[allow(dead_code)]
32    kits: Vec<super::codegen::SlotKitRef>,
33    fallible: bool,
34}
35
36/// The scratch a native kernel's state owns: one entry per entry the
37/// steps' kits declare, and the `(first slot, entry)` pairs of the
38/// scratch-backed `Ref2` outputs among them (axiom S9(a)).
39#[derive(Clone, Default)]
40pub(crate) struct ScratchPlan {
41    pub(crate) elems: Vec<crate::ast::ScratchElem>,
42    pub(crate) refs: Vec<(usize, usize)>,
43}
44
45// SAFETY: the module is finalized before it is wrapped and never
46// touched again; only its code runs, from any thread.
47unsafe impl Send for FinalizedModule {}
48unsafe impl Sync for FinalizedModule {}
49
50impl JitCode {
51    pub(crate) fn new(
52        module: JITModule,
53        kits: Vec<super::codegen::SlotKitRef>,
54        fallible: bool,
55    ) -> Self {
56        JitCode(std::sync::Arc::new(FinalizedModule {
57            module,
58            kits,
59            fallible,
60        }))
61    }
62
63    /// Whether the code can fail: it calls a helper, and a helper can
64    /// raise a node's failure through the longjmp catch. Code with no
65    /// call is arithmetic over the buffer, which cannot fail, so the
66    /// site that runs it needs no catch around it (the jump buffer, the
67    /// panic capture, and the unwind guard are the fixed cost of an
68    /// evaluation on the pure tier).
69    pub(crate) fn fallible(&self) -> bool {
70        self.0.fallible
71    }
72}
73
74/// Shared fields for all JIT kernel variants. A clone is a new state
75/// of the same program: the code and the nodes are shared, everything
76/// else is the clone's own (engines.md §3.5), and every extern
77/// pair in its buffer points into its own storage (axiom S3), never
78/// into the state it was cloned from.
79pub(super) struct JitCore {
80    /// The engine this kernel runs, as it reports it: the tier and
81    /// the provenance mode it was built with. State rather than a
82    /// property of the type, so one kernel type can serve a tier
83    /// that runs native code and one that runs none.
84    pub(super) engine: crate::compile::select::Engine,
85    pub(super) buffer: Vec<u64>,
86    pub(super) coord_count: usize,
87    pub(super) output_map: HashMap<String, usize>,
88    /// Slots the raw readers refuse: `Ref2` pairs (axiom S2). Set by
89    /// the assembler once the layout is known; empty means no such
90    /// slot.
91    pub(super) guard_slots: Vec<bool>,
92    /// Port type of each named output, for `get_value`'s decode.
93    pub(super) output_types: HashMap<String, crate::ast::PortType>,
94    /// The extern inputs, written through at every set.
95    pub(super) externs: crate::compile::externs::Externs,
96    /// The traversals the program declares (SRD 113), opened through the
97    /// `Kernel` trait.
98    pub(super) traversals: std::sync::Arc<[crate::dsl::traversal::Traversal]>,
99    pub(super) _module: JitCode,
100    /// Whether the code calls a helper, and so runs under the catch.
101    pub(super) fallible: bool,
102    pub(super) _nodes: std::sync::Arc<Vec<Box<dyn PolydatNode>>>,
103    /// The coordinates set through the `Kernel` trait, pending
104    /// evaluation.
105    pub(super) drive: crate::compile::Drive,
106    /// Where each step came from, for the failure path (A7).
107    pub(super) sites: std::sync::Arc<crate::compile::Attribution>,
108    /// The slot past the layout where native code names the step it
109    /// is in before calling a helper; `u64::MAX` before any.
110    pub(super) tracker: usize,
111    /// The scratch entries the steps' kits write into, owned by this
112    /// state (axiom S3); native code receives the base pointer.
113    pub(super) scratch: Vec<crate::ast::ScratchBuf>,
114    /// Axiom S9(a): (first slot of a Ref pair → scratch index) for
115    /// every scratch-backed Ref output.
116    pub(super) ref_scratch: Vec<(usize, usize)>,
117    /// The steps that are never current (runtime_model.md, R1.v): a
118    /// nondeterministic node or one downstream of it. Every write
119    /// clears their clean flags, so the next pull whose cone holds one
120    /// runs it again.
121    pub(super) volatile_steps: Vec<usize>,
122    /// The fusion units, and which of them each output slot's cone
123    /// holds.
124    pub(super) cones: ConePlan,
125    /// A clean flag per unit: set when the unit runs, cleared by a write
126    /// to an input in its provenance (runtime_model.md R2).
127    pub(super) unit_clean: Vec<u8>,
128    /// The units of the never-current steps, cleared at every write.
129    pub(super) volatile_units: Vec<usize>,
130    /// The program's one function, taking a list of units to run.
131    pub(super) entry: super::codegen::NativeDispatchFn,
132    /// Each output by index, as the host names it: its slot and type,
133    /// filled on the first pull by index so a pull does not look an
134    /// output up by name.
135    pub(super) outputs_at: Vec<(usize, crate::ast::PortType)>,
136}
137
138/// What a pull on this tier runs: the fusion units of its output's
139/// cone, in order, as a compiled kernel walks an output's precomputed
140/// cone order (runtime_model.md R2). The units are the planner's
141/// (`compile::fusion_units`): connected, convex groups of steps, each
142/// one block of the program's function. A pull hands the function its
143/// cone's units, and the function runs the ones that are not current
144/// and nothing else, so its cost is its cone's and not the program's.
145/// Every output's cone is found at build, into a table by slot, so a
146/// pull indexes it rather than searching or hashing.
147#[derive(Clone, Default)]
148pub(super) struct ConePlan {
149    /// Each step's input slots.
150    inputs: std::sync::Arc<[Box<[usize]>]>,
151    /// The step that writes each slot, or `usize::MAX` for a slot no
152    /// step writes (an input or an extern).
153    producer: std::sync::Arc<[usize]>,
154    /// The unit each step belongs to.
155    unit_of: std::sync::Arc<[u32]>,
156    /// Each unit's steps.
157    members: std::sync::Arc<[Box<[usize]>]>,
158    /// Every unit, in order, for a full evaluation.
159    all: std::sync::Arc<[u32]>,
160    /// Each slot's cone, by the slot it ends in: the units it holds, in
161    /// order. Every output's is found at build; another slot's, one a
162    /// raw read by slot asks for, when first asked.
163    by_slot: Vec<Option<std::sync::Arc<[u32]>>>,
164}
165
166impl ConePlan {
167    pub(super) fn new(
168        steps: &[(super::codegen::JitOp, Vec<usize>, Vec<usize>)],
169        slots: usize,
170        units: &crate::compile::fusion_units::UnitPlan,
171        outputs: impl IntoIterator<Item = usize>,
172    ) -> Self {
173        let mut producer = vec![usize::MAX; slots + 1];
174        for (i, (_, _, outs)) in steps.iter().enumerate() {
175            for &s in outs {
176                if s < producer.len() {
177                    producer[s] = i;
178                }
179            }
180        }
181        let mut plan = ConePlan {
182            inputs: steps
183                .iter()
184                .map(|(_, ins, _)| ins.clone().into_boxed_slice())
185                .collect(),
186            producer: producer.into(),
187            unit_of: units.unit_of.iter().map(|&u| u as u32).collect(),
188            members: units
189                .units
190                .iter()
191                .map(|m| m.clone().into_boxed_slice())
192                .collect(),
193            all: (0..units.units.len() as u32).collect(),
194            by_slot: vec![None; slots + 1],
195        };
196        for slot in outputs {
197            plan.of(slot);
198        }
199        plan
200    }
201
202    /// The number of units.
203    pub(super) fn unit_count(&self) -> usize {
204        self.all.len()
205    }
206
207    /// The unit a step belongs to.
208    pub(super) fn unit_of(&self, step: usize) -> usize {
209        self.unit_of[step] as usize
210    }
211
212    /// Every unit, in order.
213    pub(super) fn all(&self) -> &[u32] {
214        &self.all
215    }
216
217    /// The units of the cone `slot` depends on, in order, found once.
218    /// A unit runs whole, so the set is closed over every member's
219    /// producers, not only the producers of the steps the output reads:
220    /// a member outside the cone still runs, and its inputs must be
221    /// current when it does.
222    #[inline]
223    pub(super) fn of(&mut self, slot: usize) -> &[u32] {
224        if self.by_slot.get(slot).is_none_or(|c| c.is_none()) {
225            self.find(slot);
226        }
227        self.by_slot[slot].as_deref().unwrap_or(&[])
228    }
229
230    #[cold]
231    fn find(&mut self, slot: usize) {
232        if slot >= self.by_slot.len() {
233            self.by_slot.resize(slot + 1, None);
234        }
235        {
236            let mut unit_seen = vec![false; self.members.len()];
237            let producer_of = |s: usize| self.producer.get(s).copied().filter(|&p| p != usize::MAX);
238            let mut stack: Vec<usize> = producer_of(slot).into_iter().collect();
239            let mut units: Vec<u32> = Vec::new();
240            while let Some(step) = stack.pop() {
241                let unit = self.unit_of[step];
242                if unit_seen[unit as usize] {
243                    continue;
244                }
245                unit_seen[unit as usize] = true;
246                units.push(unit);
247                for &m in self.members[unit as usize].iter() {
248                    stack.extend(self.inputs[m].iter().filter_map(|&s| producer_of(s)));
249                }
250            }
251            // Unit numbers are in dependency order, so sorted is a valid
252            // order to run them in.
253            units.sort_unstable();
254            units.dedup();
255            self.by_slot[slot] = Some(units.into());
256        }
257    }
258}
259
260impl Clone for JitCore {
261    fn clone(&self) -> Self {
262        let mut core = JitCore {
263            engine: self.engine,
264            buffer: self.buffer.clone(),
265            coord_count: self.coord_count,
266            output_map: self.output_map.clone(),
267            guard_slots: self.guard_slots.clone(),
268            output_types: self.output_types.clone(),
269            externs: self.externs.clone(),
270            traversals: self.traversals.clone(),
271            _module: self._module.clone(),
272            fallible: self.fallible,
273            _nodes: self._nodes.clone(),
274            drive: self.drive.clone(),
275            sites: self.sites.clone(),
276            tracker: self.tracker,
277            scratch: self.scratch.clone(),
278            ref_scratch: self.ref_scratch.clone(),
279            volatile_steps: self.volatile_steps.clone(),
280            cones: self.cones.clone(),
281            unit_clean: self.unit_clean.clone(),
282            volatile_units: self.volatile_units.clone(),
283            entry: self.entry,
284            outputs_at: self.outputs_at.clone(),
285        };
286        // Every pair points into this state's own storage (axiom S3):
287        // a step's scratch entry, the value an extern stores.
288        for &(slot, idx) in &core.ref_scratch {
289            let (p, l) = core.scratch[idx].ptr_len();
290            core.buffer[slot] = p;
291            core.buffer[slot + 1] = l;
292        }
293        core.externs.seed(&mut core.buffer, None);
294        core
295    }
296}
297
298impl JitCore {
299    /// Nothing to mark here: a cell another holder published to is
300    /// handled where the pending write is applied, where the kernels
301    /// mark every step dirty, since the dependents lists do not name a
302    /// cell's readers.
303    fn dirty_input(&mut self, _slot: usize) {}
304
305    /// The program's identity: the node list, which every kernel created
306    /// from the program and every fork shares, and no other program has.
307    fn program_identity(&self) -> usize {
308        std::sync::Arc::as_ptr(&self._nodes) as *const () as usize
309    }
310
311    /// The pure tier broadcasts nothing. It is the differential oracle
312    /// behind the hybrid and Tier-1's carrier, not a surface a host
313    /// composes under (engines.md §1, §8), so no descendant binds to
314    /// one of its outputs and it makes no cell to bind to.
315    fn output_cell_for(&self, _name: &str) -> Option<crate::kernel::SharedCell> {
316        None
317    }
318
319    /// Axiom S2 typed accessor core (borrow ties to `&self`), as the
320    /// closure tier and the hybrid have it. The pure tier owns the
321    /// same scratch and the same `(slot → entry)` map, so the typed
322    /// borrows read the same way here; `guard_slots` is this core's
323    /// name for the per-slot `Ref2` mask.
324    fn ref_entry(&self, slot: usize) -> &crate::ast::ScratchBuf {
325        match self.ref_scratch.iter().find(|(s, _)| *s == slot) {
326            Some(&(_, idx)) => &self.scratch[idx],
327            None if self.guard_slots.get(slot).copied().unwrap_or(false) => panic!(
328                "slot {slot} is a Ref pair owned by the CALLER (a kernel \
329                 input) — read it on the caller side"
330            ),
331            None => panic!("slot {slot} is not a Ref2-colored slot"),
332        }
333    }
334
335    /// The value at `slot` decoded as `ty`, a pair copied out.
336    pub(super) fn slot_value(&self, slot: usize, ty: crate::ast::PortType) -> crate::ast::Value {
337        crate::compile::marshal::decode_output(&self.buffer, slot, ty)
338    }
339
340    /// One native function is the program.
341    pub(super) fn plan(&self) -> crate::EnginePlan {
342        crate::EnginePlan {
343            native_segments: 1,
344            ..Default::default()
345        }
346    }
347
348    /// The next pull or evaluation applies the pending write first.
349    pub(super) fn invalidate_all(&mut self) {
350        self.drive.stale = true;
351    }
352
353    #[allow(clippy::too_many_arguments)]
354    pub(super) fn new(
355        total_slots: usize,
356        coord_count: usize,
357        output_map: HashMap<String, usize>,
358        code: JitCode,
359        nodes: Vec<Box<dyn PolydatNode>>,
360        scratch: ScratchPlan,
361        volatile_steps: Vec<usize>,
362        entry: super::codegen::NativeDispatchFn,
363        cones: ConePlan,
364    ) -> Self {
365        let mut volatile_units: Vec<usize> =
366            volatile_steps.iter().map(|&s| cones.unit_of(s)).collect();
367        volatile_units.sort_unstable();
368        volatile_units.dedup();
369        let unit_count = cones.unit_count();
370        let mut core = Self {
371            // The pure tier, not `Native`: this core belongs to a
372            // kernel that refused every node without a native lowering
373            // rather than running its closure, and `engine()` reports
374            // what ran. The raw builder overwrites the mode.
375            engine: crate::compile::select::Engine::PureNative(
376                crate::compile::select::Provenance::PushPull,
377            ),
378            buffer: vec![0u64; total_slots + 1],
379            coord_count,
380            output_map,
381            guard_slots: Vec::new(),
382            output_types: HashMap::new(),
383            externs: crate::compile::externs::Externs::coordinates_only(coord_count),
384            traversals: Vec::new().into(),
385            fallible: code.fallible(),
386            _module: code,
387            _nodes: std::sync::Arc::new(nodes),
388            drive: crate::compile::Drive::default(),
389            sites: std::sync::Arc::default(),
390            tracker: total_slots,
391            scratch: scratch
392                .elems
393                .iter()
394                .map(|e| crate::ast::ScratchBuf::new(*e))
395                .collect(),
396            ref_scratch: scratch.refs,
397            volatile_steps,
398            cones,
399            unit_clean: vec![0u8; unit_count],
400            volatile_units,
401            entry,
402            outputs_at: Vec::new(),
403        };
404        // Every pair names its own entry from the start (axiom S3), as
405        // a clone's do. A pull runs only its cone, so a step outside
406        // every cone pulled so far has not run, and its pair must still
407        // name its entry, empty until the step writes it (S9(a)).
408        for &(slot, idx) in &core.ref_scratch {
409            let (p, l) = core.scratch[idx].ptr_len();
410            core.buffer[slot] = p;
411            core.buffer[slot + 1] = l;
412        }
413        core
414    }
415
416    /// Run the units of `slot`'s cone that are not current, or of the
417    /// whole program for `None`. The function is handed the cone's
418    /// precomputed order and the clean flags: it tests each unit's flag
419    /// itself, runs the stale ones, and marks each current as it ends.
420    #[inline]
421    pub(super) fn run_units(&mut self, slot: Option<usize>) {
422        let units: &[u32] = match slot {
423            Some(s) => self.cones.of(s),
424            None => self.cones.all(),
425        };
426        // The order lives behind an `Arc` the run does not touch, so
427        // its address holds across the call.
428        let list = units.as_ptr();
429        let len = units.len() as u64;
430        let entry = self.entry;
431        let buf_const = self.buffer.as_ptr();
432        let buf_mut = self.buffer.as_mut_ptr();
433        let sc = self.scratch.as_mut_ptr();
434        let clean = self.unit_clean.as_mut_ptr();
435        self.run(move || unsafe {
436            (entry)(buf_const, buf_mut, sc, list, len, clean);
437        });
438    }
439
440    /// Every unit is dirty: a new round, or a cell another holder
441    /// published to, whose readers no dependents list names.
442    pub(super) fn dirty_all_units(&mut self) {
443        self.unit_clean.fill(0);
444    }
445
446    /// The never-current units are dirty again: every write does this
447    /// (runtime_model.md R1.v).
448    pub(super) fn dirty_volatile_units(&mut self) {
449        for &u in &self.volatile_units {
450            self.unit_clean[u] = 0;
451        }
452    }
453
454    /// The output at `index` in the host's order: its slot and type.
455    fn output_at(&mut self, index: usize) -> (usize, crate::ast::PortType) {
456        if self.outputs_at.is_empty() {
457            self.outputs_at = self
458                .externs
459                .output_names()
460                .iter()
461                .map(|n| {
462                    let slot = self.output_map[n];
463                    let ty = self
464                        .output_types
465                        .get(n)
466                        .copied()
467                        .unwrap_or(crate::ast::PortType::U64);
468                    (slot, ty)
469                })
470                .collect();
471        }
472        *self
473            .outputs_at
474            .get(index)
475            .unwrap_or_else(|| panic!("no output at index {index}"))
476    }
477
478    /// Whether a write must run the program regardless of the cone
479    /// guard: a never-current step exists (R1.v).
480    #[inline]
481    fn has_volatile(&self) -> bool {
482        !self.volatile_steps.is_empty()
483    }
484
485    /// Axiom S9(a): every scratch-backed pair in the buffer names its
486    /// own entry, checked after a run in debug builds.
487    #[cfg(debug_assertions)]
488    fn validate_refs(&self) {
489        for &(slot, idx) in &self.ref_scratch {
490            let (p, l) = self.scratch[idx].ptr_len();
491            assert!(
492                self.buffer[slot] == p && self.buffer[slot + 1] == l,
493                "S9 ref-validator: slot pair ({slot}, {}) = ({:#x}, {}) does not match \
494                 scratch[{idx}] = ({p:#x}, {l})",
495                slot + 1,
496                self.buffer[slot],
497                self.buffer[slot + 1],
498            );
499        }
500    }
501
502    /// Install the extern inputs, written through into the buffer now.
503    pub(super) fn set_externs(&mut self, externs: crate::compile::externs::Externs) {
504        externs.seed(&mut self.buffer, None);
505        self.externs = externs;
506    }
507
508    /// Set an extern by name; returns its slot for dirty marking.
509    fn set_extern(
510        &mut self,
511        name: &str,
512        value: crate::ast::Value,
513    ) -> Result<usize, crate::kernel::WriteError> {
514        Ok(self.externs.set(name, value, &mut self.buffer)?.0)
515    }
516
517    /// [`Self::set_extern`] by input index.
518    fn set_extern_at(
519        &mut self,
520        index: usize,
521        value: crate::ast::Value,
522    ) -> Result<usize, crate::kernel::WriteError> {
523        Ok(self.externs.set_at(index, value, &mut self.buffer)?.0)
524    }
525
526    /// Bind a `shared` binding to `cell` (engine parity, step 9). The
527    /// next pull or evaluation reads it.
528    fn attach_cell(&mut self, name: &str, cell: crate::kernel::SharedCell) -> Result<(), String> {
529        self.externs.attach_cell(name, cell)?;
530        self.drive.stale = true;
531        Ok(())
532    }
533
534    /// Run one native evaluation: take what cells other holders
535    /// published, refuse an unset extern (native code cannot carry a
536    /// `None`; engines.md §3.3), run inside the longjmp catch.
537    #[inline]
538    pub(super) fn run(&mut self, native: impl FnOnce()) {
539        if self.externs.cells_dirty() {
540            self.externs.refresh_cells(&mut self.buffer);
541        }
542        if let Some((name, ty)) = self.externs.first_unset() {
543            panic!(
544                "extern '{name}' ({ty}) has no value on the pure native tier, which \
545                 cannot carry a `None`: every step is native code and there is no \
546                 closure to propagate one through. Either it was declared without a \
547                 default and never set, or a host cleared it after the build. Set it \
548                 with set_input before pulling, or run this program on `native`, which \
549                 answers a cleared extern with `None` as the interpreter does \
550                 (docs/design/engines.md §3.3)"
551            );
552        }
553        // Code that calls no helper cannot fail: it runs bare. Otherwise
554        // native code names the step it is in before each helper call;
555        // a failure before any names none. The capture guard is armed
556        // for the run, so the helper's panic is recorded quietly and
557        // re-raised enriched, as the interpreter re-raises a node's (A7).
558        if !self.fallible {
559            native();
560        } else {
561            self.buffer[self.tracker] = u64::MAX;
562            let capture = crate::kernel::engines::EvalPanicCaptureGuard::arm();
563            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
564                super::codegen::invoke_with_catch(native)
565            }));
566            drop(capture);
567            if let Err(payload) = outcome {
568                let step = self.buffer[self.tracker] as usize;
569                let sites = std::sync::Arc::clone(&self.sites);
570                sites.reraise(payload, step, &self.buffer, None);
571            }
572        }
573        #[cfg(debug_assertions)]
574        self.validate_refs();
575    }
576
577    /// The compile-constant fold of the runtime model on this tier: a
578    /// step no input reaches runs at build, once, and is current from
579    /// then on, so what is knowable at build is known at build and
580    /// fails at build.
581    ///
582    /// The other two compiled tiers keep a step list and run the
583    /// constant steps out of it. This tier has one compiled function
584    /// and no list, so the constant steps are compiled a second time
585    /// into an entry of their own, run once over this core's buffer and
586    /// scratch, and dropped with the code that held them. The steps
587    /// carry absolute slot indices, so the entry writes the same slots
588    /// the whole-program function would have.
589    ///
590    /// Externs are not consulted: a compile-constant step is one no
591    /// input reaches, extern inputs included, so a program whose
592    /// externs are still unset folds its constants anyway. That is the
593    /// difference from [`Self::run`], which refuses an unset extern
594    /// because a real evaluation reads them.
595    pub(super) fn fold_constants(
596        &mut self,
597        folded: &[(super::codegen::JitOp, Vec<usize>, Vec<usize>)],
598        origin: &[usize],
599        total_slots: usize,
600    ) -> Result<(), crate::KernelError> {
601        if folded.is_empty() {
602            return Ok(());
603        }
604        // Graph order is topological and a constant depends on
605        // constants alone, so the filtered order is a valid order.
606        let (code_fn, code) = super::codegen::compile_jit_entry(folded, Some(total_slots))
607            .map_err(|reason| crate::KernelError::ConstantFold { reason })?;
608        let buf_ptr_const = self.buffer.as_ptr();
609        let buf_ptr_mut = self.buffer.as_mut_ptr();
610        let sc = self.scratch.as_mut_ptr();
611        let native = move || unsafe {
612            (code_fn)(buf_ptr_const, buf_ptr_mut, sc);
613        };
614        if !code.fallible() {
615            native();
616        } else {
617            self.buffer[self.tracker] = u64::MAX;
618            let capture = crate::kernel::engines::EvalPanicCaptureGuard::arm();
619            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
620                super::codegen::invoke_with_catch(native)
621            }));
622            drop(capture);
623            if let Err(payload) = outcome {
624                // The entry counts its own steps, so the tracker holds
625                // an index into `folded`; the attribution is keyed by
626                // the program's step, which `origin` gives back.
627                let step = self.buffer[self.tracker] as usize;
628                let step = origin.get(step).copied().unwrap_or(step);
629                let sites = std::sync::Arc::clone(&self.sites);
630                return Err(crate::KernelError::ConstantFold {
631                    reason: sites.describe(payload, step, &self.buffer, None),
632                });
633            }
634        }
635        // `code` owns the executable memory the call ran in, so it is
636        // kept alive to here and dropped after, not before.
637        drop(code);
638        Ok(())
639    }
640}
641
642macro_rules! jit_accessors {
643    () => {
644        crate::compile::ref_readers!();
645
646        /// Returns the number of coordinate inputs this kernel accepts.
647        pub fn coord_count(&self) -> usize {
648            self.core.externs.coordinate_count()
649        }
650
651        /// Returns the buffer slot index for the named output, if present.
652        pub fn resolve_output(&self, name: &str) -> Option<usize> {
653            self.core.output_map.get(name).copied()
654        }
655
656        /// Returns the raw u64 value stored in the named output slot.
657        #[inline]
658        pub fn get(&self, name: &str) -> u64 {
659            self.get_slot(self.core.output_map[name])
660        }
661
662        /// Returns the raw u64 value stored at the given buffer slot
663        /// index. Refuses a `Ref2` slot (axiom S2): read those
664        /// through [`Self::get_value`].
665        #[inline]
666        pub fn get_slot(&self, slot: usize) -> u64 {
667            if self.core.guard_slots.get(slot).copied().unwrap_or(false) {
668                panic!(
669                    "slot {slot} is Ref2-colored; a raw u64 read would leak an interior \
670                     address. Use get_value to decode it."
671                );
672            }
673            self.core.buffer[slot]
674        }
675
676        /// The named output as a typed `Value`, decoded by its port type:
677        /// a reference pair is copied out, so the caller never holds a
678        /// reference into the buffer.
679        pub fn get_value(&self, name: &str) -> crate::ast::Value {
680            let slot = self.core.output_map[name];
681            let ty = self
682                .core
683                .output_types
684                .get(name)
685                .copied()
686                .unwrap_or(crate::ast::PortType::U64);
687            crate::compile::marshal::decode_output(&self.core.buffer, slot, ty)
688        }
689
690        /// Record the slots raw readers must refuse and each output's
691        /// port type. Called by the assembler after construction.
692        pub(crate) fn set_slot_info(
693            &mut self,
694            guard_slots: Vec<bool>,
695            output_types: HashMap<String, crate::ast::PortType>,
696        ) {
697            self.core.guard_slots = guard_slots;
698            self.core.output_types = output_types;
699        }
700
701        /// Where each step came from, for the failure path (A7).
702        pub(crate) fn set_attribution(
703            &mut self,
704            sites: std::sync::Arc<crate::compile::Attribution>,
705        ) {
706            self.core.sites = sites;
707        }
708
709        /// Run this program's compile-constant steps once, at build; see
710        /// [`JitCore::fold_constants`]. Called by the assembler after
711        /// the attribution is in place, so a constant that fails names
712        /// its node.
713        pub(crate) fn fold_constants(
714            &mut self,
715            folded: &[(super::codegen::JitOp, Vec<usize>, Vec<usize>)],
716            origin: &[usize],
717            total_slots: usize,
718        ) -> Result<(), crate::KernelError> {
719            self.core.fold_constants(folded, origin, total_slots)
720        }
721
722        /// Set an extern by name, as `PolydatState::set_input` does on
723        /// the interpreter. The value must be of the declared port
724        /// type. The value is written through into the buffer at once,
725        /// whatever its color, and every step downstream of the extern
726        /// reruns at the next evaluation.
727        pub fn set_input(
728            &mut self,
729            name: &str,
730            value: crate::ast::Value,
731        ) -> Result<(), crate::kernel::WriteError> {
732            let slot = self.core.set_extern(name, value)?;
733            self.mark_input_changed(slot);
734            Ok(())
735        }
736
737        /// [`Self::set_input`] by input index.
738        pub fn set_input_at(
739            &mut self,
740            index: usize,
741            value: crate::ast::Value,
742        ) -> Result<(), crate::kernel::WriteError> {
743            let slot = self.core.set_extern_at(index, value)?;
744            self.mark_input_changed(slot);
745            Ok(())
746        }
747
748        /// The kernel's externs by name and declared type.
749        pub fn externs(&self) -> Vec<(&str, crate::ast::PortType)> {
750            self.core.externs.names()
751        }
752
753        /// Every step downstream of a coordinate reruns at the next
754        /// evaluation: the state a kernel created from a shared program
755        /// starts in.
756        fn mark_all_dirty(&mut self) {
757            for i in 0..self.core.coord_count {
758                self.mark_input_changed(i);
759            }
760        }
761
762        /// The named output through the `Kernel` trait: the pending
763        /// writes are applied and the output's cone runs, and nothing
764        /// else (engines.md §3.1).
765        fn pull_value(&mut self, name: &str) -> crate::ast::Value {
766            let slot = self.core.output_map[name];
767            let ty = self
768                .core
769                .output_types
770                .get(name)
771                .copied()
772                .unwrap_or(crate::ast::PortType::U64);
773            self.pull_slot(slot, ty)
774        }
775
776        /// [`Self::pull_value`] by output index, through the index's
777        /// slot and type rather than its name.
778        fn pull_value_at(&mut self, index: usize) -> crate::ast::Value {
779            let (slot, ty) = self.core.output_at(index);
780            self.pull_slot(slot, ty)
781        }
782
783        /// `eval` through the `Kernel` trait: the pending coordinates.
784        fn eval_pending(&mut self) {
785            let coords = std::mem::take(&mut self.core.drive.coords);
786            self.eval(&coords);
787            self.core.drive.coords = coords;
788        }
789
790        /// The cursors the program declares, with the partitions the
791        /// compiler resolved where its `over` clause and extent were
792        /// constant, as `PolydatProgram::cursor_schemas` reports them.
793        pub fn cursor_schemas(&self) -> &[crate::iteration::source::SourceSchema] {
794            self.core.externs.cursor_schemas()
795        }
796
797        /// Narrow a cursor to one partition, as `narrow_cursor` does on
798        /// the interpreter: its `Ext` slot and six scalar projections
799        /// are set as externs.
800        pub fn set_cursor(
801            &mut self,
802            name: &str,
803            partition: &crate::iteration::cursor_partition::Partition,
804        ) -> Result<(), crate::kernel::WriteError> {
805            for (slot, value) in self.core.externs.cursor_writes(name, partition)? {
806                self.set_input(&slot, value)?;
807            }
808            Ok(())
809        }
810    };
811}
812
813// ── JitKernelRaw ───────────────────────────────────────────
814
815/// Raw JIT kernel: no provenance. Every write begins a round in which
816/// every unit is dirty; `eval` runs them all, and a pull runs its
817/// output's cone, each unit at most once in the round.
818#[derive(Clone)]
819#[doc(hidden)]
820pub struct JitKernelRaw {
821    pub(super) core: JitCore,
822}
823
824impl JitKernelRaw {
825    /// A pull through the `Kernel` trait: a pending write begins a
826    /// round, then the output's cone runs.
827    fn pull_slot(&mut self, slot: usize, ty: crate::ast::PortType) -> crate::ast::Value {
828        if self.core.drive.stale || self.core.externs.cells_dirty() {
829            let coords = std::mem::take(&mut self.core.drive.coords);
830            self.write_coords(&coords);
831            self.core.drive.coords = coords;
832            self.core.drive.stale = false;
833            self.core.dirty_all_units();
834        }
835        self.core.run_units(Some(slot));
836        self.core.slot_value(slot, ty)
837    }
838
839    /// The coordinates, written into the buffer.
840    #[inline]
841    fn write_coords(&mut self, coords: &[u64]) {
842        // Written one by one, as the other kernels write them: a slice
843        // copy of a runtime length is a call to memcpy, which costs
844        // more than the three stores it replaces.
845        for (i, &c) in coords
846            .iter()
847            .enumerate()
848            .take(self.core.externs.coordinate_slots())
849        {
850            if self.core.buffer[i] != c {
851                self.core.buffer[i] = c;
852            }
853        }
854    }
855    /// Evaluate the kernel with the given coordinate values.
856    ///
857    /// Predicate violations (`is_positive`, `in_range`,
858    /// `is_one_of`) from JIT-lowered code surface as normal
859    /// Rust panics carrying the violation message. The
860    /// longjmp wrapper in `super::codegen::invoke_with_catch`
861    /// handles the transition back to Rust land when the code
862    /// calls a helper; code that calls none cannot fail and
863    /// runs bare.
864    #[inline]
865    pub fn eval(&mut self, coords: &[u64]) {
866        self.write_coords(coords);
867        self.core.dirty_all_units();
868        self.core.run_units(None);
869    }
870
871    /// Evaluate and return the value at the given buffer slot index.
872    #[inline]
873    pub fn eval_for_slot(&mut self, coords: &[u64], slot: usize) -> u64 {
874        self.eval(coords);
875        self.core.buffer[slot]
876    }
877
878    /// A write begins a round: every unit is dirty again.
879    fn mark_input_changed(&mut self, _slot: usize) {
880        self.core.dirty_all_units();
881    }
882
883    jit_accessors!();
884}
885
886// ── JitKernelPushPull ──────────────────────────────────────
887
888/// Full optimization: push-side dirty tracking + pull-side cone guard.
889#[derive(Clone)]
890#[doc(hidden)]
891pub struct JitKernelPushPull {
892    pub(super) core: JitCore,
893    /// Per input slot, the units that read it, directly or not.
894    pub(super) input_dependents: Vec<Vec<usize>>,
895    pub(super) slot_provenance: Vec<ProvMask>,
896    pub(super) changed_mask: ProvMask,
897    /// Set by `set_input`: an extern changed, so the next evaluation
898    /// runs whatever the cone guard says.
899    pub(super) force_run: bool,
900}
901
902impl JitKernelPushPull {
903    #[inline]
904    fn set_inputs(&mut self, coords: &[u64]) {
905        self.changed_mask.clear();
906        for (i, &c) in coords
907            .iter()
908            .enumerate()
909            .take(self.core.externs.coordinate_slots())
910        {
911            if self.core.buffer[i] != c {
912                self.core.buffer[i] = c;
913                self.changed_mask.set(i);
914                self.dirty_dependents(i);
915            }
916        }
917        // A write makes every never-current unit run again (R1.v),
918        // whatever the cone guard would say of the pulled output.
919        if self.core.has_volatile() {
920            self.core.dirty_volatile_units();
921            self.force_run = true;
922        }
923    }
924
925    /// The units downstream of an input slot are dirty.
926    #[inline]
927    fn dirty_dependents(&mut self, slot: usize) {
928        if let Some(units) = self.input_dependents.get(slot) {
929            for &u in units {
930                self.core.unit_clean[u] = 0;
931            }
932        }
933    }
934
935    /// Every unit downstream of the slot reruns, and the next
936    /// evaluation runs whatever the cone guard says.
937    fn mark_input_changed(&mut self, slot: usize) {
938        self.dirty_dependents(slot);
939        self.core.dirty_volatile_units();
940        self.force_run = true;
941    }
942
943    /// A pull through the `Kernel` trait: the pending coordinates dirty
944    /// their dependents, then the output's cone runs its dirty units.
945    fn pull_slot(&mut self, slot: usize, ty: crate::ast::PortType) -> crate::ast::Value {
946        if self.core.drive.stale {
947            let coords = std::mem::take(&mut self.core.drive.coords);
948            self.set_inputs(&coords);
949            self.core.drive.coords = coords;
950            self.core.drive.stale = false;
951        }
952        // A cell another holder published to is a changed input whose
953        // readers the dependents lists do not name: every unit reruns.
954        if self.core.externs.cells_dirty() {
955            self.core.dirty_all_units();
956        }
957        self.core.run_units(Some(slot));
958        self.core.slot_value(slot, ty)
959    }
960
961    /// Evaluate the kernel with the given coordinate values.
962    #[inline]
963    pub fn eval(&mut self, coords: &[u64]) {
964        self.set_inputs(coords);
965        self.force_run = false;
966        self.core.run_units(None);
967    }
968
969    /// Evaluate and return the value at the given buffer slot index,
970    /// applying both push and pull optimizations.
971    #[inline]
972    pub fn eval_for_slot(&mut self, coords: &[u64], slot: usize) -> u64 {
973        self.set_inputs(coords);
974        if !self.force_run
975            && slot < self.slot_provenance.len()
976            && !self.slot_provenance[slot].intersects(&self.changed_mask)
977        {
978            return self.core.buffer[slot];
979        }
980        self.force_run = false;
981        self.core.run_units(Some(slot));
982        self.core.buffer[slot]
983    }
984
985    jit_accessors!();
986}
987
988// ── The engine-independent surface (engines.md §3.5) ──────
989
990crate::compile::impl_kernel_trait!(JitKernelRaw);
991crate::compile::impl_kernel_trait!(JitKernelPushPull);
992crate::compile::impl_slot_kernel!(JitKernelRaw);
993crate::compile::impl_slot_kernel!(JitKernelPushPull);