Skip to main content

qualia_core_db/net/peer/replication/
receipts.rs

1//! Identity, local effect, and durable receipt as distinct stages (SVC-01.04).
2//!
3//! Operation identity is a SHA-384 [`StrongDigest`]. Binding an id is not a
4//! local graph effect. A local effect is not a durable receipt. Transport ACK
5//! and consumption never become [`ReceiptClass::DurableReceipt`].
6//! [`DeliveryStage::DurableApplied`] is a durable receipt only after the
7//! effect ran. [`DeliveryStage::EconomicReceipt`] requires that durable-applied
8//! stage already recorded. Packages remain open; this library does not claim
9//! exactly-once external work or CORE-03 atomic commit.
10
11use crate::net::qdnf::errors::QdnfError;
12use crate::net::qdnf::session::datagrams::DeliveryStage;
13use crate::net::qdnf::types::StrongDigest;
14use crate::{q_hash, NQuin};
15
16/// Occupied identity slots. A 17th distinct bind is Capacity.
17pub const MAX_RECEIPTS: usize = 16;
18
19/// Crash-safe `.q42` SuperBlock commit states (`NET-20` / `R09`).
20#[repr(u8)]
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum SuperBlockCommitState {
23    /// Chunks received in staging area, not yet verified.
24    Staged = 1,
25    /// SHA-384 chunk digests, SHA-256 SuperBlock digest, and 5-field NQuin parity verified.
26    Verified = 2,
27    /// Interrupted commit / power-fail recovery hold; requires re-verification before commit.
28    Indeterminate = 3,
29    /// Durably committed to `.q42` volume after verification.
30    Committed = 4,
31}
32
33/// Durability class actually achieved. Transport ACK is never this enum's
34/// durable variant.
35#[repr(u8)]
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub enum ReceiptClass {
38    /// Id bound; no local effect.
39    Identity = 1,
40    /// Local apply; not durable.
41    Effect = 2,
42    /// Durable applied receipt (or economic receipt after that stage).
43    DurableReceipt = 3,
44}
45
46#[derive(Clone, Copy)]
47struct Slot {
48    occupied: bool,
49    effect: bool,
50    durable_applied: bool,
51    id: StrongDigest,
52    /// SHA-384 of exact effect bytes. ZERO means no effect digest recorded.
53    effect_digest: StrongDigest,
54}
55
56/// Sixteen-slot identity / effect / receipt table.
57pub struct ReceiptTable {
58    slots: [Slot; MAX_RECEIPTS],
59}
60
61impl ReceiptTable {
62    /// Creates a default `ReceiptTable`.
63    pub const fn new() -> Self {
64        Self {
65            slots: [Slot {
66                occupied: false,
67                effect: false,
68                durable_applied: false,
69                id: StrongDigest::ZERO,
70                effect_digest: StrongDigest::ZERO,
71            }; MAX_RECEIPTS],
72        }
73    }
74
75    fn find_id(&self, id: &StrongDigest) -> Option<usize> {
76        let mut i = 0usize;
77        while i < MAX_RECEIPTS {
78            if self.slots[i].occupied && self.slots[i].id == *id {
79                return Some(i);
80            }
81            i += 1;
82        }
83        None
84    }
85
86    fn find_free(&self) -> Option<usize> {
87        let mut i = 0usize;
88        while i < MAX_RECEIPTS {
89            if !self.slots[i].occupied {
90                return Some(i);
91            }
92            i += 1;
93        }
94        None
95    }
96}
97
98impl Default for ReceiptTable {
99    fn default() -> Self {
100        Self::new()
101    }
102}
103
104fn reject_zero(id: StrongDigest) -> Result<(), QdnfError> {
105    if id == StrongDigest::ZERO {
106        Err(QdnfError::Malformed)
107    } else {
108        Ok(())
109    }
110}
111
112/// Bind `id` as operation identity. Zero digest is malformed. A duplicate bind
113/// of the same id is idempotent. Distinct ids beyond [`MAX_RECEIPTS`] are
114/// capacity.
115pub fn bind_identity(table: &mut ReceiptTable, id: StrongDigest) -> Result<(), QdnfError> {
116    reject_zero(id)?;
117    if table.find_id(&id).is_some() {
118        return Ok(());
119    }
120    let idx = table.find_free().ok_or(QdnfError::Capacity)?;
121    table.slots[idx] = Slot {
122        occupied: true,
123        effect: false,
124        durable_applied: false,
125        id,
126        effect_digest: StrongDigest::ZERO,
127    };
128    Ok(())
129}
130
131/// Record a local graph effect. Requires a bound identity. Unknown id is
132/// unauthorized. Idempotent once the effect is applied.
133pub fn apply_effect(table: &mut ReceiptTable, id: StrongDigest) -> Result<(), QdnfError> {
134    reject_zero(id)?;
135    let idx = table.find_id(&id).ok_or(QdnfError::Unauthorized)?;
136    table.slots[idx].effect = true;
137    Ok(())
138}
139
140/// Record SHA-384 of exact effect bytes on a bound identity.
141///
142/// Same digest is idempotent. A different digest for the same id is
143/// [`QdnfError::Conflict`]. Zero digest is malformed. Unknown id is unauthorized.
144pub fn bind_effect_digest(
145    table: &mut ReceiptTable,
146    id: StrongDigest,
147    digest: StrongDigest,
148) -> Result<(), QdnfError> {
149    reject_zero(id)?;
150    if digest == StrongDigest::ZERO {
151        return Err(QdnfError::Malformed);
152    }
153    let idx = table.find_id(&id).ok_or(QdnfError::Unauthorized)?;
154    let slot = &mut table.slots[idx];
155    if slot.effect_digest != StrongDigest::ZERO && slot.effect_digest != digest {
156        return Err(QdnfError::Conflict);
157    }
158    slot.effect_digest = digest;
159    slot.effect = true;
160    Ok(())
161}
162
163/// SHA-384 of effect bytes recorded for `id`, if any.
164pub fn effect_digest_of(table: &ReceiptTable, id: StrongDigest) -> Result<StrongDigest, QdnfError> {
165    reject_zero(id)?;
166    let idx = table.find_id(&id).ok_or(QdnfError::Unauthorized)?;
167    let digest = table.slots[idx].effect_digest;
168    if digest == StrongDigest::ZERO {
169        Err(QdnfError::Incomplete)
170    } else {
171        Ok(digest)
172    }
173}
174
175/// Durability class actually achieved for `id` without acknowledging a stage.
176///
177/// Transport ACK is never consulted. Unknown id is unauthorized.
178pub fn class_of(table: &ReceiptTable, id: StrongDigest) -> Result<ReceiptClass, QdnfError> {
179    reject_zero(id)?;
180    let idx = table.find_id(&id).ok_or(QdnfError::Unauthorized)?;
181    let slot = &table.slots[idx];
182    if slot.durable_applied {
183        Ok(ReceiptClass::DurableReceipt)
184    } else if slot.effect {
185        Ok(ReceiptClass::Effect)
186    } else {
187        Ok(ReceiptClass::Identity)
188    }
189}
190
191/// Map a delivery stage onto the durability class actually achieved.
192///
193/// Transport ACK and consumption are never [`ReceiptClass::DurableReceipt`].
194/// Durable-applied requires the local effect. Economic receipt requires that
195/// durable-applied was already recorded.
196pub fn acknowledge(
197    table: &mut ReceiptTable,
198    id: StrongDigest,
199    stage: DeliveryStage,
200) -> Result<ReceiptClass, QdnfError> {
201    reject_zero(id)?;
202    let idx = table.find_id(&id).ok_or(QdnfError::Unauthorized)?;
203    let slot = &mut table.slots[idx];
204    match stage {
205        DeliveryStage::TransportAck | DeliveryStage::Consumed => {
206            if slot.effect {
207                Ok(ReceiptClass::Effect)
208            } else {
209                Ok(ReceiptClass::Identity)
210            }
211        }
212        DeliveryStage::DurableApplied => {
213            if !slot.effect {
214                return Err(QdnfError::Incomplete);
215            }
216            slot.durable_applied = true;
217            Ok(ReceiptClass::DurableReceipt)
218        }
219        DeliveryStage::EconomicReceipt => {
220            if !slot.durable_applied {
221                return Err(QdnfError::Incomplete);
222            }
223            Ok(ReceiptClass::DurableReceipt)
224        }
225    }
226}
227
228/// Transport ACK is not a durable receipt class.
229pub fn transport_ack_is_receipt_class() -> bool {
230    false
231}
232
233/// Identity, local effect, and durable receipt are three distinct stages.
234pub fn identity_effect_receipt_are_distinct() -> bool {
235    ReceiptClass::Identity as u8 != ReceiptClass::Effect as u8
236        && ReceiptClass::Effect as u8 != ReceiptClass::DurableReceipt as u8
237        && ReceiptClass::Identity as u8 != ReceiptClass::DurableReceipt as u8
238}
239
240/// Advance a SuperBlock commit state machine (`R09`).
241///
242/// `Staged -> Committed` and `Indeterminate -> Committed` are rejected (`QdnfError::Incomplete`);
243/// `Verified` and `Committed` require `block_digest_verified == true`.
244pub fn advance_superblock_commit_state(
245    current: SuperBlockCommitState,
246    next: SuperBlockCommitState,
247    block_digest_verified: bool,
248) -> Result<SuperBlockCommitState, QdnfError> {
249    match (current, next) {
250        (SuperBlockCommitState::Staged, SuperBlockCommitState::Verified)
251        | (SuperBlockCommitState::Indeterminate, SuperBlockCommitState::Verified) => {
252            if !block_digest_verified {
253                return Err(QdnfError::Incomplete);
254            }
255            Ok(SuperBlockCommitState::Verified)
256        }
257        (SuperBlockCommitState::Verified, SuperBlockCommitState::Committed) => {
258            if !block_digest_verified {
259                return Err(QdnfError::Incomplete);
260            }
261            Ok(SuperBlockCommitState::Committed)
262        }
263        (SuperBlockCommitState::Staged, SuperBlockCommitState::Indeterminate)
264        | (SuperBlockCommitState::Verified, SuperBlockCommitState::Indeterminate)
265        | (SuperBlockCommitState::Indeterminate, SuperBlockCommitState::Indeterminate) => {
266            Ok(SuperBlockCommitState::Indeterminate)
267        }
268        _ => Err(QdnfError::Incomplete),
269    }
270}
271
272/// Emit a 48-byte `SyncCheckpoint` `NQuin` with canonical 5-field XOR parity (`R09`).
273///
274/// Only `Verified` or `Committed` SuperBlocks may emit a checkpoint Quin; `Staged`
275/// and `Indeterminate` states fail closed with [`QdnfError::Incomplete`].
276pub fn emit_sync_checkpoint_quin(
277    id: &StrongDigest,
278    block_digest: &StrongDigest,
279    state: SuperBlockCommitState,
280    epoch: u64,
281) -> Result<NQuin, QdnfError> {
282    reject_zero(*id)?;
283    reject_zero(*block_digest)?;
284    if state != SuperBlockCommitState::Verified && state != SuperBlockCommitState::Committed {
285        return Err(QdnfError::Incomplete);
286    }
287    let subject = u64::from_le_bytes([
288        id.0[0], id.0[1], id.0[2], id.0[3], id.0[4], id.0[5], id.0[6], id.0[7],
289    ]);
290    let predicate = (q_hash("https://qualia.db/qsync#hasSyncCheckpoint") << 8) | (state as u64);
291    let object = u64::from_le_bytes([
292        block_digest.0[0],
293        block_digest.0[1],
294        block_digest.0[2],
295        block_digest.0[3],
296        block_digest.0[4],
297        block_digest.0[5],
298        block_digest.0[6],
299        block_digest.0[7],
300    ]) & 0x0FFF_FFFF_FFFF_FFFF;
301    let context = q_hash("https://qualia.db/qsync#ReplicationReceiptGraph") & 0x00FF_FFFF_FFFF_FFFF;
302    let metadata = ((epoch & 0x1FFF_FFFF) << 32) | u64::from(state as u8);
303    let parity = subject ^ predicate ^ object ^ context ^ metadata;
304    Ok(NQuin {
305        subject,
306        predicate,
307        object,
308        context,
309        metadata,
310        parity,
311    })
312}
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317
318    fn digest(tag: u8) -> StrongDigest {
319        StrongDigest([tag; 48])
320    }
321
322    #[test]
323    fn bind_then_transport_ack_is_identity_not_durable() {
324        let mut table = ReceiptTable::new();
325        let id = digest(1);
326        bind_identity(&mut table, id).unwrap();
327        let class = acknowledge(&mut table, id, DeliveryStage::TransportAck).unwrap();
328        assert_eq!(class, ReceiptClass::Identity);
329        assert_ne!(class, ReceiptClass::DurableReceipt);
330    }
331
332    #[test]
333    fn apply_effect_then_transport_ack_is_not_durable() {
334        let mut table = ReceiptTable::new();
335        let id = digest(2);
336        bind_identity(&mut table, id).unwrap();
337        apply_effect(&mut table, id).unwrap();
338        let class = acknowledge(&mut table, id, DeliveryStage::TransportAck).unwrap();
339        assert_eq!(class, ReceiptClass::Effect);
340        assert_ne!(class, ReceiptClass::DurableReceipt);
341    }
342
343    #[test]
344    fn apply_effect_then_durable_applied_is_durable_receipt() {
345        let mut table = ReceiptTable::new();
346        let id = digest(3);
347        bind_identity(&mut table, id).unwrap();
348        apply_effect(&mut table, id).unwrap();
349        let class = acknowledge(&mut table, id, DeliveryStage::DurableApplied).unwrap();
350        assert_eq!(class, ReceiptClass::DurableReceipt);
351    }
352
353    #[test]
354    fn durable_applied_without_effect_is_incomplete() {
355        let mut table = ReceiptTable::new();
356        let id = digest(4);
357        bind_identity(&mut table, id).unwrap();
358        assert_eq!(
359            acknowledge(&mut table, id, DeliveryStage::DurableApplied),
360            Err(QdnfError::Incomplete)
361        );
362    }
363
364    #[test]
365    fn economic_receipt_without_durable_applied_is_incomplete() {
366        let mut table = ReceiptTable::new();
367        let id = digest(5);
368        bind_identity(&mut table, id).unwrap();
369        apply_effect(&mut table, id).unwrap();
370        assert_eq!(
371            acknowledge(&mut table, id, DeliveryStage::EconomicReceipt),
372            Err(QdnfError::Incomplete)
373        );
374    }
375
376    #[test]
377    fn unknown_id_is_unauthorized() {
378        let mut table = ReceiptTable::new();
379        let id = digest(6);
380        assert_eq!(
381            acknowledge(&mut table, id, DeliveryStage::TransportAck),
382            Err(QdnfError::Unauthorized)
383        );
384        assert_eq!(apply_effect(&mut table, id), Err(QdnfError::Unauthorized));
385    }
386
387    #[test]
388    fn zero_digest_is_malformed() {
389        let mut table = ReceiptTable::new();
390        assert_eq!(
391            bind_identity(&mut table, StrongDigest::ZERO),
392            Err(QdnfError::Malformed)
393        );
394        assert_eq!(
395            apply_effect(&mut table, StrongDigest::ZERO),
396            Err(QdnfError::Malformed)
397        );
398        assert_eq!(
399            acknowledge(&mut table, StrongDigest::ZERO, DeliveryStage::TransportAck),
400            Err(QdnfError::Malformed)
401        );
402    }
403
404    #[test]
405    fn seventeenth_identity_is_capacity() {
406        let mut table = ReceiptTable::new();
407        let mut n = 1u8;
408        while n <= MAX_RECEIPTS as u8 {
409            bind_identity(&mut table, digest(n)).unwrap();
410            n += 1;
411        }
412        assert_eq!(
413            bind_identity(&mut table, digest(0x20)),
414            Err(QdnfError::Capacity)
415        );
416    }
417
418    #[test]
419    fn transport_ack_is_not_a_receipt_class() {
420        assert!(!transport_ack_is_receipt_class());
421        assert_ne!(DeliveryStage::TransportAck, DeliveryStage::DurableApplied);
422    }
423
424    #[test]
425    fn identity_effect_and_receipt_are_distinct() {
426        assert!(identity_effect_receipt_are_distinct());
427        assert_ne!(ReceiptClass::Identity, ReceiptClass::Effect);
428        assert_ne!(ReceiptClass::Effect, ReceiptClass::DurableReceipt);
429        assert_ne!(ReceiptClass::Identity, ReceiptClass::DurableReceipt);
430    }
431
432    #[test]
433    fn double_bind_identity_is_idempotent() {
434        let mut table = ReceiptTable::new();
435        let id = digest(7);
436        bind_identity(&mut table, id).unwrap();
437        bind_identity(&mut table, id).unwrap();
438        let class = acknowledge(&mut table, id, DeliveryStage::TransportAck).unwrap();
439        assert_eq!(class, ReceiptClass::Identity);
440    }
441
442    #[test]
443    fn bind_effect_digest_same_is_idempotent_different_is_conflict() {
444        let mut table = ReceiptTable::new();
445        let id = digest(8);
446        let d1 = digest(0xA1);
447        let d2 = digest(0xA2);
448        bind_identity(&mut table, id).unwrap();
449        bind_effect_digest(&mut table, id, d1).unwrap();
450        bind_effect_digest(&mut table, id, d1).unwrap();
451        assert_eq!(effect_digest_of(&table, id).unwrap(), d1);
452        assert_eq!(class_of(&table, id).unwrap(), ReceiptClass::Effect);
453        assert_eq!(
454            bind_effect_digest(&mut table, id, d2),
455            Err(QdnfError::Conflict)
456        );
457        assert_eq!(class_of(&table, id).unwrap(), ReceiptClass::Effect);
458    }
459
460    #[test]
461    fn class_of_unknown_id_is_unauthorized() {
462        let table = ReceiptTable::new();
463        assert_eq!(class_of(&table, digest(9)), Err(QdnfError::Unauthorized));
464    }
465
466    #[test]
467    fn r09_crash_safe_superblock_commit_states_and_sync_checkpoint_quin_parity() {
468        let id = digest(0x11);
469        let blk = digest(0x22);
470        assert_eq!(
471            advance_superblock_commit_state(
472                SuperBlockCommitState::Staged,
473                SuperBlockCommitState::Committed,
474                true
475            ),
476            Err(QdnfError::Incomplete)
477        );
478        let st = advance_superblock_commit_state(
479            SuperBlockCommitState::Staged,
480            SuperBlockCommitState::Indeterminate,
481            false,
482        )
483        .unwrap();
484        assert_eq!(
485            emit_sync_checkpoint_quin(&id, &blk, st, 42),
486            Err(QdnfError::Incomplete)
487        );
488        let ver = advance_superblock_commit_state(st, SuperBlockCommitState::Verified, true).unwrap();
489        let com = advance_superblock_commit_state(ver, SuperBlockCommitState::Committed, true).unwrap();
490        let q = emit_sync_checkpoint_quin(&id, &blk, com, 42).unwrap();
491        assert_eq!(
492            q.parity,
493            q.subject ^ q.predicate ^ q.object ^ q.context ^ q.metadata
494        );
495    }
496}