Skip to main content

qualia_core_db/net/qdnf/harness/
churn.rs

1//! E21.4 — bounded-seconds churn. Not days-long soak.
2
3use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::time::Instant;
5
6use crate::net::qdnf::bearer::{ipc_pair, Bearer};
7use crate::net::qdnf::errors::QdnfError;
8use crate::net::qdnf::frame::{decode_frame, encode_frame, FrameHeader};
9use crate::net::qdnf::harness::allocation::ReservationTracker;
10use crate::net::qdnf::harness::oracles::{plaintext_on_wire, ProtectedView};
11use crate::net::qdnf::harness::partition::PartitionGate;
12use crate::net::qdnf::registries::{FrameType, NextProtocol};
13use crate::net::qdnf::types::ScopeEpoch;
14
15/// Multi-day churn / soak has not been executed.
16pub fn long_duration_churn_days_executed() -> bool {
17    false
18}
19
20static CHURN_RAN: AtomicBool = AtomicBool::new(false);
21static CHURN_MS: AtomicU64 = AtomicU64::new(0);
22
23/// True after [`run_bounded_churn`] completes in this process.
24pub fn bounded_churn_executed() -> bool {
25    CHURN_RAN.load(Ordering::SeqCst)
26}
27
28/// Wall time actually waited in the last [`run_bounded_churn`] call, or 0.
29pub fn last_churn_duration_ms() -> u64 {
30    CHURN_MS.load(Ordering::SeqCst)
31}
32
33/// Cap so CI stays sane. Seconds, not days.
34pub const CHURN_CAP_MS: u64 = 2_000;
35
36const APP_SECRET: &[u8] = b"qpr-app-secret-never-on-wire";
37const PAYLOAD: [u8; 8] = [0x9a, 0x13, 0x44, 0x80, 0x02, 0x77, 0x11, 0xce];
38
39fn one_round(pool: &mut ReservationTracker, round: u32) -> Result<(), QdnfError> {
40    let gate = PartitionGate::open();
41    gate.admit()?;
42    let lease = pool.reserve(1, 64)?;
43    if pool.live_bytes() != pool.occupied_bytes() {
44        return Err(QdnfError::Conflict);
45    }
46
47    let mut header = FrameHeader::new(FrameType::DiscoveryBeacon, NextProtocol::QLink);
48    header.payload_len = PAYLOAD.len() as u16;
49    let mut wire = [0u8; 128];
50    let n = encode_frame(&header, &PAYLOAD, &mut wire)?;
51    let (decoded, off, len) = decode_frame(&wire[..n])?;
52    if decoded.payload_len as usize != PAYLOAD.len() || off != 80 || len != PAYLOAD.len() {
53        return Err(QdnfError::Malformed);
54    }
55    let view = ProtectedView {
56        wire_payload: &wire[..n],
57        application: APP_SECRET,
58    };
59    if plaintext_on_wire(view) {
60        return Err(QdnfError::Denied);
61    }
62
63    let scope = ScopeEpoch {
64        scope: 1,
65        epoch: 1u64.wrapping_add(round as u64),
66    };
67    let (mut a, mut b) = ipc_pair(scope, 1280)?;
68    a.send(&b.locator(), &wire[..n])?;
69    let mut out = [0u8; 128];
70    let (got, _meta) = b.recv(&mut out)?;
71    let _ = decode_frame(&out[..got])?;
72    a.shutdown()?;
73    b.shutdown()?;
74
75    pool.release(lease)?;
76    if pool.live_bytes() != 0 || pool.occupied_bytes() != 0 {
77        return Err(QdnfError::Conflict);
78    }
79    Ok(())
80}
81
82/// Timed pair/encode/decode loop with conservation and confidentiality checks.
83pub fn run_bounded_churn() -> Result<u64, QdnfError> {
84    CHURN_MS.store(0, Ordering::SeqCst);
85    let start = Instant::now();
86    let mut pool = ReservationTracker::new();
87    let mut round = 0u32;
88    loop {
89        let elapsed = start.elapsed();
90        if elapsed.as_millis() as u64 >= CHURN_CAP_MS {
91            break;
92        }
93        one_round(&mut pool, round)?;
94        round = round.wrapping_add(1);
95        if round == 0 {
96            break;
97        }
98    }
99    let waited = start.elapsed().as_millis() as u64;
100    CHURN_MS.store(waited, Ordering::SeqCst);
101    CHURN_RAN.store(true, Ordering::SeqCst);
102    if waited == 0 && round == 0 {
103        return Err(QdnfError::Incomplete);
104    }
105    Ok(waited)
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    #[test]
113    fn bounded_churn_waits_seconds_not_days_and_conserves() {
114        assert!(!long_duration_churn_days_executed());
115        let waited = run_bounded_churn().unwrap();
116        assert!(bounded_churn_executed());
117        assert!(!long_duration_churn_days_executed());
118        assert_eq!(last_churn_duration_ms(), waited);
119        assert!(
120            waited >= CHURN_CAP_MS,
121            "must actually wait the cap, got {waited} ms"
122        );
123        assert!(
124            waited < 5_000,
125            "must stay under five seconds for CI, got {waited} ms"
126        );
127    }
128}