Skip to main content

polydat_nodes/
arithmetic.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Arithmetic function nodes.
5//!
6//! Core integer operations for the Polydat DAG. These are the building blocks
7//! that most workloads compose: hash → mod → add for bounded IDs,
8//! mixed_radix for coordinate decomposition, interleave for combining
9//! independent dimensions.
10
11use polydat::ast::CompiledU64Op;
12
13/// Add a constant to a u64 value (wrapping).
14///
15/// Signature: `add(input: u64, addend: u64) -> (u64)`
16///
17/// Use for offsetting a bounded range: `mod(h, 100)` gives [0,100),
18/// `add(mod(h, 100), 500)` gives [500,600). Also common with timestamps:
19/// `add(base_epoch, offset)`.
20///
21/// JIT level: P3 (single `iadd` instruction).
22// SRD-80 PR B.7 — Phase 3 const-arg arithmetic family
23// migrated to `#[polydat_node]`. The macro derives `Add`,
24// `Mul`, `Div`, `Mod` from snake_case → PascalCase; the
25// `r#mod` raw identifier is stripped to "mod" for the DSL
26// name and PascalCased to `Mod` for the struct.
27//
28// `classify_node` matches by DSL name ("add", "mul", "div",
29// "mod") and reads `jit_constants()` — the macro auto-emits
30// both, so Phase 3 dispatch is preserved verbatim.
31
32#[polydat::polydat_node(category = Arithmetic)]
33fn add(input: u64, addend: Const<u64>) -> u64 {
34    input.wrapping_add(*addend)
35}
36
37#[polydat::polydat_node(category = Arithmetic)]
38fn mul(input: u64, factor: Const<u64>) -> u64 {
39    input.wrapping_mul(*factor)
40}
41
42#[polydat::polydat_node(category = Arithmetic)]
43fn div(input: u64, divisor: Const<u64>) -> u64 {
44    // Greenfield posture: zero-divisor panics at cycle time
45    // (matching the body's `/`). The original `new()` assert
46    // is retired with the migration; if early-fail is needed
47    // again, it lands via a const-constraint attribute later.
48    input / *divisor
49}
50
51#[polydat::polydat_node(category = Arithmetic)]
52fn r#mod(input: u64, modulus: Const<u64>) -> u64 {
53    input % *modulus
54}
55
56/// Modulo of a u64 value by a *wire-fed* divisor.
57///
58/// Signature: `mod_wire(input: u64, divisor: u64) -> (u64)`
59///
60/// The divisor is computed at cycle time from another node — for
61/// example, a control read or a runtime-derived shard count. The
62/// divisor port declares a `NonZeroU64` constraint, so under
63/// `// @pragma: strict_values` the compiler auto-inserts an
64/// `assert_u64_nonzero` between the source and the divisor input
65/// (SRD 15 §"Strict Wire Mode"). Without strict mode, the node
66/// trusts the divisor and a zero value will panic at cycle time —
67/// the canonical "panic at hour 14" hazard, opt-out by design.
68///
69/// Use this when the modulus genuinely varies across cycles. For
70/// the const case, prefer [`Mod`] which is faster (the divisor
71/// is baked into the JIT closure as a constant).
72///
73/// JIT level: P3 (`urem` on two wire slots; `JitOp::U64ModWire`).
74/// Modulo of a u64 by a wire-fed divisor. SRD-80 PR B.14
75/// migration — the `#[constraint(NonZeroU64)]` attribute carries
76/// the strict-wire-mode assertion contract.
77#[polydat::polydat_node(category = Arithmetic)]
78fn mod_wire(input: u64, #[constraint(NonZeroU64)] divisor: u64) -> u64 {
79    input % divisor
80}
81
82/// Division of a u64 by a wire-fed divisor. SRD-80 PR B.14
83/// migration — same NonZeroU64 contract as mod_wire.
84#[polydat::polydat_node(category = Arithmetic)]
85fn div_wire(input: u64, #[constraint(NonZeroU64)] divisor: u64) -> u64 {
86    input / divisor
87}
88
89/// Smallest multiple of `multiple` that is ≥ `value`.
90///
91/// Signature: `ceil_to_multiple(value: u64, multiple: u64) -> (u64)`
92///
93/// Workload-author shorthand for "round this value up to the
94/// next whole multiple of base." Eliminates the
95/// `(v + m - 1) / m * m` / `div_ceil` idiom from bindings.
96/// `multiple == 0` is a soft no-op: returns `value` unchanged
97/// rather than trapping, so a transient zero from a wire-bound
98/// extern doesn't break a binding mid-evaluation.
99///
100/// Use cases:
101///   - cycle counts: `ceil_to_multiple(min_cycles, base)` gives
102///     the smallest whole-pass cycle count meeting a minimum
103///   - alignment: pad an offset up to a chunk boundary
104///   - bucketing: snap a value up to the next bin edge
105///
106/// JIT level: P3 (`JitOp::CeilToMultiple`, inline).
107/// Smallest multiple of `multiple` that is ≥ `value`. SRD-80
108/// PR B.13. `multiple == 0` is a soft no-op (returns value
109/// unchanged) so a transient zero from a wire-bound extern
110/// doesn't break a binding mid-evaluation.
111#[polydat::polydat_node(category = Arithmetic)]
112fn ceil_to_multiple(value: u64, multiple: u64) -> u64 {
113    if multiple == 0 {
114        value
115    } else {
116        value.div_ceil(multiple).saturating_mul(multiple)
117    }
118}
119
120/// Count of multiples of `multiple` needed to cover `value`.
121///
122/// Signature: `multiples_at_least(value: u64, multiple: u64) -> (u64)`
123///
124/// Companion to [`CeilToMultiple`] that returns the *count*
125/// instead of the product — i.e. `ceil(value / multiple)`. The
126/// invariant `multiples_at_least(v, m) * m == ceil_to_multiple(v, m)`
127/// holds whenever `multiple > 0` and the multiplication doesn't
128/// overflow.
129///
130/// Use cases:
131///   - calibration: `multiples_at_least(min_cycles, base)` gives
132///     the pass count so the workload can both apply the
133///     multiplier and report "ran N passes" for diagnostics
134///   - bucket arithmetic: count of fixed-size buckets needed
135///     to hold N items
136///
137/// `multiple == 0` returns `0` — there is no count that covers
138/// a positive value with zero-sized multiples; rather than
139/// trap, the function quietly yields the only honest answer.
140///
141/// JIT level: P3 (single `udiv_ceil`).
142/// Count of multiples needed to cover `value`. SRD-80 PR B.13.
143/// `multiple == 0` returns 0 (no count covers positive value
144/// with zero-sized multiples). JIT P3.
145#[polydat::polydat_node(category = Arithmetic)]
146fn multiples_at_least(value: u64, multiple: u64) -> u64 {
147    if multiple == 0 {
148        0
149    } else {
150        value.div_ceil(multiple)
151    }
152}
153
154/// "Set-or-get" memoizer: returns `current` if non-zero,
155/// otherwise returns `fallback`.
156///
157/// Signature: `set_or_get(current: u64, fallback: u64) -> (u64)`
158///
159/// Functionally `if current == 0 { fallback } else { current }`
160/// — a simple conditional. The name reflects its intended use
161/// alongside SRD-13f cross-scope shared wires:
162///
163/// ```text
164///   shared query_passes := set_or_get(
165///       query_passes,
166///       multiples_at_least(min_cycles, base),
167///   )
168/// ```
169///
170/// First phase to evaluate this: `query_passes` reads 0 (the
171/// unset sentinel), `set_or_get` returns the computed fallback,
172/// the `shared :=` broadcast writes the value to the parent
173/// scope's SharedCell. Every subsequent phase reads the
174/// already-set value and the fallback computation is
175/// effectively a no-op (it still evaluates, but its result is
176/// discarded). The write-back is idempotent — writing the
177/// already-cached value back doesn't change anything.
178///
179/// Concurrency: first-writer-wins is provided by the SharedCell
180/// mutex, not by this node. The node itself is pure — given
181/// the same inputs it returns the same output. Concurrent
182/// phases evaluating it simultaneously will compute the same
183/// fallback and race on the cell write; whichever writes last
184/// wins, but they're writing the same value anyway.
185///
186/// JIT level: P3 through its slot kit (no named JitOp); the body
187/// is the compare+select.
188//
189// SRD-80b Phase E: migrated to `#[polydat_node]`. Struct
190// renamed from `SetOrGetU64` to `SetOrGet` (greenfield
191// posture — no cross-crate callers reference the old name)
192// to match the macro's snake_case → PascalCase derivation.
193#[polydat::polydat_node(category = Arithmetic)]
194fn set_or_get(current: u64, fallback: u64) -> u64 {
195    if current == 0 { fallback } else { current }
196}
197
198/// Clamp an unsigned integer to [min, max].
199///
200/// Signature: `clamp(input: u64, min: u64, max: u64) -> (u64)`
201///
202/// Unlike mod (which wraps), clamp saturates at the boundary. Use when
203/// you want values to pile up at the edges rather than wrap around.
204///
205/// JIT level: P3 (`umax` + `umin`).
206//
207// SRD-80b Phase E: migrated to `#[polydat_node]`. Struct
208// renamed from `ClampU64` to `Clamp` (greenfield posture —
209// no cross-crate callers reference the old name).
210#[polydat::polydat_node(category = Arithmetic)]
211fn clamp(input: u64, min: Const<u64>, max: Const<u64>) -> u64 {
212    input.clamp(*min, *max)
213}
214
215/// Decompose a u64 into mixed-radix digits.
216///
217/// Signature: `mixed_radix(input: u64, radixes...) -> (d0: u64, d1: u64, ...)`
218///
219/// The primary tool for coordinate decomposition. Maps a flat cycle
220/// counter into a multi-dimensional space. Each radix defines the size
221/// of that dimension. A trailing radix of 0 means unbounded (consumes
222/// the remainder).
223///
224/// Example: `(device, reading) := mixed_radix(cycle, 10000, 0)` gives
225/// 10,000 devices with unbounded readings per device.
226///
227/// Traversal is nested-loop, innermost first: d0 increments every cycle,
228/// d1 increments every `radix[0]` cycles, etc.
229///
230/// JIT level: P3 (unrolled urem/udiv chain).
231//
232// Migrated to `#[polydat_node]` via the `Const<Vec<u64>>` +
233// `DynamicOutputs<T>` shape; the output port count comes from
234// `radixes.len()` at construction. The `compiled_u64` /
235// `jit_constants` overrides feed `JitOp::MixedRadixConst`.
236fn mixed_radix_jit(node: &MixedRadix) -> CompiledU64Op {
237    let radixes = node.radixes.clone();
238    Box::new(move |inputs, outputs| {
239        let mut remainder = inputs[0];
240        for (i, &radix) in radixes.iter().enumerate() {
241            if radix == 0 {
242                outputs[i] = remainder;
243                remainder = 0;
244            } else {
245                outputs[i] = remainder % radix;
246                remainder /= radix;
247            }
248        }
249    })
250}
251
252fn mixed_radix_jit_constants(node: &MixedRadix) -> Vec<u64> {
253    node.radixes.clone()
254}
255
256/// Decompose `value` into mixed-radix digits using the given
257/// `radixes`. The output is a vector of N digits where N =
258/// `radixes.len()`. A radix of 0 in the trailing position
259/// captures the remainder verbatim.
260#[polydat::polydat_node(
261    category = Arithmetic,
262    compiled_u64 = mixed_radix_jit,
263    jit_constants = mixed_radix_jit_constants,
264    validate = mixed_radix_validate,
265)]
266fn mixed_radix(
267    input: u64,
268    radixes: polydat::derive_support::Const<&[u64]>,
269) -> polydat::derive_support::DynamicOutputs<u64> {
270    let mut remainder = input;
271    let mut result = Vec::with_capacity(radixes.len());
272    for &radix in radixes.iter() {
273        if radix == 0 {
274            result.push(remainder);
275            remainder = 0;
276        } else {
277            result.push(remainder % radix);
278            remainder /= radix;
279        }
280    }
281    polydat::derive_support::DynamicOutputs(result)
282}
283
284/// `mixed_radix`'s rule over its radix list: every radix but the last
285/// must be non-zero, since a zero there would divide by zero, while a
286/// zero in the last position is the "everything left" sentinel the
287/// body reads. The rule is positional across one list argument, which
288/// no per-parameter constraint can state.
289fn mixed_radix_validate(
290    _name: &str,
291    consts: &[polydat::dsl::factory::ConstArg],
292) -> Result<(), String> {
293    for (i, c) in consts
294        .iter()
295        .enumerate()
296        .take(consts.len().saturating_sub(1))
297    {
298        if c.as_u64() == 0 {
299            return Err(format!("radix {i} must be non-zero"));
300        }
301    }
302    Ok(())
303}
304
305/// Sum N u64 inputs (wrapping). Variadic: accepts 0..N wire inputs.
306///
307/// Signature: `sum(in_0: u64, ..., in_N: u64) -> (u64)`
308///
309/// Group theory: identity element is 0 (additive identity).
310/// `sum()` = 0, `sum(a)` = a, `sum(a, b, c)` = a + b + c.
311///
312/// Use for combining multiple values into a single aggregate.
313///
314/// JIT level: P3 (unrolled chain, `JitOp::VariadicSum`; likewise
315/// product/min/max).
316// SRD-80 PR B.9 — variadic N-ary u64 reductions migrated to
317// `#[polydat_node]`. Macro generates Sum/Product/Min/Max
318// structs with `new(n_wires)` ctors and auto-emits Phase 2
319// closures that pass the JIT `&[u64]` buffer directly to the
320// body. AllCommutative declared via attribute.
321
322#[polydat::polydat_node(category = Variadic, identity = 0u64, commutativity = AllCommutative)]
323fn sum(values: &[u64]) -> u64 {
324    values.iter().fold(0u64, |a, b| a.wrapping_add(*b))
325}
326
327#[polydat::polydat_node(category = Variadic, identity = 1u64, commutativity = AllCommutative)]
328fn product(values: &[u64]) -> u64 {
329    values.iter().fold(1u64, |a, b| a.wrapping_mul(*b))
330}
331
332#[polydat::polydat_node(category = Variadic, identity = u64::MAX, commutativity = AllCommutative)]
333fn min(values: &[u64]) -> u64 {
334    values.iter().copied().fold(u64::MAX, std::cmp::min)
335}
336
337#[polydat::polydat_node(category = Variadic, identity = 0u64, commutativity = AllCommutative)]
338fn max(values: &[u64]) -> u64 {
339    values.iter().copied().fold(0u64, std::cmp::max)
340}
341
342/// Interleave the bits of two u64 values into one (Morton code).
343///
344/// Signature: `interleave(a: u64, b: u64) -> (u64)`
345///
346/// Bit 0 of a → bit 0 of output, bit 0 of b → bit 1, bit 1 of a → bit 2,
347/// etc. This preserves locality from both dimensions — essential for
348/// combining two independent coordinates into a single hash input:
349/// `hash(interleave(device_id, reading_idx))` produces a value that
350/// changes when either dimension changes, with spatial correlation.
351///
352/// JIT level: P3 (extern call).
353//
354// SRD-80b Phase E: migrated to `#[polydat_node]`. Struct
355// name `Interleave` matches snake_case → PascalCase of `interleave`.
356#[polydat::polydat_node(category = Arithmetic)]
357fn interleave(a: u64, b: u64) -> u64 {
358    let mut result: u64 = 0;
359    for i in 0..32 {
360        result |= ((a >> i) & 1) << (2 * i);
361        result |= ((b >> i) & 1) << (2 * i + 1);
362    }
363    result
364}
365
366#[cfg(test)]
367mod tests {
368    use super::*;
369    use polydat::ast::{PolydatNode, Value};
370
371    #[test]
372    fn add_wrapping() {
373        let node = Add::new(10);
374        let mut out = [Value::None];
375        node.eval(&[Value::U64(5)], &mut out);
376        assert_eq!(out[0].as_u64(), 15);
377    }
378
379    #[test]
380    fn mod_basic() {
381        let node = Mod::new(100);
382        let mut out = [Value::None];
383        node.eval(&[Value::U64(542)], &mut out);
384        assert_eq!(out[0].as_u64(), 42);
385    }
386
387    #[test]
388    fn mixed_radix_decompose() {
389        let node = MixedRadix::new(vec![100, 1000, 0]);
390        let mut out = [Value::None, Value::None, Value::None];
391        // 4201337 → (37, 13, 42)
392        // 4201337 % 100 = 37
393        // 4201337 / 100 = 42013; 42013 % 1000 = 13
394        // 42013 / 1000 = 42
395        node.eval(&[Value::U64(4_201_337)], &mut out);
396        assert_eq!(out[0].as_u64(), 37);
397        assert_eq!(out[1].as_u64(), 13);
398        assert_eq!(out[2].as_u64(), 42);
399    }
400
401    #[test]
402    fn mixed_radix_cartesian() {
403        // 100 tenants × 1000 devices × unbounded readings
404        let node = MixedRadix::new(vec![100, 1000, 0]);
405        let mut out = [Value::None, Value::None, Value::None];
406
407        // cycle 0 → tenant 0, device 0, reading 0
408        node.eval(&[Value::U64(0)], &mut out);
409        assert_eq!(out[0].as_u64(), 0);
410        assert_eq!(out[1].as_u64(), 0);
411        assert_eq!(out[2].as_u64(), 0);
412
413        // cycle 100_000 → tenant 0, device 0, reading 1
414        node.eval(&[Value::U64(100_000)], &mut out);
415        assert_eq!(out[0].as_u64(), 0);
416        assert_eq!(out[1].as_u64(), 0);
417        assert_eq!(out[2].as_u64(), 1);
418    }
419
420    #[test]
421    fn interleave_basic() {
422        let node = Interleave::new();
423        let mut out = [Value::None];
424        node.eval(&[Value::U64(0b101), Value::U64(0b010)], &mut out);
425        // a=101, b=010
426        // bit 0: a0=1, b0=0 → positions 0,1 = 01
427        // bit 1: a1=0, b1=1 → positions 2,3 = 10
428        // bit 2: a2=1, b2=0 → positions 4,5 = 01
429        // result = 0b01_10_01 = 0b011001 = 25
430        assert_eq!(out[0].as_u64(), 0b01_10_01);
431    }
432
433    #[test]
434    fn div_basic() {
435        let node = Div::new(100);
436        let mut out = [Value::None];
437        node.eval(&[Value::U64(4_201_337)], &mut out);
438        assert_eq!(out[0].as_u64(), 42013);
439    }
440
441    // --- Variadic N-ary tests ---
442
443    #[test]
444    fn sum_variadic() {
445        // 0 inputs → identity = 0
446        let node = Sum::new(0);
447        let mut out = [Value::None];
448        node.eval(&[], &mut out);
449        assert_eq!(out[0].as_u64(), 0);
450
451        // 1 input → passthrough
452        let node = Sum::new(1);
453        node.eval(&[Value::U64(42)], &mut out);
454        assert_eq!(out[0].as_u64(), 42);
455
456        // 3 inputs → fold
457        let node = Sum::new(3);
458        node.eval(&[Value::U64(10), Value::U64(20), Value::U64(30)], &mut out);
459        assert_eq!(out[0].as_u64(), 60);
460    }
461
462    #[test]
463    fn product_variadic() {
464        // 0 inputs → identity = 1
465        let node = Product::new(0);
466        let mut out = [Value::None];
467        node.eval(&[], &mut out);
468        assert_eq!(out[0].as_u64(), 1);
469
470        // 1 input → passthrough
471        let node = Product::new(1);
472        node.eval(&[Value::U64(7)], &mut out);
473        assert_eq!(out[0].as_u64(), 7);
474
475        // 3 inputs → fold
476        let node = Product::new(3);
477        node.eval(&[Value::U64(2), Value::U64(3), Value::U64(7)], &mut out);
478        assert_eq!(out[0].as_u64(), 42);
479    }
480
481    #[test]
482    fn min_variadic() {
483        // 0 inputs → identity = u64::MAX
484        let node = Min::new(0);
485        let mut out = [Value::None];
486        node.eval(&[], &mut out);
487        assert_eq!(out[0].as_u64(), u64::MAX);
488
489        // 3 inputs → min
490        let node = Min::new(3);
491        node.eval(&[Value::U64(50), Value::U64(10), Value::U64(30)], &mut out);
492        assert_eq!(out[0].as_u64(), 10);
493    }
494
495    #[test]
496    fn max_variadic() {
497        // 0 inputs → identity = 0
498        let node = Max::new(0);
499        let mut out = [Value::None];
500        node.eval(&[], &mut out);
501        assert_eq!(out[0].as_u64(), 0);
502
503        // 3 inputs → max
504        let node = Max::new(3);
505        node.eval(&[Value::U64(50), Value::U64(10), Value::U64(30)], &mut out);
506        assert_eq!(out[0].as_u64(), 50);
507    }
508
509    // --- Slot model consistency ---
510
511    /// Verify that `meta().jit_constants_from_slots()` matches
512    /// `jit_constants()` for all arithmetic nodes with constants.
513    #[test]
514    fn slot_constants_match_jit_constants() {
515        use polydat::ast::PolydatNode;
516
517        let nodes: Vec<Box<dyn PolydatNode>> = vec![
518            Box::new(Add::new(42)),
519            Box::new(Mul::new(7)),
520            Box::new(Div::new(100)),
521            Box::new(Mod::new(256)),
522            Box::new(Clamp::new(10, 90)),
523            Box::new(MixedRadix::new(vec![100, 1000, 0])),
524        ];
525
526        for node in &nodes {
527            let from_trait = node.jit_constants();
528            let from_slots = node.meta().jit_constants_from_slots();
529            assert_eq!(
530                from_trait,
531                from_slots,
532                "constant mismatch for node '{}': trait={from_trait:?}, slots={from_slots:?}",
533                node.meta().name,
534            );
535        }
536    }
537
538    // ── ceil_to_multiple ──────────────────────────────────
539
540    fn run_binary(node: &dyn PolydatNode, a: u64, b: u64) -> u64 {
541        let mut out = [Value::None];
542        node.eval(&[Value::U64(a), Value::U64(b)], &mut out);
543        out[0].as_u64()
544    }
545
546    #[test]
547    fn ceil_to_multiple_returns_value_when_already_a_multiple() {
548        let n = CeilToMultiple::default();
549        assert_eq!(run_binary(&n, 800, 100), 800);
550    }
551
552    #[test]
553    fn ceil_to_multiple_rounds_up_to_next_boundary() {
554        let n = CeilToMultiple::default();
555        assert_eq!(run_binary(&n, 801, 100), 900);
556    }
557
558    #[test]
559    fn ceil_to_multiple_zero_value_is_zero() {
560        let n = CeilToMultiple::default();
561        assert_eq!(run_binary(&n, 0, 100), 0);
562    }
563
564    #[test]
565    fn ceil_to_multiple_below_one_multiple_rounds_to_multiple() {
566        let n = CeilToMultiple::default();
567        assert_eq!(run_binary(&n, 50, 100), 100);
568        assert_eq!(run_binary(&n, 1, 100), 100);
569    }
570
571    #[test]
572    fn ceil_to_multiple_zero_multiple_is_soft_no_op() {
573        let n = CeilToMultiple::default();
574        assert_eq!(
575            run_binary(&n, 42, 0),
576            42,
577            "multiple=0 must not trap; passes value through"
578        );
579    }
580
581    // ── multiples_at_least ────────────────────────────────
582
583    #[test]
584    fn multiples_at_least_exact_division() {
585        let n = MultiplesAtLeast::default();
586        assert_eq!(run_binary(&n, 800, 100), 8);
587    }
588
589    #[test]
590    fn multiples_at_least_rounds_up_partial() {
591        let n = MultiplesAtLeast::default();
592        assert_eq!(run_binary(&n, 801, 100), 9);
593        assert_eq!(run_binary(&n, 1, 100), 1);
594    }
595
596    #[test]
597    fn multiples_at_least_zero_value_is_zero() {
598        let n = MultiplesAtLeast::default();
599        assert_eq!(run_binary(&n, 0, 100), 0);
600    }
601
602    #[test]
603    fn multiples_at_least_zero_multiple_is_zero() {
604        let n = MultiplesAtLeast::default();
605        assert_eq!(run_binary(&n, 42, 0), 0);
606    }
607
608    // ── set_or_get ────────────────────────────────────────
609
610    #[test]
611    fn set_or_get_returns_current_when_non_zero() {
612        let n = SetOrGet::default();
613        assert_eq!(run_binary(&n, 7, 99), 7);
614        assert_eq!(run_binary(&n, u64::MAX, 99), u64::MAX);
615    }
616
617    #[test]
618    fn set_or_get_returns_fallback_when_current_is_zero() {
619        let n = SetOrGet::default();
620        assert_eq!(run_binary(&n, 0, 99), 99);
621    }
622
623    #[test]
624    fn set_or_get_zero_fallback_is_zero() {
625        // If both inputs are zero, output is zero — soft default
626        // for the degenerate case (caller's choice not to seed
627        // a meaningful fallback).
628        let n = SetOrGet::default();
629        assert_eq!(run_binary(&n, 0, 0), 0);
630    }
631
632    #[test]
633    fn set_or_get_idempotent_on_already_set() {
634        // The "every subsequent phase" path: current is the
635        // cached value, fallback is the (still-evaluated but
636        // discarded) recomputation. Returning current preserves
637        // the cached state across phases.
638        let n = SetOrGet::default();
639        for v in [1u64, 42, 1000, u64::MAX] {
640            // Even if the fallback differs each call (e.g., a
641            // recomputation that picked a slightly different
642            // value due to a different base), the cached value
643            // wins.
644            assert_eq!(run_binary(&n, v, 999), v);
645        }
646    }
647
648    #[test]
649    fn ceil_to_multiple_and_count_satisfy_invariant() {
650        // Documented invariant: ceil_to_multiple(v, m) == multiples_at_least(v, m) * m
651        // whenever m > 0 and the multiplication doesn't overflow.
652        let ceil = CeilToMultiple::default();
653        let count = MultiplesAtLeast::default();
654        for (v, m) in [
655            (0u64, 100),
656            (1, 100),
657            (50, 100),
658            (100, 100),
659            (101, 100),
660            (10000, 7),
661            (10000, 64),
662            (12345, 256),
663        ] {
664            let c_val = run_binary(&ceil, v, m);
665            let n_val = run_binary(&count, v, m);
666            assert_eq!(
667                c_val,
668                n_val * m,
669                "invariant violated for (v={v}, m={m}): ceil={c_val}, count={n_val}"
670            );
671        }
672    }
673
674    /// Verify wire_inputs() returns correct count for all arithmetic nodes.
675    #[test]
676    fn slot_wire_inputs_match_inputs() {
677        use polydat::ast::PolydatNode;
678
679        let nodes: Vec<Box<dyn PolydatNode>> = vec![
680            Box::new(Add::new(0)),
681            Box::new(Mod::new(1)),
682            Box::new(Sum::new(3)),
683            Box::new(Product::new(2)),
684            Box::new(Interleave::new()),
685            Box::new(MixedRadix::new(vec![10, 20])),
686            Box::new(CeilToMultiple::default()),
687            Box::new(MultiplesAtLeast::default()),
688            Box::new(SetOrGet::default()),
689        ];
690
691        for node in &nodes {
692            let old_count = node.meta().wire_inputs().len();
693            let new_count = node.meta().wire_inputs().len();
694            assert_eq!(
695                old_count,
696                new_count,
697                "wire input count mismatch for '{}': inputs={old_count}, wire_inputs()={new_count}",
698                node.meta().name,
699            );
700        }
701    }
702}
703
704#[cfg(test)]
705mod node_validator_tests {
706    use polydat::dsl::compile::compile_polydat_kernel;
707
708    /// `mixed_radix`'s positional rule is declared on the node, so
709    /// the factory refuses a zero in a non-terminal radix when the
710    /// program is built — on every engine, and before a cycle can
711    /// divide by it. A zero in the last position is the sentinel the
712    /// body reads and stays legal.
713    #[test]
714    fn a_zero_radix_is_refused_except_in_the_last_position() {
715        let err = compile_polydat_kernel("input cycle: u64\n(a, b) := mixed_radix(cycle, 0, 10)\n")
716            .err()
717            .map(|e| e.to_string())
718            .unwrap_or_else(|| panic!("a zero leading radix must not build"));
719        assert!(err.contains("radix 0 must be non-zero"), "{err}");
720
721        assert!(
722            compile_polydat_kernel("input cycle: u64\n(a, b) := mixed_radix(cycle, 10, 0)\n")
723                .is_ok(),
724            "a trailing zero is the remainder sentinel"
725        );
726    }
727}