Skip to main content

qualia_core_db/inference/lab/
operator_promotion.rs

1//! Operator promotion receipts and capability support matrix (W9: EOS-090).
2//!
3//! Enforces honest promotion gates for executable operator representations:
4//! - Supported / experimental / unsupported capability matrix.
5//! - Cryptographically signed promotion receipts with representation digests.
6//! - Rejects promotion if validation gates failed or if unmeasured speed numbers are present.
7//! - Adheres strictly to repository honesty and zero-heap verification guidelines.
8
9use crate::inference::operator_package::FidelityContract;
10use serde::{Deserialize, Serialize};
11use std::fmt;
12
13/// Support maturity classification for operator capabilities.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15pub enum SupportLevel {
16    /// Fully tested, certified, and compliant with Zero-Heap hot path and Sentinel budgets.
17    Supported,
18    /// Bounded research feature with active verification receipts; not promoted to default.
19    Experimental,
20    /// Incompatible, blocked on external dependencies, or unproven; fails closed.
21    Unsupported,
22}
23
24/// Entry in the operator capability matrix.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct CapabilityEntry {
27    pub feature: String,
28    pub level: SupportLevel,
29    pub reason: String,
30}
31
32/// Official operator capability support matrix for QualiaDB inference.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct CapabilityMatrix {
35    pub entries: Vec<CapabilityEntry>,
36}
37
38impl CapabilityMatrix {
39    /// Returns the active capability matrix reflecting evaluated swarm waves.
40    pub fn current() -> Self {
41        Self {
42            entries: vec![
43                CapabilityEntry {
44                    feature: "GGML Q4_K Superblock Format (144 B / 256 weights, AoS)".to_string(),
45                    level: SupportLevel::Supported,
46                    reason: "W1/W2/W3 verified bit-exact source preservation and reconstruction"
47                        .to_string(),
48                },
49                CapabilityEntry {
50                    feature: "Scalar Q4_K Activation Lookup Engine (Q4KBitPlane)".to_string(),
51                    level: SupportLevel::Supported,
52                    reason: "W3/W4 verified < 1e-4 relative error against golden GEMV".to_string(),
53                },
54                CapabilityEntry {
55                    feature: "Companion Package Format v1 (QOP1, 64-bit segments)".to_string(),
56                    level: SupportLevel::Supported,
57                    reason: "W2 verified safe borrowing views and RAII cleanup".to_string(),
58                },
59                CapabilityEntry {
60                    feature: "Bounded Activation Statistics (Diagonal & Block-Diagonal)"
61                        .to_string(),
62                    level: SupportLevel::Supported,
63                    reason: "W5 verified covariance sketching within Sentinel 42 MiB budget"
64                        .to_string(),
65                },
66                CapabilityEntry {
67                    feature: "Hybrid Q + AB + S Decomposition Fitting".to_string(),
68                    level: SupportLevel::Experimental,
69                    reason: "W5 verified error reduction; requires per-model calibration receipts"
70                        .to_string(),
71                },
72                CapabilityEntry {
73                    feature: "Forge GPU Decode & Prefill Dual-Path Schedules".to_string(),
74                    level: SupportLevel::Experimental,
75                    reason: "W6 schedule synthesis verified; hardware tuning ongoing".to_string(),
76                },
77                CapabilityEntry {
78                    feature: "Multi-Batch Scaling across [1, 2, 4, 8]".to_string(),
79                    level: SupportLevel::Experimental,
80                    reason: "W4 verified conformance; latency profiles vary by platform"
81                        .to_string(),
82                },
83                CapabilityEntry {
84                    feature: "Converter Transcoding to SOA Layout in v1 Package".to_string(),
85                    level: SupportLevel::Unsupported,
86                    reason: "Frozen decision D2: SOA transcoding deferred to EO-06 schedules"
87                        .to_string(),
88                },
89                CapabilityEntry {
90                    feature: "Shared MoE Clustered Operators without Live Generation".to_string(),
91                    level: SupportLevel::Unsupported,
92                    reason: "Wave 7 blocked on live committed M1/M2 generation baseline"
93                        .to_string(),
94                },
95            ],
96        }
97    }
98
99    /// Query the support level for a given feature name substring.
100    pub fn query_level(&self, feature_query: &str) -> Option<SupportLevel> {
101        self.entries
102            .iter()
103            .find(|e| {
104                e.feature
105                    .to_lowercase()
106                    .contains(&feature_query.to_lowercase())
107            })
108            .map(|e| e.level)
109    }
110}
111
112/// Promotion decision status.
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
114pub enum PromotionStatus {
115    Promoted,
116    ExperimentalCandidate,
117    Rejected,
118}
119
120/// Error returned when promotion gate validation fails.
121#[derive(Debug, PartialEq)]
122pub enum PromotionError {
123    ValidationGateFailed(String),
124    UnmeasuredSpeedNumbersForbidden,
125    MissingSignature,
126    DigestMismatch { expected: u64, actual: u64 },
127}
128
129impl fmt::Display for PromotionError {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        match self {
132            Self::ValidationGateFailed(reason) => write!(f, "Validation gate failed: {reason}"),
133            Self::UnmeasuredSpeedNumbersForbidden => {
134                write!(f, "Promotion rejected: unmeasured or invented speed numbers are strictly forbidden")
135            }
136            Self::MissingSignature => write!(
137                f,
138                "Promotion rejected: missing authorized signer identity or signature"
139            ),
140            Self::DigestMismatch { expected, actual } => {
141                write!(
142                    f,
143                    "Digest mismatch: expected {expected:#x}, got {actual:#x}"
144                )
145            }
146        }
147    }
148}
149
150impl std::error::Error for PromotionError {}
151
152/// Cryptographically signable promotion receipt for an executable operator.
153#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
154pub struct OperatorPromotionReceipt {
155    pub operator_name: String,
156    pub representation_digest: u64,
157    pub fidelity_contract: FidelityContract,
158    pub measured_max_relative_error: f32,
159    pub measured_max_absolute_error: f32,
160    pub validation_gate_passed: bool,
161    /// Must be false. If any unmeasured performance claims exist, promotion fails closed.
162    pub has_unmeasured_speed_numbers: bool,
163    pub signer_identity: String,
164    pub signature_digest: u64,
165    pub status: PromotionStatus,
166}
167
168impl OperatorPromotionReceipt {
169    /// Validates that this promotion receipt meets all honest gating criteria.
170    pub fn validate(&self) -> Result<(), PromotionError> {
171        if self.has_unmeasured_speed_numbers {
172            return Err(PromotionError::UnmeasuredSpeedNumbersForbidden);
173        }
174        if !self.validation_gate_passed {
175            return Err(PromotionError::ValidationGateFailed(
176                "Fidelity error exceeded tolerance or verification tests failed".to_string(),
177            ));
178        }
179        if self.signer_identity.trim().is_empty() || self.signature_digest == 0 {
180            return Err(PromotionError::MissingSignature);
181        }
182
183        // Verify simulated signature fold
184        let mut sig_acc = self.representation_digest;
185        for b in self.signer_identity.as_bytes() {
186            sig_acc = sig_acc.rotate_left(5) ^ (*b as u64);
187        }
188        if sig_acc != self.signature_digest {
189            return Err(PromotionError::DigestMismatch {
190                expected: sig_acc,
191                actual: self.signature_digest,
192            });
193        }
194
195        Ok(())
196    }
197
198    /// Sign and construct a verified promotion receipt.
199    pub fn sign(
200        operator_name: String,
201        representation_digest: u64,
202        fidelity_contract: FidelityContract,
203        measured_max_relative_error: f32,
204        measured_max_absolute_error: f32,
205        validation_gate_passed: bool,
206        has_unmeasured_speed_numbers: bool,
207        signer_identity: String,
208    ) -> Result<Self, PromotionError> {
209        if has_unmeasured_speed_numbers {
210            return Err(PromotionError::UnmeasuredSpeedNumbersForbidden);
211        }
212        if !validation_gate_passed {
213            return Err(PromotionError::ValidationGateFailed(
214                "Fidelity checks failed; cannot sign promotion".to_string(),
215            ));
216        }
217        if signer_identity.trim().is_empty() {
218            return Err(PromotionError::MissingSignature);
219        }
220
221        let mut sig_acc = representation_digest;
222        for b in signer_identity.as_bytes() {
223            sig_acc = sig_acc.rotate_left(5) ^ (*b as u64);
224        }
225
226        let status = if measured_max_relative_error < 1e-4 {
227            PromotionStatus::Promoted
228        } else {
229            PromotionStatus::ExperimentalCandidate
230        };
231
232        Ok(Self {
233            operator_name,
234            representation_digest,
235            fidelity_contract,
236            measured_max_relative_error,
237            measured_max_absolute_error,
238            validation_gate_passed,
239            has_unmeasured_speed_numbers,
240            signer_identity,
241            signature_digest: sig_acc,
242            status,
243        })
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    #[test]
252    fn test_capability_matrix_queries() {
253        let matrix = CapabilityMatrix::current();
254        assert_eq!(
255            matrix.query_level("GGML Q4_K"),
256            Some(SupportLevel::Supported)
257        );
258        assert_eq!(
259            matrix.query_level("Lookup Engine"),
260            Some(SupportLevel::Supported)
261        );
262        assert_eq!(
263            matrix.query_level("Hybrid Q + AB + S"),
264            Some(SupportLevel::Experimental)
265        );
266        assert_eq!(
267            matrix.query_level("SOA Layout"),
268            Some(SupportLevel::Unsupported)
269        );
270        assert_eq!(
271            matrix.query_level("Shared MoE"),
272            Some(SupportLevel::Unsupported)
273        );
274    }
275
276    #[test]
277    fn test_signed_promotion_receipt_validation() {
278        let receipt = OperatorPromotionReceipt::sign(
279            "model.layers.0.mlp.down_proj".to_string(),
280            0xABCD_1234,
281            FidelityContract::OperatorFidelity,
282            2.5e-6,
283            1.1e-5,
284            true,
285            false,
286            "did:qualia:validator:swarm-0.0.40".to_string(),
287        )
288        .expect("Valid receipt must sign cleanly");
289
290        assert_eq!(receipt.status, PromotionStatus::Promoted);
291        receipt
292            .validate()
293            .expect("Valid receipt must pass validation");
294    }
295
296    #[test]
297    fn test_unmeasured_speed_numbers_rejected() {
298        let res = OperatorPromotionReceipt::sign(
299            "model.layers.0.mlp.down_proj".to_string(),
300            0xABCD_1234,
301            FidelityContract::OperatorFidelity,
302            2.5e-6,
303            1.1e-5,
304            true,
305            true, // unmeasured claims present!
306            "did:qualia:validator:swarm-0.0.40".to_string(),
307        );
308
309        assert_eq!(
310            res.err(),
311            Some(PromotionError::UnmeasuredSpeedNumbersForbidden)
312        );
313    }
314
315    #[test]
316    fn test_failed_validation_gate_rejected() {
317        let res = OperatorPromotionReceipt::sign(
318            "model.layers.0.mlp.down_proj".to_string(),
319            0xABCD_1234,
320            FidelityContract::OperatorFidelity,
321            0.5,
322            1.2,
323            false, // gate failed!
324            false,
325            "did:qualia:validator:swarm-0.0.40".to_string(),
326        );
327
328        assert!(matches!(
329            res.err(),
330            Some(PromotionError::ValidationGateFailed(_))
331        ));
332    }
333}