Skip to main content

aft_base/
write_counters.rs

1//! Process-wide attribution of AFT-owned writes.
2//!
3//! Writers register a `(domain, root)` counter once and retain the returned
4//! [`Counter`]. Crediting that counter is only two relaxed atomic additions;
5//! registry locking and string allocation stay off the write path.
6
7use std::collections::{BTreeMap, BTreeSet, VecDeque};
8use std::sync::atomic::{AtomicU64, Ordering};
9use std::sync::{Arc, Mutex, OnceLock};
10use std::time::{SystemTime, UNIX_EPOCH};
11
12use serde::{Deserialize, Serialize};
13
14use crate::process_io::Bytes;
15
16pub const RETENTION_MS: u64 = 7 * 24 * 60 * 60 * 1_000;
17pub const DEFAULT_WINDOW_MS: u64 = 10 * 60 * 1_000;
18pub const MINUTE_MS: u64 = 60_000;
19const PROCESS_ROOT: &str = "<process>";
20
21/// Closed attribution vocabulary used by persistence and management clients.
22#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum Domain {
25    CallgraphCold,
26    CallgraphColdStaging,
27    CallgraphRefresh,
28    CallgraphCheckpoint,
29    SearchIndexBuild,
30    SearchIndexDelta,
31    SemanticCold,
32    SemanticDelta,
33    SemanticCompaction,
34    SymbolCache,
35    InspectCache,
36    ViewsBlob,
37    ViewsDerived,
38    ViewsClosure,
39    AftDb,
40    BashTaskIo,
41    Backups,
42    Checkpoints,
43    Logs,
44    Other,
45}
46
47impl Domain {
48    pub const ALL: [Self; 20] = [
49        Self::CallgraphCold,
50        Self::CallgraphColdStaging,
51        Self::CallgraphRefresh,
52        Self::CallgraphCheckpoint,
53        Self::SearchIndexBuild,
54        Self::SearchIndexDelta,
55        Self::SemanticCold,
56        Self::SemanticDelta,
57        Self::SemanticCompaction,
58        Self::SymbolCache,
59        Self::InspectCache,
60        Self::ViewsBlob,
61        Self::ViewsDerived,
62        Self::ViewsClosure,
63        Self::AftDb,
64        Self::BashTaskIo,
65        Self::Backups,
66        Self::Checkpoints,
67        Self::Logs,
68        Self::Other,
69    ];
70
71    pub const fn as_str(self) -> &'static str {
72        match self {
73            Self::CallgraphCold => "callgraph_cold",
74            Self::CallgraphColdStaging => "callgraph_cold_staging",
75            Self::CallgraphRefresh => "callgraph_refresh",
76            Self::CallgraphCheckpoint => "callgraph_checkpoint",
77            Self::SearchIndexBuild => "search_index_build",
78            Self::SearchIndexDelta => "search_index_delta",
79            Self::SemanticCold => "semantic_cold",
80            Self::SemanticDelta => "semantic_delta",
81            Self::SemanticCompaction => "semantic_compaction",
82            Self::SymbolCache => "symbol_cache",
83            Self::InspectCache => "inspect_cache",
84            Self::ViewsBlob => "views_blob",
85            Self::ViewsDerived => "views_derived",
86            Self::ViewsClosure => "views_closure",
87            Self::AftDb => "aft_db",
88            Self::BashTaskIo => "bash_task_io",
89            Self::Backups => "backups",
90            Self::Checkpoints => "checkpoints",
91            Self::Logs => "logs",
92            Self::Other => "other",
93        }
94    }
95
96    pub fn parse(value: &str) -> Option<Self> {
97        Self::ALL
98            .into_iter()
99            .find(|domain| domain.as_str() == value)
100    }
101}
102
103#[derive(Debug)]
104pub struct Entry {
105    pub domain: Domain,
106    pub root_id: String,
107    pub(crate) logical: AtomicU64,
108    pub(crate) physical: AtomicU64,
109    pub folded_logical: AtomicU64,
110    pub folded_physical: AtomicU64,
111    pub seam_labels: Mutex<BTreeSet<String>>,
112}
113
114#[derive(Debug)]
115pub struct UnmeasurableEntry {
116    pub root_id: String,
117    pub seam: String,
118    pub reason: String,
119    pub estimate_basis: Option<String>,
120    pub(crate) observations: AtomicU64,
121    pub(crate) estimated_physical_bytes: AtomicU64,
122    pub folded_observations: AtomicU64,
123    pub folded_estimated_physical_bytes: AtomicU64,
124}
125
126impl UnmeasurableEntry {
127    pub fn pending(&self) -> (u64, u64) {
128        (
129            self.observations
130                .load(Ordering::Relaxed)
131                .saturating_sub(self.folded_observations.load(Ordering::Relaxed)),
132            self.estimated_physical_bytes
133                .load(Ordering::Relaxed)
134                .saturating_sub(self.folded_estimated_physical_bytes.load(Ordering::Relaxed)),
135        )
136    }
137}
138
139impl Entry {
140    pub fn pending(&self) -> (u64, u64) {
141        (
142            self.logical
143                .load(Ordering::Relaxed)
144                .saturating_sub(self.folded_logical.load(Ordering::Relaxed)),
145            self.physical
146                .load(Ordering::Relaxed)
147                .saturating_sub(self.folded_physical.load(Ordering::Relaxed)),
148        )
149    }
150}
151
152/// Pre-registered, allocation-free write-path counter.
153#[derive(Clone, Debug)]
154pub struct Counter(Arc<Entry>);
155
156impl Counter {
157    pub fn credit(&self, logical_bytes: u64, physical_bytes: u64) {
158        saturating_add(&self.0.logical, logical_bytes);
159        saturating_add(&self.0.physical, physical_bytes);
160    }
161
162    pub fn credit_logical(&self, logical_bytes: u64) {
163        self.credit(logical_bytes, 0);
164    }
165
166    pub fn domain(&self) -> Domain {
167        self.0.domain
168    }
169
170    pub fn root_id(&self) -> String {
171        self.0.root_id.clone()
172    }
173
174    pub fn note_seam_label(&self, label: &str) {
175        self.0
176            .seam_labels
177            .lock()
178            .unwrap_or_else(std::sync::PoisonError::into_inner)
179            .insert(label.to_owned());
180    }
181
182    /// Record a write operation whose bytes cannot be measured without changing
183    /// the operation being observed. Estimates stay separate from attributed bytes.
184    pub fn note_unmeasurable(
185        &self,
186        seam: &str,
187        reason: &str,
188        estimated_physical_bytes: Option<u64>,
189        estimate_basis: Option<&str>,
190    ) {
191        note_unmeasurable(
192            self.0.root_id.clone(),
193            seam,
194            reason,
195            estimated_physical_bytes,
196            estimate_basis,
197        );
198    }
199}
200
201#[allow(deprecated)] // fetch_update became try_update in Rust 1.99; the MSRV (1.92) lacks try_update
202pub fn saturating_add(value: &AtomicU64, delta: u64) {
203    let _ = value.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
204        Some(current.saturating_add(delta))
205    });
206}
207
208#[derive(Clone, Debug)]
209pub struct ProcessBaseline {
210    pub bytes: Option<Bytes>,
211    pub sampled_at_ms: u64,
212}
213
214#[derive(Clone, Debug)]
215pub struct RecentRow {
216    pub minute_ts: u64,
217    pub domain: Domain,
218    pub root_id: String,
219    pub physical_bytes: u64,
220}
221
222#[derive(Debug)]
223pub struct Registry {
224    pub started_ms: u64,
225    pub entries: Mutex<BTreeMap<(Domain, String), Arc<Entry>>>,
226    pub unmeasurable_entries: Mutex<BTreeMap<(String, String), Arc<UnmeasurableEntry>>>,
227    pub process_baseline: Mutex<ProcessBaseline>,
228    pub fold_lock: Mutex<()>,
229    pub recent: Mutex<VecDeque<RecentRow>>,
230    pub recent_top: Mutex<Vec<WriterRow>>,
231}
232
233#[rustfmt::skip]
234test_support_visibility! {
235
236pub(crate) fn now_ms() -> u64 {
237    SystemTime::now()
238        .duration_since(UNIX_EPOCH)
239        .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)
240        .unwrap_or(0)
241}
242}
243
244pub fn registry() -> &'static Registry {
245    static REGISTRY: OnceLock<Registry> = OnceLock::new();
246    REGISTRY.get_or_init(|| {
247        let started_ms = now_ms();
248        Registry {
249            started_ms,
250            entries: Mutex::new(BTreeMap::new()),
251            unmeasurable_entries: Mutex::new(BTreeMap::new()),
252            process_baseline: Mutex::new(ProcessBaseline {
253                bytes: Bytes::capture(),
254                sampled_at_ms: started_ms,
255            }),
256            fold_lock: Mutex::new(()),
257            recent: Mutex::new(VecDeque::new()),
258            recent_top: Mutex::new(Vec::new()),
259        }
260    })
261}
262
263pub fn register(domain: Domain, root_id: impl Into<String>) -> Counter {
264    let root_id = root_id.into();
265    let mut entries = registry()
266        .entries
267        .lock()
268        .unwrap_or_else(std::sync::PoisonError::into_inner);
269    Counter(
270        entries
271            .entry((domain, root_id.clone()))
272            .or_insert_with(|| {
273                Arc::new(Entry {
274                    domain,
275                    root_id,
276                    logical: AtomicU64::new(0),
277                    physical: AtomicU64::new(0),
278                    folded_logical: AtomicU64::new(0),
279                    folded_physical: AtomicU64::new(0),
280                    seam_labels: Mutex::new(BTreeSet::new()),
281                })
282            })
283            .clone(),
284    )
285}
286
287/// Convenience for operation-boundary instrumentation. Repeated/hot writers
288/// should retain a [`Counter`] instead.
289pub fn credit(domain: Domain, root_id: impl Into<String>, logical: u64, physical: u64) {
290    register(domain, root_id).credit(logical, physical);
291}
292
293fn note_unmeasurable(
294    root_id: String,
295    seam: &str,
296    reason: &str,
297    estimated_physical_bytes: Option<u64>,
298    estimate_basis: Option<&str>,
299) {
300    debug_assert_eq!(estimated_physical_bytes.is_some(), estimate_basis.is_some());
301    let key = (root_id.clone(), seam.to_owned());
302    let entry = {
303        let mut entries = registry()
304            .unmeasurable_entries
305            .lock()
306            .unwrap_or_else(std::sync::PoisonError::into_inner);
307        entries
308            .entry(key)
309            .or_insert_with(|| {
310                Arc::new(UnmeasurableEntry {
311                    root_id,
312                    seam: seam.to_owned(),
313                    reason: reason.to_owned(),
314                    estimate_basis: estimate_basis.map(str::to_owned),
315                    observations: AtomicU64::new(0),
316                    estimated_physical_bytes: AtomicU64::new(0),
317                    folded_observations: AtomicU64::new(0),
318                    folded_estimated_physical_bytes: AtomicU64::new(0),
319                })
320            })
321            .clone()
322    };
323    debug_assert_eq!(entry.reason, reason);
324    debug_assert_eq!(entry.estimate_basis.as_deref(), estimate_basis);
325    saturating_add(&entry.observations, 1);
326    if let Some(bytes) = estimated_physical_bytes {
327        saturating_add(&entry.estimated_physical_bytes, bytes);
328    }
329}
330
331pub fn note_process_unmeasurable(
332    seam: &str,
333    reason: &str,
334    estimated_physical_bytes: Option<u64>,
335    estimate_basis: Option<&str>,
336) {
337    note_unmeasurable(
338        PROCESS_ROOT.to_owned(),
339        seam,
340        reason,
341        estimated_physical_bytes,
342        estimate_basis,
343    );
344}
345
346pub fn process_root_counter(domain: Domain) -> Counter {
347    register(domain, PROCESS_ROOT)
348}
349
350#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
351pub struct WriterRow {
352    pub domain: String,
353    pub root_id: String,
354    pub logical_bytes: u64,
355    pub physical_bytes: u64,
356    #[serde(default, skip_serializing_if = "Vec::is_empty")]
357    pub seam_labels: Vec<String>,
358}