Skip to main content

lean_ctx/core/
bounce_tracker.rs

1use std::collections::HashMap;
2use std::sync::{Mutex, OnceLock};
3
4const BOUNCE_WINDOW: u64 = 5;
5const BOUNCE_RATE_THRESHOLD: f64 = 0.30;
6/// Seq-tick window during which a full read is treated as *edit-forced* rather
7/// than a compression bounce. Must match the window `should_force_full` uses to
8/// escalate post-edit reads to `full`, so the read we forced is never blamed on
9/// the compression arm (GL #622).
10const EDIT_FORCE_WINDOW: u64 = 10;
11/// Outer-map retention: a path whose newest activity is older than this many seq ticks
12/// can no longer satisfy BOUNCE_WINDOW (5) or the edit-force window (10), so it is inert
13/// and safe to evict. Kept well above both windows to never change detection outcomes.
14const TRACKED_PATH_TTL_SEQ: u64 = 64;
15
16#[derive(Debug, Clone)]
17struct ReadEvent {
18    _mode: String,
19    tokens_sent: usize,
20    _original_tokens: usize,
21    seq: u64,
22    was_compressed: bool,
23    /// Scope and task the read ran under; a bounce is that task's signal.
24    origin: Option<crate::core::context_store::task_signals::Origin>,
25}
26
27#[derive(Debug, Default)]
28struct BounceStats {
29    total_reads: u64,
30    bounces: u64,
31    wasted_tokens: usize,
32}
33
34#[derive(Debug, Default)]
35pub struct BounceTracker {
36    recent_reads: HashMap<String, Vec<ReadEvent>>,
37    per_extension: HashMap<String, BounceStats>,
38    recently_edited: HashMap<String, u64>,
39    seq_counter: u64,
40    total_bounces: u64,
41    total_wasted_tokens: usize,
42    /// When true (only for the process-global tracker), detected bounces are appended to
43    /// the persistent savings ledger so a fresh `gain` process sees historical bounce.
44    /// Local trackers in unit tests leave this `false` to avoid touching the real ledger.
45    persist: bool,
46}
47
48fn is_compressed_mode(mode: &str) -> bool {
49    !matches!(mode, "full" | "diff")
50}
51
52fn extension_of(path: &str) -> String {
53    path.rsplit('.')
54        .next()
55        .map(|e| format!(".{}", e.to_ascii_lowercase()))
56        .unwrap_or_default()
57}
58
59impl BounceTracker {
60    pub fn new() -> Self {
61        Self::default()
62    }
63
64    pub fn next_seq(&mut self) -> u64 {
65        self.seq_counter += 1;
66        self.seq_counter
67    }
68
69    pub fn set_seq(&mut self, seq: u64) {
70        self.seq_counter = seq;
71    }
72
73    pub fn record_read(
74        &mut self,
75        path: &str,
76        mode: &str,
77        tokens_sent: usize,
78        original_tokens: usize,
79    ) {
80        let norm = crate::core::pathutil::normalize_tool_path(path);
81        let seq = self.seq_counter;
82        let compressed = is_compressed_mode(mode);
83
84        if !compressed {
85            self.detect_bounce(&norm, seq);
86        }
87        if self.persist {
88            // Keep the long-term majority rule honest: clean reads dilute
89            // historical bounces (#496).
90            crate::core::path_mode_memory::record_read_if_tracked(&norm);
91        }
92
93        let current = if self.persist {
94            crate::core::context_store::task_signals::current_origin()
95        } else {
96            None
97        };
98        if let Some(current) = &current {
99            // Bounces are seen only by the process that served the read: a
100            // task served by several processes is not fully observed.
101            crate::core::context_store::task_signals::observe(current);
102        }
103        let origin = current.filter(|_| compressed);
104        let events = self.recent_reads.entry(norm).or_default();
105        events.push(ReadEvent {
106            _mode: mode.to_string(),
107            tokens_sent,
108            _original_tokens: original_tokens,
109            seq,
110            was_compressed: compressed,
111            origin,
112        });
113
114        if events.len() > 10 {
115            events.drain(..events.len() - 10);
116        }
117
118        let ext = extension_of(path);
119        if !ext.is_empty() {
120            let stats = self.per_extension.entry(ext).or_default();
121            stats.total_reads += 1;
122        }
123
124        self.prune_stale_paths();
125    }
126
127    fn detect_bounce(&mut self, norm_path: &str, full_seq: u64) {
128        // A full re-read the system itself forced after an edit is not a
129        // compression failure (GL #622): `should_force_full` returns `full` for
130        // EDIT_FORCE_WINDOW ticks post-edit, so the agent had no choice. Counting
131        // it as a bounce would penalize the compression arm for the edit and
132        // inflate the per-extension bounce rate until `should_force_full` pins the
133        // whole extension to `full` — a self-reinforcing loss of compression.
134        if let Some(&edit_seq) = self.recently_edited.get(norm_path)
135            && full_seq.saturating_sub(edit_seq) <= EDIT_FORCE_WINDOW
136        {
137            return;
138        }
139
140        let Some(events) = self.recent_reads.get(norm_path) else {
141            return;
142        };
143
144        if let Some(ev) = events.iter().next_back()
145            && ev.was_compressed
146            && full_seq.saturating_sub(ev.seq) <= BOUNCE_WINDOW
147        {
148            let wasted = ev.tokens_sent;
149            let origin = ev.origin.clone();
150            self.total_bounces += 1;
151            self.total_wasted_tokens += wasted;
152
153            let ext = extension_of(norm_path);
154            if !ext.is_empty() {
155                let stats = self.per_extension.entry(ext).or_default();
156                stats.bounces += 1;
157                stats.wasted_tokens += wasted;
158            }
159
160            if self.persist {
161                if let Some(origin) = origin {
162                    // Off this tracker's lock: recording waits on a file lock.
163                    std::thread::spawn(move || {
164                        crate::core::context_store::task_signals::record(
165                            &origin,
166                            crate::core::context_store::task_signals::Signal::Bounce,
167                        );
168                    });
169                }
170                crate::core::savings_ledger::record_bounce_event(wasted);
171                // Long-term per-path memory (#496): remember which exact
172                // files keep bouncing so auto-mode learns across restarts.
173                crate::core::path_mode_memory::record_bounce(norm_path);
174                // Quality signal (#538): bounces push the learned entropy
175                // threshold down for this extension (compress less) and
176                // penalize the bandit arm that produced the read (#593).
177                crate::core::adaptive_thresholds::record_quality_signal(
178                    norm_path,
179                    crate::core::threshold_learning::QualitySignal::Bounce,
180                );
181                // Stigmergy (#540): a bounce marks this path as Stuck so
182                // other agents see friction here. Background: lock may block.
183                let scent_path = norm_path.to_string();
184                std::thread::spawn(move || {
185                    crate::core::scent_field::deposit(
186                        crate::core::scent_field::scent_agent_id(),
187                        crate::core::scent_field::ScentKind::Stuck,
188                        &scent_path,
189                        0.5,
190                    );
191                });
192            }
193        }
194    }
195
196    pub fn record_shell_file_access(&mut self, path: &str) {
197        let norm = crate::core::pathutil::normalize_tool_path(path);
198        let seq = self.seq_counter;
199        self.detect_bounce(&norm, seq);
200    }
201
202    /// Records an explicit archive/context expansion as a quality bounce.
203    ///
204    /// Unlike a full file re-read, `ctx_expand` may address a content handle
205    /// rather than a path, so it cannot always be inferred by `detect_bounce`.
206    /// Benchmark replay uses this method to keep the quality proxy on the same
207    /// tracker as ordinary compressed-then-full bounces.
208    pub fn record_expansion(&mut self, source: Option<&str>, wasted_tokens: usize) {
209        self.total_bounces = self.total_bounces.saturating_add(1);
210        self.total_wasted_tokens = self.total_wasted_tokens.saturating_add(wasted_tokens);
211
212        if let Some(path) = source {
213            let ext = extension_of(path);
214            if !ext.is_empty() {
215                let stats = self.per_extension.entry(ext).or_default();
216                stats.bounces = stats.bounces.saturating_add(1);
217                stats.wasted_tokens = stats.wasted_tokens.saturating_add(wasted_tokens);
218            }
219        }
220    }
221
222    /// The newest read of `path` this process still remembers: whether it
223    /// was compressed and the scope and task it ran under, so a later event
224    /// is charged to the read that caused it. `None`: no read is known here
225    /// (another process, or before a restart).
226    pub(crate) fn last_read(
227        &self,
228        path: &str,
229    ) -> Option<(
230        bool,
231        Option<crate::core::context_store::task_signals::Origin>,
232    )> {
233        let norm = crate::core::pathutil::normalize_tool_path(path);
234        let event = self.recent_reads.get(&norm)?.last()?;
235        Some((event.was_compressed, event.origin.clone()))
236    }
237
238    pub fn record_edit(&mut self, path: &str) {
239        let norm = crate::core::pathutil::normalize_tool_path(path);
240        self.recently_edited.insert(norm, self.seq_counter);
241        self.prune_stale_paths();
242    }
243
244    /// Evict outer-map entries whose newest seq is older than the detection windows —
245    /// they can no longer affect bounce detection or `should_force_full`. Bounds the
246    /// `recent_reads` / `recently_edited` maps on a long-lived process.
247    fn prune_stale_paths(&mut self) {
248        let seq = self.seq_counter;
249        self.recent_reads.retain(|_, events| {
250            events
251                .last()
252                .is_some_and(|e| seq.saturating_sub(e.seq) <= TRACKED_PATH_TTL_SEQ)
253        });
254        self.recently_edited
255            .retain(|_, &mut edit_seq| seq.saturating_sub(edit_seq) <= TRACKED_PATH_TTL_SEQ);
256    }
257
258    pub fn should_force_full(&self, path: &str) -> bool {
259        let norm = crate::core::pathutil::normalize_tool_path(path);
260
261        if let Some(&edit_seq) = self.recently_edited.get(&norm)
262            && self.seq_counter.saturating_sub(edit_seq) <= EDIT_FORCE_WINDOW
263        {
264            return true;
265        }
266
267        let ext = extension_of(path);
268        if !ext.is_empty()
269            && let Some(stats) = self.per_extension.get(&ext)
270            && stats.total_reads >= 3
271        {
272            let rate = stats.bounces as f64 / stats.total_reads as f64;
273            if rate >= BOUNCE_RATE_THRESHOLD {
274                return true;
275            }
276        }
277
278        false
279    }
280
281    pub fn bounce_rate_for_extension(&self, path: &str) -> Option<f64> {
282        let ext = extension_of(path);
283        self.per_extension.get(&ext).and_then(|s| {
284            if s.total_reads >= 3 {
285                Some(s.bounces as f64 / s.total_reads as f64)
286            } else {
287                None
288            }
289        })
290    }
291
292    pub fn total_bounces(&self) -> u64 {
293        self.total_bounces
294    }
295
296    pub fn total_wasted_tokens(&self) -> usize {
297        self.total_wasted_tokens
298    }
299
300    pub fn adjusted_savings(&self, raw_savings: usize) -> isize {
301        raw_savings as isize - self.total_wasted_tokens as isize
302    }
303
304    pub fn per_extension_json(&self) -> Vec<serde_json::Value> {
305        let mut exts: Vec<_> = self
306            .per_extension
307            .iter()
308            .filter(|(_, s)| s.total_reads > 0)
309            .collect();
310        exts.sort_by_key(|a| std::cmp::Reverse(a.1.bounces));
311        exts.iter()
312            .take(10)
313            .map(|(ext, stats)| {
314                let rate = if stats.total_reads > 0 {
315                    stats.bounces as f64 / stats.total_reads as f64
316                } else {
317                    0.0
318                };
319                serde_json::json!({
320                    "ext": ext,
321                    "reads": stats.total_reads,
322                    "bounces": stats.bounces,
323                    "wasted_tokens": stats.wasted_tokens,
324                    "rate": (rate * 1000.0).round() / 1000.0,
325                })
326            })
327            .collect()
328    }
329
330    pub fn format_summary(&self) -> String {
331        if self.total_bounces == 0 {
332            return "Bounces: 0".to_string();
333        }
334        let mut lines = vec![format!(
335            "Bounces: {} ({} wasted tokens)",
336            self.total_bounces, self.total_wasted_tokens
337        )];
338        let mut exts: Vec<_> = self
339            .per_extension
340            .iter()
341            .filter(|(_, s)| s.bounces > 0)
342            .collect();
343        exts.sort_by_key(|a| std::cmp::Reverse(a.1.bounces));
344        for (ext, stats) in exts.iter().take(5) {
345            let rate = if stats.total_reads > 0 {
346                stats.bounces as f64 / stats.total_reads as f64 * 100.0
347            } else {
348                0.0
349            };
350            lines.push(format!(
351                "  {ext}: {}/{} reads bounced ({rate:.0}%), {} tok wasted",
352                stats.bounces, stats.total_reads, stats.wasted_tokens,
353            ));
354        }
355        lines.join("\n")
356    }
357}
358
359static GLOBAL_TRACKER: OnceLock<Mutex<BounceTracker>> = OnceLock::new();
360
361pub fn global() -> &'static Mutex<BounceTracker> {
362    GLOBAL_TRACKER.get_or_init(|| {
363        // Seed from the persistent ledger so every process (including a fresh `gain`)
364        // accounts for historical bounce, then mark this tracker as the persisting one.
365        let summary = crate::core::savings_ledger::summary();
366        let mut bt = BounceTracker::new();
367        bt.total_wasted_tokens = summary.bounce_tokens as usize;
368        bt.total_bounces = summary.bounce_events as u64;
369        bt.persist = true;
370        Mutex::new(bt)
371    })
372}
373
374#[cfg(test)]
375pub mod tests {
376    use super::*;
377
378    #[test]
379    fn no_bounce_when_first_read_is_full() {
380        let mut bt = BounceTracker::new();
381        bt.seq_counter = 1;
382        bt.record_read("src/main.rs", "full", 500, 500);
383        assert_eq!(bt.total_bounces(), 0);
384        assert_eq!(bt.total_wasted_tokens(), 0);
385    }
386
387    #[test]
388    fn bounce_detected_on_compressed_then_full() {
389        let mut bt = BounceTracker::new();
390        bt.seq_counter = 1;
391        bt.record_read("src/main.rs", "map", 50, 500);
392        bt.seq_counter = 2;
393        bt.record_read("src/main.rs", "full", 500, 500);
394        assert_eq!(bt.total_bounces(), 1);
395        assert_eq!(bt.total_wasted_tokens(), 50);
396    }
397
398    #[test]
399    fn no_bounce_outside_window() {
400        let mut bt = BounceTracker::new();
401        bt.seq_counter = 1;
402        bt.record_read("src/main.rs", "map", 50, 500);
403        bt.seq_counter = 10;
404        bt.record_read("src/main.rs", "full", 500, 500);
405        assert_eq!(bt.total_bounces(), 0);
406    }
407
408    #[test]
409    fn shell_access_triggers_bounce() {
410        let mut bt = BounceTracker::new();
411        bt.seq_counter = 1;
412        bt.record_read("config.yml", "signatures", 30, 400);
413        bt.seq_counter = 3;
414        bt.record_shell_file_access("config.yml");
415        assert_eq!(bt.total_bounces(), 1);
416        assert_eq!(bt.total_wasted_tokens(), 30);
417    }
418
419    #[test]
420    fn explicit_expansion_tracks_quality_and_waste() {
421        let mut bt = BounceTracker::new();
422        bt.record_expansion(Some("src/main.rs"), 125);
423        assert_eq!(bt.total_bounces(), 1);
424        assert_eq!(bt.total_wasted_tokens(), 125);
425    }
426
427    #[test]
428    fn edit_forced_full_read_is_not_a_bounce() {
429        // GL #622: a compressed overview read, then an edit, then the `full`
430        // re-read that `should_force_full` mandates must NOT register as a bounce
431        // — the edit forced it, the compression did not fail.
432        let mut bt = BounceTracker::new();
433        bt.seq_counter = 1;
434        bt.record_read("src/lib.rs", "map", 40, 500);
435        bt.seq_counter = 2;
436        bt.record_edit("src/lib.rs");
437        bt.seq_counter = 4;
438        bt.record_read("src/lib.rs", "full", 500, 500);
439        assert_eq!(
440            bt.total_bounces(),
441            0,
442            "edit-forced full read must not count as a compression bounce"
443        );
444    }
445
446    #[test]
447    fn full_read_without_edit_still_bounces() {
448        // The guard is scoped to edit-forced reads only: an unprompted full
449        // re-read after a compressed read is still a real bounce.
450        let mut bt = BounceTracker::new();
451        bt.seq_counter = 1;
452        bt.record_read("src/lib.rs", "map", 40, 500);
453        bt.seq_counter = 3;
454        bt.record_read("src/lib.rs", "full", 500, 500);
455        assert_eq!(bt.total_bounces(), 1);
456    }
457
458    #[test]
459    fn should_force_full_after_edit() {
460        let mut bt = BounceTracker::new();
461        bt.seq_counter = 5;
462        bt.record_edit("src/lib.rs");
463        bt.seq_counter = 8;
464        assert!(bt.should_force_full("src/lib.rs"));
465        bt.seq_counter = 20;
466        assert!(!bt.should_force_full("src/lib.rs"));
467    }
468
469    #[test]
470    fn should_force_full_by_extension_bounce_rate() {
471        let mut bt = BounceTracker::new();
472        for i in 1..=6 {
473            bt.seq_counter = i * 2 - 1;
474            bt.record_read(&format!("f{i}.yml"), "map", 30, 400);
475            bt.seq_counter = i * 2;
476            bt.record_read(&format!("f{i}.yml"), "full", 400, 400);
477        }
478        assert!(bt.should_force_full("new.yml"));
479    }
480
481    #[test]
482    fn adjusted_savings_subtracts_waste() {
483        let mut bt = BounceTracker::new();
484        bt.seq_counter = 1;
485        bt.record_read("a.rs", "map", 50, 500);
486        bt.seq_counter = 2;
487        bt.record_read("a.rs", "full", 500, 500);
488        assert_eq!(bt.adjusted_savings(1000), 950);
489    }
490
491    #[test]
492    fn bounce_rate_for_extension_below_minimum() {
493        let bt = BounceTracker::new();
494        assert!(bt.bounce_rate_for_extension("test.rs").is_none());
495    }
496
497    #[test]
498    fn format_summary_empty() {
499        let bt = BounceTracker::new();
500        assert_eq!(bt.format_summary(), "Bounces: 0");
501    }
502}