Skip to main content

qualia_core_db/bundle/stream/policy/
manifest.rs

1//! Exact canonical manifest framing; hashes and semantic graph owners are reused.
2use super::types::MAGIC;
3use super::{MAX_MANIFEST_BYTES, ManifestFields, PolicyError as E};
4use crate::crypto::network::digest::sha384;
5use crate::net::qdnf::types::StrongDigest;
6use crate::semantic_instruments::resolve::{
7    DependencyKind,
8    bounded_closure::{ClosureCandidate, MAX_CLOSURE_ORIGINAL_BYTES},
9};
10const ROW: usize = 57;
11const HEADER: usize = MAGIC.len() + 48 * 5 + 8 + 4;
12#[derive(Clone, Copy, Debug)]
13pub struct ManifestView<'a> {
14    encoded: &'a [u8],
15    fields: ManifestFields,
16    rows: &'a [u8],
17    edges: &'a [u8],
18}
19impl<'a> ManifestView<'a> {
20    pub const fn fields(&self) -> ManifestFields {
21        self.fields
22    }
23    pub const fn encoded_bytes(&self) -> &'a [u8] {
24        self.encoded
25    }
26    pub fn digest(&self) -> StrongDigest {
27        sha384(self.encoded)
28    }
29    fn row(&self, index: usize) -> (StrongDigest, u8, u64) {
30        let row = &self.rows[index * ROW..(index + 1) * ROW];
31        (
32            digest(&row[..48]),
33            row[48],
34            u64::from_be_bytes(row[49..57].try_into().unwrap()),
35        )
36    }
37    pub(super) fn matches(&self, candidate: &ClosureCandidate<'_, '_>) -> Result<(), E> {
38        check_fields(self.fields, candidate)?;
39        if self.rows.len() / ROW != candidate.nodes().len()
40            || self.edges.len() / 2 != candidate.edges().len()
41            || candidate
42                .original_byte_count()
43                .checked_add(self.encoded.len())
44                .filter(|n| *n <= MAX_CLOSURE_ORIGINAL_BYTES)
45                .is_none()
46        {
47            return Err(E::Limit);
48        }
49        for i in 0..self.rows.len() / ROW {
50            let (id, kind, length) = self.row(i);
51            let node = candidate
52                .nodes()
53                .iter()
54                .find(|n| n.digest == id)
55                .ok_or(E::Graph)?;
56            if kind != kind_tag(node.kind) || length != node.original_bytes.len() as u64 {
57                return Err(E::Graph);
58            }
59        }
60        for pair in self.edges.chunks_exact(2) {
61            let from = self.row(pair[0] as usize).0;
62            let to = self.row(pair[1] as usize).0;
63            if !candidate
64                .edges()
65                .iter()
66                .any(|e| e.dependent == from && e.dependency == to)
67            {
68                return Err(E::Graph);
69            }
70        }
71        Ok(())
72    }
73}
74fn digest(bytes: &[u8]) -> StrongDigest {
75    StrongDigest(bytes.try_into().expect("validated fixed-width digest"))
76}
77fn kind_tag(kind: DependencyKind) -> u8 {
78    match kind {
79        DependencyKind::Ontology => 1,
80        DependencyKind::Lexicon => 2,
81        DependencyKind::Dataset => 3,
82        DependencyKind::LawPackage => 4,
83        DependencyKind::Instrument => 5,
84        DependencyKind::NativeModule => 6,
85    }
86}
87fn fields_valid(f: ManifestFields) -> Result<(), E> {
88    if f.source_length < 64
89        || f.source_length > (1u64 << 40)
90        || [f.source, f.semantic_root, f.policy, f.consumer, f.issuer]
91            .iter()
92            .any(|d| d.is_zero())
93    {
94        return Err(E::Reference);
95    }
96    Ok(())
97}
98fn check_fields(f: ManifestFields, c: &ClosureCandidate<'_, '_>) -> Result<(), E> {
99    fields_valid(f)?;
100    if f.semantic_root != c.root_digest()
101        || !c.nodes().iter().any(|n| n.digest == f.policy)
102        || !c.nodes().iter().any(|n| n.digest == f.consumer)
103    {
104        return Err(E::Reference);
105    }
106    Ok(())
107}
108pub fn decode_manifest(bytes: &[u8]) -> Result<ManifestView<'_>, E> {
109    if bytes.len() > MAX_MANIFEST_BYTES {
110        return Err(E::Limit);
111    }
112    if bytes.len() < HEADER || !bytes.starts_with(MAGIC) {
113        return Err(E::Encoding);
114    }
115    let mut pos = MAGIC.len();
116    let source = digest(&bytes[pos..pos + 48]);
117    pos += 48;
118    let source_length = u64::from_be_bytes(bytes[pos..pos + 8].try_into().unwrap());
119    pos += 8;
120    let semantic_root = digest(&bytes[pos..pos + 48]);
121    pos += 48;
122    let policy = digest(&bytes[pos..pos + 48]);
123    pos += 48;
124    let consumer = digest(&bytes[pos..pos + 48]);
125    pos += 48;
126    let issuer = digest(&bytes[pos..pos + 48]);
127    pos += 48;
128    if bytes[pos] != 1 {
129        return Err(E::Encoding);
130    }
131    pos += 1;
132    let nodes = bytes[pos] as usize;
133    pos += 1;
134    let edges = u16::from_be_bytes(bytes[pos..pos + 2].try_into().unwrap()) as usize;
135    pos += 2;
136    if !(1..=16).contains(&nodes) || edges > 256 {
137        return Err(E::Limit);
138    }
139    if bytes.len() != pos + nodes * ROW + edges * 2 {
140        return Err(E::Encoding);
141    }
142    let fields = ManifestFields {
143        source,
144        source_length,
145        semantic_root,
146        policy,
147        consumer,
148        issuer,
149    };
150    fields_valid(fields)?;
151    let view = ManifestView {
152        encoded: bytes,
153        fields,
154        rows: &bytes[pos..pos + nodes * ROW],
155        edges: &bytes[pos + nodes * ROW..],
156    };
157    let mut total = bytes.len() as u64;
158    for i in 0..nodes {
159        let (id, kind, length) = view.row(i);
160        if id.is_zero() || !(1..=6).contains(&kind) || (i != 0 && view.row(i - 1).0.0 >= id.0) {
161            return Err(E::Encoding);
162        }
163        total = total.checked_add(length).ok_or(E::Limit)?;
164        if total > MAX_CLOSURE_ORIGINAL_BYTES as u64 {
165            return Err(E::Limit);
166        }
167    }
168    for reference in [semantic_root, policy, consumer] {
169        if !(0..nodes).any(|i| view.row(i).0 == reference) {
170            return Err(E::Reference);
171        }
172    }
173    let mut previous = None;
174    for pair in view.edges.chunks_exact(2) {
175        let key = (pair[0], pair[1]);
176        if pair[0] as usize >= nodes
177            || pair[1] as usize >= nodes
178            || pair[0] == pair[1]
179            || previous.is_some_and(|p| p >= key)
180        {
181            return Err(E::Encoding);
182        }
183        previous = Some(key);
184    }
185    Ok(view)
186}
187/// Canonicalize an already structurally checked candidate into caller storage.
188pub fn encode_manifest_into(
189    fields: ManifestFields,
190    candidate: &ClosureCandidate<'_, '_>,
191    out: &mut [u8],
192) -> Result<usize, E> {
193    check_fields(fields, candidate)?;
194    let nodes = candidate.nodes();
195    let length = HEADER + nodes.len() * ROW + candidate.edges().len() * 2;
196    if length > MAX_MANIFEST_BYTES
197        || candidate
198            .original_byte_count()
199            .checked_add(length)
200            .filter(|n| *n <= MAX_CLOSURE_ORIGINAL_BYTES)
201            .is_none()
202    {
203        return Err(E::Limit);
204    }
205    let out = out.get_mut(..length).ok_or(E::Capacity)?;
206    let mut order = [0usize; 16];
207    for i in 0..nodes.len() {
208        order[i] = i;
209    }
210    // Fixed insertion sort: bounded, deterministic, allocation-free and nonrecursive.
211    for i in 1..nodes.len() {
212        let value = order[i];
213        let mut j = i;
214        while j != 0 && nodes[order[j - 1]].digest.0 > nodes[value].digest.0 {
215            order[j] = order[j - 1];
216            j -= 1;
217        }
218        order[j] = value;
219    }
220    let mut pos = 0;
221    fn put(out: &mut [u8], pos: &mut usize, bytes: &[u8]) {
222        out[*pos..*pos + bytes.len()].copy_from_slice(bytes);
223        *pos += bytes.len();
224    }
225    put(out, &mut pos, MAGIC);
226    put(out, &mut pos, &fields.source.0);
227    put(out, &mut pos, &fields.source_length.to_be_bytes());
228    for id in [
229        fields.semantic_root,
230        fields.policy,
231        fields.consumer,
232        fields.issuer,
233    ] {
234        put(out, &mut pos, &id.0);
235    }
236    put(out, &mut pos, &[1, nodes.len() as u8]);
237    put(
238        out,
239        &mut pos,
240        &(candidate.edges().len() as u16).to_be_bytes(),
241    );
242    for i in &order[..nodes.len()] {
243        let node = nodes[*i];
244        put(out, &mut pos, &node.digest.0);
245        put(out, &mut pos, &[kind_tag(node.kind)]);
246        put(
247            out,
248            &mut pos,
249            &(node.original_bytes.len() as u64).to_be_bytes(),
250        );
251    }
252    for (from, i) in order[..nodes.len()].iter().enumerate() {
253        for (to, j) in order[..nodes.len()].iter().enumerate() {
254            if candidate
255                .edges()
256                .iter()
257                .any(|e| e.dependent == nodes[*i].digest && e.dependency == nodes[*j].digest)
258            {
259                put(out, &mut pos, &[from as u8, to as u8]);
260            }
261        }
262    }
263    debug_assert_eq!(pos, length);
264    Ok(length)
265}
266
267mod transport;
268pub use transport::{ManifestArtifact,ManifestDependency};