Skip to main content

aft_base/
bounded_io.rs

1//! Bound first access to a protection/filesystem boundary, not every file read.
2//!
3//! A request probes each directory once. Ordinary files in accessible local
4//! directories stay on the caller's hot path. Network/removable/unknown volumes
5//! and symlinks retain per-file isolation. Helpers own no actor or epoch guard.
6use std::any::Any;
7use std::cell::RefCell;
8use std::collections::{HashMap, HashSet};
9use std::io::{self, Read};
10use std::path::{Path, PathBuf};
11#[cfg(any(test, feature = "test-support"))]
12use std::sync::atomic::AtomicUsize;
13use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
14#[cfg(any(test, feature = "test-support"))]
15use std::sync::LazyLock;
16use std::sync::{Arc, Condvar, Mutex, OnceLock};
17use std::time::{Duration, Instant};
18
19use crate::protocol::Response;
20
21pub const IO_BUDGET: Duration = Duration::from_secs(5);
22/// Wall-clock budget for grep/glob index-unavailable fallback walks on the dispatch thread.
23pub const FALLBACK_WALK_BUDGET: Duration = Duration::from_secs(10);
24pub(crate) const WALK_PARTIAL_GAP: &str =
25    "Directory walk reached its time budget; only examined entries are reported.";
26/// Request budget for a mutation's path checks when no caller budget exists.
27/// It matches the budget agent tool calls already run under, so a native
28/// request and a tool call wait equally long for a helper to be scheduled.
29pub(crate) const MUTATION_BUDGET: Duration = Duration::from_secs(25);
30const MAX_IO_THREADS: usize = 64;
31const IO_POOL_SIZE: usize = 8;
32static NEXT_BUDGET: AtomicU64 = AtomicU64::new(1);
33static HELPERS: OnceLock<Arc<Limiter>> = OnceLock::new();
34#[cfg(any(test, feature = "test-support"))]
35pub static THREAD_SPAWNS: AtomicUsize = AtomicUsize::new(0);
36#[cfg(any(test, feature = "test-support"))]
37#[derive(Default)]
38pub struct Measurements {
39    pub(crate) dispatches: AtomicUsize,
40    pub round_trips: AtomicUsize,
41    pub directory_probes: AtomicUsize,
42    pub traversal_probes: AtomicUsize,
43}
44
45#[derive(Clone, Debug)]
46struct Failure {
47    code: &'static str,
48    message: String,
49}
50impl std::fmt::Display for Failure {
51    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        formatter.write_str(&self.message)
53    }
54}
55impl std::error::Error for Failure {}
56
57/// Keep admission timeouts distinct when callers turn I/O errors into responses.
58pub fn timeout_code(error: &io::Error) -> &'static str {
59    error
60        .get_ref()
61        .and_then(|error| error.downcast_ref::<Failure>())
62        .map_or("read_blocked", |failure| failure.code)
63}
64
65#[derive(Clone)]
66struct ProbeError {
67    kind: io::ErrorKind,
68    message: String,
69    raw_os_error: Option<i32>,
70    failure: Option<Failure>,
71}
72impl ProbeError {
73    fn from(error: &io::Error) -> Self {
74        Self {
75            kind: error.kind(),
76            message: error.to_string(),
77            raw_os_error: error.raw_os_error(),
78            failure: error
79                .get_ref()
80                .and_then(|error| error.downcast_ref::<Failure>())
81                .cloned(),
82        }
83    }
84    fn error(&self) -> io::Error {
85        if let Some(failure) = &self.failure {
86            return io::Error::new(self.kind, failure.clone());
87        }
88        self.raw_os_error
89            .map(io::Error::from_raw_os_error)
90            .unwrap_or_else(|| io::Error::new(self.kind, self.message.clone()))
91    }
92}
93#[derive(Clone, Copy)]
94struct Access {
95    direct: bool,
96}
97struct Probe {
98    state: Mutex<ProbeState>,
99    ready: Condvar,
100    activity: Mutex<ProbeActivity>,
101}
102#[derive(Default)]
103struct ProbeActivity {
104    path: Option<PathBuf>,
105    progress: Option<Instant>,
106    walking: bool,
107    cancelled: Option<Arc<AtomicBool>>,
108}
109struct ProbeState {
110    result: Option<Result<Access, ProbeError>>,
111    deadline: Instant,
112    started: Option<Instant>,
113}
114impl Probe {
115    fn queued(deadline: Instant) -> Self {
116        Self {
117            state: Mutex::new(ProbeState {
118                result: None,
119                deadline,
120                started: None,
121            }),
122            ready: Condvar::new(),
123            activity: Mutex::new(ProbeActivity::default()),
124        }
125    }
126    fn set_deadline(&self, deadline: Instant, started: Option<Instant>) {
127        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
128        state.deadline = deadline;
129        state.started = started;
130        self.ready.notify_all();
131    }
132}
133#[derive(Clone)]
134pub struct Budget {
135    id: u64,
136    disclosure_only: bool,
137    pub deadline: Instant,
138    failure: Arc<Mutex<Option<Failure>>>,
139    failed: Arc<AtomicBool>,
140    walk_partial: Arc<AtomicBool>,
141    /// A read stall alone does not mean the walk reached its own deadline.
142    walk_time_limit_reached: Arc<AtomicBool>,
143    walk_gap: Arc<Mutex<Option<String>>>,
144    large_read_skips: Arc<Mutex<SkipCollector>>,
145    directories: Arc<Mutex<HashMap<PathBuf, Arc<Probe>>>>,
146    traversable: Arc<Mutex<HashSet<PathBuf>>>,
147    permissions: Arc<Mutex<Vec<PermissionObservation>>>,
148    /// Keep unreadable walk descendants out of `permissions`: consent uses that
149    /// list to ask the user to grant access to explicitly named folders.
150    walk_permissions:
151        Arc<Mutex<std::collections::BTreeMap<PathBuf, std::collections::BTreeSet<PathBuf>>>>,
152    walk_names: Arc<Mutex<HashMap<PathBuf, PathBuf>>>,
153    walk_root: Option<PathBuf>,
154    /// Set once the end of the budget has been kept back for the reply.
155    reply_margin_kept: bool,
156    #[cfg(any(test, feature = "test-support"))]
157    pub measurements: Arc<Measurements>,
158    #[cfg(any(test, feature = "test-support"))]
159    access_budget: Duration,
160    #[cfg(any(test, feature = "test-support"))]
161    access_budget_by_path: Arc<HashMap<PathBuf, Duration>>,
162}
163
164#[derive(Default)]
165struct SkipCollector {
166    files: std::collections::BTreeMap<PathBuf, std::collections::BTreeSet<String>>,
167    scopes: usize,
168}
169impl Budget {
170    /// Collect skips for native search without adding a request deadline or
171    /// sticky read failures. I/O helpers see no budget; parallel readers carry
172    /// the disclosure context with `capture` instead.
173    pub(crate) fn disclosure_only() -> Self {
174        let mut budget = Self::after(IO_BUDGET);
175        budget.disclosure_only = true;
176        budget
177    }
178    pub fn capped(&self, deadline: Instant) -> Self {
179        let mut budget = self.clone();
180        budget.deadline = budget.deadline.min(deadline);
181        budget
182    }
183    pub fn after(duration: Duration) -> Self {
184        Self {
185            id: NEXT_BUDGET.fetch_add(1, Ordering::Relaxed),
186            disclosure_only: false,
187            deadline: Instant::now() + duration,
188            failure: Arc::new(Mutex::new(None)),
189            failed: Arc::new(AtomicBool::new(false)),
190            walk_partial: Arc::new(AtomicBool::new(false)),
191            walk_time_limit_reached: Arc::new(AtomicBool::new(false)),
192            walk_gap: Arc::new(Mutex::new(None)),
193            large_read_skips: capture()
194                .map(|budget| budget.large_read_skips)
195                .unwrap_or_default(),
196            directories: Arc::new(Mutex::new(HashMap::new())),
197            traversable: Arc::new(Mutex::new(HashSet::new())),
198            permissions: Arc::new(Mutex::new(Vec::new())),
199            walk_permissions: Arc::default(),
200            walk_names: Arc::default(),
201            walk_root: None,
202            reply_margin_kept: false,
203            #[cfg(any(test, feature = "test-support"))]
204            measurements: Arc::new(Measurements::default()),
205            #[cfg(any(test, feature = "test-support"))]
206            access_budget: IO_BUDGET,
207            #[cfg(any(test, feature = "test-support"))]
208            access_budget_by_path: Arc::new(HashMap::new()),
209        }
210    }
211    pub fn permissions(&self) -> Vec<PermissionObservation> {
212        self.permissions
213            .lock()
214            .unwrap_or_else(|e| e.into_inner())
215            .clone()
216    }
217    #[cfg(any(test, feature = "test-support"))]
218    pub fn measurements(&self) -> (usize, usize) {
219        (
220            self.measurements.dispatches.load(Ordering::Relaxed),
221            self.measurements.round_trips.load(Ordering::Relaxed),
222        )
223    }
224    #[cfg(any(test, feature = "test-support"))]
225    pub fn with_access_budget(mut self, duration: Duration) -> Self {
226        self.access_budget = duration;
227        self
228    }
229    #[cfg(all(
230        any(test, feature = "test-support"),
231        any(target_os = "macos", target_os = "linux")
232    ))]
233    pub fn with_path_access_budget(mut self, path: &Path, duration: Duration) -> Self {
234        Arc::make_mut(&mut self.access_budget_by_path).insert(path.to_path_buf(), duration);
235        self
236    }
237}
238
239#[derive(Clone, Debug)]
240pub struct PermissionObservation {
241    pub folder: PathBuf,
242    pub readable: bool,
243}
244
245pub fn name_walk_root(root: &Path, name: &Path) {
246    if let Some(budget) = current() {
247        budget
248            .walk_names
249            .lock()
250            .unwrap_or_else(|e| e.into_inner())
251            .entry(crate::path_identity::lexical_normalize(root))
252            .or_insert_with(|| name.to_path_buf());
253    }
254}
255
256fn walk_permission_gap(root: &Path, display_root: &Path, folders: &[PathBuf]) -> String {
257    let count = folders.len();
258    let mut names = folders
259        .iter()
260        .take(3)
261        .map(|folder| {
262            folder
263                .strip_prefix(root)
264                .ok()
265                .filter(|relative| !relative.as_os_str().is_empty())
266                .unwrap_or(folder)
267                .display()
268                .to_string()
269        })
270        .collect::<Vec<_>>();
271    if count > 3 {
272        names.push(format!("and {} more", count - 3));
273    }
274    let (folders, pronoun) = if count == 1 {
275        ("folder", "it")
276    } else {
277        ("folders", "them")
278    };
279    format!(
280        "macOS did not let AFT read {count} {folders} under {}, so the result skips {pronoun}: {}.",
281        display_root.display(),
282        names.join(", ")
283    )
284}
285
286#[cfg(test)]
287mod walk_permission_gap_tests {
288    use super::*;
289
290    #[test]
291    fn macos_walk_permission_gap_counts_and_relative_paths() {
292        let root = Path::new("/walk");
293        let folders = (1..=38)
294            .map(|index| root.join(format!("protected-{index}")))
295            .collect::<Vec<_>>();
296        for (count, expected) in [
297            (1, "macOS did not let AFT read 1 folder under /walk, so the result skips it: protected-1."),
298            (2, "macOS did not let AFT read 2 folders under /walk, so the result skips them: protected-1, protected-2."),
299            (3, "macOS did not let AFT read 3 folders under /walk, so the result skips them: protected-1, protected-2, protected-3."),
300            (38, "macOS did not let AFT read 38 folders under /walk, so the result skips them: protected-1, protected-2, protected-3, and 35 more."),
301        ] {
302            assert_eq!(walk_permission_gap(root, root, &folders[..count]), expected);
303        }
304    }
305
306    #[test]
307    fn macos_walk_permission_gap_preserves_other_gaps_and_is_not_a_card_observation() {
308        let mut budget = Budget::after(Duration::from_secs(10));
309        budget.walk_root = Some(PathBuf::from("/walk"));
310        budget
311            .walk_names
312            .lock()
313            .unwrap()
314            .insert(PathBuf::from("/walk"), PathBuf::from("."));
315        budget.walk_partial.store(true, Ordering::Release);
316        budget
317            .walk_time_limit_reached
318            .store(true, Ordering::Release);
319        with_budget(Some(budget.clone()), || {
320            for _ in 0..2 {
321                observe_permission(
322                    Path::new("/walk/protected"),
323                    &Err(io::Error::from_raw_os_error(1)),
324                    true,
325                );
326            }
327            assert!(
328                budget.permissions().is_empty(),
329                "a walk denial must never reach card creation"
330            );
331            let response = finish_response(Response::success(
332                "walk",
333                serde_json::json!({"text":"readable.rs\n\nshown 1 of 1 files"}),
334            ));
335            let response = finish_response(response);
336            assert!(response.success);
337            assert_eq!(response.data["complete"], false);
338            assert_eq!(
339                response.data["gaps"],
340                serde_json::json!([
341                WALK_PARTIAL_GAP,
342                "macOS did not let AFT read 1 folder under ., so the result skips it: protected."
343            ])
344            );
345            let text = response.data["text"].as_str().unwrap();
346            assert_eq!(text.matches("macOS did not let").count(), 1);
347            assert!(text.contains(WALK_PARTIAL_GAP));
348            assert!(text.ends_with("shown 1 of 1 files"));
349        });
350    }
351}
352
353fn observe_permission(path: &Path, result: &io::Result<Access>, macos: bool) {
354    if !macos {
355        return;
356    }
357    let readable = match result {
358        Ok(_) => true,
359        Err(error) if error.raw_os_error() == Some(1) => false,
360        _ => return,
361    };
362    if let Some(budget) = current() {
363        let folder = permission_folder(path);
364        if let Some(root) = budget
365            .walk_root
366            .as_ref()
367            .filter(|root| !readable && folder != **root && folder.starts_with(root))
368        {
369            budget
370                .walk_permissions
371                .lock()
372                .unwrap_or_else(|e| e.into_inner())
373                .entry(root.clone())
374                .or_default()
375                .insert(folder);
376            return;
377        }
378        budget
379            .permissions
380            .lock()
381            .unwrap_or_else(|e| e.into_inner())
382            .push(PermissionObservation { folder, readable });
383    }
384}
385
386// macOS privacy permissions apply to the enclosing protected folder, not each
387// descendant directory.
388// This is only a display/deduplication identity; it never changes path policy.
389fn permission_folder(path: &Path) -> PathBuf {
390    let home = std::env::var_os("HOME").map(PathBuf::from);
391    if let Some(home) = home {
392        for folder in [
393            "Desktop",
394            "Documents",
395            "Downloads",
396            "Pictures",
397            "Music",
398            "Movies",
399        ] {
400            let folder = home.join(folder);
401            if path.starts_with(&folder) {
402                return folder;
403            }
404        }
405    }
406    path.to_path_buf()
407}
408
409/// The helper only probes access. The caller may mutate only after this returns.
410pub fn probe_access(req_id: &str, path: &Path) -> Result<(), Response> {
411    // A new target may have several nonexistent ancestors. Probe the nearest
412    // existing directory without creating any of those missing components.
413    let result = probe_target(path);
414    match result {
415        Ok(()) => Ok(()),
416        Err(error) if missing_probe_target(&error, path, cfg!(windows)) => {
417            let mut parent = path.parent();
418            while let Some(folder) = parent {
419                match probe_directory(folder, None) {
420                    Ok(()) => return Ok(()),
421                    Err(error) if missing_probe_target(&error, folder, cfg!(windows)) => {
422                        parent = folder.parent()
423                    }
424                    Err(error) => return Err(access_error(req_id, folder, error)),
425                }
426            }
427            Ok(())
428        }
429        Err(error) => Err(access_error(req_id, path, error)),
430    }
431}
432
433fn missing_probe_target(error: &io::Error, path: &Path, windows: bool) -> bool {
434    error.kind() == io::ErrorKind::NotFound
435        // Win32 rejects a literal glob with ERROR_INVALID_NAME (123). Probe its
436        // existing ancestor; the handler expands and validates concrete files.
437        // Access-denied errors and ordinary invalid names still fail closed.
438        || (windows
439            && error.raw_os_error() == Some(123)
440            && path.components().any(|component| {
441                matches!(component, std::path::Component::Normal(name)
442                    if name.to_string_lossy().contains(['*', '?', '[', ']', '{', '}']))
443            }))
444}
445
446fn access_error(req_id: &str, path: &Path, error: io::Error) -> Response {
447    let code = if cfg!(target_os = "macos") && error.raw_os_error() == Some(1) {
448        let folder = current()
449            .and_then(|budget| {
450                budget
451                    .permissions()
452                    .into_iter()
453                    .find(|p| !p.readable)
454                    .map(|p| p.folder)
455            })
456            .unwrap_or_else(|| permission_folder(path.parent().unwrap_or(path)));
457        observe_permission(&folder, &Err(io::Error::from_raw_os_error(1)), true);
458        return Response::error_with_data(req_id, "macos_permission_denied", format!("macOS denied access to {}; grant ck-aft access in System Settings → Privacy & Security, then retry", folder.display()), serde_json::json!({"folder":folder,"program":"ck-aft"}));
459    } else if error.kind() == io::ErrorKind::TimedOut {
460        timeout_code(&error)
461    } else {
462        "path_access_denied"
463    };
464    Response::error_with_data(
465        req_id,
466        code,
467        format!("{}: {error}", path.display()),
468        serde_json::json!({"path":path,"os_error":error.raw_os_error()}),
469    )
470}
471
472pub fn finish_response(mut response: Response) -> Response {
473    response = finish_response_without_skips(response);
474    response
475}
476
477fn finish_response_without_skips(mut response: Response) -> Response {
478    if matches!(
479        response.data["code"].as_str(),
480        Some("denied_floor" | "path_outside_root" | "access_read_only")
481    ) {
482        return response;
483    }
484    if let Some(folder) = current().and_then(|budget| {
485        budget
486            .permissions()
487            .into_iter()
488            .find(|p| !p.readable)
489            .map(|p| p.folder)
490    }) {
491        return Response::error_with_data(&response.id, "macos_permission_denied", format!("macOS denied access to {}; grant ck-aft access in System Settings → Privacy & Security, then retry", folder.display()), serde_json::json!({"folder":folder,"program":"ck-aft"}));
492    }
493    let error = current().and_then(|budget| {
494        budget
495            .failure
496            .lock()
497            .unwrap_or_else(|e| e.into_inner())
498            .clone()
499    });
500    let permission_gaps = current().map_or_else(Vec::new, |budget| {
501        let names = budget.walk_names.lock().unwrap_or_else(|e| e.into_inner());
502        budget
503            .walk_permissions
504            .lock()
505            .unwrap_or_else(|e| e.into_inner())
506            .iter()
507            .map(|(root, folders)| {
508                walk_permission_gap(
509                    root,
510                    names.get(root).unwrap_or(root),
511                    &folders.iter().cloned().collect::<Vec<_>>(),
512                )
513            })
514            .collect::<Vec<_>>()
515    });
516    if response.success
517        && (current().is_some_and(|b| b.walk_partial.load(Ordering::Acquire))
518            || !permission_gaps.is_empty())
519    {
520        let named_gap = error.map(|error| error.message).or_else(|| {
521            current().and_then(|budget| {
522                budget
523                    .walk_gap
524                    .lock()
525                    .unwrap_or_else(|e| e.into_inner())
526                    .clone()
527            })
528        });
529        let mut gaps = Vec::new();
530        if current().is_some_and(|b| b.walk_time_limit_reached.load(Ordering::Acquire)) {
531            gaps.push(WALK_PARTIAL_GAP.to_string());
532        }
533        if let Some(gap) = named_gap {
534            if gap != WALK_PARTIAL_GAP {
535                gaps.push(gap);
536            }
537        }
538        gaps.extend(permission_gaps);
539        if let Some(existing) = response.data["gaps"].as_array() {
540            gaps.retain(|gap| !existing.iter().any(|value| value.as_str() == Some(gap)));
541        }
542        if gaps.is_empty() {
543            return response;
544        }
545        let gap = gaps.join("\n");
546        response.data["complete"] = serde_json::json!(false);
547        if let Some(existing) = response.data["gaps"].as_array_mut() {
548            existing.extend(gaps.into_iter().map(serde_json::Value::String));
549        } else {
550            response.data["gaps"] = serde_json::json!(gaps);
551        }
552        let text = response.data["text"].as_str().unwrap_or_default();
553        // Coverage details precede the shared trailer so the last line remains
554        // the list's machine-readable count and narrowing advice.
555        let text = match text.rsplit_once("\n\n") {
556            Some((body, trailer)) if trailer.starts_with("shown ") => {
557                format!("{body}\n\n{gap}\n\n{trailer}")
558            }
559            _ => format!("{text}\n\n{gap}"),
560        };
561        response.data["text"] = serde_json::json!(text);
562        return response;
563    }
564    match error {
565        Some(error) => Response::error(&response.id, error.code, error.message),
566        None => response,
567    }
568}
569
570test_support_visibility! {
571/// A ceiling skip is a coverage gap, not a sticky I/O failure: other files
572/// in the same request must still be readable.
573pub(crate) fn note_large_read_skip(path: &Path) {
574    note_skipped_file(path, crate::large_read_counts::WHOLE_READ_SKIP_REASON);
575}
576}
577
578pub fn note_skipped_file(path: &Path, reason: &str) {
579    if let Some(budget) = capture() {
580        budget
581            .large_read_skips
582            .lock()
583            .unwrap_or_else(|e| e.into_inner())
584            .files
585            .entry(path.to_path_buf())
586            .or_default()
587            .insert(reason.to_string());
588    }
589}
590
591/// Keep all omission categories until the outer command has finished. Nested
592/// commands and workers that inherit the budget share the collector rather
593/// than adding a response field.
594pub fn with_skip_disclosure(run: impl FnOnce() -> Response) -> Response {
595    let _scope = enter_disclosure_if_absent();
596    let budget = capture().unwrap();
597    let root = {
598        let mut skips = budget
599            .large_read_skips
600            .lock()
601            .unwrap_or_else(|e| e.into_inner());
602        let root = skips.scopes == 0;
603        skips.scopes += 1;
604        root
605    };
606    struct Depth(Arc<Mutex<SkipCollector>>);
607    impl Drop for Depth {
608        fn drop(&mut self) {
609            self.0.lock().unwrap_or_else(|e| e.into_inner()).scopes -= 1;
610        }
611    }
612    let depth = Depth(budget.large_read_skips);
613    let mut response = run();
614    drop(depth);
615    if root {
616        disclose_large_read_skips(&mut response);
617    }
618    response
619}
620
621pub fn skip_disclosure_active() -> bool {
622    capture().is_some_and(|budget| {
623        budget
624            .large_read_skips
625            .lock()
626            .unwrap_or_else(|e| e.into_inner())
627            .scopes
628            != 0
629    })
630}
631
632test_support_visibility! {
633pub(crate) fn disclose_large_read_skips(response: &mut Response) {
634    if !response.success {
635        return;
636    }
637    let Some(budget) = capture() else { return };
638    let mut skipped = budget
639        .large_read_skips
640        .lock()
641        .unwrap_or_else(|e| e.into_inner());
642    if skipped.scopes != 0 {
643        return;
644    }
645    if let Some(existing) = response.data["skipped_files"].as_array() {
646        for entry in existing {
647            if let (Some(file), Some(reason)) = (entry["file"].as_str(), entry["reason"].as_str()) {
648                let reasons = skipped.files.entry(PathBuf::from(file)).or_default();
649                if let Some(all) = entry["reasons"].as_array() {
650                    reasons.extend(
651                        all.iter()
652                            .filter_map(|reason| reason.as_str().map(str::to_string)),
653                    );
654                } else {
655                    reasons.insert(reason.to_string());
656                }
657            }
658        }
659    }
660    if skipped.files.is_empty() {
661        return;
662    }
663    let total = skipped.files.len();
664    let names = skipped.files.iter().take(20).map(|(path, reasons)| {
665        let mut entry = serde_json::json!({"file":path,"reason":reasons.iter().cloned().collect::<Vec<_>>().join("; ")});
666        if reasons.len() > 1 { entry["reasons"] = serde_json::json!(reasons); }
667        entry
668    }).collect::<Vec<_>>();
669    response.data["complete"] = serde_json::json!(false);
670    response.data["skipped_files"] = serde_json::json!(names);
671    response.data["skipped_files_remaining"] = serde_json::json!(total - names.len());
672    let envelope = crate::list_surfaces::search::skipped_files_envelope(names.len(), total);
673    response.data["skipped_files_list_envelope"] = serde_json::json!(envelope);
674    // Leave empty search text for format_search to supply "No results." and
675    // notes about capped enumeration, more available rows and degraded search.
676    if let Some(text) = response.data["text"]
677        .as_str()
678        .filter(|text| !text.is_empty())
679    {
680        response.data["text"] =
681            serde_json::json!(append_skipped_files_text(text.to_string(), &response.data));
682    }
683}
684
685}
686
687pub fn append_skipped_files_text(text: String, data: &serde_json::Value) -> String {
688    let gap = skipped_files_text(data);
689    if gap.is_empty() {
690        return text;
691    }
692    let text = strip_skipped_files_text(&text, data);
693    match text.rsplit_once("\n\n") {
694        Some((body, trailer)) if trailer.starts_with("shown ") => {
695            format!("{body}\n\n{gap}\n\n{trailer}")
696        }
697        _ if text.is_empty() => gap,
698        _ => format!("{text}\n\n{gap}"),
699    }
700}
701
702pub fn strip_skipped_files_text(text: &str, data: &serde_json::Value) -> String {
703    let gap = skipped_files_text(data);
704    if gap.is_empty() {
705        return text.to_string();
706    }
707    if text == gap {
708        return String::new();
709    }
710    text.replacen(&format!("\n\n{gap}"), "", 1)
711}
712
713fn skipped_files_text(data: &serde_json::Value) -> String {
714    if data.get("skipped_files_list_envelope").is_none() {
715        return String::new();
716    }
717    let Some(files) = data["skipped_files"].as_array() else {
718        return String::new();
719    };
720    let mut groups = std::collections::BTreeMap::<&str, Vec<&str>>::new();
721    for file in files {
722        if let (Some(path), Some(reason)) = (file["file"].as_str(), file["reason"].as_str()) {
723            groups.entry(reason).or_default().push(path);
724        }
725    }
726    let mut gap = groups
727        .into_iter()
728        .map(|(reason, names)| format!("{reason}\n{}", names.join("\n")))
729        .collect::<Vec<_>>()
730        .join("\n\n");
731    let trailer =
732        crate::ndjson_text::build_ndjson_text("", data, Some("payload.skipped_files"), false);
733    if !trailer.is_empty() {
734        gap.push_str("\n\n");
735        gap.push_str(&trailer);
736    }
737    gap
738}
739thread_local! {
740    static CURRENT: RefCell<Option<Budget>> = const { RefCell::new(None) };
741    static ACTIVE_PROBE: RefCell<Option<Arc<Probe>>> = const { RefCell::new(None) };
742    // Rayon shares the request's single-flight probes, but does not contend on
743    // that map per file. Its workers remember successful lookups locally.
744    static DIRECTORIES: RefCell<(u64, HashMap<PathBuf, Access>)> = RefCell::new((0, HashMap::new()));
745    static HELPER_DEADLINE: std::cell::Cell<Option<Instant>> = const { std::cell::Cell::new(None) };
746    static MUTATION_ADMISSION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
747    static CARRY_FACTORY: RefCell<Option<CarryFactory>> = const { RefCell::new(None) };
748    static CARRY_RESTORE: RefCell<Option<Option<CarryRestore>>> = const { RefCell::new(None) };
749}
750
751/// Higher layers carry request-local state without exposing its type to I/O.
752pub(crate) type Carry = Box<dyn FnOnce() -> io::Result<Box<dyn Any + Send>> + Send>;
753pub type CarryFactory = Arc<dyn Fn() -> io::Result<Carry> + Send + Sync>;
754type CarryRestore = Box<dyn FnOnce() + Send>;
755
756#[cfg(any(test, feature = "test-support"))]
757static TEST_HELPER_SCOPE: std::sync::OnceLock<fn() -> Box<dyn Any>> = std::sync::OnceLock::new();
758
759#[cfg(any(test, feature = "test-support"))]
760pub fn register_test_helper_scope(scope: fn() -> Box<dyn Any>) {
761    // Tool-owned counters live above this module. Their owner supplies the
762    // reset scope so reused helpers start each test job with clean counters.
763    let _ = TEST_HELPER_SCOPE.set(scope);
764}
765
766/// Updated alongside the higher layer's thread-local state, including restores.
767/// A helper also restores state first installed by its work, even if the
768/// helper was entered with no carried state at all.
769pub fn replace_carry_factory(factory: Option<CarryFactory>, restore: CarryRestore) {
770    CARRY_RESTORE.with(|pending| {
771        if let Some(first @ None) = &mut *pending.borrow_mut() {
772            *first = Some(restore);
773        }
774    });
775    CARRY_FACTORY.with(|current| *current.borrow_mut() = factory);
776}
777
778struct CarryJobScope {
779    factory: Option<CarryFactory>,
780    restore: Option<Option<CarryRestore>>,
781}
782
783impl CarryJobScope {
784    fn enter() -> Self {
785        Self {
786            factory: CARRY_FACTORY.with(|current| current.borrow().clone()),
787            restore: CARRY_RESTORE.with(|pending| pending.replace(Some(None))),
788        }
789    }
790}
791
792impl Drop for CarryJobScope {
793    fn drop(&mut self) {
794        let restore = CARRY_RESTORE
795            .with(|pending| pending.replace(self.restore.take()))
796            .flatten();
797        if let Some(restore) = restore {
798            restore();
799        }
800        CARRY_FACTORY.with(|current| *current.borrow_mut() = self.factory.take());
801    }
802}
803
804#[cfg(any(test, feature = "test-support"))]
805pub fn has_carry_factory() -> bool {
806    CARRY_FACTORY.with(|current| current.borrow().is_some())
807}
808
809#[cfg(any(test, feature = "test-support"))]
810pub fn dirty_helper_job_state() {
811    MUTATION_ADMISSION.with(|flag| flag.set(true));
812    DIRECTORIES.with(|cache| {
813        let mut cache = cache.borrow_mut();
814        cache.0 = 42;
815        cache
816            .1
817            .insert(PathBuf::from("old"), Access { direct: true });
818    });
819}
820
821#[cfg(any(test, feature = "test-support"))]
822pub fn helper_job_state() -> (bool, bool) {
823    (
824        DIRECTORIES.with(|cache| cache.borrow().1.is_empty()),
825        MUTATION_ADMISSION.with(|flag| flag.get()),
826    )
827}
828
829fn carry_refusal(path: &Path) -> io::Error {
830    failure(
831        path,
832        "read_io_queue_timeout",
833        "filesystem helper did not start before the deadline; this call did not start",
834    )
835}
836
837fn capture_carry(path: &Path) -> io::Result<Option<Carry>> {
838    let factory = CARRY_FACTORY.with(|current| current.borrow().clone());
839    factory
840        .map(|factory| {
841            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| factory()))
842                .ok()
843                .and_then(Result::ok)
844                .ok_or_else(|| carry_refusal(path))
845        })
846        .transpose()
847}
848
849fn enter_carry(path: &Path, carry: Option<Carry>) -> io::Result<Option<Box<dyn Any + Send>>> {
850    carry
851        .map(|carry| {
852            std::panic::catch_unwind(std::panic::AssertUnwindSafe(carry))
853                .ok()
854                .and_then(Result::ok)
855                .ok_or_else(|| carry_refusal(path))
856        })
857        .transpose()
858}
859pub struct Scope(Option<Budget>);
860impl Drop for Scope {
861    fn drop(&mut self) {
862        CURRENT.with(|current| *current.borrow_mut() = self.0.take());
863    }
864}
865pub fn current() -> Option<Budget> {
866    capture().filter(|budget| !budget.disclosure_only)
867}
868
869/// Carry the request's skip collector even when native search has no I/O budget.
870pub fn capture() -> Option<Budget> {
871    CURRENT.with(|current| current.borrow().clone())
872}
873
874test_support_visibility! {
875pub(crate) fn enter_disclosure_if_absent() -> Scope {
876    enter(capture().or_else(|| Some(Budget::disclosure_only())))
877}
878}
879
880/// Person approval has its own deadline; preserve the remaining filesystem and
881/// reply budget when a held fetch resumes on this tool thread.
882pub(crate) fn exclude_secret_approval_wait(elapsed: Duration) {
883    CURRENT.with(|current| {
884        if let Some(budget) = current.borrow_mut().as_mut() {
885            budget.deadline += elapsed;
886        }
887    });
888}
889pub fn enter_if_absent(duration: Duration) -> Scope {
890    let budget = current().unwrap_or_else(|| Budget::after(duration));
891    Scope(CURRENT.with(|current| current.replace(Some(budget))))
892}
893/// Scope for the path checks of a mutation the user asked for (delete, edit,
894/// write, ...). A helper that has not started yet has touched nothing, and a
895/// mutation has no partial answer to return, so a slow-to-schedule helper (a
896/// loaded machine, or a Windows process whose thread start waits on a
897/// long-running DLL load) may wait for admission until the request deadline
898/// instead of the per-access cap. Once the helper starts, the usual access
899/// cap applies unchanged, so a blocked filesystem still fails as
900/// `read_blocked` within that cap.
901pub struct MutationScope {
902    previous: bool,
903    _scope: Scope,
904}
905impl Drop for MutationScope {
906    fn drop(&mut self) {
907        MUTATION_ADMISSION.with(|flag| flag.set(self.previous));
908    }
909}
910pub fn enter_mutation() -> MutationScope {
911    let scope = enter_if_absent(MUTATION_BUDGET);
912    MutationScope {
913        previous: MUTATION_ADMISSION.with(|flag| flag.replace(true)),
914        _scope: scope,
915    }
916}
917pub fn with_budget<T>(budget: Option<Budget>, work: impl FnOnce() -> T) -> T {
918    let _scope = enter(budget);
919    work()
920}
921pub fn enter(budget: Option<Budget>) -> Scope {
922    Scope(CURRENT.with(|current| current.replace(budget)))
923}
924/// Keep the last `margin` of the current request's budget for its reply:
925/// move the filesystem deadline `margin` earlier for the rest of the
926/// command. A request calls this before its last filesystem work, so a
927/// stalled read fails while the reply can still reach the caller in time.
928/// Only the first call moves the deadline, so a command that reads several
929/// documents keeps one margin, not one per document.
930pub fn keep_reply_margin(margin: Duration) {
931    CURRENT.with(|current| {
932        if let Some(budget) = current.borrow_mut().as_mut() {
933            if !budget.reply_margin_kept {
934                budget.reply_margin_kept = true;
935                budget.deadline = budget
936                    .deadline
937                    .checked_sub(margin)
938                    .unwrap_or(budget.deadline);
939            }
940        }
941    });
942}
943fn deadline(at: Option<Instant>) -> Instant {
944    request_deadline(at)
945        .into_iter()
946        .fold(Instant::now() + IO_BUDGET, Instant::min)
947}
948fn request_deadline(at: Option<Instant>) -> Option<Instant> {
949    at.into_iter()
950        .chain(current().map(|budget| budget.deadline))
951        .min()
952}
953
954/// Check a synchronous mutation loop without dispatching another I/O helper.
955/// Record the same timeout as a bounded filesystem call so response formatting
956/// returns the existing read_deadline_exceeded reply.
957pub fn check_request_deadline(path: &Path, now: Instant) -> io::Result<()> {
958    if let Some(error) = prior_failure() {
959        return Err(error);
960    }
961    if request_deadline(None).is_some_and(|deadline| now >= deadline) {
962        return Err(failure(
963            path,
964            "read_deadline_exceeded",
965            "filesystem deadline elapsed before this call started",
966        ));
967    }
968    Ok(())
969}
970fn failure(path: &Path, code: &'static str, reason: &str) -> io::Error {
971    let message = format!("{code}: {}: {reason}", path.display());
972    if let Some(budget) = current() {
973        budget
974            .failure
975            .lock()
976            .unwrap_or_else(|e| e.into_inner())
977            .get_or_insert_with(|| Failure {
978                code,
979                message: message.clone(),
980            });
981        budget.failed.store(true, Ordering::Release);
982    }
983    io::Error::new(io::ErrorKind::TimedOut, Failure { code, message })
984}
985fn prior_failure() -> Option<io::Error> {
986    CURRENT.with(|current| {
987        let current = current.borrow();
988        let budget = current.as_ref()?;
989        if !budget.failed.load(Ordering::Acquire) {
990            return None;
991        }
992        let error = budget
993            .failure
994            .lock()
995            .unwrap_or_else(|e| e.into_inner())
996            .as_ref()
997            .map(|failure| io::Error::new(io::ErrorKind::TimedOut, failure.clone()));
998        error
999    })
1000}
1001
1002type IoJob = Box<dyn FnOnce() + Send + 'static>;
1003
1004/// A published walk snapshot never holds its lock while accessing the filesystem.
1005/// The caller can take the last examined prefix even if the helper is stuck in `next`.
1006pub struct WalkProgress<T> {
1007    cancellation: Option<crate::executor::JobCancellation>,
1008    snapshot: Arc<Mutex<T>>,
1009    stopped: Arc<AtomicBool>,
1010    deadline: Instant,
1011    published: Arc<AtomicBool>,
1012}
1013pub struct WalkCompletion {
1014    pub incomplete: bool,
1015    pub time_limit: bool,
1016}
1017impl<T> WalkProgress<T> {
1018    pub fn stopped(&self) -> bool {
1019        self.stopped.load(Ordering::Acquire)
1020            || self
1021                .cancellation
1022                .as_ref()
1023                .is_some_and(|token| token.cancel_requested_before_commit())
1024            || Instant::now() >= self.deadline
1025            || prior_failure().is_some()
1026    }
1027    pub fn update(&self, update: impl FnOnce(&mut T)) {
1028        let mut snapshot = self.snapshot.lock().unwrap_or_else(|e| e.into_inner());
1029        if self.stopped.load(Ordering::Acquire) {
1030            return;
1031        }
1032        update(&mut snapshot);
1033        drop(snapshot);
1034        self.published.store(true, Ordering::Release);
1035        if let Some(token) = &self.cancellation {
1036            token.report_progress();
1037        }
1038        ACTIVE_PROBE.with(|probe| {
1039            if let Some(probe) = probe.borrow().as_ref() {
1040                probe
1041                    .activity
1042                    .lock()
1043                    .unwrap_or_else(|e| e.into_inner())
1044                    .progress = Some(Instant::now());
1045            }
1046        });
1047    }
1048}
1049
1050pub fn run_walk<T: Clone + Send + 'static>(
1051    path: &Path,
1052    at: Option<Instant>,
1053    initial: T,
1054    work: impl FnOnce(PathBuf, WalkProgress<T>) -> io::Result<T> + Send + 'static,
1055) -> (T, WalkCompletion) {
1056    if prior_failure().is_some() {
1057        return (
1058            initial,
1059            WalkCompletion {
1060                incomplete: true,
1061                time_limit: false,
1062            },
1063        );
1064    }
1065    let deadline = request_deadline(at).unwrap_or_else(|| Instant::now() + IO_BUDGET);
1066    let snapshot = Arc::new(Mutex::new(initial));
1067    let stopped = Arc::new(AtomicBool::new(false));
1068    let published = Arc::new(AtomicBool::new(false));
1069    let progress = WalkProgress {
1070        cancellation: crate::executor::current_job_cancellation(),
1071        snapshot: snapshot.clone(),
1072        stopped: stopped.clone(),
1073        deadline,
1074        published: published.clone(),
1075    };
1076    let probe = Arc::new(Probe::queued(deadline));
1077    {
1078        let mut activity = probe.activity.lock().unwrap_or_else(|e| e.into_inner());
1079        activity.walking = true;
1080        activity.cancelled = Some(stopped.clone());
1081    }
1082    // A stalled descendant is a gap in this walk, not a reason to discard
1083    // already-discovered paths when the caller reads or admits them afterward.
1084    let parent = current();
1085    let local = parent.clone().map(|mut budget| {
1086        budget.failure = Arc::new(Mutex::new(None));
1087        budget.failed = Arc::new(AtomicBool::new(false));
1088        budget.walk_root = Some(path.to_path_buf());
1089        budget
1090    });
1091    let (result, failure) = with_budget(local, || {
1092        let result = run_with_timeout(
1093            path,
1094            Some(deadline),
1095            Arc::clone(HELPERS.get_or_init(|| Limiter::new(IO_POOL_SIZE))),
1096            access_budget(path),
1097            Some(probe),
1098            move |path| work(path, progress),
1099        );
1100        let failure = current()
1101            .and_then(|budget| {
1102                budget
1103                    .failure
1104                    .lock()
1105                    .unwrap_or_else(|e| e.into_inner())
1106                    .clone()
1107            })
1108            .or_else(|| {
1109                result
1110                    .as_ref()
1111                    .err()
1112                    .and_then(|error| error.get_ref()?.downcast_ref::<Failure>().cloned())
1113            });
1114        (result, failure)
1115    });
1116    stopped.store(true, Ordering::Release);
1117    let failed = failure.is_some();
1118    let time_limit = Instant::now() >= deadline;
1119    let partial = result.is_err() || failed || time_limit;
1120    let named_gap = failure
1121        .as_ref()
1122        .map(|failure| failure.message.clone())
1123        .or_else(|| {
1124            result
1125                .as_ref()
1126                .err()
1127                .filter(|_| !time_limit)
1128                .map(ToString::to_string)
1129        });
1130    if partial && (published.load(Ordering::Acquire) || !failed) {
1131        if let Some(budget) = &parent {
1132            budget.walk_partial.store(true, Ordering::Release);
1133            if time_limit {
1134                budget
1135                    .walk_time_limit_reached
1136                    .store(true, Ordering::Release);
1137            }
1138            if let Some(gap) = named_gap {
1139                budget
1140                    .walk_gap
1141                    .lock()
1142                    .unwrap_or_else(|e| e.into_inner())
1143                    .get_or_insert(gap);
1144            }
1145        }
1146    } else if let (Some(budget), Some(failure)) = (parent, failure) {
1147        budget
1148            .failure
1149            .lock()
1150            .unwrap_or_else(|e| e.into_inner())
1151            .get_or_insert(failure);
1152        budget.failed.store(true, Ordering::Release);
1153    }
1154    (
1155        result.unwrap_or_else(|_| snapshot.lock().unwrap_or_else(|e| e.into_inner()).clone()),
1156        WalkCompletion {
1157            incomplete: partial,
1158            time_limit,
1159        },
1160    )
1161}
1162
1163/// Attribute nested access to the entry being checked, not the walk's root.
1164pub(crate) fn reading_path(path: &Path) -> impl Drop {
1165    struct ReadingPath(Option<(Arc<Probe>, Option<PathBuf>)>);
1166    impl Drop for ReadingPath {
1167        fn drop(&mut self) {
1168            if let Some((probe, previous)) = self.0.take() {
1169                probe
1170                    .activity
1171                    .lock()
1172                    .unwrap_or_else(|e| e.into_inner())
1173                    .path = previous;
1174            }
1175        }
1176    }
1177    ReadingPath(ACTIVE_PROBE.with(|probe| {
1178        probe.borrow().as_ref().map(|probe| {
1179            let previous = probe
1180                .activity
1181                .lock()
1182                .unwrap_or_else(|e| e.into_inner())
1183                .path
1184                .replace(path.to_path_buf());
1185            (probe.clone(), previous)
1186        })
1187    }))
1188}
1189
1190pub fn walk_path(path: &Path) -> bool {
1191    let keep_going = ACTIVE_PROBE.with(|probe| {
1192        if let Some(probe) = probe.borrow().as_ref() {
1193            let mut activity = probe.activity.lock().unwrap_or_else(|e| e.into_inner());
1194            if activity
1195                .cancelled
1196                .as_ref()
1197                .is_some_and(|cancelled| cancelled.load(Ordering::Acquire))
1198            {
1199                return false;
1200            }
1201            activity.path = Some(path.to_path_buf());
1202            activity.progress = Some(Instant::now());
1203        }
1204        true
1205    });
1206    #[cfg(all(any(test, feature = "test-support"), unix))]
1207    stall_running_helper_if_requested(path);
1208    keep_going
1209}
1210
1211struct Worker {
1212    sender: std::sync::mpsc::Sender<IoJob>,
1213    retired: Arc<AtomicBool>,
1214}
1215#[derive(Default)]
1216struct PoolState {
1217    idle: Vec<Worker>,
1218    usable: usize,
1219    live: usize,
1220    abandoned: usize,
1221    spawned: u64,
1222    retired_total: u64,
1223    replacements: u64,
1224    queue_timeouts: u64,
1225    cap_hits: u64,
1226}
1227struct Limiter {
1228    state: Mutex<PoolState>,
1229    available: Condvar,
1230    max: usize,
1231    max_live: usize,
1232    create: std::sync::mpsc::SyncSender<()>,
1233    #[cfg(any(test, feature = "test-support"))]
1234    test_scope: Option<fn() -> Box<dyn Any>>,
1235}
1236impl Limiter {
1237    fn new(max: usize) -> Arc<Self> {
1238        Self::with_limits(max, MAX_IO_THREADS)
1239    }
1240    fn with_limits(max: usize, max_live: usize) -> Arc<Self> {
1241        Self::with_options(
1242            max,
1243            max_live,
1244            #[cfg(any(test, feature = "test-support"))]
1245            None,
1246        )
1247    }
1248    fn with_options(
1249        max: usize,
1250        max_live: usize,
1251        #[cfg(any(test, feature = "test-support"))] test_scope: Option<fn() -> Box<dyn Any>>,
1252    ) -> Arc<Self> {
1253        assert!(max > 0 && max <= max_live);
1254        let (create, requests) = std::sync::mpsc::sync_channel(1);
1255        Arc::new_cyclic(|weak: &std::sync::Weak<Self>| {
1256            let pool = weak.clone();
1257            // Creating a worker can stall, for example on Windows DLL
1258            // initialization. After this one-time factory startup, admission
1259            // callers only enqueue creation requests and wait to their deadline;
1260            // worker creation never holds the pool state lock.
1261            let _ = std::thread::Builder::new()
1262                .name("aft-filesystem-probe-factory".into())
1263                .spawn(move || {
1264                    while requests.recv().is_ok() {
1265                        let Some(pool) = pool.upgrade() else { break };
1266                        pool.create_worker();
1267                    }
1268                });
1269            Self {
1270                state: Mutex::new(PoolState::default()),
1271                available: Condvar::new(),
1272                max,
1273                max_live,
1274                create,
1275                #[cfg(any(test, feature = "test-support"))]
1276                test_scope,
1277            }
1278        })
1279    }
1280    fn create_worker(self: &Arc<Self>) {
1281        {
1282            let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
1283            if !state.idle.is_empty() || state.usable >= self.max || state.live >= self.max_live {
1284                return;
1285            }
1286            state.live += 1;
1287            state.usable += 1;
1288        }
1289        let (sender, receiver) = std::sync::mpsc::channel::<IoJob>();
1290        let retired = Arc::new(AtomicBool::new(false));
1291        let worker_retired = Arc::clone(&retired);
1292        let pool = Arc::downgrade(self);
1293        #[cfg(any(test, feature = "test-support"))]
1294        let test_scope = self.test_scope;
1295        let spawned = std::thread::Builder::new()
1296            .name("aft-filesystem-probe".into())
1297            .spawn(move || {
1298                let _exit = WorkerExit {
1299                    pool,
1300                    retired: worker_retired,
1301                };
1302                while let Ok(job) = receiver.recv() {
1303                    // A panicking job disconnects its result channel. Keep this
1304                    // worker alive until its caller retires it and closes sender.
1305                    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1306                        let _state = HelperJobScope::enter();
1307                        #[cfg(any(test, feature = "test-support"))]
1308                        let _test_state = test_scope
1309                            .or_else(|| TEST_HELPER_SCOPE.get().copied())
1310                            .map(|scope| scope());
1311                        job();
1312                    }));
1313                }
1314            });
1315        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
1316        if spawned.is_ok() {
1317            #[cfg(any(test, feature = "test-support"))]
1318            THREAD_SPAWNS.fetch_add(1, Ordering::Relaxed);
1319            state.replacements += u64::from(state.retired_total > state.replacements);
1320            state.spawned += 1;
1321            state.idle.push(Worker { sender, retired });
1322        } else {
1323            state.live -= 1;
1324            state.usable -= 1;
1325        }
1326        self.available.notify_all();
1327    }
1328    fn acquire(self: &Arc<Self>, at: Instant) -> Option<Permit> {
1329        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
1330        let mut counted_cap = false;
1331        loop {
1332            let remaining = at.saturating_duration_since(Instant::now());
1333            if remaining.is_zero() {
1334                state.queue_timeouts += 1;
1335                return None;
1336            }
1337            if let Some(worker) = state.idle.pop() {
1338                return Some(Permit {
1339                    pool: Arc::clone(self),
1340                    worker: Some(worker),
1341                    reusable: true,
1342                });
1343            }
1344            if state.usable < self.max && state.live < self.max_live {
1345                if matches!(
1346                    self.create.try_send(()),
1347                    Err(std::sync::mpsc::TrySendError::Disconnected(_))
1348                ) {
1349                    return None;
1350                }
1351            }
1352            if state.live >= self.max_live && !counted_cap {
1353                state.cap_hits += 1;
1354                counted_cap = true;
1355            }
1356            state = self
1357                .available
1358                .wait_timeout(state, remaining)
1359                .unwrap_or_else(|e| e.into_inner())
1360                .0;
1361        }
1362    }
1363    fn health(&self) -> serde_json::Value {
1364        match self.state.try_lock() {
1365            Ok(state) => pool_health_snapshot(&state, self.max, self.max_live, "ready"),
1366            Err(error) => serde_json::json!({
1367                "pool_size": self.max,
1368                "thread_cap": self.max_live,
1369                "status": "unavailable",
1370                "reason": match error {
1371                    std::sync::TryLockError::WouldBlock => "state_busy",
1372                    std::sync::TryLockError::Poisoned(_) => "state_poisoned",
1373                },
1374            }),
1375        }
1376    }
1377}
1378struct HelperJobScope {
1379    _carry: CarryJobScope,
1380    directories: (u64, HashMap<PathBuf, Access>),
1381    mutation_admission: bool,
1382    #[cfg(any(test, feature = "test-support"))]
1383    canonicalize_calls: Option<Vec<PathBuf>>,
1384}
1385impl HelperJobScope {
1386    fn enter() -> Self {
1387        // Reset only at the dispatched job boundary. Nested probes run inline
1388        // and must keep the enclosing job's cache, counters and test hooks.
1389        Self {
1390            _carry: CarryJobScope::enter(),
1391            directories: DIRECTORIES.with(|cache| cache.replace(Default::default())),
1392            mutation_admission: MUTATION_ADMISSION.with(|flag| flag.replace(false)),
1393            #[cfg(any(test, feature = "test-support"))]
1394            canonicalize_calls: crate::path_identity::CANONICALIZE_CALLS
1395                .with(|calls| calls.replace(None)),
1396        }
1397    }
1398}
1399impl Drop for HelperJobScope {
1400    fn drop(&mut self) {
1401        DIRECTORIES.with(|cache| cache.replace(std::mem::take(&mut self.directories)));
1402        MUTATION_ADMISSION.with(|flag| flag.set(self.mutation_admission));
1403        #[cfg(any(test, feature = "test-support"))]
1404        crate::path_identity::CANONICALIZE_CALLS
1405            .with(|calls| *calls.borrow_mut() = self.canonicalize_calls.take());
1406    }
1407}
1408fn pool_health_snapshot(
1409    state: &PoolState,
1410    max: usize,
1411    max_live: usize,
1412    status: &str,
1413) -> serde_json::Value {
1414    serde_json::json!({
1415        "pool_size": max,
1416        "thread_cap": max_live,
1417        "status": status,
1418        "live": state.live,
1419        "idle": state.idle.len(),
1420        "usable": state.usable,
1421        "abandoned": state.abandoned,
1422        "spawned_total": state.spawned,
1423        "abandoned_total": state.retired_total,
1424        "replacements_total": state.replacements,
1425        "cap_hits_total": state.cap_hits,
1426        "queue_timeouts_total": state.queue_timeouts,
1427    })
1428}
1429pub fn helper_health() -> serde_json::Value {
1430    helper_health_from(&HELPERS)
1431}
1432
1433/// Start every worker the shared filesystem helper pool keeps. The pool
1434/// starts workers on demand, up to its configured size, and keeps reusable
1435/// workers idle for later calls (only a worker abandoned after a timeout
1436/// exits). A test that compares this process's threads before and after some
1437/// work fills it first; otherwise the pool growing to meet that work reads as
1438/// threads the work kept.
1439#[cfg(any(test, feature = "test-support"))]
1440pub fn fill_helper_pool_for_test() {
1441    let pool = Arc::clone(HELPERS.get_or_init(|| Limiter::new(IO_POOL_SIZE)));
1442    let deadline = Instant::now() + Duration::from_secs(30);
1443    // Holding every permit at once leaves no idle worker to reuse, so each
1444    // acquire starts a new one until the pool is at its size.
1445    let permits: Vec<Permit> = (0..pool.max)
1446        .map(|_| {
1447            pool.acquire(deadline)
1448                .expect("the filesystem helper pool did not fill")
1449        })
1450        .collect();
1451    drop(permits);
1452}
1453fn helper_health_from(helpers: &OnceLock<Arc<Limiter>>) -> serde_json::Value {
1454    // Health runs on the frame loop: observing an unused pool must not start
1455    // its factory, and observing a busy pool must not wait for its state lock.
1456    match helpers.get() {
1457        Some(pool) => pool.health(),
1458        None => pool_health_snapshot(
1459            &PoolState::default(),
1460            IO_POOL_SIZE,
1461            MAX_IO_THREADS,
1462            "not_started",
1463        ),
1464    }
1465}
1466struct WorkerExit {
1467    pool: std::sync::Weak<Limiter>,
1468    retired: Arc<AtomicBool>,
1469}
1470impl Drop for WorkerExit {
1471    fn drop(&mut self) {
1472        if let Some(pool) = self.pool.upgrade() {
1473            let mut state = pool.state.lock().unwrap_or_else(|e| e.into_inner());
1474            state.live -= 1;
1475            if self.retired.load(Ordering::Relaxed) {
1476                state.abandoned -= 1;
1477            }
1478            pool.available.notify_all();
1479        }
1480    }
1481}
1482struct Permit {
1483    pool: Arc<Limiter>,
1484    worker: Option<Worker>,
1485    reusable: bool,
1486}
1487impl Permit {
1488    fn send(&mut self, job: IoJob) -> io::Result<()> {
1489        self.reusable = false;
1490        self.worker
1491            .as_ref()
1492            .unwrap()
1493            .sender
1494            .send(job)
1495            .map_err(|_| io::Error::other("filesystem helper stopped"))
1496    }
1497}
1498impl Drop for Permit {
1499    fn drop(&mut self) {
1500        let worker = self.worker.take().unwrap();
1501        let mut state = self.pool.state.lock().unwrap_or_else(|e| e.into_inner());
1502        if self.reusable {
1503            state.idle.push(worker);
1504        } else {
1505            // A timed-out job cannot be cancelled inside the OS. Remove its
1506            // healthy slot, but count its thread against the hard cap until it
1507            // actually exits. Closing the sender makes a late return exit.
1508            worker.retired.store(true, Ordering::Relaxed);
1509            state.usable -= 1;
1510            state.abandoned += 1;
1511            state.retired_total += 1;
1512        }
1513        self.pool.available.notify_all();
1514    }
1515}
1516/// Isolate boundary probes, whole walks, and reads on risky filesystems.
1517/// Stuck helpers retain the submitted job closure and its owned captures.
1518pub fn run<T: Send + 'static>(
1519    path: &Path,
1520    at: Option<Instant>,
1521    work: impl FnOnce(PathBuf) -> io::Result<T> + Send + 'static,
1522) -> io::Result<T> {
1523    run_with_limiter(
1524        path,
1525        at,
1526        Arc::clone(HELPERS.get_or_init(|| Limiter::new(IO_POOL_SIZE))),
1527        work,
1528    )
1529}
1530
1531/// A separate helper pool whose stalled jobs cannot consume file-read workers.
1532#[derive(Clone)]
1533pub struct IsolatedPool(Arc<Limiter>);
1534
1535impl IsolatedPool {
1536    #[cfg(any(test, feature = "test-support"))]
1537    pub fn with_test_scope(thread_cap: usize, scope: fn() -> Box<dyn Any>) -> Self {
1538        Self(Limiter::with_options(thread_cap, thread_cap, Some(scope)))
1539    }
1540    pub fn new(thread_cap: usize) -> Self {
1541        Self(Limiter::with_limits(thread_cap, thread_cap))
1542    }
1543
1544    pub fn run<T: Send + 'static>(
1545        &self,
1546        path: &Path,
1547        at: Option<Instant>,
1548        work: impl FnOnce(PathBuf) -> io::Result<T> + Send + 'static,
1549    ) -> io::Result<T> {
1550        run_with_limiter(path, at, Arc::clone(&self.0), work)
1551    }
1552}
1553
1554/// Reserves time for a bounded walk to return partial results before the bounded I/O helper's
1555/// deadline; a helper still stuck in one OS call remains a `read_blocked`.
1556pub fn deadline_before_io_timeout(
1557    path: &Path,
1558    budget: Duration,
1559    return_margin: Duration,
1560) -> Instant {
1561    let now = Instant::now();
1562    let access_deadline = now + access_budget(path);
1563    let hard_deadline =
1564        request_deadline(None).map_or(access_deadline, |request| request.min(access_deadline));
1565    let walk_deadline = now + budget;
1566    let return_deadline = hard_deadline.checked_sub(return_margin).unwrap_or(now);
1567    walk_deadline.min(return_deadline)
1568}
1569fn run_with_limiter<T: Send + 'static>(
1570    path: &Path,
1571    at: Option<Instant>,
1572    limiter: Arc<Limiter>,
1573    work: impl FnOnce(PathBuf) -> io::Result<T> + Send + 'static,
1574) -> io::Result<T> {
1575    run_with_timeout(path, at, limiter, access_budget(path), None, work)
1576}
1577fn access_budget(path: &Path) -> Duration {
1578    #[cfg(any(test, feature = "test-support"))]
1579    return current().map_or(IO_BUDGET, |budget| {
1580        budget
1581            .access_budget_by_path
1582            .get(path)
1583            .copied()
1584            .unwrap_or(budget.access_budget)
1585    });
1586    #[cfg(not(any(test, feature = "test-support")))]
1587    {
1588        let _ = path;
1589        IO_BUDGET
1590    }
1591}
1592fn run_with_timeout<T: Send + 'static>(
1593    path: &Path,
1594    at: Option<Instant>,
1595    limiter: Arc<Limiter>,
1596    access_budget: Duration,
1597    probe: Option<Arc<Probe>>,
1598    work: impl FnOnce(PathBuf) -> io::Result<T> + Send + 'static,
1599) -> io::Result<T> {
1600    let _reading = reading_path(path);
1601    if let Some(error) = prior_failure() {
1602        return Err(error);
1603    }
1604    let queued = Instant::now();
1605    let request_deadline = request_deadline(at);
1606    // Without a request deadline, queueing and access each get their own cap.
1607    // Inside a mutation, a helper may wait to be admitted and scheduled until
1608    // the request deadline, because nothing has run yet; see `MutationScope`.
1609    let queue_deadline = match request_deadline {
1610        Some(at) if MUTATION_ADMISSION.with(std::cell::Cell::get) => at,
1611        Some(at) => at.min(queued + access_budget),
1612        None => queued + access_budget,
1613    };
1614    if let Some(probe) = &probe {
1615        probe.set_deadline(queue_deadline, None);
1616    }
1617    if queued >= queue_deadline {
1618        return Err(failure(
1619            path,
1620            "read_deadline_exceeded",
1621            "filesystem deadline elapsed before this call started",
1622        ));
1623    }
1624    // A bounded walk already owns an isolated helper. Do not consume another
1625    // slot per nested directory probe (or let healthy walks deadlock each
1626    // other on admission). Its caller's deadline must be no later than ours.
1627    let walking = ACTIVE_PROBE.with(|probe| {
1628        probe.borrow().as_ref().is_some_and(|probe| {
1629            probe
1630                .activity
1631                .lock()
1632                .unwrap_or_else(|e| e.into_inner())
1633                .walking
1634        })
1635    });
1636    if let Some(outer) = HELPER_DEADLINE.with(|outer| {
1637        outer.get().filter(|outer| {
1638            *outer <= queue_deadline || (walking && request_deadline.is_some_and(|at| at >= *outer))
1639        })
1640    }) {
1641        if let Some(probe) = &probe {
1642            probe.set_deadline(outer, Some(Instant::now()));
1643        }
1644        return work(path.to_path_buf());
1645    }
1646    let Some(mut permit) = limiter.acquire(queue_deadline) else {
1647        return Err(failure(path, "read_io_queue_timeout", "no filesystem helper slot became available before the deadline; this call did not start"));
1648    };
1649    let owned = path.to_path_buf();
1650    let budget = current();
1651    let alloc_label = crate::alloc_trace::carry();
1652    let carry = capture_carry(path)?;
1653    #[cfg(any(test, feature = "test-support"))]
1654    let measurements = budget.as_ref().map(|b| Arc::clone(&b.measurements));
1655    let (tx, rx) = std::sync::mpsc::sync_channel(1);
1656    let probe = probe.unwrap_or_else(|| Arc::new(Probe::queued(queue_deadline)));
1657    let helper_probe = Arc::clone(&probe);
1658    #[cfg(any(test, feature = "test-support"))]
1659    if let Some(counts) = &measurements {
1660        counts.round_trips.fetch_add(1, Ordering::Relaxed);
1661    }
1662    permit.send(Box::new(move || {
1663            let _alloc_label = alloc_label.enter();
1664            #[cfg(any(test, feature = "test-support"))]
1665            regression_tests::before_helper(&owned);
1666            let result = (|| {
1667                let _carry = enter_carry(&owned, carry)?;
1668                with_budget(budget, || {
1669                // Owning a slot does not mean the OS has scheduled this helper.
1670                // Never start expired work or blame its scheduling delay on I/O.
1671                // Publish the phase under the same lock used by the owner and
1672                // shared waiters, so neither can mistake a started access for
1673                // an expired queue while the helper is being scheduled.
1674                let mut state = helper_probe.state.lock().unwrap_or_else(|e| e.into_inner());
1675                let started = Instant::now();
1676                if started >= queue_deadline {
1677                    return Err(failure(&owned, "read_io_queue_timeout", "filesystem helper did not start before the deadline; this call did not start"));
1678                }
1679                // Admission and scheduling are not OS access. Start the access
1680                // cap here, while retaining the caller's hard request deadline.
1681                let at = request_deadline
1682                    .map_or(started + access_budget, |at| at.min(started + access_budget));
1683                state.started = Some(started);
1684                state.deadline = at;
1685                helper_probe.ready.notify_all();
1686                drop(state);
1687                struct DeadlineScope(Option<Instant>);
1688                impl Drop for DeadlineScope {
1689                    fn drop(&mut self) {
1690                        HELPER_DEADLINE.with(|deadline| deadline.set(self.0));
1691                    }
1692                }
1693                let helper_at = if helper_probe.activity.lock().unwrap_or_else(|e| e.into_inner()).walking {
1694                    request_deadline.unwrap_or(at)
1695                } else { at };
1696                let _deadline = DeadlineScope(HELPER_DEADLINE.with(|deadline| deadline.replace(Some(helper_at))));
1697                struct ActiveProbeScope(Option<Arc<Probe>>);
1698                impl Drop for ActiveProbeScope {
1699                    fn drop(&mut self) {
1700                        ACTIVE_PROBE.with(|probe| *probe.borrow_mut() = self.0.take());
1701                    }
1702                }
1703                let _active = ActiveProbeScope(ACTIVE_PROBE.with(|probe| probe.replace(Some(helper_probe.clone()))));
1704                helper_probe.activity.lock().unwrap_or_else(|e| e.into_inner()).progress = Some(started);
1705                #[cfg(any(test, feature = "test-support"))]
1706                regression_tests::after_helper_start(&owned);
1707                work(owned)
1708                })
1709            })();
1710            let _ = tx.send(result);
1711        }))?;
1712    #[cfg(any(test, feature = "test-support"))]
1713    if let Some(counts) = &measurements {
1714        counts.dispatches.fetch_add(1, Ordering::Relaxed);
1715    }
1716    let mut wait_until = queue_deadline.min(queued + access_budget);
1717    loop {
1718        match rx.recv_timeout(wait_until.saturating_duration_since(Instant::now())) {
1719            Ok(result) => {
1720                permit.reusable = true;
1721                return result;
1722            }
1723            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
1724                let state = probe.state.lock().unwrap_or_else(|e| e.into_inner());
1725                let Some(started) = state.started else {
1726                    // A mutation may wait for admission past one access cap.
1727                    // Look again at least once per cap, so a helper that
1728                    // starts late and then hangs still fails at its own
1729                    // access deadline instead of at the request deadline.
1730                    let now = Instant::now();
1731                    if now < queue_deadline {
1732                        wait_until = queue_deadline.min(now + access_budget);
1733                        continue;
1734                    }
1735                    return Err(failure(
1736                    path,
1737                    "read_io_queue_timeout",
1738                    "filesystem helper did not start before the deadline; this call did not start",
1739                ));
1740                };
1741                let mut at = state.deadline;
1742                drop(state);
1743                let activity = probe.activity.lock().unwrap_or_else(|e| e.into_inner());
1744                let access_started = if activity.walking {
1745                    activity.progress.unwrap_or(started)
1746                } else {
1747                    started
1748                };
1749                let stalled_at = access_started + access_budget;
1750                if activity.walking {
1751                    at = request_deadline.map_or(stalled_at, |deadline| deadline.min(stalled_at));
1752                }
1753                let blocked_path = activity.path.clone().unwrap_or_else(|| path.to_path_buf());
1754                let walk_deadline = activity.walking
1755                    && request_deadline.is_some_and(|deadline| deadline <= stalled_at);
1756                drop(activity);
1757                if Instant::now() < at {
1758                    wait_until = at;
1759                    continue;
1760                }
1761                if walk_deadline {
1762                    return Err(io::Error::new(
1763                        io::ErrorKind::TimedOut,
1764                        "walk deadline elapsed",
1765                    ));
1766                }
1767                let hint = if cfg!(target_os = "macos") {
1768                    "; on macOS, check ck-aft access in Privacy & Security, then retry"
1769                } else {
1770                    ""
1771                };
1772                return Err(failure(
1773                    &blocked_path,
1774                    "read_blocked",
1775                    &format!(
1776                        "OS access did not finish within {:.3} s{hint}",
1777                        at.saturating_duration_since(access_started).as_secs_f64()
1778                    ),
1779                ));
1780            }
1781            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
1782                return Err(io::Error::other("filesystem helper stopped"));
1783            }
1784        }
1785    }
1786}
1787fn directory(path: &Path, at: Option<Instant>) -> io::Result<Access> {
1788    let _reading = reading_path(path);
1789    if let Some(error) = prior_failure() {
1790        return Err(error);
1791    }
1792    let id = CURRENT.with(|current| current.borrow().as_ref().map(|b| b.id));
1793    if let Some(access) = DIRECTORIES.with(|dirs| {
1794        let dirs = dirs.borrow();
1795        (Some(dirs.0) == id)
1796            .then(|| dirs.1.get(path).copied())
1797            .flatten()
1798    }) {
1799        return Ok(access);
1800    }
1801    let budget = current().unwrap_or_else(|| Budget::after(IO_BUDGET));
1802    let (probe, owner) = {
1803        let mut dirs = budget.directories.lock().unwrap_or_else(|e| e.into_inner());
1804        match dirs.entry(path.to_path_buf()) {
1805            std::collections::hash_map::Entry::Occupied(entry) => (Arc::clone(entry.get()), false),
1806            std::collections::hash_map::Entry::Vacant(entry) => {
1807                let probe = Arc::new(Probe::queued(
1808                    at.map_or(budget.deadline, |at| at.min(budget.deadline)),
1809                ));
1810                entry.insert(Arc::clone(&probe));
1811                (probe, true)
1812            }
1813        }
1814    };
1815    let access = if owner {
1816        #[cfg(any(test, feature = "test-support"))]
1817        budget
1818            .measurements
1819            .directory_probes
1820            .fetch_add(1, Ordering::Relaxed);
1821        let result = run_with_timeout(
1822            path,
1823            at,
1824            Arc::clone(HELPERS.get_or_init(|| Limiter::new(IO_POOL_SIZE))),
1825            access_budget(path),
1826            Some(Arc::clone(&probe)),
1827            |path| {
1828                #[cfg(any(test, feature = "test-support"))]
1829                regression_tests::before_directory_probe(&path)?;
1830                #[cfg(all(any(test, feature = "test-support"), unix))]
1831                tests::before_directory_probe(&path)?;
1832                // Opening and advancing ReadDir probes consent, not just existence.
1833                let mut entries = std::fs::read_dir(&path)?;
1834                let _ = entries.next().transpose()?;
1835                let access = Access {
1836                    direct: local_filesystem(&path)?,
1837                };
1838                #[cfg(all(any(test, feature = "test-support"), unix))]
1839                tests::after_directory_probe(&path);
1840                Ok(access)
1841            },
1842        );
1843        let macos = cfg!(target_os = "macos");
1844        #[cfg(all(any(test, feature = "test-support"), unix))]
1845        let macos = macos || tests::macos_directory(path);
1846        observe_permission(path, &result, macos);
1847        let result = result.map_err(|error| ProbeError::from(&error));
1848        probe.state.lock().unwrap_or_else(|e| e.into_inner()).result = Some(result.clone());
1849        probe.ready.notify_all();
1850        result.map_err(|error| error.error())?
1851    } else {
1852        let request_deadline = request_deadline(at);
1853        let mut state = probe.state.lock().unwrap_or_else(|e| e.into_inner());
1854        while state.result.is_none() {
1855            // The owner may still be queued. Once it starts, all waiters follow
1856            // its new access deadline, without extending their own request.
1857            let at = request_deadline.map_or(state.deadline, |at| at.min(state.deadline));
1858            let remaining = at.saturating_duration_since(Instant::now());
1859            if remaining.is_zero() {
1860                let blocked = state.started.is_some() && at == state.deadline;
1861                return Err(failure(
1862                    path,
1863                    if blocked {
1864                        "read_blocked"
1865                    } else {
1866                        "read_io_queue_timeout"
1867                    },
1868                    if blocked {
1869                        "OS access deadline elapsed waiting for this directory's running probe"
1870                    } else {
1871                        "deadline elapsed waiting for this directory's shared probe"
1872                    },
1873                ));
1874            }
1875            state = probe
1876                .ready
1877                .wait_timeout(state, remaining)
1878                .unwrap_or_else(|e| e.into_inner())
1879                .0;
1880        }
1881        state
1882            .result
1883            .as_ref()
1884            .unwrap()
1885            .clone()
1886            .map_err(|error| error.error())?
1887    };
1888    DIRECTORIES.with(|dirs| {
1889        let mut dirs = dirs.borrow_mut();
1890        if dirs.0 != budget.id {
1891            dirs.0 = budget.id;
1892            dirs.1.clear();
1893        }
1894        dirs.1.insert(path.to_path_buf(), access);
1895    });
1896    Ok(access)
1897}
1898pub(crate) fn probe_directory(path: &Path, at: Option<Instant>) -> io::Result<()> {
1899    directory(path, at).map(|_| ())
1900}
1901
1902/// Only descendants discovered by a read-only walk are coverage gaps. The
1903/// starting folder and its ancestors still require a named access error.
1904pub fn probe_walk_directory(root: &Path, path: &Path) -> io::Result<()> {
1905    let budget = current().map(|mut budget| {
1906        budget.walk_root = Some(root.to_path_buf());
1907        budget
1908    });
1909    with_budget(budget, || probe_directory(path, None))
1910}
1911fn parent(path: &Path, at: Option<Instant>) -> io::Result<Access> {
1912    directory(
1913        path.parent()
1914            .filter(|p| !p.as_os_str().is_empty())
1915            .unwrap_or(Path::new(".")),
1916        at,
1917    )
1918}
1919fn cached_directory(path: &Path) -> Option<Access> {
1920    let id = CURRENT.with(|budget| budget.borrow().as_ref().map(|b| b.id))?;
1921    let local = DIRECTORIES.with(|dirs| {
1922        let dirs = dirs.borrow();
1923        (dirs.0 == id).then(|| dirs.1.get(path).copied()).flatten()
1924    });
1925    if local.is_some() {
1926        return local;
1927    }
1928    // Another thread of this request may already have probed the directory:
1929    // grep reads files on rayon workers, then stats every match again on the
1930    // thread that sorts the results. Reuse that finished probe, as
1931    // `directory` would, instead of spawning a helper per directory this
1932    // thread did not read itself. A probe still running is not waited for
1933    // here; callers then take their normal bounded path.
1934    let budget = current()?;
1935    let probe = budget
1936        .directories
1937        .lock()
1938        .unwrap_or_else(|e| e.into_inner())
1939        .get(path)
1940        .cloned()?;
1941    let access = match probe.state.lock().unwrap_or_else(|e| e.into_inner()).result {
1942        Some(Ok(access)) => access,
1943        _ => return None,
1944    };
1945    // Remember it on this thread too, so later files under the same
1946    // directory do not take the request-wide lock again.
1947    DIRECTORIES.with(|dirs| {
1948        let mut dirs = dirs.borrow_mut();
1949        if dirs.0 != budget.id {
1950            dirs.0 = budget.id;
1951            dirs.1.clear();
1952        }
1953        dirs.1.insert(path.to_path_buf(), access);
1954    });
1955    Some(access)
1956}
1957fn traversal_parent(path: &Path) -> Option<&Path> {
1958    path.parent().map(|parent| {
1959        if parent.as_os_str().is_empty() {
1960            Path::new(".")
1961        } else {
1962            parent
1963        }
1964    })
1965}
1966// A successful stat on a local filesystem permits sibling stats, not directory
1967// enumeration or file reads. Keep this weaker evidence out of the listing cache.
1968fn cached_traversal(path: &Path) -> bool {
1969    cached_directory(path).is_some_and(|access| access.direct)
1970        || CURRENT.with(|current| {
1971            current.borrow().as_ref().is_some_and(|budget| {
1972                budget
1973                    .traversable
1974                    .lock()
1975                    .unwrap_or_else(|e| e.into_inner())
1976                    .contains(path)
1977            })
1978        })
1979}
1980fn run_traversal<T: Send + 'static>(
1981    path: &Path,
1982    work: impl FnOnce(PathBuf) -> io::Result<T> + Send + 'static,
1983) -> io::Result<T> {
1984    #[cfg(any(test, feature = "test-support"))]
1985    if let Some(budget) = current() {
1986        budget
1987            .measurements
1988            .traversal_probes
1989            .fetch_add(1, Ordering::Relaxed);
1990    }
1991    let (result, traversable) = run(path, None, move |path| {
1992        let parent = traversal_parent(&path).map(Path::to_path_buf);
1993        let result = work(path)?;
1994        // Filesystem identification can itself block, so keep it in the helper.
1995        let traversable = parent.filter(|parent| local_filesystem(parent).unwrap_or(false));
1996        Ok((result, traversable))
1997    })?;
1998    // Publish only after the caller receives success, never from a late helper.
1999    if let (Some(parent), Some(budget)) = (traversable, current()) {
2000        budget
2001            .traversable
2002            .lock()
2003            .unwrap_or_else(|e| e.into_inner())
2004            .insert(parent);
2005    }
2006    Ok(result)
2007}
2008pub fn probe_target(path: &Path) -> io::Result<()> {
2009    if cached_directory(path).is_some() {
2010        return Ok(());
2011    }
2012    let metadata = if path
2013        .parent()
2014        .and_then(cached_directory)
2015        .is_some_and(|access| access.direct)
2016    {
2017        let metadata = std::fs::symlink_metadata(path)?;
2018        if metadata.file_type().is_symlink() {
2019            run(path, None, std::fs::metadata)?
2020        } else {
2021            metadata
2022        }
2023    } else {
2024        match run(path, None, std::fs::metadata) {
2025            Ok(metadata) => metadata,
2026            Err(error) => {
2027                if error.raw_os_error() == Some(1) {
2028                    let folder = permission_folder(path);
2029                    observe_permission(
2030                        &folder,
2031                        &Err(io::Error::from_raw_os_error(1)),
2032                        cfg!(target_os = "macos"),
2033                    );
2034                }
2035                return Err(error);
2036            }
2037        }
2038    };
2039    if metadata.is_dir() {
2040        directory(path, None)?;
2041    } else {
2042        parent(path, None)?;
2043    }
2044    Ok(())
2045}
2046// Only positively identified local filesystems are eligible for direct reads.
2047// Network/FUSE/unknown mounts stay bounded per file even after a successful
2048// directory probe; a mount that stops responding mid-request cannot park a root.
2049#[cfg(any(target_os = "macos", target_os = "linux"))]
2050fn local_filesystem(path: &Path) -> io::Result<bool> {
2051    #[cfg(target_os = "macos")]
2052    {
2053        let resolved = std::fs::canonicalize(path)?;
2054        let text = resolved.to_string_lossy();
2055        // Local APFS directory access does not guarantee a cloud placeholder's
2056        // contents are resident. Hydration may still block on first file read.
2057        if text.contains("/Library/Mobile Documents/") || text.contains("/Library/CloudStorage/") {
2058            return Ok(false);
2059        }
2060    }
2061    let path = std::ffi::CString::new(path.as_os_str().as_encoded_bytes())?;
2062    let mut stat = std::mem::MaybeUninit::<libc::statfs>::uninit();
2063    if unsafe { libc::statfs(path.as_ptr(), stat.as_mut_ptr()) } != 0 {
2064        return Err(io::Error::last_os_error());
2065    }
2066    let stat = unsafe { stat.assume_init() };
2067    #[cfg(target_os = "macos")]
2068    {
2069        let name = unsafe { std::ffi::CStr::from_ptr(stat.f_mntonname.as_ptr()) };
2070        Ok(
2071            stat.f_flags & libc::MNT_LOCAL as u32 != 0
2072                && !name.to_bytes().starts_with(b"/Volumes/"),
2073        )
2074    }
2075    #[cfg(target_os = "linux")]
2076    {
2077        Ok(matches!(
2078            stat.f_type as u64,
2079            0xEF53 | 0x58465342 | 0x9123683E | 0x01021994 | 0x794c7630 | 0x2FC12FC1
2080        ))
2081    }
2082}
2083#[cfg(not(any(target_os = "macos", target_os = "linux")))]
2084fn local_filesystem(_: &Path) -> io::Result<bool> {
2085    Ok(false)
2086}
2087
2088pub fn read(path: &Path, at: Option<Instant>) -> io::Result<Vec<u8>> {
2089    if Instant::now() >= deadline(at) {
2090        return Err(failure(
2091            path,
2092            "read_deadline_exceeded",
2093            "scan deadline elapsed before file access",
2094        ));
2095    }
2096    let access = parent(path, at)?;
2097    if !access.direct {
2098        return run(path, at, |path| regular_read(&path, false));
2099    }
2100    let metadata = std::fs::symlink_metadata(path)?;
2101    if metadata.file_type().is_symlink() {
2102        return run(path, at, |path| regular_read(&path, false));
2103    }
2104    if !metadata.is_file() {
2105        return Err(io::Error::new(
2106            io::ErrorKind::InvalidInput,
2107            "not a regular file",
2108        ));
2109    }
2110    match regular_read(path, true) {
2111        #[cfg(unix)]
2112        Err(error) if error.raw_os_error() == Some(libc::ELOOP) => {
2113            run(path, at, |path| regular_read(&path, false))
2114        }
2115        result => result,
2116    }
2117}
2118
2119/// A regular file whose chunk reads retain the same access checks and helper
2120/// deadlines as a whole-file read. The descriptor stays open between chunks.
2121pub struct Reader {
2122    path: PathBuf,
2123    file: Option<std::fs::File>,
2124    direct: bool,
2125    at: Option<Instant>,
2126    /// The opened descriptor's size, taken when it was opened.
2127    size_at_open: u64,
2128}
2129
2130pub fn reader(path: &Path, at: Option<Instant>) -> io::Result<Reader> {
2131    if Instant::now() >= deadline(at) {
2132        return Err(failure(
2133            path,
2134            "read_deadline_exceeded",
2135            "scan deadline elapsed before file access",
2136        ));
2137    }
2138    let access = parent(path, at)?;
2139    let metadata = access
2140        .direct
2141        .then(|| std::fs::symlink_metadata(path))
2142        .transpose()?;
2143    let direct = metadata
2144        .as_ref()
2145        .is_some_and(|metadata| !metadata.file_type().is_symlink());
2146    if direct && !metadata.as_ref().unwrap().is_file() {
2147        return Err(io::Error::new(
2148            io::ErrorKind::InvalidInput,
2149            "not a regular file",
2150        ));
2151    }
2152    let ((file, size_at_open), direct) = if direct {
2153        match regular_open_sized(path, true) {
2154            #[cfg(unix)]
2155            Err(error) if error.raw_os_error() == Some(libc::ELOOP) => (
2156                run(path, at, |path| regular_open_sized(&path, false))?,
2157                false,
2158            ),
2159            result => (result?, true),
2160        }
2161    } else {
2162        (
2163            run(path, at, |path| regular_open_sized(&path, false))?,
2164            false,
2165        )
2166    };
2167    Ok(Reader {
2168        path: path.to_path_buf(),
2169        file: Some(file),
2170        direct,
2171        at,
2172        size_at_open,
2173    })
2174}
2175
2176impl Reader {
2177    pub fn chunk(&mut self, mut buffer: Vec<u8>, size: usize) -> io::Result<Vec<u8>> {
2178        if Instant::now() >= deadline(self.at) {
2179            return Err(failure(
2180                &self.path,
2181                "read_deadline_exceeded",
2182                "scan deadline elapsed during file read",
2183            ));
2184        }
2185        let mut file = self
2186            .file
2187            .take()
2188            .ok_or_else(|| io::Error::other("file read already failed"))?;
2189        let read = move || {
2190            buffer.resize(size, 0);
2191            let mut count = 0;
2192            while count < buffer.len() {
2193                match file.read(&mut buffer[count..]) {
2194                    Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
2195                    Ok(0) => break,
2196                    result => count += result?,
2197                }
2198            }
2199            buffer.truncate(count);
2200            crate::io_accounting::WORK
2201                .content_read_bytes
2202                .fetch_add(count as u64, std::sync::atomic::Ordering::Relaxed);
2203            Ok((file, buffer))
2204        };
2205        let (file, buffer) = if self.direct {
2206            read()?
2207        } else {
2208            run(&self.path, self.at, move |_| read())?
2209        };
2210        self.file = Some(file);
2211        Ok(buffer)
2212    }
2213
2214    /// The file's size when it was opened. A large-file read stops there, so
2215    /// bytes a writer appends during the read are not read.
2216    pub fn size_at_open(&self) -> u64 {
2217        self.size_at_open
2218    }
2219
2220    /// Append at most `size` more bytes to `buffer`, reading until that many
2221    /// arrived or the file ended, with the same deadline and helper handling
2222    /// as [`Self::chunk`]. Unlike `chunk` it writes into spare capacity
2223    /// without zeroing it first.
2224    ///
2225    /// The buffer grows by at most `size` bytes: the reservation is exact, so
2226    /// it never doubles, and `read_to_end` through `take(size)` only fills
2227    /// the room already reserved. When that room is full it probes with a
2228    /// stack buffer before growing (std's `default_read_to_end`), and the
2229    /// probe of an exhausted `Take` reads nothing.
2230    pub fn append(&mut self, mut buffer: Vec<u8>, size: usize) -> io::Result<Vec<u8>> {
2231        if Instant::now() >= deadline(self.at) {
2232            return Err(failure(
2233                &self.path,
2234                "read_deadline_exceeded",
2235                "scan deadline elapsed during file read",
2236            ));
2237        }
2238        let mut file = self
2239            .file
2240            .take()
2241            .ok_or_else(|| io::Error::other("file read already failed"))?;
2242        let read = move || {
2243            let before = buffer.len();
2244            buffer.try_reserve_exact(size).map_err(io::Error::other)?;
2245            (&mut file).take(size as u64).read_to_end(&mut buffer)?;
2246            crate::io_accounting::WORK.content_read_bytes.fetch_add(
2247                (buffer.len() - before) as u64,
2248                std::sync::atomic::Ordering::Relaxed,
2249            );
2250            Ok((file, buffer))
2251        };
2252        let (file, buffer) = if self.direct {
2253            read()?
2254        } else {
2255            run(&self.path, self.at, move |_| read())?
2256        };
2257        self.file = Some(file);
2258        Ok(buffer)
2259    }
2260}
2261
2262fn regular_open(path: &Path, no_follow: bool) -> io::Result<std::fs::File> {
2263    regular_open_sized(path, no_follow).map(|(file, _)| file)
2264}
2265
2266/// Open project content without waiting for a FIFO writer. Judge the opened
2267/// handle so replacing an admitted path cannot bypass the regular-file check.
2268pub fn open_content_file(path: &Path) -> io::Result<std::fs::File> {
2269    open_content_file_sized(path, false).map(|(file, _)| file)
2270}
2271
2272/// Read UTF-8 project content with the same opened-handle requirement.
2273pub fn read_content_to_string(path: impl AsRef<Path>) -> io::Result<String> {
2274    std::io::read_to_string(open_content_file(path.as_ref())?)
2275}
2276
2277/// The same handle check without following a final symlink, for scratch reads.
2278pub(crate) fn open_content_file_no_follow(path: &Path) -> io::Result<std::fs::File> {
2279    open_content_file_sized(path, true).map(|(file, _)| file)
2280}
2281
2282fn open_content_file_sized(path: &Path, _no_follow: bool) -> io::Result<(std::fs::File, u64)> {
2283    let mut options = std::fs::OpenOptions::new();
2284    options.read(true);
2285    #[cfg(unix)]
2286    {
2287        use std::os::unix::fs::OpenOptionsExt;
2288        options.custom_flags(libc::O_NONBLOCK | if _no_follow { libc::O_NOFOLLOW } else { 0 });
2289    }
2290    let file = options.open(path)?;
2291    let metadata = file.metadata()?;
2292    if !metadata.is_file() {
2293        return Err(io::Error::new(
2294            io::ErrorKind::InvalidInput,
2295            "not a regular file",
2296        ));
2297    }
2298    Ok((file, metadata.len()))
2299}
2300
2301/// [`regular_open`], with the opened descriptor's size.
2302fn regular_open_sized(path: &Path, _no_follow: bool) -> io::Result<(std::fs::File, u64)> {
2303    if !_no_follow && !std::fs::metadata(path)?.is_file() {
2304        return Err(io::Error::new(
2305            io::ErrorKind::InvalidInput,
2306            "not a regular file",
2307        ));
2308    }
2309    #[cfg(all(any(test, feature = "test-support"), unix))]
2310    tests::before_regular_open(path)?;
2311    let scratch_check = crate::task_temp_reads::check_path(path)?;
2312    crate::io_accounting::WORK
2313        .content_reads
2314        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2315    let (file, size) = open_content_file_sized(path, _no_follow)?;
2316    crate::task_temp_reads::check_opened(path, scratch_check.as_ref(), &file)?;
2317    Ok((file, size))
2318}
2319
2320fn regular_read(path: &Path, no_follow: bool) -> io::Result<Vec<u8>> {
2321    let mut file = regular_open(path, no_follow)?;
2322    let metadata = file.metadata()?;
2323    let mut bytes = Vec::new();
2324    bytes
2325        .try_reserve(usize::try_from(metadata.len()).map_err(io::Error::other)?)
2326        .map_err(io::Error::other)?;
2327    file.read_to_end(&mut bytes)?;
2328    crate::io_accounting::WORK
2329        .content_read_bytes
2330        .fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed);
2331    Ok(bytes)
2332}
2333pub fn read_to_string(path: &Path) -> io::Result<String> {
2334    String::from_utf8(read(path, None)?)
2335        .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
2336}
2337pub fn canonicalize(path: &Path) -> io::Result<PathBuf> {
2338    if let Some(error) = prior_failure() {
2339        return Err(error);
2340    }
2341    if cached_directory(path).is_some_and(|access| access.direct) {
2342        return std::fs::canonicalize(path);
2343    }
2344    // Resolving a path needs traversal, not permission to enumerate its parent.
2345    // Reuse a known-safe parent, otherwise isolate only canonicalize itself.
2346    if traversal_parent(path).is_some_and(cached_traversal)
2347        && std::fs::symlink_metadata(path).is_ok_and(|m| !m.file_type().is_symlink())
2348    {
2349        std::fs::canonicalize(path)
2350    } else {
2351        run_traversal(path, std::fs::canonicalize)
2352    }
2353}
2354pub fn metadata(path: &Path) -> io::Result<std::fs::Metadata> {
2355    if let Some(error) = prior_failure() {
2356        return Err(error);
2357    }
2358    // A stat must not turn into an unrelated ancestor's directory listing.
2359    let direct = cached_directory(path).map_or_else(
2360        || cached_traversal(path) || traversal_parent(path).is_some_and(cached_traversal),
2361        |access| access.direct,
2362    );
2363    if direct {
2364        let metadata = std::fs::symlink_metadata(path)?;
2365        if !metadata.file_type().is_symlink() {
2366            return Ok(metadata);
2367        }
2368    }
2369    run_traversal(path, std::fs::metadata)
2370}
2371
2372#[cfg(any(test, feature = "test-support"))]
2373#[cfg_attr(not(test), allow(dead_code, unused_imports))]
2374#[path = "bounded_io_tests.rs"]
2375pub mod regression_tests;
2376#[cfg(all(any(test, feature = "test-support"), unix))]
2377pub use regression_tests::{stall_helper, stall_running_helper};
2378#[cfg(all(any(test, feature = "test-support"), unix))]
2379pub fn stall_helper_if_requested(path: &Path) {
2380    regression_tests::before_helper(path);
2381}
2382#[cfg(all(any(test, feature = "test-support"), unix))]
2383pub(crate) fn stall_running_helper_if_requested(path: &Path) {
2384    regression_tests::after_helper_start(path);
2385}
2386
2387#[cfg(all(any(test, feature = "test-support"), unix))]
2388#[cfg_attr(not(test), allow(dead_code, unused_imports))]
2389pub mod tests {
2390    use super::*;
2391
2392    #[test]
2393    fn carry_factory_errors_and_panics_refuse_work() {
2394        for phase in 0..4 {
2395            std::thread::spawn(move || {
2396                let factory: CarryFactory = Arc::new(move || match phase {
2397                    0 => Err(io::Error::other("injected capture failure")),
2398                    1 => panic!("injected capture panic"),
2399                    2 => Ok(Box::new(|| Err(io::Error::other("injected entry failure")))),
2400                    _ => Ok(Box::new(|| panic!("injected entry panic"))),
2401                });
2402                replace_carry_factory(Some(factory), Box::new(|| {}));
2403                let ran = Arc::new(AtomicBool::new(false));
2404                let called = ran.clone();
2405                let result = IsolatedPool::new(1).run(Path::new("carry"), None, move |_| {
2406                    called.store(true, Ordering::SeqCst);
2407                    Ok(())
2408                });
2409                assert_eq!(timeout_code(&result.unwrap_err()), "read_io_queue_timeout");
2410                assert!(!ran.load(Ordering::SeqCst));
2411                replace_carry_factory(None, Box::new(|| {}));
2412            })
2413            .join()
2414            .unwrap();
2415        }
2416    }
2417    use std::os::unix::fs::OpenOptionsExt;
2418
2419    static MACOS_DIRECTORIES: LazyLock<Mutex<HashMap<PathBuf, bool>>> =
2420        LazyLock::new(|| Mutex::new(HashMap::new()));
2421    pub struct MacosProbe(PathBuf);
2422    impl MacosProbe {
2423        pub fn allow(&self) {
2424            MACOS_DIRECTORIES
2425                .lock()
2426                .unwrap()
2427                .insert(self.0.clone(), true);
2428        }
2429    }
2430    impl Drop for MacosProbe {
2431        fn drop(&mut self) {
2432            MACOS_DIRECTORIES.lock().unwrap().remove(&self.0);
2433        }
2434    }
2435    pub fn deny_macos_directory(path: &Path) -> MacosProbe {
2436        let path = std::fs::canonicalize(path).unwrap();
2437        MACOS_DIRECTORIES
2438            .lock()
2439            .unwrap()
2440            .insert(path.clone(), false);
2441        MacosProbe(path)
2442    }
2443    pub(super) fn macos_directory(path: &Path) -> bool {
2444        MACOS_DIRECTORIES.lock().unwrap().contains_key(path)
2445    }
2446    static BLOCKERS: LazyLock<Mutex<HashMap<PathBuf, (PathBuf, Arc<AtomicUsize>)>>> =
2447        LazyLock::new(|| Mutex::new(HashMap::new()));
2448    static PROBE_FINISHERS: LazyLock<Mutex<HashMap<PathBuf, std::sync::mpsc::Sender<()>>>> =
2449        LazyLock::new(|| Mutex::new(HashMap::new()));
2450    static FIFO_REPLACEMENTS: LazyLock<
2451        Mutex<HashMap<PathBuf, (Arc<AtomicUsize>, std::sync::mpsc::Sender<()>)>>,
2452    > = LazyLock::new(|| Mutex::new(HashMap::new()));
2453    pub struct BlockProbe {
2454        keys: Vec<PathBuf>,
2455        pub fired: Arc<AtomicUsize>,
2456        pub finished: std::sync::mpsc::Receiver<()>,
2457    }
2458    impl Drop for BlockProbe {
2459        fn drop(&mut self) {
2460            let mut blockers = BLOCKERS.lock().unwrap();
2461            for key in &self.keys {
2462                blockers.remove(key);
2463                PROBE_FINISHERS.lock().unwrap().remove(key);
2464            }
2465        }
2466    }
2467    pub fn block_directory_probe(directory: &Path, fifo: &Path) -> BlockProbe {
2468        let mut keys = vec![
2469            directory.to_path_buf(),
2470            std::fs::canonicalize(directory).unwrap(),
2471        ];
2472        keys.dedup();
2473        let fired = Arc::new(AtomicUsize::new(0));
2474        let (sender, finished) = std::sync::mpsc::channel();
2475        let mut blockers = BLOCKERS.lock().unwrap();
2476        for key in &keys {
2477            blockers.insert(key.clone(), (fifo.to_path_buf(), Arc::clone(&fired)));
2478            PROBE_FINISHERS
2479                .lock()
2480                .unwrap()
2481                .insert(key.clone(), sender.clone());
2482        }
2483        BlockProbe {
2484            keys,
2485            fired,
2486            finished,
2487        }
2488    }
2489    pub(super) fn after_directory_probe(path: &Path) {
2490        if let Some(sender) = PROBE_FINISHERS.lock().unwrap().remove(path) {
2491            let _ = sender.send(());
2492        }
2493    }
2494    pub(super) fn before_directory_probe(directory: &Path) -> io::Result<()> {
2495        if MACOS_DIRECTORIES.lock().unwrap().get(directory) == Some(&false) {
2496            return Err(io::Error::from_raw_os_error(libc::EPERM));
2497        }
2498        let blocker = BLOCKERS.lock().unwrap().get(directory).cloned();
2499        if let Some((path, fired)) = blocker {
2500            fired.fetch_add(1, Ordering::Relaxed);
2501            let _file = std::fs::File::open(path)?;
2502        }
2503        Ok(())
2504    }
2505    pub(super) fn before_regular_open(path: &Path) -> io::Result<()> {
2506        note_open(path);
2507        let fired = FIFO_REPLACEMENTS.lock().unwrap().remove(path);
2508        if let Some((fired, reached)) = fired {
2509            std::fs::remove_file(path)?;
2510            fifo(path);
2511            fired.fetch_add(1, Ordering::Relaxed);
2512            let _ = reached.send(());
2513        }
2514        Ok(())
2515    }
2516    static OPEN_WATCHES: LazyLock<Mutex<HashMap<PathBuf, Arc<AtomicUsize>>>> =
2517        LazyLock::new(|| Mutex::new(HashMap::new()));
2518    /// Counts the opens of one file's contents while it is alive, so a test
2519    /// can prove a file was never read.
2520    pub struct OpenWatch {
2521        path: PathBuf,
2522        pub opens: Arc<AtomicUsize>,
2523    }
2524    impl Drop for OpenWatch {
2525        fn drop(&mut self) {
2526            OPEN_WATCHES.lock().unwrap().remove(&self.path);
2527        }
2528    }
2529    pub fn watch_opens(path: &Path) -> OpenWatch {
2530        let opens = Arc::new(AtomicUsize::new(0));
2531        OPEN_WATCHES
2532            .lock()
2533            .unwrap()
2534            .insert(path.to_path_buf(), Arc::clone(&opens));
2535        OpenWatch {
2536            path: path.to_path_buf(),
2537            opens,
2538        }
2539    }
2540    /// Record an open of `path`'s contents for an [`OpenWatch`] on it.
2541    pub fn note_open(path: &Path) {
2542        if let Some(opens) = OPEN_WATCHES.lock().unwrap().get(path) {
2543            opens.fetch_add(1, Ordering::Relaxed);
2544        }
2545    }
2546    pub fn fifo(path: &Path) {
2547        let path = std::ffi::CString::new(path.as_os_str().as_encoded_bytes()).unwrap();
2548        assert_eq!(unsafe { libc::mkfifo(path.as_ptr(), 0o600) }, 0);
2549    }
2550    pub fn release_fifo(path: &Path) {
2551        use std::io::Write;
2552        let mut file = std::fs::OpenOptions::new()
2553            .read(true)
2554            .write(true)
2555            .custom_flags(libc::O_NONBLOCK)
2556            .open(path)
2557            .unwrap();
2558        let _ = file.write_all(b"released\n");
2559    }
2560    #[test]
2561    fn blocked_open_returns_before_fifo_writer_arrives() {
2562        let dir = tempfile::tempdir().unwrap();
2563        let path = dir.path().join("blocked");
2564        fifo(&path);
2565        let (tx, rx) = std::sync::mpsc::channel();
2566        let input = path.clone();
2567        let thread = std::thread::spawn(move || {
2568            tx.send(run(
2569                &input,
2570                Some(Instant::now() + Duration::from_millis(80)),
2571                std::fs::read,
2572            ))
2573            .unwrap()
2574        });
2575        let before_writer = rx.recv_timeout(Duration::from_millis(800));
2576        release_fifo(&path);
2577        thread.join().unwrap();
2578        let error = before_writer
2579            .expect("read waited for a FIFO writer instead of its deadline")
2580            .unwrap_err();
2581        assert_eq!(error.kind(), io::ErrorKind::TimedOut);
2582        assert!(error.to_string().contains("read_blocked"));
2583    }
2584    #[test]
2585    fn sequential_probes_reuse_helper_threads() {
2586        let limiter = Limiter::new(4);
2587        let budget = Budget::after(Duration::from_secs(5));
2588        let mut threads = HashSet::new();
2589        with_budget(Some(budget.clone()), || {
2590            for _ in 0..40 {
2591                threads.insert(
2592                    run_with_limiter(Path::new("healthy"), None, limiter.clone(), |_| {
2593                        Ok(std::thread::current().id())
2594                    })
2595                    .unwrap(),
2596                );
2597            }
2598        });
2599        assert!(
2600            threads.len() <= 4,
2601            "spawned {} helpers for 40 sequential probes",
2602            threads.len()
2603        );
2604    }
2605
2606    #[test]
2607    fn timed_out_helper_is_replaced_without_delaying_later_probes() {
2608        let limiter = Limiter::new(1);
2609        let (release_tx, release_rx) = std::sync::mpsc::channel();
2610        let (started_tx, started_rx) = std::sync::mpsc::channel();
2611        let first_pool = limiter.clone();
2612        let first = std::thread::spawn(move || {
2613            run_with_limiter(
2614                Path::new("blocked"),
2615                Some(Instant::now() + Duration::from_millis(150)),
2616                first_pool,
2617                move |_| {
2618                    started_tx.send(()).unwrap();
2619                    release_rx.recv().unwrap();
2620                    Ok(())
2621                },
2622            )
2623        });
2624        started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
2625        let blocked = first.join().unwrap().unwrap_err();
2626        let before = Instant::now();
2627        let later = run_with_limiter(
2628            Path::new("healthy"),
2629            Some(before + Duration::from_millis(150)),
2630            limiter.clone(),
2631            |_| Ok(42),
2632        );
2633        let health = limiter.health();
2634        release_tx.send(()).unwrap();
2635        assert_eq!(timeout_code(&blocked), "read_blocked");
2636        assert_eq!(
2637            later.unwrap(),
2638            42,
2639            "a timed-out helper must not retain the healthy slot"
2640        );
2641        assert!(before.elapsed() < Duration::from_millis(300));
2642        assert_eq!(health["abandoned"], 1);
2643        assert_eq!(health["replacements_total"], 1);
2644        assert_eq!(health["spawned_total"], 2);
2645    }
2646
2647    #[test]
2648    fn abandoned_helper_cap_bounds_threads_and_recovers_after_release() {
2649        let pool = Limiter::with_limits(1, 2);
2650        let mut releases = Vec::new();
2651        for _ in 0..2 {
2652            let (release, blocked) = std::sync::mpsc::channel();
2653            releases.push(release);
2654            let error = run_with_limiter(
2655                Path::new("blocked"),
2656                Some(Instant::now() + Duration::from_millis(200)),
2657                pool.clone(),
2658                move |_| {
2659                    blocked.recv().unwrap();
2660                    Ok(())
2661                },
2662            )
2663            .unwrap_err();
2664            assert_eq!(timeout_code(&error), "read_blocked");
2665        }
2666        let fired = Arc::new(AtomicBool::new(false));
2667        let work_fired = fired.clone();
2668        let before = Instant::now();
2669        let error = run_with_limiter(
2670            Path::new("queued"),
2671            Some(before + Duration::from_millis(80)),
2672            pool.clone(),
2673            move |_| {
2674                work_fired.store(true, Ordering::Relaxed);
2675                Ok(())
2676            },
2677        )
2678        .unwrap_err();
2679        let health = pool.health();
2680        for release in releases {
2681            release.send(()).unwrap();
2682        }
2683        assert_eq!(timeout_code(&error), "read_io_queue_timeout");
2684        assert!(!fired.load(Ordering::Relaxed));
2685        assert!(before.elapsed() < Duration::from_millis(300));
2686        assert_eq!(health["live"], 2);
2687        assert_eq!(health["abandoned"], 2);
2688        assert_eq!(health["spawned_total"], 2);
2689        assert_eq!(health["replacements_total"], 1);
2690        assert_eq!(health["cap_hits_total"], 1);
2691        assert_eq!(health["queue_timeouts_total"], 1);
2692        run_with_limiter(
2693            Path::new("recovered"),
2694            Some(Instant::now() + Duration::from_secs(2)),
2695            pool,
2696            |_| Ok(()),
2697        )
2698        .unwrap();
2699    }
2700
2701    #[test]
2702    fn reused_helper_resets_deadline_and_request_context() {
2703        let pool = Limiter::new(1);
2704        let first = Budget::after(IO_BUDGET);
2705        let first_id = first.id;
2706        with_budget(Some(first), || {
2707            run_with_limiter(Path::new("first"), None, pool.clone(), move |_| {
2708                assert_eq!(current().unwrap().id, first_id);
2709                assert!(HELPER_DEADLINE.with(|at| at.get()).is_some());
2710                Ok(())
2711            })
2712        })
2713        .unwrap();
2714        let mut permit = pool.acquire(Instant::now() + IO_BUDGET).unwrap();
2715        let (tx, rx) = std::sync::mpsc::channel();
2716        permit
2717            .send(Box::new(move || {
2718                tx.send((
2719                    current().is_none(),
2720                    HELPER_DEADLINE.with(|at| at.get()).is_none(),
2721                ))
2722                .unwrap();
2723            }))
2724            .unwrap();
2725        let (request_cleared, deadline_cleared) = rx.recv_timeout(IO_BUDGET).unwrap();
2726        permit.reusable = true;
2727        assert!(
2728            request_cleared,
2729            "a reused helper retained the previous request"
2730        );
2731        assert!(
2732            deadline_cleared,
2733            "a reused helper retained the previous deadline"
2734        );
2735    }
2736
2737    #[test]
2738    fn saturation_waits_for_a_healthy_helper_instead_of_claiming_blocked_access() {
2739        let limiter = Limiter::new(1);
2740        let (started_tx, started_rx) = std::sync::mpsc::channel();
2741        let (release_tx, release_rx) = std::sync::mpsc::channel();
2742        let first_limiter = Arc::clone(&limiter);
2743        let first = std::thread::spawn(move || {
2744            run_with_limiter(Path::new("first"), None, first_limiter, move |_| {
2745                started_tx.send(()).unwrap();
2746                release_rx.recv().unwrap();
2747                Ok(1)
2748            })
2749        });
2750        started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
2751        let (tx, rx) = std::sync::mpsc::channel();
2752        let second = std::thread::spawn(move || {
2753            tx.send(run_with_limiter(Path::new("second"), None, limiter, |_| {
2754                Ok(2)
2755            }))
2756            .unwrap()
2757        });
2758        assert!(rx.recv_timeout(Duration::from_millis(30)).is_err());
2759        release_tx.send(()).unwrap();
2760        assert_eq!(first.join().unwrap().unwrap(), 1);
2761        assert_eq!(rx.recv_timeout(Duration::from_secs(2)).unwrap().unwrap(), 2);
2762        second.join().unwrap();
2763    }
2764    #[test]
2765    fn saturation_deadline_is_queue_timeout_not_read_blocked() {
2766        let limiter = Limiter::new(1);
2767        let permit = limiter
2768            .acquire(Instant::now() + Duration::from_secs(1))
2769            .unwrap();
2770        let fired = Arc::new(AtomicUsize::new(0));
2771        let work_fired = Arc::clone(&fired);
2772        let budget = Budget::after(Duration::from_millis(80));
2773        let error = with_budget(Some(budget.clone()), || {
2774            run_with_limiter(Path::new("queued"), None, limiter, move |_| {
2775                work_fired.fetch_add(1, Ordering::Relaxed);
2776                Ok(())
2777            })
2778        })
2779        .unwrap_err();
2780        drop(permit);
2781        assert!(error.to_string().contains("read_io_queue_timeout"));
2782        assert!(!error.to_string().contains("read_blocked"));
2783        assert_eq!(fired.load(Ordering::Relaxed), 0);
2784        assert_eq!(
2785            budget.failure.lock().unwrap().as_ref().unwrap().code,
2786            "read_io_queue_timeout"
2787        );
2788    }
2789    #[test]
2790    fn accessible_directory_never_opens_a_fifo_as_a_file() {
2791        let dir = tempfile::tempdir().unwrap();
2792        let path = dir.path().join("fifo");
2793        fifo(&path);
2794        let error = with_budget(Some(Budget::after(IO_BUDGET)), || read(&path, None)).unwrap_err();
2795        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
2796    }
2797    #[test]
2798    fn fifo_replacement_after_admission_cannot_block_direct_open() {
2799        let dir = tempfile::tempdir().unwrap();
2800        let path = dir.path().join("regular.txt");
2801        std::fs::write(&path, "regular\n").unwrap();
2802        let fired = Arc::new(AtomicUsize::new(0));
2803        let (reached_tx, reached_rx) = std::sync::mpsc::channel();
2804        FIFO_REPLACEMENTS
2805            .lock()
2806            .unwrap()
2807            .insert(path.clone(), (Arc::clone(&fired), reached_tx));
2808        let input = path.clone();
2809        let (tx, rx) = std::sync::mpsc::channel();
2810        let thread = std::thread::spawn(move || tx.send(read(&input, None)).unwrap());
2811        let reached = reached_rx.recv_timeout(IO_BUDGET + Duration::from_secs(1));
2812        let before_writer = rx.recv_timeout(Duration::from_millis(800));
2813        if fired.load(Ordering::Relaxed) > 0 {
2814            release_fifo(&path);
2815        }
2816        thread.join().unwrap();
2817        reached.expect("the replacement must happen after file admission");
2818        let error = before_writer
2819            .expect("a FIFO replacement blocked the direct open")
2820            .unwrap_err();
2821        assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
2822        assert_eq!(fired.load(Ordering::Relaxed), 1);
2823    }
2824}
2825
2826#[cfg(all(test, unix))]
2827mod modes_macos_tests {
2828    use super::*;
2829
2830    #[test]
2831    fn macos_permission_observation_preserves_eperm_and_named_folder() {
2832        let dir = tempfile::tempdir().unwrap();
2833        let budget = Budget::after(IO_BUDGET);
2834        let _scope = enter(Some(budget.clone()));
2835        let error = ProbeError::from(&io::Error::from_raw_os_error(libc::EPERM));
2836        assert_eq!(error.error().raw_os_error(), Some(libc::EPERM));
2837        observe_permission(dir.path(), &Err(error.error()), true);
2838        let response = finish_response(Response::success("probe", serde_json::json!({})));
2839        assert_eq!(response.data["code"], "macos_permission_denied");
2840        assert_eq!(response.data["folder"], serde_json::json!(dir.path()));
2841        assert_eq!(response.data["program"], "ck-aft");
2842        assert_eq!(budget.permissions().len(), 1);
2843        let non_macos = Budget::after(IO_BUDGET);
2844        let _scope = enter(Some(non_macos.clone()));
2845        observe_permission(dir.path(), &Err(error.error()), false);
2846        assert!(non_macos.permissions().is_empty());
2847    }
2848}
2849
2850#[cfg(test)]
2851mod probe_target_tests {
2852    use super::*;
2853
2854    #[test]
2855    fn windows_invalid_glob_name_probes_ancestors_but_access_denial_does_not() {
2856        let invalid_name = io::Error::from_raw_os_error(123);
2857        let glob = Path::new(r"C:\project\*.txt");
2858        assert!(missing_probe_target(&invalid_name, glob, true));
2859        assert!(!missing_probe_target(&invalid_name, glob, false));
2860        assert!(!missing_probe_target(
2861            &invalid_name,
2862            Path::new(r"C:\project\file.txt"),
2863            true
2864        ));
2865        assert!(!missing_probe_target(
2866            &io::Error::from_raw_os_error(5),
2867            glob,
2868            true
2869        ));
2870        assert!(missing_probe_target(
2871            &io::Error::new(io::ErrorKind::NotFound, "missing"),
2872            glob,
2873            true
2874        ));
2875    }
2876}