Skip to main content

qualia_core_db/
wal_intent.rs

1//! Bounded in-memory intent/commit ledger (CORE-03 partial).
2//!
3//! Separate typed marker stream from [`crate::wal`] (packed NQuins + SHA-256
4//! header). Does not claim remote atomicity or remote custody.
5
6use crate::crypto::network::digest::sha384;
7use crate::net::qdnf::errors::QdnfError;
8use crate::net::qdnf::types::{Generation, StrongDigest};
9
10pub const MAX_INTENTS: usize = 32;
11pub const MAX_OBJECT_BYTES: usize = 512;
12pub const MARKER_LEN: usize = 80;
13
14const MAGIC: [u8; 4] = *b"QINT";
15
16#[repr(u8)]
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum ArtifactKind {
19    Contract = 1,
20    Proof = 2,
21    Operation = 3,
22    Receipt = 4,
23    Evidence = 5,
24}
25
26#[repr(u8)]
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum MarkerKind {
29    Intent = 1,
30    Commit = 2,
31    Abort = 3,
32}
33
34#[repr(C)]
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub struct TxId {
37    pub bytes: [u8; 16],
38}
39
40impl TxId {
41    pub const ZERO: Self = Self { bytes: [0u8; 16] };
42}
43
44#[repr(C)]
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub struct ExactObjectRef {
47    pub kind: ArtifactKind,
48    pub digest: StrongDigest,
49    pub byte_len: u16,
50}
51
52impl ExactObjectRef {
53    pub const EMPTY: Self = Self {
54        kind: ArtifactKind::Contract,
55        digest: StrongDigest::ZERO,
56        byte_len: 0,
57    };
58}
59
60#[repr(C)]
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
62pub struct IntentRecord {
63    pub tx: TxId,
64    pub kind: MarkerKind,
65    pub object: ExactObjectRef,
66    pub writer_id: u64,
67    pub generation: Generation,
68}
69
70impl IntentRecord {
71    pub const EMPTY: Self = Self {
72        tx: TxId::ZERO,
73        kind: MarkerKind::Intent,
74        object: ExactObjectRef::EMPTY,
75        writer_id: 0,
76        generation: Generation::ZERO,
77    };
78}
79
80/// Preserve original signed bytes in a caller buffer. Digest is SHA-384 of
81/// those exact bytes.
82pub fn bind_exact_object(
83    kind: ArtifactKind,
84    bytes: &[u8],
85    out_copy: &mut [u8],
86) -> Result<ExactObjectRef, QdnfError> {
87    if bytes.len() > MAX_OBJECT_BYTES || bytes.len() > out_copy.len() {
88        return Err(QdnfError::Capacity);
89    }
90    out_copy[..bytes.len()].copy_from_slice(bytes);
91    Ok(ExactObjectRef {
92        kind,
93        digest: sha384(bytes),
94        byte_len: bytes.len() as u16,
95    })
96}
97
98#[derive(Clone, Copy)]
99struct Slot {
100    occupied: bool,
101    record: IntentRecord,
102}
103
104#[derive(Clone, Copy)]
105struct WriterAuth {
106    occupied: bool,
107    writer_id: u64,
108    live_generation: Generation,
109}
110
111/// Fixed 32-slot intent table with per-writer live generations.
112pub struct IntentTable {
113    slots: [Slot; MAX_INTENTS],
114    writers: [WriterAuth; MAX_INTENTS],
115}
116
117impl IntentTable {
118    /// Creates a default `IntentTable`.
119    pub const fn new() -> Self {
120        Self {
121            slots: [Slot {
122                occupied: false,
123                record: IntentRecord::EMPTY,
124            }; MAX_INTENTS],
125            writers: [WriterAuth {
126                occupied: false,
127                writer_id: 0,
128                live_generation: Generation::ZERO,
129            }; MAX_INTENTS],
130        }
131    }
132
133    /// Stage durable submission intent BEFORE any external dispatch.
134    pub fn stage_intent(
135        &mut self,
136        tx: TxId,
137        object: ExactObjectRef,
138        writer_id: u64,
139        authority_generation: Generation,
140    ) -> Result<Generation, QdnfError> {
141        if self.find_occupied(tx).is_some() {
142            return Err(QdnfError::Conflict);
143        }
144        if let Some(idx) = self.find_writer(writer_id) {
145            if authority_generation.0 < self.writers[idx].live_generation.0 {
146                return Err(QdnfError::StaleGeneration);
147            }
148        }
149        let free = self.find_free().ok_or(QdnfError::Capacity)?;
150        self.upsert_writer(writer_id, authority_generation)?;
151        self.slots[free] = Slot {
152            occupied: true,
153            record: IntentRecord {
154                tx,
155                kind: MarkerKind::Intent,
156                object,
157                writer_id,
158                generation: authority_generation,
159            },
160        };
161        Ok(authority_generation)
162    }
163
164    /// Commits `tx` at `authority_generation`; error when stale/unknown.
165    pub fn commit(&mut self, tx: TxId, authority_generation: Generation) -> Result<(), QdnfError> {
166        self.transition(tx, authority_generation, MarkerKind::Commit)
167    }
168
169    /// Aborts `tx`.
170    pub fn abort(&mut self, tx: TxId, authority_generation: Generation) -> Result<(), QdnfError> {
171        self.transition(tx, authority_generation, MarkerKind::Abort)
172    }
173
174    /// Pending intents for that writer cannot commit at the old generation.
175    pub fn withdraw_authority(
176        &mut self,
177        writer_id: u64,
178        new_generation: Generation,
179    ) -> Result<(), QdnfError> {
180        if let Some(idx) = self.find_writer(writer_id) {
181            if new_generation.0 <= self.writers[idx].live_generation.0 {
182                return Err(QdnfError::StaleGeneration);
183            }
184            self.writers[idx].live_generation = new_generation;
185            return Ok(());
186        }
187        self.upsert_writer(writer_id, new_generation)
188    }
189
190    /// Encode a fixed marker into a caller buffer. Never claims remote atomicity.
191    /// Artifact kind / byte_len are encoded as Contract / 0 (not in this signature).
192    pub fn encode_marker(
193        kind: MarkerKind,
194        tx: TxId,
195        digest: &StrongDigest,
196        out: &mut [u8],
197    ) -> Result<usize, QdnfError> {
198        if out.len() < MARKER_LEN {
199            return Err(QdnfError::Capacity);
200        }
201        out[..4].copy_from_slice(&MAGIC);
202        out[4] = kind as u8;
203        out[5] = ArtifactKind::Contract as u8;
204        out[6..8].copy_from_slice(&0u16.to_be_bytes());
205        out[8..24].copy_from_slice(&tx.bytes);
206        out[24..72].copy_from_slice(&digest.0);
207        out[72..MARKER_LEN].fill(0);
208        Ok(MARKER_LEN)
209    }
210
211    /// Recover concatenated markers. Torn trailing bytes are not applied.
212    pub fn recover_into(
213        markers: &[u8],
214        out: &mut [IntentRecord; MAX_INTENTS],
215    ) -> Result<usize, QdnfError> {
216        let mut produced = 0usize;
217        let mut offset = 0usize;
218        while offset + MARKER_LEN <= markers.len() {
219            if produced >= out.len() {
220                return Err(QdnfError::Capacity);
221            }
222            out[produced] = decode_marker(&markers[offset..offset + MARKER_LEN])?;
223            produced += 1;
224            offset += MARKER_LEN;
225        }
226        Ok(produced)
227    }
228
229    /// Honest probe: `false` — a local pin does not imply remote custody.
230    pub fn local_pin_implies_remote_custody() -> bool {
231        false
232    }
233
234    /// Honest probe: `false` — local commit is not remote-atomic.
235    pub fn local_commit_is_remote_atomic() -> bool {
236        false
237    }
238
239    fn transition(
240        &mut self,
241        tx: TxId,
242        authority_generation: Generation,
243        target: MarkerKind,
244    ) -> Result<(), QdnfError> {
245        let idx = self.find_occupied(tx).ok_or(QdnfError::Incomplete)?;
246        let rec = &self.slots[idx].record;
247        match (rec.kind, target) {
248            (MarkerKind::Commit, MarkerKind::Commit) | (MarkerKind::Abort, MarkerKind::Abort) => {
249                return Err(QdnfError::Conflict);
250            }
251            (MarkerKind::Abort, MarkerKind::Commit) | (MarkerKind::Commit, MarkerKind::Abort) => {
252                return Err(QdnfError::Ambiguous);
253            }
254            (MarkerKind::Intent, _) => {}
255            _ => return Err(QdnfError::Ambiguous),
256        }
257        if rec.generation != authority_generation {
258            return Err(QdnfError::StaleGeneration);
259        }
260        if let Some(w) = self.find_writer(rec.writer_id) {
261            if self.writers[w].live_generation != authority_generation {
262                return Err(QdnfError::StaleGeneration);
263            }
264        }
265        self.slots[idx].record.kind = target;
266        Ok(())
267    }
268
269    fn find_occupied(&self, tx: TxId) -> Option<usize> {
270        let mut i = 0usize;
271        while i < MAX_INTENTS {
272            if self.slots[i].occupied && self.slots[i].record.tx.bytes == tx.bytes {
273                return Some(i);
274            }
275            i += 1;
276        }
277        None
278    }
279
280    fn find_free(&self) -> Option<usize> {
281        let mut i = 0usize;
282        while i < MAX_INTENTS {
283            if !self.slots[i].occupied {
284                return Some(i);
285            }
286            i += 1;
287        }
288        None
289    }
290
291    fn find_writer(&self, writer_id: u64) -> Option<usize> {
292        let mut i = 0usize;
293        while i < MAX_INTENTS {
294            if self.writers[i].occupied && self.writers[i].writer_id == writer_id {
295                return Some(i);
296            }
297            i += 1;
298        }
299        None
300    }
301
302    fn upsert_writer(&mut self, writer_id: u64, generation: Generation) -> Result<(), QdnfError> {
303        if let Some(idx) = self.find_writer(writer_id) {
304            if generation.0 > self.writers[idx].live_generation.0 {
305                self.writers[idx].live_generation = generation;
306            }
307            return Ok(());
308        }
309        let mut i = 0usize;
310        while i < MAX_INTENTS {
311            if !self.writers[i].occupied {
312                self.writers[i] = WriterAuth {
313                    occupied: true,
314                    writer_id,
315                    live_generation: generation,
316                };
317                return Ok(());
318            }
319            i += 1;
320        }
321        Err(QdnfError::Capacity)
322    }
323}
324
325fn decode_marker(raw: &[u8]) -> Result<IntentRecord, QdnfError> {
326    if raw.len() != MARKER_LEN {
327        return Err(QdnfError::Truncated);
328    }
329    if raw[..4] != MAGIC || raw[72..MARKER_LEN] != [0u8; 8] {
330        return Err(QdnfError::Malformed);
331    }
332    let kind = match raw[4] {
333        1 => MarkerKind::Intent,
334        2 => MarkerKind::Commit,
335        3 => MarkerKind::Abort,
336        _ => return Err(QdnfError::Malformed),
337    };
338    let artifact = match raw[5] {
339        1 => ArtifactKind::Contract,
340        2 => ArtifactKind::Proof,
341        3 => ArtifactKind::Operation,
342        4 => ArtifactKind::Receipt,
343        5 => ArtifactKind::Evidence,
344        _ => return Err(QdnfError::Malformed),
345    };
346    let byte_len = u16::from_be_bytes([raw[6], raw[7]]);
347    let mut tx_bytes = [0u8; 16];
348    tx_bytes.copy_from_slice(&raw[8..24]);
349    let mut digest_bytes = [0u8; 48];
350    digest_bytes.copy_from_slice(&raw[24..72]);
351    Ok(IntentRecord {
352        tx: TxId { bytes: tx_bytes },
353        kind,
354        object: ExactObjectRef {
355            kind: artifact,
356            digest: StrongDigest(digest_bytes),
357            byte_len,
358        },
359        writer_id: 0,
360        generation: Generation::ZERO,
361    })
362}
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367
368    fn tx(n: u8) -> TxId {
369        let mut bytes = [0u8; 16];
370        bytes[15] = n;
371        TxId { bytes }
372    }
373
374    fn bind(kind: ArtifactKind, bytes: &[u8]) -> ExactObjectRef {
375        let mut copy = [0u8; MAX_OBJECT_BYTES];
376        bind_exact_object(kind, bytes, &mut copy).expect("bind")
377    }
378
379    #[test]
380    fn bind_exact_object_copies_and_digest_is_forty_eight() {
381        let payload = b"signed-contract-bytes";
382        let mut copy = [0u8; MAX_OBJECT_BYTES];
383        let object = bind_exact_object(ArtifactKind::Proof, payload, &mut copy).unwrap();
384        assert_eq!(&copy[..payload.len()], payload);
385        assert_eq!(object.digest.0.len(), 48);
386        assert_eq!(object.digest, sha384(payload));
387        copy[0] ^= 0xFF;
388        assert_ne!(object.digest, sha384(&copy[..payload.len()]));
389        assert_eq!(object.digest, sha384(payload));
390    }
391
392    #[test]
393    fn stage_then_commit_second_commit_is_conflict() {
394        let mut table = IntentTable::new();
395        let gen = Generation(1);
396        table
397            .stage_intent(tx(1), bind(ArtifactKind::Contract, b"op-1"), 7, gen)
398            .unwrap();
399        table.commit(tx(1), gen).unwrap();
400        assert_eq!(table.commit(tx(1), gen), Err(QdnfError::Conflict));
401    }
402
403    #[test]
404    fn abort_then_commit_is_ambiguous() {
405        let mut table = IntentTable::new();
406        let gen = Generation(1);
407        table
408            .stage_intent(tx(2), bind(ArtifactKind::Receipt, b"op-2"), 7, gen)
409            .unwrap();
410        table.abort(tx(2), gen).unwrap();
411        assert_eq!(table.commit(tx(2), gen), Err(QdnfError::Ambiguous));
412    }
413
414    #[test]
415    fn withdraw_then_commit_at_old_generation_is_stale() {
416        let mut table = IntentTable::new();
417        let old = Generation(1);
418        table
419            .stage_intent(tx(3), bind(ArtifactKind::Operation, b"op-3"), 9, old)
420            .unwrap();
421        table.withdraw_authority(9, Generation(2)).unwrap();
422        assert_eq!(table.commit(tx(3), old), Err(QdnfError::StaleGeneration));
423    }
424
425    #[test]
426    fn thirty_third_stage_is_capacity() {
427        let mut table = IntentTable::new();
428        let object = bind(ArtifactKind::Evidence, b"slot");
429        let gen = Generation(1);
430        let mut i = 0u8;
431        while i < MAX_INTENTS as u8 {
432            table.stage_intent(tx(i + 1), object, 1, gen).unwrap();
433            i += 1;
434        }
435        assert_eq!(
436            table.stage_intent(tx(0xFF), object, 1, gen),
437            Err(QdnfError::Capacity)
438        );
439    }
440
441    #[test]
442    fn encode_marker_recover_into_round_trip_ignores_torn_tail() {
443        let object = bind(ArtifactKind::Contract, b"marker-a");
444        let mut stream = [0u8; MARKER_LEN * 2 + 10];
445        assert_eq!(
446            IntentTable::encode_marker(
447                MarkerKind::Intent,
448                tx(10),
449                &object.digest,
450                &mut stream[..MARKER_LEN]
451            )
452            .unwrap(),
453            MARKER_LEN
454        );
455        assert_eq!(
456            IntentTable::encode_marker(
457                MarkerKind::Commit,
458                tx(11),
459                &object.digest,
460                &mut stream[MARKER_LEN..MARKER_LEN * 2],
461            )
462            .unwrap(),
463            MARKER_LEN
464        );
465        stream[MARKER_LEN * 2..].fill(0xAA);
466        let mut out = [IntentRecord::EMPTY; MAX_INTENTS];
467        let intact = IntentTable::recover_into(&stream[..MARKER_LEN * 2], &mut out).unwrap();
468        assert_eq!(intact, 2);
469        assert_eq!(
470            IntentTable::recover_into(&stream, &mut out).unwrap(),
471            intact
472        );
473        assert_eq!(out[0].tx, tx(10));
474        assert_eq!(out[0].kind, MarkerKind::Intent);
475        assert_eq!(out[0].object.digest, object.digest);
476        assert_eq!(out[1].tx, tx(11));
477        assert_eq!(out[1].kind, MarkerKind::Commit);
478        assert_eq!(out[1].object.digest, object.digest);
479    }
480
481    #[test]
482    fn local_pin_and_local_commit_are_not_remote() {
483        assert!(!IntentTable::local_pin_implies_remote_custody());
484        assert!(!IntentTable::local_commit_is_remote_atomic());
485    }
486
487    #[test]
488    fn identical_bytes_do_not_unify_distinct_authorities() {
489        let payload = b"same-bytes";
490        let a = bind(ArtifactKind::Contract, payload);
491        let b = bind(ArtifactKind::Contract, payload);
492        assert_eq!(a.digest, b.digest);
493        let mut table = IntentTable::new();
494        let gen = Generation(3);
495        table.stage_intent(tx(20), a, 100, gen).unwrap();
496        table.stage_intent(tx(21), b, 200, gen).unwrap();
497        assert_eq!(
498            table.stage_intent(tx(20), a, 100, gen),
499            Err(QdnfError::Conflict)
500        );
501        table.commit(tx(20), gen).unwrap();
502        table.commit(tx(21), gen).unwrap();
503    }
504}