omega-cognitive-kernel 0.15.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Case memory with **prioritized experience replay** (PER-style).
//!
//! - Priority ∝ `|error_mean|^α` (prediction error as TD-error proxy)
//! - Full buffer: **evict lowest priority** (not FIFO)
//! - `retrieve`: sample without replacement ∝ priority^α
//! - Optional IS weights for bias correction when training-style consumers need them

#[allow(unused_imports)]
use crate::prelude::*;

use crate::types::Trajectory;
use alloc::collections::VecDeque;
use serde::{Deserialize, Serialize};

/// Floor so zero-error cases still get tiny sample chance.
const PRIORITY_EPS: f64 = 1e-3;
/// Exponent on |error| when computing priority (classic PER uses α ∈ [0, 1]).
const PRIORITY_ALPHA: f64 = 0.6;
/// After a case is sampled, multiply priority by this (soften re-sampling dominance).
const PRIORITY_DECAY_ON_SAMPLE: f64 = 0.92;

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Data structure representing case.
pub struct Case {
    /// Stable identity within a case memory; used to update the exact sampled entry.
    #[serde(default)]
    pub sequence: u64,
    /// Summary for this value.
    pub summary: String,
    /// Goal for this value.
    pub goal: String,
    /// Error mean for this value.
    pub error_mean: f64,
    /// Time at which the timestamp occurred.
    pub timestamp: crate::UtcTimestamp,
    /// Replay priority; higher = more likely to keep & sample.
    #[serde(default = "default_priority")]
    pub priority: f64,
}

fn default_priority() -> f64 {
    PRIORITY_EPS
}

impl Case {
    /// Performs priority from error for this type.
    pub fn priority_from_error(error_mean: f64) -> f64 {
        let e = libm::fabs(error_mean).max(PRIORITY_EPS);
        libm::pow(e, PRIORITY_ALPHA)
    }
}

#[derive(Debug)]
/// Data structure representing case memory.
pub struct CaseMemory {
    cases: VecDeque<Case>,
    capacity: usize,
    /// Running sum of priorities for O(1) normalization hints (recomputed on structural change).
    priority_sum: f64,
    sample_counter: core::cell::Cell<u32>,
    next_sequence: u64,
}

impl CaseMemory {
    /// Creates a new value of this type.
    pub fn new(capacity: usize) -> Self {
        Self {
            cases: VecDeque::with_capacity(capacity),
            capacity: capacity.max(1),
            priority_sum: 0.0,
            sample_counter: core::cell::Cell::new(0),
            next_sequence: 0,
        }
    }

    /// Performs len for this type.
    pub fn len(&self) -> usize {
        self.cases.len()
    }

    /// Returns whether empty.
    pub fn is_empty(&self) -> bool {
        self.cases.is_empty()
    }

    /// Performs capacity for this type.
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    fn recompute_sum(&mut self) {
        self.priority_sum = self
            .cases
            .iter()
            .map(|c| c.priority.max(PRIORITY_EPS))
            .sum();
    }

    /// Index of minimum-priority case (oldest among ties).
    fn min_priority_index(&self) -> Option<usize> {
        if self.cases.is_empty() {
            return None;
        }
        let mut best_i = 0usize;
        let mut best_p = self.cases[0].priority;
        for (i, c) in self.cases.iter().enumerate().skip(1) {
            if c.priority < best_p - 1e-15 {
                best_i = i;
                best_p = c.priority;
            }
        }
        Some(best_i)
    }

    /// Performs add for this type.
    pub fn add(&mut self, traj: &Trajectory) {
        let error_mean = if traj.prediction_errors.is_empty() {
            0.0
        } else {
            traj.prediction_errors.iter().sum::<f64>() / traj.prediction_errors.len() as f64
        };

        let priority = Case::priority_from_error(error_mean);
        let summary = format!(
            "actions={} errors_mean={:.3} p={:.4}",
            traj.actions.len(),
            error_mean,
            priority
        );

        let case = Case {
            sequence: self.next_sequence,
            summary,
            goal: traj
                .meta
                .get("goal")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown")
                .to_string(),
            error_mean,
            // Identical simulation inputs should not depend on wall-clock timing.
            timestamp: crate::UtcTimestamp::UNIX_EPOCH,
            priority,
        };
        self.next_sequence = self.next_sequence.wrapping_add(1);

        if self.cases.len() >= self.capacity {
            // Evict lowest priority (PER buffer management), not FIFO.
            if let Some(i) = self.min_priority_index() {
                if let Some(old) = self.cases.remove(i) {
                    self.priority_sum -= old.priority.max(PRIORITY_EPS);
                }
            }
        }

        self.priority_sum += case.priority.max(PRIORITY_EPS);
        self.cases.push_back(case);
        if self.priority_sum < 0.0 || !self.priority_sum.is_finite() {
            self.recompute_sum();
        }
    }

    /// Deterministic recent-first listing (debug / UI).
    pub fn recent(&self, k: usize) -> Vec<Case> {
        self.cases.iter().rev().take(k).cloned().collect()
    }

    /// Prioritized sample without replacement. `query` reserved for future goal filtering.
    pub fn retrieve(&self, _query: &str, k: usize) -> Vec<Case> {
        if self.cases.is_empty() || k == 0 {
            return Vec::new();
        }
        let n = self.cases.len().min(k);
        let mut remaining: Vec<(usize, f64)> = self
            .cases
            .iter()
            .enumerate()
            .map(|(i, c)| (i, c.priority.max(PRIORITY_EPS)))
            .collect();

        let mut out = Vec::with_capacity(n);
        // Replay state is local to this memory, so runs are independent and
        // reproducible even when other kernels or threads are active.
        let counter = self.sample_counter.get();
        self.sample_counter.set(counter.wrapping_add(1));
        let mut seed = (self.cases.len() as u64)
            .wrapping_mul(0x9E37_79B9)
            .wrapping_add((counter as u64).wrapping_mul(0x85EB_CA6B))
            .wrapping_add(
                self.cases
                    .back()
                    .map(|c| c.error_mean.to_bits() ^ c.priority.to_bits())
                    .unwrap_or(1),
            );

        for _ in 0..n {
            let sum: f64 = remaining.iter().map(|(_, p)| *p).sum();
            if sum <= 0.0 || remaining.is_empty() {
                break;
            }
            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
            let r = (seed >> 33) as f64 / (u32::MAX as f64) * sum;
            let mut acc = 0.0;
            let mut pick = 0usize;
            for (j, (_, p)) in remaining.iter().enumerate() {
                acc += *p;
                if r <= acc {
                    pick = j;
                    break;
                }
                pick = j;
            }
            let (idx, _) = remaining.remove(pick);
            out.push(self.cases[idx].clone());
        }
        out
    }

    /// Same as `retrieve`, but decays priorities of sampled cases (in-place) and
    /// returns approximate importance-sampling weights `w_i ∝ 1 / (N * P(i))`.
    pub fn retrieve_with_is_weights(&mut self, query: &str, k: usize) -> (Vec<Case>, Vec<f64>) {
        let sampled = self.retrieve(query, k);
        if sampled.is_empty() {
            return (sampled, Vec::new());
        }
        let n = self.cases.len().max(1) as f64;
        let sum = self.priority_sum.max(PRIORITY_EPS);
        let mut weights = Vec::with_capacity(sampled.len());

        for s in &sampled {
            // Match by explicit identity: timestamps and errors can legitimately collide.
            if let Some(slot) = self.cases.iter_mut().find(|c| c.sequence == s.sequence) {
                let p = slot.priority.max(PRIORITY_EPS);
                let prob = p / sum;
                let w = 1.0 / (n * prob.max(1e-12));
                weights.push(w);
                self.priority_sum -= slot.priority.max(PRIORITY_EPS);
                slot.priority = (slot.priority * PRIORITY_DECAY_ON_SAMPLE).max(PRIORITY_EPS);
                self.priority_sum += slot.priority;
            } else {
                weights.push(1.0);
            }
        }

        // Normalize IS weights so max is 1 (common practical trick).
        if let Some(max_w) = weights.iter().cloned().fold(None, |a: Option<f64>, b| {
            Some(a.map(|x| x.max(b)).unwrap_or(b))
        }) {
            if max_w > 0.0 {
                for w in &mut weights {
                    *w /= max_w;
                }
            }
        }
        if !self.priority_sum.is_finite() {
            self.recompute_sum();
        }
        (sampled, weights)
    }

    /// Performs snapshot for this type.
    pub fn snapshot(&self) -> (Vec<Case>, usize) {
        (self.cases.iter().cloned().collect(), self.capacity)
    }

    /// Performs restore for this type.
    pub fn restore(cases: Vec<Case>, capacity: usize) -> Self {
        let mut mem = Self::new(capacity);
        let mut next_sequence = 0u64;
        for mut c in cases {
            if c.sequence == 0
                || mem
                    .cases
                    .iter()
                    .any(|existing| existing.sequence == c.sequence)
            {
                while mem
                    .cases
                    .iter()
                    .any(|existing| existing.sequence == next_sequence)
                {
                    next_sequence = next_sequence.wrapping_add(1);
                }
                c.sequence = next_sequence;
            }
            next_sequence = next_sequence.max(c.sequence.wrapping_add(1));
            if c.priority <= 0.0 || !c.priority.is_finite() {
                c.priority = Case::priority_from_error(c.error_mean);
            }
            if mem.cases.len() >= capacity {
                if let Some(i) = mem.min_priority_index() {
                    mem.cases.remove(i);
                }
            }
            mem.cases.push_back(c);
        }
        mem.next_sequence = next_sequence;
        mem.recompute_sum();
        mem
    }

    /// Performs sample counter for this type.
    pub fn sample_counter(&self) -> u32 {
        self.sample_counter.get()
    }

    /// Performs restore with sample counter for this type.
    pub fn restore_with_sample_counter(
        cases: Vec<Case>,
        capacity: usize,
        sample_counter: u32,
    ) -> Self {
        let mut memory = Self::restore(cases, capacity);
        memory.sample_counter = core::cell::Cell::new(sample_counter);
        memory
    }
}

impl Default for CaseMemory {
    fn default() -> Self {
        Self::new(256)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::Trajectory;
    use alloc::collections::BTreeMap;

    fn sample_traj(goal: &str, err: f64) -> Trajectory {
        let mut meta = BTreeMap::new();
        meta.insert("goal".into(), serde_json::Value::String(goal.into()));
        Trajectory {
            observations: vec![],
            predictions: vec![],
            actions: vec![],
            outcomes: vec![],
            prediction_errors: vec![err],
            meta,
        }
    }

    #[test]
    fn adds_and_retrieves_cases() {
        let mut mem = CaseMemory::new(10);
        mem.add(&sample_traj("explore", 0.3));
        mem.add(&sample_traj("exploit", 0.1));
        let cases = mem.retrieve("any", 5);
        assert_eq!(cases.len(), 2);
    }

    #[test]
    fn evicts_lowest_priority_not_fifo() {
        let mut mem = CaseMemory::new(2);
        mem.add(&sample_traj("low", 0.05)); // low priority
        mem.add(&sample_traj("high", 0.9)); // high priority
        mem.add(&sample_traj("mid", 0.4)); // should kick out "low"
        let goals: Vec<_> = mem.cases.iter().map(|c| c.goal.as_str()).collect();
        assert!(
            !goals.contains(&"low"),
            "low-error case should be evicted: {goals:?}"
        );
        assert!(goals.contains(&"high"));
        assert!(goals.contains(&"mid"));
    }

    #[test]
    fn retrieve_prefers_high_error() {
        let mut mem = CaseMemory::new(20);
        for _ in 0..10 {
            mem.add(&sample_traj("easy", 0.02));
        }
        mem.add(&sample_traj("hard", 0.95));
        let mut hard_hits = 0;
        for _ in 0..40 {
            let batch = mem.retrieve("", 3);
            if batch.iter().any(|c| c.goal == "hard") {
                hard_hits += 1;
            }
        }
        // High-error case should appear often under priority sampling.
        assert!(hard_hits >= 4, "hard_hits={hard_hits}");
    }

    #[test]
    fn is_weights_normalized() {
        let mut mem = CaseMemory::new(10);
        mem.add(&sample_traj("a", 0.2));
        mem.add(&sample_traj("b", 0.8));
        let (cases, ws) = mem.retrieve_with_is_weights("", 2);
        assert_eq!(cases.len(), ws.len());
        assert!(ws.iter().all(|w| *w > 0.0 && *w <= 1.0 + 1e-9));
    }

    #[test]
    fn restore_backfills_priority() {
        let c = Case {
            sequence: 0,
            summary: "x".into(),
            goal: "g".into(),
            error_mean: 0.5,
            timestamp: crate::now_utc(),
            priority: 0.0, // legacy
        };
        let mem = CaseMemory::restore(vec![c], 8);
        assert!(mem.cases[0].priority > 0.0);
    }

    #[test]
    fn decays_each_sampled_case_once_when_timestamps_and_errors_collide() {
        let mut mem = CaseMemory::new(4);
        mem.add(&sample_traj("same-a", 0.5));
        mem.add(&sample_traj("same-b", 0.5));

        assert_eq!(mem.cases[0].timestamp, mem.cases[1].timestamp);
        assert_eq!(mem.cases[0].timestamp, crate::UtcTimestamp::UNIX_EPOCH);
        assert_eq!(mem.cases[0].error_mean, mem.cases[1].error_mean);
        assert_ne!(mem.cases[0].sequence, mem.cases[1].sequence);

        let initial = mem.cases[0].priority;
        let _ = mem.retrieve_with_is_weights("", 2);
        for case in &mem.cases {
            assert!((case.priority - initial * PRIORITY_DECAY_ON_SAMPLE).abs() < 1e-12);
        }
        let _ = mem.retrieve_with_is_weights("", 2);
        for case in &mem.cases {
            assert!((case.priority - initial * PRIORITY_DECAY_ON_SAMPLE.powi(2)).abs() < 1e-12);
        }
    }

    #[test]
    fn sampling_is_local_and_snapshot_restores_cursor() {
        let mut first = CaseMemory::new(10);
        let mut second = CaseMemory::new(10);
        for memory in [&mut first, &mut second] {
            for index in 0..5 {
                memory.add(&sample_traj(
                    &format!("case-{index}"),
                    0.1 + index as f64 * 0.1,
                ));
            }
        }
        let first_sample: Vec<String> = first.retrieve("", 3).into_iter().map(|c| c.goal).collect();
        let second_sample: Vec<String> =
            second.retrieve("", 3).into_iter().map(|c| c.goal).collect();
        assert_eq!(first_sample, second_sample);
        let (cases, capacity) = first.snapshot();
        let restored =
            CaseMemory::restore_with_sample_counter(cases, capacity, first.sample_counter());
        let expected: Vec<String> = first.retrieve("", 3).into_iter().map(|c| c.goal).collect();
        let actual: Vec<String> = restored
            .retrieve("", 3)
            .into_iter()
            .map(|c| c.goal)
            .collect();
        assert_eq!(expected, actual);
    }
}