aft-base 0.67.1

Shared foundation for Agent Foundational Toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
use super::*;

#[test]
fn stage2_disclosure_scope_has_no_deadline_or_sticky_read_failure() {
    let root = tempfile::tempdir().unwrap();
    let _scope = enter_disclosure_if_absent();
    assert!(current().is_none());
    assert!(request_deadline(None).is_none());
    let id = capture().unwrap().id;
    {
        let _nested = enter_disclosure_if_absent();
        assert_eq!(capture().unwrap().id, id);
    }
    let _error = failure(&root.path().join("absent"), "read_blocked", "test failure");
    assert!(prior_failure().is_none());
    let context = capture();
    rayon::join(
        || {
            with_budget(context.clone(), || {
                note_large_read_skip(&root.path().join("large.txt"))
            })
        },
        || {},
    );
    let response = with_skip_disclosure(|| {
        finish_response(Response::success(
            "native",
            serde_json::json!({"complete":true}),
        ))
    });
    assert!(response.success);
    assert_eq!(response.data["complete"], false);
    assert_eq!(response.data["skipped_files"].as_array().unwrap().len(), 1);
}

#[test]
fn stage2_skip_disclosure_is_sorted_bounded_deduplicated_and_non_failing() {
    let root = tempfile::tempdir().unwrap();
    let readable = root.path().join("readable.txt");
    std::fs::write(&readable, b"still readable").unwrap();
    let response = with_budget(Some(Budget::after(Duration::from_secs(30))), || {
        for at in (0..23).rev() {
            let path = root.path().join(format!("large-{at:02}.txt"));
            note_large_read_skip(&path);
            note_large_read_skip(&path);
        }
        assert_eq!(read(&readable, None).unwrap(), b"still readable");
        with_skip_disclosure(|| {
            finish_response(Response::success(
                "skips",
                serde_json::json!({"complete":true,"text":"results"}),
            ))
        })
    });
    assert!(response.success);
    assert_eq!(response.data["complete"], false);
    let skips = response.data["skipped_files"].as_array().unwrap();
    assert_eq!(skips.len(), 20);
    assert!(skips[0]["file"].as_str().unwrap().ends_with("large-00.txt"));
    assert!(skips[19]["file"]
        .as_str()
        .unwrap()
        .ends_with("large-19.txt"));
    assert_eq!(response.data["skipped_files_remaining"], 3);
    assert!(response.data["text"]
        .as_str()
        .unwrap()
        .contains("shown 20 of 23 files (cap) ยท narrow: path"));
}
use std::sync::mpsc::{channel, Receiver, Sender};

struct HelperGate {
    reached: Sender<()>,
    release: Receiver<()>,
    finished: Sender<()>,
}

static HELPER_GATES: LazyLock<Mutex<HashMap<PathBuf, HelperGate>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));
static RUNNING_GATES: LazyLock<Mutex<HashMap<PathBuf, HelperGate>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

#[cfg(unix)]
pub struct HelperStall {
    path: PathBuf,
    gates: &'static Mutex<HashMap<PathBuf, HelperGate>>,
    pub reached: Receiver<()>,
    release: Sender<()>,
    finished: Receiver<()>,
}

#[cfg(unix)]
impl Drop for HelperStall {
    fn drop(&mut self) {
        self.gates.lock().unwrap().remove(&self.path);
        if self.release.send(()).is_ok() {
            let _ = self.finished.recv_timeout(IO_BUDGET);
        }
    }
}

#[cfg(unix)]
pub fn stall_helper(path: &Path) -> HelperStall {
    stall_helper_at(path, &HELPER_GATES)
}

#[cfg(unix)]
pub fn stall_running_helper(path: &Path) -> HelperStall {
    stall_helper_at(path, &RUNNING_GATES)
}

#[cfg(unix)]
fn stall_helper_at(
    path: &Path,
    gates: &'static Mutex<HashMap<PathBuf, HelperGate>>,
) -> HelperStall {
    let (reached, reached_rx) = channel();
    let (release, release_rx) = channel();
    let (finished, finished_rx) = channel();
    gates.lock().unwrap().insert(
        path.to_path_buf(),
        HelperGate {
            reached,
            release: release_rx,
            finished,
        },
    );
    HelperStall {
        path: path.to_path_buf(),
        gates,
        reached: reached_rx,
        release,
        finished: finished_rx,
    }
}

static BLOCKED_DIRECTORIES: LazyLock<Mutex<HashMap<PathBuf, Arc<AtomicUsize>>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

pub(super) fn before_helper(path: &Path) {
    wait_at_gate(path, &HELPER_GATES);
}

pub(super) fn after_helper_start(path: &Path) {
    wait_at_gate(path, &RUNNING_GATES);
}

fn wait_at_gate(path: &Path, gates: &Mutex<HashMap<PathBuf, HelperGate>>) {
    let gate = gates.lock().unwrap().remove(path);
    if let Some(gate) = gate {
        let _ = gate.reached.send(());
        let _ = gate.release.recv();
        let _ = gate.finished.send(());
    }
}

pub(super) fn before_directory_probe(path: &Path) -> io::Result<()> {
    wait_at_gate(path, &RUNNING_GATES);
    if let Some(fired) = BLOCKED_DIRECTORIES.lock().unwrap().get(path) {
        fired.fetch_add(1, Ordering::Relaxed);
        return Err(failure(
            path,
            "read_blocked",
            "injected stalled directory enumeration",
        ));
    }
    Ok(())
}

#[cfg(unix)]
#[test]
fn walk_filter_stall_names_directory_being_read() {
    let dir = tempfile::tempdir().unwrap();
    let child = dir.path().join("child");
    std::fs::create_dir(&child).unwrap();
    let stall = stall_running_helper(&child);
    let budget =
        Budget::after(Duration::from_secs(5)).with_access_budget(Duration::from_millis(200));
    let child_in_walk = child.clone();
    let error = with_budget(Some(budget), || {
        run(dir.path(), None, move |_| {
            probe_directory(&child_in_walk, None)
        })
    })
    .unwrap_err();
    stall.reached.recv_timeout(Duration::from_secs(1)).unwrap();
    assert!(
        error
            .to_string()
            .contains(&format!("read_blocked: {}:", child.display())),
        "{error}"
    );
}

pub struct BlockDirectory(PathBuf, pub Arc<AtomicUsize>);

impl BlockDirectory {
    pub fn new(path: &Path) -> Self {
        let fired = Arc::new(AtomicUsize::new(0));
        BLOCKED_DIRECTORIES
            .lock()
            .unwrap()
            .insert(path.to_path_buf(), Arc::clone(&fired));
        Self(path.to_path_buf(), fired)
    }
}

impl Drop for BlockDirectory {
    fn drop(&mut self) {
        BLOCKED_DIRECTORIES.lock().unwrap().remove(&self.0);
    }
}

#[cfg(unix)]
#[test]
fn walk_read_block_and_time_budget_report_both_gaps() {
    let dir = tempfile::tempdir().unwrap();
    let keep = dir.path().join("keep.rs");
    let child = dir.path().join("child");
    std::fs::write(&keep, "fn keep() {}\n").unwrap();
    std::fs::create_dir(&child).unwrap();
    let blocked = BlockDirectory::new(&child);
    let after_error = dir.path().join("after-directory-error");
    let stall = stall_running_helper(&after_error);
    let kept = keep.clone();
    let blocked_child = child.clone();
    let budget = Budget::after(Duration::from_secs(5)).with_access_budget(Duration::from_secs(2));
    let response = with_budget(Some(budget), || {
        let (files, completion) = run_walk(
            dir.path(),
            Some(Instant::now() + Duration::from_millis(300)),
            Vec::<PathBuf>::new(),
            move |_, progress| {
                progress.update(|files| files.push(kept.clone()));
                let error = probe_directory(&blocked_child, None).unwrap_err();
                assert!(error.to_string().contains("read_blocked"));
                // Keep the same walk alive after its injected directory failure
                // until the caller's walk deadline expires.
                after_helper_start(&after_error);
                Ok(vec![kept])
            },
        );
        assert!(completion.incomplete);
        assert!(completion.time_limit);
        finish_response(Response::success(
            "walk-both-gaps",
            serde_json::json!({
                "complete": true, "files": files,
            }),
        ))
    });
    stall.reached.recv_timeout(Duration::from_secs(1)).unwrap();
    assert_eq!(blocked.1.load(Ordering::Relaxed), 1);
    assert!(response.success, "{:?}", response.data);
    assert_eq!(response.data["complete"], false);
    assert_eq!(response.data["files"], serde_json::json!([keep]));
    let gaps = response.data["gaps"].as_array().unwrap();
    assert_eq!(gaps.len(), 2);
    assert_eq!(
        gaps[0],
        "Directory walk reached its time budget; only examined entries are reported."
    );
    let named_gap = format!("read_blocked: {}:", child.display());
    assert!(gaps[1].as_str().unwrap().starts_with(&named_gap));
    let text = response.data["text"].as_str().unwrap();
    assert!(text.lines().any(|line| line
        == "Directory walk reached its time budget; only examined entries are reported."));
    assert!(text.contains(&named_gap));
}

#[test]
fn walk_directory_probes_reuse_the_owned_helper() {
    let dir = tempfile::tempdir().unwrap();
    let child = dir.path().join("child");
    std::fs::create_dir(&child).unwrap();
    let budget =
        Budget::after(Duration::from_secs(5)).with_access_budget(Duration::from_millis(200));
    with_budget(Some(budget.clone()), || {
        let (_, completion) = run_walk(dir.path(), None, 0usize, move |_, progress| {
            probe_directory(&child, None)?;
            progress.update(|count| *count += 1);
            Ok(1)
        });
        assert!(!completion.incomplete);
    });
    assert_eq!(
        budget.measurements().0,
        1,
        "a walk must not queue a nested helper"
    );
}

#[test]
fn helper_health_does_not_start_an_unused_pool() {
    let helpers = OnceLock::new();
    let health = helper_health_from(&helpers);
    assert_eq!(health["status"], "not_started");
    assert_eq!(health["pool_size"], IO_POOL_SIZE);
    assert_eq!(health["thread_cap"], MAX_IO_THREADS);
    assert_eq!(health["live"], 0);
    assert!(helpers.get().is_none(), "health started the helper factory");
}

#[test]
fn helper_health_does_not_wait_for_the_state_lock() {
    let pool = Limiter::new(1);
    let state = pool.state.lock().unwrap();
    let reader = pool.clone();
    let (tx, rx) = channel();
    let thread = std::thread::spawn(move || tx.send(reader.health()).unwrap());
    let health = rx.recv_timeout(Duration::from_secs(1));
    drop(state);
    thread.join().unwrap();
    let health = health.expect("health waited for the helper state lock");
    assert_eq!(health["status"], "unavailable");
    assert_eq!(health["reason"], "state_busy");
    assert!(
        health.get("live").is_none(),
        "unavailable counts are unknown"
    );
    assert_eq!(pool.health()["status"], "ready");
}

#[test]
fn metadata_and_canonicalize_do_not_enumerate_an_ancestor() {
    let dir = tempfile::tempdir().unwrap();
    let ancestor = std::fs::canonicalize(dir.path()).unwrap();
    let root = ancestor.join("project");
    std::fs::create_dir(&root).unwrap();
    let blocked = BlockDirectory::new(&ancestor);
    assert!(
        with_budget(Some(Budget::after(IO_BUDGET)), || metadata(&root))
            .unwrap()
            .is_dir()
    );
    let resolved = with_budget(Some(Budget::after(IO_BUDGET)), || canonicalize(&root)).unwrap();
    assert_eq!(resolved, std::fs::canonicalize(&root).unwrap());
    assert_eq!(blocked.1.load(Ordering::Relaxed), 0);
}

// Only macOS and Linux currently identify local filesystems for direct access;
// Windows and unknown mounts retain per-file helper isolation.
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[test]
fn sibling_metadata_reuses_traversal_without_granting_listing_access() {
    let dir = tempfile::tempdir().unwrap();
    let root = std::fs::canonicalize(dir.path()).unwrap();
    assert!(local_filesystem(&root).unwrap());
    let paths: Vec<_> = (0..8).map(|n| root.join(format!("file-{n}"))).collect();
    for path in &paths {
        std::fs::write(path, "sibling").unwrap();
    }
    let blocked = BlockDirectory::new(&root);
    let budget = Budget::after(IO_BUDGET);
    with_budget(Some(budget.clone()), || {
        for path in &paths {
            assert!(metadata(path).unwrap().is_file());
        }
        assert_eq!(budget.measurements(), (1, 1), "one cold stat helper");
        assert_eq!(blocked.1.load(Ordering::Relaxed), 0);
        let error = read(&paths[0], None).unwrap_err();
        assert!(error.to_string().contains("read_blocked"), "{error}");
        assert_eq!(blocked.1.load(Ordering::Relaxed), 1);
        assert_eq!(
            budget.measurements(),
            (2, 2),
            "reading still probes the parent"
        );
    });
}

#[cfg(any(target_os = "macos", target_os = "linux"))]
#[test]
fn canonicalize_warms_sibling_traversal_shared_only_within_the_request() {
    let dir = tempfile::tempdir().unwrap();
    let root = std::fs::canonicalize(dir.path()).unwrap();
    assert!(local_filesystem(&root).unwrap());
    let first = root.join("first");
    let second = root.join("second");
    std::fs::write(&first, "first").unwrap();
    std::fs::write(&second, "second").unwrap();
    let blocked = BlockDirectory::new(&root);
    let budget = Budget::after(IO_BUDGET);
    with_budget(Some(budget.clone()), || {
        assert_eq!(canonicalize(&first).unwrap(), first);
        assert_eq!(canonicalize(&second).unwrap(), second);
        let worker_budget = budget.clone();
        let worker_path = second.clone();
        std::thread::spawn(move || {
            with_budget(Some(worker_budget), || {
                assert!(metadata(&worker_path).unwrap().is_file());
            });
        })
        .join()
        .unwrap();
        assert_eq!(budget.measurements(), (1, 1));
    });
    assert!(!cached_traversal(&root), "no evidence outside the request");
    let fresh_budget = Budget::after(IO_BUDGET);
    with_budget(Some(fresh_budget.clone()), || {
        assert!(metadata(&second).unwrap().is_file());
        assert_eq!(
            fresh_budget.measurements(),
            (1, 1),
            "a new request probes again"
        );
    });
    assert_eq!(blocked.1.load(Ordering::Relaxed), 0);
}

// A directory probed by one thread of a request answers a stat below it on any
// other thread of the same request. Grep reads files on rayon workers, then
// stats every matched file again on the thread that sorts the results; that
// thread must not spawn a helper per directory it did not read itself.
#[cfg(any(target_os = "macos", target_os = "linux"))]
#[test]
fn directory_probed_on_another_thread_answers_child_metadata() {
    let dir = tempfile::tempdir().unwrap();
    let root = std::fs::canonicalize(dir.path()).unwrap();
    assert!(local_filesystem(&root).unwrap());
    let file = root.join("file");
    std::fs::write(&file, "contents").unwrap();
    let budget = Budget::after(IO_BUDGET);
    let worker_budget = budget.clone();
    let worker_root = root.clone();
    std::thread::spawn(move || {
        with_budget(Some(worker_budget), || {
            probe_directory(&worker_root, None).unwrap();
        });
    })
    .join()
    .unwrap();
    assert_eq!(budget.measurements(), (1, 1), "one directory probe");
    with_budget(Some(budget.clone()), || {
        assert!(metadata(&file).unwrap().is_file());
        assert!(canonicalize(&root).is_ok());
        assert!(probe_target(&root).is_ok());
    });
    assert_eq!(
        budget.measurements(),
        (1, 1),
        "the request's finished directory probe must be reused on every thread"
    );
    // A new request does not inherit that probe.
    let fresh_budget = Budget::after(IO_BUDGET);
    with_budget(Some(fresh_budget.clone()), || {
        assert!(metadata(&file).unwrap().is_file());
    });
    assert_eq!(fresh_budget.measurements(), (1, 1));
}

#[test]
fn failed_stats_do_not_warm_traversal() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("missing");
    let budget = Budget::after(IO_BUDGET);
    with_budget(Some(budget.clone()), || {
        assert_eq!(metadata(&path).unwrap_err().kind(), io::ErrorKind::NotFound);
        assert_eq!(
            canonicalize(&path).unwrap_err().kind(),
            io::ErrorKind::NotFound
        );
        assert!(!cached_traversal(dir.path()));
        assert_eq!(budget.measurements(), (2, 2));
        std::fs::write(&path, "now present").unwrap();
        assert!(metadata(&path).unwrap().is_file());
        assert_eq!(budget.measurements(), (3, 3));
    });
}

#[test]
fn traversal_does_not_answer_an_explicit_directory_access_probe() {
    let dir = tempfile::tempdir().unwrap();
    let root = std::fs::canonicalize(dir.path()).unwrap();
    let path = root.join("file");
    std::fs::write(&path, "contents").unwrap();
    let blocked = BlockDirectory::new(&root);
    with_budget(Some(Budget::after(IO_BUDGET)), || {
        assert!(metadata(&path).unwrap().is_file());
        let error = probe_target(&root).unwrap_err();
        assert!(error.to_string().contains("read_blocked"), "{error}");
        assert_eq!(blocked.1.load(Ordering::Relaxed), 1);
    });
}

#[test]
fn timed_out_traversal_does_not_publish_late_success() {
    let dir = tempfile::tempdir().unwrap();
    let root = std::fs::canonicalize(dir.path()).unwrap();
    let path = root.join("file");
    std::fs::write(&path, "contents").unwrap();
    let budget = Budget::after(Duration::from_millis(250));
    let caller_budget = budget.clone();
    let (started_tx, started_rx) = channel();
    let (release_tx, release_rx) = channel();
    let (finished_tx, finished_rx) = channel();
    struct Finished(Sender<()>);
    impl Drop for Finished {
        fn drop(&mut self) {
            let _ = self.0.send(());
        }
    }
    let caller = std::thread::spawn(move || {
        with_budget(Some(caller_budget), || {
            run_traversal(&path, move |path| {
                let result = std::fs::metadata(path)?;
                started_tx.send(()).unwrap();
                let _ = release_rx.recv();
                Ok((result, Finished(finished_tx)))
            })
            .err()
            .unwrap()
        })
    });
    let started = started_rx.recv_timeout(IO_BUDGET);
    let error = caller.join().unwrap();
    release_tx.send(()).unwrap();
    finished_rx.recv_timeout(IO_BUDGET).unwrap();
    started.expect("the stat must finish before holding its result past the deadline");
    assert_eq!(error.kind(), io::ErrorKind::TimedOut);
    assert_eq!(timeout_code(&error), "read_blocked");
    with_budget(Some(budget), || assert!(!cached_traversal(&root)));
}

#[cfg(unix)]
#[test]
fn traversal_keeps_symlink_stats_isolated() {
    let dir = tempfile::tempdir().unwrap();
    let root = std::fs::canonicalize(dir.path()).unwrap();
    let file = root.join("file");
    let link = root.join("link");
    std::fs::write(&file, "contents").unwrap();
    std::os::unix::fs::symlink(&file, &link).unwrap();
    let budget = Budget::after(IO_BUDGET);
    with_budget(Some(budget.clone()), || {
        assert!(metadata(&file).unwrap().is_file());
        assert!(metadata(&link).unwrap().is_file());
        assert_eq!(canonicalize(&link).unwrap(), file);
        assert_eq!(budget.measurements(), (3, 3));
    });
}

#[test]
fn explicit_directory_probe_still_observes_blocked_access() {
    let dir = tempfile::tempdir().unwrap();
    let blocked = BlockDirectory::new(dir.path());
    let error = with_budget(Some(Budget::after(IO_BUDGET)), || {
        probe_directory(dir.path(), None)
    })
    .unwrap_err();
    assert!(error.to_string().contains("read_blocked"));
    assert_eq!(blocked.1.load(Ordering::Relaxed), 1);
}

#[test]
fn unscheduled_helper_is_queue_timeout_and_never_runs_late() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("unscheduled");
    let (reached_tx, reached_rx) = channel();
    let (release_tx, release_rx) = channel();
    let (finished_tx, finished_rx) = channel();
    HELPER_GATES.lock().unwrap().insert(
        path.clone(),
        HelperGate {
            reached: reached_tx,
            release: release_rx,
            finished: finished_tx,
        },
    );
    let fired = Arc::new(AtomicUsize::new(0));
    let work_fired = Arc::clone(&fired);
    let (dropped_tx, dropped_rx) = channel();
    struct Dropped(Sender<()>);
    impl Drop for Dropped {
        fn drop(&mut self) {
            let _ = self.0.send(());
        }
    }
    let dropped = Dropped(dropped_tx);
    let caller = std::thread::spawn(move || {
        run_with_limiter(
            &path,
            Some(Instant::now() + Duration::from_millis(80)),
            Limiter::new(1),
            move |_| {
                let _dropped = dropped;
                work_fired.fetch_add(1, Ordering::Relaxed);
                Ok(())
            },
        )
    });
    let reached = reached_rx.recv_timeout(IO_BUDGET);
    let error = caller.join().unwrap().unwrap_err();
    release_tx.send(()).unwrap();
    finished_rx.recv_timeout(IO_BUDGET).unwrap();
    dropped_rx.recv_timeout(IO_BUDGET).unwrap();
    reached.expect("the helper must reach the scheduling gate");
    assert!(
        error.to_string().contains("read_io_queue_timeout"),
        "{error}"
    );
    assert!(!error.to_string().contains("read_blocked"), "{error}");
    assert_eq!(
        fired.load(Ordering::Relaxed),
        0,
        "expired work must not start after release"
    );
}

#[test]
fn saturated_limiter_is_queue_timeout_and_does_not_start_work() {
    let limiter = Limiter::new(1);
    let _permit = limiter.acquire(Instant::now() + IO_BUDGET).unwrap();
    let fired = Arc::new(AtomicUsize::new(0));
    let work_fired = Arc::clone(&fired);
    let error = run_with_limiter(
        Path::new("queued"),
        Some(Instant::now() + Duration::from_millis(80)),
        limiter,
        move |_| {
            work_fired.fetch_add(1, Ordering::Relaxed);
            Ok(())
        },
    )
    .unwrap_err();
    assert!(
        error.to_string().contains("read_io_queue_timeout"),
        "{error}"
    );
    assert!(!error.to_string().contains("read_blocked"), "{error}");
    assert_eq!(fired.load(Ordering::Relaxed), 0);
    let cached_error = ProbeError::from(&error).error();
    let response = access_error("queued", Path::new("queued"), cached_error);
    assert_eq!(
        response.data["code"], "read_io_queue_timeout",
        "{response:?}"
    );
}

#[cfg(unix)]
#[test]
fn queued_time_does_not_consume_running_access_budget() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("queued-then-healthy");
    let gate = stall_helper(&path);
    let (started_tx, started_rx) = channel();
    let (release_tx, release_rx) = channel();
    let (result_tx, result_rx) = channel();
    let caller = std::thread::spawn(move || {
        result_tx
            .send(with_budget(
                Some(Budget::after(Duration::from_secs(30))),
                || {
                    run_with_timeout(
                        &path,
                        None,
                        Limiter::new(1),
                        Duration::from_secs(6),
                        None,
                        move |_| {
                            started_tx.send(()).unwrap();
                            let _ = release_rx.recv();
                            Ok(42)
                        },
                    )
                },
            ))
            .unwrap();
    });
    gate.reached.recv_timeout(IO_BUDGET).unwrap();
    // A three-second queue leaves ample scheduling margin. Four seconds of
    // running work fit the six-second access cap, but not a cap begun at enqueue.
    assert!(result_rx.recv_timeout(Duration::from_secs(3)).is_err());
    drop(gate);
    let started = started_rx.recv_timeout(IO_BUDGET);
    let early = result_rx.recv_timeout(Duration::from_secs(4));
    let _ = release_tx.send(());
    caller.join().unwrap();
    let result = early.unwrap_or_else(|_| result_rx.recv_timeout(IO_BUDGET).unwrap());
    assert!(
        started.is_ok(),
        "the filesystem operation must actually start: {started:?}; run_with_timeout returned {result:?}"
    );
    assert_eq!(
        result.unwrap(),
        42,
        "queueing must not exhaust the access cap"
    );
}

#[test]
fn running_access_keeps_shorter_request_deadline() {
    let (started_tx, started_rx) = channel();
    let (release_tx, release_rx) = channel();
    let (finished_tx, finished_rx) = channel();
    let caller = std::thread::spawn(move || {
        with_budget(Some(Budget::after(Duration::from_millis(80))), || {
            run_with_timeout(
                Path::new("running-past-request"),
                None,
                Limiter::new(1),
                Duration::from_secs(1),
                None,
                move |_| {
                    let _ = started_tx.send(());
                    let _ = release_rx.recv();
                    let _ = finished_tx.send(());
                    Ok(())
                },
            )
        })
    });
    let started = started_rx.recv_timeout(IO_BUDGET);
    let error = caller.join().unwrap().unwrap_err();
    let _ = release_tx.send(());
    finished_rx.recv_timeout(IO_BUDGET).unwrap();
    started.expect("the filesystem operation must actually start");
    assert_eq!(timeout_code(&error), "read_blocked");
    let message = error.to_string();
    let duration = message
        .split_once("within ")
        .unwrap()
        .1
        .split_once(" s")
        .unwrap()
        .0
        .parse::<f64>()
        .unwrap();
    assert!((0.0..=0.080).contains(&duration), "{error}");
}

#[cfg(unix)]
#[test]
fn queued_time_without_request_budget_does_not_consume_running_access_budget() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("queued-without-request-budget");
    let gate = stall_helper(&path);
    let (started_tx, started_rx) = channel();
    let (release_tx, release_rx) = channel();
    let (result_tx, result_rx) = channel();
    let caller = std::thread::spawn(move || {
        assert!(current().is_none(), "this call must have no request budget");
        result_tx
            .send(run_with_timeout(
                &path,
                None,
                Limiter::new(1),
                Duration::from_secs(1),
                None,
                move |_| {
                    started_tx.send(()).unwrap();
                    let _ = release_rx.recv();
                    Ok(42)
                },
            ))
            .unwrap();
    });
    gate.reached.recv_timeout(IO_BUDGET).unwrap();
    assert!(result_rx.recv_timeout(Duration::from_millis(750)).is_err());
    drop(gate);
    let started = started_rx.recv_timeout(IO_BUDGET);
    let early = result_rx.recv_timeout(Duration::from_millis(500));
    let _ = release_tx.send(());
    caller.join().unwrap();
    started.expect("the filesystem operation must actually start");
    let result = early.unwrap_or_else(|_| result_rx.recv_timeout(IO_BUDGET).unwrap());
    assert_eq!(result.unwrap(), 42, "queueing is not a request deadline");
}

#[cfg(unix)]
#[test]
fn shared_probe_waiter_follows_queued_then_running_owner() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().to_path_buf();
    let queued = stall_helper(&path);
    let running = stall_running_helper(&path);
    let budget = Budget::after(Duration::from_secs(20));
    let owner_path = path.clone();
    let owner_budget = budget.clone();
    let owner = std::thread::spawn(move || {
        with_budget(Some(owner_budget), || probe_directory(&owner_path, None))
    });
    queued.reached.recv_timeout(IO_BUDGET).unwrap();
    let (waiting_tx, waiting_rx) = channel();
    let (result_tx, result_rx) = channel();
    let waiter_budget = budget.clone();
    let waiter = std::thread::spawn(move || {
        with_budget(Some(waiter_budget), || {
            waiting_tx.send(()).unwrap();
            result_tx.send(probe_directory(&path, None)).unwrap();
        });
    });
    waiting_rx.recv_timeout(IO_BUDGET).unwrap();
    // Neither phase exceeds the access cap, but their sum exceeds the old
    // waiter's fixed five-second allowance.
    assert!(result_rx.recv_timeout(Duration::from_millis(3750)).is_err());
    drop(queued);
    running.reached.recv_timeout(IO_BUDGET).unwrap();
    let early = result_rx.recv_timeout(Duration::from_millis(2500));
    drop(running);
    let owner_result = owner.join().unwrap();
    waiter.join().unwrap();
    let result = early.unwrap_or_else(|_| result_rx.recv_timeout(IO_BUDGET).unwrap());
    result.expect("a shared waiter must receive the healthy owner's result");
    owner_result.unwrap();
    assert_eq!(budget.measurements(), (1, 1), "the probe must be shared");
    assert!(!budget.failed.load(Ordering::Acquire));
}

#[cfg(unix)]
#[test]
fn shared_probe_waiter_keeps_shorter_request_deadline_after_owner_starts() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().to_path_buf();
    let queued = stall_helper(&path);
    let running = stall_running_helper(&path);
    let budget = Budget::after(Duration::from_secs(10));
    let owner_path = path.clone();
    let owner_budget = budget.clone();
    let owner = std::thread::spawn(move || {
        with_budget(Some(owner_budget), || probe_directory(&owner_path, None))
    });
    queued.reached.recv_timeout(IO_BUDGET).unwrap();
    let (waiting_tx, waiting_rx) = channel();
    let (result_tx, result_rx) = channel();
    let waiter = std::thread::spawn(move || {
        with_budget(Some(budget), || {
            let at = Instant::now() + Duration::from_millis(500);
            waiting_tx.send(at).unwrap();
            result_tx.send(probe_directory(&path, Some(at))).unwrap();
        });
    });
    let at = waiting_rx.recv_timeout(IO_BUDGET).unwrap();
    assert!(result_rx.recv_timeout(Duration::from_millis(100)).is_err());
    drop(queued);
    running.reached.recv_timeout(IO_BUDGET).unwrap();
    let result = result_rx.recv_timeout(Duration::from_secs(2));
    let finished = Instant::now();
    drop(running);
    let _ = owner.join().unwrap();
    waiter.join().unwrap();
    let error = result.unwrap().unwrap_err();
    assert_eq!(timeout_code(&error), "read_io_queue_timeout", "{error}");
    assert!(finished >= at, "the waiter must not expire early");
    assert!(finished < at + Duration::from_secs(1));
}

#[cfg(all(unix, any(target_os = "macos", target_os = "linux")))]
#[test]
fn shared_probe_waiters_preserve_owner_queue_and_access_timeout_codes() {
    for running in [false, true] {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().to_path_buf();
        let gate = if running {
            stall_running_helper(&path)
        } else {
            stall_helper(&path)
        };
        let budget =
            Budget::after(Duration::from_secs(5)).with_access_budget(Duration::from_millis(200));
        let owner_path = path.clone();
        let owner_budget = budget.clone();
        let (owner_tx, owner_rx) = channel();
        let owner = std::thread::spawn(move || {
            let result = with_budget(Some(owner_budget), || probe_directory(&owner_path, None));
            owner_tx.send(result).unwrap();
        });
        gate.reached.recv_timeout(IO_BUDGET).unwrap();
        let (result_tx, result_rx) = channel();
        let waiter = std::thread::spawn(move || {
            with_budget(Some(budget), || {
                result_tx.send(probe_directory(&path, None)).unwrap();
            });
        });
        // A loaded runner can delay the test thread past an arbitrary short
        // grace period while the timed-out helpers are still waiting at this gate.
        // Observe both deadline results before releasing the helper.
        let result = result_rx
            .recv_timeout(Duration::from_secs(30))
            .expect("the shared-probe waiter must observe its deadline");
        let owner_result = owner_rx
            .recv_timeout(Duration::from_secs(30))
            .expect("the shared-probe owner must observe its deadline");
        drop(gate);
        owner.join().unwrap();
        waiter.join().unwrap();
        let owner_error = owner_result.unwrap_err();
        let waiter_error = result.unwrap_err();
        let expected = if running {
            "read_blocked"
        } else {
            "read_io_queue_timeout"
        };
        assert_eq!(timeout_code(&owner_error), expected, "{owner_error}");
        assert_eq!(timeout_code(&waiter_error), expected, "{waiter_error}");
    }
}

#[test]
fn running_helper_timeout_has_only_native_platform_hint() {
    let (release_tx, release_rx) = channel();
    let (started_tx, started_rx) = channel();
    let (finished_tx, finished_rx) = channel();
    let caller = std::thread::spawn(move || {
        run_with_limiter(Path::new("running"), None, Limiter::new(1), move |_| {
            started_tx.send(()).unwrap();
            let _ = release_rx.recv();
            finished_tx.send(()).unwrap();
            Ok(())
        })
    });
    let started = started_rx.recv_timeout(IO_BUDGET);
    let error = caller.join().unwrap().unwrap_err();
    release_tx.send(()).unwrap();
    finished_rx.recv_timeout(IO_BUDGET).unwrap();
    started.expect("the helper must start its operation");
    assert!(error.to_string().contains("read_blocked"), "{error}");
    let message = error.to_string();
    let (prefix, duration_and_hint) = message.split_once("within ").unwrap();
    assert_eq!(prefix, "read_blocked: running: OS access did not finish ");
    let (duration, hint) = duration_and_hint.split_once(" s").unwrap();
    assert!(duration.parse::<f64>().unwrap() > 0.0);
    let expected_hint = if cfg!(target_os = "macos") {
        "; on macOS, check ck-aft access in Privacy & Security, then retry"
    } else {
        ""
    };
    assert_eq!(hint, expected_hint);
}

// Waiting for admission must not lengthen OS access: a mutation's helper that
// started and then hangs still fails as read_blocked within the access cap.
#[cfg(all(unix, any(target_os = "macos", target_os = "linux")))]
#[test]
fn mutation_admission_keeps_the_running_access_cap() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("running-mutation-check");
    let gate = stall_running_helper(&path);
    let budget =
        Budget::after(Duration::from_secs(25)).with_access_budget(Duration::from_millis(200));
    let started = Instant::now();
    let error = with_budget(Some(budget), || {
        let _mutation = enter_mutation();
        run(&path, None, |_| Ok(()))
    })
    .unwrap_err();
    let elapsed = started.elapsed();
    drop(gate);
    assert_eq!(timeout_code(&error), "read_blocked", "{error}");
    assert!(elapsed < Duration::from_secs(5), "{elapsed:?}");
}

// Reads keep the per-access queue cap: outside a mutation, a helper that is
// not scheduled within one access cap still refuses with
// read_io_queue_timeout.
#[cfg(all(unix, any(target_os = "macos", target_os = "linux")))]
#[test]
fn read_admission_keeps_the_queue_cap_outside_mutations() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("queued-read");
    let gate = stall_helper(&path);
    let budget =
        Budget::after(Duration::from_secs(25)).with_access_budget(Duration::from_millis(200));
    let started = Instant::now();
    let error = with_budget(Some(budget), || run(&path, None, |_| Ok(()))).unwrap_err();
    let elapsed = started.elapsed();
    drop(gate);
    assert_eq!(timeout_code(&error), "read_io_queue_timeout", "{error}");
    assert!(elapsed < Duration::from_secs(5), "{elapsed:?}");
}

#[test]
fn audit1432_walk_gap_precedes_the_entire_skipped_files_block() {
    with_budget(Some(Budget::after(Duration::from_secs(30))), || {
        let budget = current().unwrap();
        budget.walk_partial.store(true, Ordering::Release);
        budget
            .walk_time_limit_reached
            .store(true, Ordering::Release);
        for at in 0..23 {
            note_large_read_skip(Path::new(&format!("large-{at:02}.log")));
        }
        let response = with_skip_disclosure(|| {
            finish_response(Response::success(
                "walk-and-skips",
                serde_json::json!({"text":"rows"}),
            ))
        });
        let text = response.data["text"].as_str().unwrap();
        assert!(
            text.find(WALK_PARTIAL_GAP).unwrap()
                < text
                    .find(crate::large_read_counts::WHOLE_READ_SKIP_REASON)
                    .unwrap(),
            "{text}"
        );
        assert!(
            text.ends_with("shown 20 of 23 files (cap) ยท narrow: path"),
            "{text}"
        );
    });
}