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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! Typestate builder for complete operation specifications.
//!
//! `OpSpecBuilder` uses the typestate pattern to make missing required fields
//! a compile-time error. A caller that forgets `cpu_fn` or `wgsl_fn` simply
//! cannot call `build()`, which eliminates an entire class of runtime
//! configuration bugs from the op-authoring workflow.

use core::marker::PhantomData;

use crate::enforce::category::{Category, IntrinsicTable};
use crate::proof::comparator::ComparatorKind;
use crate::spec::types::{
    AltWgslSource, BoundaryValue, Convention, EquivalenceClass, OpSignature, OpSpec, Strictness,
};
use crate::spec::{
    AlgebraicLaw, ArchetypeRef, DeclaredLaw, MutationClass, OracleKind, SpecRow, Verification,
    Version,
};

/// Marker for an unset required `OpSpec` field.
///
/// Used as a type parameter default so that an `OpSpecBuilder` starts in an
/// incomplete state. The type parameter changes to `Present` only when the
/// corresponding setter is called.
pub struct Missing;

/// Marker for a set required `OpSpec` field.
///
/// When all seven required type parameters are `Present`, the `build` method
/// becomes available. This makes the builder a compile-time checklist.
pub struct Present;

/// Error returned when an `OpSpec` cannot be built because a required field
/// was not provided.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BuildError {
    /// A required field is missing.
    ///
    /// In practice this error is unreachable when the typestate builder is
    /// used correctly, because `build()` is only callable after all required
    /// fields have been set. It exists as a defensive fallback for internal
    /// conversions and future `build_unchecked` escape hatches.
    MissingField {
        /// Name of the missing field.
        field: &'static str,
    },
}

/// Builder that only exposes `build` after required semantic fields are set.
///
/// The generic parameters track which required fields have been supplied:
/// `Sig` for signature, `Cpu` for cpu_fn, `Wgsl` for wgsl_fn, `Cat` for
/// category, `Laws` for laws, `Strict` for strictness, and `Ver` for version.
/// All default to `Missing`. Once every required field is `Present`, the
/// `build()` and `expect()` methods become available.
pub struct OpSpecBuilder<
    Sig = Missing,
    Cpu = Missing,
    Wgsl = Missing,
    Cat = Missing,
    Laws = Missing,
    Strict = Missing,
    Ver = Missing,
> {
    id: &'static str,
    archetype: &'static str,
    signature: Option<OpSignature>,
    cpu_fn: Option<fn(&[u8]) -> Vec<u8>>,
    wgsl_fn: Option<fn() -> String>,
    category: Option<Category>,
    intrinsic_table: IntrinsicTable,
    laws: Option<Vec<AlgebraicLaw>>,
    strictness: Option<Strictness>,
    version: Option<u32>,
    alt_wgsl_fns: Vec<AltWgslSource>,
    declared_laws: Box<[DeclaredLaw]>,
    spec_table: &'static [SpecRow],
    archetypes: &'static [ArchetypeRef],
    mutation_sensitivity: &'static [MutationClass],
    oracle_override: Option<OracleKind>,
    since_version: Version,
    docs_path: &'static str,
    equivalence_classes: Vec<EquivalenceClass>,
    boundary_values: Vec<BoundaryValue>,
    comparator: ComparatorKind,
    convention: Convention,
    version_history: Vec<u32>,
    workgroup_size: Option<u32>,
    min_throughput_bytes_per_sec: Option<u64>,
    expected_output_bytes: Option<usize>,
    external_oracle_url: Option<&'static str>,
    property_invariants: &'static [&'static str],
    ir_program: Option<fn() -> vyre::ir::Program>,
    no_algebraic_laws_reason: Option<&'static str>,
    admission_witness_cap: Option<usize>,
    cpu_fingerprint: Option<u64>,
    overflow_contract: Option<crate::spec::types::OverflowContract>,
    _state: PhantomData<(Sig, Cpu, Wgsl, Cat, Laws, Strict, Ver)>,
}

impl OpSpecBuilder<Missing, Missing, Missing, Missing, Missing, Missing, Missing> {
    /// Start building a specification for a stable operation id.
    ///
    /// The `id` must be a dot-separated path such as `primitive.math.add`.
    /// It is used as the registry key, the documentation anchor, and the
    /// certificate subject, so it must be unique and immutable after the
    /// first commit.
    ///
    /// # Examples
    ///
    /// ```
    /// use vyre_conform::types::OpSpec;
    /// let builder = OpSpec::builder("primitive.math.add");
    /// ```
    #[inline]
    pub fn new(id: &'static str) -> Self {
        Self {
            id,
            archetype: "",
            signature: None,
            cpu_fn: None,
            wgsl_fn: None,
            category: None,
            intrinsic_table: IntrinsicTable::default(),
            laws: None,
            strictness: None,
            version: None,
            alt_wgsl_fns: Vec::new(),
            declared_laws: Box::new([]),
            spec_table: &[],
            archetypes: &[],
            mutation_sensitivity: &[],
            oracle_override: None,
            since_version: Version::V1_0,
            docs_path: "",
            equivalence_classes: Vec::new(),
            boundary_values: Vec::new(),
            comparator: ComparatorKind::ExactMatch,
            convention: Convention::V1,
            version_history: Vec::new(),
            workgroup_size: None,
            min_throughput_bytes_per_sec: None,
            expected_output_bytes: None,
            external_oracle_url: None,
            property_invariants: &[],
            ir_program: None,
            no_algebraic_laws_reason: None,
            admission_witness_cap: None,
            cpu_fingerprint: None,
            overflow_contract: None,
            _state: PhantomData,
        }
    }
}

impl<Sig, Cpu, Wgsl, Cat, Laws, Strict, Ver> OpSpecBuilder<Sig, Cpu, Wgsl, Cat, Laws, Strict, Ver> {
    fn convert<NextSig, NextCpu, NextWgsl, NextCat, NextLaws, NextStrict, NextVer>(
        self,
    ) -> OpSpecBuilder<NextSig, NextCpu, NextWgsl, NextCat, NextLaws, NextStrict, NextVer> {
        OpSpecBuilder {
            id: self.id,
            archetype: self.archetype,
            signature: self.signature,
            cpu_fn: self.cpu_fn,
            wgsl_fn: self.wgsl_fn,
            category: self.category,
            intrinsic_table: self.intrinsic_table,
            laws: self.laws,
            strictness: self.strictness,
            version: self.version,
            alt_wgsl_fns: self.alt_wgsl_fns,
            declared_laws: self.declared_laws,
            spec_table: self.spec_table,
            archetypes: self.archetypes,
            mutation_sensitivity: self.mutation_sensitivity,
            oracle_override: self.oracle_override,
            since_version: self.since_version,
            docs_path: self.docs_path,
            equivalence_classes: self.equivalence_classes,
            boundary_values: self.boundary_values,
            comparator: self.comparator,
            convention: self.convention,
            version_history: self.version_history,
            workgroup_size: self.workgroup_size,
            min_throughput_bytes_per_sec: self.min_throughput_bytes_per_sec,
            expected_output_bytes: self.expected_output_bytes,
            external_oracle_url: self.external_oracle_url,
            property_invariants: self.property_invariants,
            ir_program: self.ir_program,
            no_algebraic_laws_reason: self.no_algebraic_laws_reason,
            admission_witness_cap: self.admission_witness_cap,
            cpu_fingerprint: self.cpu_fingerprint,
            overflow_contract: self.overflow_contract,
            _state: PhantomData,
        }
    }

    /// Set the archetype from the locked vocabulary.
    ///
    /// The archetype string determines which structural test patterns are
    /// auto-generated for this op. Using a locked vocabulary prevents drift
    /// between the generator catalog and the op declarations.
    #[inline]
    pub fn archetype(mut self, archetype: &'static str) -> Self {
        self.archetype = archetype;
        self
    }

    /// Set the declared type signature.
    ///
    /// The signature is load-bearing: it determines how the conformance
    /// generator produces input bytes, how the CPU reference interprets them,
    /// and how the backend is expected to return output. A wrong signature
    /// makes every downstream gate meaningless.
    #[inline]
    pub fn signature(
        mut self,
        signature: OpSignature,
    ) -> OpSpecBuilder<Present, Cpu, Wgsl, Cat, Laws, Strict, Ver> {
        self.signature = Some(signature);
        self.convert()
    }

    /// Set the CPU reference function that defines operation semantics.
    ///
    /// The CPU reference is the ground truth against which every backend is
    /// judged. If the GPU output disagrees with this function on any
    /// witnessed input, the conform gate rejects the backend. The function
    /// must be deterministic, total on the declared input types, and
    /// independent of thread-local or global mutable state.
    #[inline]
    pub fn cpu_fn(
        mut self,
        cpu_fn: fn(&[u8]) -> Vec<u8>,
    ) -> OpSpecBuilder<Sig, Present, Wgsl, Cat, Laws, Strict, Ver> {
        self.cpu_fn = Some(cpu_fn);
        self.convert()
    }

    /// Set the canonical WGSL source generator.
    ///
    /// The returned WGSL is what the conform engine dispatches to the backend
    /// during parity tests. It must compile to valid WGSL and must implement
    /// exactly the semantics of `cpu_fn`. Any divergence between the two is
    /// a conform finding.
    #[inline]
    pub fn wgsl_fn(
        mut self,
        wgsl_fn: fn() -> String,
    ) -> OpSpecBuilder<Sig, Cpu, Present, Cat, Laws, Strict, Ver> {
        self.wgsl_fn = Some(wgsl_fn);
        self.convert()
    }

    /// Set the A/C category declaration.
    ///
    /// Category A means the op is a zero-overhead composition of primitives.
    /// Category C means it is a hardware intrinsic with no software fallback.
    /// The category determines which enforcers run and which budgets apply.
    #[inline]
    pub fn category(
        mut self,
        category: Category,
    ) -> OpSpecBuilder<Sig, Cpu, Wgsl, Present, Laws, Strict, Ver> {
        self.category = Some(category);
        self.convert()
    }

    /// Set the per-backend intrinsic spellings for Category C operations.
    ///
    /// Category A ops leave this at its default (empty). Category C ops must
    /// populate it so that the backend can map the stable op id to the
    /// backend-specific intrinsic name.
    #[inline]
    pub fn intrinsic_table(mut self, intrinsic_table: IntrinsicTable) -> Self {
        self.intrinsic_table = intrinsic_table;
        self
    }

    /// Set the declared algebraic laws.
    ///
    /// Laws are the structural proof that the op behaves as advertised. The
    /// algebra checker verifies each declared law exhaustively on small
    /// domains and with randomized witnesses on full domains. An op with no
    /// laws is uninstrumented — silent wrong answers have nowhere to surface.
    #[inline]
    pub fn laws(
        mut self,
        laws: Vec<AlgebraicLaw>,
    ) -> OpSpecBuilder<Sig, Cpu, Wgsl, Cat, Present, Strict, Ver> {
        self.laws = Some(laws);
        self.convert()
    }

    /// Set the exactness policy.
    ///
    /// `Strict` requires byte-identical output. `Approximate` allows a small
    /// ULP difference for floating-point ops. The comparator uses this policy
    /// when comparing GPU output against the CPU reference.
    #[inline]
    pub fn strictness(
        mut self,
        strictness: Strictness,
    ) -> OpSpecBuilder<Sig, Cpu, Wgsl, Cat, Laws, Present, Ver> {
        self.strictness = Some(strictness);
        self.convert()
    }

    /// Set the immutable behavior version.
    ///
    /// Once an op is published, its versioned semantics are frozen. Bumping
    /// this number signals a breaking change in behavior and forces every
    /// backend to re-certify against the new semantic fingerprint.
    #[inline]
    pub fn version(
        mut self,
        version: u32,
    ) -> OpSpecBuilder<Sig, Cpu, Wgsl, Cat, Laws, Strict, Present> {
        self.version = Some(version);
        self.convert()
    }

    /// Set alternative WGSL source generators.
    ///
    /// Alternative WGSL paths are used by backends that require a different
    /// spelling or calling convention while preserving the same observable
    /// semantics.
    #[inline]
    pub fn alt_wgsl_fns(mut self, alt_wgsl_fns: Vec<AltWgslSource>) -> Self {
        self.alt_wgsl_fns = alt_wgsl_fns;
        self
    }

    /// Declare the integer overflow contract for this op (plan 3.6).
    ///
    /// One of `Wrapping`, `Saturating`, `Checked`, or `Unchecked`. The
    /// `overflow_contract` gate requires this to be set for every op
    /// whose signature contains `DataType::U32`, `DataType::I32`, or
    /// `DataType::U64`. Ops that do not touch integer types may leave
    /// this unset.
    #[inline]
    pub fn overflow_contract(mut self, contract: crate::spec::types::OverflowContract) -> Self {
        self.overflow_contract = Some(contract);
        self
    }

    /// Set proof-aware law declarations.
    ///
    /// `declared_laws` attaches a verification strategy to each law. If
    /// none are supplied, the builder auto-derives them from `laws` with
    /// a baseline `ExhaustiveU8` strategy.
    #[inline]
    pub fn declared_laws(mut self, declared_laws: impl Into<Box<[DeclaredLaw]>>) -> Self {
        self.declared_laws = declared_laws.into();
        self
    }

    /// Set concrete spec-table rows.
    ///
    /// Spec-table rows are hand-curated known-answer tests. They are cheap
    /// to run and serve as the first line of defense against regressions.
    #[inline]
    pub fn spec_table(mut self, spec_table: &'static [SpecRow]) -> Self {
        self.spec_table = spec_table;
        self
    }

    /// Set archetype identifiers for generated coverage.
    ///
    /// Archetypes tell the generator which adversarial patterns to apply.
    /// Common archetypes include `boundary`, `identity`, and `commutative_swap`.
    #[inline]
    pub fn archetypes(mut self, archetypes: &'static [ArchetypeRef]) -> Self {
        self.archetypes = archetypes;
        self
    }

    /// Set mutation classes that operation tests should detect.
    ///
    /// Mutation classes define the adversarial defects that the conformance
    /// suite is expected to catch. If a mutation survives undetected, the
    /// suite grade is reduced and the op cannot be certified.
    #[inline]
    pub fn mutation_sensitivity(mut self, mutation_sensitivity: &'static [MutationClass]) -> Self {
        self.mutation_sensitivity = mutation_sensitivity;
        self
    }

    /// Override the default oracle selection for this operation.
    ///
    /// By default the conform engine uses the CPU reference oracle. Some ops
    /// (e.g. composition chains) may legitimately override this to use the
    /// law oracle or an external reference.
    #[inline]
    pub fn oracle_override(mut self, oracle_override: Option<OracleKind>) -> Self {
        self.oracle_override = oracle_override;
        self
    }

    /// Set the semantic schema version this operation was introduced in.
    ///
    /// `since_version` is checked by the stability gate: an op cannot claim
    /// to have shipped in a future schema version. New ops should use
    /// `CURRENT_VERSION`.
    #[inline]
    pub fn since_version(mut self, since_version: Version) -> Self {
        self.since_version = since_version;
        self
    }

    /// Set the repository-relative documentation path for this operation.
    ///
    /// The docs path is used by the coverage report and the book generator
    /// to link from the registry to human-readable operation documentation.
    #[inline]
    pub fn docs_path(mut self, docs_path: &'static str) -> Self {
        self.docs_path = docs_path;
        self
    }

    /// Set input equivalence classes.
    ///
    /// Equivalence classes partition the input space into regions that
    /// should exercise different code paths. The generator samples from
    /// each class to maximize coverage without exhaustive enumeration.
    #[inline]
    pub fn equivalence_classes(mut self, equivalence_classes: Vec<EquivalenceClass>) -> Self {
        self.equivalence_classes = equivalence_classes;
        self
    }

    /// Set explicit boundary values.
    ///
    /// Boundary values are deterministic inputs that sit at the edges of
    /// the type domain: `0`, `1`, `u32::MAX`, `u32::MAX - 1`, etc. They
    /// catch off-by-one errors and truncation bugs that random sampling
    /// might miss.
    #[inline]
    pub fn boundary_values(mut self, boundary_values: Vec<BoundaryValue>) -> Self {
        self.boundary_values = boundary_values;
        self
    }

    /// Set the output comparator.
    ///
    /// The comparator determines how GPU output is compared against the CPU
    /// reference. `ExactMatch` is the default and should be used for every
    /// non-floating-point op.
    #[inline]
    pub fn comparator(mut self, comparator: ComparatorKind) -> Self {
        self.comparator = comparator;
        self
    }

    /// Set the calling convention.
    ///
    /// The convention determines buffer layout, binding numbers, and the
    /// shape of the dispatch wrapper. `V1` is the stable convention; later
    /// versions may add lookup tables or additional bindings.
    #[inline]
    pub fn convention(mut self, convention: Convention) -> Self {
        self.convention = convention;
        self
    }

    /// Set previous published versions.
    ///
    /// Version history is used by the compatibility gate to ensure that
    /// backwards-compatible changes do not break existing certificates.
    #[inline]
    pub fn version_history(mut self, version_history: Vec<u32>) -> Self {
        self.version_history = version_history;
        self
    }

    /// Set the preferred conformance workgroup size.
    ///
    /// The determinism enforcer uses this to clamp the workgroup sizes it
    /// tests. If unset, the enforcer probes up to 1024 threads.
    #[inline]
    pub fn workgroup_size(mut self, workgroup_size: Option<u32>) -> Self {
        self.workgroup_size = workgroup_size;
        self
    }

    /// Set the minimum throughput requirement.
    ///
    /// The cost-certificate gate compares measured dispatch time against
    /// this budget. A backend that is correct but too slow still fails
    /// conformance.
    #[inline]
    pub fn min_throughput_bytes_per_sec(
        mut self,
        min_throughput_bytes_per_sec: Option<u64>,
    ) -> Self {
        self.min_throughput_bytes_per_sec = min_throughput_bytes_per_sec;
        self
    }

    /// Set the expected output byte size for a single invocation.
    ///
    /// This is used by the admission gate to validate that the CPU reference
    /// produces output of a reasonable size for the declared signature.
    #[inline]
    pub fn expected_output_bytes(mut self, expected_output_bytes: Option<usize>) -> Self {
        self.expected_output_bytes = expected_output_bytes;
        self
    }

    /// Set the external oracle URL.
    ///
    /// An external oracle points to an independent implementation or
    /// specification document that serves as an additional source of truth
    /// for the conform engine.
    #[inline]
    pub fn external_oracle_url(mut self, url: Option<&'static str>) -> Self {
        self.external_oracle_url = url;
        self
    }

    /// Set the declared property invariants.
    ///
    /// Property invariants are natural-language assertions that the op
    /// satisfies properties not expressible as algebraic laws. They are
    /// checked by the property-test gate.
    #[inline]
    pub fn property_invariants(mut self, invariants: &'static [&'static str]) -> Self {
        self.property_invariants = invariants;
        self
    }

    /// Set the optional IR program for the reference interpreter oracle.
    ///
    /// When supplied, the reference interpreter oracle runs this IR program
    /// as an independent computation of expected output. It is especially
    /// useful for ops that are easier to express in vyre IR than in raw
    /// byte manipulation.
    #[inline]
    pub fn ir_program(mut self, program: Option<fn() -> vyre::ir::Program>) -> Self {
        self.ir_program = program;
        self
    }

    /// Set the justification for declaring no algebraic laws.
    ///
    /// An op with zero laws is allowed only when it provides a human-readable
    /// explanation of why laws do not apply (e.g. "behavior is defined by a
    /// complex finite-state machine that has no simple algebraic closure").
    #[inline]
    pub fn no_algebraic_laws_reason(mut self, reason: Option<&'static str>) -> Self {
        self.no_algebraic_laws_reason = reason;
        self
    }

    /// Set the per-spec override for the gate-4 witness cap.
    ///
    /// Gate 4 (deterministic semantics) generates inputs until it hits this
    /// cap. Category A ops default to `u32::MAX` (effectively unbounded),
    /// while other categories default to 10 000. This setter allows an op
    /// to declare a tighter bound when its generator is especially prolific.
    #[inline]
    pub fn admission_witness_cap(mut self, cap: Option<usize>) -> Self {
        self.admission_witness_cap = cap;
        self
    }

    /// Set the declared CPU fingerprint for gate-5 verification.
    ///
    /// The CPU fingerprint is a deterministic hash of the CPU reference
    /// function on a canonical input set. It catches accidental edits to
    /// the reference function that the author did not intend to commit.
    #[inline]
    pub fn cpu_fingerprint(mut self, fingerprint: Option<u64>) -> Self {
        self.cpu_fingerprint = fingerprint;
        self
    }
}

impl OpSpecBuilder<Present, Present, Present, Present, Present, Present, Present> {
    /// Finish a complete operation spec, panicking if a required field is missing.
    ///
    /// This is infallible in practice because the typestate builder ensures all
    /// required fields are present before this method becomes callable. It is
    /// a convenience for test code and const contexts that prefer an unwrap-like
    /// API over explicit error handling.
    ///
    /// # Panics
    ///
    /// Panics only if `build()` returns `Err`, which is structurally impossible
    /// when the typestate parameters are all `Present`.
    #[inline]
    pub fn expect(self, msg: &str) -> OpSpec {
        self.build().expect(msg)
    }

    /// Finish a complete operation spec.
    ///
    /// Returns `Ok(OpSpec)` when all required fields are present. Because the
    /// typestate builder makes missing fields a compile-time error, this
    /// function is effectively infallible for well-typed callers.
    ///
    /// # Errors
    ///
    /// Returns `Err(BuildError::MissingField)` only when a required field is
    /// `None`. In normal usage this cannot happen because the typestate
    /// parameters guarantee presence.
    #[inline]
    pub fn build(self) -> Result<OpSpec, BuildError> {
        let signature = self
            .signature
            .ok_or(BuildError::MissingField { field: "signature" })?;
        let cpu_fn = self
            .cpu_fn
            .ok_or(BuildError::MissingField { field: "cpu_fn" })?;
        let laws = self
            .laws
            .ok_or(BuildError::MissingField { field: "laws" })?;
        // Auto-derive declared_laws from laws when none are explicitly set.
        // Each law gets ExhaustiveU8 verification as a baseline. Specs that
        // need stronger provenance (WitnessedU32, ExhaustiveU16) should set
        // declared_laws explicitly.
        let declared_laws = if self.declared_laws.is_empty() && !laws.is_empty() {
            laws.iter()
                .map(|law| DeclaredLaw {
                    law: law.clone(),
                    verified_by: Verification::ExhaustiveU8,
                })
                .collect::<Vec<_>>()
                .into_boxed_slice()
        } else {
            self.declared_laws
        };
        Ok(OpSpec {
            id: self.id,
            archetype: self.archetype,
            category: self
                .category
                .ok_or(BuildError::MissingField { field: "category" })?,
            intrinsic_table: self.intrinsic_table,
            signature,
            strictness: self.strictness.ok_or(BuildError::MissingField {
                field: "strictness",
            })?,
            cpu_fn,
            wgsl_fn: self
                .wgsl_fn
                .ok_or(BuildError::MissingField { field: "wgsl_fn" })?,
            alt_wgsl_fns: self.alt_wgsl_fns,
            laws,
            declared_laws,
            spec_table: self.spec_table,
            archetypes: self.archetypes,
            mutation_sensitivity: self.mutation_sensitivity,
            oracle_override: self.oracle_override,
            since_version: self.since_version,
            docs_path: self.docs_path,
            equivalence_classes: self.equivalence_classes,
            boundary_values: self.boundary_values,
            comparator: self.comparator,
            convention: self.convention,
            version: self
                .version
                .ok_or(BuildError::MissingField { field: "version" })?,
            version_history: self.version_history,
            workgroup_size: self.workgroup_size,
            min_throughput_bytes_per_sec: self.min_throughput_bytes_per_sec,
            expected_output_bytes: self.expected_output_bytes,
            external_oracle_url: self.external_oracle_url,
            property_invariants: self.property_invariants,
            ir_program: self.ir_program,
            no_algebraic_laws_reason: self.no_algebraic_laws_reason,
            admission_witness_cap: self.admission_witness_cap,
            cpu_fingerprint: self.cpu_fingerprint,
            overflow_contract: self.overflow_contract,
        })
    }
}