xpile-backend 0.1.37

Backend trait — every target language (Rust, Ruchy, PTX, WGSL, SPIR-V, Lean) implements this.
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
//! Backend trait — code-lane emission abstraction.
//!
//! Every target language in xpile (Rust, Ruchy, PTX, WGSL, SPIR-V, Lean)
//! provides one type implementing [`Backend`]. The trait is intentionally
//! narrow: take meta-HIR and a config, return an [`Artifact`].
//!
//! Sibling of `xpile-frontend::Frontend`. Architectural invariants
//! codified in `contracts/xpile-backend-trait-v1.yaml`.

use serde::{Deserialize, Serialize};
use xpile_contracts::ContractId;
use xpile_meta_hir::Module;

/// Target language a backend can emit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Target {
    /// Idiomatic Rust source. Implemented by `xpile-rust-codegen`.
    Rust,
    /// Ruchy source. Implemented by `xpile-ruchy-codegen`.
    Ruchy,
    /// NVIDIA PTX text. Implemented by `xpile-ptx-codegen`.
    Ptx,
    /// WebGPU Shading Language. Implemented by `xpile-wgsl-codegen`.
    Wgsl,
    /// SPIR-V text or binary. Implemented by `xpile-spirv-codegen` (future).
    Spirv,
    /// Lean 4 executable code (def, partial def, inductive, ...).
    /// Implemented by `xpile-lean-codegen`. The proof-lane Lean (theorems)
    /// goes through `xpile-lean-contract-backend` instead.
    Lean,
    /// POSIX shell (sh / bash / zsh) — the bashrs merger domain.
    /// Implemented by `bashrs-backend` (scaffold at v0.1.0; full emit
    /// at v0.2.0 once the bashrs source folding lands). PMAT-037 /
    /// XPILE-BASHRS-MERGER-001. See `sub/bashrs-merger.md` Layer A.
    Shell,
}

/// Lowering profile — the two-mHIR asymmetric decision for Rust↔Ruchy.
///
/// See `docs/specifications/sub/bidirectional-ruchy.md` (planned).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Profile {
    /// meta-HIR normalized for Rust emission (default for most targets).
    RustOut,
    /// meta-HIR normalized for Ruchy emission (pipeline operator
    /// reconstructed at emission time).
    RuchyOut,
}

/// Hardware profile for targets whose emission depends on hardware
/// capabilities (PTX `compute_capability`, WGSL feature set, SPIR-V version).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum HwProfile {
    Ptx {
        /// e.g., "sm_80", "sm_89", "sm_90".
        compute_capability: String,
    },
    Wgsl {
        /// e.g., ["timestamp-query", "f16"].
        features: Vec<String>,
    },
    Spirv {
        version: (u32, u32),
    },
}

/// Configuration passed to [`Backend::lower`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BackendConfig {
    pub target: Target,
    pub profile: Profile,
    pub hardware: Option<HwProfile>,
}

/// Emitted artifact — primary source/IR text plus sidecar files plus
/// the structural citation chain to Layer-5 compile contracts.
///
/// The `citations` field is the structural channel that closes the
/// audit chain: every target-specific IR construct in `primary` cites
/// a Layer-5 compile contract by ID. Recovery is via this field, NOT
/// via regex over `primary` text. See
/// `contracts/xpile-backend-trait-v1.yaml` equation `compile_contract_citation`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Artifact {
    /// Emitted source / IR text (Rust source, Ruchy source, PTX text,
    /// WGSL source, SPIR-V text, Lean source).
    pub primary: String,
    /// Optional binaries, manifests, debug maps, accompanying the primary.
    pub sidecars: Vec<(String, Vec<u8>)>,
    /// Layer-5 compile contracts sanctioning every target-specific
    /// construct in `primary`. Structural — not regex-recoverable.
    pub citations: Vec<ContractId>,
    /// Multi-emitter quorum status (PMAT-262 / Section 29). At v0.1.0
    /// every Backend impl emits exactly one artifact, so this is always
    /// `QuorumStatus::Single { emitter: <backend_name> }`. Multi-emitter
    /// backends (future rustc_codegen_nvvm + aprender-gpu quorum on PTX)
    /// populate `QuorumStatus::Multi { ... }` with the diff_exec result.
    ///
    /// Defaults via serde to `Single { emitter: "unknown" }` for
    /// backward-compatible deserialization of older JSON payloads.
    #[serde(default = "default_quorum_status")]
    pub quorum_status: QuorumStatus,
}

fn default_quorum_status() -> QuorumStatus {
    QuorumStatus::Single {
        emitter: "unknown".to_string(),
    }
}

#[derive(Debug, thiserror::Error)]
pub enum BackendError {
    #[error("unsupported target: {0:?}")]
    UnsupportedTarget(Target),
    #[error("missing hardware profile for target {0:?}")]
    MissingHardware(Target),
    #[error("lowering error: {0}")]
    Lower(String),
    #[error("compile-contract citation missing for emitted construct: {0}")]
    MissingCompileContractCitation(String),
}

/// Code-lane emission trait. See `docs/specifications/sub/backend-trait.md`.
pub trait Backend: Send + Sync {
    /// Human-readable backend name, e.g. "rust", "ptx", "wgsl".
    fn name(&self) -> &'static str;

    /// Targets this backend can emit. Each [`Target`] variant is
    /// owned by exactly one Backend impl (`target_ownership` invariant).
    fn targets(&self) -> &[Target];

    /// Lower a meta-HIR module under the given config to an [`Artifact`].
    ///
    /// Invariants: deterministic per `(module, config)`; frame-pure
    /// (no mutation of inputs); every target-specific IR construct
    /// in `Artifact.primary` cited via `Artifact.citations`.
    fn lower(&self, module: &Module, config: &BackendConfig) -> Result<Artifact, BackendError>;
}

// ─── PMAT-261 / Section 29: Multi-emitter quorum scaffolding ────────────
//
// Types codifying the design in
// `docs/specifications/sub/layer5-multi-emitter-quorum.md`. Pure
// scaffolding at PMAT-261 — no Backend impl yet uses these. Future PRs
// (rustc_codegen_nvvm wiring, aprender-gpu bridge, DiffExec engine)
// build against this stable API surface.

/// Role of a backend emitter within a multi-emitter quorum.
///
/// `compile_targets.via.role` in the YAML schema corresponds to this
/// enum. At most one `General` per quorum (the mandatory fallback);
/// any number of `Specialist` (each with its own `shape_filter`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EmitterRole {
    /// Handles any contract-conforming input. Mandatory fallback —
    /// `pv lint` (post-PMAT-262) will require at least one `General`
    /// emitter per Layer-5 contract's `compile_targets.via`.
    /// Examples: `rustc_codegen_nvvm` (PTX), `naga` (WGSL),
    /// `rspirv` (SPIR-V).
    General,
    /// Handles a domain-specific subset via hand-tuned templates.
    /// Optional — degrades gracefully to single-emitter when missing.
    /// Examples: `aprender-gpu` (GEMM/MMA PTX kernels),
    /// `bashrs-realistic` (corpus-tuned POSIX patterns).
    Specialist,
}

/// Policy for combining outputs when both General and Specialist
/// emitters fire on the same input. Configured per Layer-5 contract
/// via `compile_targets.quorum_policy` in the YAML.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum QuorumPolicy {
    /// If the specialist handles the kernel, use its output. Falls
    /// back to general otherwise. Single-vote Runtime stratum.
    PreferSpecialist,
    /// Emit via BOTH, run BOTH on test inputs, compare numerical
    /// outputs within tolerance. Multi-vote Runtime stratum.
    /// **Falsifies the contract on divergence** — this is the
    /// stratum-upgrading policy that closes the §4 "Run=1 demo
    /// fixture" caveat from audit-design.md.
    DiffExec {
        /// Maximum allowed absolute difference between corresponding
        /// numerical outputs of the two emitters.
        tolerance: f64,
    },
    /// Strict text-equality between PTX outputs. Useful for
    /// regression-locking, NOT for falsification — different valid
    /// PTX programs commonly produce identical execution results via
    /// different instruction sequences.
    Strict,
}

/// Status of a multi-emitter quorum vote, attached to an [`Artifact`]
/// produced by a multi-emitter backend.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum QuorumStatus {
    /// Only one emitter fired (specialist missing for this shape, or
    /// quorum policy is `PreferSpecialist` and specialist matched).
    /// Runtime stratum vote count: 1.
    Single { emitter: String },
    /// Both emitters fired; outputs were combined under the policy.
    /// Runtime stratum vote count: 2.
    Multi {
        emitters: Vec<String>,
        diff_exec: Option<DiffExecResult>,
    },
}

/// Result of a `DiffExec` quorum policy execution. Two PTX (or WGSL/
/// SPIR-V) programs were run on test inputs; the engine compared
/// their numerical outputs.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum DiffExecResult {
    /// Outputs matched within tolerance. Records the max absolute
    /// difference observed for audit trail.
    Match { max_abs_diff: f64 },
    /// Outputs diverged beyond tolerance. **Contract violation** —
    /// CI fails. Records the divergence for diagnosis.
    Divergent { max_abs_diff: f64, tolerance: f64 },
    /// Engine did not run (e.g., test hardware unavailable). Vote
    /// downgrades from Runtime to a placeholder. The substrate
    /// records this rather than silently dropping it.
    NotRun { reason: String },
}

/// A single emitter entry from `compile_targets.via` in the YAML
/// schema. Mirrors the structured-record form spec'd in
/// `sub/layer5-multi-emitter-quorum.md` §"Contract YAML schema extension".
///
/// At v0.1.0 the YAML schema is still a flat `[String]`; this struct
/// is the v0.2.0+ target representation `pv lint` will deserialize.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ViaEntry {
    /// Emitter name, e.g. "rustc_codegen_nvvm", "aprender-gpu".
    pub emitter: String,
    /// Role within the quorum.
    pub role: EmitterRole,
    /// Local crate that registers this emitter (for `role: general`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub crate_name: Option<String>,
    /// Cross-repo binding target (for `role: specialist` cases where
    /// the emitter lives in a different fleet repo, e.g. aprender).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cross_repo: Option<String>,
    /// Optional shape filter — for specialists, identifies which
    /// input shapes this emitter handles. Tied to a sub-contract
    /// (e.g., `gemm_fp16_mma_64x128` matches aprender's
    /// `C-COMPUTE-GEMM-FP16-MMA` contract).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shape_filter: Option<String>,
}

// ─── PMAT-263 / Section 29: TargetEmitter trait + MultiEmitterBackend ────
//
// Routing layer for multi-emitter backends. A [`MultiEmitterBackend`]
// composes a general emitter (mandatory fallback) + an optional
// specialist emitter under a [`QuorumPolicy`]. Single-emitter and
// multi-emitter cases produce explicit `QuorumStatus` on the emitted
// [`Artifact`].

/// Plain text emitted by a single [`TargetEmitter`] before the
/// multi-emitter routing decides what to put in the final [`Artifact`].
/// Doesn't carry `QuorumStatus` (that's chosen by the wrapper).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EmittedText {
    pub primary: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub citations: Vec<ContractId>,
}

/// Single-emitter trait — sub-trait of a multi-emitter backend.
/// One [`TargetEmitter`] handles emission for one logical path
/// (general vs specialist). Each [`MultiEmitterBackend`] wraps
/// one mandatory general emitter and optionally one specialist.
pub trait TargetEmitter: Send + Sync {
    /// Human-readable emitter name (used in [`QuorumStatus`]).
    fn name(&self) -> &str;

    /// Attempt to emit for this input. Specialists return `None`
    /// when their shape filter doesn't match — the wrapper then
    /// uses only the general emitter. General emitters should
    /// always return `Some(...)` for any contract-conforming input.
    fn try_emit(
        &self,
        module: &Module,
        config: &BackendConfig,
    ) -> Option<Result<EmittedText, BackendError>>;
}

/// PMAT-486 (§30 Track 4): engine that executes two emitted programs on
/// contract-fixture inputs and numerically compares the outputs within a
/// tolerance — the Runtime-stratum half of the §29 quorum. The trait +
/// hook land here (free CI); the real CUDA / Vulkan implementations
/// (PMAT-488 / PMAT-490) run out-of-band on self-hosted GPU runners.
///
/// Error posture (per the §30 Track-4 review): with **no engine
/// installed** the `DiffExec` policy records `NotRun { reason: no-engine }`
/// (benign — free CI stays green). An **installed** engine that returns
/// `Err` propagates a hard [`BackendError`] that fails the job — a broken
/// GPU run must NOT masquerade as "not run".
pub trait DiffExecEngine: Send + Sync {
    /// Execute `general_text` and `specialist_text` on the contract's
    /// fixture inputs and compare. `Ok(Match|Divergent)` records the
    /// vote; `Err(msg)` is a hard failure (e.g. driver fault / launch
    /// error) the caller turns into a `BackendError`.
    fn execute_and_compare(
        &self,
        general_text: &str,
        specialist_text: &str,
        module: &Module,
        config: &BackendConfig,
        tolerance: f64,
    ) -> Result<DiffExecResult, String>;
}

/// Multi-emitter backend wrapper. Composes a general emitter
/// (mandatory) + an optional specialist under a [`QuorumPolicy`].
/// Implements [`Backend`] so it slots into the existing dispatch
/// without touching `TranspileSession`.
pub struct MultiEmitterBackend {
    /// Single target this multi-emitter backend serves
    /// (e.g., [`Target::Ptx`]).
    pub target: Target,
    /// Mandatory general emitter. Must handle any
    /// contract-conforming input as a fallback.
    pub general: Box<dyn TargetEmitter>,
    /// Optional specialist emitter. Returns `None` from `try_emit`
    /// when its shape filter doesn't match the input.
    pub specialist: Option<Box<dyn TargetEmitter>>,
    /// How to combine outputs when both emitters fire.
    pub quorum_policy: QuorumPolicy,
    /// PMAT-486: optional `DiffExec` execution engine. `None` (the
    /// default) records `NotRun { no-engine }` under `QuorumPolicy::
    /// DiffExec`; `Some(engine)` runs the Runtime-stratum comparison.
    pub diff_exec_engine: Option<std::sync::Arc<dyn DiffExecEngine>>,
}

impl MultiEmitterBackend {
    pub fn new_single(target: Target, general: Box<dyn TargetEmitter>) -> Self {
        Self {
            target,
            general,
            specialist: None,
            quorum_policy: QuorumPolicy::PreferSpecialist,
            diff_exec_engine: None,
        }
    }

    pub fn new_with_specialist(
        target: Target,
        general: Box<dyn TargetEmitter>,
        specialist: Box<dyn TargetEmitter>,
        quorum_policy: QuorumPolicy,
    ) -> Self {
        Self {
            target,
            general,
            specialist: Some(specialist),
            quorum_policy,
            diff_exec_engine: None,
        }
    }

    /// PMAT-486: install a `DiffExec` engine (builder style). The real
    /// CUDA / Vulkan engines (PMAT-488 / PMAT-490) plug in here on the
    /// self-hosted GPU runners; on free CI the engine stays `None`.
    pub fn with_diff_exec_engine(mut self, engine: std::sync::Arc<dyn DiffExecEngine>) -> Self {
        self.diff_exec_engine = Some(engine);
        self
    }
}

impl Backend for MultiEmitterBackend {
    fn name(&self) -> &'static str {
        // The wrapper name is generic; per-emitter names live in
        // QuorumStatus on each emitted Artifact for audit recovery.
        "multi-emitter"
    }

    fn targets(&self) -> &[Target] {
        std::slice::from_ref(&self.target)
    }

    fn lower(&self, module: &Module, config: &BackendConfig) -> Result<Artifact, BackendError> {
        let general_result = self.general.try_emit(module, config).ok_or_else(|| {
            BackendError::Lower(format!(
                "general emitter {} must always match contract-conforming input",
                self.general.name()
            ))
        })??;

        let specialist_result = self.specialist.as_ref().and_then(|s| {
            s.try_emit(module, config)
                .map(|r| (s.name().to_string(), r))
        });

        match specialist_result {
            None => {
                // Only general fired — Single-vote Runtime stratum.
                Ok(Artifact {
                    primary: general_result.primary,
                    sidecars: Vec::new(),
                    citations: general_result.citations,
                    quorum_status: QuorumStatus::Single {
                        emitter: self.general.name().to_string(),
                    },
                })
            }
            Some((specialist_name, specialist_emit)) => {
                let specialist_text = specialist_emit?;
                match &self.quorum_policy {
                    QuorumPolicy::PreferSpecialist => {
                        // Use specialist's output; general was emitted for
                        // sanity but isn't reported as a vote.
                        Ok(Artifact {
                            primary: specialist_text.primary,
                            sidecars: Vec::new(),
                            citations: specialist_text.citations,
                            quorum_status: QuorumStatus::Single {
                                emitter: specialist_name,
                            },
                        })
                    }
                    QuorumPolicy::Strict => {
                        // Text-equality check.
                        let diff_exec = if general_result.primary == specialist_text.primary {
                            Some(DiffExecResult::Match { max_abs_diff: 0.0 })
                        } else {
                            Some(DiffExecResult::Divergent {
                                max_abs_diff: f64::INFINITY,
                                tolerance: 0.0,
                            })
                        };
                        Ok(Artifact {
                            primary: general_result.primary.clone(),
                            sidecars: vec![(
                                "specialist_emission".to_string(),
                                specialist_text.primary.into_bytes(),
                            )],
                            citations: general_result.citations,
                            quorum_status: QuorumStatus::Multi {
                                emitters: vec![self.general.name().to_string(), specialist_name],
                                diff_exec,
                            },
                        })
                    }
                    QuorumPolicy::DiffExec { tolerance } => {
                        // PMAT-486: run the installed engine, or record
                        // NotRun{no-engine} when none is installed (free
                        // CI). An installed engine that errors propagates
                        // a hard BackendError — a broken GPU run must NOT
                        // masquerade as "not run".
                        let diff_exec = match &self.diff_exec_engine {
                            Some(engine) => engine
                                .execute_and_compare(
                                    &general_result.primary,
                                    &specialist_text.primary,
                                    module,
                                    config,
                                    *tolerance,
                                )
                                .map_err(|e| {
                                    BackendError::Lower(format!(
                                        "DiffExec engine for {:?} failed: {e}",
                                        self.target
                                    ))
                                })?,
                            None => DiffExecResult::NotRun {
                                reason: format!(
                                    "no DiffExec engine installed (tolerance was {tolerance})"
                                ),
                            },
                        };
                        Ok(Artifact {
                            primary: general_result.primary.clone(),
                            sidecars: vec![(
                                "specialist_emission".to_string(),
                                specialist_text.primary.into_bytes(),
                            )],
                            citations: general_result.citations,
                            quorum_status: QuorumStatus::Multi {
                                emitters: vec![self.general.name().to_string(), specialist_name],
                                diff_exec: Some(diff_exec),
                            },
                        })
                    }
                }
            }
        }
    }
}

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

    #[test]
    fn emitter_role_serde_round_trip() {
        let general = EmitterRole::General;
        let s = serde_json::to_string(&general).unwrap();
        assert_eq!(s, "\"general\"");
        let back: EmitterRole = serde_json::from_str(&s).unwrap();
        assert_eq!(back, general);

        let specialist = EmitterRole::Specialist;
        let s = serde_json::to_string(&specialist).unwrap();
        assert_eq!(s, "\"specialist\"");
    }

    #[test]
    fn quorum_policy_diff_exec_carries_tolerance() {
        let policy = QuorumPolicy::DiffExec { tolerance: 1.0e-3 };
        let s = serde_json::to_string(&policy).unwrap();
        assert!(s.contains("diff_exec"));
        assert!(s.contains("0.001"));
        let back: QuorumPolicy = serde_json::from_str(&s).unwrap();
        assert_eq!(back, policy);
    }

    #[test]
    fn quorum_status_multi_records_emitters_and_diff() {
        let status = QuorumStatus::Multi {
            emitters: vec!["rustc_codegen_nvvm".into(), "aprender-gpu".into()],
            diff_exec: Some(DiffExecResult::Match {
                max_abs_diff: 1.3e-4,
            }),
        };
        let s = serde_json::to_string(&status).unwrap();
        assert!(s.contains("multi"));
        assert!(s.contains("rustc_codegen_nvvm"));
        assert!(s.contains("aprender-gpu"));
    }

    #[test]
    fn diff_exec_divergent_carries_both_diff_and_tolerance() {
        let r = DiffExecResult::Divergent {
            max_abs_diff: 0.5,
            tolerance: 0.001,
        };
        let s = serde_json::to_string(&r).unwrap();
        let back: DiffExecResult = serde_json::from_str(&s).unwrap();
        assert_eq!(back, r);
    }

    #[test]
    fn via_entry_general_has_no_specialist_fields() {
        let v = ViaEntry {
            emitter: "rustc_codegen_nvvm".into(),
            role: EmitterRole::General,
            crate_name: Some("xpile-ptx-codegen".into()),
            cross_repo: None,
            shape_filter: None,
        };
        let s = serde_json::to_string(&v).unwrap();
        // Optional None fields skipped from output.
        assert!(!s.contains("cross_repo"));
        assert!(!s.contains("shape_filter"));
        assert!(s.contains("general"));
    }

    #[test]
    fn via_entry_specialist_carries_cross_repo_and_shape_filter() {
        let v = ViaEntry {
            emitter: "aprender-gpu".into(),
            role: EmitterRole::Specialist,
            crate_name: None,
            cross_repo: Some("aprender".into()),
            shape_filter: Some("gemm_fp16_mma_64x128".into()),
        };
        let s = serde_json::to_string(&v).unwrap();
        assert!(s.contains("specialist"));
        assert!(s.contains("aprender"));
        assert!(s.contains("gemm_fp16_mma_64x128"));
    }

    /// PMAT-262: Artifact carries QuorumStatus; default deserialization
    /// gracefully populates Single { emitter: "unknown" } for older JSON
    /// payloads that predate the field.
    #[test]
    fn artifact_quorum_status_defaults_for_older_payloads() {
        let legacy_json = r#"{"primary":"// test","sidecars":[],"citations":[]}"#;
        let a: Artifact = serde_json::from_str(legacy_json).unwrap();
        assert_eq!(
            a.quorum_status,
            QuorumStatus::Single {
                emitter: "unknown".to_string()
            }
        );
    }

    /// PMAT-262: Artifact round-trips QuorumStatus::Single produced by
    /// every single-emitter backend at v0.1.0.
    #[test]
    fn artifact_quorum_status_single_round_trips() {
        let a = Artifact {
            primary: "// test".into(),
            sidecars: Vec::new(),
            citations: Vec::new(),
            quorum_status: QuorumStatus::Single {
                emitter: "xpile-rust-codegen".to_string(),
            },
        };
        let s = serde_json::to_string(&a).unwrap();
        let back: Artifact = serde_json::from_str(&s).unwrap();
        assert_eq!(back, a);
    }

    // ─── PMAT-263: MultiEmitterBackend routing tests with mock emitters ─

    /// Mock emitter returning a fixed primary string and always matching
    /// (use for `general` role). Cloneable to construct two copies for
    /// match cases.
    struct MockGeneral {
        name: &'static str,
        body: String,
    }
    impl TargetEmitter for MockGeneral {
        fn name(&self) -> &str {
            self.name
        }
        fn try_emit(
            &self,
            _module: &Module,
            _config: &BackendConfig,
        ) -> Option<Result<EmittedText, BackendError>> {
            Some(Ok(EmittedText {
                primary: self.body.clone(),
                citations: Vec::new(),
            }))
        }
    }

    /// Mock specialist emitter — matches conditionally and returns a
    /// configurable body.
    struct MockSpecialist {
        name: &'static str,
        matches: bool,
        body: String,
    }
    impl TargetEmitter for MockSpecialist {
        fn name(&self) -> &str {
            self.name
        }
        fn try_emit(
            &self,
            _module: &Module,
            _config: &BackendConfig,
        ) -> Option<Result<EmittedText, BackendError>> {
            if self.matches {
                Some(Ok(EmittedText {
                    primary: self.body.clone(),
                    citations: Vec::new(),
                }))
            } else {
                None
            }
        }
    }

    fn dummy_module() -> Module {
        Module {
            name: "test".into(),
            source_lang: xpile_meta_hir::SourceLang::Rust,
            items: Vec::new(),
            ffi_boundaries: Vec::new(),
        }
    }

    fn dummy_config() -> BackendConfig {
        BackendConfig {
            target: Target::Ptx,
            profile: Profile::RustOut,
            hardware: None,
        }
    }

    #[test]
    fn multi_emitter_specialist_missing_falls_back_to_general() {
        let backend = MultiEmitterBackend::new_single(
            Target::Ptx,
            Box::new(MockGeneral {
                name: "general",
                body: "general output".into(),
            }),
        );
        let artifact = backend.lower(&dummy_module(), &dummy_config()).unwrap();
        assert_eq!(artifact.primary, "general output");
        assert_eq!(
            artifact.quorum_status,
            QuorumStatus::Single {
                emitter: "general".to_string()
            }
        );
    }

    #[test]
    fn multi_emitter_specialist_unmatched_falls_back_to_general() {
        let backend = MultiEmitterBackend::new_with_specialist(
            Target::Ptx,
            Box::new(MockGeneral {
                name: "general",
                body: "general output".into(),
            }),
            Box::new(MockSpecialist {
                name: "specialist",
                matches: false,
                body: "specialist output".into(),
            }),
            QuorumPolicy::DiffExec { tolerance: 1e-3 },
        );
        let artifact = backend.lower(&dummy_module(), &dummy_config()).unwrap();
        assert_eq!(artifact.primary, "general output");
        // Specialist returned None → Single vote.
        assert_eq!(
            artifact.quorum_status,
            QuorumStatus::Single {
                emitter: "general".to_string()
            }
        );
    }

    #[test]
    fn multi_emitter_prefer_specialist_uses_specialist_output() {
        let backend = MultiEmitterBackend::new_with_specialist(
            Target::Ptx,
            Box::new(MockGeneral {
                name: "general",
                body: "general".into(),
            }),
            Box::new(MockSpecialist {
                name: "specialist",
                matches: true,
                body: "specialist tuned".into(),
            }),
            QuorumPolicy::PreferSpecialist,
        );
        let artifact = backend.lower(&dummy_module(), &dummy_config()).unwrap();
        assert_eq!(artifact.primary, "specialist tuned");
        assert_eq!(
            artifact.quorum_status,
            QuorumStatus::Single {
                emitter: "specialist".to_string()
            }
        );
    }

    #[test]
    fn multi_emitter_strict_match_records_zero_diff() {
        let backend = MultiEmitterBackend::new_with_specialist(
            Target::Ptx,
            Box::new(MockGeneral {
                name: "general",
                body: "same output".into(),
            }),
            Box::new(MockSpecialist {
                name: "specialist",
                matches: true,
                body: "same output".into(),
            }),
            QuorumPolicy::Strict,
        );
        let artifact = backend.lower(&dummy_module(), &dummy_config()).unwrap();
        match artifact.quorum_status {
            QuorumStatus::Multi {
                emitters,
                diff_exec,
            } => {
                assert_eq!(emitters, vec!["general", "specialist"]);
                assert_eq!(diff_exec, Some(DiffExecResult::Match { max_abs_diff: 0.0 }));
            }
            _ => panic!("expected Multi quorum status"),
        }
        // Specialist's output recorded as sidecar for audit trail.
        assert_eq!(artifact.sidecars.len(), 1);
        assert_eq!(artifact.sidecars[0].0, "specialist_emission");
    }

    #[test]
    fn multi_emitter_strict_divergence_records_infinity() {
        let backend = MultiEmitterBackend::new_with_specialist(
            Target::Ptx,
            Box::new(MockGeneral {
                name: "general",
                body: "general output".into(),
            }),
            Box::new(MockSpecialist {
                name: "specialist",
                matches: true,
                body: "different output".into(),
            }),
            QuorumPolicy::Strict,
        );
        let artifact = backend.lower(&dummy_module(), &dummy_config()).unwrap();
        match artifact.quorum_status {
            QuorumStatus::Multi { diff_exec, .. } => {
                assert!(matches!(diff_exec, Some(DiffExecResult::Divergent { .. })));
            }
            _ => panic!("expected Multi quorum status"),
        }
    }

    #[test]
    fn multi_emitter_diff_exec_records_not_run_until_engine_plugged_in() {
        let backend = MultiEmitterBackend::new_with_specialist(
            Target::Ptx,
            Box::new(MockGeneral {
                name: "rustc_codegen_nvvm",
                body: "ptx general".into(),
            }),
            Box::new(MockSpecialist {
                name: "aprender-gpu",
                matches: true,
                body: "ptx specialist".into(),
            }),
            QuorumPolicy::DiffExec { tolerance: 1e-3 },
        );
        let artifact = backend.lower(&dummy_module(), &dummy_config()).unwrap();
        match artifact.quorum_status {
            QuorumStatus::Multi {
                emitters,
                diff_exec,
            } => {
                assert_eq!(emitters, vec!["rustc_codegen_nvvm", "aprender-gpu"]);
                // DiffExec engine isn't plugged in yet — should record NotRun.
                assert!(matches!(diff_exec, Some(DiffExecResult::NotRun { .. })));
            }
            _ => panic!("expected Multi quorum status"),
        }
    }

    // ─── PMAT-266: Adversarial invariants for MultiEmitterBackend ───
    //
    // These tests pin down security-relevant contract behavior that the
    // PMAT-263 happy-path tests don't cover: citation provenance, error
    // propagation, hidden-divergence documentation, and observability of
    // the `NotRun` reason. They guard against silent regressions in the
    // routing layer that would weaken the Section 29 oracle.

    /// Mock emitter with configurable citations — used to verify which
    /// emitter's citations end up in the final Artifact.
    struct MockGeneralWithCitations {
        body: String,
        citations: Vec<ContractId>,
    }
    impl TargetEmitter for MockGeneralWithCitations {
        fn name(&self) -> &str {
            "general-with-cites"
        }
        fn try_emit(
            &self,
            _module: &Module,
            _config: &BackendConfig,
        ) -> Option<Result<EmittedText, BackendError>> {
            Some(Ok(EmittedText {
                primary: self.body.clone(),
                citations: self.citations.clone(),
            }))
        }
    }

    /// Mock specialist that always matches and carries configurable
    /// citations distinct from `MockGeneralWithCitations`.
    struct MockSpecialistWithCitations {
        body: String,
        citations: Vec<ContractId>,
    }
    impl TargetEmitter for MockSpecialistWithCitations {
        fn name(&self) -> &str {
            "specialist-with-cites"
        }
        fn try_emit(
            &self,
            _module: &Module,
            _config: &BackendConfig,
        ) -> Option<Result<EmittedText, BackendError>> {
            Some(Ok(EmittedText {
                primary: self.body.clone(),
                citations: self.citations.clone(),
            }))
        }
    }

    /// Mock emitter that always fails — used to verify error
    /// propagation from each role.
    struct MockFailingEmitter {
        name: &'static str,
        err: String,
    }
    impl TargetEmitter for MockFailingEmitter {
        fn name(&self) -> &str {
            self.name
        }
        fn try_emit(
            &self,
            _module: &Module,
            _config: &BackendConfig,
        ) -> Option<Result<EmittedText, BackendError>> {
            Some(Err(BackendError::Lower(self.err.clone())))
        }
    }

    /// Mock emitter that returns `None` — for `general`, this is a
    /// contract violation (general MUST match contract-conforming
    /// input); the wrapper must surface it as a hard `BackendError`.
    struct MockNoneEmitter;
    impl TargetEmitter for MockNoneEmitter {
        fn name(&self) -> &str {
            "always-none"
        }
        fn try_emit(
            &self,
            _module: &Module,
            _config: &BackendConfig,
        ) -> Option<Result<EmittedText, BackendError>> {
            None
        }
    }

    #[test]
    fn strict_divergence_preserves_general_citations_not_specialist() {
        // Security invariant: under `Strict`, citations come from
        // `general`. The proof lane relies on this — citations identify
        // which contracts the artifact was authored against. A
        // specialist that disagrees with general must not be able to
        // silently swap its own citations into the audit trail.
        let backend = MultiEmitterBackend::new_with_specialist(
            Target::Ptx,
            Box::new(MockGeneralWithCitations {
                body: "general output".into(),
                citations: vec![ContractId::new("C-GENERAL-CITED")],
            }),
            Box::new(MockSpecialistWithCitations {
                body: "different output".into(),
                citations: vec![ContractId::new("C-SPECIALIST-CITED")],
            }),
            QuorumPolicy::Strict,
        );
        let artifact = backend.lower(&dummy_module(), &dummy_config()).unwrap();
        assert_eq!(artifact.citations.len(), 1);
        assert_eq!(artifact.citations[0].as_str(), "C-GENERAL-CITED");
        // Specialist's body is still recoverable from the sidecar even
        // though its citations are dropped.
        assert_eq!(artifact.sidecars.len(), 1);
        assert_eq!(
            artifact.sidecars[0].1,
            b"different output".to_vec(),
            "specialist body should be preserved in sidecar"
        );
    }

    #[test]
    fn prefer_specialist_hides_divergence_by_design() {
        // Documented trade-off: `PreferSpecialist` is the
        // single-vote-runtime stratum — it intentionally does NOT
        // compare general vs specialist. Use `Strict` or `DiffExec`
        // when divergence detection matters. This test pins down the
        // behavior so a future "helpful" refactor can't accidentally
        // turn this into a quiet divergence detector.
        let backend = MultiEmitterBackend::new_with_specialist(
            Target::Ptx,
            Box::new(MockGeneralWithCitations {
                body: "general thinks the answer is 42".into(),
                citations: vec![ContractId::new("C-GENERAL")],
            }),
            Box::new(MockSpecialistWithCitations {
                body: "specialist thinks the answer is 99".into(),
                citations: vec![ContractId::new("C-SPECIALIST")],
            }),
            QuorumPolicy::PreferSpecialist,
        );
        let artifact = backend.lower(&dummy_module(), &dummy_config()).unwrap();
        // Specialist's body wins; specialist's citations win;
        // QuorumStatus reports Single (no divergence captured).
        assert!(artifact.primary.contains("99"));
        assert_eq!(artifact.citations[0].as_str(), "C-SPECIALIST");
        match artifact.quorum_status {
            QuorumStatus::Single { emitter } => {
                assert_eq!(emitter, "specialist-with-cites");
            }
            other => panic!("expected Single quorum status, got {other:?}"),
        }
        // No sidecar — general's emission isn't even captured.
        assert!(artifact.sidecars.is_empty());
    }

    #[test]
    fn general_emitter_failure_propagates() {
        // If `general` returns Some(Err(...)), the wrapper must
        // propagate the error — never silently fall through to
        // specialist. General is the mandatory fallback; its failure
        // is the whole backend's failure.
        let backend = MultiEmitterBackend::new_with_specialist(
            Target::Ptx,
            Box::new(MockFailingEmitter {
                name: "general-broken",
                err: "general blew up".into(),
            }),
            Box::new(MockSpecialist {
                name: "specialist",
                matches: true,
                body: "specialist output".into(),
            }),
            QuorumPolicy::PreferSpecialist,
        );
        let err = backend.lower(&dummy_module(), &dummy_config()).unwrap_err();
        match err {
            BackendError::Lower(msg) => assert!(msg.contains("general blew up")),
            other => panic!("expected Lower error, got {other:?}"),
        }
    }

    #[test]
    fn specialist_emitter_failure_propagates_when_matched() {
        // If `specialist` matches and then errors, propagate. This is
        // a real partial-failure mode for shape-tuned emitters
        // (matched on shape but failed during lowering).
        let backend = MultiEmitterBackend::new_with_specialist(
            Target::Ptx,
            Box::new(MockGeneral {
                name: "general",
                body: "general output".into(),
            }),
            Box::new(MockFailingEmitter {
                name: "specialist-broken",
                err: "specialist blew up after matching".into(),
            }),
            QuorumPolicy::Strict,
        );
        let err = backend.lower(&dummy_module(), &dummy_config()).unwrap_err();
        match err {
            BackendError::Lower(msg) => {
                assert!(msg.contains("specialist blew up after matching"))
            }
            other => panic!("expected Lower error, got {other:?}"),
        }
    }

    #[test]
    fn general_returning_none_is_a_hard_contract_violation() {
        // `general` returning `None` from `try_emit` means it refused
        // to handle contract-conforming input — that's a hard error.
        // (Specialists are allowed to return None; general isn't.)
        let backend = MultiEmitterBackend::new_single(Target::Ptx, Box::new(MockNoneEmitter));
        let err = backend.lower(&dummy_module(), &dummy_config()).unwrap_err();
        match err {
            BackendError::Lower(msg) => {
                assert!(
                    msg.contains("always-none"),
                    "error should name the offending emitter; got: {msg}"
                );
                assert!(msg.contains("must always match"));
            }
            other => panic!("expected Lower error, got {other:?}"),
        }
    }

    #[test]
    fn diff_exec_not_run_reason_records_tolerance_for_observability() {
        // The `NotRun` reason is the user-facing breadcrumb pointing
        // at "DiffExec engine not yet wired" — and it must carry the
        // configured tolerance so debug output is actionable.
        let backend = MultiEmitterBackend::new_with_specialist(
            Target::Ptx,
            Box::new(MockGeneral {
                name: "general",
                body: "g".into(),
            }),
            Box::new(MockSpecialist {
                name: "specialist",
                matches: true,
                body: "s".into(),
            }),
            QuorumPolicy::DiffExec { tolerance: 2.5e-4 },
        );
        let artifact = backend.lower(&dummy_module(), &dummy_config()).unwrap();
        match artifact.quorum_status {
            QuorumStatus::Multi {
                diff_exec: Some(DiffExecResult::NotRun { reason }),
                ..
            } => {
                assert!(
                    reason.contains("0.00025")
                        || reason.contains("2.5e-4")
                        || reason.contains("0.000250"),
                    "tolerance should appear in NotRun reason; got: {reason}"
                );
            }
            other => panic!("expected Multi NotRun status, got {other:?}"),
        }
    }

    #[test]
    fn diff_exec_does_not_short_circuit_on_text_equality() {
        // Architectural invariant: even when general and specialist
        // emit byte-identical text, `DiffExec` policy must still
        // record `NotRun` (because the real engine compares numerical
        // outputs after execution, not source text). A future
        // optimization that says "skip diff if text matches" would
        // break this invariant — the engine's job is to check the
        // RUNTIME behavior, and identical source could still produce
        // divergent runtime values on different hardware.
        let backend = MultiEmitterBackend::new_with_specialist(
            Target::Ptx,
            Box::new(MockGeneral {
                name: "general",
                body: "byte identical".into(),
            }),
            Box::new(MockSpecialist {
                name: "specialist",
                matches: true,
                body: "byte identical".into(),
            }),
            QuorumPolicy::DiffExec { tolerance: 1e-6 },
        );
        let artifact = backend.lower(&dummy_module(), &dummy_config()).unwrap();
        match artifact.quorum_status {
            QuorumStatus::Multi { diff_exec, .. } => {
                assert!(
                    matches!(diff_exec, Some(DiffExecResult::NotRun { .. })),
                    "DiffExec policy must NOT short-circuit on text equality \
                     — engine compares runtime values, not source text"
                );
            }
            other => panic!("expected Multi quorum status, got {other:?}"),
        }
    }

    // ─── PMAT-486: DiffExecEngine trait + hook ──────────────────────

    /// Stub engine returning a fixed result (or a hard error).
    struct StubEngine {
        result: Result<DiffExecResult, String>,
    }
    impl DiffExecEngine for StubEngine {
        fn execute_and_compare(
            &self,
            _g: &str,
            _s: &str,
            _m: &Module,
            _c: &BackendConfig,
            _tol: f64,
        ) -> Result<DiffExecResult, String> {
            self.result.clone()
        }
    }

    fn diff_exec_backend() -> MultiEmitterBackend {
        MultiEmitterBackend::new_with_specialist(
            Target::Ptx,
            Box::new(MockGeneral {
                name: "general",
                body: "g".into(),
            }),
            Box::new(MockSpecialist {
                name: "specialist",
                matches: true,
                body: "s".into(),
            }),
            QuorumPolicy::DiffExec { tolerance: 1e-6 },
        )
    }

    /// PMAT-486: an installed engine's `Ok(Match)` becomes the recorded
    /// Runtime vote (replacing NotRun).
    #[test]
    fn diff_exec_engine_records_match() {
        let backend = diff_exec_backend().with_diff_exec_engine(std::sync::Arc::new(StubEngine {
            result: Ok(DiffExecResult::Match { max_abs_diff: 0.0 }),
        }));
        let artifact = backend.lower(&dummy_module(), &dummy_config()).unwrap();
        match artifact.quorum_status {
            QuorumStatus::Multi {
                diff_exec: Some(DiffExecResult::Match { .. }),
                ..
            } => {}
            other => panic!("expected Multi Match, got {other:?}"),
        }
    }

    /// PMAT-486: an installed engine that errors propagates a hard
    /// `BackendError` — it must NOT be swallowed into `NotRun`.
    #[test]
    fn diff_exec_engine_error_is_a_hard_failure() {
        let backend = diff_exec_backend().with_diff_exec_engine(std::sync::Arc::new(StubEngine {
            result: Err("driver fault: CUDA_ERROR_LAUNCH_FAILED".into()),
        }));
        let err = backend
            .lower(&dummy_module(), &dummy_config())
            .expect_err("engine error must surface as a hard BackendError");
        assert!(matches!(err, BackendError::Lower(_)));
    }

    /// PMAT-486: with no engine installed, the policy still records the
    /// benign `NotRun { no-engine }` (free CI stays green).
    #[test]
    fn diff_exec_no_engine_records_not_run() {
        let backend = diff_exec_backend();
        let artifact = backend.lower(&dummy_module(), &dummy_config()).unwrap();
        match artifact.quorum_status {
            QuorumStatus::Multi {
                diff_exec: Some(DiffExecResult::NotRun { reason }),
                ..
            } => assert!(reason.contains("no DiffExec engine"), "got: {reason}"),
            other => panic!("expected Multi NotRun, got {other:?}"),
        }
    }
}