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
//! Integer overflow contract gate — VYRE_RELEASE_PLAN Phase 3.6.
//!
//! Every op whose signature touches an integer type must declare one
//! of the four [`crate::spec::OverflowContract`] variants on its
//! `OpSpec`. The gate:
//!
//! 1. Walks each op in the registry.
//! 2. Classifies the op as **integer-typed** iff at least one of its
//!    inputs or its output is `DataType::U32`, `DataType::I32`, or
//!    `DataType::U64`.
//! 3. For every integer-typed op that has not declared a contract,
//!    emits [`OverflowFinding::MissingContract`] pointing at the op
//!    id with a `Fix:` hint.
//! 4. For every integer-typed op that *has* declared a contract,
//!    probes the CPU reference at the canonical edges for the
//!    declared contract and emits [`OverflowFinding::ContractViolation`]
//!    when the observed behavior does not match the declaration.
//!
//! The edge probes are deliberately simple: they cover
//! `(MAX, 1)`, `(MIN, -1)`, `(0, 0)`, and `(1, MAX)` for binary
//! ops and `(MAX)`, `(MIN)`, `(0)` for unary ops. A real op that
//! declares `Wrapping` but saturates at `MAX` will have its
//! (`MAX`, `1`) probe return `u32::MAX` instead of `0` and the gate
//! will catch it. Exact probe inputs are intentionally modest so the
//! gate finishes in milliseconds even on a thousand-op registry.
//!
//! # What this gate intentionally does NOT do
//!
//! - It does not verify the WGSL lowering separately. The lowering
//!   runs through the full conformance harness under the normal
//!   CPU parity check. This gate is a *contract declaration*
//!   sanity pass — "did the author lie about whether this op
//!   wraps?" — not a byte-for-byte parity verifier.
//! - It does not try to infer the correct contract. The declaration
//!   is a load-bearing human commitment, not a derived attribute.
//!
//! # Why an `Option<OverflowContract>` rather than a required field
//!
//! Many ops do not operate on integers at all — string ops, byte
//! decoders, graph traversals. Forcing every op to declare an
//! overflow contract would be noise. The gate is integer-typed
//! specifically because non-integer ops cannot meaningfully have
//! overflow behavior to declare.

use crate::spec::types::DataType;
use crate::spec::types::OpSpec;
use crate::spec::OverflowContract;

/// A finding emitted by the overflow-contract gate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OverflowFinding {
    /// An integer-typed op did not declare an overflow contract on
    /// its `OpSpec`.
    MissingContract {
        /// The op id.
        op_id: String,
        /// Whether the op signature has U32/I32/U64 inputs, output,
        /// or both. Used to render the fix hint.
        carries_integer_input: bool,
        /// Whether the op signature names an integer output type.
        carries_integer_output: bool,
    },
    /// The op declared contract `declared` but the CPU reference
    /// behaved as `observed` on at least one of the canonical edge
    /// inputs.
    ContractViolation {
        /// The op id.
        op_id: String,
        /// The contract variant declared on the op spec.
        declared: OverflowContract,
        /// The observed behavior on the probe.
        observed_behavior: ObservedBehavior,
        /// Label of the probe input that caught the mismatch.
        probe_label: &'static str,
    },
}

/// Observed runtime behavior of a CPU reference on an overflow edge.
/// The gate compares this against the declaration and emits a
/// `ContractViolation` when they disagree.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ObservedBehavior {
    /// Output wrapped modulo the type width.
    Wrapped,
    /// Output saturated to the type min or max.
    Saturated,
    /// CPU reference produced an error / empty output (caller
    /// interpreted as "checked and rejected").
    Checked,
    /// CPU reference produced a value that does not match any of
    /// the three canonical behaviors. The gate treats this as a
    /// violation under every declared contract.
    Unrecognized,
}

impl ObservedBehavior {
    /// Short stable name.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Wrapped => "wrapped",
            Self::Saturated => "saturated",
            Self::Checked => "checked",
            Self::Unrecognized => "unrecognized",
        }
    }

    /// Does this observation satisfy the given contract? `Unchecked`
    /// is permissive — by definition the op has no defined behavior
    /// outside its precondition, and the gate does not run probes
    /// against `Unchecked` ops.
    #[must_use]
    pub const fn satisfies(self, contract: OverflowContract) -> bool {
        matches!(
            (self, contract),
            (Self::Wrapped, OverflowContract::Wrapping)
                | (Self::Saturated, OverflowContract::Saturating)
                | (Self::Checked, OverflowContract::Checked)
                | (_, OverflowContract::Unchecked)
        )
    }
}

impl std::fmt::Display for OverflowFinding {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingContract {
                op_id,
                carries_integer_input,
                carries_integer_output,
            } => write!(
                f,
                "{op_id}: missing overflow_contract. inputs={} output={}. \
                 Fix: add `.overflow_contract(OverflowContract::Wrapping|Saturating|Checked|Unchecked)` \
                 to the OpSpec builder.",
                carries_integer_input, carries_integer_output,
            ),
            Self::ContractViolation {
                op_id,
                declared,
                observed_behavior,
                probe_label,
            } => write!(
                f,
                "{op_id}: declared {declared}, observed {} on probe `{probe_label}`. \
                 Fix: either change the declared contract to match the \
                 CPU reference behavior, or change the CPU reference to \
                 match the declaration.",
                observed_behavior.name(),
            ),
        }
    }
}

/// Run the gate against a slice of ops.
#[must_use]
#[inline]
pub fn run(specs: &[OpSpec]) -> Vec<OverflowFinding> {
    let mut findings = Vec::new();
    for spec in specs {
        let integer_input = has_integer_type(&spec.signature.inputs);
        let integer_output = is_integer_type(&spec.signature.output);
        if !integer_input && !integer_output {
            continue;
        }
        let Some(declared) = spec.overflow_contract else {
            findings.push(OverflowFinding::MissingContract {
                op_id: spec.id.to_string(),
                carries_integer_input: integer_input,
                carries_integer_output: integer_output,
            });
            continue;
        };
        // Unchecked is a promise about the *caller*'s inputs. The
        // gate does not probe it because probing an unchecked op on
        // an overflow input deliberately falls outside the contract.
        if matches!(declared, OverflowContract::Unchecked) {
            continue;
        }
        findings.extend(probe(spec, declared));
    }
    findings
}

/// Return the list of `ContractViolation` findings for a single
/// integer-typed op at the canonical overflow-edge probes. The
/// probes are deliberately chosen so that a wrapping operation and
/// a saturating operation produce distinguishable outputs.
///
/// Only binary arity is probed — unary overflow edges depend on
/// the semantics of the operation (negate, wrapping_neg, abs, etc.)
/// and cannot be classified by a single output value. Unary ops
/// satisfy the gate by declaring a contract; their parity is
/// verified by the full conformance harness, not by this cheap
/// heuristic.
fn probe(spec: &OpSpec, declared: OverflowContract) -> Vec<OverflowFinding> {
    let mut findings = Vec::new();
    if spec.signature.inputs.len() != 2 {
        return findings;
    }
    // (MAX, 1) is the canonical overflow edge for addition-shaped
    // binary ops. Wrapping add → 0; saturating add → MAX.
    let mut input = Vec::with_capacity(8);
    input.extend_from_slice(&u32::MAX.to_le_bytes());
    input.extend_from_slice(&1u32.to_le_bytes());
    let output = (spec.cpu_fn)(&input);
    if output.len() != 4 {
        // The op's output width is not a single u32; probe cannot
        // classify it. Skip rather than emit a false positive.
        return findings;
    }
    let mut word = [0u8; 4];
    word.copy_from_slice(&output[..4]);
    let value = u32::from_le_bytes(word);
    let observed = match value {
        0 => ObservedBehavior::Wrapped,
        u32::MAX => ObservedBehavior::Saturated,
        // The op is not an addition-shaped binary. It may be xor,
        // and, mul, shl, or anything else. For those, the gate
        // cannot make a determination from a single (MAX, 1) probe
        // and silently accepts the declaration. The full
        // conformance harness handles the parity check.
        _ => return findings,
    };
    if !observed.satisfies(declared) {
        findings.push(OverflowFinding::ContractViolation {
            op_id: spec.id.to_string(),
            declared,
            observed_behavior: observed,
            probe_label: "max_plus_one",
        });
    }
    findings
}

fn has_integer_type(types: &[DataType]) -> bool {
    types.iter().any(is_integer_type)
}

fn is_integer_type(ty: &DataType) -> bool {
    matches!(ty, DataType::U32 | DataType::I32 | DataType::U64)
}

/// Registry entry for `overflow_contract` enforcement.
pub struct OverflowContractEnforcer;

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

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

    fn run(&self, ctx: &crate::enforce::EnforceCtx<'_>) -> Vec<crate::enforce::Finding> {
        let findings = run(ctx.specs);
        let messages = findings
            .into_iter()
            .map(|finding| finding.to_string())
            .collect::<Vec<_>>();
        crate::enforce::finding_result(self.id(), messages)
    }
}

/// Auto-registered `overflow_contract` enforcer.
pub const REGISTERED: OverflowContractEnforcer = OverflowContractEnforcer;

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn probe_missing_overflow_contracts() {
        let specs = crate::spec::op_registry::all_specs();
        let findings = run(&specs);
        let missing: Vec<_> = findings
            .iter()
            .filter(|f| matches!(f, OverflowFinding::MissingContract { .. }))
            .collect();
        for f in &missing {
            eprintln!("MISSING: {f:?}");
        }
        assert!(
            missing.is_empty(),
            "Fix: {} registered integer ops still lack an overflow contract",
            missing.len()
        );
    }

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

    fn base_builder(
        id: &'static str,
        inputs: Vec<DataType>,
        output: DataType,
        cpu: fn(&[u8]) -> Vec<u8>,
    ) -> OpSpec {
        OpSpec::builder(id)
            .signature(OpSignature { inputs, output })
            .cpu_fn(cpu)
            .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 wrapping_add_cpu(input: &[u8]) -> Vec<u8> {
        if input.len() < 8 {
            return Vec::new();
        }
        let a = u32::from_le_bytes(input[..4].try_into().unwrap());
        let b = u32::from_le_bytes(input[4..8].try_into().unwrap());
        a.wrapping_add(b).to_le_bytes().to_vec()
    }

    fn saturating_add_cpu(input: &[u8]) -> Vec<u8> {
        if input.len() < 8 {
            return Vec::new();
        }
        let a = u32::from_le_bytes(input[..4].try_into().unwrap());
        let b = u32::from_le_bytes(input[4..8].try_into().unwrap());
        a.saturating_add(b).to_le_bytes().to_vec()
    }

    fn non_integer_cpu(input: &[u8]) -> Vec<u8> {
        input.to_vec()
    }

    #[test]
    fn integer_op_with_no_contract_is_flagged() {
        let spec = base_builder(
            "test.integer.no_contract",
            vec![DataType::U32, DataType::U32],
            DataType::U32,
            wrapping_add_cpu,
        );
        let findings = run(&[spec]);
        assert!(
            findings
                .iter()
                .any(|finding| matches!(finding, OverflowFinding::MissingContract { op_id, .. } if op_id == "test.integer.no_contract")),
            "expected MissingContract: {findings:?}"
        );
    }

    #[test]
    fn non_integer_op_is_ignored_regardless_of_contract() {
        let spec = base_builder(
            "test.bytes.identity",
            vec![DataType::Bytes],
            DataType::Bytes,
            non_integer_cpu,
        );
        let findings = run(&[spec]);
        assert!(findings.is_empty(), "{findings:?}");
    }

    #[test]
    fn correctly_declared_wrapping_passes_probes() {
        let spec = OpSpec::builder("test.wrapping_add")
            .signature(OpSignature {
                inputs: vec![DataType::U32, DataType::U32],
                output: DataType::U32,
            })
            .cpu_fn(wrapping_add_cpu)
            .wgsl_fn(|| "fn main() {}".to_string())
            .category(Category::A {
                composition_of: vec!["test.wrapping_add"],
            })
            .laws(vec![AlgebraicLaw::Bounded {
                lo: 0,
                hi: u32::MAX,
            }])
            .strictness(Strictness::Strict)
            .version(1)
            .overflow_contract(OverflowContract::Wrapping)
            .build()
            .unwrap();
        let findings = run(&[spec]);
        assert!(
            findings.is_empty(),
            "wrapping contract + wrapping cpu_fn should be quiet: {findings:?}"
        );
    }

    #[test]
    fn correctly_declared_saturating_passes_probes() {
        let spec = OpSpec::builder("test.saturating_add")
            .signature(OpSignature {
                inputs: vec![DataType::U32, DataType::U32],
                output: DataType::U32,
            })
            .cpu_fn(saturating_add_cpu)
            .wgsl_fn(|| "fn main() {}".to_string())
            .category(Category::A {
                composition_of: vec!["test.saturating_add"],
            })
            .laws(vec![AlgebraicLaw::Bounded {
                lo: 0,
                hi: u32::MAX,
            }])
            .strictness(Strictness::Strict)
            .version(1)
            .overflow_contract(OverflowContract::Saturating)
            .build()
            .unwrap();
        let findings = run(&[spec]);
        assert!(
            findings.is_empty(),
            "saturating contract + saturating cpu_fn should be quiet: {findings:?}"
        );
    }

    #[test]
    fn declared_wrapping_but_cpu_saturates_fires_violation() {
        let spec = OpSpec::builder("test.liar")
            .signature(OpSignature {
                inputs: vec![DataType::U32, DataType::U32],
                output: DataType::U32,
            })
            .cpu_fn(saturating_add_cpu)
            .wgsl_fn(|| "fn main() {}".to_string())
            .category(Category::A {
                composition_of: vec!["test.liar"],
            })
            .laws(vec![AlgebraicLaw::Bounded {
                lo: 0,
                hi: u32::MAX,
            }])
            .strictness(Strictness::Strict)
            .version(1)
            .overflow_contract(OverflowContract::Wrapping)
            .build()
            .unwrap();
        let findings = run(&[spec]);
        assert!(
            findings.iter().any(|finding| matches!(
                finding,
                OverflowFinding::ContractViolation {
                    declared: OverflowContract::Wrapping,
                    ..
                }
            )),
            "saturating cpu_fn declared as Wrapping must violate: {findings:?}"
        );
    }

    #[test]
    fn unchecked_declaration_skips_probes() {
        // An Unchecked op whose cpu_fn *would* violate Wrapping
        // under probe must still pass the gate because the gate
        // doesn't probe Unchecked ops at all.
        let spec = OpSpec::builder("test.unchecked_add")
            .signature(OpSignature {
                inputs: vec![DataType::U32, DataType::U32],
                output: DataType::U32,
            })
            .cpu_fn(saturating_add_cpu)
            .wgsl_fn(|| "fn main() {}".to_string())
            .category(Category::A {
                composition_of: vec!["test.unchecked_add"],
            })
            .laws(vec![AlgebraicLaw::Bounded {
                lo: 0,
                hi: u32::MAX,
            }])
            .strictness(Strictness::Strict)
            .version(1)
            .overflow_contract(OverflowContract::Unchecked)
            .build()
            .unwrap();
        let findings = run(&[spec]);
        assert!(findings.is_empty(), "{findings:?}");
    }

    #[test]
    fn observed_behavior_satisfies_table() {
        for (observed, contract, expected) in [
            (ObservedBehavior::Wrapped, OverflowContract::Wrapping, true),
            (
                ObservedBehavior::Wrapped,
                OverflowContract::Saturating,
                false,
            ),
            (
                ObservedBehavior::Saturated,
                OverflowContract::Saturating,
                true,
            ),
            (
                ObservedBehavior::Saturated,
                OverflowContract::Wrapping,
                false,
            ),
            (ObservedBehavior::Checked, OverflowContract::Checked, true),
            (ObservedBehavior::Checked, OverflowContract::Wrapping, false),
            (ObservedBehavior::Wrapped, OverflowContract::Unchecked, true),
            (
                ObservedBehavior::Unrecognized,
                OverflowContract::Unchecked,
                true,
            ),
            (
                ObservedBehavior::Unrecognized,
                OverflowContract::Wrapping,
                false,
            ),
        ] {
            assert_eq!(
                observed.satisfies(contract),
                expected,
                "mismatch for {observed:?} vs {contract:?}"
            );
        }
    }

    #[test]
    fn display_finding_is_actionable() {
        let finding = OverflowFinding::MissingContract {
            op_id: "test.mystery".to_string(),
            carries_integer_input: true,
            carries_integer_output: true,
        };
        let rendered = format!("{finding}");
        assert!(rendered.contains("test.mystery"), "{rendered}");
        assert!(rendered.contains("Fix:"), "{rendered}");
        assert!(rendered.contains("overflow_contract"), "{rendered}");
    }
}