Skip to main content

asupersync_conformance/
reference_registry.rs

1//! Source-owned reference-surface registry for conformance harnesses.
2//!
3//! A harness may only report a runtime verdict that the registry allows for
4//! its surface. Missing rows and unwired-reference pass claims fail closed.
5
6use serde::{Deserialize, Serialize};
7use std::collections::BTreeMap;
8use std::fmt;
9
10/// The root conformance registry contract embedded in the conformance crate.
11///
12/// This reads the IN-PACKAGE copy at `conformance/artifacts/`, not the
13/// workspace-root original. `include_str!` is resolved at compile time against
14/// files that must be present in the published `.crate` tarball, and
15/// `cargo package` ships only the package directory — a path escaping upward
16/// with `../../` builds fine from a git checkout and then fails for every
17/// consumer who installs from the registry. That is exactly how 0.3.4 and 0.4.0
18/// both shipped unbuildable (frankenlibc bd-kcmnj4).
19///
20/// `packaged_contract_matches_workspace_canonical` below keeps this copy
21/// byte-identical to `artifacts/conformance_registry_contract_v1.json`, which
22/// remains the canonical source the workspace tests and README point at.
23pub const SOURCE_CONFORMANCE_REGISTRY_CONTRACT: &str =
24    include_str!("../artifacts/conformance_registry_contract_v1.json");
25
26/// Runtime verdicts a conformance harness can report through the registry.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
28#[serde(rename_all = "lowercase")]
29pub enum RuntimeConformanceVerdict {
30    /// The harness has a live reference and observed parity.
31    Pass,
32    /// The harness ran and found a real mismatch.
33    Fail,
34    /// The harness ran local checks but a required reference is unavailable.
35    Xfail,
36    /// The harness could not run because its reference surface is unavailable.
37    Unavailable,
38}
39
40impl RuntimeConformanceVerdict {
41    /// Stable lowercase string used in registry artifacts.
42    pub const fn as_str(self) -> &'static str {
43        match self {
44            Self::Pass => "pass",
45            Self::Fail => "fail",
46            Self::Xfail => "xfail",
47            Self::Unavailable => "unavailable",
48        }
49    }
50}
51
52impl fmt::Display for RuntimeConformanceVerdict {
53    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
54        formatter.write_str(self.as_str())
55    }
56}
57
58/// One registered conformance reference surface.
59#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
60pub struct ReferenceSurfaceRow {
61    pub surface_id: String,
62    pub binary: String,
63    pub source_path: String,
64    pub reference_family: String,
65    pub reference_status: String,
66    pub fail_closed_without_live_reference: bool,
67    pub runtime_allowed_verdicts: Vec<RuntimeConformanceVerdict>,
68    pub proof_command: String,
69    pub proof_lane: String,
70}
71
72impl ReferenceSurfaceRow {
73    /// Whether this row names a live independent reference.
74    pub fn has_live_reference(&self) -> bool {
75        self.reference_status == "live_reference_wired"
76    }
77
78    /// Whether the row explicitly allows the verdict.
79    pub fn allows(&self, verdict: RuntimeConformanceVerdict) -> bool {
80        self.runtime_allowed_verdicts.contains(&verdict)
81    }
82}
83
84/// Successful registry admission for a harness verdict.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct ReferenceVerdictAdmission {
87    pub surface_id: String,
88    pub binary: String,
89    pub verdict: RuntimeConformanceVerdict,
90    pub reference_status: String,
91}
92
93/// One fail-closed finding from the registry e2e guard.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
95pub struct ReferenceRegistryGuardFailure {
96    pub surface_id: String,
97    pub binary: String,
98    pub reason: String,
99}
100
101/// Deterministic report emitted by the registry e2e guard command.
102#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
103pub struct ReferenceRegistryGuardReport {
104    pub schema_version: &'static str,
105    pub verdict: String,
106    pub checked_surface_count: usize,
107    pub checked_binaries: Vec<String>,
108    pub failures: Vec<ReferenceRegistryGuardFailure>,
109}
110
111impl ReferenceRegistryGuardReport {
112    /// Whether the guard found no fail-closed findings.
113    pub fn is_pass(&self) -> bool {
114        self.failures.is_empty() && self.verdict == "pass"
115    }
116}
117
118/// Fail-closed registry validation errors.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub enum ReferenceRegistryError {
121    Json(String),
122    EmptySurfaceId,
123    DuplicateSurfaceId(String),
124    MissingSurfaceId(String),
125    UnwiredReferencePass {
126        surface_id: String,
127        reference_status: String,
128    },
129    DisallowedVerdict {
130        surface_id: String,
131        verdict: RuntimeConformanceVerdict,
132        allowed: Vec<RuntimeConformanceVerdict>,
133    },
134}
135
136impl fmt::Display for ReferenceRegistryError {
137    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
138        match self {
139            Self::Json(error) => write!(formatter, "invalid conformance registry JSON: {error}"),
140            Self::EmptySurfaceId => {
141                formatter.write_str("conformance registry row has empty surface_id")
142            }
143            Self::DuplicateSurfaceId(surface_id) => {
144                write!(formatter, "duplicate conformance surface_id: {surface_id}")
145            }
146            Self::MissingSurfaceId(surface_id) => {
147                write!(
148                    formatter,
149                    "missing conformance registry surface_id: {surface_id}"
150                )
151            }
152            Self::UnwiredReferencePass {
153                surface_id,
154                reference_status,
155            } => write!(
156                formatter,
157                "surface {surface_id} cannot report pass while reference_status={reference_status}"
158            ),
159            Self::DisallowedVerdict {
160                surface_id,
161                verdict,
162                allowed,
163            } => write!(
164                formatter,
165                "surface {surface_id} cannot report verdict {verdict}; allowed verdicts are {allowed:?}"
166            ),
167        }
168    }
169}
170
171impl std::error::Error for ReferenceRegistryError {}
172
173#[derive(Debug, Deserialize)]
174struct ReferenceSurfaceContract {
175    reference_surfaces: Vec<ReferenceSurfaceRow>,
176}
177
178/// Queryable conformance reference-surface registry.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct ReferenceSurfaceRegistry {
181    rows: BTreeMap<String, ReferenceSurfaceRow>,
182}
183
184impl ReferenceSurfaceRegistry {
185    /// Load the embedded root registry contract.
186    pub fn source_contract() -> Result<Self, ReferenceRegistryError> {
187        Self::from_json_str(SOURCE_CONFORMANCE_REGISTRY_CONTRACT)
188    }
189
190    /// Parse a registry contract JSON document.
191    pub fn from_json_str(json: &str) -> Result<Self, ReferenceRegistryError> {
192        let contract = serde_json::from_str::<ReferenceSurfaceContract>(json)
193            .map_err(|error| ReferenceRegistryError::Json(error.to_string()))?;
194        Self::from_rows(contract.reference_surfaces)
195    }
196
197    /// Build a registry from decoded rows.
198    pub fn from_rows(rows: Vec<ReferenceSurfaceRow>) -> Result<Self, ReferenceRegistryError> {
199        let mut by_id = BTreeMap::new();
200        for row in rows {
201            let surface_id = row.surface_id.trim().to_string();
202            if surface_id.is_empty() {
203                return Err(ReferenceRegistryError::EmptySurfaceId);
204            }
205            if by_id.insert(surface_id.clone(), row).is_some() {
206                return Err(ReferenceRegistryError::DuplicateSurfaceId(surface_id));
207            }
208        }
209        Ok(Self { rows: by_id })
210    }
211
212    /// Number of registered reference surfaces.
213    pub fn len(&self) -> usize {
214        self.rows.len()
215    }
216
217    /// Whether the registry has no rows.
218    pub fn is_empty(&self) -> bool {
219        self.rows.is_empty()
220    }
221
222    /// Registered surfaces in deterministic surface-id order.
223    pub fn surfaces(&self) -> impl Iterator<Item = &ReferenceSurfaceRow> {
224        self.rows.values()
225    }
226
227    /// Fetch one row by surface id.
228    pub fn surface(
229        &self,
230        surface_id: &str,
231    ) -> Result<&ReferenceSurfaceRow, ReferenceRegistryError> {
232        self.rows
233            .get(surface_id)
234            .ok_or_else(|| ReferenceRegistryError::MissingSurfaceId(surface_id.to_string()))
235    }
236
237    /// Admit or reject a harness verdict for a registered surface.
238    pub fn admit_runtime_verdict(
239        &self,
240        surface_id: &str,
241        verdict: RuntimeConformanceVerdict,
242    ) -> Result<ReferenceVerdictAdmission, ReferenceRegistryError> {
243        let row = self.surface(surface_id)?;
244        if verdict == RuntimeConformanceVerdict::Pass
245            && row.fail_closed_without_live_reference
246            && !row.has_live_reference()
247        {
248            return Err(ReferenceRegistryError::UnwiredReferencePass {
249                surface_id: row.surface_id.clone(),
250                reference_status: row.reference_status.clone(),
251            });
252        }
253        if !row.allows(verdict) {
254            return Err(ReferenceRegistryError::DisallowedVerdict {
255                surface_id: row.surface_id.clone(),
256                verdict,
257                allowed: row.runtime_allowed_verdicts.clone(),
258            });
259        }
260        Ok(ReferenceVerdictAdmission {
261            surface_id: row.surface_id.clone(),
262            binary: row.binary.clone(),
263            verdict,
264            reference_status: row.reference_status.clone(),
265        })
266    }
267
268    /// Walk every registered reference surface and produce an e2e guard report.
269    pub fn guard_report(&self) -> ReferenceRegistryGuardReport {
270        let mut checked_binaries = Vec::new();
271        let mut failures = Vec::new();
272
273        for row in self.surfaces() {
274            checked_binaries.push(row.binary.clone());
275
276            push_if_empty(&mut failures, row, &row.binary, "missing-binary");
277            push_if_empty(&mut failures, row, &row.source_path, "missing-source-path");
278            push_if_empty(&mut failures, row, &row.proof_lane, "missing-proof-lane");
279            push_if_empty(
280                &mut failures,
281                row,
282                &row.proof_command,
283                "missing-proof-command",
284            );
285
286            if !row.source_path.ends_with(".rs") {
287                push_failure(&mut failures, row, "source-path-not-rust");
288            }
289            if !row.proof_command.starts_with("rch exec -- ") {
290                push_failure(&mut failures, row, "proof-command-not-rch");
291            }
292            if !row.proof_command.contains("cargo test") {
293                push_failure(&mut failures, row, "proof-command-not-cargo-test");
294            }
295            let bin_arg = format!("--bin {}", row.binary);
296            if !row.proof_command.contains(&bin_arg) {
297                push_failure(&mut failures, row, "proof-command-missing-bin");
298            }
299            if row.has_live_reference() && row.proof_lane.trim().is_empty() {
300                push_failure(&mut failures, row, "live-reference-missing-proof-lane");
301            }
302            if !row.has_live_reference() {
303                if !row.fail_closed_without_live_reference {
304                    push_failure(&mut failures, row, "unwired-reference-not-fail-closed");
305                }
306                if row.allows(RuntimeConformanceVerdict::Pass) {
307                    push_failure(&mut failures, row, "unwired-reference-allows-pass");
308                }
309                if !matches!(
310                    self.admit_runtime_verdict(&row.surface_id, RuntimeConformanceVerdict::Pass),
311                    Err(ReferenceRegistryError::UnwiredReferencePass { .. })
312                ) {
313                    push_failure(
314                        &mut failures,
315                        row,
316                        "unwired-reference-pass-not-rejected-by-admission",
317                    );
318                }
319            }
320        }
321
322        let verdict = if failures.is_empty() {
323            "pass"
324        } else {
325            "fail_closed"
326        };
327        ReferenceRegistryGuardReport {
328            schema_version: "conformance-reference-registry-guard-v1",
329            verdict: verdict.to_string(),
330            checked_surface_count: checked_binaries.len(),
331            checked_binaries,
332            failures,
333        }
334    }
335}
336
337fn push_if_empty(
338    failures: &mut Vec<ReferenceRegistryGuardFailure>,
339    row: &ReferenceSurfaceRow,
340    value: &str,
341    reason: &str,
342) {
343    if value.trim().is_empty() {
344        push_failure(failures, row, reason);
345    }
346}
347
348fn push_failure(
349    failures: &mut Vec<ReferenceRegistryGuardFailure>,
350    row: &ReferenceSurfaceRow,
351    reason: &str,
352) {
353    failures.push(ReferenceRegistryGuardFailure {
354        surface_id: row.surface_id.clone(),
355        binary: row.binary.clone(),
356        reason: reason.to_string(),
357    });
358}
359
360/// Resolves a workspace-root path for a file this crate also ships a copy of.
361///
362/// Returns `None` when the crate is being built from a published `.crate`
363/// tarball, where the workspace does not exist by construction: a tarball
364/// unpacks to `<registry>/asupersync-conformance-X.Y.Z/`, whose parent holds
365/// unrelated crate sources rather than this workspace.
366#[cfg(test)]
367pub(crate) fn workspace_canonical(relative: &str) -> Option<std::path::PathBuf> {
368    let workspace_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).parent()?;
369    if !workspace_root.join("Cargo.toml").is_file() || !workspace_root.join(".git").exists() {
370        return None;
371    }
372    Some(workspace_root.join(relative))
373}
374
375#[cfg(test)]
376mod tests {
377    use super::*;
378
379    /// The in-package copy is what actually ships, so it must not drift from
380    /// the workspace-root original that the README and the workspace tests
381    /// treat as canonical. Guards the repair made for frankenlibc bd-kcmnj4.
382    #[test]
383    fn packaged_contract_matches_workspace_canonical() {
384        let Some(canonical) = workspace_canonical("artifacts/conformance_registry_contract_v1.json")
385        else {
386            // Built from the published tarball. Still assert the embedded copy
387            // is real, so this never degenerates into a silent pass.
388            assert!(
389                SOURCE_CONFORMANCE_REGISTRY_CONTRACT.contains("\"reference_surfaces\""),
390                "packaged crate must embed a non-trivial contract"
391            );
392            return;
393        };
394        let canonical_text = std::fs::read_to_string(&canonical).unwrap_or_else(|err| {
395            panic!(
396                "canonical {} must exist in a source checkout: {err}",
397                canonical.display()
398            )
399        });
400        assert_eq!(
401            canonical_text,
402            SOURCE_CONFORMANCE_REGISTRY_CONTRACT,
403            "conformance/artifacts/conformance_registry_contract_v1.json has drifted from {}. \
404             The in-package copy is the one that ships, so drift here means published crates \
405             embed stale contract data while the workspace tests still pass.",
406            canonical.display()
407        );
408    }
409
410    /// The QUIC migration bin compiles the in-package copy of the harness;
411    /// `tests/conformance/` keeps the original that the workspace test tree
412    /// uses. Both must stay identical or the shipped bin tests different
413    /// behaviour than the workspace does.
414    #[test]
415    fn packaged_quic_harness_matches_workspace_canonical() {
416        let packaged = include_str!("quic_connection_migration_rfc9000.rs");
417        assert!(
418            packaged.contains("QuicConnectionMigrationConformanceHarness"),
419            "packaged crate must embed the real QUIC harness"
420        );
421        let Some(canonical) =
422            workspace_canonical("tests/conformance/quic_connection_migration_rfc9000.rs")
423        else {
424            return;
425        };
426        let canonical_text = std::fs::read_to_string(&canonical).unwrap_or_else(|err| {
427            panic!(
428                "canonical {} must exist in a source checkout: {err}",
429                canonical.display()
430            )
431        });
432        assert_eq!(
433            canonical_text,
434            packaged,
435            "conformance/src/quic_connection_migration_rfc9000.rs has drifted from {}. \
436             The in-package copy is the one that ships.",
437            canonical.display()
438        );
439    }
440
441    fn inline_contract(reference_status: &str, allowed: &[&str]) -> String {
442        let allowed = allowed
443            .iter()
444            .map(|verdict| format!("\"{verdict}\""))
445            .collect::<Vec<_>>()
446            .join(",");
447        format!(
448            r#"{{
449                "reference_surfaces": [
450                    {{
451                        "surface_id": "demo-surface",
452                        "binary": "demo_conformance",
453                        "source_path": "conformance/src/bin/demo_conformance.rs",
454                        "reference_family": "demo",
455                        "reference_status": "{reference_status}",
456                        "fail_closed_without_live_reference": true,
457                        "runtime_allowed_verdicts": [{allowed}],
458                        "proof_command": "rch exec -- cargo test --manifest-path conformance/Cargo.toml --bin demo_conformance",
459                        "proof_lane": "binary-unit"
460                    }}
461                ]
462            }}"#
463        )
464    }
465
466    #[test]
467    fn source_contract_loads_registered_reference_surfaces() {
468        let registry = ReferenceSurfaceRegistry::source_contract().expect("load source registry");
469        assert!(
470            registry.len() >= 5,
471            "source registry should carry the hardened reference surfaces"
472        );
473        let row = registry
474            .surface("otel-trace-context-propagation")
475            .expect("trace-context surface row");
476        assert_eq!(row.binary, "otel_trace_context_propagation_conformance");
477        assert!(row.has_live_reference());
478        assert!(row.allows(RuntimeConformanceVerdict::Pass));
479    }
480
481    #[test]
482    fn unwired_surface_rejects_pass_before_allowed_verdict_check() {
483        let registry = ReferenceSurfaceRegistry::from_json_str(&inline_contract(
484            "live_reference_not_wired",
485            &["pass", "xfail"],
486        ))
487        .expect("parse inline registry");
488        let error = registry
489            .admit_runtime_verdict("demo-surface", RuntimeConformanceVerdict::Pass)
490            .expect_err("unwired reference must reject pass");
491        assert!(matches!(
492            error,
493            ReferenceRegistryError::UnwiredReferencePass { .. }
494        ));
495    }
496
497    #[test]
498    fn xfail_is_admitted_when_registry_allows_it() {
499        let registry = ReferenceSurfaceRegistry::from_json_str(&inline_contract(
500            "live_reference_not_wired",
501            &["xfail", "fail"],
502        ))
503        .expect("parse inline registry");
504        let admission = registry
505            .admit_runtime_verdict("demo-surface", RuntimeConformanceVerdict::Xfail)
506            .expect("xfail should be admitted");
507        assert_eq!(admission.surface_id, "demo-surface");
508        assert_eq!(admission.verdict, RuntimeConformanceVerdict::Xfail);
509    }
510
511    #[test]
512    fn live_reference_can_report_pass_when_allowed() {
513        let registry = ReferenceSurfaceRegistry::from_json_str(&inline_contract(
514            "live_reference_wired",
515            &["pass", "fail"],
516        ))
517        .expect("parse inline registry");
518        let admission = registry
519            .admit_runtime_verdict("demo-surface", RuntimeConformanceVerdict::Pass)
520            .expect("live reference pass should be admitted");
521        assert_eq!(admission.reference_status, "live_reference_wired");
522    }
523
524    #[test]
525    fn missing_surface_fails_closed() {
526        let registry = ReferenceSurfaceRegistry::from_json_str(&inline_contract(
527            "live_reference_wired",
528            &["pass"],
529        ))
530        .expect("parse inline registry");
531        let error = registry
532            .admit_runtime_verdict("missing-surface", RuntimeConformanceVerdict::Pass)
533            .expect_err("missing row must fail closed");
534        assert_eq!(
535            error,
536            ReferenceRegistryError::MissingSurfaceId("missing-surface".to_string())
537        );
538    }
539
540    #[test]
541    fn duplicate_surface_ids_fail_closed() {
542        let json = r#"{
543            "reference_surfaces": [
544                {
545                    "surface_id": "demo-surface",
546                    "binary": "demo_a",
547                    "source_path": "a.rs",
548                    "reference_family": "demo",
549                    "reference_status": "live_reference_wired",
550                    "fail_closed_without_live_reference": false,
551                    "runtime_allowed_verdicts": ["pass"],
552                    "proof_command": "rch exec -- cargo test --bin demo_a",
553                    "proof_lane": "binary-unit"
554                },
555                {
556                    "surface_id": "demo-surface",
557                    "binary": "demo_b",
558                    "source_path": "b.rs",
559                    "reference_family": "demo",
560                    "reference_status": "live_reference_wired",
561                    "fail_closed_without_live_reference": false,
562                    "runtime_allowed_verdicts": ["pass"],
563                    "proof_command": "rch exec -- cargo test --bin demo_b",
564                    "proof_lane": "binary-unit"
565                }
566            ]
567        }"#;
568        let error = ReferenceSurfaceRegistry::from_json_str(json)
569            .expect_err("duplicate ids must fail closed");
570        assert_eq!(
571            error,
572            ReferenceRegistryError::DuplicateSurfaceId("demo-surface".to_string())
573        );
574    }
575
576    #[test]
577    fn source_contract_guard_report_passes_registered_surfaces() {
578        let registry = ReferenceSurfaceRegistry::source_contract().expect("load source registry");
579        let report = registry.guard_report();
580        assert!(
581            report.is_pass(),
582            "guard report failures: {:?}",
583            report.failures
584        );
585        assert_eq!(report.checked_surface_count, registry.len());
586        assert!(
587            report
588                .checked_binaries
589                .contains(&"otel_trace_context_propagation_conformance".to_string())
590        );
591    }
592
593    #[test]
594    fn guard_report_fails_closed_for_live_reference_without_proof_lane() {
595        let registry = ReferenceSurfaceRegistry::from_json_str(
596            r#"{
597                "reference_surfaces": [
598                    {
599                        "surface_id": "live-reference-without-proof",
600                        "binary": "live_reference_without_proof_conformance",
601                        "source_path": "conformance/src/bin/live_reference_without_proof_conformance.rs",
602                        "reference_family": "demo",
603                        "reference_status": "live_reference_wired",
604                        "fail_closed_without_live_reference": false,
605                        "runtime_allowed_verdicts": ["pass"],
606                        "proof_command": "rch exec -- cargo test --manifest-path conformance/Cargo.toml --bin live_reference_without_proof_conformance",
607                        "proof_lane": ""
608                    }
609                ]
610            }"#,
611        )
612        .expect("parse inline registry");
613        let report = registry.guard_report();
614        assert!(!report.is_pass());
615        assert_eq!(report.verdict, "fail_closed");
616        assert!(report.failures.iter().any(|failure| {
617            failure.surface_id == "live-reference-without-proof"
618                && failure.reason == "missing-proof-lane"
619        }));
620    }
621}