Skip to main content

qualia_core_db/tensor/
gsr.rs

1//! Ground-State Resolver (GSR) integration for quantum context resolution.
2//!
3//! This module keeps runtime state zero-heap by using fixed-capacity arrays for
4//! QUBO terms, request queues, and result caches.
5
6use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
7
8pub const MAX_QUBO_COEFFICIENTS: usize = 64;
9pub const MAX_LINEAR_TERMS: usize = 64;
10pub const MAX_PENDING_REQUESTS: usize = 16;
11pub const MAX_RESULTS_CACHE: usize = 32;
12pub const MAX_AXIOM_CACHE: usize = 32;
13
14/// QUBO problem for quantum context resolution.
15#[repr(C)]
16#[derive(Debug, Clone, Copy, PartialEq)]
17pub struct QuboProblem {
18    /// Hash-based problem identifier.
19    pub problem_id: u64,
20    /// QUBO matrix coefficients.
21    pub coefficients: [(usize, usize, f32); MAX_QUBO_COEFFICIENTS],
22    /// Number of active quadratic coefficients.
23    pub coefficient_count: usize,
24    /// Linear terms.
25    pub linear_terms: [(usize, f32); MAX_LINEAR_TERMS],
26    /// Number of active linear terms.
27    pub linear_term_count: usize,
28    /// Problem size (number of variables).
29    pub size: usize,
30    /// Context identifier for this problem.
31    pub context_id: u64,
32}
33
34impl Default for QuboProblem {
35    fn default() -> Self {
36        Self {
37            problem_id: 0,
38            coefficients: [(0, 0, 0.0); MAX_QUBO_COEFFICIENTS],
39            coefficient_count: 0,
40            linear_terms: [(0, 0.0); MAX_LINEAR_TERMS],
41            linear_term_count: 0,
42            size: 0,
43            context_id: 0,
44        }
45    }
46}
47
48impl QuboProblem {
49    /// Adds quadratic coefficient `(i,j)`; `GsrError` on bad index.
50    pub fn add_coefficient(&mut self, i: usize, j: usize, coeff: f32) -> Result<(), GsrError> {
51        if self.coefficient_count >= self.coefficients.len() {
52            return Err(GsrError::CoefficientCapacityExceeded);
53        }
54
55        self.coefficients[self.coefficient_count] = (i, j, coeff);
56        self.coefficient_count += 1;
57        Ok(())
58    }
59
60    /// Adds a linear coefficient for `i`.
61    pub fn add_linear_term(&mut self, i: usize, coeff: f32) -> Result<(), GsrError> {
62        if self.linear_term_count >= self.linear_terms.len() {
63            return Err(GsrError::LinearTermCapacityExceeded);
64        }
65
66        self.linear_terms[self.linear_term_count] = (i, coeff);
67        self.linear_term_count += 1;
68        Ok(())
69    }
70}
71
72/// GSR resolution result.
73#[repr(C)]
74#[derive(Debug, Clone, Copy, PartialEq)]
75pub struct GsrResult {
76    /// Hash-based problem identifier.
77    pub problem_id: u64,
78    /// Winning context (q value to promote to ground truth).
79    pub winning_context: f32,
80    /// Resolution confidence (0.0 to 1.0).
81    pub confidence: f32,
82    /// Resolution timestamp.
83    pub resolved_at: u64,
84    /// Computation time in milliseconds.
85    pub compute_time_ms: u64,
86    /// Whether classical exhaustion was used.
87    pub classical_fallback: bool,
88}
89
90/// GSR resolution request.
91#[repr(C)]
92#[derive(Debug, Clone, Copy, PartialEq)]
93pub struct GsrRequest {
94    /// QUBO problem to solve.
95    pub problem: QuboProblem,
96    /// Maximum computation time in milliseconds.
97    pub max_compute_time_ms: u64,
98    /// Priority level (0 = highest).
99    pub priority: u8,
100    /// Request timestamp.
101    pub requested_at: u64,
102}
103
104/// Ground-State Resolver for quantum context resolution.
105pub struct GroundStateResolver {
106    pending_requests: [Option<GsrRequest>; MAX_PENDING_REQUESTS],
107    results_cache: [Option<GsrResult>; MAX_RESULTS_CACHE],
108    axiom_cache: [Option<(u64, f32)>; MAX_AXIOM_CACHE],
109    last_cleanup: Instant,
110    qpu_available: bool,
111    classical_solver_enabled: bool,
112}
113
114impl GroundStateResolver {
115    /// Create a new GSR instance.
116    pub fn new() -> Self {
117        Self {
118            pending_requests: [None; MAX_PENDING_REQUESTS],
119            results_cache: [None; MAX_RESULTS_CACHE],
120            axiom_cache: [None; MAX_AXIOM_CACHE],
121            last_cleanup: Instant::now(),
122            qpu_available: false,
123            classical_solver_enabled: true,
124        }
125    }
126
127    /// Submit a QUBO problem for resolution.
128    pub fn submit_problem(&mut self, request: GsrRequest) -> Result<u64, GsrError> {
129        if self.get_result(request.problem.problem_id).is_some() {
130            return Ok(request.problem.problem_id);
131        }
132
133        let slot = self
134            .pending_requests
135            .iter_mut()
136            .find(|entry| entry.is_none())
137            .ok_or(GsrError::PendingQueueFull)?;
138        *slot = Some(request);
139
140        self.process_requests()?;
141        Ok(request.problem.problem_id)
142    }
143
144    /// Get result for a problem.
145    pub fn get_result(&self, problem_id: u64) -> Option<GsrResult> {
146        self.results_cache
147            .iter()
148            .flatten()
149            .find(|result| result.problem_id == problem_id)
150            .copied()
151    }
152
153    /// Process pending requests.
154    fn process_requests(&mut self) -> Result<(), GsrError> {
155        for index in 0..self.pending_requests.len() {
156            let request = match self.pending_requests[index].take() {
157                Some(request) => request,
158                None => continue,
159            };
160
161            let result = if self.qpu_available {
162                self.solve_with_qpu(&request)?
163            } else {
164                self.solve_with_classical(&request)?
165            };
166
167            self.store_result(result)?;
168        }
169
170        Ok(())
171    }
172
173    /// Solve problem using QPU semantics.
174    fn solve_with_qpu(&self, request: &GsrRequest) -> Result<GsrResult, GsrError> {
175        let start = Instant::now();
176        let mut winning_context = 0.0f32;
177        let mut saw_term = false;
178
179        for &(_, weight) in request.problem.linear_terms[..request.problem.linear_term_count].iter()
180        {
181            let magnitude = weight.abs();
182            if !saw_term || magnitude > winning_context {
183                winning_context = magnitude;
184                saw_term = true;
185            }
186        }
187
188        Ok(GsrResult {
189            problem_id: request.problem.problem_id,
190            winning_context,
191            confidence: 0.95,
192            resolved_at: current_unix_secs(),
193            compute_time_ms: start.elapsed().as_millis() as u64,
194            classical_fallback: false,
195        })
196    }
197
198    /// Solve problem using classical exhaustion (fallback).
199    fn solve_with_classical(&self, request: &GsrRequest) -> Result<GsrResult, GsrError> {
200        if !self.classical_solver_enabled {
201            return Err(GsrError::ClassicalSolverDisabled);
202        }
203
204        let start = Instant::now();
205        let winning_context = if request.problem.size <= 16 {
206            self.classical_exhaustive_search(&request.problem)?
207        } else {
208            self.classical_greedy_approximation(&request.problem)?
209        };
210
211        Ok(GsrResult {
212            problem_id: request.problem.problem_id,
213            winning_context,
214            confidence: 0.85,
215            resolved_at: current_unix_secs(),
216            compute_time_ms: start.elapsed().as_millis() as u64,
217            classical_fallback: true,
218        })
219    }
220
221    /// Classical exhaustive search for small QUBO problems.
222    fn classical_exhaustive_search(&self, problem: &QuboProblem) -> Result<f32, GsrError> {
223        if problem.size > 31 {
224            return Err(GsrError::ProblemTooLarge);
225        }
226
227        let n = problem.size;
228        let mut best_value = f32::NEG_INFINITY;
229        let mut best_context = 0.0;
230
231        for mask in 0u32..(1u32 << n) {
232            let mut value = 0.0;
233
234            for &(i, j, coeff) in &problem.coefficients[..problem.coefficient_count] {
235                let xi = ((mask >> i) & 1) as f32;
236                let xj = ((mask >> j) & 1) as f32;
237                value += coeff * xi * xj;
238            }
239
240            for &(i, linear_coeff) in &problem.linear_terms[..problem.linear_term_count] {
241                let xi = ((mask >> i) & 1) as f32;
242                value += linear_coeff * xi;
243            }
244
245            if value > best_value {
246                best_value = value;
247                best_context = mask as f32;
248            }
249        }
250
251        Ok(best_context)
252    }
253
254    /// Classical greedy approximation for larger QUBO problems.
255    fn classical_greedy_approximation(&self, problem: &QuboProblem) -> Result<f32, GsrError> {
256        let mut context = 0u32;
257
258        for &(i, linear_coeff) in &problem.linear_terms[..problem.linear_term_count] {
259            if linear_coeff > 0.0 {
260                context |= 1u32 << i;
261            }
262        }
263
264        Ok(context as f32)
265    }
266
267    /// Marks whether QPU hardware is reachable.
268    pub fn set_qpu_available(&mut self, available: bool) {
269        self.qpu_available = available;
270    }
271
272    /// `true` when QPU is reachable.
273    pub fn is_qpu_available(&self) -> bool {
274        self.qpu_available
275    }
276
277    /// Enables/disables the classical fallback solver.
278    pub fn set_classical_solver_enabled(&mut self, enabled: bool) {
279        self.classical_solver_enabled = enabled;
280    }
281
282    /// Evolve epistemic frame based on GSR result.
283    pub fn evolve_epistemic_frame(
284        &mut self,
285        problem_id: u64,
286        result: &GsrResult,
287    ) -> Result<(), GsrError> {
288        if let Some(entry) = self
289            .axiom_cache
290            .iter_mut()
291            .find(|entry| matches!(entry, Some((id, _)) if *id == problem_id))
292        {
293            *entry = Some((problem_id, result.winning_context));
294            return Ok(());
295        }
296
297        let slot = self
298            .axiom_cache
299            .iter_mut()
300            .find(|entry| entry.is_none())
301            .ok_or(GsrError::AxiomCacheFull)?;
302        *slot = Some((problem_id, result.winning_context));
303        Ok(())
304    }
305
306    /// Get cached axiom for a problem.
307    pub fn get_cached_axiom(&self, problem_id: u64) -> Option<f32> {
308        self.axiom_cache
309            .iter()
310            .flatten()
311            .find(|(id, _)| *id == problem_id)
312            .map(|(_, value)| *value)
313    }
314
315    /// Clean up old cache entries.
316    pub fn cleanup_cache(&mut self, max_age: Duration) -> Result<(), GsrError> {
317        let now = Instant::now();
318        if now.duration_since(self.last_cleanup) <= Duration::from_secs(300) {
319            return Ok(());
320        }
321
322        let current_time = current_unix_secs();
323        for entry in &mut self.results_cache {
324            if let Some(result) = entry {
325                if current_time.saturating_sub(result.resolved_at) >= max_age.as_secs() {
326                    *entry = None;
327                }
328            }
329        }
330
331        self.last_cleanup = now;
332        Ok(())
333    }
334
335    fn store_result(&mut self, result: GsrResult) -> Result<(), GsrError> {
336        if let Some(entry) = self.results_cache.iter_mut().find(
337            |entry| matches!(entry, Some(existing) if existing.problem_id == result.problem_id),
338        ) {
339            *entry = Some(result);
340            return Ok(());
341        }
342
343        let slot = self
344            .results_cache
345            .iter_mut()
346            .find(|entry| entry.is_none())
347            .ok_or(GsrError::ResultsCacheFull)?;
348        *slot = Some(result);
349        Ok(())
350    }
351}
352
353impl Default for GroundStateResolver {
354    fn default() -> Self {
355        Self::new()
356    }
357}
358
359fn current_unix_secs() -> u64 {
360    SystemTime::now()
361        .duration_since(UNIX_EPOCH)
362        .unwrap()
363        .as_secs()
364}
365
366/// GSR-related errors.
367#[derive(Debug, Clone, Copy, PartialEq, Eq)]
368pub enum GsrError {
369    CoefficientCapacityExceeded,
370    LinearTermCapacityExceeded,
371    PendingQueueFull,
372    ResultsCacheFull,
373    AxiomCacheFull,
374    ProblemTooLarge,
375    ClassicalSolverDisabled,
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381
382    #[test]
383    fn test_gsr_creation() {
384        let gsr = GroundStateResolver::new();
385        assert!(!gsr.is_qpu_available());
386    }
387
388    #[test]
389    fn test_qpu_availability() {
390        let mut gsr = GroundStateResolver::new();
391        gsr.set_qpu_available(true);
392        assert!(gsr.is_qpu_available());
393
394        gsr.set_qpu_available(false);
395        assert!(!gsr.is_qpu_available());
396    }
397
398    #[test]
399    fn test_classical_exhaustive_search() {
400        let gsr = GroundStateResolver::new();
401        let mut problem = QuboProblem {
402            problem_id: 1,
403            size: 2,
404            context_id: 0,
405            ..QuboProblem::default()
406        };
407        problem.add_linear_term(0, 1.0).unwrap();
408        problem.add_linear_term(1, -0.5).unwrap();
409
410        let result = gsr.classical_exhaustive_search(&problem).unwrap();
411        assert!(result >= 0.0);
412    }
413
414    #[test]
415    fn test_classical_greedy_approximation() {
416        let gsr = GroundStateResolver::new();
417        let mut problem = QuboProblem {
418            problem_id: 2,
419            size: 3,
420            context_id: 0,
421            ..QuboProblem::default()
422        };
423        problem.add_linear_term(0, 1.0).unwrap();
424        problem.add_linear_term(1, -0.5).unwrap();
425        problem.add_linear_term(2, 2.0).unwrap();
426
427        let result = gsr.classical_greedy_approximation(&problem).unwrap();
428        assert!(result >= 0.0);
429    }
430
431    #[test]
432    fn test_axiom_caching() {
433        let mut gsr = GroundStateResolver::new();
434        let result = GsrResult {
435            problem_id: 42,
436            winning_context: 42.0,
437            confidence: 0.9,
438            resolved_at: 1000,
439            compute_time_ms: 100,
440            classical_fallback: false,
441        };
442
443        gsr.evolve_epistemic_frame(42, &result).unwrap();
444        let cached = gsr.get_cached_axiom(42);
445
446        assert_eq!(cached, Some(42.0));
447    }
448
449    #[test]
450    fn test_submit_problem_caches_result() {
451        let mut gsr = GroundStateResolver::new();
452        let mut problem = QuboProblem {
453            problem_id: 7,
454            size: 2,
455            context_id: 9,
456            ..QuboProblem::default()
457        };
458        problem.add_linear_term(0, 1.0).unwrap();
459
460        let request = GsrRequest {
461            problem,
462            max_compute_time_ms: 100,
463            priority: 0,
464            requested_at: 1,
465        };
466
467        let problem_id = gsr.submit_problem(request).unwrap();
468        let result = gsr.get_result(problem_id);
469
470        assert_eq!(problem_id, 7);
471        assert!(result.is_some());
472    }
473}