Skip to main content

aft_base/
large_read_counts.rs

1//! Shared large-read health counters, independent of the readers.
2
3use std::sync::atomic::{AtomicU64, Ordering};
4
5pub const LARGE_READ_BYTES: u64 = 4 * 1024 * 1024;
6
7/// The readers whose large reads health counts, by site.
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum Site {
10    /// Indexed grep verification (`search_candidate_file`).
11    GrepIndexed,
12    /// Indexed grep collection by file (`matching_lines_in_content`).
13    GrepCollect,
14    /// Folder-walk grep (`fallback_search_file`).
15    GrepFallback,
16    /// The degraded search fallback's read phase.
17    DegradedGrep,
18    /// The literal presence check.
19    Presence,
20    /// `matching_line_from_source`.
21    MatchingLine,
22    /// The reranker's candidate text.
23    CandidateText,
24    /// `request_source_file` (definition and reference helpers).
25    SourceFile,
26    /// `lexical_candidate_exactness`.
27    LexicalExactness,
28    /// Exact-memo digest reads and the direct digest proof.
29    MemoDigest,
30    /// The external exact sweep.
31    ExternalSweep,
32    /// Exact-corpus and anchored verification reads.
33    ExactCorpus,
34    /// Data-file classification.
35    DataFile,
36    /// Nearest-name lookups.
37    NearestNames,
38    /// Grep row line windows.
39    LineWindows,
40    /// Bounded snippet line reads.
41    SnippetLines,
42    /// `parser::read_source`.
43    ParseSource,
44}
45
46pub const SITES: [(Site, &str); 17] = [
47    (Site::GrepIndexed, "grep_indexed"),
48    (Site::GrepCollect, "grep_collect"),
49    (Site::GrepFallback, "grep_fallback"),
50    (Site::DegradedGrep, "degraded_grep"),
51    (Site::Presence, "presence"),
52    (Site::MatchingLine, "matching_line"),
53    (Site::CandidateText, "candidate_text"),
54    (Site::SourceFile, "source_file"),
55    (Site::LexicalExactness, "lexical_exactness"),
56    (Site::MemoDigest, "memo_digest"),
57    (Site::ExternalSweep, "external_sweep"),
58    (Site::ExactCorpus, "exact_corpus"),
59    (Site::DataFile, "data_file"),
60    (Site::NearestNames, "nearest_names"),
61    (Site::LineWindows, "line_windows"),
62    (Site::SnippetLines, "snippet_lines"),
63    (Site::ParseSource, "parse_source"),
64];
65
66pub struct Counter {
67    pub count: AtomicU64,
68    pub bytes: AtomicU64,
69    pub largest: AtomicU64,
70    pub whole_count: AtomicU64,
71    pub whole_bytes: AtomicU64,
72    pub skipped: AtomicU64,
73}
74
75#[allow(clippy::declare_interior_mutable_const)]
76pub const ZERO: Counter = Counter {
77    count: AtomicU64::new(0),
78    bytes: AtomicU64::new(0),
79    largest: AtomicU64::new(0),
80    whole_count: AtomicU64::new(0),
81    whole_bytes: AtomicU64::new(0),
82    skipped: AtomicU64::new(0),
83};
84
85pub static COUNTERS: [Counter; SITES.len()] = [ZERO; SITES.len()];
86
87#[cfg(any(test, feature = "test-support"))]
88thread_local! {
89    // Recording tests can exercise the public entry points without racing
90    // readers in other tests or resetting their process-wide observations.
91    pub static TEST_COUNTERS: std::cell::RefCell<Option<[Counter; SITES.len()]>> = const { std::cell::RefCell::new(None) };
92}
93
94pub fn with_counter<T>(site: Site, work: impl FnOnce(&Counter) -> T) -> T {
95    #[cfg(any(test, feature = "test-support"))]
96    let mut work = Some(work);
97    #[cfg(any(test, feature = "test-support"))]
98    if let Some(result) = TEST_COUNTERS.with(|counters| {
99        counters
100            .borrow()
101            .as_ref()
102            .map(|counters| work.take().unwrap()(&counters[site as usize]))
103    }) {
104        return result;
105    }
106    #[cfg(any(test, feature = "test-support"))]
107    let work = work.unwrap();
108    work(&COUNTERS[site as usize])
109}
110
111fn record_read(site: Site, size: u64, bytes: u64, whole: bool) {
112    if size <= LARGE_READ_BYTES && bytes <= LARGE_READ_BYTES {
113        return;
114    }
115    with_counter(site, |counter| {
116        counter.count.fetch_add(1, Ordering::Relaxed);
117        counter.bytes.fetch_add(bytes, Ordering::Relaxed);
118        counter.largest.fetch_max(bytes, Ordering::Relaxed);
119        if whole {
120            counter.whole_count.fetch_add(1, Ordering::Relaxed);
121            counter.whole_bytes.fetch_add(bytes, Ordering::Relaxed);
122        }
123    });
124}
125
126/// Count a streamed read at `site` of a file that was `size` bytes at open, of which
127/// `bytes` were read, when the file is a large read. Bytes and the largest
128/// read are in bytes read.
129pub fn record(site: Site, size: u64, bytes: u64) {
130    record_read(site, size, bytes, false);
131}
132
133/// Count a whole read of `bytes` bytes at `site`.
134pub fn record_whole(site: Site, bytes: usize) {
135    record_read(site, bytes as u64, bytes as u64, true);
136}
137
138/// Twice the largest file production readers touched (8.1 MB), so whole reads
139/// cannot turn a growing log into a multi-gigabyte allocation.
140pub const WHOLE_READ_CEILING: u64 = 16 * 1024 * 1024;
141
142/// Kept in one place so the agent-visible explanation can be reviewed separately.
143pub const WHOLE_READ_SKIP_REASON: &str =
144    "Skipped: reading this file would exceed the 16 MiB in-memory read ceiling.";
145
146pub fn allow_whole(site: Site, path: &std::path::Path, size: u64) -> std::io::Result<()> {
147    if size <= WHOLE_READ_CEILING {
148        return Ok(());
149    }
150    skip(site, path);
151    Err(std::io::Error::other(WHOLE_READ_SKIP_REASON))
152}
153
154pub fn skip(site: Site, path: &std::path::Path) {
155    with_counter(site, |counter| {
156        counter.skipped.fetch_add(1, Ordering::Relaxed);
157    });
158    crate::bounded_io::note_large_read_skip(path);
159}
160
161pub fn is_ceiling_error(error: &std::io::Error) -> bool {
162    error.to_string() == WHOLE_READ_SKIP_REASON
163}