Skip to main content

qualia_core_db/modalities/logic/
qubo.rs

1//! Semantic-to-QUBO boil-down compiler for zero-context quantum offloading.
2//!
3//! Strips DIDs and URIs into ephemeral local indices, emits linear biases and
4//! quadratic coupler weights, then re-hydrates binary solutions back to Quins.
5
6use crate::NQuin;
7
8pub const OP_EMIT_WEIGHT: u8 = 0x50;
9pub const MAX_QUBO_VARS: usize = 64;
10pub const MAX_COUPLERS: usize = 512;
11
12#[derive(Debug, Clone, Copy, PartialEq)]
13pub enum QuboCompileError {
14    VarBufferFull,
15    CouplerBufferFull,
16    IndexMapFull,
17    ClassifiedEgress,
18}
19
20#[repr(C)]
21#[derive(Debug, Clone, Copy)]
22pub struct QuboWeightEmit {
23    pub var_a: u8,
24    pub var_b: u8,
25    pub weight: f32,
26}
27
28#[derive(Debug, Clone)]
29pub struct QuboMatrix {
30    pub num_vars: u8,
31    pub linear: [f32; MAX_QUBO_VARS],
32    pub couplers: [QuboWeightEmit; MAX_COUPLERS],
33    pub coupler_count: usize,
34    pub index_map: [(u64, u8); MAX_QUBO_VARS],
35    pub index_count: usize,
36}
37
38impl Default for QuboMatrix {
39    fn default() -> Self {
40        Self {
41            num_vars: 0,
42            linear: [0.0; MAX_QUBO_VARS],
43            couplers: [QuboWeightEmit {
44                var_a: 0,
45                var_b: 0,
46                weight: 0.0,
47            }; MAX_COUPLERS],
48            coupler_count: 0,
49            index_map: [(0, 0); MAX_QUBO_VARS],
50            index_count: 0,
51        }
52    }
53}
54
55impl QuboMatrix {
56    fn map_var(&mut self, entity_hash: u64) -> Result<u8, QuboCompileError> {
57        for i in 0..self.index_count {
58            if self.index_map[i].0 == entity_hash {
59                return Ok(self.index_map[i].1);
60            }
61        }
62        if self.index_count >= MAX_QUBO_VARS {
63            return Err(QuboCompileError::IndexMapFull);
64        }
65        let idx = self.index_count as u8;
66        self.index_map[self.index_count] = (entity_hash, idx);
67        self.index_count += 1;
68        if idx as usize + 1 > self.num_vars as usize {
69            self.num_vars = idx + 1;
70        }
71        Ok(idx)
72    }
73
74    /// Emits a linear bias on `var`; `QuboCompileError` at capacity.
75    pub fn emit_linear(&mut self, var: u8, bias: f32) -> Result<(), QuboCompileError> {
76        if var as usize >= MAX_QUBO_VARS {
77            return Err(QuboCompileError::VarBufferFull);
78        }
79        self.linear[var as usize] += bias;
80        Ok(())
81    }
82
83    /// Emits a coupler `(a,b)` with `weight`.
84    pub fn emit_coupler(&mut self, a: u8, b: u8, weight: f32) -> Result<(), QuboCompileError> {
85        if self.coupler_count >= MAX_COUPLERS {
86            return Err(QuboCompileError::CouplerBufferFull);
87        }
88        self.couplers[self.coupler_count] = QuboWeightEmit {
89            var_a: a,
90            var_b: b,
91            weight,
92        };
93        self.coupler_count += 1;
94        Ok(())
95    }
96
97    /// Clears the var→index map.
98    pub fn wipe_index_map(&mut self) {
99        for slot in &mut self.index_map {
100            unsafe {
101                std::ptr::write_volatile(&mut slot.0, 0);
102            }
103        }
104        self.index_count = 0;
105    }
106}
107
108/// Walk constraint Quins and compile a blind QUBO matrix.
109pub fn compile_quins_to_qubo(
110    quins: &[NQuin],
111    out: &mut QuboMatrix,
112) -> Result<(), QuboCompileError> {
113    *out = QuboMatrix::default();
114    for q in quins {
115        if q.get_sensitivity_byte() == NQuin::SENSITIVITY_CLASSIFIED {
116            return Err(QuboCompileError::ClassifiedEgress);
117        }
118        let subj = out.map_var(q.subject)?;
119        let obj = out.map_var(q.object)?;
120        let pred_low = (q.predicate & 0xFF) as u8;
121        let weight = if pred_low == OP_EMIT_WEIGHT {
122            decode_inline_weight(q.object)
123        } else {
124            penalty_from_predicate(pred_low)
125        };
126        if subj == obj {
127            out.emit_linear(subj, weight)?;
128        } else {
129            out.emit_coupler(subj, obj, weight)?;
130            out.emit_linear(subj, weight * 0.5)?;
131            out.emit_linear(obj, weight * 0.5)?;
132        }
133    }
134    Ok(())
135}
136
137/// VM opcode handler: push a float weight from the object register.
138pub fn emit_weight_from_quin(
139    quin: &NQuin,
140    matrix: &mut QuboMatrix,
141) -> Result<(), QuboCompileError> {
142    let subj = matrix.map_var(quin.subject)?;
143    let obj = matrix.map_var(quin.object)?;
144    let w = decode_inline_weight(quin.object);
145    if subj == obj {
146        matrix.emit_linear(subj, w)
147    } else {
148        matrix.emit_coupler(subj, obj, w)
149    }
150}
151
152fn decode_inline_weight(object: u64) -> f32 {
153    let tag = (object >> 60) & 0x7;
154    if tag == 0b010 {
155        let scaled = (object & 0x0FFF_FFFF_FFFF_FFFF) as i64;
156        (scaled as f32) / 1_000_000.0
157    } else {
158        let raw = (object & 0xFFFF) as i32;
159        (raw as f32) / 100.0
160    }
161}
162
163fn penalty_from_predicate(opcode: u8) -> f32 {
164    match opcode {
165        0x10 => 5.0,  // OP_OBLIGATE — violation penalty
166        0x11 => -2.0, // OP_PERMIT — reward
167        0x12 => 8.0,  // OP_FORBID — hard penalty
168        _ => 1.0,
169    }
170}
171
172/// Classical fallback: greedy energy minimization on small QUBO.
173pub fn solve_classical(matrix: &QuboMatrix, assignment: &mut [u8; MAX_QUBO_VARS]) -> f32 {
174    let n = matrix.num_vars as usize;
175    for i in 0..n {
176        assignment[i] = 0;
177    }
178    let mut improved = true;
179    let mut energy = qubo_energy(matrix, assignment, n);
180    while improved {
181        improved = false;
182        for i in 0..n {
183            assignment[i] = 1 - assignment[i];
184            let new_e = qubo_energy(matrix, assignment, n);
185            if new_e < energy {
186                energy = new_e;
187                improved = true;
188            } else {
189                assignment[i] = 1 - assignment[i];
190            }
191        }
192    }
193    energy
194}
195
196fn qubo_energy(matrix: &QuboMatrix, assignment: &[u8; MAX_QUBO_VARS], n: usize) -> f32 {
197    let mut e = 0.0f32;
198    for i in 0..n {
199        if assignment[i] == 1 {
200            e += matrix.linear[i];
201        }
202    }
203    for c in 0..matrix.coupler_count {
204        let cw = matrix.couplers[c];
205        let a = cw.var_a as usize;
206        let b = cw.var_b as usize;
207        if a < n && b < n && assignment[a] == 1 && assignment[b] == 1 {
208            e += cw.weight;
209        }
210    }
211    e
212}
213
214/// Re-hydrate a binary solution using the ephemeral index map.
215pub fn rehydrate_solution(
216    matrix: &mut QuboMatrix,
217    assignment: &[u8; MAX_QUBO_VARS],
218    out: &mut [NQuin],
219) -> usize {
220    let mut count = 0;
221    for i in 0..matrix.index_count {
222        if count >= out.len() {
223            break;
224        }
225        let (entity, var) = matrix.index_map[i];
226        let val = assignment[var as usize];
227        let predicate = crate::q_hash("q42:quantumAssignment");
228        let context = crate::q_hash("q42:rehydrated");
229        let object = if val == 1 { 1 } else { 0 };
230        let q = NQuin {
231            subject: entity,
232            predicate,
233            object,
234            context,
235            metadata: 0xC000_0000_0000_0003,
236            parity: entity ^ predicate ^ object ^ context,
237        };
238        out[count] = q;
239        count += 1;
240    }
241    matrix.wipe_index_map();
242    count
243}
244
245/// Pre-flight gate: reject prompts that signal classified quantum egress.
246pub fn quantum_prompt_gate(prompt: &str) -> Option<&'static str> {
247    let lower = prompt.to_lowercase();
248    if lower.contains("classified") && (lower.contains("[qpu:") || lower.contains("quantum")) {
249        return Some("FATAL: Cannot egress 0x02_CLASSIFIED assertions to a remote QPU.");
250    }
251    if lower.contains("sensitivitylabel") && lower.contains("0x02") {
252        return Some("FATAL: Classified sensitivity label blocks QPU egress.");
253    }
254    None
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    #[test]
262    fn compile_empty_quins() {
263        let mut m = QuboMatrix::default();
264        assert!(compile_quins_to_qubo(&[], &mut m).is_ok());
265        assert_eq!(m.num_vars, 0);
266    }
267
268    #[test]
269    fn classified_quin_blocks_egress() {
270        let mut q = NQuin {
271            subject: 1,
272            predicate: 0,
273            object: 2,
274            context: 0,
275            metadata: 0,
276            parity: 0,
277        };
278        q.set_sensitivity_byte(NQuin::SENSITIVITY_CLASSIFIED);
279        let mut m = QuboMatrix::default();
280        assert_eq!(
281            compile_quins_to_qubo(&[q], &mut m),
282            Err(QuboCompileError::ClassifiedEgress)
283        );
284    }
285
286    #[test]
287    fn classical_solver_finds_low_energy() {
288        let mut m = QuboMatrix::default();
289        m.num_vars = 2;
290        m.linear[0] = -1.0;
291        m.linear[1] = -1.0;
292        m.couplers[0] = QuboWeightEmit {
293            var_a: 0,
294            var_b: 1,
295            weight: 2.0,
296        };
297        m.coupler_count = 1;
298        let mut assign = [0u8; MAX_QUBO_VARS];
299        let e = solve_classical(&m, &mut assign);
300        assert!(e <= 0.0);
301    }
302}