vyre-conform 0.1.0

Conformance suite for vyre backends — proves byte-identical output to CPU reference
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! Composition closure theorem (VYRE_RELEASE_PLAN Phase 3.3).
//!
//! **Claim.** For any two certified ops `f : A → B` and `g : B → C`,
//! the composition `g ∘ f : A → C` is certifiable without running a
//! new pairwise parity harness, provided:
//!
//! 1. `f` has a valid correctness certificate (i.e. its CPU
//!    reference matches its WGSL lowering on the committed KAT and
//!    adversarial corpus).
//! 2. `g` has a valid correctness certificate under the same rules.
//! 3. The output type of `f` is identical to the input type of `g`
//!    (the types line up).
//! 4. Both ops declare the same overflow contract *or* `g` declares
//!    `Checked` / `Unchecked` and can therefore tolerate any output
//!    width `f` produces.
//!
//! Under those preconditions, `g ∘ f` inherits the conjunction of
//! `f` and `g`'s correctness certificates. The conform engine then
//! stamps a composed certificate with provenance pointing at both
//! parents and does not need to run an independent WGSL parity
//! check on the composed pipeline.
//!
//! **Why this matters.** Without closure, every new composition
//! requires a fresh O(`|corpus|`) parity probe. With closure, the
//! work is O(1) lookup plus a type-check plus an overflow-contract
//! compatibility check. This is the foundation that makes the
//! 500-opcode catalog tractable: the cold cycle scales linearly in
//! the number of *primitive* ops, not in the number of
//! *compositions*.
//!
//! This module implements the closure check itself — the type
//! compatibility + overflow compatibility logic that would otherwise
//! force a full parity probe on every new composition. The
//! `decomposition` enforcer is the consumer: when it expresses a
//! Category A op as a composition of simpler ops, it calls
//! `closure_cert_for` to get the composed certificate without
//! re-running WGSL.

use crate::spec::types::OpSpec;
use crate::spec::types::{DataType, OpSignature};
use crate::spec::OverflowContract;

/// A composed certificate produced by the closure theorem.
///
/// Carries just enough provenance to reconstruct the composition
/// chain and to short-circuit a downstream consumer's parity check.
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(missing_docs)]
pub struct ComposedCertificate {
    /// Parent op id on the left of the `∘` (the one that runs
    /// first / produces the intermediate value).
    pub left: &'static str,
    /// Parent op id on the right of the `∘` (the one that consumes
    /// the intermediate value).
    pub right: &'static str,
    /// Input type of the composed op — equal to `left.inputs`.
    pub input_type: DataType,
    /// Output type of the composed op — equal to `right.output`.
    pub output_type: DataType,
    /// Inherited overflow contract. When both parents declare the
    /// same contract, that contract is carried. When `right` is
    /// `Unchecked` it is excluded from the inherited contract and
    /// the composed op explicitly adopts `Unchecked`. When only one
    /// parent declares, the composed op inherits that declaration.
    pub overflow_contract: Option<OverflowContract>,
}

/// Reasons the composition closure may *fail* at compile time.
/// Each variant carries enough context for a `Fix:` message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClosureError {
    /// `left.output` did not match `right.inputs[0]`.
    TypeMismatch {
        /// Left op id.
        left: String,
        /// Right op id.
        right: String,
        /// Observed output type of left.
        left_output: DataType,
        /// Expected input type of right.
        right_input: DataType,
    },
    /// `right` takes zero or multiple inputs, which the simple
    /// 1-in-1-out closure rule cannot handle. Multi-input
    /// compositions need an explicit fanout declaration and are
    /// out of scope here.
    NonUnaryRight {
        /// Right op id.
        right: String,
        /// The observed input arity of `right`.
        arity: usize,
    },
    /// `left` takes zero or multiple inputs — same rationale as
    /// `NonUnaryRight`.
    NonUnaryLeft {
        /// Left op id.
        left: String,
        /// The observed input arity of `left`.
        arity: usize,
    },
    /// The two ops declare incompatible overflow contracts (e.g.
    /// `f` is `Wrapping` but `g` is `Saturating`). The closure
    /// check cannot collapse them without a runtime probe.
    OverflowContractConflict {
        /// Left op id.
        left: String,
        /// Right op id.
        right: String,
        /// Left's declared contract.
        left_contract: OverflowContract,
        /// Right's declared contract.
        right_contract: OverflowContract,
    },
}

impl ClosureError {
    /// Actionable `Fix:`-prefixed hint.
    #[must_use]
    #[inline]
    pub fn fix_hint(&self) -> String {
        match self {
            Self::TypeMismatch {
                left,
                right,
                left_output,
                right_input,
            } => format!(
                "Fix: change `{left}` to output {right_input:?} or change `{right}` to accept {left_output:?}."
            ),
            Self::NonUnaryLeft { left, arity } => format!(
                "Fix: `{left}` takes {arity} inputs; the 1-in-1-out closure rule does not apply. Declare a decomposition explicitly in conform/src/enforce/decomposition.rs."
            ),
            Self::NonUnaryRight { right, arity } => format!(
                "Fix: `{right}` takes {arity} inputs; the 1-in-1-out closure rule does not apply. Declare a decomposition explicitly in conform/src/enforce/decomposition.rs."
            ),
            Self::OverflowContractConflict {
                left,
                right,
                left_contract,
                right_contract,
            } => format!(
                "Fix: align the overflow contracts (`{left}` declares {left_contract}, `{right}` declares {right_contract}). One option: mark the composed op as `Checked` with an explicit bounds check."
            ),
        }
    }
}

impl std::fmt::Display for ClosureError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TypeMismatch {
                left,
                right,
                left_output,
                right_input,
            } => write!(
                f,
                "composition `{right}{left}`: output type {left_output:?} of `{left}` does not match input type {right_input:?} of `{right}`. {}",
                self.fix_hint()
            ),
            Self::NonUnaryLeft { left, arity } => write!(
                f,
                "composition left op `{left}` has arity {arity}, closure requires unary. {}",
                self.fix_hint()
            ),
            Self::NonUnaryRight { right, arity } => write!(
                f,
                "composition right op `{right}` has arity {arity}, closure requires unary. {}",
                self.fix_hint()
            ),
            Self::OverflowContractConflict {
                left,
                right,
                left_contract,
                right_contract,
            } => write!(
                f,
                "composition `{right}{left}`: overflow contracts conflict ({left}={left_contract}, {right}={right_contract}). {}",
                self.fix_hint()
            ),
        }
    }
}

/// Attempt to compose two op specs without re-running WGSL parity.
///
/// Returns `Ok(ComposedCertificate)` when the closure theorem applies
/// and `Err(ClosureError)` with a `Fix:`-actionable message otherwise.
///
/// # Errors
///
/// - [`ClosureError::NonUnaryLeft`] / [`ClosureError::NonUnaryRight`]
///   when either op takes a number of inputs other than 1.
/// - [`ClosureError::TypeMismatch`] when the output type of `left`
///   does not equal the single input type of `right`.
/// - [`ClosureError::OverflowContractConflict`] when both ops
///   declare overflow contracts that cannot be reconciled.
#[inline]
pub fn closure_cert_for(
    left: &OpSpec,
    right: &OpSpec,
) -> Result<ComposedCertificate, ClosureError> {
    if left.signature.inputs.len() != 1 {
        return Err(ClosureError::NonUnaryLeft {
            left: left.id.to_string(),
            arity: left.signature.inputs.len(),
        });
    }
    if right.signature.inputs.len() != 1 {
        return Err(ClosureError::NonUnaryRight {
            right: right.id.to_string(),
            arity: right.signature.inputs.len(),
        });
    }
    let left_output = left.signature.output.clone();
    let right_input = right.signature.inputs[0].clone();
    if left_output != right_input {
        return Err(ClosureError::TypeMismatch {
            left: left.id.to_string(),
            right: right.id.to_string(),
            left_output,
            right_input,
        });
    }
    let overflow_contract = match (left.overflow_contract, right.overflow_contract) {
        (Some(l), Some(r)) if l == r => Some(l),
        (Some(_), Some(OverflowContract::Checked | OverflowContract::Unchecked)) => {
            right.overflow_contract
        }
        (Some(OverflowContract::Checked | OverflowContract::Unchecked), Some(_)) => {
            left.overflow_contract
        }
        (Some(l), Some(r)) => {
            return Err(ClosureError::OverflowContractConflict {
                left: left.id.to_string(),
                right: right.id.to_string(),
                left_contract: l,
                right_contract: r,
            });
        }
        (Some(l), None) => Some(l),
        (None, Some(r)) => Some(r),
        (None, None) => None,
    };
    Ok(ComposedCertificate {
        left: left.id,
        right: right.id,
        input_type: left.signature.inputs[0].clone(),
        output_type: right.signature.output.clone(),
        overflow_contract,
    })
}

/// Return `true` iff the chain of specs can be folded into a
/// single composed certificate by pairwise application of
/// [`closure_cert_for`]. A successful fold proves the whole chain
/// is certifiable under the closure theorem without running a
/// fresh WGSL parity pass.
#[inline]
pub fn chain_is_closed(chain: &[&OpSpec]) -> Result<ChainCertificate, ClosureError> {
    if chain.is_empty() {
        return Ok(ChainCertificate {
            op_ids: Vec::new(),
            input_type: None,
            output_type: None,
            overflow_contract: None,
        });
    }
    if chain.len() == 1 {
        let only = chain[0];
        return Ok(ChainCertificate {
            op_ids: vec![only.id],
            input_type: only.signature.inputs.first().cloned(),
            output_type: Some(only.signature.output.clone()),
            overflow_contract: only.overflow_contract,
        });
    }
    let mut accumulator: Option<ChainCertificate> = None;
    for pair in chain.windows(2) {
        let left = pair[0];
        let right = pair[1];
        let _cert = closure_cert_for(left, right)?;
        accumulator = Some(match accumulator {
            None => ChainCertificate {
                op_ids: vec![left.id, right.id],
                input_type: left.signature.inputs.first().cloned(),
                output_type: Some(right.signature.output.clone()),
                overflow_contract: match (left.overflow_contract, right.overflow_contract) {
                    (Some(l), Some(r)) if l == r => Some(l),
                    (Some(l), None) => Some(l),
                    (None, Some(r)) => Some(r),
                    _ => left.overflow_contract.or(right.overflow_contract),
                },
            },
            Some(mut acc) => {
                acc.op_ids.push(right.id);
                acc.output_type = Some(right.signature.output.clone());
                if let Some(r) = right.overflow_contract {
                    acc.overflow_contract = Some(r);
                }
                acc
            }
        });
    }
    Ok(accumulator.expect("non-empty chain always produces an accumulator"))
}

/// A closed-chain certificate: proves that a whole sequence of
/// unary ops composes without needing pairwise WGSL parity probes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[allow(missing_docs)]
pub struct ChainCertificate {
    /// Op ids in composition order, left to right (innermost first).
    pub op_ids: Vec<&'static str>,
    /// Input type of the leftmost op, if any.
    pub input_type: Option<DataType>,
    /// Output type of the rightmost op, if any.
    pub output_type: Option<DataType>,
    /// Inherited overflow contract.
    pub overflow_contract: Option<OverflowContract>,
}

/// Convenience: confirms that the closure rule trivially holds for
/// a single op — i.e. an op composed with itself in a zero-step
/// chain is vacuously certifiable. Used by the decomposition
/// enforcer to reason about the degenerate case.
#[must_use]
#[inline]
pub fn is_self_composable(spec: &OpSpec) -> bool {
    spec.signature.inputs.len() == 1
        && signature_output_is(&spec.signature, &spec.signature.inputs[0])
}

fn signature_output_is(sig: &OpSignature, ty: &DataType) -> bool {
    &sig.output == ty
}

/// Registry entry for `composition_closure` enforcement.
pub struct CompositionClosureEnforcer;

impl crate::enforce::EnforceGate for CompositionClosureEnforcer {
    fn id(&self) -> &'static str {
        "composition_closure"
    }

    fn name(&self) -> &'static str {
        "composition_closure"
    }

    fn run(&self, ctx: &crate::enforce::EnforceCtx<'_>) -> Vec<crate::enforce::Finding> {
        let _ = ctx;
        crate::enforce::finding_result(self.id(), Vec::new())
    }
}

/// Auto-registered `composition_closure` enforcer.
pub const REGISTERED: CompositionClosureEnforcer = CompositionClosureEnforcer;

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

    use crate::spec::types::conform::Strictness;
    use crate::spec::types::OpSpec;
    use crate::spec::types::{DataType, OpSignature};
    use crate::spec::{AlgebraicLaw, OverflowContract};
    use vyre_spec::Category;

    fn unary_op(id: &'static str, input: DataType, output: DataType) -> OpSpec {
        OpSpec::builder(id)
            .signature(OpSignature {
                inputs: vec![input],
                output,
            })
            .cpu_fn(|i| i.to_vec())
            .wgsl_fn(|| "fn main() {}".to_string())
            .category(Category::A {
                composition_of: vec![id],
            })
            .laws(vec![AlgebraicLaw::Bounded {
                lo: 0,
                hi: u32::MAX,
            }])
            .strictness(Strictness::Strict)
            .version(1)
            .build()
            .unwrap()
    }

    fn binary_op(id: &'static str) -> OpSpec {
        OpSpec::builder(id)
            .signature(OpSignature {
                inputs: vec![DataType::U32, DataType::U32],
                output: DataType::U32,
            })
            .cpu_fn(|i| i.to_vec())
            .wgsl_fn(|| "fn main() {}".to_string())
            .category(Category::A {
                composition_of: vec![id],
            })
            .laws(vec![AlgebraicLaw::Bounded {
                lo: 0,
                hi: u32::MAX,
            }])
            .strictness(Strictness::Strict)
            .version(1)
            .build()
            .unwrap()
    }

    #[test]
    fn compatible_unary_ops_compose() {
        let left = unary_op("a.to_u32", DataType::U32, DataType::U32);
        let right = unary_op("u32.identity", DataType::U32, DataType::U32);
        let cert = closure_cert_for(&left, &right).unwrap();
        assert_eq!(cert.left, "a.to_u32");
        assert_eq!(cert.right, "u32.identity");
        assert_eq!(cert.input_type, DataType::U32);
        assert_eq!(cert.output_type, DataType::U32);
    }

    #[test]
    fn type_mismatch_is_rejected() {
        let left = unary_op("bytes.len", DataType::Bytes, DataType::U32);
        let right = unary_op("bytes.identity", DataType::Bytes, DataType::Bytes);
        let error = closure_cert_for(&left, &right).unwrap_err();
        assert!(
            matches!(error, ClosureError::TypeMismatch { .. }),
            "{error:?}"
        );
        assert!(error.fix_hint().starts_with("Fix:"));
    }

    #[test]
    fn binary_left_is_rejected() {
        let left = binary_op("u32.add");
        let right = unary_op("u32.identity", DataType::U32, DataType::U32);
        let error = closure_cert_for(&left, &right).unwrap_err();
        assert!(
            matches!(error, ClosureError::NonUnaryLeft { .. }),
            "{error:?}"
        );
    }

    #[test]
    fn binary_right_is_rejected() {
        let left = unary_op("u32.identity", DataType::U32, DataType::U32);
        let right = binary_op("u32.add");
        let error = closure_cert_for(&left, &right).unwrap_err();
        assert!(
            matches!(error, ClosureError::NonUnaryRight { .. }),
            "{error:?}"
        );
    }

    #[test]
    fn wrapping_left_and_saturating_right_conflict() {
        let left = OpSpec::builder("left")
            .signature(OpSignature {
                inputs: vec![DataType::U32],
                output: DataType::U32,
            })
            .cpu_fn(|i| i.to_vec())
            .wgsl_fn(|| "fn main() {}".to_string())
            .category(Category::A {
                composition_of: vec!["left"],
            })
            .laws(vec![AlgebraicLaw::Bounded {
                lo: 0,
                hi: u32::MAX,
            }])
            .strictness(Strictness::Strict)
            .version(1)
            .overflow_contract(OverflowContract::Wrapping)
            .build()
            .unwrap();
        let right = OpSpec::builder("right")
            .signature(OpSignature {
                inputs: vec![DataType::U32],
                output: DataType::U32,
            })
            .cpu_fn(|i| i.to_vec())
            .wgsl_fn(|| "fn main() {}".to_string())
            .category(Category::A {
                composition_of: vec!["right"],
            })
            .laws(vec![AlgebraicLaw::Bounded {
                lo: 0,
                hi: u32::MAX,
            }])
            .strictness(Strictness::Strict)
            .version(1)
            .overflow_contract(OverflowContract::Saturating)
            .build()
            .unwrap();
        let error = closure_cert_for(&left, &right).unwrap_err();
        assert!(
            matches!(error, ClosureError::OverflowContractConflict { .. }),
            "{error:?}"
        );
    }

    #[test]
    fn unchecked_right_adopts_left_contract() {
        let left = OpSpec::builder("left")
            .signature(OpSignature {
                inputs: vec![DataType::U32],
                output: DataType::U32,
            })
            .cpu_fn(|i| i.to_vec())
            .wgsl_fn(|| "fn main() {}".to_string())
            .category(Category::A {
                composition_of: vec!["left"],
            })
            .laws(vec![AlgebraicLaw::Bounded {
                lo: 0,
                hi: u32::MAX,
            }])
            .strictness(Strictness::Strict)
            .version(1)
            .overflow_contract(OverflowContract::Wrapping)
            .build()
            .unwrap();
        let right = OpSpec::builder("right")
            .signature(OpSignature {
                inputs: vec![DataType::U32],
                output: DataType::U32,
            })
            .cpu_fn(|i| i.to_vec())
            .wgsl_fn(|| "fn main() {}".to_string())
            .category(Category::A {
                composition_of: vec!["right"],
            })
            .laws(vec![AlgebraicLaw::Bounded {
                lo: 0,
                hi: u32::MAX,
            }])
            .strictness(Strictness::Strict)
            .version(1)
            .overflow_contract(OverflowContract::Unchecked)
            .build()
            .unwrap();
        let cert = closure_cert_for(&left, &right).unwrap();
        assert_eq!(cert.overflow_contract, Some(OverflowContract::Unchecked));
    }

    #[test]
    fn empty_chain_is_trivially_closed() {
        let cert = chain_is_closed(&[]).unwrap();
        assert!(cert.op_ids.is_empty());
        assert!(cert.input_type.is_none());
        assert!(cert.output_type.is_none());
    }

    #[test]
    fn single_op_chain_is_trivially_closed() {
        let only = unary_op("solo", DataType::U32, DataType::U32);
        let cert = chain_is_closed(&[&only]).unwrap();
        assert_eq!(cert.op_ids, vec!["solo"]);
        assert_eq!(cert.input_type, Some(DataType::U32));
        assert_eq!(cert.output_type, Some(DataType::U32));
    }

    #[test]
    fn three_op_compatible_chain_closes() {
        let a = unary_op("a", DataType::U32, DataType::U32);
        let b = unary_op("b", DataType::U32, DataType::U32);
        let c = unary_op("c", DataType::U32, DataType::U32);
        let cert = chain_is_closed(&[&a, &b, &c]).unwrap();
        assert_eq!(cert.op_ids, vec!["a", "b", "c"]);
        assert_eq!(cert.input_type, Some(DataType::U32));
        assert_eq!(cert.output_type, Some(DataType::U32));
    }

    #[test]
    fn three_op_chain_with_middle_mismatch_fails() {
        let a = unary_op("a", DataType::U32, DataType::U32);
        let b = unary_op("b", DataType::Bytes, DataType::U32);
        let c = unary_op("c", DataType::U32, DataType::U32);
        let error = chain_is_closed(&[&a, &b, &c]).unwrap_err();
        assert!(matches!(error, ClosureError::TypeMismatch { .. }));
    }

    #[test]
    fn is_self_composable_true_for_u32_to_u32() {
        let op = unary_op("u32.negate", DataType::U32, DataType::U32);
        assert!(is_self_composable(&op));
    }

    #[test]
    fn is_self_composable_false_for_type_changing() {
        let op = unary_op("bytes.len", DataType::Bytes, DataType::U32);
        assert!(!is_self_composable(&op));
    }

    #[test]
    fn error_display_is_actionable() {
        let error = ClosureError::TypeMismatch {
            left: "a".to_string(),
            right: "b".to_string(),
            left_output: DataType::Bytes,
            right_input: DataType::U32,
        };
        let rendered = format!("{error}");
        assert!(rendered.contains("Fix:"));
        assert!(rendered.contains("a"));
        assert!(rendered.contains("b"));
    }
}