Skip to main content

aft_base/
io_accounting.rs

1//! Process-wide work counters and the path context attached to I/O errors.
2//! The counters are shared by every root and by background work, so a
3//! difference between two readings can include work done for other roots.
4use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
5
6/// Keep the error kind and native source available to retry/absence checks
7/// while naming the I/O that failed. OS errors alone do not include its path.
8pub fn at(operation: &str, path: &std::path::Path, source: std::io::Error) -> std::io::Error {
9    std::io::Error::new(
10        source.kind(),
11        PathIoError {
12            operation: operation.to_owned(),
13            path: path.to_path_buf(),
14            source,
15        },
16    )
17}
18
19#[derive(Debug)]
20struct PathIoError {
21    operation: String,
22    path: std::path::PathBuf,
23    source: std::io::Error,
24}
25
26impl std::fmt::Display for PathIoError {
27    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
28        write!(
29            f,
30            "{} {}: {}",
31            self.operation,
32            self.path.display(),
33            self.source
34        )
35    }
36}
37
38impl std::error::Error for PathIoError {
39    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
40        Some(&self.source)
41    }
42}
43
44/// Lifetime totals for measured work sites, shared by every root in this process.
45/// Relaxed loads are intentionally not a transactional snapshot; difference them
46/// only within one daemon lifetime, never sum overlapping per-root intervals.
47pub struct WorkCounters {
48    pub source_hashes: AtomicU64,
49    pub source_hash_bytes: AtomicU64,
50    pub content_reads: AtomicU64,
51    pub content_read_bytes: AtomicU64,
52    pub full_walks: AtomicU64,
53    pub git_subprocesses: AtomicU64,
54    pub applicability_walks: AtomicU64,
55    pub logical_aggregates: AtomicU64,
56    pub own_generation_folds: AtomicU64,
57    pub dispatch_blobs_decoded: AtomicU64,
58    pub dispatch_files_resolved: AtomicU64,
59    pub dispatch_sites_resolved: AtomicU64,
60    pub dispatch_full_passes: AtomicU64,
61    pub dispatch_type_target_files: AtomicU64,
62    pub semantic_store_gets: AtomicU64,
63    pub semantic_store_payload_bytes: AtomicU64,
64    pub semantic_touch_rows_written: AtomicU64,
65    pub semantic_touch_transactions: AtomicU64,
66    pub semantic_fills: AtomicU64,
67    pub semantic_files_filled: AtomicU64,
68}
69
70pub static WORK: WorkCounters = WorkCounters {
71    source_hashes: AtomicU64::new(0),
72    source_hash_bytes: AtomicU64::new(0),
73    content_reads: AtomicU64::new(0),
74    content_read_bytes: AtomicU64::new(0),
75    full_walks: AtomicU64::new(0),
76    git_subprocesses: AtomicU64::new(0),
77    applicability_walks: AtomicU64::new(0),
78    logical_aggregates: AtomicU64::new(0),
79    own_generation_folds: AtomicU64::new(0),
80    dispatch_blobs_decoded: AtomicU64::new(0),
81    dispatch_files_resolved: AtomicU64::new(0),
82    dispatch_sites_resolved: AtomicU64::new(0),
83    dispatch_full_passes: AtomicU64::new(0),
84    dispatch_type_target_files: AtomicU64::new(0),
85    semantic_store_gets: AtomicU64::new(0),
86    semantic_store_payload_bytes: AtomicU64::new(0),
87    semantic_touch_rows_written: AtomicU64::new(0),
88    semantic_touch_transactions: AtomicU64::new(0),
89    semantic_fills: AtomicU64::new(0),
90    semantic_files_filled: AtomicU64::new(0),
91};
92
93/// Live harness-selected runtimes, including builders before a base is ready.
94pub(crate) static BASE_REF_PROTOTYPE_USERS: AtomicUsize = AtomicUsize::new(0);
95
96/// Hash source bytes, counting repeated hashes as repeated work. Payload and
97/// embedding-text checksums are not source hashes and must not use this helper.
98pub(crate) fn source_hash(bytes: &[u8]) -> blake3::Hash {
99    WORK.source_hashes.fetch_add(1, Ordering::Relaxed);
100    WORK.source_hash_bytes
101        .fetch_add(bytes.len() as u64, Ordering::Relaxed);
102    blake3::hash(bytes)
103}
104
105pub fn work_snapshot() -> serde_json::Value {
106    serde_json::json!({
107        "schema": 1,
108        "pid": std::process::id(),
109        "scope": "process_lifetime_instrumented_sites",
110        "base_ref_prototype": BASE_REF_PROTOTYPE_USERS.load(Ordering::Relaxed) > 0,
111        "source_hashes": WORK.source_hashes.load(Ordering::Relaxed),
112        "source_hash_bytes": WORK.source_hash_bytes.load(Ordering::Relaxed),
113        "content_reads": WORK.content_reads.load(Ordering::Relaxed),
114        "content_read_bytes": WORK.content_read_bytes.load(Ordering::Relaxed),
115        "full_walks": WORK.full_walks.load(Ordering::Relaxed),
116        "git_subprocesses": WORK.git_subprocesses.load(Ordering::Relaxed),
117        "applicability_walks": WORK.applicability_walks.load(Ordering::Relaxed),
118        "logical_aggregates": WORK.logical_aggregates.load(Ordering::Relaxed),
119        "own_generation_folds": WORK.own_generation_folds.load(Ordering::Relaxed),
120        "dispatch_blobs_decoded": WORK.dispatch_blobs_decoded.load(Ordering::Relaxed),
121        "dispatch_files_resolved": WORK.dispatch_files_resolved.load(Ordering::Relaxed),
122        "dispatch_sites_resolved": WORK.dispatch_sites_resolved.load(Ordering::Relaxed),
123        "dispatch_full_passes": WORK.dispatch_full_passes.load(Ordering::Relaxed),
124        "dispatch_type_target_files": WORK.dispatch_type_target_files.load(Ordering::Relaxed),
125        "semantic_store_gets": WORK.semantic_store_gets.load(Ordering::Relaxed),
126        "semantic_store_payload_bytes": WORK.semantic_store_payload_bytes.load(Ordering::Relaxed),
127        "semantic_touch_rows_written": WORK.semantic_touch_rows_written.load(Ordering::Relaxed),
128        "semantic_touch_transactions": WORK.semantic_touch_transactions.load(Ordering::Relaxed),
129        "semantic_fills": WORK.semantic_fills.load(Ordering::Relaxed),
130        "semantic_files_filled": WORK.semantic_files_filled.load(Ordering::Relaxed),
131    })
132}
133
134#[cfg(test)]
135mod tests {
136    #[test]
137    fn path_context_preserves_absence_and_retry_kinds() {
138        for kind in [std::io::ErrorKind::NotFound, std::io::ErrorKind::WouldBlock] {
139            let error = super::at(
140                "reading",
141                std::path::Path::new("missing-input"),
142                std::io::Error::new(kind, "original failure"),
143            );
144            assert_eq!(error.kind(), kind);
145            assert_eq!(error.to_string(), "reading missing-input: original failure");
146        }
147    }
148
149    #[test]
150    fn path_context_preserves_native_error_sources() {
151        let error = super::at(
152            "opening",
153            std::path::Path::new("busy-database"),
154            std::io::Error::from_raw_os_error(32),
155        );
156        let context = error
157            .get_ref()
158            .unwrap()
159            .downcast_ref::<super::PathIoError>()
160            .unwrap();
161        assert_eq!(context.source.raw_os_error(), Some(32));
162        assert_eq!(
163            std::error::Error::source(context)
164                .unwrap()
165                .downcast_ref::<std::io::Error>()
166                .unwrap()
167                .raw_os_error(),
168            Some(32)
169        );
170        assert!(error.to_string().starts_with("opening busy-database: "));
171    }
172}