Skip to main content

lean_ctx/tools/registered/
ctx_read.rs

1use std::collections::HashMap;
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::sync::{Arc, Mutex};
4
5use rmcp::model::Tool;
6use rmcp::ErrorData;
7use serde_json::{json, Map, Value};
8
9use crate::server::tool_trait::{
10    get_bool, get_int, get_str, require_resolved_path, McpTool, ToolContext, ToolOutput,
11};
12use crate::tool_defs::tool_def;
13
14/// Per-file lock that serializes concurrent reads of the same path.
15///
16/// When multiple subagents read sequentially through a shared set of files,
17/// they tend to hit the same path at the same time. Without per-file locking
18/// they all contend on the global cache write lock while doing redundant I/O.
19/// This lock ensures only one thread reads a given file from disk; the others
20/// wait cheaply on the per-file mutex, then hit the warm cache.
21fn per_file_lock(path: &str) -> Arc<Mutex<()>> {
22    static FILE_LOCKS: std::sync::OnceLock<Mutex<HashMap<String, Arc<Mutex<()>>>>> =
23        std::sync::OnceLock::new();
24    let map = FILE_LOCKS.get_or_init(|| Mutex::new(HashMap::new()));
25    let mut map = map.lock().unwrap();
26
27    const MAX_ENTRIES: usize = 500;
28    if map.len() > MAX_ENTRIES {
29        map.retain(|_, v| Arc::strong_count(v) > 1);
30    }
31
32    map.entry(path.to_string())
33        .or_insert_with(|| Arc::new(Mutex::new(())))
34        .clone()
35}
36
37pub struct CtxReadTool;
38
39impl McpTool for CtxReadTool {
40    fn name(&self) -> &'static str {
41        "ctx_read"
42    }
43
44    fn tool_def(&self) -> Tool {
45        tool_def(
46            "ctx_read",
47            "Read file (cached, compressed). Cached re-reads can be ~13 tok when unchanged. Auto-selects optimal mode. \
48Modes: full|map|signatures|diff|aggressive|entropy|task|reference|lines:N-M. fresh=true forces a disk re-read.",
49            json!({
50                "type": "object",
51                "properties": {
52                    "path": { "type": "string", "description": "Absolute file path to read" },
53                    "mode": {
54                        "type": "string",
55                        "description": "Compression mode (default: full). Use 'map' for context-only files. For line ranges: 'lines:N-M' (e.g. 'lines:400-500')."
56                    },
57                    "start_line": {
58                        "type": "integer",
59                        "description": "Read from this line number to end of file. Implies fresh=true (disk re-read) to avoid stale snippets."
60                    },
61                    "fresh": {
62                        "type": "boolean",
63                        "description": "Bypass cache and force a full re-read. Use when running as a subagent that may not have the parent's context."
64                    }
65                },
66                "required": ["path"]
67            }),
68        )
69    }
70
71    fn handle(
72        &self,
73        args: &Map<String, Value>,
74        ctx: &ToolContext,
75    ) -> Result<ToolOutput, ErrorData> {
76        let path = require_resolved_path(ctx, args, "path")?;
77
78        self.handle_inner(args, ctx, &path)
79    }
80}
81
82impl CtxReadTool {
83    #[allow(clippy::unused_self)]
84    fn handle_inner(
85        &self,
86        args: &Map<String, Value>,
87        ctx: &ToolContext,
88        path: &str,
89    ) -> Result<ToolOutput, ErrorData> {
90        let session_lock = ctx
91            .session
92            .as_ref()
93            .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
94        let cache_lock = ctx
95            .cache
96            .as_ref()
97            .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
98
99        let current_task = {
100            let session = session_lock.blocking_read();
101            session.task.as_ref().map(|t| t.description.clone())
102        };
103        let task_ref = current_task.as_deref();
104
105        let profile = crate::core::profiles::active_profile();
106        let mut mode = if let Some(m) = get_str(args, "mode") {
107            m
108        } else if profile.read.default_mode_effective() == "auto" {
109            // Non-blocking: if the cache write-lock is held by a timed-out zombie
110            // thread, blocking_read() would hang with NO timeout protection.
111            if let Ok(cache) = cache_lock.try_read() {
112                crate::tools::ctx_smart_read::select_mode_with_task(&cache, path, task_ref)
113            } else {
114                tracing::debug!(
115                    "cache lock contested during auto-mode selection for {path}; \
116                     falling back to full"
117                );
118                "full".to_string()
119            }
120        } else {
121            profile.read.default_mode_effective().to_string()
122        };
123
124        let mut fresh = get_bool(args, "fresh").unwrap_or(false);
125        let start_line = get_int(args, "start_line");
126        if let Some(sl) = start_line {
127            let sl = sl.max(1_i64);
128            mode = format!("lines:{sl}-999999");
129            fresh = true;
130        }
131
132        let pressure_action = ctx.pressure_snapshot.as_ref().map(|p| &p.recommendation);
133        let resolved_agent_id = ctx
134            .agent_id
135            .as_ref()
136            .and_then(|a| a.blocking_read().clone());
137        let gate_result = crate::server::context_gate::pre_dispatch_read_for_agent(
138            path,
139            &mode,
140            task_ref,
141            Some(&ctx.project_root),
142            pressure_action,
143            resolved_agent_id.as_deref(),
144        );
145        if gate_result.budget_blocked {
146            let msg = gate_result
147                .budget_warning
148                .unwrap_or_else(|| "Agent token budget exceeded".to_string());
149            return Err(ErrorData::invalid_params(msg, None));
150        }
151        let budget_warning = gate_result.budget_warning.clone();
152        if let Some(overridden) = gate_result.overridden_mode {
153            mode = overridden;
154        }
155
156        let mode = if crate::tools::ctx_read::is_instruction_file(path) {
157            "full".to_string()
158        } else {
159            auto_degrade_read_mode(&mode)
160        };
161
162        if mode.starts_with("lines:") {
163            fresh = true;
164        }
165
166        if crate::core::binary_detect::is_binary_file(path) {
167            let msg = crate::core::binary_detect::binary_file_message(path);
168            return Err(ErrorData::invalid_params(msg, None));
169        }
170        {
171            let cap = crate::core::limits::max_read_bytes() as u64;
172            if let Ok(meta) = std::fs::metadata(path) {
173                if meta.len() > cap {
174                    let msg = format!(
175                        "File too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
176                         Use mode=\"lines:1-100\" for partial reads or increase the limit.",
177                        meta.len(),
178                        cap
179                    );
180                    return Err(ErrorData::invalid_params(msg, None));
181                }
182            }
183        }
184
185        // Acquire cache write lock with timeout guard to prevent infinite hangs.
186        // All lock acquisitions (per-file mutex, cache RwLock) use bounded waits
187        // so a zombie thread from a previous timed-out call cannot block us forever.
188        let read_timeout = std::time::Duration::from_secs(30);
189        let cancelled = Arc::new(AtomicBool::new(false));
190        let (output, resolved_mode, original, is_cache_hit, file_ref, cache_stats) = {
191            let cache_lock = cache_lock.clone();
192            let mode = mode.clone();
193            let crp_mode = ctx.crp_mode;
194            let task_owned = current_task.clone();
195            let path_owned = path.to_string();
196            let cancel_flag = cancelled.clone();
197            let (tx, rx) = std::sync::mpsc::sync_channel(1);
198            std::thread::spawn(move || {
199                let file_lock = per_file_lock(&path_owned);
200
201                // Bounded per-file lock: if a zombie thread still holds it, don't
202                // wait forever. 25s keeps us inside the 30s recv_timeout.
203                let _file_guard = {
204                    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(25);
205                    loop {
206                        if cancel_flag.load(Ordering::Relaxed) {
207                            return;
208                        }
209                        if let Ok(guard) = file_lock.try_lock() {
210                            break guard;
211                        }
212                        if std::time::Instant::now() >= deadline {
213                            tracing::error!(
214                                "ctx_read: per-file lock timeout after 25s for {path_owned}"
215                            );
216                            return;
217                        }
218                        std::thread::sleep(std::time::Duration::from_millis(50));
219                    }
220                };
221
222                if cancel_flag.load(Ordering::Relaxed) {
223                    return;
224                }
225
226                // Bounded cache write-lock: avoids indefinite block when a zombie
227                // thread from a previous timed-out call still holds the lock.
228                let mut cache = {
229                    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(25);
230                    loop {
231                        if cancel_flag.load(Ordering::Relaxed) {
232                            return;
233                        }
234                        if let Ok(guard) = cache_lock.try_write() {
235                            break guard;
236                        }
237                        if std::time::Instant::now() >= deadline {
238                            tracing::error!(
239                                "ctx_read: cache write-lock timeout after 25s for {path_owned}"
240                            );
241                            return;
242                        }
243                        std::thread::sleep(std::time::Duration::from_millis(50));
244                    }
245                };
246
247                let task_ref = task_owned.as_deref();
248                let read_output = if fresh {
249                    crate::tools::ctx_read::handle_fresh_with_task_resolved(
250                        &mut cache,
251                        &path_owned,
252                        &mode,
253                        crp_mode,
254                        task_ref,
255                    )
256                } else {
257                    crate::tools::ctx_read::handle_with_task_resolved(
258                        &mut cache,
259                        &path_owned,
260                        &mode,
261                        crp_mode,
262                        task_ref,
263                    )
264                };
265                let content = read_output.content;
266                let rmode = read_output.resolved_mode;
267                let orig = cache.get(&path_owned).map_or(0, |e| e.original_tokens);
268                let hit = content.contains(" cached ");
269                let fref = cache.file_ref_map().get(path_owned.as_str()).cloned();
270                let stats = cache.get_stats();
271                let stats_snapshot = (stats.total_reads, stats.cache_hits);
272                let _ = tx.send((content, rmode, orig, hit, fref, stats_snapshot));
273            });
274            if let Ok(result) = rx.recv_timeout(read_timeout) {
275                result
276            } else {
277                cancelled.store(true, Ordering::Relaxed);
278                tracing::error!("ctx_read timed out after {read_timeout:?} for {path}");
279                let msg = format!(
280                    "ERROR: ctx_read timed out after {}s reading {path}. \
281                     The file may be very large or a blocking I/O issue occurred. \
282                     Try mode=\"lines:1-100\" for a partial read.",
283                    read_timeout.as_secs()
284                );
285                return Err(ErrorData::internal_error(msg, None));
286            }
287        };
288
289        let output_tokens = crate::core::tokens::count_tokens(&output);
290        let saved = original.saturating_sub(output_tokens);
291
292        // Session updates (short lock)
293        let mut ensured_root: Option<String> = None;
294        let project_root_snapshot;
295        {
296            let mut session = session_lock.blocking_write();
297            session.touch_file(path, file_ref.as_deref(), &resolved_mode, original);
298            if is_cache_hit {
299                session.record_cache_hit();
300            }
301            if session.active_structured_intent.is_none() && session.files_touched.len() >= 2 {
302                let touched: Vec<String> = session
303                    .files_touched
304                    .iter()
305                    .map(|f| f.path.clone())
306                    .collect();
307                let inferred =
308                    crate::core::intent_engine::StructuredIntent::from_file_patterns(&touched);
309                if inferred.confidence >= 0.4 {
310                    session.active_structured_intent = Some(inferred);
311                }
312            }
313            let root_missing = session
314                .project_root
315                .as_deref()
316                .is_none_or(|r| r.trim().is_empty());
317            if root_missing {
318                if let Some(root) = crate::core::protocol::detect_project_root(path) {
319                    session.project_root = Some(root.clone());
320                    ensured_root = Some(root);
321                }
322            }
323            project_root_snapshot = session
324                .project_root
325                .clone()
326                .unwrap_or_else(|| ".".to_string());
327        }
328
329        if let Some(root) = ensured_root.as_deref() {
330            crate::core::index_orchestrator::ensure_all_background(root);
331        }
332
333        crate::core::heatmap::record_file_access(path, original, saved);
334
335        // Mode predictor + feedback — no locks needed, uses snapshots from above
336        {
337            let sig = crate::core::mode_predictor::FileSignature::from_path(path, original);
338            let density = if output_tokens > 0 {
339                original as f64 / output_tokens as f64
340            } else {
341                1.0
342            };
343            let outcome = crate::core::mode_predictor::ModeOutcome {
344                mode: resolved_mode.clone(),
345                tokens_in: original,
346                tokens_out: output_tokens,
347                density: density.min(1.0),
348            };
349            let mut predictor = crate::core::mode_predictor::ModePredictor::new();
350            predictor.set_project_root(&project_root_snapshot);
351            predictor.record(sig, outcome);
352            predictor.save();
353
354            let ext = std::path::Path::new(path)
355                .extension()
356                .and_then(|e| e.to_str())
357                .unwrap_or("")
358                .to_string();
359            let thresholds = crate::core::adaptive_thresholds::thresholds_for_path(path);
360            let feedback_outcome = crate::core::feedback::CompressionOutcome {
361                session_id: format!("{}", std::process::id()),
362                language: ext,
363                entropy_threshold: thresholds.bpe_entropy,
364                jaccard_threshold: thresholds.jaccard,
365                total_turns: cache_stats.0 as u32,
366                tokens_saved: saved as u64,
367                tokens_original: original as u64,
368                cache_hits: cache_stats.1 as u32,
369                total_reads: cache_stats.0 as u32,
370                task_completed: true,
371                timestamp: chrono::Local::now().to_rfc3339(),
372            };
373            let mut store = crate::core::feedback::FeedbackStore::load();
374            store.project_root = Some(project_root_snapshot.clone());
375            store.record_outcome(feedback_outcome);
376        }
377
378        if let Some(aid) = resolved_agent_id.as_deref() {
379            crate::core::agent_budget::record_consumption(aid, output_tokens);
380        }
381
382        let final_output = if let Some(ref warning) = budget_warning {
383            format!("{output}\n\n{warning}")
384        } else {
385            output
386        };
387
388        Ok(ToolOutput {
389            text: final_output,
390            original_tokens: original,
391            saved_tokens: saved,
392            mode: Some(resolved_mode),
393            path: Some(path.to_string()),
394            changed: false,
395        })
396    }
397}
398
399fn auto_degrade_read_mode(mode: &str) -> String {
400    use crate::core::degradation_policy::DegradationVerdictV1;
401    let profile = crate::core::profiles::active_profile();
402    if !profile.degradation.enforce_effective() {
403        return mode.to_string();
404    }
405    let policy = crate::core::degradation_policy::evaluate_v1_for_tool("ctx_read", None);
406    match policy.decision.verdict {
407        DegradationVerdictV1::Ok => mode.to_string(),
408        DegradationVerdictV1::Warn => match mode {
409            "full" => "map".to_string(),
410            other => other.to_string(),
411        },
412        DegradationVerdictV1::Throttle => match mode {
413            "full" | "map" => "signatures".to_string(),
414            other => other.to_string(),
415        },
416        DegradationVerdictV1::Block => "signatures".to_string(),
417    }
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423    use std::sync::atomic::{AtomicUsize, Ordering};
424
425    #[test]
426    fn per_file_lock_same_path_returns_same_mutex() {
427        let lock_a1 = per_file_lock("/tmp/test_same_path.txt");
428        let lock_a2 = per_file_lock("/tmp/test_same_path.txt");
429        assert!(Arc::ptr_eq(&lock_a1, &lock_a2));
430    }
431
432    #[test]
433    fn per_file_lock_different_paths_return_different_mutexes() {
434        let lock_a = per_file_lock("/tmp/test_path_a.txt");
435        let lock_b = per_file_lock("/tmp/test_path_b.txt");
436        assert!(!Arc::ptr_eq(&lock_a, &lock_b));
437    }
438
439    #[test]
440    fn per_file_lock_serializes_concurrent_access() {
441        let counter = Arc::new(AtomicUsize::new(0));
442        let max_concurrent = Arc::new(AtomicUsize::new(0));
443        let path = "/tmp/test_concurrent_serialization.txt";
444        let mut handles = Vec::new();
445
446        for _ in 0..5 {
447            let counter = counter.clone();
448            let max_concurrent = max_concurrent.clone();
449            let path = path.to_string();
450            handles.push(std::thread::spawn(move || {
451                let lock = per_file_lock(&path);
452                let _guard = lock.lock().unwrap();
453                let active = counter.fetch_add(1, Ordering::SeqCst) + 1;
454                max_concurrent.fetch_max(active, Ordering::SeqCst);
455                std::thread::sleep(std::time::Duration::from_millis(10));
456                counter.fetch_sub(1, Ordering::SeqCst);
457            }));
458        }
459
460        for h in handles {
461            h.join().unwrap();
462        }
463
464        assert_eq!(max_concurrent.load(Ordering::SeqCst), 1);
465    }
466
467    #[test]
468    fn per_file_lock_allows_parallel_different_paths() {
469        let counter = Arc::new(AtomicUsize::new(0));
470        let max_concurrent = Arc::new(AtomicUsize::new(0));
471        let mut handles = Vec::new();
472
473        for i in 0..4 {
474            let counter = counter.clone();
475            let max_concurrent = max_concurrent.clone();
476            let path = format!("/tmp/test_parallel_{i}.txt");
477            handles.push(std::thread::spawn(move || {
478                let lock = per_file_lock(&path);
479                let _guard = lock.lock().unwrap();
480                let active = counter.fetch_add(1, Ordering::SeqCst) + 1;
481                max_concurrent.fetch_max(active, Ordering::SeqCst);
482                std::thread::sleep(std::time::Duration::from_millis(50));
483                counter.fetch_sub(1, Ordering::SeqCst);
484            }));
485        }
486
487        for h in handles {
488            h.join().unwrap();
489        }
490
491        assert!(max_concurrent.load(Ordering::SeqCst) > 1);
492    }
493
494    /// Regression test for Issue #229: a zombie thread holding the cache write-lock
495    /// must not block subsequent reads indefinitely. The try_write() loop inside
496    /// the spawned thread should respect its 25s deadline and the cancellation flag.
497    #[test]
498    fn zombie_thread_does_not_block_subsequent_cache_access() {
499        let cache: Arc<tokio::sync::RwLock<u32>> = Arc::new(tokio::sync::RwLock::new(0));
500
501        // Simulate a zombie: hold the write-lock on a background thread for 2s.
502        let zombie_lock = cache.clone();
503        let _zombie = std::thread::spawn(move || {
504            let _guard = zombie_lock.blocking_write();
505            std::thread::sleep(std::time::Duration::from_secs(2));
506        });
507        std::thread::sleep(std::time::Duration::from_millis(50));
508
509        // A try_read() must fail immediately (zombie holds write-lock).
510        assert!(cache.try_read().is_err());
511
512        // A try_write() loop with cancellation must exit promptly.
513        let cancel = Arc::new(AtomicBool::new(false));
514        let cancel2 = cancel.clone();
515        let lock2 = cache.clone();
516        let waiter = std::thread::spawn(move || {
517            let start = std::time::Instant::now();
518            loop {
519                if cancel2.load(Ordering::Relaxed) {
520                    return (false, start.elapsed());
521                }
522                if let Ok(_guard) = lock2.try_write() {
523                    return (true, start.elapsed());
524                }
525                std::thread::sleep(std::time::Duration::from_millis(50));
526            }
527        });
528
529        // Set cancellation after 200ms — the loop should exit quickly.
530        std::thread::sleep(std::time::Duration::from_millis(200));
531        cancel.store(true, Ordering::Relaxed);
532
533        let (acquired, elapsed) = waiter.join().unwrap();
534        assert!(
535            !acquired,
536            "should not have acquired lock while zombie holds it"
537        );
538        assert!(
539            elapsed < std::time::Duration::from_secs(1),
540            "cancellation should have stopped the loop promptly"
541        );
542    }
543}