Skip to main content

qualia_core_db/sensing/
association_contract.rs

1//! Host-model and evidence-policy boundaries for relational association.
2
3use core::num::NonZeroU64;
4
5use super::super::{
6    radio_evidence::{RadioIdentifier, RadioObservationTime},
7    record::{CalibrationDeclaration, MeasurementQuality, ProvenanceDeclaration},
8    uncertainty::{EvidenceReference, MethodVersion, UncertaintyRecord},
9    MeasurementModality, PhysicalFieldSemantics, SemanticId,
10};
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum CandidateKind {
14    Unknown,
15    Entity,
16    Agent,
17}
18
19/// Opaque candidate reference, not an authenticated identity. Ontology types
20/// can denote an animal, instrument, person, physical process, or another kind.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct EntityCandidate {
23    pub id: NonZeroU64,
24    pub kind: CandidateKind,
25    pub ontology_type: SemanticId,
26}
27
28/// Separate binary propositions may coexist; ownership, proximity, care and
29/// device operation must use separate caller-selected relation identifiers.
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub struct AssociationHypothesis {
32    pub id: NonZeroU64,
33    pub subject: EntityCandidate,
34    pub relation_id: NonZeroU64,
35    pub object: EntityCandidate,
36}
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum AssociationEvidenceKind {
40    Measurement(MeasurementModality),
41    RadioIdentifier,
42    NfcIdentifier,
43    EnvironmentalContext,
44    SocialContext,
45    IdentityAnchor,
46    Other(SemanticId),
47}
48
49#[derive(Clone, Copy, Debug, PartialEq)]
50pub enum AssociationValue {
51    Unknown,
52    Missing,
53    Scalar {
54        value: f64,
55        quantity: SemanticId,
56        unit: SemanticId,
57    },
58    Radio(RadioIdentifier),
59    /// Resolved by the host model/authority, including NFC records and identity
60    /// anchor enumerations. A citation alone does not authenticate its contents.
61    Reference(EvidenceReference),
62}
63
64/// Missing metadata remains explicit and is passed unchanged to both trust
65/// boundaries. Dependence group IDs are declarations, not independence proof.
66#[derive(Clone, Copy, Debug, PartialEq)]
67pub struct AssociationEvidence<'a> {
68    pub observation_id: NonZeroU64,
69    pub source_id: SemanticId,
70    pub context_id: SemanticId,
71    pub kind: AssociationEvidenceKind,
72    pub value: AssociationValue,
73    pub observed_at: RadioObservationTime,
74    pub quality: MeasurementQuality,
75    pub calibration: CalibrationDeclaration,
76    pub provenance: ProvenanceDeclaration,
77    pub field: Option<PhysicalFieldSemantics>,
78    pub uncertainty: Option<&'a UncertaintyRecord>,
79    pub dependence_group: Option<NonZeroU64>,
80}
81
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub enum DependenceAssumption {
84    Unknown,
85    /// One model likelihood for the full joint observation, with arbitrary
86    /// correlation. No multiplication of individual measurements occurs.
87    Joint,
88    /// Groups are conditionally independent under BOTH the hypothesis and its
89    /// negation. Each group's internal correlation remains the model's job.
90    IndependentGroups {
91        justification: EvidenceReference,
92    },
93}
94
95#[derive(Clone, Copy, Debug, PartialEq, Eq)]
96pub struct AssociationModelReference {
97    pub method: MethodVersion,
98    pub calibration: EvidenceReference,
99}
100
101/// No person-specific policy is assumed. Even a scientific case without an
102/// actor or configured policy needs an affirmative authority decision.
103#[derive(Clone, Copy, Debug, PartialEq, Eq)]
104pub struct AssociationRequest {
105    pub context_id: NonZeroU64,
106    pub purpose_id: NonZeroU64,
107    pub actor_id: Option<NonZeroU64>,
108    pub policy_context: Option<EvidenceReference>,
109}
110
111/// Publication results are in exact hypothesis order. Combined with the other
112/// authority arguments, they describe every proposed output field except the
113/// publication decision that the authority is about to issue.
114#[derive(Clone, Copy, Debug, PartialEq)]
115pub enum AssociationPhase<'a> {
116    Evaluate,
117    Publish {
118        results: &'a [super::AssociationResult],
119        evaluation_decision: EvidenceReference,
120    },
121}
122
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
124pub enum AssociationPermission {
125    Unknown,
126    Denied,
127    Approved { decision: EvidenceReference },
128}
129
130/// Must check current host/Qualia policy, evidence provenance and appropriate
131/// use, candidate/relation scope, model calibration/applicability, and any
132/// independence justification. Context citations alone are not permission.
133/// Evaluate decisions bind the input scope. Publish decisions must bind that
134/// scope, the evaluation decision, and every exact proposed result; inspecting
135/// only the inputs is insufficient. Returned citations refer to the authority's
136/// phase-specific records, not cryptographic receipts created by this module.
137/// Calls must be bounded, allocation-free and deterministic for the snapshot.
138pub trait AssociationAuthority {
139    fn authorize(
140        &mut self,
141        phase: AssociationPhase<'_>,
142        request: &AssociationRequest,
143        hypotheses: &[AssociationHypothesis],
144        evidence: &[AssociationEvidence<'_>],
145        model: AssociationModelReference,
146        dependence: DependenceAssumption,
147    ) -> AssociationPermission;
148}
149
150/// A filtered borrow prevents accidental per-record multiplication in the
151/// estimator. The host model must still account for all within-group dependence.
152#[derive(Clone, Copy)]
153pub struct AssociationEvidenceGroup<'a, 'data> {
154    pub(super) evidence: &'a [AssociationEvidence<'data>],
155    pub(super) group: Option<NonZeroU64>,
156}
157
158impl<'a, 'data> AssociationEvidenceGroup<'a, 'data> {
159    pub const fn group_id(self) -> Option<NonZeroU64> {
160        self.group
161    }
162
163    pub fn records(self) -> impl Iterator<Item = &'a AssociationEvidence<'data>> {
164        self.evidence
165            .iter()
166            .filter(move |record| self.group.is_none() || record.dependence_group == self.group)
167    }
168}
169
170/// Natural logs of joint likelihoods/densities for one group under H and !H.
171/// Negative infinity denotes impossible evidence; NaN/+infinity are rejected.
172#[derive(Clone, Copy, Debug, PartialEq)]
173pub struct BinaryLogLikelihoods {
174    pub given_association: f64,
175    pub given_no_association: f64,
176}
177
178/// Supplies a separately calibrated prior and joint group likelihoods. `None`
179/// means outside model coverage, never neutral evidence or a default prior.
180/// The prior must not already incorporate observations in the evidence slice.
181/// Implementations must be bounded, allocation-free and deterministic; this
182/// boundary does not train, calibrate, authenticate or sandbox a host model.
183pub trait CalibratedAssociationModel {
184    fn reference(&self) -> AssociationModelReference;
185    fn prior_probability(
186        &self,
187        request: &AssociationRequest,
188        hypothesis: &AssociationHypothesis,
189    ) -> Option<f64>;
190    fn joint_log_likelihoods(
191        &self,
192        request: &AssociationRequest,
193        hypothesis: &AssociationHypothesis,
194        evidence: AssociationEvidenceGroup<'_, '_>,
195    ) -> Option<BinaryLogLikelihoods>;
196}