Skip to main content

omega_cognitive_kernel/memory/
case.rs

1//! Case memory with **prioritized experience replay** (PER-style).
2//!
3//! - Priority ∝ `|error_mean|^α` (prediction error as TD-error proxy)
4//! - Full buffer: **evict lowest priority** (not FIFO)
5//! - `retrieve`: sample without replacement ∝ priority^α
6//! - Optional IS weights for bias correction when training-style consumers need them
7
8#[allow(unused_imports)]
9use crate::prelude::*;
10
11use crate::types::Trajectory;
12use alloc::collections::VecDeque;
13use serde::{Deserialize, Serialize};
14
15/// Floor so zero-error cases still get tiny sample chance.
16const PRIORITY_EPS: f64 = 1e-3;
17/// Exponent on |error| when computing priority (classic PER uses α ∈ [0, 1]).
18const PRIORITY_ALPHA: f64 = 0.6;
19/// After a case is sampled, multiply priority by this (soften re-sampling dominance).
20const PRIORITY_DECAY_ON_SAMPLE: f64 = 0.92;
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
23/// Data structure representing case.
24pub struct Case {
25    /// Stable identity within a case memory; used to update the exact sampled entry.
26    #[serde(default)]
27    pub sequence: u64,
28    /// Summary for this value.
29    pub summary: String,
30    /// Goal for this value.
31    pub goal: String,
32    /// Error mean for this value.
33    pub error_mean: f64,
34    /// Time at which the timestamp occurred.
35    pub timestamp: crate::UtcTimestamp,
36    /// Replay priority; higher = more likely to keep & sample.
37    #[serde(default = "default_priority")]
38    pub priority: f64,
39}
40
41fn default_priority() -> f64 {
42    PRIORITY_EPS
43}
44
45impl Case {
46    /// Performs priority from error for this type.
47    pub fn priority_from_error(error_mean: f64) -> f64 {
48        let e = libm::fabs(error_mean).max(PRIORITY_EPS);
49        libm::pow(e, PRIORITY_ALPHA)
50    }
51}
52
53#[derive(Debug)]
54/// Data structure representing case memory.
55pub struct CaseMemory {
56    cases: VecDeque<Case>,
57    capacity: usize,
58    /// Running sum of priorities for O(1) normalization hints (recomputed on structural change).
59    priority_sum: f64,
60    sample_counter: core::cell::Cell<u32>,
61    next_sequence: u64,
62}
63
64impl CaseMemory {
65    /// Creates a new value of this type.
66    pub fn new(capacity: usize) -> Self {
67        Self {
68            cases: VecDeque::with_capacity(capacity),
69            capacity: capacity.max(1),
70            priority_sum: 0.0,
71            sample_counter: core::cell::Cell::new(0),
72            next_sequence: 0,
73        }
74    }
75
76    /// Performs len for this type.
77    pub fn len(&self) -> usize {
78        self.cases.len()
79    }
80
81    /// Returns whether empty.
82    pub fn is_empty(&self) -> bool {
83        self.cases.is_empty()
84    }
85
86    /// Performs capacity for this type.
87    pub fn capacity(&self) -> usize {
88        self.capacity
89    }
90
91    fn recompute_sum(&mut self) {
92        self.priority_sum = self
93            .cases
94            .iter()
95            .map(|c| c.priority.max(PRIORITY_EPS))
96            .sum();
97    }
98
99    /// Index of minimum-priority case (oldest among ties).
100    fn min_priority_index(&self) -> Option<usize> {
101        if self.cases.is_empty() {
102            return None;
103        }
104        let mut best_i = 0usize;
105        let mut best_p = self.cases[0].priority;
106        for (i, c) in self.cases.iter().enumerate().skip(1) {
107            if c.priority < best_p - 1e-15 {
108                best_i = i;
109                best_p = c.priority;
110            }
111        }
112        Some(best_i)
113    }
114
115    /// Performs add for this type.
116    pub fn add(&mut self, traj: &Trajectory) {
117        let error_mean = if traj.prediction_errors.is_empty() {
118            0.0
119        } else {
120            traj.prediction_errors.iter().sum::<f64>() / traj.prediction_errors.len() as f64
121        };
122
123        let priority = Case::priority_from_error(error_mean);
124        let summary = format!(
125            "actions={} errors_mean={:.3} p={:.4}",
126            traj.actions.len(),
127            error_mean,
128            priority
129        );
130
131        let case = Case {
132            sequence: self.next_sequence,
133            summary,
134            goal: traj
135                .meta
136                .get("goal")
137                .and_then(|v| v.as_str())
138                .unwrap_or("unknown")
139                .to_string(),
140            error_mean,
141            // Identical simulation inputs should not depend on wall-clock timing.
142            timestamp: crate::UtcTimestamp::UNIX_EPOCH,
143            priority,
144        };
145        self.next_sequence = self.next_sequence.wrapping_add(1);
146
147        if self.cases.len() >= self.capacity {
148            // Evict lowest priority (PER buffer management), not FIFO.
149            if let Some(i) = self.min_priority_index() {
150                if let Some(old) = self.cases.remove(i) {
151                    self.priority_sum -= old.priority.max(PRIORITY_EPS);
152                }
153            }
154        }
155
156        self.priority_sum += case.priority.max(PRIORITY_EPS);
157        self.cases.push_back(case);
158        if self.priority_sum < 0.0 || !self.priority_sum.is_finite() {
159            self.recompute_sum();
160        }
161    }
162
163    /// Deterministic recent-first listing (debug / UI).
164    pub fn recent(&self, k: usize) -> Vec<Case> {
165        self.cases.iter().rev().take(k).cloned().collect()
166    }
167
168    /// Prioritized sample without replacement. `query` reserved for future goal filtering.
169    pub fn retrieve(&self, _query: &str, k: usize) -> Vec<Case> {
170        if self.cases.is_empty() || k == 0 {
171            return Vec::new();
172        }
173        let n = self.cases.len().min(k);
174        let mut remaining: Vec<(usize, f64)> = self
175            .cases
176            .iter()
177            .enumerate()
178            .map(|(i, c)| (i, c.priority.max(PRIORITY_EPS)))
179            .collect();
180
181        let mut out = Vec::with_capacity(n);
182        // Replay state is local to this memory, so runs are independent and
183        // reproducible even when other kernels or threads are active.
184        let counter = self.sample_counter.get();
185        self.sample_counter.set(counter.wrapping_add(1));
186        let mut seed = (self.cases.len() as u64)
187            .wrapping_mul(0x9E37_79B9)
188            .wrapping_add((counter as u64).wrapping_mul(0x85EB_CA6B))
189            .wrapping_add(
190                self.cases
191                    .back()
192                    .map(|c| c.error_mean.to_bits() ^ c.priority.to_bits())
193                    .unwrap_or(1),
194            );
195
196        for _ in 0..n {
197            let sum: f64 = remaining.iter().map(|(_, p)| *p).sum();
198            if sum <= 0.0 || remaining.is_empty() {
199                break;
200            }
201            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
202            let r = (seed >> 33) as f64 / (u32::MAX as f64) * sum;
203            let mut acc = 0.0;
204            let mut pick = 0usize;
205            for (j, (_, p)) in remaining.iter().enumerate() {
206                acc += *p;
207                if r <= acc {
208                    pick = j;
209                    break;
210                }
211                pick = j;
212            }
213            let (idx, _) = remaining.remove(pick);
214            out.push(self.cases[idx].clone());
215        }
216        out
217    }
218
219    /// Same as `retrieve`, but decays priorities of sampled cases (in-place) and
220    /// returns approximate importance-sampling weights `w_i ∝ 1 / (N * P(i))`.
221    pub fn retrieve_with_is_weights(&mut self, query: &str, k: usize) -> (Vec<Case>, Vec<f64>) {
222        let sampled = self.retrieve(query, k);
223        if sampled.is_empty() {
224            return (sampled, Vec::new());
225        }
226        let n = self.cases.len().max(1) as f64;
227        let sum = self.priority_sum.max(PRIORITY_EPS);
228        let mut weights = Vec::with_capacity(sampled.len());
229
230        for s in &sampled {
231            // Match by explicit identity: timestamps and errors can legitimately collide.
232            if let Some(slot) = self.cases.iter_mut().find(|c| c.sequence == s.sequence) {
233                let p = slot.priority.max(PRIORITY_EPS);
234                let prob = p / sum;
235                let w = 1.0 / (n * prob.max(1e-12));
236                weights.push(w);
237                self.priority_sum -= slot.priority.max(PRIORITY_EPS);
238                slot.priority = (slot.priority * PRIORITY_DECAY_ON_SAMPLE).max(PRIORITY_EPS);
239                self.priority_sum += slot.priority;
240            } else {
241                weights.push(1.0);
242            }
243        }
244
245        // Normalize IS weights so max is 1 (common practical trick).
246        if let Some(max_w) = weights.iter().cloned().fold(None, |a: Option<f64>, b| {
247            Some(a.map(|x| x.max(b)).unwrap_or(b))
248        }) {
249            if max_w > 0.0 {
250                for w in &mut weights {
251                    *w /= max_w;
252                }
253            }
254        }
255        if !self.priority_sum.is_finite() {
256            self.recompute_sum();
257        }
258        (sampled, weights)
259    }
260
261    /// Performs snapshot for this type.
262    pub fn snapshot(&self) -> (Vec<Case>, usize) {
263        (self.cases.iter().cloned().collect(), self.capacity)
264    }
265
266    /// Performs restore for this type.
267    pub fn restore(cases: Vec<Case>, capacity: usize) -> Self {
268        let mut mem = Self::new(capacity);
269        let mut next_sequence = 0u64;
270        for mut c in cases {
271            if c.sequence == 0
272                || mem
273                    .cases
274                    .iter()
275                    .any(|existing| existing.sequence == c.sequence)
276            {
277                while mem
278                    .cases
279                    .iter()
280                    .any(|existing| existing.sequence == next_sequence)
281                {
282                    next_sequence = next_sequence.wrapping_add(1);
283                }
284                c.sequence = next_sequence;
285            }
286            next_sequence = next_sequence.max(c.sequence.wrapping_add(1));
287            if c.priority <= 0.0 || !c.priority.is_finite() {
288                c.priority = Case::priority_from_error(c.error_mean);
289            }
290            if mem.cases.len() >= capacity {
291                if let Some(i) = mem.min_priority_index() {
292                    mem.cases.remove(i);
293                }
294            }
295            mem.cases.push_back(c);
296        }
297        mem.next_sequence = next_sequence;
298        mem.recompute_sum();
299        mem
300    }
301
302    /// Performs sample counter for this type.
303    pub fn sample_counter(&self) -> u32 {
304        self.sample_counter.get()
305    }
306
307    /// Performs restore with sample counter for this type.
308    pub fn restore_with_sample_counter(
309        cases: Vec<Case>,
310        capacity: usize,
311        sample_counter: u32,
312    ) -> Self {
313        let mut memory = Self::restore(cases, capacity);
314        memory.sample_counter = core::cell::Cell::new(sample_counter);
315        memory
316    }
317}
318
319impl Default for CaseMemory {
320    fn default() -> Self {
321        Self::new(256)
322    }
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328    use crate::types::Trajectory;
329    use alloc::collections::BTreeMap;
330
331    fn sample_traj(goal: &str, err: f64) -> Trajectory {
332        let mut meta = BTreeMap::new();
333        meta.insert("goal".into(), serde_json::Value::String(goal.into()));
334        Trajectory {
335            observations: vec![],
336            predictions: vec![],
337            actions: vec![],
338            outcomes: vec![],
339            prediction_errors: vec![err],
340            meta,
341        }
342    }
343
344    #[test]
345    fn adds_and_retrieves_cases() {
346        let mut mem = CaseMemory::new(10);
347        mem.add(&sample_traj("explore", 0.3));
348        mem.add(&sample_traj("exploit", 0.1));
349        let cases = mem.retrieve("any", 5);
350        assert_eq!(cases.len(), 2);
351    }
352
353    #[test]
354    fn evicts_lowest_priority_not_fifo() {
355        let mut mem = CaseMemory::new(2);
356        mem.add(&sample_traj("low", 0.05)); // low priority
357        mem.add(&sample_traj("high", 0.9)); // high priority
358        mem.add(&sample_traj("mid", 0.4)); // should kick out "low"
359        let goals: Vec<_> = mem.cases.iter().map(|c| c.goal.as_str()).collect();
360        assert!(
361            !goals.contains(&"low"),
362            "low-error case should be evicted: {goals:?}"
363        );
364        assert!(goals.contains(&"high"));
365        assert!(goals.contains(&"mid"));
366    }
367
368    #[test]
369    fn retrieve_prefers_high_error() {
370        let mut mem = CaseMemory::new(20);
371        for _ in 0..10 {
372            mem.add(&sample_traj("easy", 0.02));
373        }
374        mem.add(&sample_traj("hard", 0.95));
375        let mut hard_hits = 0;
376        for _ in 0..40 {
377            let batch = mem.retrieve("", 3);
378            if batch.iter().any(|c| c.goal == "hard") {
379                hard_hits += 1;
380            }
381        }
382        // High-error case should appear often under priority sampling.
383        assert!(hard_hits >= 4, "hard_hits={hard_hits}");
384    }
385
386    #[test]
387    fn is_weights_normalized() {
388        let mut mem = CaseMemory::new(10);
389        mem.add(&sample_traj("a", 0.2));
390        mem.add(&sample_traj("b", 0.8));
391        let (cases, ws) = mem.retrieve_with_is_weights("", 2);
392        assert_eq!(cases.len(), ws.len());
393        assert!(ws.iter().all(|w| *w > 0.0 && *w <= 1.0 + 1e-9));
394    }
395
396    #[test]
397    fn restore_backfills_priority() {
398        let c = Case {
399            sequence: 0,
400            summary: "x".into(),
401            goal: "g".into(),
402            error_mean: 0.5,
403            timestamp: crate::now_utc(),
404            priority: 0.0, // legacy
405        };
406        let mem = CaseMemory::restore(vec![c], 8);
407        assert!(mem.cases[0].priority > 0.0);
408    }
409
410    #[test]
411    fn decays_each_sampled_case_once_when_timestamps_and_errors_collide() {
412        let mut mem = CaseMemory::new(4);
413        mem.add(&sample_traj("same-a", 0.5));
414        mem.add(&sample_traj("same-b", 0.5));
415
416        assert_eq!(mem.cases[0].timestamp, mem.cases[1].timestamp);
417        assert_eq!(mem.cases[0].timestamp, crate::UtcTimestamp::UNIX_EPOCH);
418        assert_eq!(mem.cases[0].error_mean, mem.cases[1].error_mean);
419        assert_ne!(mem.cases[0].sequence, mem.cases[1].sequence);
420
421        let initial = mem.cases[0].priority;
422        let _ = mem.retrieve_with_is_weights("", 2);
423        for case in &mem.cases {
424            assert!((case.priority - initial * PRIORITY_DECAY_ON_SAMPLE).abs() < 1e-12);
425        }
426        let _ = mem.retrieve_with_is_weights("", 2);
427        for case in &mem.cases {
428            assert!((case.priority - initial * PRIORITY_DECAY_ON_SAMPLE.powi(2)).abs() < 1e-12);
429        }
430    }
431
432    #[test]
433    fn sampling_is_local_and_snapshot_restores_cursor() {
434        let mut first = CaseMemory::new(10);
435        let mut second = CaseMemory::new(10);
436        for memory in [&mut first, &mut second] {
437            for index in 0..5 {
438                memory.add(&sample_traj(
439                    &format!("case-{index}"),
440                    0.1 + index as f64 * 0.1,
441                ));
442            }
443        }
444        let first_sample: Vec<String> = first.retrieve("", 3).into_iter().map(|c| c.goal).collect();
445        let second_sample: Vec<String> =
446            second.retrieve("", 3).into_iter().map(|c| c.goal).collect();
447        assert_eq!(first_sample, second_sample);
448        let (cases, capacity) = first.snapshot();
449        let restored =
450            CaseMemory::restore_with_sample_counter(cases, capacity, first.sample_counter());
451        let expected: Vec<String> = first.retrieve("", 3).into_iter().map(|c| c.goal).collect();
452        let actual: Vec<String> = restored
453            .retrieve("", 3)
454            .into_iter()
455            .map(|c| c.goal)
456            .collect();
457        assert_eq!(expected, actual);
458    }
459}