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    /// Creates `Provenance` with the given state.
33    pub fn new(
34        kind: ArtifactKind,
35        corpus_hash: u64,
36        corpus_docs: usize,
37        ref_ppl: f64,
38        cand_ppl: f64,
39        delta_ppl: f64,
40        passed: bool,
41    ) -> Self {
42        Self {
43            kind,
44            corpus_hash,
45            corpus_docs,
46            engine_version: env!("CARGO_PKG_VERSION").to_string(),
47            ref_ppl,
48            cand_ppl,
49            delta_ppl,
50            passed,
51        }
52    }
53
54    /// Encode as CBOR (infallible for this schema; `Vec` writer never errors).
55    pub fn to_cbor(&self) -> Vec<u8> {
56        let mut buf = Vec::new();
57        let _ = ciborium::into_writer(self, &mut buf);
58        buf
59    }
60
61    /// Decode from CBOR; `None` on malformed bytes / schema mismatch.
62    pub fn from_cbor(bytes: &[u8]) -> Option<Self> {
63        ciborium::from_reader(bytes).ok()
64    }
65}
66
67/// Frame `artifact` bytes behind the CBOR provenance header:
68/// `[ MAGIC(8) | prov_len:u32 LE | CBOR(provenance) | artifact bytes ]`.
69pub fn frame_artifact(artifact: &[u8], prov: &Provenance) -> Vec<u8> {
70    let cbor = prov.to_cbor();
71    let mut out = Vec::with_capacity(8 + 4 + cbor.len() + artifact.len());
72    out.extend_from_slice(&FRAME_MAGIC);
73    out.extend_from_slice(&(cbor.len() as u32).to_le_bytes());
74    out.extend_from_slice(&cbor);
75    out.extend_from_slice(artifact);
76    out
77}
78
79/// Parse a framed artifact → `(provenance, artifact_bytes)`. The engine calls this before adopting
80/// an artifact so an unframed / corrupt / unparseable-provenance blob is rejected (fail-closed).
81pub fn parse_frame(bytes: &[u8]) -> Result<(Provenance, &[u8]), CalibrationError> {
82    if bytes.len() < 12 || bytes[..8] != FRAME_MAGIC {
83        return Err(CalibrationError::PackageFailed("bad frame magic".into()));
84    }
85    let prov_len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize;
86    let start = 12usize;
87    let end = start
88        .checked_add(prov_len)
89        .filter(|&e| e <= bytes.len())
90        .ok_or_else(|| CalibrationError::PackageFailed("provenance length out of range".into()))?;
91    let prov = Provenance::from_cbor(&bytes[start..end])
92        .ok_or_else(|| CalibrationError::PackageFailed("provenance CBOR unparseable".into()))?;
93    Ok((prov, &bytes[end..]))
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    fn sample_prov() -> Provenance {
101        Provenance::new(
102            ArtifactKind::AwqScales,
103            0xDEAD_BEEF,
104            12,
105            8.5,
106            8.7,
107            0.0235,
108            true,
109        )
110    }
111
112    #[test]
113    fn provenance_cbor_round_trips() {
114        let p = sample_prov();
115        let back = Provenance::from_cbor(&p.to_cbor()).expect("round-trip");
116        assert_eq!(back, p);
117        assert!(Provenance::from_cbor(&[0xFF, 0x00, 0x13]).is_none());
118    }
119
120    #[test]
121    fn frame_round_trips_and_preserves_artifact() {
122        let p = sample_prov();
123        let artifact = b"\x00\x01\x02the-real-artifact-bytes\xff";
124        let framed = frame_artifact(artifact, &p);
125        let (prov, body) = parse_frame(&framed).expect("parse");
126        assert_eq!(prov, p);
127        assert_eq!(body, artifact);
128    }
129
130    #[test]
131    fn parse_frame_rejects_garbage_and_truncation() {
132        assert!(parse_frame(b"not-a-frame").is_err());
133        assert!(parse_frame(&[]).is_err());
134        let mut framed = frame_artifact(b"x", &sample_prov());
135        // Corrupt the declared provenance length to overrun the buffer.
136        framed[8] = 0xFF;
137        framed[9] = 0xFF;
138        assert!(parse_frame(&framed).is_err());
139    }
140}