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        std::fs::write(path, json).map_err(|e| e.to_string())
239    }
240
241    /// Converts legacy key formats to the unified `domain:ext:bucket` scheme.
242    /// Reads old keys, writes new keys, removes old keys. Idempotent.
243    fn migrate_legacy_keys(&mut self) {
244        let old_keys: Vec<String> = self
245            .bandits
246            .keys()
247            .filter(|k| !k.contains(':'))
248            .cloned()
249            .collect();
250
251        for key in old_keys {
252            let Some(bandit) = self.bandits.remove(&key) else {
253                continue;
254            };
255
256            if let Some(ext) = key.strip_suffix("_feedback") {
257                let new_key = bandit_key("feedback", ext, None);
258                self.bandits.entry(new_key).or_insert(bandit);
259            } else if let Some((ext, bucket)) = split_legacy_sized_key(&key) {
260                let thresh_key = bandit_key("threshold", ext, Some(bucket));
261                let mode_key = bandit_key("mode", ext, Some(bucket));
262                self.bandits
263                    .entry(thresh_key)
264                    .or_insert_with(|| bandit.clone());
265                self.bandits.entry(mode_key).or_insert(bandit);
266            }
267        }
268    }
269
270    pub fn format_report(&self) -> String {
271        if self.bandits.is_empty() {
272            return "No bandit data yet.".to_string();
273        }
274        let mut lines = vec!["Threshold Bandits (Thompson Sampling):".to_string()];
275        for (key, bandit) in &self.bandits {
276            lines.push(format!("  {key} (pulls: {}):", bandit.total_pulls));
277            for arm in &bandit.arms {
278                let mean = arm.mean();
279                lines.push(format!(
280                    "    {}: α={:.1} β={:.1} mean={:.0}% entropy={:.2} jaccard={:.2} budget={:.0}%",
281                    arm.name,
282                    arm.alpha,
283                    arm.beta,
284                    mean * 100.0,
285                    arm.entropy_threshold,
286                    arm.jaccard_threshold,
287                    arm.budget_ratio * 100.0
288                ));
289            }
290        }
291        lines.join("\n")
292    }
293}
294
295fn bandit_path(project_root: &str) -> std::path::PathBuf {
296    let hash = crate::core::project_hash::hash_project_root(project_root);
297    crate::core::data_dir::lean_ctx_data_dir()
298        .unwrap_or_else(|_| std::path::PathBuf::from("."))
299        .join("projects")
300        .join(hash)
301        .join("bandits.json")
302}
303
304fn rng_f64() -> f64 {
305    let mut bytes = [0u8; 8];
306    getrandom::fill(&mut bytes).unwrap_or(());
307    let val = u64::from_le_bytes(bytes);
308    (val >> 11) as f64 / ((1u64 << 53) as f64)
309}
310
311fn rng_usize(bound: usize) -> usize {
312    if bound == 0 {
313        return 0;
314    }
315    let mut bytes = [0u8; 8];
316    getrandom::fill(&mut bytes).unwrap_or(());
317    let val = u64::from_le_bytes(bytes);
318    (val as usize) % bound
319}
320
321fn beta_sample(alpha: f64, beta: f64) -> f64 {
322    let x = gamma_sample(alpha);
323    let y = gamma_sample(beta);
324    if x + y == 0.0 {
325        return 0.5;
326    }
327    x / (x + y)
328}
329
330#[allow(clippy::many_single_char_names)] // Marsaglia's algorithm uses standard math notation
331fn gamma_sample(shape: f64) -> f64 {
332    if shape < 1.0 {
333        let u = rng_f64().max(1e-10);
334        gamma_sample(shape + 1.0) * u.powf(1.0 / shape)
335    } else {
336        let d = shape - 1.0 / 3.0;
337        let c = 1.0 / (9.0_f64 * d).sqrt();
338        loop {
339            let x = standard_normal();
340            let v = (1.0 + c * x).powi(3);
341            if v <= 0.0 {
342                continue;
343            }
344            let u = rng_f64().max(1e-10);
345            if u < 1.0 - 0.0331 * x.powi(4) || u.ln() < 0.5 * x * x + d * (1.0 - v + v.ln()) {
346                return d * v;
347            }
348        }
349    }
350}
351
352fn standard_normal() -> f64 {
353    let u1: f64 = rng_f64().max(1e-10);
354    let u2: f64 = rng_f64();
355    (-2.0_f64 * u1.ln()).sqrt() * (2.0_f64 * std::f64::consts::PI * u2).cos()
356}
357
358#[cfg(test)]
359pub mod tests {
360    use super::*;
361
362    #[test]
363    fn bandit_default_has_three_arms() {
364        let b = ThresholdBandit::default();
365        assert_eq!(b.arms.len(), 3);
366        assert_eq!(b.arms[0].name, "conservative");
367        assert_eq!(b.arms[1].name, "balanced");
368        assert_eq!(b.arms[2].name, "aggressive");
369    }
370
371    #[test]
372    fn bandit_selection_works() {
373        let mut b = ThresholdBandit::default();
374        for _ in 0..10 {
375            let arm = b.choose_arm();
376            let _ = arm.name.clone();
377        }
378        assert_eq!(b.total_pulls, 10);
379    }
380
381    #[test]
382    fn choose_arm_is_deterministic_by_default() {
383        // #4 / #498: with stochastic exploration off (test default), choose_arm
384        // returns the argmax-of-mean arm every time — reproducible.
385        let mut a = ThresholdBandit::default();
386        let mut b = ThresholdBandit::default();
387        // Train both identically toward "aggressive".
388        for _ in 0..15 {
389            a.update("aggressive", true);
390            b.update("aggressive", true);
391        }
392        let pick_a: Vec<String> = (0..5).map(|_| a.choose_arm().name.clone()).collect();
393        let pick_b: Vec<String> = (0..5).map(|_| b.choose_arm().name.clone()).collect();
394        assert_eq!(pick_a, pick_b, "selection must be reproducible");
395        assert!(
396            pick_a.iter().all(|n| n == "aggressive"),
397            "argmax should pick the trained arm, got {pick_a:?}"
398        );
399    }
400
401    #[test]
402    fn best_arm_by_mean_picks_highest_posterior() {
403        let mut b = ThresholdBandit::default();
404        for _ in 0..10 {
405            b.update("balanced", true);
406        }
407        assert_eq!(b.arms[b.best_arm_idx_by_mean()].name, "balanced");
408    }
409
410    #[test]
411    fn bandit_update_shifts_distribution() {
412        let mut b = ThresholdBandit::default();
413        for _ in 0..20 {
414            b.update("aggressive", true);
415        }
416        for _ in 0..20 {
417            b.update("conservative", false);
418        }
419        let agg = b.arms.iter().find(|a| a.name == "aggressive").unwrap();
420        let con = b.arms.iter().find(|a| a.name == "conservative").unwrap();
421        assert!(agg.mean() > con.mean());
422    }
423
424    #[test]
425    fn beta_sample_in_range() {
426        for _ in 0..100 {
427            let s = beta_sample(2.0, 2.0);
428            assert!((0.0..=1.0).contains(&s), "got {s}");
429        }
430    }
431
432    #[test]
433    fn store_save_load_roundtrip() {
434        let _env = crate::core::data_dir::test_env_lock();
435        let data_dir = tempfile::tempdir().unwrap();
436        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
437
438        let project = tempfile::tempdir().unwrap();
439        let root = project.path().to_string_lossy().to_string();
440        let mut store = BanditStore::default();
441        store.get_or_create(&bandit_key("mode", "rs", Some("md")));
442        store.save(&root).unwrap();
443        let loaded = BanditStore::load(&root);
444        assert!(
445            loaded
446                .bandits
447                .contains_key(&bandit_key("mode", "rs", Some("md")))
448        );
449    }
450
451    #[test]
452    fn migrate_legacy_feedback_key() {
453        let mut store = BanditStore::default();
454        let mut b = ThresholdBandit {
455            total_pulls: 42,
456            ..ThresholdBandit::default()
457        };
458        b.update("aggressive", true);
459        store.bandits.insert("rs_feedback".to_string(), b);
460
461        store.migrate_legacy_keys();
462
463        assert!(
464            !store.bandits.contains_key("rs_feedback"),
465            "old key must be removed"
466        );
467        assert!(
468            store
469                .bandits
470                .contains_key(&bandit_key("feedback", "rs", None)),
471            "new key must exist"
472        );
473        assert_eq!(
474            store.bandits[&bandit_key("feedback", "rs", None)].total_pulls,
475            42
476        );
477    }
478
479    #[test]
480    fn migrate_legacy_sized_key_splits_into_threshold_and_mode() {
481        let mut store = BanditStore::default();
482        let b = ThresholdBandit {
483            total_pulls: 10,
484            ..ThresholdBandit::default()
485        };
486        store.bandits.insert("rs_md".to_string(), b);
487
488        store.migrate_legacy_keys();
489
490        assert!(
491            !store.bandits.contains_key("rs_md"),
492            "old key must be removed"
493        );
494        assert!(
495            store
496                .bandits
497                .contains_key(&bandit_key("threshold", "rs", Some("md"))),
498            "threshold key must exist"
499        );
500        assert!(
501            store
502                .bandits
503                .contains_key(&bandit_key("mode", "rs", Some("md"))),
504            "mode key must exist"
505        );
506    }
507
508    #[test]
509    fn migrate_is_idempotent() {
510        let mut store = BanditStore::default();
511        store.get_or_create(&bandit_key("feedback", "rs", None));
512        store.migrate_legacy_keys();
513        store.migrate_legacy_keys();
514        assert_eq!(store.bandits.len(), 1);
515    }
516}