qualia_core_db/governance/webizen/arena.rs
1use super::*;
2
3/// A fast, non-cryptographic bitwise hash to lookup sub-goals in the SLG Arena
4/// without wasting CPU cycles on cryptographic overhead.
5#[inline(always)]
6fn fast_hash_goal(subject: u64, predicate: u64, object: u64) -> usize {
7 let mut hash = subject.wrapping_add(0x9E3779B97F4A7C15);
8 hash = (hash ^ (hash >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);
9 hash = (hash ^ predicate).wrapping_mul(0x94D049BB133111EB);
10 hash = (hash ^ object).wrapping_mul(0x9E3779B97F4A7C15);
11 (hash ^ (hash >> 31)) as usize
12}
13
14/// True when any triple in the rule's premise or conclusion carries a variable.
15/// Such rules cannot compile to a single ground deontic norm and are instead
16/// grounded by forward-chaining (`SlgArena::fire_guard_rules`).
17fn rule_has_variables(rule: &CompiledRule) -> bool {
18 let term_is_var = |t: &crate::modalities::logic::n3_compiler::CompiledTerm| t.is_variable();
19 rule.premise
20 .triples
21 .iter()
22 .chain(rule.conclusion.triples.iter())
23 .any(|tr| term_is_var(&tr.subject) || term_is_var(&tr.predicate) || term_is_var(&tr.object))
24}
25
26/// Unify one premise-triple field against a fact field under the current bindings.
27///
28/// * IRI / literal term → matches iff `q_hash(term) == field`.
29/// * variable term → matches the existing binding, or (if unbound) binds it to
30/// `field` and grows `nbound`.
31///
32/// Hashing uses the same `q_hash` as `n3_compiler::triple_to_quin`, so a premise
33/// term and an ingested fact agree.
34fn unify_field(
35 t: &CompiledTerm,
36 field: u64,
37 bindings: &mut [(u64, u64)],
38 nbound: &mut usize,
39) -> bool {
40 match t {
41 CompiledTerm::Uri(s) | CompiledTerm::Literal(s) => *s == field,
42 CompiledTerm::Variable(key) => {
43 for i in 0..*nbound {
44 if bindings[i].0 == *key {
45 return bindings[i].1 == field;
46 }
47 }
48 if *nbound < bindings.len() {
49 bindings[*nbound] = (*key, field);
50 *nbound += 1;
51 true
52 } else {
53 false // binding table exhausted — refuse rather than mis-bind
54 }
55 }
56 }
57}
58
59/// Resolve a conclusion-triple field to a concrete hash under the bindings.
60/// Returns `None` for an unbound conclusion variable (a fresh variable not
61/// constrained by the premise) — such conclusions are skipped, never guessed.
62#[allow(clippy::ptr_arg)]
63fn resolve_term(term: &CompiledTerm, bindings: &[(u64, u64)]) -> Option<u64> {
64 match term {
65 CompiledTerm::Uri(s) | CompiledTerm::Literal(s) => Some(*s),
66 CompiledTerm::Variable(key) => bindings.iter().find(|(k, _)| *k == *key).map(|(_, v)| *v),
67 }
68}
69
70/// Conjunctive backtracking join of a rule's premise triples against the facts.
71///
72/// At full depth (every premise triple satisfied), each conclusion triple is
73/// instantiated with the bound variables and staged into `pending`. Backtracking
74/// is implicit: each fact iteration restarts binding from `nbound`, so bindings a
75/// failed branch added are simply overwritten on the next branch.
76#[allow(clippy::too_many_arguments)]
77fn join_premise(
78 premise: &[CompiledTriple],
79 conclusion: &[CompiledTriple],
80 facts: &[NQuin],
81 idx: usize,
82 bindings: &mut [(u64, u64)],
83 nbound: usize,
84 pending: &mut [NQuin],
85 pending_count: &mut usize,
86) {
87 if idx >= MAX_PREMISE_DEPTH {
88 return; // guard against pathologically deep premises
89 }
90 if idx == premise.len() {
91 for ct in conclusion {
92 if *pending_count >= pending.len() {
93 return;
94 }
95 let (Some(s), Some(p), Some(o)) = (
96 resolve_term(&ct.subject, &bindings[..nbound]),
97 resolve_term(&ct.predicate, &bindings[..nbound]),
98 resolve_term(&ct.object, &bindings[..nbound]),
99 ) else {
100 continue;
101 };
102 let mut q = NQuin {
103 subject: s,
104 predicate: p,
105 object: o,
106 context: 0,
107 metadata: 1,
108 parity: 0,
109 };
110 q.parity = q.subject ^ q.predicate ^ q.object ^ q.context;
111 pending[*pending_count] = q;
112 *pending_count += 1;
113 }
114 return;
115 }
116
117 let t = &premise[idx];
118 for fact in facts {
119 let mut local_nbound = nbound;
120 if unify_field(&t.subject, fact.subject, bindings, &mut local_nbound)
121 && unify_field(&t.predicate, fact.predicate, bindings, &mut local_nbound)
122 && unify_field(&t.object, fact.object, bindings, &mut local_nbound)
123 {
124 join_premise(
125 premise,
126 conclusion,
127 facts,
128 idx + 1,
129 bindings,
130 local_nbound,
131 pending,
132 pending_count,
133 );
134 }
135 }
136}
137
138pub struct SlgArena {
139 // We will use a safe Vec wrapper here since it is allocated strictly once and never grown.
140 #[cfg(feature = "alloc_buffers")]
141 buffer: alloc::vec::Vec<NQuin>,
142 #[cfg(not(feature = "alloc_buffers"))]
143 buffer: std::vec::Vec<NQuin>,
144 head_pointer: usize,
145 recent_slots: [usize; RECENT_SLOT_RING],
146 recent_slot_head: usize,
147 // Native Rule Registry to hold N3 Logical Implications
148 #[cfg(feature = "alloc_buffers")]
149 rule_registry: alloc::vec::Vec<CompiledRule>,
150 #[cfg(not(feature = "alloc_buffers"))]
151 rule_registry: std::vec::Vec<CompiledRule>,
152 /// Pre-parsed rules indexed by id; activated via `NativeRegisterRule`.
153 #[cfg(feature = "alloc_buffers")]
154 staged_rules: alloc::vec::Vec<CompiledRule>,
155 #[cfg(not(feature = "alloc_buffers"))]
156 staged_rules: std::vec::Vec<CompiledRule>,
157}
158
159#[cfg(feature = "alloc_buffers")]
160extern crate alloc;
161
162impl SlgArena {
163 /// Creates `SlgArena` with the given state.
164 pub fn new() -> Self {
165 #[cfg(feature = "alloc_buffers")]
166 extern crate alloc;
167
168 #[cfg(feature = "alloc_buffers")]
169 let mut buffer = alloc::vec::Vec::with_capacity(MAX_SLOTS);
170 #[cfg(not(feature = "alloc_buffers"))]
171 let mut buffer = std::vec::Vec::with_capacity(MAX_SLOTS);
172
173 // Pre-fill the ring buffer with empty Quins
174 for _ in 0..MAX_SLOTS {
175 buffer.push(NQuin {
176 subject: 0,
177 predicate: 0,
178 object: 0,
179 context: 0,
180 metadata: 0,
181 parity: 0,
182 });
183 }
184
185 #[cfg(feature = "alloc_buffers")]
186 let rule_registry = alloc::vec::Vec::new();
187 #[cfg(not(feature = "alloc_buffers"))]
188 let rule_registry = std::vec::Vec::new();
189 #[cfg(feature = "alloc_buffers")]
190 let staged_rules = alloc::vec::Vec::new();
191 #[cfg(not(feature = "alloc_buffers"))]
192 let staged_rules = std::vec::Vec::new();
193
194 Self {
195 buffer,
196 head_pointer: 0,
197 recent_slots: [0; RECENT_SLOT_RING],
198 recent_slot_head: 0,
199 rule_registry,
200 staged_rules,
201 }
202 }
203
204 /// Registers a logical implication rule into the Webizen VM
205 pub fn register_rule(&mut self, rule: &Rule<'_>) {
206 vm_log!("🧠 Webizen registered new Compiled N3 Rule");
207 self.rule_registry.push(compile_rule_to_zero_heap(rule));
208 }
209
210 /// Stage a parsed rule for later activation via `NativeRegisterRule`.
211 /// Returns the rule id (`object_reg` value) used to activate it.
212 pub fn stage_rule(&mut self, rule: &Rule<'_>) -> u64 {
213 let id = self.staged_rules.len() as u64;
214 self.staged_rules.push(compile_rule_to_zero_heap(rule));
215 id
216 }
217
218 /// Activate a staged rule by id into the live rule registry.
219 pub fn activate_staged_rule(&mut self, rule_id: u64) -> bool {
220 let idx = rule_id as usize;
221 if idx >= self.staged_rules.len() {
222 return false;
223 }
224 self.rule_registry.push(self.staged_rules[idx].clone());
225 true
226 }
227
228 /// Committed rules.
229 pub fn rule_count(&self) -> usize {
230 self.rule_registry.len()
231 }
232
233 /// Staged (uncommitted) rules.
234 pub fn staged_rule_count(&self) -> usize {
235 self.staged_rules.len()
236 }
237
238 /// Reset the live pass working set (head + recent ring slots).
239 ///
240 /// Does not reallocate the 42 MiB backing and does not scan every slot.
241 /// Occupied recent-ring entries are zeroed so a subsequent pass cannot
242 /// observe prior facts through the lossy ring.
243 pub fn reset_pass(&mut self) {
244 let empty = NQuin {
245 subject: 0,
246 predicate: 0,
247 object: 0,
248 context: 0,
249 metadata: 0,
250 parity: 0,
251 };
252 let mut i = 0usize;
253 while i < RECENT_SLOT_RING {
254 let idx = self.recent_slots[i];
255 if idx < self.buffer.len() {
256 self.buffer[idx] = empty;
257 }
258 self.recent_slots[i] = 0;
259 i += 1;
260 }
261 self.head_pointer = 0;
262 self.recent_slot_head = 0;
263 }
264
265 #[inline]
266 /// `SlgArena::pass_head`.
267 pub fn pass_head(&self) -> usize {
268 self.head_pointer
269 }
270
271 /// Collect recently written Quins with valid ECC parity (bounded scan, zero heap).
272 pub fn collect_active_quins(&self, out: &mut [NQuin]) -> usize {
273 let mut n = 0usize;
274 let scan = RECENT_SLOT_RING.min(self.recent_slot_head);
275 for off in 0..scan {
276 let ring_idx = (self.recent_slot_head + RECENT_SLOT_RING - 1 - off) % RECENT_SLOT_RING;
277 let idx = self.recent_slots[ring_idx];
278 let q = self.buffer[idx];
279 if q.subject == 0 {
280 continue;
281 }
282 let expected = q.subject ^ q.predicate ^ q.object ^ q.context;
283 if q.parity != expected {
284 continue;
285 }
286 if n < out.len() {
287 out[n] = q;
288 n += 1;
289 }
290 }
291 n
292 }
293
294 /// Compile registered N3 rules to norms + bytecode and execute on Core 1 (cold path).
295 pub fn fire_registered_rules(&mut self, contract_hash: u64) -> usize {
296 // Zero-heap: move the registry out (pointer swap, not a clone of the rules) so
297 // the loop can call `&mut self` methods (`write_table` / `execute_vm_frame`)
298 // while reading the rules; restored below before `fire_guard_rules` needs it.
299 // Safe: nothing in the loop reads or mutates `rule_registry` (only
300 // `register_rule` does, and it is never called during firing).
301 let rules = core::mem::take(&mut self.rule_registry);
302 let mut fired = 0usize;
303 for rule in &rules {
304 // Only ground rules compile to a single deontic norm; variable rules
305 // are grounded by forward-chaining (`fire_guard_rules`) below, so
306 // compiling them here would write a spurious norm keyed on a
307 // variable-name hash.
308 if !rule_has_variables(rule) {
309 if let Some(norm) = crate::modalities::logic::deontic::compile_n3_rule_to_norm(
310 rule,
311 contract_hash,
312 0,
313 ) {
314 self.write_table(norm);
315 }
316 }
317 let mut opcodes = [SlgOpcode::Halt; 64];
318 if let Ok(count) =
319 crate::modalities::logic::n3_compiler::compile_rule_to_opcodes(rule, &mut opcodes)
320 {
321 let mut frame = VmFrame::default();
322 if execute_vm_frame(self, &opcodes[..count], &mut frame).is_some() {
323 fired += 1;
324 }
325 }
326 }
327 // Restore the registry before `fire_guard_rules` forward-chains over it.
328 self.rule_registry = rules;
329 // Variable (non-ground) rules — e.g. the agency.n3 G1 corporate-capture
330 // guard — cannot compile to a single ground norm; they are grounded by
331 // forward-chaining their premise over the facts live in the arena.
332 fired += self.fire_guard_rules();
333 fired
334 }
335
336 /// Forward-chaining grounding pass for variable (non-ground) N3 guard rules.
337 ///
338 /// `fire_registered_rules` handles *ground* deontic rules via
339 /// `compile_n3_rule_to_norm`. This is its complement: for every registered rule
340 /// whose premise contains variables, it performs a conjunctive backtracking join
341 /// of the premise triples against the facts currently live in the arena, and for
342 /// each satisfying binding instantiates and asserts the (variable-substituted)
343 /// conclusion triples back into the arena. Returns the number of conclusion
344 /// triples newly asserted.
345 ///
346 /// Worked example — agency.n3 **G1**:
347 /// ```text
348 /// { ?c a values:CorporatePerson ; values:claims ?r .
349 /// ?r a values:Right ; values:heldBy values:NaturalPerson }
350 /// => { ?c values:flag values:PersonhoodCategoryError } .
351 /// ```
352 /// Given facts that a corporate person claims a natural-person right, the guard
353 /// asserts `(?c, values:flag, values:PersonhoodCategoryError)` — the personhood
354 /// category error (a Deny) — observable via [`Self::has_quin`].
355 ///
356 /// Cold path: bounded stack buffers, no hot-path heap growth. Hashing is uniform
357 /// `q_hash` over IRIs/variables/literals (matching `n3_compiler::triple_to_quin`),
358 /// so grounding matches facts ingested through the standard triple path.
359 ///
360 /// Forward chaining asserts the conclusion of any satisfied premise. Defeasible
361 /// *override* of a deontic norm (e.g. a marked corporate overlay defeating a
362 /// prohibition) is handled in the deontic-norm lane via the `q42:unless`
363 /// defeater path (`evaluate_deontic_contract`), not here — the agency.n3 guards
364 /// (G1/G1') are strict `=>` rules.
365 pub fn fire_guard_rules(&mut self) -> usize {
366 // Zero-heap: see `fire_registered_rules` — move the registry out (no clone),
367 // iterate across the fixpoint rounds, restore at the end. Safe: the loop only
368 // reads facts and calls `write_table` / `has_quin`, never touching the registry.
369 let rules = core::mem::take(&mut self.rule_registry);
370 let mut total = 0usize;
371
372 // Forward-chain to a bounded fixpoint: a conclusion asserted in one round
373 // may satisfy another guard's premise next round (e.g. overclaim → flag →
374 // requiresHumanReview). `has_quin` idempotency guarantees termination.
375 for _round in 0..MAX_FIXPOINT_ROUNDS {
376 // Snapshot the live facts (immutable borrow ends before we assert).
377 let mut facts = [NQuin::default(); 1024];
378 let fact_count = self.collect_active_quins(&mut facts);
379
380 let mut pending = [NQuin::default(); MAX_GUARD_CONCLUSIONS];
381 let mut pending_count = 0usize;
382
383 for rule in &rules {
384 if !rule_has_variables(rule) {
385 continue; // ground rules go through the deontic-norm path
386 }
387 // `triples` is a fixed `[_; 8]` array, so `.is_empty()` is always
388 // false - gate on the populated `len` instead.
389 if rule.premise.len == 0 || rule.conclusion.len == 0 {
390 continue;
391 }
392 let mut bindings = [(0u64, 0u64); MAX_RULE_VARS];
393 join_premise(
394 &rule.premise.triples[..rule.premise.len],
395 // Slice the conclusion by `len` too: passing the full array
396 // would stage (8 - len) junk (0,0,0) triples per match, which
397 // - being skipped by `has_quin` (subject==0) - get re-asserted
398 // every round, never reaching the fixpoint and flooding the
399 // recent-write ring until real conclusions are evicted.
400 &rule.conclusion.triples[..rule.conclusion.len],
401 &facts[..fact_count],
402 0,
403 &mut bindings,
404 0,
405 &mut pending,
406 &mut pending_count,
407 );
408 }
409
410 let mut asserted = 0usize;
411 for q in pending.iter().take(pending_count) {
412 // Idempotent: don't re-assert a conclusion already present.
413 if !self.has_quin(q.subject, q.predicate, q.object) {
414 self.write_table(*q);
415 asserted += 1;
416 }
417 }
418 total += asserted;
419 if asserted == 0 {
420 break; // fixpoint reached
421 }
422 }
423 self.rule_registry = rules;
424 total
425 }
426
427 /// True when a fact `(subject, predicate, object)` is live in the arena with
428 /// valid ECC parity. Used to observe forward-chained guard conclusions.
429 pub fn has_quin(&self, subject: u64, predicate: u64, object: u64) -> bool {
430 let mut scratch = [NQuin::default(); 1024];
431 let n = self.collect_active_quins(&mut scratch);
432 scratch[..n]
433 .iter()
434 .any(|q| q.subject == subject && q.predicate == predicate && q.object == object)
435 }
436
437 /// Checks the SLG Arena for a previously proven sub-goal.
438 pub fn check_table(&self, subject: u64, predicate: u64, object: u64) -> Option<NQuin> {
439 let slot = fast_hash_goal(subject, predicate, object) % MAX_SLOTS;
440
441 let cached = self.buffer[slot];
442 if cached.subject == subject && cached.predicate == predicate && cached.object == object {
443 Some(cached)
444 } else {
445 None
446 }
447 }
448
449 /// Writes a proven sub-goal into the SLG Arena.
450 /// If the slot is occupied (hash collision) or we hit the boundary,
451 /// it acts as a FIFO ring-buffer and strictly overwrites the oldest cache entries.
452 pub fn write_table(&mut self, result: NQuin) {
453 let slot = fast_hash_goal(result.subject, result.predicate, result.object) % MAX_SLOTS;
454
455 // Cyclic Eviction Policy: Overwrite whatever is in the slot natively
456 self.buffer[slot] = result;
457 self.recent_slots[self.recent_slot_head % RECENT_SLOT_RING] = slot;
458 self.recent_slot_head = self.recent_slot_head.saturating_add(1);
459
460 // Increment global ring-buffer pointer (used if we wanted strict sequential FIFO instead of hashed slots)
461 self.head_pointer = (self.head_pointer + 1) % MAX_SLOTS;
462 }
463
464 /// Mutable quin slot for a key.
465 pub(crate) fn find_mutable_quin(
466 &mut self,
467 subject: u64,
468 predicate: u64,
469 object: u64,
470 ) -> Option<&mut NQuin> {
471 let scan = RECENT_SLOT_RING.min(self.recent_slot_head);
472 for off in 0..scan {
473 let ring_idx = (self.recent_slot_head + RECENT_SLOT_RING - 1 - off) % RECENT_SLOT_RING;
474 let idx = self.recent_slots[ring_idx];
475 let matches = self.buffer[idx].subject == subject
476 && self.buffer[idx].predicate == predicate
477 && (object == 0 || self.buffer[idx].object == object);
478 if matches {
479 return Some(&mut self.buffer[idx]);
480 }
481 }
482 None
483 }
484}