polydat-core 0.6.1

Polydat runtime: value model, graph compiler, execution engines, kernels
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Type and value assertion nodes.
//!
//! Polydat's runtime contract: node `eval` trusts its inputs. Bad input
//! panics, by design, because the hot path stays branch-free. The
//! "guarded" version of a node that would otherwise panic is built
//! as an *assembly* of two functions — the original node, and an
//! assertion node spliced in front of one of its inputs. The assertion runs the
//! check; the downstream node still trusts its inputs.
//!
//! Two families:
//!
//! * **Type assertions** — one per supported [`PortType`]. They
//!   confirm the runtime [`Value`] variant matches the static
//!   port type and pass it through. The compiler inserts none:
//!   wires are statically typed, and a resolved wire's type is the
//!   sink port's type, so a runtime type check has nothing to catch.
//!
//! * **Value assertions** — one per `PortType`, parameterised by
//!   a [`ConstConstraint`]. Pass the value through if the
//!   constraint holds, otherwise panic with a structured message.
//!   The same vocabulary the const-constraint metadata uses on
//!   `ParamSpec` is reused on `Port` and on these nodes.
//!
//! The compiler inserts value assertions under `pragma strict_values`
//! (graph_compiler.md §2). Neither family is callable from Polydat
//! source (library_catalog.md, the hand-written-impl carve-outs).

use crate::ast::SlotShape;
use crate::ast::{NodeMeta, PolydatNode, Port, PortType, Slot, Value};
use crate::dsl::const_constraints::ConstConstraint;

// =========================================================================
// Type assertions: one per PortType
// =========================================================================

/// Pass-through guard that confirms the runtime value variant
/// matches a declared `PortType`. Panics on mismatch.
///
/// Constructed with [`assert_type_node`]. The compiler inserts none,
/// under `strict_types` or otherwise: a resolved wire's type is the
/// sink port's type (graph_compiler.md §2).
pub struct AssertType {
    meta: NodeMeta,
    expected: PortType,
}

impl AssertType {
    /// A type assertion for `typ`, named `assert_<type>`.
    pub fn new(typ: PortType) -> Self {
        let name = match typ {
            PortType::U64 => "assert_u64",
            PortType::F64 => "assert_f64",
            PortType::Bool => "assert_bool",
            PortType::Str => "assert_str",
            PortType::Bytes => "assert_bytes",
            PortType::Json => "assert_json",
            PortType::U32 => "assert_u32",
            PortType::I32 => "assert_i32",
            PortType::I64 => "assert_i64",
            PortType::F32 => "assert_f32",
            PortType::U8 => "assert_u8",
            PortType::I8 => "assert_i8",
            PortType::U16 => "assert_u16",
            PortType::I16 => "assert_i16",
            PortType::F16 => "assert_f16",
            PortType::U128 => "assert_u128",
            PortType::I128 => "assert_i128",
            PortType::Reg128 => "assert_reg128",
            PortType::RegI8x16 => "assert_reg_i8x16",
            PortType::RegI16x8 => "assert_reg_i16x8",
            PortType::RegI32x4 => "assert_reg_i32x4",
            PortType::RegI64x2 => "assert_reg_i64x2",
            PortType::RegF16x8 => "assert_reg_f16x8",
            PortType::RegF32x4 => "assert_reg_f32x4",
            PortType::RegF64x2 => "assert_reg_f64x2",
            PortType::Ext => "assert_ext",
            PortType::Handle => "assert_handle",
            PortType::VecF32 => "assert_vec_f32",
            PortType::VecI32 => "assert_vec_i32",
            PortType::VecF64 => "assert_vec_f64",
            PortType::VecI64 => "assert_vec_i64",
            PortType::VecF16 => "assert_vec_f16",
            PortType::VecI16 => "assert_vec_i16",
            PortType::VecI8 => "assert_vec_i8",
            PortType::Dyn => "assert_dyn",
        };
        Self {
            meta: NodeMeta {
                name: name.into(),
                outs: vec![Port::new("output", typ)],
                ins: vec![Slot::Wire(Port::new("input", typ))],
            },
            expected: typ,
        }
    }

    /// Returns the `PortType` this node asserts against.
    pub fn expected(&self) -> PortType {
        self.expected
    }
}

impl PolydatNode for AssertType {
    fn meta(&self) -> &NodeMeta {
        &self.meta
    }

    fn eval(&self, inputs: &[Value], outputs: &mut [Value]) {
        let v = &inputs[0];
        if !value_matches(v, self.expected) {
            panic!(
                "{}: expected runtime value of type {:?}, got {:?}",
                self.meta.name, self.expected, v
            );
        }
        outputs[0] = v.clone();
    }

    /// The compiled form. In a slot buffer a wire's color is its type,
    /// so the variant check the interpreter makes has nothing to
    /// observe there; the compiled step is the copy `identity` makes:
    /// an immediate copied, a `Ref2` value copied into this step's own
    /// scratch, since a pair is never forwarded (axiom S3).
    fn compiled_u64(&self) -> Option<crate::ast::CompiledU64Op> {
        if self.expected.slot_color() == crate::ast::SlotColor::Ref2 {
            return None;
        }
        Some(Box::new(|inputs: &[u64], outputs: &mut [u64]| {
            outputs.copy_from_slice(inputs)
        }))
    }

    fn compiled_slot(
        &self,
        _wire_types: &[PortType],
        _engine: crate::compile::select::Engine,
    ) -> Option<crate::ast::CompiledSlotKit> {
        crate::compile::assembly::ref_copy_kit(self.expected)
    }
}

fn value_matches(v: &Value, typ: PortType) -> bool {
    match (v, typ) {
        (Value::U64(_), PortType::U64) => true,
        (Value::F64(_), PortType::F64) => true,
        (Value::Bool(_), PortType::Bool) => true,
        (Value::Str(_), PortType::Str) => true,
        (Value::Bytes(_), PortType::Bytes) => true,
        (Value::Json(_), PortType::Json) => true,
        // Narrow-int variants ride in the wider variant per the
        // PortType doc on `node.rs` — accept the natural carrier.
        (Value::U64(_), PortType::U32) => true,
        (Value::U64(_), PortType::I32) => true,
        (Value::U64(_), PortType::I64) => true,
        (Value::F64(_), PortType::F32) => true,
        (Value::U64(_), PortType::U8 | PortType::U16) => true,
        // F16 rides its bit pattern in U64 (same stuffing as F32
        // node outputs); host-written F64 also satisfies F16.
        (Value::U64(_), PortType::F16) => true,
        (Value::F64(_), PortType::F16) => true,
        // Honest signed carrier serves all signed widths; the
        // bit-stuffed U64 forms of the narrow signed projections are
        // accepted too.
        (Value::I64(_), PortType::I64 | PortType::I32 | PortType::I8 | PortType::I16) => true,
        (Value::U64(_), PortType::I8 | PortType::I16) => true,
        (Value::U128(_), PortType::U128) => true,
        (Value::I128(_), PortType::I128) => true,
        // Register views are free bitcasts of one another.
        (
            Value::Reg128(_, _),
            PortType::Reg128
            | PortType::RegI8x16
            | PortType::RegI16x8
            | PortType::RegI32x4
            | PortType::RegI64x2
            | PortType::RegF16x8
            | PortType::RegF32x4
            | PortType::RegF64x2,
        ) => true,
        // Ext is opaque; we accept any concrete reflection.
        (Value::Ext(_), PortType::Ext) => true,
        _ => false,
    }
}

// =========================================================================
// Value assertions: type + constraint pair
// =========================================================================

/// Runtime value-constraint guard. Holds a [`ConstConstraint`]
/// the value must satisfy each cycle. Panics with a structured
/// message on violation; passes the value through otherwise.
///
/// Constructed with [`assert_value_node`] from the compiler when
/// the source can't statically be proven to deliver a value
/// satisfying the sink's constraint. Reuses the same
/// `ConstConstraint` vocabulary the const-validator uses, so the
/// two layers speak one language.
pub struct AssertValue {
    meta: NodeMeta,
    typ: PortType,
    constraint: ConstConstraint,
}

impl AssertValue {
    /// A value assertion for `typ` under `constraint`, named by the pair.
    pub fn new(typ: PortType, constraint: ConstConstraint) -> Self {
        let name = match (&typ, &constraint) {
            (PortType::U64, ConstConstraint::NonZeroU64) => "assert_u64_nonzero",
            (PortType::U64, ConstConstraint::RangeU64 { .. }) => "assert_u64_range",
            (PortType::U64, ConstConstraint::AllowedU64(_)) => "assert_u64_allowed",
            (PortType::F64, ConstConstraint::RangeF64 { .. }) => "assert_f64_range",
            (PortType::Str, ConstConstraint::NonEmptyStr) => "assert_str_non_empty",
            (PortType::Str, ConstConstraint::StrParser(_)) => "assert_str_parses",
            // Catch-all for combinations we haven't dedicated a
            // distinct DSL name to yet.
            _ => "assert_value",
        };
        Self {
            meta: NodeMeta {
                name: name.into(),
                outs: vec![Port::new("output", typ)],
                ins: vec![Slot::Wire(Port::new("input", typ))],
            },
            typ,
            constraint,
        }
    }

    /// The constraint asserted.
    pub fn constraint(&self) -> &ConstConstraint {
        &self.constraint
    }

    /// The type asserted.
    pub fn port_type(&self) -> PortType {
        self.typ
    }
}

impl PolydatNode for AssertValue {
    fn meta(&self) -> &NodeMeta {
        &self.meta
    }

    fn eval(&self, inputs: &[Value], outputs: &mut [Value]) {
        // Re-route the constraint check through `ConstConstraint::check`
        // by lifting the value into a `ConstArg` shaped tuple. Avoids
        // duplicating the per-variant logic between assembly and
        // runtime.
        match check_value(&self.constraint, &inputs[0], "value") {
            Some(Ok(())) => {}
            Some(Err(msg)) => panic!("{}: {msg}", self.meta.name),
            None => panic!(
                "{}: unsupported runtime value variant {:?}",
                self.meta.name, inputs[0]
            ),
        }
        outputs[0] = inputs[0].clone();
    }

    /// The compiled form: the same constraint checked against the slot,
    /// decoded by the asserted type, with the same message on failure.
    /// A carrier reads as its integer, a float from its bits; the
    /// other shapes have no u64 form.
    fn compiled_u64(&self) -> Option<crate::ast::CompiledU64Op> {
        use crate::dsl::factory::ConstArg;
        let lift: fn(u64) -> ConstArg = match self.typ {
            PortType::U64 | PortType::U32 | PortType::U16 | PortType::U8 => ConstArg::Int,
            PortType::F64 => |slot| ConstArg::Float(f64::from_bits(slot)),
            _ => return None,
        };
        let name = self.meta.name.clone();
        let constraint = self.constraint;
        Some(Box::new(move |inputs: &[u64], outputs: &mut [u64]| {
            if let Err(msg) = constraint.check(&lift(inputs[0]), "value") {
                panic!("{name}: {msg}");
            }
            outputs[0] = inputs[0];
        }))
    }

    /// A string reads through its pair, is checked, and is copied into
    /// this step's own scratch (axiom S3).
    fn compiled_slot(
        &self,
        _wire_types: &[PortType],
        _engine: crate::compile::select::Engine,
    ) -> Option<crate::ast::CompiledSlotKit> {
        use crate::dsl::factory::ConstArg;
        if self.typ != PortType::Str {
            return None;
        }
        let name = self.meta.name.clone();
        let constraint = self.constraint;
        let copy = crate::compile::assembly::ref_copy_kit(PortType::Str)?;
        Some(crate::ast::CompiledSlotKit {
            scratch: copy.scratch,
            op: Box::new(
                move |inputs: &[u64],
                      outputs: &mut [u64],
                      scratch: &mut [crate::ast::ScratchBuf]| {
                    // SAFETY: the pair was published by the producing
                    // step into storage alive until it reruns (S3, S4).
                    let text = unsafe {
                        std::str::from_utf8_unchecked(std::slice::from_raw_parts(
                            inputs[0] as usize as *const u8,
                            inputs[1] as usize,
                        ))
                    };
                    if let Err(msg) = constraint.check(&ConstArg::Str(text.to_string()), "value") {
                        panic!("{name}: {msg}");
                    }
                    (copy.op)(inputs, outputs, scratch);
                },
            ),
        })
    }
}

// =========================================================================
// Helpers used by the compiler when auto-wiring assertions
// =========================================================================

/// Check `value` against `constraint`, naming the checked value
/// `name` in the message. `None` when the value's variant is one the
/// constraint vocabulary has no reading of (anything but `U64`, `F64`
/// and `Str`).
pub fn check_value(
    constraint: &ConstConstraint,
    value: &Value,
    name: &str,
) -> Option<Result<(), String>> {
    use crate::dsl::factory::ConstArg;
    let arg = match value {
        Value::U64(v) => ConstArg::Int(*v),
        Value::F64(v) => ConstArg::Float(*v),
        Value::Str(s) => ConstArg::Str(s.to_string()),
        _ => return None,
    };
    Some(constraint.check(&arg, name))
}

/// The condition `constraint` states, in words, for diagnostics.
pub fn describe_constraint(constraint: &ConstConstraint) -> String {
    match constraint {
        ConstConstraint::RangeU64 { min, max } => format!("in [{min}, {max}]"),
        ConstConstraint::RangeF64 { min, max } => format!("in [{min}, {max}]"),
        ConstConstraint::AllowedU64(allowed) => format!("one of {allowed:?}"),
        ConstConstraint::NonZeroU64 => "non-zero".into(),
        ConstConstraint::NonEmptyStr => "non-empty".into(),
        ConstConstraint::StrParser(_) => "accepted by the port's parser".into(),
        ConstConstraint::PositiveFiniteF64 => "positive and finite".into(),
        ConstConstraint::FiniteF64 => "finite".into(),
    }
}

/// Whether two constraints state the same condition. A parser
/// constraint equals another only when both name the same function.
pub fn same_constraint(a: &ConstConstraint, b: &ConstConstraint) -> bool {
    use ConstConstraint as C;
    match (a, b) {
        (C::RangeU64 { min: a0, max: a1 }, C::RangeU64 { min: b0, max: b1 }) => {
            a0 == b0 && a1 == b1
        }
        (C::RangeF64 { min: a0, max: a1 }, C::RangeF64 { min: b0, max: b1 }) => {
            a0.to_bits() == b0.to_bits() && a1.to_bits() == b1.to_bits()
        }
        (C::AllowedU64(a), C::AllowedU64(b)) => a == b,
        (C::StrParser(a), C::StrParser(b)) => std::ptr::fn_addr_eq(*a, *b),
        (C::NonZeroU64, C::NonZeroU64)
        | (C::NonEmptyStr, C::NonEmptyStr)
        | (C::PositiveFiniteF64, C::PositiveFiniteF64)
        | (C::FiniteF64, C::FiniteF64) => true,
        _ => false,
    }
}

/// Construct the right type assertion node for a given `PortType`.
/// The compiler inserts none: a resolved wire's type is the sink
/// port's type (graph_compiler.md §2).
pub fn assert_type_node(typ: PortType) -> Box<dyn PolydatNode> {
    Box::new(AssertType::new(typ))
}

/// Construct a value assertion node for the given (type, constraint) pair.
pub fn assert_value_node(typ: PortType, constraint: ConstConstraint) -> Box<dyn PolydatNode> {
    Box::new(AssertValue::new(typ, constraint))
}

// =========================================================================
// Tests
// =========================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn assert_u64_passes_u64_through() {
        let node = AssertType::new(PortType::U64);
        let mut out = [Value::None];
        node.eval(&[Value::U64(42)], &mut out);
        assert_eq!(out[0].as_u64(), 42);
    }

    #[test]
    #[should_panic(expected = "expected runtime value of type U64")]
    fn assert_u64_panics_on_string() {
        let node = AssertType::new(PortType::U64);
        let mut out = [Value::None];
        node.eval(&[Value::Str("not a number".into())], &mut out);
    }

    #[test]
    fn assert_value_nonzero_passes_nonzero() {
        let node = AssertValue::new(PortType::U64, ConstConstraint::NonZeroU64);
        let mut out = [Value::None];
        node.eval(&[Value::U64(7)], &mut out);
        assert_eq!(out[0].as_u64(), 7);
    }

    #[test]
    #[should_panic(expected = "must be non-zero")]
    fn assert_value_nonzero_panics_on_zero() {
        let node = AssertValue::new(PortType::U64, ConstConstraint::NonZeroU64);
        let mut out = [Value::None];
        node.eval(&[Value::U64(0)], &mut out);
    }

    #[test]
    fn assert_value_range_f64_passes_unit_interval() {
        let node = AssertValue::new(
            PortType::F64,
            ConstConstraint::RangeF64 { min: 0.0, max: 1.0 },
        );
        let mut out = [Value::None];
        node.eval(&[Value::F64(0.5)], &mut out);
        assert_eq!(out[0].as_f64(), 0.5);
    }

    #[test]
    #[should_panic(expected = "must be in [0, 1]")]
    fn assert_value_range_f64_panics_on_out_of_range() {
        let node = AssertValue::new(
            PortType::F64,
            ConstConstraint::RangeF64 { min: 0.0, max: 1.0 },
        );
        let mut out = [Value::None];
        node.eval(&[Value::F64(1.5)], &mut out);
    }
}