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
163#[derive(Debug, Clone, Serialize, Deserialize, Default)]
164pub struct BanditStore {
165    pub bandits: HashMap<String, ThresholdBandit>,
166}
167
168/// Unified key format: `{domain}:{ext}:{bucket}`.
169///
170/// Separates three previously conflated BanditStore consumers:
171/// - `feedback:{ext}` — compression quality per language (was `{ext}_feedback`)
172/// - `threshold:{ext}:{sm|md|lg|xl}` — adaptive threshold tuning (was `{ext}_{bucket}`)
173/// - `mode:{ext}:{sm|md|lg|xl}` — auto mode selection (was `{ext}_{bucket}`, now separate)
174pub fn bandit_key(domain: &str, ext: &str, bucket: Option<&str>) -> String {
175    match bucket {
176        Some(b) => format!("{domain}:{ext}:{b}"),
177        None => format!("{domain}:{ext}"),
178    }
179}
180
181fn split_legacy_sized_key(key: &str) -> Option<(&str, &str)> {
182    for suffix in &["_sm", "_md", "_lg", "_xl"] {
183        if let Some(ext) = key.strip_suffix(suffix) {
184            return Some((ext, &suffix[1..]));
185        }
186    }
187    None
188}
189
190impl BanditStore {
191    pub fn get_or_create(&mut self, key: &str) -> &mut ThresholdBandit {
192        self.bandits.entry(key.to_string()).or_default()
193    }
194
195    pub fn load(project_root: &str) -> Self {
196        let path = bandit_path(project_root);
197        if path.exists()
198            && let Ok(content) = std::fs::read_to_string(&path)
199            && let Ok(mut store) = serde_json::from_str::<BanditStore>(&content)
200        {
201            store.migrate_legacy_keys();
202            return store;
203        }
204        Self::default()
205    }
206
207    pub fn save(&self, project_root: &str) -> Result<(), String> {
208        let path = bandit_path(project_root);
209        if let Some(parent) = path.parent() {
210            std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
211        }
212        let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
213        // A torn file parses as nothing and `load` falls back to an empty
214        // store, which the next save would persist over the learned state.
215        crate::core::atomic_fs::try_atomic_write(&path, json.as_bytes(), None)
216            .map_err(|e| e.to_string())
217    }
218
219    /// Converts legacy key formats to the unified `domain:ext:bucket` scheme.
220    /// Reads old keys, writes new keys, removes old keys. Idempotent.
221    fn migrate_legacy_keys(&mut self) {
222        let old_keys: Vec<String> = self
223            .bandits
224            .keys()
225            .filter(|k| !k.contains(':'))
226            .cloned()
227            .collect();
228
229        for key in old_keys {
230            let Some(bandit) = self.bandits.remove(&key) else {
231                continue;
232            };
233
234            if let Some(ext) = key.strip_suffix("_feedback") {
235                let new_key = bandit_key("feedback", ext, None);
236                self.bandits.entry(new_key).or_insert(bandit);
237            } else if let Some((ext, bucket)) = split_legacy_sized_key(&key) {
238                let thresh_key = bandit_key("threshold", ext, Some(bucket));
239                let mode_key = bandit_key("mode", ext, Some(bucket));
240                self.bandits
241                    .entry(thresh_key)
242                    .or_insert_with(|| bandit.clone());
243                self.bandits.entry(mode_key).or_insert(bandit);
244            }
245        }
246    }
247
248    pub fn format_report(&self) -> String {
249        if self.bandits.is_empty() {
250            return "No bandit data yet.".to_string();
251        }
252        let mut lines = vec!["Threshold Bandits (Thompson Sampling):".to_string()];
253        for (key, bandit) in &self.bandits {
254            lines.push(format!("  {key} (pulls: {}):", bandit.total_pulls));
255            for arm in &bandit.arms {
256                let mean = arm.mean();
257                lines.push(format!(
258                    "    {}: α={:.1} β={:.1} mean={:.0}% entropy={:.2} jaccard={:.2} budget={:.0}%",
259                    arm.name,
260                    arm.alpha,
261                    arm.beta,
262                    mean * 100.0,
263                    arm.entropy_threshold,
264                    arm.jaccard_threshold,
265                    arm.budget_ratio * 100.0
266                ));
267            }
268        }
269        lines.join("\n")
270    }
271}
272
273fn bandit_path(project_root: &str) -> std::path::PathBuf {
274    let hash = crate::core::project_hash::hash_project_root(project_root);
275    crate::core::data_dir::lean_ctx_data_dir()
276        .unwrap_or_else(|_| std::path::PathBuf::from("."))
277        .join("projects")
278        .join(hash)
279        .join("bandits.json")
280}
281
282fn rng_f64() -> f64 {
283    let mut bytes = [0u8; 8];
284    getrandom::fill(&mut bytes).unwrap_or(());
285    let val = u64::from_le_bytes(bytes);
286    (val >> 11) as f64 / ((1u64 << 53) as f64)
287}
288
289fn rng_usize(bound: usize) -> usize {
290    if bound == 0 {
291        return 0;
292    }
293    let mut bytes = [0u8; 8];
294    getrandom::fill(&mut bytes).unwrap_or(());
295    let val = u64::from_le_bytes(bytes);
296    (val as usize) % bound
297}
298
299fn beta_sample(alpha: f64, beta: f64) -> f64 {
300    let x = gamma_sample(alpha);
301    let y = gamma_sample(beta);
302    if x + y == 0.0 {
303        return 0.5;
304    }
305    x / (x + y)
306}
307
308#[allow(clippy::many_single_char_names)] // Marsaglia's algorithm uses standard math notation
309fn gamma_sample(shape: f64) -> f64 {
310    if shape < 1.0 {
311        let u = rng_f64().max(1e-10);
312        gamma_sample(shape + 1.0) * u.powf(1.0 / shape)
313    } else {
314        let d = shape - 1.0 / 3.0;
315        let c = 1.0 / (9.0_f64 * d).sqrt();
316        loop {
317            let x = standard_normal();
318            let v = (1.0 + c * x).powi(3);
319            if v <= 0.0 {
320                continue;
321            }
322            let u = rng_f64().max(1e-10);
323            if u < 1.0 - 0.0331 * x.powi(4) || u.ln() < 0.5 * x * x + d * (1.0 - v + v.ln()) {
324                return d * v;
325            }
326        }
327    }
328}
329
330fn standard_normal() -> f64 {
331    let u1: f64 = rng_f64().max(1e-10);
332    let u2: f64 = rng_f64();
333    (-2.0_f64 * u1.ln()).sqrt() * (2.0_f64 * std::f64::consts::PI * u2).cos()
334}
335
336#[cfg(test)]
337pub mod tests {
338    use super::*;
339
340    #[test]
341    fn bandit_default_has_three_arms() {
342        let b = ThresholdBandit::default();
343        assert_eq!(b.arms.len(), 3);
344        assert_eq!(b.arms[0].name, "conservative");
345        assert_eq!(b.arms[1].name, "balanced");
346        assert_eq!(b.arms[2].name, "aggressive");
347    }
348
349    #[test]
350    fn bandit_selection_works() {
351        let mut b = ThresholdBandit::default();
352        for _ in 0..10 {
353            let arm = b.choose_arm();
354            let _ = arm.name.clone();
355        }
356        assert_eq!(b.total_pulls, 10);
357    }
358
359    #[test]
360    fn choose_arm_is_deterministic_by_default() {
361        // #4 / #498: with stochastic exploration off (test default), choose_arm
362        // returns the argmax-of-mean arm every time — reproducible.
363        let mut a = ThresholdBandit::default();
364        let mut b = ThresholdBandit::default();
365        // Train both identically toward "aggressive".
366        for _ in 0..15 {
367            a.update("aggressive", true);
368            b.update("aggressive", true);
369        }
370        let pick_a: Vec<String> = (0..5).map(|_| a.choose_arm().name.clone()).collect();
371        let pick_b: Vec<String> = (0..5).map(|_| b.choose_arm().name.clone()).collect();
372        assert_eq!(pick_a, pick_b, "selection must be reproducible");
373        assert!(
374            pick_a.iter().all(|n| n == "aggressive"),
375            "argmax should pick the trained arm, got {pick_a:?}"
376        );
377    }
378
379    #[test]
380    fn best_arm_by_mean_picks_highest_posterior() {
381        let mut b = ThresholdBandit::default();
382        for _ in 0..10 {
383            b.update("balanced", true);
384        }
385        assert_eq!(b.arms[b.best_arm_idx_by_mean()].name, "balanced");
386    }
387
388    #[test]
389    fn bandit_update_shifts_distribution() {
390        let mut b = ThresholdBandit::default();
391        for _ in 0..20 {
392            b.update("aggressive", true);
393        }
394        for _ in 0..20 {
395            b.update("conservative", false);
396        }
397        let agg = b.arms.iter().find(|a| a.name == "aggressive").unwrap();
398        let con = b.arms.iter().find(|a| a.name == "conservative").unwrap();
399        assert!(agg.mean() > con.mean());
400    }
401
402    #[test]
403    fn beta_sample_in_range() {
404        for _ in 0..100 {
405            let s = beta_sample(2.0, 2.0);
406            assert!((0.0..=1.0).contains(&s), "got {s}");
407        }
408    }
409
410    #[test]
411    fn store_save_load_roundtrip() {
412        let _env = crate::core::data_dir::test_env_lock();
413        let data_dir = tempfile::tempdir().unwrap();
414        crate::test_env::set_var("LEAN_CTX_DATA_DIR", data_dir.path());
415
416        let project = tempfile::tempdir().unwrap();
417        let root = project.path().to_string_lossy().to_string();
418        let mut store = BanditStore::default();
419        store.get_or_create(&bandit_key("mode", "rs", Some("md")));
420        store.save(&root).unwrap();
421        let loaded = BanditStore::load(&root);
422        assert!(
423            loaded
424                .bandits
425                .contains_key(&bandit_key("mode", "rs", Some("md")))
426        );
427    }
428
429    #[test]
430    fn migrate_legacy_feedback_key() {
431        let mut store = BanditStore::default();
432        let mut b = ThresholdBandit {
433            total_pulls: 42,
434            ..ThresholdBandit::default()
435        };
436        b.update("aggressive", true);
437        store.bandits.insert("rs_feedback".to_string(), b);
438
439        store.migrate_legacy_keys();
440
441        assert!(
442            !store.bandits.contains_key("rs_feedback"),
443            "old key must be removed"
444        );
445        assert!(
446            store
447                .bandits
448                .contains_key(&bandit_key("feedback", "rs", None)),
449            "new key must exist"
450        );
451        assert_eq!(
452            store.bandits[&bandit_key("feedback", "rs", None)].total_pulls,
453            42
454        );
455    }
456
457    #[test]
458    fn migrate_legacy_sized_key_splits_into_threshold_and_mode() {
459        let mut store = BanditStore::default();
460        let b = ThresholdBandit {
461            total_pulls: 10,
462            ..ThresholdBandit::default()
463        };
464        store.bandits.insert("rs_md".to_string(), b);
465
466        store.migrate_legacy_keys();
467
468        assert!(
469            !store.bandits.contains_key("rs_md"),
470            "old key must be removed"
471        );
472        assert!(
473            store
474                .bandits
475                .contains_key(&bandit_key("threshold", "rs", Some("md"))),
476            "threshold key must exist"
477        );
478        assert!(
479            store
480                .bandits
481                .contains_key(&bandit_key("mode", "rs", Some("md"))),
482            "mode key must exist"
483        );
484    }
485
486    #[test]
487    fn migrate_is_idempotent() {
488        let mut store = BanditStore::default();
489        store.get_or_create(&bandit_key("feedback", "rs", None));
490        store.migrate_legacy_keys();
491        store.migrate_legacy_keys();
492        assert_eq!(store.bandits.len(), 1);
493    }
494}