Skip to main content

qualia_core_db/governance/webizen/
arena_admit.rs

1//! Caller-owned Webizen arena admission.
2//!
3//! Admits **reuse** of caller-owned arena storage. This module does not allocate
4//! the 42 MiB Sentinel buffer and does not construct [`super::SlgArena`].
5//! Exclusive occupancy is tracked through the existing RT-01 [`LeaseTable`].
6//!
7//! Classification notes (CORE-01, partial):
8//! - Canonical Quin parity is five-field (`NQuin::calculate_parity`).
9//! - Four-field XOR (`s^p^o^context`, dropping metadata) is classified as
10//!   legacy and is **not** auto-repaired.
11//! - The 512-entry recent-slot ring is lossy and must not certify
12//!   evidence / replay / obligation.
13//! - Hash-slot occupancy collisions are always [`CollisionPolicy::MustRecompute`];
14//!   absence of a hash hit is not "fact missing" or "complete retained facts".
15
16use crate::net::peer::runtime::{BufferLease, LeaseTable};
17use crate::net::qdnf::errors::QdnfError;
18use crate::NQuin;
19
20/// `NQuin` ABI width. Must stay 48 bytes.
21pub const QUIN_ABI_BYTES: usize = 48;
22/// Sentinel **pass** working-set: exact 42 MiB slot backing (not the cell budget).
23pub const SENTINEL_PASS_BYTES: usize = 42 * 1024 * 1024;
24/// Slots in exact 42 MiB backing: `SENTINEL_PASS_BYTES / QUIN_ABI_BYTES`.
25pub const SENTINEL_SLOTS: usize = SENTINEL_PASS_BYTES / QUIN_ABI_BYTES; // 917_504
26/// Ordinary cell budget ceiling. 42 MiB is the Sentinel pass, not the cell.
27pub const ORDINARY_CELL_BYTES: usize = 512 * 1024 * 1024;
28/// Recent-slot ring (512 entries in the arena) is lossy. Never durable.
29pub const RECENT_RING_IS_DURABLE: bool = false;
30/// Maximum staged + live rules in one admit record.
31pub const MAX_RULE_STAGING: u16 = 64;
32
33/// Budget class for a caller-owned backing size.
34#[repr(u8)]
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum ArenaBudgetClass {
37    /// Exact 42 MiB slot backing for one Sentinel pass.
38    SentinelPass = 0,
39    /// Strictly larger than 42 MiB and at most 512 MiB.
40    OrdinaryCell = 1,
41    /// Not an admitted pass or cell (documented for matchers; classify fails closed).
42    Rejected = 2,
43}
44
45/// Occupied hash-slot collision policy. Absence is never "complete facts".
46#[repr(u8)]
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub enum CollisionPolicy {
49    /// Recompute / continue. Do not infer missing or fully retained facts.
50    MustRecompute = 0,
51}
52
53/// Stored Quin parity classification. Never dual-accept without classifying.
54#[repr(u8)]
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub enum ParityKind {
57    /// `subject ^ predicate ^ object ^ context ^ metadata` (canonical).
58    FiveFieldCanonical = 0,
59    /// `subject ^ predicate ^ object ^ context` (legacy; do not auto-repair).
60    FourFieldLegacy = 1,
61}
62
63/// Lease/scope wrapper over caller-owned arena backing.
64///
65/// Does not own or allocate the 42 MiB buffer. `live_rules` / `reserved_rules`
66/// are staging counters for this admit record only.
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
68pub struct ArenaAdmit {
69    pub scope: u64,
70    pub policy_generation: u64,
71    pub source_generation: u64,
72    pub lease: BufferLease,
73    live_rules: u16,
74    reserved_rules: u16,
75}
76
77impl ArenaAdmit {
78    /// Zero `live_rules` (and unused reservations). Keep lease/scope/policy/source.
79    ///
80    /// Prevents stale staging from leaking between jobs in **this** admit record.
81    /// Does not touch `SlgArena`; the caller zeros their own buffer.
82    pub fn reset_for_reuse(&mut self) -> Result<(), QdnfError> {
83        self.live_rules = 0;
84        self.reserved_rules = 0;
85        Ok(())
86    }
87
88    /// Reset caller-owned scratch slots that stand in for Sentinel backing.
89    /// Tests must not allocate 42 MiB to prove this binding.
90    pub fn reset_bound_slots(
91        &mut self,
92        slots: &mut [NQuin],
93        recent: &mut [usize],
94        head: &mut usize,
95    ) -> Result<(), QdnfError> {
96        self.reset_for_reuse()?;
97        let empty = NQuin {
98            subject: 0,
99            predicate: 0,
100            object: 0,
101            context: 0,
102            metadata: 0,
103            parity: 0,
104        };
105        let mut i = 0usize;
106        while i < slots.len() {
107            slots[i] = empty;
108            i += 1;
109        }
110        let mut j = 0usize;
111        while j < recent.len() {
112            recent[j] = 0;
113            j += 1;
114        }
115        *head = 0;
116        Ok(())
117    }
118
119    /// Bind reuse to a live [`super::SlgArena`] pass. Does not construct one.
120    pub fn reset_slg_arena(&mut self, arena: &mut super::SlgArena) -> Result<(), QdnfError> {
121        self.reset_for_reuse()?;
122        arena.reset_pass();
123        Ok(())
124    }
125
126    /// Bind this admit record to `scope` + policy/source generations.
127    ///
128    /// Cross-scope → [`QdnfError::Unauthorized`]. Generation mismatch →
129    /// [`QdnfError::StaleGeneration`].
130    pub fn require_scope(
131        &self,
132        scope: u64,
133        policy_generation: u64,
134        source_generation: u64,
135    ) -> Result<(), QdnfError> {
136        if self.scope != scope {
137            return Err(QdnfError::Unauthorized);
138        }
139        if self.policy_generation != policy_generation
140            || self.source_generation != source_generation
141        {
142            return Err(QdnfError::StaleGeneration);
143        }
144        Ok(())
145    }
146
147    /// Reserve a staging slot. Must succeed before incrementing `live_rules`.
148    /// Capacity at [`MAX_RULE_STAGING`] (live + reserved).
149    pub fn reserve_rule_slot(&mut self) -> Result<(), QdnfError> {
150        let occupied = self
151            .live_rules
152            .checked_add(self.reserved_rules)
153            .ok_or(QdnfError::Capacity)?;
154        if occupied >= MAX_RULE_STAGING {
155            return Err(QdnfError::Capacity);
156        }
157        self.reserved_rules = self
158            .reserved_rules
159            .checked_add(1)
160            .ok_or(QdnfError::Capacity)?;
161        Ok(())
162    }
163
164    /// Move one reservation into `live_rules`. Conflict if none reserved.
165    pub fn activate_reserved_rule(&mut self) -> Result<(), QdnfError> {
166        if self.reserved_rules == 0 {
167            return Err(QdnfError::Conflict);
168        }
169        self.reserved_rules -= 1;
170        self.live_rules = self.live_rules.checked_add(1).ok_or(QdnfError::Capacity)?;
171        Ok(())
172    }
173
174    /// Release the exclusive lease. Subsequent `LeaseTable::release` of a stored
175    /// handle copy is [`QdnfError::DoubleRelease`] or [`QdnfError::StaleGeneration`].
176    pub fn revoke(self, leases: &mut LeaseTable) -> Result<(), QdnfError> {
177        leases.release(self.lease.handle)
178    }
179
180    /// Live (activated) rule count for this admit record.
181    pub const fn live_rules(&self) -> u16 {
182        self.live_rules
183    }
184
185    /// Reserved but not yet activated rule count for this admit record.
186    pub const fn reserved_rules(&self) -> u16 {
187        self.reserved_rules
188    }
189}
190
191/// Classify a caller backing size. Exact 42 MiB is the Sentinel pass; (42 MiB, 512 MiB]
192/// is an ordinary cell. Smaller than 42 MiB is not a documented scratch class here.
193/// Over 512 MiB is over the cell budget. Both fail closed as [`QdnfError::Capacity`].
194pub fn classify_budget(bytes: u64) -> Result<ArenaBudgetClass, QdnfError> {
195    let sentinel = SENTINEL_PASS_BYTES as u64;
196    let cell = ORDINARY_CELL_BYTES as u64;
197    if bytes == sentinel {
198        Ok(ArenaBudgetClass::SentinelPass)
199    } else if bytes > sentinel && bytes <= cell {
200        Ok(ArenaBudgetClass::OrdinaryCell)
201    } else {
202        let _ = ArenaBudgetClass::Rejected;
203        Err(QdnfError::Capacity)
204    }
205}
206
207/// Acquire an exclusive RT-01 lease for `backing_bytes` and bind scope + generations.
208///
209/// `backing_bytes` is cast-checked to `u32`. This does not allocate arena storage.
210pub fn admit(
211    leases: &mut LeaseTable,
212    scope: u64,
213    policy_generation: u64,
214    source_generation: u64,
215    backing_bytes: u64,
216) -> Result<ArenaAdmit, QdnfError> {
217    match classify_budget(backing_bytes)? {
218        ArenaBudgetClass::SentinelPass | ArenaBudgetClass::OrdinaryCell => {}
219        ArenaBudgetClass::Rejected => return Err(QdnfError::Capacity),
220    }
221    let capacity = u32::try_from(backing_bytes).map_err(|_| QdnfError::Capacity)?;
222    let lease = leases.acquire(capacity, true)?;
223    Ok(ArenaAdmit {
224        scope,
225        policy_generation,
226        source_generation,
227        lease,
228        live_rules: 0,
229        reserved_rules: 0,
230    })
231}
232
233/// Occupied hash-slot collision: always recompute. A miss is not completeness.
234pub fn collision_on_occupied_hash_slot() -> CollisionPolicy {
235    CollisionPolicy::MustRecompute
236}
237
238/// Classify stored parity. Canonical five-field wins when both XOR folds match
239/// (e.g. `metadata == 0`). Garbage is [`QdnfError::Malformed`]. Never dual-accept.
240pub fn classify_parity(
241    stored: u64,
242    s: u64,
243    p: u64,
244    o: u64,
245    ctx: u64,
246    metadata: u64,
247) -> Result<ParityKind, QdnfError> {
248    let five = NQuin::calculate_parity(s, p, o, ctx, metadata);
249    if stored == five {
250        return Ok(ParityKind::FiveFieldCanonical);
251    }
252    let four = s ^ p ^ o ^ ctx;
253    if stored == four {
254        return Ok(ParityKind::FourFieldLegacy);
255    }
256    Err(QdnfError::Malformed)
257}
258
259/// Empty / unoccupied table entries fail closed. They are not an allow.
260pub fn empty_entry_is_not_allow(occupied: bool) -> Result<(), QdnfError> {
261    if occupied {
262        Ok(())
263    } else {
264        Err(QdnfError::Denied)
265    }
266}
267
268/// The recent-slot ring is lossy. It must not certify obligation.
269pub fn recent_ring_may_certify_obligation() -> bool {
270    false
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276    use crate::net::peer::runtime::LeaseHandle;
277
278    fn admit_sentinel(leases: &mut LeaseTable, scope: u64, policy: u64, source: u64) -> ArenaAdmit {
279        admit(leases, scope, policy, source, SENTINEL_PASS_BYTES as u64).expect("admit sentinel")
280    }
281
282    #[test]
283    fn classify_budget_pass_cell_and_capacity() {
284        assert_eq!(
285            classify_budget(SENTINEL_PASS_BYTES as u64),
286            Ok(ArenaBudgetClass::SentinelPass)
287        );
288        assert_eq!(
289            classify_budget(ORDINARY_CELL_BYTES as u64),
290            Ok(ArenaBudgetClass::OrdinaryCell)
291        );
292        assert_eq!(
293            classify_budget(SENTINEL_PASS_BYTES as u64 + 1),
294            Ok(ArenaBudgetClass::OrdinaryCell)
295        );
296        assert_eq!(
297            classify_budget(ORDINARY_CELL_BYTES as u64 + 1),
298            Err(QdnfError::Capacity)
299        );
300        assert_eq!(classify_budget(1), Err(QdnfError::Capacity));
301    }
302
303    #[test]
304    fn admit_require_scope_rejects_wrong_scope_and_stale_source() {
305        let mut leases = LeaseTable::new();
306        let rec = admit_sentinel(&mut leases, 0xA, 1, 10);
307        rec.require_scope(0xA, 1, 10).unwrap();
308        assert_eq!(rec.require_scope(0xB, 1, 10), Err(QdnfError::Unauthorized));
309        assert_eq!(
310            rec.require_scope(0xA, 1, 9),
311            Err(QdnfError::StaleGeneration)
312        );
313        rec.revoke(&mut leases).unwrap();
314    }
315
316    #[test]
317    fn reset_for_reuse_clears_live_rules_and_keeps_lease() {
318        let mut leases = LeaseTable::new();
319        let mut rec = admit_sentinel(&mut leases, 7, 2, 3);
320        rec.reserve_rule_slot().unwrap();
321        rec.activate_reserved_rule().unwrap();
322        assert_eq!(rec.live_rules(), 1);
323        rec.reset_for_reuse().unwrap();
324        assert_eq!(rec.live_rules(), 0);
325        assert_eq!(rec.reserved_rules(), 0);
326        rec.require_scope(7, 2, 3).unwrap();
327        assert!(rec.lease.exclusive);
328        assert_eq!(rec.lease.capacity, SENTINEL_PASS_BYTES as u32);
329        rec.revoke(&mut leases).unwrap();
330    }
331
332    #[test]
333    fn reserve_then_activate_conflict_without_reserve_and_sixty_fifth_capacity() {
334        let mut leases = LeaseTable::new();
335        let mut rec = admit_sentinel(&mut leases, 1, 1, 1);
336        rec.reserve_rule_slot().unwrap();
337        rec.activate_reserved_rule().unwrap();
338        assert_eq!(rec.live_rules(), 1);
339        assert_eq!(rec.activate_reserved_rule(), Err(QdnfError::Conflict));
340        rec.reset_for_reuse().unwrap();
341        for _ in 0..MAX_RULE_STAGING {
342            rec.reserve_rule_slot().unwrap();
343        }
344        assert_eq!(rec.reserve_rule_slot(), Err(QdnfError::Capacity));
345        rec.revoke(&mut leases).unwrap();
346    }
347
348    #[test]
349    fn revoke_then_release_of_old_handle_is_double_release_or_stale() {
350        let mut leases = LeaseTable::new();
351        let rec = admit_sentinel(&mut leases, 4, 5, 6);
352        let handle: LeaseHandle = rec.lease.handle;
353        let _generation_copy = handle.generation;
354        rec.revoke(&mut leases).unwrap();
355        let second = leases.release(handle);
356        assert!(
357            second == Err(QdnfError::DoubleRelease) || second == Err(QdnfError::StaleGeneration),
358            "expected DoubleRelease or StaleGeneration, got {second:?}"
359        );
360    }
361
362    #[test]
363    fn occupied_hash_slot_collision_is_must_recompute() {
364        assert_eq!(
365            collision_on_occupied_hash_slot(),
366            CollisionPolicy::MustRecompute
367        );
368    }
369
370    #[test]
371    fn classify_parity_five_field_four_field_and_malformed() {
372        let s = 0x11;
373        let p = 0x22;
374        let o = 0x33;
375        let ctx = 0x44;
376        let metadata = 0x55;
377        let five = NQuin::calculate_parity(s, p, o, ctx, metadata);
378        let four = s ^ p ^ o ^ ctx;
379        assert_ne!(
380            five, four,
381            "non-zero metadata must distinguish the two folds"
382        );
383        assert_eq!(
384            classify_parity(five, s, p, o, ctx, metadata),
385            Ok(ParityKind::FiveFieldCanonical)
386        );
387        assert_eq!(
388            classify_parity(four, s, p, o, ctx, metadata),
389            Ok(ParityKind::FourFieldLegacy)
390        );
391        assert_eq!(
392            classify_parity(0xDEAD_BEEF, s, p, o, ctx, metadata),
393            Err(QdnfError::Malformed)
394        );
395        // Dual-match (metadata == 0) classifies as canonical five-field, not both.
396        let zero_meta = 0;
397        let both = NQuin::calculate_parity(s, p, o, ctx, zero_meta);
398        assert_eq!(both, s ^ p ^ o ^ ctx);
399        assert_eq!(
400            classify_parity(both, s, p, o, ctx, zero_meta),
401            Ok(ParityKind::FiveFieldCanonical)
402        );
403    }
404
405    #[test]
406    fn empty_entry_is_denied_not_allow() {
407        assert_eq!(empty_entry_is_not_allow(false), Err(QdnfError::Denied));
408        empty_entry_is_not_allow(true).unwrap();
409    }
410
411    #[test]
412    fn recent_ring_must_not_certify_obligation() {
413        assert!(!RECENT_RING_IS_DURABLE);
414        assert!(!recent_ring_may_certify_obligation());
415    }
416
417    #[test]
418    fn quin_abi_and_sentinel_slot_constants() {
419        assert_eq!(QUIN_ABI_BYTES, 48);
420        assert_eq!(SENTINEL_SLOTS, 917_504);
421        assert_eq!(SENTINEL_PASS_BYTES, 42 * 1024 * 1024);
422        assert_eq!(SENTINEL_SLOTS, SENTINEL_PASS_BYTES / QUIN_ABI_BYTES);
423    }
424
425    #[test]
426    fn reset_bound_slots_clears_scratch_without_42mib_arena() {
427        let mut leases = LeaseTable::new();
428        let mut rec = admit_sentinel(&mut leases, 3, 1, 1);
429        rec.reserve_rule_slot().unwrap();
430        rec.activate_reserved_rule().unwrap();
431        let mut slots = [NQuin {
432            subject: 9,
433            predicate: 8,
434            object: 7,
435            context: 6,
436            metadata: 5,
437            parity: 4,
438        }; 4];
439        let mut recent = [1usize, 2, 3, 0];
440        let mut head = 7usize;
441        rec.reset_bound_slots(&mut slots, &mut recent, &mut head)
442            .unwrap();
443        assert_eq!(rec.live_rules(), 0);
444        assert_eq!(head, 0);
445        assert_eq!(recent, [0, 0, 0, 0]);
446        assert_eq!(slots[0].subject, 0);
447        rec.revoke(&mut leases).unwrap();
448    }
449}