Skip to main content

lean_ctx/core/
bandit.rs

1//! Bandit-based read-mode selection for ctx_read auto-mode.
2//! This is core OSS infrastructure for optimizing read modes,
3//! distinct from the commercial Adaptive Intensity feature
4//! (Section 8) which governs Solution Intelligence intensity levels.
5
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct BanditArm {
11    pub name: String,
12    pub alpha: f64,
13    pub beta: f64,
14    pub entropy_threshold: f64,
15    pub jaccard_threshold: f64,
16    pub budget_ratio: f64,
17}
18
19impl BanditArm {
20    fn sample(&self) -> f64 {
21        beta_sample(self.alpha, self.beta)
22    }
23
24    pub fn update_from_feedback(&mut self, outcome: &crate::core::feedback::CompressionOutcome) {
25        let efficiency = if outcome.tokens_original > 0 {
26            outcome.tokens_saved as f64 / outcome.tokens_original as f64
27        } else {
28            0.0
29        };
30        let success = efficiency > 0.3 && outcome.task_completed;
31        if success {
32            self.update_success();
33        } else {
34            self.update_failure();
35        }
36    }
37
38    pub fn update_success(&mut self) {
39        self.alpha += 1.0;
40    }
41
42    pub fn update_failure(&mut self) {
43        self.beta += 1.0;
44    }
45
46    pub fn decay(&mut self, factor: f64) {
47        self.alpha = (self.alpha * factor).max(1.0);
48        self.beta = (self.beta * factor).max(1.0);
49    }
50
51    pub fn mean(&self) -> f64 {
52        self.alpha / (self.alpha + self.beta)
53    }
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct ThresholdBandit {
58    pub arms: Vec<BanditArm>,
59    pub total_pulls: u64,
60}
61
62impl Default for ThresholdBandit {
63    fn default() -> Self {
64        Self {
65            arms: vec![
66                BanditArm {
67                    name: "conservative".to_string(),
68                    alpha: 2.0,
69                    beta: 1.0,
70                    entropy_threshold: 1.2,
71                    jaccard_threshold: 0.8,
72                    budget_ratio: 0.5,
73                },
74                BanditArm {
75                    name: "balanced".to_string(),
76                    alpha: 2.0,
77                    beta: 1.0,
78                    entropy_threshold: 0.9,
79                    jaccard_threshold: 0.7,
80                    budget_ratio: 0.35,
81                },
82                BanditArm {
83                    name: "aggressive".to_string(),
84                    alpha: 2.0,
85                    beta: 1.0,
86                    entropy_threshold: 0.6,
87                    jaccard_threshold: 0.55,
88                    budget_ratio: 0.2,
89                },
90            ],
91            total_pulls: 0,
92        }
93    }
94}
95
96impl ThresholdBandit {
97    /// Choose an arm for this decision. Deterministic by default — the arm with
98    /// the highest posterior mean (argmax) — so tool behavior is reproducible and
99    /// provider prompt caching stays valid (#498). Probabilistic exploration
100    /// (epsilon-greedy + Thompson sampling) is used only when
101    /// [`Config::is_stochastic_enabled`] is on (`LEAN_CTX_STOCHASTIC` or
102    /// auto-mode-learning). Always counts the pull and registers activity (#4).
103    ///
104    /// [`Config::is_stochastic_enabled`]: crate::core::config::Config::is_stochastic_enabled
105    pub fn choose_arm(&mut self) -> &BanditArm {
106        self.total_pulls += 1;
107        crate::core::introspect::tick("field_weights_bandit");
108        let idx = if crate::core::config::Config::load().is_stochastic_enabled() {
109            self.select_arm_stochastic()
110        } else {
111            self.best_arm_idx_by_mean()
112        };
113        &self.arms[idx]
114    }
115
116    /// Deterministic argmax of the posterior mean. Tie-break by lowest index so
117    /// the choice is stable and reproducible.
118    pub fn best_arm_idx_by_mean(&self) -> usize {
119        self.arms
120            .iter()
121            .enumerate()
122            .max_by(|(_, a), (_, b)| {
123                a.mean()
124                    .partial_cmp(&b.mean())
125                    .unwrap_or(std::cmp::Ordering::Equal)
126            })
127            .map_or(0, |(i, _)| i)
128    }
129
130    /// Probabilistic arm selection (epsilon-greedy + Thompson sampling). Uses
131    /// `getrandom`, so it is NON-deterministic and must only be reached behind the
132    /// stochastic gate. Returns the chosen arm index.
133    fn select_arm_stochastic(&self) -> usize {
134        let epsilon = (0.1 / (1.0 + self.total_pulls as f64 / 100.0)).max(0.02);
135        if rng_f64() < epsilon {
136            return rng_usize(self.arms.len());
137        }
138        let samples: Vec<f64> = self.arms.iter().map(BanditArm::sample).collect();
139        samples
140            .iter()
141            .enumerate()
142            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
143            .map_or(0, |(i, _)| i)
144    }
145
146    pub fn update(&mut self, arm_name: &str, success: bool) {
147        if let Some(arm) = self.arms.iter_mut().find(|a| a.name == arm_name) {
148            if success {
149                arm.update_success();
150            } else {
151                arm.update_failure();
152            }
153        }
154    }
155
156    pub fn decay_all(&mut self, factor: f64) {
157        for arm in &mut self.arms {
158            arm.decay(factor);
159        }
160    }
161
162    pub fn update_from_session(&mut self, outcomes: &[crate::core::feedback::CompressionOutcome]) {
163        for outcome in outcomes {
164            let efficiency = if outcome.tokens_original > 0 {
165                outcome.tokens_saved as f64 / outcome.tokens_original as f64
166            } else {
167                0.0
168            };
169            let success = efficiency > 0.3 && outcome.task_completed;
170
171            let arm_name = if outcome.entropy_threshold >= 1.0 {
172                "conservative"
173            } else if outcome.entropy_threshold >= 0.7 {
174                "balanced"
175            } else {
176                "aggressive"
177            };
178
179            self.update(arm_name, success);
180        }
181
182        if !outcomes.is_empty() {
183            self.decay_all(0.98);
184        }
185    }
186}
187
188#[derive(Debug, Clone, Serialize, Deserialize, Default)]
189pub struct BanditStore {
190    pub bandits: HashMap<String, ThresholdBandit>,
191}
192
193/// Unified key format: `{domain}:{ext}:{bucket}`.
194///
195/// Separates three previously conflated BanditStore consumers:
196/// - `feedback:{ext}` — compression quality per language (was `{ext}_feedback`)
197/// - `threshold:{ext}:{sm|md|lg|xl}` — adaptive threshold tuning (was `{ext}_{bucket}`)
198/// - `mode:{ext}:{sm|md|lg|xl}` — auto mode selection (was `{ext}_{bucket}`, now separate)
199pub fn bandit_key(domain: &str, ext: &str, bucket: Option<&str>) -> String {
200    match bucket {
201        Some(b) => format!("{domain}:{ext}:{b}"),
202        None => format!("{domain}:{ext}"),
203    }
204}
205
206fn split_legacy_sized_key(key: &str) -> Option<(&str, &str)> {
207    for suffix in &["_sm", "_md", "_lg", "_xl"] {
208        if let Some(ext) = key.strip_suffix(suffix) {
209            return Some((ext, &suffix[1..]));
210        }
211    }
212    None
213}
214
215impl BanditStore {
216    pub fn get_or_create(&mut self, key: &str) -> &mut ThresholdBandit {
217        self.bandits.entry(key.to_string()).or_default()
218    }
219
220    pub fn load(project_root: &str) -> Self {
221        let path = bandit_path(project_root);
222        if path.exists()
223            && let Ok(content) = std::fs::read_to_string(&path)
224            && let Ok(mut store) = serde_json::from_str::<BanditStore>(&content)
225        {
226            store.migrate_legacy_keys();
227            return store;
228        }
229        Self::default()
230    }
231
232    pub fn save(&self, project_root: &str) -> Result<(), String> {
233        let path = bandit_path(project_root);
234        if let Some(parent) = path.parent() {
235            std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
236        }
237        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
238        // A torn file parses as nothing and `load` falls back to an empty
239        // store, which the next save would persist over the learned state.
240        crate::core::atomic_fs::try_atomic_write(&path, json.as_bytes(), None)
241            .map_err(|e| e.to_string())
242    }
243
244    /// Converts legacy key formats to the unified `domain:ext:bucket` scheme.
245    /// Reads old keys, writes new keys, removes old keys. Idempotent.
246    fn migrate_legacy_keys(&mut self) {
247        let old_keys: Vec<String> = self
248            .bandits
249            .keys()
250            .filter(|k| !k.contains(':'))
251            .cloned()
252            .collect();
253
254        for key in old_keys {
255            let Some(bandit) = self.bandits.remove(&key) else {
256                continue;
257            };
258
259            if let Some(ext) = key.strip_suffix("_feedback") {
260                let new_key = bandit_key("feedback", ext, None);
261                self.bandits.entry(new_key).or_insert(bandit);
262            } else if let Some((ext, bucket)) = split_legacy_sized_key(&key) {
263                let thresh_key = bandit_key("threshold", ext, Some(bucket));
264                let mode_key = bandit_key("mode", ext, Some(bucket));
265                self.bandits
266                    .entry(thresh_key)
267                    .or_insert_with(|| bandit.clone());
268                self.bandits.entry(mode_key).or_insert(bandit);
269            }
270        }
271    }
272
273    pub fn format_report(&self) -> String {
274        if self.bandits.is_empty() {
275            return "No bandit data yet.".to_string();
276        }
277        let mut lines = vec!["Threshold Bandits (Thompson Sampling):".to_string()];
278        for (key, bandit) in &self.bandits {
279            lines.push(format!("  {key} (pulls: {}):", bandit.total_pulls));
280            for arm in &bandit.arms {
281                let mean = arm.mean();
282                lines.push(format!(
283                    "    {}: α={:.1} β={:.1} mean={:.0}% entropy={:.2} jaccard={:.2} budget={:.0}%",
284                    arm.name,
285                    arm.alpha,
286                    arm.beta,
287                    mean * 100.0,
288                    arm.entropy_threshold,
289                    arm.jaccard_threshold,
290                    arm.budget_ratio * 100.0
291                ));
292            }
293        }
294        lines.join("\n")
295    }
296}
297
298fn bandit_path(project_root: &str) -> std::path::PathBuf {
299    let hash = crate::core::project_hash::hash_project_root(project_root);
300    crate::core::data_dir::lean_ctx_data_dir()
301        .unwrap_or_else(|_| std::path::PathBuf::from("."))
302        .join("projects")
303        .join(hash)
304        .join("bandits.json")
305}
306
307fn rng_f64() -> f64 {
308    let mut bytes = [0u8; 8];
309    getrandom::fill(&mut bytes).unwrap_or(());
310    let val = u64::from_le_bytes(bytes);
311    (val >> 11) as f64 / ((1u64 << 53) as f64)
312}
313
314fn rng_usize(bound: usize) -> usize {
315    if bound == 0 {
316        return 0;
317    }
318    let mut bytes = [0u8; 8];
319    getrandom::fill(&mut bytes).unwrap_or(());
320    let val = u64::from_le_bytes(bytes);
321    (val as usize) % bound
322}
323
324fn beta_sample(alpha: f64, beta: f64) -> f64 {
325    let x = gamma_sample(alpha);
326    let y = gamma_sample(beta);
327    if x + y == 0.0 {
328        return 0.5;
329    }
330    x / (x + y)
331}
332
333#[allow(clippy::many_single_char_names)] // Marsaglia's algorithm uses standard math notation
334fn gamma_sample(shape: f64) -> f64 {
335    if shape < 1.0 {
336        let u = rng_f64().max(1e-10);
337        gamma_sample(shape + 1.0) * u.powf(1.0 / shape)
338    } else {
339        let d = shape - 1.0 / 3.0;
340        let c = 1.0 / (9.0_f64 * d).sqrt();
341        loop {
342            let x = standard_normal();
343            let v = (1.0 + c * x).powi(3);
344            if v <= 0.0 {
345                continue;
346            }
347            let u = rng_f64().max(1e-10);
348            if u < 1.0 - 0.0331 * x.powi(4) || u.ln() < 0.5 * x * x + d * (1.0 - v + v.ln()) {
349                return d * v;
350            }
351        }
352    }
353}
354
355fn standard_normal() -> f64 {
356    let u1: f64 = rng_f64().max(1e-10);
357    let u2: f64 = rng_f64();
358    (-2.0_f64 * u1.ln()).sqrt() * (2.0_f64 * std::f64::consts::PI * u2).cos()
359}
360
361#[cfg(test)]
362pub mod tests {
363    use super::*;
364
365    #[test]
366    fn bandit_default_has_three_arms() {
367        let b = ThresholdBandit::default();
368        assert_eq!(b.arms.len(), 3);
369        assert_eq!(b.arms[0].name, "conservative");
370        assert_eq!(b.arms[1].name, "balanced");
371        assert_eq!(b.arms[2].name, "aggressive");
372    }
373
374    #[test]
375    fn bandit_selection_works() {
376        let mut b = ThresholdBandit::default();
377        for _ in 0..10 {
378            let arm = b.choose_arm();
379            let _ = arm.name.clone();
380        }
381        assert_eq!(b.total_pulls, 10);
382    }
383
384    #[test]
385    fn choose_arm_is_deterministic_by_default() {
386        // #4 / #498: with stochastic exploration off (test default), choose_arm
387        // returns the argmax-of-mean arm every time — reproducible.
388        let mut a = ThresholdBandit::default();
389        let mut b = ThresholdBandit::default();
390        // Train both identically toward "aggressive".
391        for _ in 0..15 {
392            a.update("aggressive", true);
393            b.update("aggressive", true);
394        }
395        let pick_a: Vec<String> = (0..5).map(|_| a.choose_arm().name.clone()).collect();
396        let pick_b: Vec<String> = (0..5).map(|_| b.choose_arm().name.clone()).collect();
397        assert_eq!(pick_a, pick_b, "selection must be reproducible");
398        assert!(
399            pick_a.iter().all(|n| n == "aggressive"),
400            "argmax should pick the trained arm, got {pick_a:?}"
401        );
402    }
403
404    #[test]
405    fn best_arm_by_mean_picks_highest_posterior() {
406        let mut b = ThresholdBandit::default();
407        for _ in 0..10 {
408            b.update("balanced", true);
409        }
410        assert_eq!(b.arms[b.best_arm_idx_by_mean()].name, "balanced");
411    }
412
413    #[test]
414    fn bandit_update_shifts_distribution() {
415        let mut b = ThresholdBandit::default();
416        for _ in 0..20 {
417            b.update("aggressive", true);
418        }
419        for _ in 0..20 {
420            b.update("conservative", false);
421        }
422        let agg = b.arms.iter().find(|a| a.name == "aggressive").unwrap();
423        let con = b.arms.iter().find(|a| a.name == "conservative").unwrap();
424        assert!(agg.mean() > con.mean());
425    }
426
427    #[test]
428    fn beta_sample_in_range() {
429        for _ in 0..100 {
430            let s = beta_sample(2.0, 2.0);
431            assert!((0.0..=1.0).contains(&s), "got {s}");
432        }
433    }
434
435    #[test]
436    fn store_save_load_roundtrip() {
437        let _env = crate::core::data_dir::test_env_lock();
438        let data_dir = tempfile::tempdir().unwrap();
439        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
440
441        let project = tempfile::tempdir().unwrap();
442        let root = project.path().to_string_lossy().to_string();
443        let mut store = BanditStore::default();
444        store.get_or_create(&bandit_key("mode", "rs", Some("md")));
445        store.save(&root).unwrap();
446        let loaded = BanditStore::load(&root);
447        assert!(
448            loaded
449                .bandits
450                .contains_key(&bandit_key("mode", "rs", Some("md")))
451        );
452    }
453
454    #[test]
455    fn migrate_legacy_feedback_key() {
456        let mut store = BanditStore::default();
457        let mut b = ThresholdBandit {
458            total_pulls: 42,
459            ..ThresholdBandit::default()
460        };
461        b.update("aggressive", true);
462        store.bandits.insert("rs_feedback".to_string(), b);
463
464        store.migrate_legacy_keys();
465
466        assert!(
467            !store.bandits.contains_key("rs_feedback"),
468            "old key must be removed"
469        );
470        assert!(
471            store
472                .bandits
473                .contains_key(&bandit_key("feedback", "rs", None)),
474            "new key must exist"
475        );
476        assert_eq!(
477            store.bandits[&bandit_key("feedback", "rs", None)].total_pulls,
478            42
479        );
480    }
481
482    #[test]
483    fn migrate_legacy_sized_key_splits_into_threshold_and_mode() {
484        let mut store = BanditStore::default();
485        let b = ThresholdBandit {
486            total_pulls: 10,
487            ..ThresholdBandit::default()
488        };
489        store.bandits.insert("rs_md".to_string(), b);
490
491        store.migrate_legacy_keys();
492
493        assert!(
494            !store.bandits.contains_key("rs_md"),
495            "old key must be removed"
496        );
497        assert!(
498            store
499                .bandits
500                .contains_key(&bandit_key("threshold", "rs", Some("md"))),
501            "threshold key must exist"
502        );
503        assert!(
504            store
505                .bandits
506                .contains_key(&bandit_key("mode", "rs", Some("md"))),
507            "mode key must exist"
508        );
509    }
510
511    #[test]
512    fn migrate_is_idempotent() {
513        let mut store = BanditStore::default();
514        store.get_or_create(&bandit_key("feedback", "rs", None));
515        store.migrate_legacy_keys();
516        store.migrate_legacy_keys();
517        assert_eq!(store.bandits.len(), 1);
518    }
519}