Skip to main content

qualia_core_db/wgsl_forge/calibration/
package.rs

1//! W10 calibration — stage 5: provenance + packaging.
2//!
3//! A certified artifact is framed with a CBOR provenance header (corpus hash, engine version, gate
4//! numbers) so the engine can refuse an artifact that wasn't produced + certified by the forge.
5//! Provenance rides as CBOR — the project's canonical payload substrate (see the memory note
6//! `feedback-cbor-ld-payloads-not-adhoc-json`), not ad-hoc JSON.
7
8#![cfg(not(target_arch = "wasm32"))]
9
10use super::{ArtifactKind, CalibrationError};
11
12/// Frame magic — `QCAL` + version.
13pub const FRAME_MAGIC: [u8; 8] = *b"QCAL0001";
14
15/// Certification provenance for a calibration artifact.
16#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
17pub struct Provenance {
18    pub kind: ArtifactKind,
19    /// FNV-1a content hash of the calibration corpus.
20    pub corpus_hash: u64,
21    pub corpus_docs: usize,
22    /// Engine/crate version that produced + certified this artifact (`CARGO_PKG_VERSION`).
23    pub engine_version: String,
24    pub ref_ppl: f64,
25    pub cand_ppl: f64,
26    pub delta_ppl: f64,
27    pub passed: bool,
28}
29
30impl Provenance {
31    #[allow(clippy::too_many_arguments)]
32    pub fn new(
33        kind: ArtifactKind,
34        corpus_hash: u64,
35        corpus_docs: usize,
36        ref_ppl: f64,
37        cand_ppl: f64,
38        delta_ppl: f64,
39        passed: bool,
40    ) -> Self {
41        Self {
42            kind,
43            corpus_hash,
44            corpus_docs,
45            engine_version: env!("CARGO_PKG_VERSION").to_string(),
46            ref_ppl,
47            cand_ppl,
48            delta_ppl,
49            passed,
50        }
51    }
52
53    /// Encode as CBOR (infallible for this schema; `Vec` writer never errors).
54    pub fn to_cbor(&self) -> Vec<u8> {
55        let mut buf = Vec::new();
56        let _ = ciborium::into_writer(self, &mut buf);
57        buf
58    }
59
60    /// Decode from CBOR; `None` on malformed bytes / schema mismatch.
61    pub fn from_cbor(bytes: &[u8]) -> Option<Self> {
62        ciborium::from_reader(bytes).ok()
63    }
64}
65
66/// Frame `artifact` bytes behind the CBOR provenance header:
67/// `[ MAGIC(8) | prov_len:u32 LE | CBOR(provenance) | artifact bytes ]`.
68pub fn frame_artifact(artifact: &[u8], prov: &Provenance) -> Vec<u8> {
69    let cbor = prov.to_cbor();
70    let mut out = Vec::with_capacity(8 + 4 + cbor.len() + artifact.len());
71    out.extend_from_slice(&FRAME_MAGIC);
72    out.extend_from_slice(&(cbor.len() as u32).to_le_bytes());
73    out.extend_from_slice(&cbor);
74    out.extend_from_slice(artifact);
75    out
76}
77
78/// Parse a framed artifact → `(provenance, artifact_bytes)`. The engine calls this before adopting
79/// an artifact so an unframed / corrupt / unparseable-provenance blob is rejected (fail-closed).
80pub fn parse_frame(bytes: &[u8]) -> Result<(Provenance, &[u8]), CalibrationError> {
81    if bytes.len() < 12 || bytes[..8] != FRAME_MAGIC {
82        return Err(CalibrationError::PackageFailed("bad frame magic".into()));
83    }
84    let prov_len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;
85    let start = 12usize;
86    let end = start
87        .checked_add(prov_len)
88        .filter(|&e| e <= bytes.len())
89        .ok_or_else(|| CalibrationError::PackageFailed("provenance length out of range".into()))?;
90    let prov = Provenance::from_cbor(&bytes[start..end])
91        .ok_or_else(|| CalibrationError::PackageFailed("provenance CBOR unparseable".into()))?;
92    Ok((prov, &bytes[end..]))
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    fn sample_prov() -> Provenance {
100        Provenance::new(
101            ArtifactKind::AwqScales,
102            0xDEAD_BEEF,
103            12,
104            8.5,
105            8.7,
106            0.0235,
107            true,
108        )
109    }
110
111    #[test]
112    fn provenance_cbor_round_trips() {
113        let p = sample_prov();
114        let back = Provenance::from_cbor(&p.to_cbor()).expect("round-trip");
115        assert_eq!(back, p);
116        assert!(Provenance::from_cbor(&[0xFF, 0x00, 0x13]).is_none());
117    }
118
119    #[test]
120    fn frame_round_trips_and_preserves_artifact() {
121        let p = sample_prov();
122        let artifact = b"\x00\x01\x02the-real-artifact-bytes\xff";
123        let framed = frame_artifact(artifact, &p);
124        let (prov, body) = parse_frame(&framed).expect("parse");
125        assert_eq!(prov, p);
126        assert_eq!(body, artifact);
127    }
128
129    #[test]
130    fn parse_frame_rejects_garbage_and_truncation() {
131        assert!(parse_frame(b"not-a-frame").is_err());
132        assert!(parse_frame(&[]).is_err());
133        let mut framed = frame_artifact(b"x", &sample_prov());
134        // Corrupt the declared provenance length to overrun the buffer.
135        framed[8] = 0xFF;
136        framed[9] = 0xFF;
137        assert!(parse_frame(&framed).is_err());
138    }
139}