Skip to main content

qualia_core_db/net/qdnf/replication/
qnf_eval.rs

1//! E06.5 QNF evaluation: Q42 + existing artifact envelopes vs a QNF extension.
2//!
3//! Workloads are real in-tree sizes (route edges, contract bundles, ML-DSA-65
4//! proofs, evidence originals). Large graph size does not select the format.
5//! [`QnfExtensionAdopted`] is the recorded decision and is never implied by
6//! the presence of this library or by QNF draft magic.
7
8use crate::crypto::network::types::ML_DSA_65_SIG_LEN;
9use crate::net::qdnf::contracts::ContractBundle;
10use crate::net::qdnf::errors::QdnfError;
11use crate::net::qdnf::evidence::promote::{EvidenceRecord, MAX_ORIGINAL};
12use crate::net::qdnf::replication::stream::PAGE_BYTES;
13use crate::net::qdnf::route::ads::PathAdvert;
14use crate::net::qdnf::route::validate::ValidatedEdge;
15use crate::NQuin;
16
17/// Candidate QNF header (draft §4.1). Not a frozen on-disk layout.
18pub const QNF_HEADER_BYTES: u32 = 256;
19/// Directory entry width (draft §4.2).
20pub const QNF_DIR_ENTRY_BYTES: u32 = 128;
21/// AUTH + BIND + CHNK + DATA + OBJS. VIEW is optional and not counted.
22pub const QNF_REQUIRED_SECTIONS: u32 = 5;
23/// Dual COSE generation proofs: two ML-DSA-65 signatures (draft AUTH).
24pub const QNF_AUTH_BYTES: u32 = (ML_DSA_65_SIG_LEN * 2) as u32;
25/// Bounded BIND CBOR budget used for the comparison (not a parser).
26pub const QNF_BIND_BYTES: u32 = 128;
27pub const QNF_CHUNK_DESC_BYTES: u32 = 64;
28pub const QNF_OBJECT_DESC_BYTES: u32 = 64;
29pub const QNF_CHUNK_DATA_BYTES: u32 = 65536;
30/// QNF draft major/minor while unselected. Not frozen (CORE-04.05).
31pub const QNF_DRAFT_MAJOR: u16 = 0;
32pub const QNF_DRAFT_MINOR: u16 = 1;
33/// Existing artifact envelope version: SHA-384 identity + exact length.
34pub const ARTIFACT_ENVELOPE_VERSION: u16 = 1;
35/// Q42 48-byte projection ABI. Unchanged by this evaluation.
36pub const Q42_ABI_BYTES: u16 = 48;
37
38/// ASCII `QNFNET01` from the candidate header. Not an adopted reader magic.
39pub const QNF_MAGIC: [u8; 8] = *b"QNFNET01";
40
41/// Recorded E06.5 decision. False: QNF is unselected.
42#[allow(non_upper_case_globals)]
43pub const QnfExtensionAdopted: bool = EVALUATION.adopted;
44
45/// Evaluation artifact produced from the measured workloads.
46pub const EVALUATION: FormatDecision = FormatDecision {
47    adopted: false,
48    selected: SelectedRepresentation::Q42ExistingArtifacts,
49    artifact_version: ARTIFACT_ENVELOPE_VERSION,
50    qnf_draft_major: QNF_DRAFT_MAJOR,
51    qnf_draft_minor: QNF_DRAFT_MINOR,
52    q42_abi_bytes: Q42_ABI_BYTES,
53    qnf_header_bytes: QNF_HEADER_BYTES as u16,
54    migration: MigrationPath::RetainExisting,
55    qnf_layout_frozen: false,
56};
57
58#[repr(u8)]
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub enum SelectedRepresentation {
61    Q42ExistingArtifacts = 1,
62    QnfExtension = 2,
63}
64
65#[repr(u8)]
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum MigrationPath {
68    /// Stay on Q42 projections + SHA-384 artifact originals. No dual-read.
69    RetainExisting = 1,
70    /// Only if adopted: digest-keyed dual-read, then a frozen container_qnf.
71    DualReadThenQnf = 2,
72}
73
74#[repr(u8)]
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum WorkloadKind {
77    Route = 1,
78    Contract = 2,
79    PqProof = 3,
80    Evidence = 4,
81}
82
83#[repr(C)]
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
85pub struct WorkloadCost {
86    pub kind: WorkloadKind,
87    pub payload_bytes: u32,
88    pub q42_envelope_bytes: u32,
89    pub qnf_candidate_bytes: u32,
90}
91
92#[repr(C)]
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94pub struct FormatDecision {
95    pub adopted: bool,
96    pub selected: SelectedRepresentation,
97    pub artifact_version: u16,
98    pub qnf_draft_major: u16,
99    pub qnf_draft_minor: u16,
100    pub q42_abi_bytes: u16,
101    pub qnf_header_bytes: u16,
102    pub migration: MigrationPath,
103    pub qnf_layout_frozen: bool,
104}
105
106/// Evaluation artifact: decision plus the four measured costs.
107#[repr(C)]
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub struct FormatRecord {
110    pub decision: FormatDecision,
111    pub costs: [WorkloadCost; 4],
112    pub large_graph_selects_qnf: bool,
113    pub page_window_bytes: u32,
114}
115
116/// Measure representative workloads and return the evaluation artifact.
117pub fn evaluate_qnf() -> FormatRecord {
118    let costs = [
119        cost_of(WorkloadKind::Route, route_payload_bytes()),
120        cost_of(WorkloadKind::Contract, contract_payload_bytes()),
121        cost_of(WorkloadKind::PqProof, pq_payload_bytes()),
122        cost_of(WorkloadKind::Evidence, evidence_payload_bytes()),
123    ];
124    let selected = select_representation(&costs);
125    let adopted = selected == SelectedRepresentation::QnfExtension;
126    FormatRecord {
127        decision: FormatDecision {
128            adopted,
129            selected,
130            artifact_version: ARTIFACT_ENVELOPE_VERSION,
131            qnf_draft_major: QNF_DRAFT_MAJOR,
132            qnf_draft_minor: QNF_DRAFT_MINOR,
133            q42_abi_bytes: Q42_ABI_BYTES,
134            qnf_header_bytes: QNF_HEADER_BYTES as u16,
135            migration: if adopted {
136                MigrationPath::DualReadThenQnf
137            } else {
138                MigrationPath::RetainExisting
139            },
140            qnf_layout_frozen: adopted,
141        },
142        costs,
143        large_graph_selects_qnf: false,
144        page_window_bytes: PAGE_BYTES as u32,
145    }
146}
147
148/// QNF magic is Unsupported while unselected. Never parsed as a Q42 volume.
149pub fn open_qnf_magic(magic: &[u8; 8]) -> Result<(), QdnfError> {
150    if *magic != QNF_MAGIC {
151        return Err(QdnfError::Malformed);
152    }
153    if QnfExtensionAdopted {
154        Ok(())
155    } else {
156        Err(QdnfError::Unsupported)
157    }
158}
159
160#[inline]
161/// `?::decision_matches_flag`.
162pub fn decision_matches_flag(record: &FormatRecord) -> bool {
163    record.decision.adopted == QnfExtensionAdopted
164        && (record.decision.adopted
165            == (record.decision.selected == SelectedRepresentation::QnfExtension))
166}
167
168fn route_payload_bytes() -> u32 {
169    (core::mem::size_of::<ValidatedEdge>() + core::mem::size_of::<PathAdvert>()) as u32
170}
171
172fn contract_payload_bytes() -> u32 {
173    core::mem::size_of::<ContractBundle>() as u32
174}
175
176fn pq_payload_bytes() -> u32 {
177    ML_DSA_65_SIG_LEN as u32
178}
179
180fn evidence_payload_bytes() -> u32 {
181    (core::mem::size_of::<EvidenceRecord>() + MAX_ORIGINAL) as u32
182}
183
184fn q42_envelope_bytes(payload: u32) -> u32 {
185    // SHA-384 identity + u32 length + 48-byte NQuin projection + payload.
186    let identity = 48u32.saturating_add(4);
187    let projection = core::mem::size_of::<NQuin>() as u32;
188    identity.saturating_add(projection).saturating_add(payload)
189}
190
191fn qnf_candidate_bytes(payload: u32) -> u32 {
192    let dir = QNF_DIR_ENTRY_BYTES.saturating_mul(QNF_REQUIRED_SECTIONS);
193    let chunks = chunk_descriptors(payload);
194    QNF_HEADER_BYTES
195        .saturating_add(dir)
196        .saturating_add(QNF_AUTH_BYTES)
197        .saturating_add(QNF_BIND_BYTES)
198        .saturating_add(chunks)
199        .saturating_add(payload)
200        .saturating_add(QNF_OBJECT_DESC_BYTES)
201}
202
203fn chunk_descriptors(payload: u32) -> u32 {
204    if payload == 0 {
205        return QNF_CHUNK_DESC_BYTES;
206    }
207    let n = payload.div_ceil(QNF_CHUNK_DATA_BYTES).max(1);
208    QNF_CHUNK_DESC_BYTES.saturating_mul(n)
209}
210
211fn cost_of(kind: WorkloadKind, payload: u32) -> WorkloadCost {
212    WorkloadCost {
213        kind,
214        payload_bytes: payload,
215        q42_envelope_bytes: q42_envelope_bytes(payload),
216        qnf_candidate_bytes: qnf_candidate_bytes(payload),
217    }
218}
219
220/// QNF wins only if it is smaller on a workload *and* it offers a range-read
221/// specialization beyond the existing 4 KiB page window. Large graph size is
222/// ignored (CORE-04.03).
223fn select_representation(costs: &[WorkloadCost; 4]) -> SelectedRepresentation {
224    let mut cheaper = false;
225    let mut i = 0usize;
226    while i < costs.len() {
227        if costs[i].qnf_candidate_bytes < costs[i].q42_envelope_bytes {
228            cheaper = true;
229            break;
230        }
231        i += 1;
232    }
233    if cheaper && qnf_range_specialization_beyond_pages() {
234        SelectedRepresentation::QnfExtension
235    } else {
236        SelectedRepresentation::Q42ExistingArtifacts
237    }
238}
239
240/// Existing replica paging is 4 KiB. QNF draft chunks are 64 KiB — coarser,
241/// not a measured specialization that justifies a new container.
242const fn qnf_range_specialization_beyond_pages() -> bool {
243    false
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    #[test]
251    fn evaluation_artifact_exists_and_adopted_matches_decision() {
252        let record = evaluate_qnf();
253        assert_eq!(record.decision, EVALUATION);
254        assert!(decision_matches_flag(&record));
255        assert!(!QnfExtensionAdopted);
256        assert!(!record.decision.adopted);
257        assert_eq!(
258            record.decision.selected,
259            SelectedRepresentation::Q42ExistingArtifacts
260        );
261        assert_eq!(record.decision.migration, MigrationPath::RetainExisting);
262        assert!(!record.decision.qnf_layout_frozen);
263        assert!(!record.large_graph_selects_qnf);
264        assert_eq!(record.page_window_bytes, PAGE_BYTES as u32);
265        assert_eq!(record.decision.q42_abi_bytes, 48);
266        assert_eq!(record.decision.artifact_version, ARTIFACT_ENVELOPE_VERSION);
267        assert_eq!(record.decision.qnf_draft_major, 0);
268        assert_eq!(record.decision.qnf_draft_minor, 1);
269
270        let mut i = 0usize;
271        while i < record.costs.len() {
272            let c = record.costs[i];
273            assert!(c.payload_bytes > 0);
274            assert!(c.q42_envelope_bytes > c.payload_bytes);
275            assert!(c.qnf_candidate_bytes > c.q42_envelope_bytes);
276            i += 1;
277        }
278    }
279
280    #[test]
281    fn qnf_magic_is_unsupported_while_unselected() {
282        assert_eq!(open_qnf_magic(&QNF_MAGIC), Err(QdnfError::Unsupported));
283        assert_eq!(open_qnf_magic(b"Q42VOL01"), Err(QdnfError::Malformed));
284        assert!(!QnfExtensionAdopted);
285    }
286
287    #[test]
288    fn adopted_flag_is_not_a_silent_true() {
289        assert_eq!(QnfExtensionAdopted, EVALUATION.adopted);
290        assert_ne!(EVALUATION.selected, SelectedRepresentation::QnfExtension);
291        assert_eq!(QnfExtensionAdopted, false);
292    }
293}