Skip to main content

qualia_core_db/sensing/
grounding.rs

1//! Bounded fail-closed grounding boundary for sensing-derived claims.
2//!
3//! This module compares explicit physical semantics and exact NQuin assertions,
4//! preserves source/sample/citation identity and declared uncertainty, then
5//! requires an injected evidence authority before any claim can be accepted.
6//! It does not authenticate signatures itself, resolve arbitrary citation
7//! hashes, establish scientific truth, or persist/audit a decision.
8
9use crate::NQuin;
10
11use super::record::CalibrationDeclaration;
12
13pub const MAX_SENSING_GROUNDING_EVIDENCE: usize = 64;
14pub const UNCERTAINTY_SCALE: u32 = 1_000_000;
15
16/// Explicit proposition and physical quantity/unit binding to evaluate.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub struct SensingClaim {
19    assertion: NQuin,
20    physical_quantity_id: u64,
21    unit_id: u64,
22}
23
24impl SensingClaim {
25    pub const fn new(
26        assertion: NQuin,
27        physical_quantity_id: u64,
28        unit_id: u64,
29    ) -> Result<Self, GroundingError> {
30        if physical_quantity_id == 0 || unit_id == 0 {
31            return Err(GroundingError::MissingPhysicalSemantics);
32        }
33        Ok(Self {
34            assertion,
35            physical_quantity_id,
36            unit_id,
37        })
38    }
39
40    pub const fn assertion(self) -> NQuin {
41        self.assertion
42    }
43
44    pub const fn physical_quantity_id(self) -> u64 {
45        self.physical_quantity_id
46    }
47
48    pub const fn unit_id(self) -> u64 {
49        self.unit_id
50    }
51}
52
53/// An explicit, unresolved sensing-evidence declaration.
54///
55/// These values are assertions until `SensingEvidenceAuthenticator` confirms
56/// the exact declaration against trusted signed evidence. Unknown uncertainty
57/// remains `Unknown`; it is never replaced by zero. A calibration enum value
58/// is likewise a declaration, not cryptographic proof by itself.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub struct SensingEvidence {
61    citation_id: u64,
62    source_id: u64,
63    sample_id: u64,
64    assertion: NQuin,
65    physical_quantity_id: u64,
66    unit_id: u64,
67    uncertainty: EvidenceUncertainty,
68    calibration: CalibrationDeclaration,
69}
70
71impl SensingEvidence {
72    #[allow(clippy::too_many_arguments)]
73    pub const fn new(
74        citation_id: u64,
75        source_id: u64,
76        sample_id: u64,
77        assertion: NQuin,
78        physical_quantity_id: u64,
79        unit_id: u64,
80        uncertainty: EvidenceUncertainty,
81        calibration: CalibrationDeclaration,
82    ) -> Result<Self, GroundingError> {
83        if citation_id == 0 || source_id == 0 || sample_id == 0 {
84            return Err(GroundingError::InvalidIdentifier);
85        }
86        if physical_quantity_id == 0 || unit_id == 0 {
87            return Err(GroundingError::MissingPhysicalSemantics);
88        }
89        Ok(Self {
90            citation_id,
91            source_id,
92            sample_id,
93            assertion,
94            physical_quantity_id,
95            unit_id,
96            uncertainty,
97            calibration,
98        })
99    }
100
101    pub const fn citation_id(self) -> u64 {
102        self.citation_id
103    }
104
105    pub const fn source_id(self) -> u64 {
106        self.source_id
107    }
108
109    pub const fn sample_id(self) -> u64 {
110        self.sample_id
111    }
112
113    pub const fn assertion(self) -> NQuin {
114        self.assertion
115    }
116
117    pub const fn physical_quantity_id(self) -> u64 {
118        self.physical_quantity_id
119    }
120
121    pub const fn unit_id(self) -> u64 {
122        self.unit_id
123    }
124
125    pub const fn uncertainty(self) -> EvidenceUncertainty {
126        self.uncertainty
127    }
128
129    pub const fn calibration(self) -> CalibrationDeclaration {
130        self.calibration
131    }
132}
133
134/// Relative uncertainty declaration in millionths, or explicitly unknown.
135#[derive(Clone, Copy, Debug, PartialEq, Eq)]
136pub enum EvidenceUncertainty {
137    Unknown,
138    RelativeMillionths(u32),
139}
140
141impl EvidenceUncertainty {
142    pub const fn relative_millionths(value: u32) -> Result<Self, GroundingError> {
143        if value > UNCERTAINTY_SCALE {
144            return Err(GroundingError::InvalidUncertainty);
145        }
146        Ok(Self::RelativeMillionths(value))
147    }
148}
149
150/// Implemented only at the trust boundary that can verify the signed evidence
151/// envelope and its source/grant/revocation/retention state. `true` must bind
152/// every field of `evidence`, including its fact bytes, unit, uncertainty,
153/// calibration declaration and IDs; a bare hash or unsigned record is never
154/// sufficient. This trait is an authority boundary, not a signature algorithm.
155pub trait SensingEvidenceAuthenticator {
156    fn authenticates(&self, evidence: &SensingEvidence) -> bool;
157
158    /// Confirm that the referenced calibration artifact itself is valid for
159    /// this source/sample/quantity/time. A signed declaration alone is not
160    /// calibration verification. Implementations may conservatively return
161    /// false when no calibration authority or resolver is available.
162    fn calibration_verified(&self, _evidence: &SensingEvidence) -> bool {
163        false
164    }
165}
166
167#[derive(Clone, Copy, Debug, PartialEq, Eq)]
168pub struct GroundingPolicy {
169    maximum_auto_uncertainty_millionths: u32,
170    require_calibration: bool,
171}
172
173impl GroundingPolicy {
174    pub const fn new(
175        maximum_auto_uncertainty_millionths: u32,
176        require_calibration: bool,
177    ) -> Result<Self, GroundingError> {
178        if maximum_auto_uncertainty_millionths > UNCERTAINTY_SCALE {
179            return Err(GroundingError::InvalidPolicy);
180        }
181        Ok(Self {
182            maximum_auto_uncertainty_millionths,
183            require_calibration,
184        })
185    }
186}
187
188/// Deterministic disposition. `Accepted` means authenticated support met the
189/// declared uncertainty/calibration policy; it does not mean physical truth.
190#[derive(Clone, Copy, Debug, PartialEq, Eq)]
191pub enum GroundingDecision {
192    Accepted {
193        citation_id: u64,
194        source_id: u64,
195        sample_id: u64,
196        uncertainty_millionths: u32,
197    },
198    Review {
199        citation_id: u64,
200        source_id: u64,
201        sample_id: u64,
202        reason: ReviewReason,
203    },
204    Denied(DenialReason),
205}
206
207#[derive(Clone, Copy, Debug, PartialEq, Eq)]
208pub enum ReviewReason {
209    UnknownUncertainty,
210    UncertaintyAbovePolicy,
211    CalibrationNotVerified,
212}
213
214#[derive(Clone, Copy, Debug, PartialEq, Eq)]
215pub enum DenialReason {
216    NoEvidence,
217    TooManyEvidenceItems,
218    DuplicateCitation,
219    NoExactSupport,
220    UnsupportedEvidenceOnly,
221    UnauthenticatedExactSupport,
222    InvalidUncertainty,
223}
224
225#[derive(Clone, Copy, Debug, PartialEq, Eq)]
226pub enum GroundingError {
227    InvalidIdentifier,
228    MissingPhysicalSemantics,
229    InvalidUncertainty,
230    InvalidPolicy,
231}
232
233/// Ground a claim against at most 64 explicitly resolved evidence records.
234///
235/// Only exact `(subject,predicate,object,context,metadata)` matches with equal
236/// physical quantity and unit count as support. The evaluator never accepts an
237/// unauthenticated exact match. Among authenticated exact matches, it chooses
238/// the lowest known uncertainty, then citation ID, for deterministic output.
239/// Unknown/high uncertainty or absent required calibration returns `Review`;
240/// no exact authenticated support returns `Denied`.
241pub fn evaluate_sensing_grounding(
242    claim: SensingClaim,
243    evidence: &[SensingEvidence],
244    policy: GroundingPolicy,
245    authenticator: &dyn SensingEvidenceAuthenticator,
246) -> GroundingDecision {
247    if evidence.is_empty() {
248        return GroundingDecision::Denied(DenialReason::NoEvidence);
249    }
250    if evidence.len() > MAX_SENSING_GROUNDING_EVIDENCE {
251        return GroundingDecision::Denied(DenialReason::TooManyEvidenceItems);
252    }
253    for i in 0..evidence.len() {
254        for j in (i + 1)..evidence.len() {
255            if evidence[i].citation_id == evidence[j].citation_id {
256                return GroundingDecision::Denied(DenialReason::DuplicateCitation);
257            }
258        }
259    }
260
261    let mut exact_seen = false;
262    let mut best: Option<(usize, Option<u32>)> = None;
263    for (index, item) in evidence.iter().enumerate() {
264        if !same_assertion(&claim.assertion, &item.assertion)
265            || claim.physical_quantity_id != item.physical_quantity_id
266            || claim.unit_id != item.unit_id
267        {
268            continue;
269        }
270        exact_seen = true;
271        if !authenticator.authenticates(item) {
272            continue;
273        }
274        let uncertainty = match item.uncertainty {
275            EvidenceUncertainty::Unknown => None,
276            EvidenceUncertainty::RelativeMillionths(value) if value <= UNCERTAINTY_SCALE => {
277                Some(value)
278            }
279            EvidenceUncertainty::RelativeMillionths(_) => {
280                return GroundingDecision::Denied(DenialReason::InvalidUncertainty)
281            }
282        };
283        let replace_best = match best {
284            None => true,
285            Some((best_index, best_uncertainty)) => {
286                uncertainty_order(uncertainty, item.citation_id)
287                    < uncertainty_order(best_uncertainty, evidence[best_index].citation_id)
288            }
289        };
290        if replace_best {
291            best = Some((index, uncertainty));
292        }
293    }
294
295    let Some((best_index, uncertainty)) = best else {
296        return GroundingDecision::Denied(if exact_seen {
297            DenialReason::UnauthenticatedExactSupport
298        } else if evidence
299            .iter()
300            .any(|item| same_assertion(&claim.assertion, &item.assertion))
301        {
302            DenialReason::UnsupportedEvidenceOnly
303        } else {
304            DenialReason::NoExactSupport
305        });
306    };
307    let selected = evidence[best_index];
308    let identity = (selected.citation_id, selected.source_id, selected.sample_id);
309    let Some(uncertainty_millionths) = uncertainty else {
310        return GroundingDecision::Review {
311            citation_id: identity.0,
312            source_id: identity.1,
313            sample_id: identity.2,
314            reason: ReviewReason::UnknownUncertainty,
315        };
316    };
317    if uncertainty_millionths > policy.maximum_auto_uncertainty_millionths {
318        return GroundingDecision::Review {
319            citation_id: identity.0,
320            source_id: identity.1,
321            sample_id: identity.2,
322            reason: ReviewReason::UncertaintyAbovePolicy,
323        };
324    }
325    if policy.require_calibration
326        && (!matches!(selected.calibration, CalibrationDeclaration::Calibrated(_))
327            || !authenticator.calibration_verified(&selected))
328    {
329        return GroundingDecision::Review {
330            citation_id: identity.0,
331            source_id: identity.1,
332            sample_id: identity.2,
333            reason: ReviewReason::CalibrationNotVerified,
334        };
335    }
336    GroundingDecision::Accepted {
337        citation_id: identity.0,
338        source_id: identity.1,
339        sample_id: identity.2,
340        uncertainty_millionths,
341    }
342}
343
344fn uncertainty_order(uncertainty: Option<u32>, citation_id: u64) -> (u8, u32, u64) {
345    match uncertainty {
346        Some(value) => (0, value, citation_id),
347        None => (1, u32::MAX, citation_id),
348    }
349}
350
351fn same_assertion(left: &NQuin, right: &NQuin) -> bool {
352    left.subject == right.subject
353        && left.predicate == right.predicate
354        && left.object == right.object
355        && left.context == right.context
356        && left.metadata == right.metadata
357}