Skip to main content

omega_cognitive_kernel/reactor/
mod.rs

1#[allow(unused_imports)]
2use crate::prelude::*;
3
4use alloc::collections::BinaryHeap;
5use core::cmp::Ordering;
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
9pub struct ReactorTask {
10    pub name: String,
11    pub priority_score: i64,
12    pub seq: u64,
13    pub uncertainty: f64,
14    pub risk: f64,
15    pub preemptible: bool,
16}
17
18impl Eq for ReactorTask {}
19
20impl Ord for ReactorTask {
21    fn cmp(&self, other: &Self) -> Ordering {
22        self.priority_score
23            .cmp(&other.priority_score)
24            .then_with(|| other.seq.cmp(&self.seq))
25    }
26}
27
28impl PartialOrd for ReactorTask {
29    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
30        Some(self.cmp(other))
31    }
32}
33
34#[derive(Debug, Default)]
35pub struct PriorityReactor {
36    heap: BinaryHeap<ReactorTask>,
37    next_seq: u64,
38}
39
40impl PriorityReactor {
41    pub fn new() -> Self {
42        Self::default()
43    }
44
45    pub fn submit(
46        &mut self,
47        name: impl Into<String>,
48        base_priority: f64,
49        uncertainty: f64,
50        risk: f64,
51        preemptible: bool,
52    ) {
53        self.next_seq += 1;
54        let urgency =
55            base_priority + 40.0 * uncertainty.clamp(0.0, 1.0) + 20.0 * risk.clamp(0.0, 2.0);
56        self.heap.push(ReactorTask {
57            name: name.into(),
58            priority_score: (urgency * 1000.0) as i64,
59            seq: self.next_seq,
60            uncertainty,
61            risk,
62            preemptible,
63        });
64    }
65
66    pub fn pop_next(&mut self) -> Option<ReactorTask> {
67        self.heap.pop()
68    }
69
70    pub fn len(&self) -> usize {
71        self.heap.len()
72    }
73
74    pub fn is_empty(&self) -> bool {
75        self.heap.is_empty()
76    }
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82
83    #[test]
84    fn higher_uncertainty_task_preempts_queue() {
85        let mut reactor = PriorityReactor::new();
86        reactor.submit("routine", 10.0, 0.1, 0.0, true);
87        reactor.submit("urgent", 10.0, 0.9, 0.5, true);
88        let top = reactor.pop_next().map(|t| t.name);
89        assert_eq!(top.as_deref(), Some("urgent"));
90    }
91}