omega_cognitive_kernel/l2/
meta_cache.rs1#[allow(unused_imports)]
2use crate::prelude::*;
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
6pub struct ContextFingerprint {
8 pub error_mean: f64,
10 pub error_variance: f64,
12 pub rollback_rate: f64,
14 pub action_entropy: f64,
16}
17impl ContextFingerprint {
18 pub fn from_window(errors: &[f64], rollbacks: u32, total: u32, action_entropy: f64) -> Self {
21 let n = errors.len().max(1) as f64;
22 let mean = errors.iter().sum::<f64>() / n;
23 let variance = errors.iter().map(|e| (e - mean) * (e - mean)).sum::<f64>() / n;
24 Self {
25 error_mean: mean,
26 error_variance: variance,
27 rollback_rate: rollbacks as f64 / total.max(1) as f64,
28 action_entropy,
29 }
30 }
31 pub fn similarity(&self, other: &Self) -> f64 {
33 let distance = libm::fabs(self.error_mean - other.error_mean)
34 + libm::sqrt(libm::fabs(self.error_variance - other.error_variance))
35 + libm::fabs(self.rollback_rate - other.rollback_rate)
36 + 0.5 * libm::fabs(self.action_entropy - other.action_entropy);
37 (1.0 - distance / 2.5).clamp(0.0, 1.0)
38 }
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize)]
42pub struct MetaCacheEntry {
44 pub fingerprint: ContextFingerprint,
46 pub expert_weights: [f64; 4],
48 pub alpha: f64,
50 pub credit: f64,
52 pub last_used: u64,
54}
55#[derive(Debug, Clone, Serialize, Deserialize)]
56#[serde(default)]
57pub struct MetaCache {
59 pub entries: Vec<MetaCacheEntry>,
61 pub capacity: usize,
63 pub hit_threshold: f64,
65 pub clock: u64,
67 pub last_hit: bool,
69}
70impl Default for MetaCache {
71 fn default() -> Self {
72 Self {
73 entries: Vec::new(),
74 capacity: 16,
75 hit_threshold: 0.78,
76 clock: 0,
77 last_hit: false,
78 }
79 }
80}
81impl MetaCache {
82 pub fn store(
84 &mut self,
85 fingerprint: ContextFingerprint,
86 weights: [f64; 4],
87 alpha: f64,
88 credit: f64,
89 ) {
90 self.clock = self.clock.saturating_add(1);
91 if let Some(entry) = self
92 .entries
93 .iter_mut()
94 .find(|e| e.fingerprint.similarity(&fingerprint) > 0.96)
95 {
96 entry.expert_weights = weights;
97 entry.alpha = alpha;
98 entry.credit = credit.max(entry.credit);
99 entry.last_used = self.clock;
100 } else {
101 self.entries.push(MetaCacheEntry {
102 fingerprint,
103 expert_weights: weights,
104 alpha,
105 credit,
106 last_used: self.clock,
107 });
108 }
109 if self.entries.len() > self.capacity.max(1) {
110 let index = self
111 .entries
112 .iter()
113 .enumerate()
114 .min_by(|(_, a), (_, b)| {
115 (a.credit + a.last_used as f64 * 1.0e-6)
116 .partial_cmp(&(b.credit + b.last_used as f64 * 1.0e-6))
117 .unwrap_or(core::cmp::Ordering::Equal)
118 })
119 .map(|(i, _)| i)
120 .unwrap_or(0);
121 self.entries.remove(index);
122 }
123 }
124 pub fn lookup(&mut self, fingerprint: &ContextFingerprint) -> Option<(usize, [f64; 4], f64)> {
126 self.last_hit = false;
127 let best = self
128 .entries
129 .iter()
130 .enumerate()
131 .filter_map(|(i, entry)| {
132 let similarity = entry.fingerprint.similarity(fingerprint);
133 (similarity >= self.hit_threshold).then_some((i, similarity))
134 })
135 .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(core::cmp::Ordering::Equal));
136 if let Some((index, _)) = best {
137 self.clock = self.clock.saturating_add(1);
138 self.entries[index].last_used = self.clock;
139 self.entries[index].credit += 1.0;
140 self.last_hit = true;
141 return Some((
142 index,
143 self.entries[index].expert_weights,
144 self.entries[index].alpha,
145 ));
146 }
147 None
148 }
149}
150
151#[cfg(test)]
152mod tests {
153 use super::*;
154
155 #[test]
156 fn repeated_context_hits_and_cache_is_bounded() {
157 let mut cache = MetaCache {
158 capacity: 2,
159 ..MetaCache::default()
160 };
161 let fingerprint = ContextFingerprint {
162 error_mean: 0.4,
163 error_variance: 0.02,
164 rollback_rate: 0.1,
165 action_entropy: 0.7,
166 };
167 cache.store(fingerprint, [0.1, 0.8, 0.05, 0.05], 0.24, 1.0);
168 let (_, weights, alpha) = cache.lookup(&fingerprint).expect("warm start");
169 assert_eq!(weights[1], 0.8);
170 assert_eq!(alpha, 0.24);
171 assert!(cache.last_hit);
172 for error_mean in [0.6, 0.8, 0.95] {
173 cache.store(
174 ContextFingerprint {
175 error_mean,
176 ..fingerprint
177 },
178 [0.25; 4],
179 0.1,
180 0.0,
181 );
182 }
183 assert!(cache.entries.len() <= 2);
184 let encoded = serde_json::to_string(&cache).unwrap();
185 let decoded: MetaCache = serde_json::from_str(&encoded).unwrap();
186 assert_eq!(decoded.entries.len(), cache.entries.len());
187 }
188}