Skip to main content

lean_ctx/core/
threshold_learning.rs

1//! Online-learned per-extension compression-threshold deltas (#538, EFF-1).
2//!
3//! Closes the quality feedback loop that the static `LANGUAGE_THRESHOLDS`
4//! table and the savings-only bandit cannot: bounces (compressed read followed
5//! by a full re-read) and edit failures after compressed reads push the
6//! entropy threshold DOWN (compress less), while clean compressed reads and
7//! wasted full reads push it UP (compress more). The learned delta is additive
8//! on top of the static base table, hard-clamped so the base stays the safety
9//! anchor, and decays toward zero daily so stale lessons fade.
10//!
11//! Neuroscience analogue: dopaminergic active forgetting — eviction policy is
12//! learned from outcome signals, not hardcoded (SleepGate 2603.14517).
13
14use std::collections::HashMap;
15use std::sync::Mutex;
16use std::time::Instant;
17
18use serde::{Deserialize, Serialize};
19
20/// Learning rate per signal; signal weights below multiply this.
21const LR: f64 = 0.02;
22/// Learned delta never exceeds ±CLAMP — static table stays the anchor.
23const CLAMP: f64 = 0.15;
24/// Deltas only apply once an extension has this many observations.
25const MIN_SAMPLES: u32 = 10;
26/// Daily multiplicative decay toward 0 (drift back to the base table).
27const DAILY_DECAY: f64 = 0.98;
28/// Flush to disk at most this often.
29const FLUSH_SECS: u64 = 60;
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum QualitySignal {
33    /// Compressed read was followed by a full re-read within the bounce window.
34    Bounce,
35    /// An edit failed after the file was last read in a compressed mode.
36    EditFail,
37    /// A compressed read that (so far) was not bounced.
38    CleanCompressed,
39    /// A large full read of an extension that never bounces — compression
40    /// would almost certainly have been safe.
41    WastedFull,
42}
43
44impl QualitySignal {
45    /// Signed weight: negative lowers the entropy threshold (compress less),
46    /// positive raises it (compress more aggressively).
47    fn weight(self) -> f64 {
48        match self {
49            QualitySignal::Bounce => -3.0,
50            QualitySignal::EditFail => -6.0,
51            QualitySignal::CleanCompressed => 0.5,
52            QualitySignal::WastedFull => 2.0,
53        }
54    }
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize, Default)]
58pub(crate) struct LearnedDelta {
59    pub delta_entropy: f64,
60    pub samples: u32,
61    /// Unix epoch day of the last decay application.
62    pub last_decay_day: u64,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize, Default)]
66pub(crate) struct ThresholdLearner {
67    /// Keyed by lowercase extension without dot (e.g. "rs").
68    pub per_ext: HashMap<String, LearnedDelta>,
69    pub schema_version: u32,
70}
71
72static BUFFER: Mutex<Option<(ThresholdLearner, Instant)>> = Mutex::new(None);
73
74fn store_path() -> std::path::PathBuf {
75    crate::core::paths::cache_dir()
76        .unwrap_or_else(|_| std::path::PathBuf::from("."))
77        .join("thresholds_learned.json")
78}
79
80fn epoch_day(now_secs: u64) -> u64 {
81    now_secs / 86_400
82}
83
84fn now_secs() -> u64 {
85    std::time::SystemTime::now()
86        .duration_since(std::time::UNIX_EPOCH)
87        .map_or(0, |d| d.as_secs())
88}
89
90impl ThresholdLearner {
91    fn load_from_disk() -> Self {
92        let path = store_path();
93        if let Ok(content) = std::fs::read_to_string(&path)
94            && let Ok(learner) = serde_json::from_str::<ThresholdLearner>(&content)
95        {
96            return learner;
97        }
98        ThresholdLearner {
99            schema_version: 1,
100            ..Default::default()
101        }
102    }
103
104    fn save_to_disk(&self) {
105        let path = store_path();
106        if let Some(parent) = path.parent() {
107            let _ = std::fs::create_dir_all(parent);
108        }
109        if let Ok(json) = serde_json::to_string_pretty(self) {
110            // Readers must never see a partial file: it would load as empty.
111            let _ = crate::core::atomic_fs::try_atomic_write(&path, json.as_bytes(), None);
112        }
113    }
114
115    /// Team-merge (#550): sample-weighted average of deltas, never a blind
116    /// overwrite. `samples = max(...)` (not the sum) and weighted-mean deltas
117    /// make re-importing the same bundle a no-op (idempotent roundtrip) and
118    /// prevent double counting. Clamps stay authoritative.
119    pub(crate) fn merge_from(&mut self, other: &Self) {
120        for (ext, theirs) in &other.per_ext {
121            match self.per_ext.get_mut(ext) {
122                None => {
123                    let mut d = theirs.clone();
124                    d.delta_entropy = d.delta_entropy.clamp(-CLAMP, CLAMP);
125                    self.per_ext.insert(ext.clone(), d);
126                }
127                Some(ours) => {
128                    let total = u64::from(ours.samples) + u64::from(theirs.samples);
129                    if theirs.samples == 0 || total == 0 {
130                        continue;
131                    }
132                    let weighted = (ours.delta_entropy * f64::from(ours.samples)
133                        + theirs.delta_entropy * f64::from(theirs.samples))
134                        / total as f64;
135                    ours.delta_entropy = weighted.clamp(-CLAMP, CLAMP);
136                    ours.samples = ours.samples.max(theirs.samples);
137                    ours.last_decay_day = ours.last_decay_day.max(theirs.last_decay_day);
138                }
139            }
140        }
141    }
142
143    /// Apply one quality signal for `ext` at `now` (unix seconds).
144    pub(crate) fn record(&mut self, ext: &str, signal: QualitySignal, now: u64) {
145        let ext = normalize_ext(ext);
146        if ext.is_empty() {
147            return;
148        }
149        let day = epoch_day(now);
150        let entry = self.per_ext.entry(ext).or_default();
151        Self::apply_decay(entry, day);
152        entry.delta_entropy = (entry.delta_entropy + LR * signal.weight()).clamp(-CLAMP, CLAMP);
153        entry.samples = entry.samples.saturating_add(1);
154    }
155
156    /// Additive entropy-threshold delta for `ext`, or 0.0 before MIN_SAMPLES.
157    pub(crate) fn delta_for(&mut self, ext: &str, now: u64) -> f64 {
158        let ext = normalize_ext(ext);
159        let day = epoch_day(now);
160        match self.per_ext.get_mut(&ext) {
161            Some(entry) => {
162                Self::apply_decay(entry, day);
163                if entry.samples >= MIN_SAMPLES {
164                    entry.delta_entropy
165                } else {
166                    0.0
167                }
168            }
169            None => 0.0,
170        }
171    }
172
173    fn apply_decay(entry: &mut LearnedDelta, today: u64) {
174        if entry.last_decay_day == 0 {
175            entry.last_decay_day = today;
176            return;
177        }
178        let days = today.saturating_sub(entry.last_decay_day);
179        if days > 0 {
180            // Cap the exponent: after ~1 year of inactivity the delta is ~0 anyway.
181            let factor = DAILY_DECAY.powi(days.min(365) as i32);
182            entry.delta_entropy *= factor;
183            entry.last_decay_day = today;
184        }
185    }
186
187    /// One line per learned extension, for ctx_metrics.
188    pub(crate) fn report_lines(&self) -> Vec<String> {
189        let mut exts: Vec<_> = self.per_ext.iter().collect();
190        exts.sort_by(|a, b| a.0.cmp(b.0));
191        exts.iter()
192            .map(|(ext, d)| {
193                let active = if d.samples >= MIN_SAMPLES {
194                    "active"
195                } else {
196                    "warmup"
197                };
198                format!(
199                    "  .{ext}: delta={:+.3} (n={}, {active})",
200                    d.delta_entropy, d.samples
201                )
202            })
203            .collect()
204    }
205}
206
207fn normalize_ext(ext: &str) -> String {
208    ext.trim_start_matches('.').to_ascii_lowercase()
209}
210
211fn with_buffer<R>(f: impl FnOnce(&mut ThresholdLearner) -> R) -> R {
212    let mut guard = BUFFER
213        .lock()
214        .unwrap_or_else(std::sync::PoisonError::into_inner);
215    if guard.is_none() {
216        *guard = Some((ThresholdLearner::load_from_disk(), Instant::now()));
217    }
218    let (learner, last_flush) = guard.as_mut().expect("buffer initialized above");
219    let result = f(learner);
220    if last_flush.elapsed().as_secs() >= FLUSH_SECS {
221        learner.save_to_disk();
222        *last_flush = Instant::now();
223    }
224    result
225}
226
227/// Process-global: record a quality signal for the extension of `path`.
228pub(crate) fn record_signal(path: &str, signal: QualitySignal) {
229    let ext = std::path::Path::new(path)
230        .extension()
231        .and_then(|e| e.to_str())
232        .unwrap_or("")
233        .to_string();
234    if ext.is_empty() {
235        return;
236    }
237    with_buffer(|l| l.record(&ext, signal, now_secs()));
238}
239
240/// Process-global: learned additive delta for the extension (0.0 in warmup).
241pub(crate) fn learned_delta(ext: &str) -> f64 {
242    with_buffer(|l| l.delta_for(ext, now_secs()))
243}
244
245/// Process-global: flush the buffer to disk (call from shutdown paths).
246pub(crate) fn flush() {
247    let guard = BUFFER
248        .lock()
249        .unwrap_or_else(std::sync::PoisonError::into_inner);
250    if let Some((ref learner, _)) = *guard {
251        learner.save_to_disk();
252    }
253}
254
255/// Process-global: report lines for ctx_metrics.
256pub(crate) fn report() -> Vec<String> {
257    with_buffer(|l| l.report_lines())
258}
259
260/// Process-global: machine-readable snapshot for the dashboard (#548),
261/// sorted by extension.
262pub(crate) fn snapshot() -> Vec<(String, LearnedDelta)> {
263    with_buffer(|l| {
264        let mut v: Vec<_> = l
265            .per_ext
266            .iter()
267            .map(|(k, d)| (k.clone(), d.clone()))
268            .collect();
269        v.sort_by(|a, b| a.0.cmp(&b.0));
270        v
271    })
272}
273
274/// Process-global: clone of the full learner state for export (#550).
275pub(crate) fn export_state() -> ThresholdLearner {
276    with_buffer(|l| l.clone())
277}
278
279/// Process-global: merge a foreign learner state in and persist (#550).
280pub(crate) fn merge_state(other: &ThresholdLearner) {
281    with_buffer(|l| l.merge_from(other));
282    flush();
283}
284
285#[cfg(test)]
286mod tests {
287    use super::*;
288
289    const NOW: u64 = 1_780_000_000;
290
291    #[test]
292    fn warmup_returns_zero_delta() {
293        let mut l = ThresholdLearner::default();
294        for _ in 0..MIN_SAMPLES - 1 {
295            l.record("rs", QualitySignal::Bounce, NOW);
296        }
297        assert_eq!(l.delta_for("rs", NOW), 0.0);
298        l.record("rs", QualitySignal::Bounce, NOW);
299        assert!(l.delta_for("rs", NOW) < 0.0);
300    }
301
302    #[test]
303    fn bounce_burst_lowers_threshold() {
304        let mut l = ThresholdLearner::default();
305        for _ in 0..20 {
306            l.record("yml", QualitySignal::Bounce, NOW);
307        }
308        let d = l.delta_for("yml", NOW);
309        assert!(d < -0.05, "bounce burst should push delta down, got {d}");
310    }
311
312    #[test]
313    fn edit_fail_is_stronger_than_bounce() {
314        let mut l = ThresholdLearner::default();
315        for _ in 0..MIN_SAMPLES {
316            l.record("a", QualitySignal::Bounce, NOW);
317            l.record("b", QualitySignal::EditFail, NOW);
318        }
319        assert!(l.delta_for("b", NOW) <= l.delta_for("a", NOW));
320    }
321
322    #[test]
323    fn waste_burst_raises_threshold() {
324        let mut l = ThresholdLearner::default();
325        for _ in 0..20 {
326            l.record("json", QualitySignal::WastedFull, NOW);
327        }
328        let d = l.delta_for("json", NOW);
329        assert!(d > 0.05, "waste burst should push delta up, got {d}");
330    }
331
332    #[test]
333    fn clamp_holds_under_extreme_signals() {
334        let mut l = ThresholdLearner::default();
335        for _ in 0..500 {
336            l.record("rs", QualitySignal::EditFail, NOW);
337        }
338        assert!(l.delta_for("rs", NOW) >= -CLAMP - f64::EPSILON);
339        for _ in 0..2000 {
340            l.record("rs", QualitySignal::WastedFull, NOW);
341        }
342        assert!(l.delta_for("rs", NOW) <= CLAMP + f64::EPSILON);
343    }
344
345    #[test]
346    fn decay_drifts_back_toward_zero() {
347        let mut l = ThresholdLearner::default();
348        for _ in 0..30 {
349            l.record("rs", QualitySignal::Bounce, NOW);
350        }
351        let before = l.delta_for("rs", NOW);
352        let after = l.delta_for("rs", NOW + 30 * 86_400);
353        assert!(
354            after.abs() < before.abs(),
355            "30 days of decay should shrink |delta|: {before} -> {after}"
356        );
357    }
358
359    #[test]
360    fn clean_reads_recover_after_bounces() {
361        let mut l = ThresholdLearner::default();
362        for _ in 0..15 {
363            l.record("ts", QualitySignal::Bounce, NOW);
364        }
365        let low = l.delta_for("ts", NOW);
366        for _ in 0..200 {
367            l.record("ts", QualitySignal::CleanCompressed, NOW);
368        }
369        assert!(l.delta_for("ts", NOW) > low);
370    }
371
372    #[test]
373    fn ext_normalization() {
374        let mut l = ThresholdLearner::default();
375        for _ in 0..MIN_SAMPLES {
376            l.record(".RS", QualitySignal::Bounce, NOW);
377        }
378        assert!(l.delta_for("rs", NOW) < 0.0);
379    }
380}