Skip to main content

qualia_core_db/modalities/
reconciliation.rs

1//! Corpus reconciliation and vintage staleness engine (§GAP-11, reconciliation.md).
2//!
3//! Models the temporal distance between the internal view (held state stamped with vintage)
4//! and the external view (authoritative upstream or live feed). Replaces silent overwrites
5//! with governed comparison (`Converged`, `Diverged`, `Deferred`, `Contested`), queryable staleness,
6//! and `reCheckable` cascades on derived downstream claims. Zero-heap hot path.
7
8use crate::{q_hash, NQuin};
9
10/// Bit flag in Quin metadata (bit 15) indicating a downstream claim is re-checkable due to upstream vintage advance.
11pub const RECHECKABLE_FLAG: u64 = 1 << 15;
12
13/// Outcome status of an internal-external view reconciliation.
14#[repr(u8)]
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
16pub enum ReconciliationStatus {
17    /// Internal view matches external view.
18    #[default]
19    Converged = 0,
20    /// Upstream vintage or content has advanced beyond held state.
21    Diverged = 1,
22    /// Upstream source update received but reconciliation intentionally deferred (e.g. pending review).
23    Deferred = 2,
24    /// Ground-truth dispute or conflicting source data recorded.
25    Contested = 3,
26}
27
28/// A reconciliation event record measuring vintage distance and state agreement.
29#[derive(Debug, Clone, Copy, PartialEq)]
30pub struct ReconciliationRecord {
31    pub entity_id: u64,
32    pub internal_vintage: u32,
33    pub external_vintage: u32,
34    pub reconciled_at: u32,
35    pub expected_lag_s: u32,
36    pub status: ReconciliationStatus,
37    pub divergence_score: f32,
38}
39
40impl ReconciliationRecord {
41    /// Whether the held state is considered stale at `now` relative to `expected_lag_s`.
42    #[inline]
43    pub fn is_stale(&self, now: u32) -> bool {
44        let elapsed = now.saturating_sub(self.reconciled_at);
45        elapsed > self.expected_lag_s || self.external_vintage > self.internal_vintage
46    }
47}
48
49/// Compare internal view against external view to produce a reconciliation record.
50/// Pure function, zero-heap.
51pub fn compare_views(
52    entity_id: u64,
53    internal_fingerprint: u64,
54    external_fingerprint: u64,
55    internal_vintage: u32,
56    external_vintage: u32,
57    now: u32,
58    expected_lag_s: u32,
59) -> ReconciliationRecord {
60    let (status, divergence_score) = if internal_fingerprint == external_fingerprint {
61        (ReconciliationStatus::Converged, 0.0)
62    } else if external_vintage > internal_vintage {
63        let vintage_delta = (external_vintage - internal_vintage) as f32;
64        (ReconciliationStatus::Diverged, vintage_delta.min(1.0))
65    } else {
66        // Same vintage but differing content indicates a contested assertion or alternate edition
67        (ReconciliationStatus::Contested, 0.5)
68    };
69
70    ReconciliationRecord {
71        entity_id,
72        internal_vintage,
73        external_vintage,
74        reconciled_at: now,
75        expected_lag_s,
76        status,
77        divergence_score,
78    }
79}
80
81/// Cascades re-check flags onto downstream derived claims when an upstream reconciliation diverged.
82/// Sets `RECHECKABLE_FLAG` (bit 15) in the metadata field of each matching quin.
83/// Returns the number of updated quins. Zero-heap caller-buffered.
84pub fn cascade_recheck_flags(
85    record: &ReconciliationRecord,
86    downstream_claims: &mut [NQuin],
87) -> usize {
88    if record.status == ReconciliationStatus::Converged {
89        return 0;
90    }
91
92    let mut updated = 0usize;
93    for q in downstream_claims.iter_mut() {
94        if q.context == record.entity_id || q.subject == record.entity_id {
95            if (q.metadata & RECHECKABLE_FLAG) == 0 {
96                q.metadata |= RECHECKABLE_FLAG;
97                q.parity = q.subject ^ q.predicate ^ q.object ^ q.context;
98                updated += 1;
99            }
100        }
101    }
102    updated
103}
104
105/// Predicate URI for reconciliation event (`qualia:reconciliation:Event`).
106#[inline]
107pub fn reconciliation_event_predicate() -> u64 {
108    q_hash("qualia:reconciliation:Event")
109}
110
111/// Predicate URI for staleness status (`qualia:reconciliation:isStale`).
112#[inline]
113pub fn is_stale_predicate() -> u64 {
114    q_hash("qualia:reconciliation:isStale")
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    fn test_compare_views_converged() {
123        let rec = compare_views(0x123, 0xABC, 0xABC, 2026, 2026, 1000, 3600);
124        assert_eq!(rec.status, ReconciliationStatus::Converged);
125        assert_eq!(rec.divergence_score, 0.0);
126        assert!(!rec.is_stale(1500));
127        assert!(rec.is_stale(5000)); // exceeded lag
128    }
129
130    #[test]
131    fn test_compare_views_diverged() {
132        let rec = compare_views(0x123, 0xABC, 0xDEF, 2024, 2026, 1000, 3600);
133        assert_eq!(rec.status, ReconciliationStatus::Diverged);
134        assert!(rec.is_stale(1050)); // upstream vintage is newer
135    }
136
137    #[test]
138    fn test_cascade_recheck_flags() {
139        let rec = compare_views(0x999, 0x111, 0x222, 1, 2, 100, 300);
140        let q1 = NQuin {
141            subject: 0x999,
142            predicate: q_hash("pred:metric"),
143            object: 100,
144            context: 0,
145            metadata: 0,
146            parity: 0,
147        };
148        let q2 = NQuin {
149            subject: 0x888,
150            predicate: q_hash("pred:unrelated"),
151            object: 200,
152            context: 0,
153            metadata: 0,
154            parity: 0,
155        };
156
157        let mut claims = [q1, q2];
158        let count = cascade_recheck_flags(&rec, &mut claims);
159        assert_eq!(count, 1);
160        assert_ne!(claims[0].metadata & RECHECKABLE_FLAG, 0);
161        assert_eq!(claims[1].metadata & RECHECKABLE_FLAG, 0);
162    }
163}