Skip to main content

khive_runtime/pack/
audit_success_rows.rs

1use std::sync::atomic::{AtomicU64, Ordering};
2
3use serde_json::{json, Value};
4
5use super::VerbRegistry;
6
7/// Success-audit population fixed at registry construction (ADR-103 Amendment 7).
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
9pub enum AuditSuccessRowsMode {
10    /// Omit or sample only the explicitly reviewed trusted handlers.
11    #[default]
12    Reduced,
13    /// Preserve every success row and disable success-row decision counters.
14    All,
15}
16
17impl AuditSuccessRowsMode {
18    /// Value reported by diagnostics and accepted by `KHIVE_AUDIT_SUCCESS_ROWS`.
19    pub const fn as_str(self) -> &'static str {
20        match self {
21            Self::Reduced => "reduced",
22            Self::All => "all",
23        }
24    }
25
26    pub(super) fn from_env() -> Self {
27        match std::env::var_os("KHIVE_AUDIT_SUCCESS_ROWS") {
28            None => Self::Reduced,
29            Some(value) => match value.to_str() {
30                Some("reduced") => Self::Reduced,
31                Some("all") => Self::All,
32                _ => {
33                    tracing::warn!(
34                        value = ?value,
35                        "unrecognized KHIVE_AUDIT_SUCCESS_ROWS; using all"
36                    );
37                    Self::All
38                }
39            },
40        }
41    }
42}
43
44/// Canonical result predicate that forces a sampled success row to be retained.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum AuditSuccessRowForcingRule {
47    /// Retain unless `outcome` is exactly the string `success`.
48    PollNotSuccessful,
49    /// Retain unless both cleanup counts are exactly the integer zero.
50    QuarantineChanged,
51}
52
53impl VerbRegistry {
54    /// Reviewed `(owning pack, verb)` pairs whose trusted success rows may be omitted.
55    pub const AUDIT_SUCCESS_ROW_OMITTED_VERBS: &'static [(&'static str, &'static str)] = &[
56        ("comm", "comm.inbox"),
57        ("comm", "comm.probe"),
58        ("comm", "comm.cursor_get"),
59        ("kg", "whoami"),
60    ];
61
62    /// Reviewed `(owning pack, verb, every, forcing rule)` sampling policies.
63    pub const AUDIT_SUCCESS_ROW_SAMPLED_VERBS: &'static [(
64        &'static str,
65        &'static str,
66        u64,
67        AuditSuccessRowForcingRule,
68    )] = &[
69        (
70            "comm",
71            "comm.heartbeat",
72            10,
73            AuditSuccessRowForcingRule::PollNotSuccessful,
74        ),
75        (
76            "comm",
77            "comm.cleanup_expired_quarantine",
78            10,
79            AuditSuccessRowForcingRule::QuarantineChanged,
80        ),
81    ];
82
83    /// This registry's fixed success-row mode, including when no audit sink exists.
84    pub fn audit_success_rows_mode(&self) -> AuditSuccessRowsMode {
85        self.audit_success_rows_mode
86    }
87}
88
89static OMITTED_COUNTS: [(&str, AtomicU64); 4] = [
90    ("comm.inbox", AtomicU64::new(0)),
91    ("comm.probe", AtomicU64::new(0)),
92    ("comm.cursor_get", AtomicU64::new(0)),
93    ("whoami", AtomicU64::new(0)),
94];
95static SAMPLED_OUT_COUNTS: [(&str, AtomicU64); 2] = [
96    ("comm.heartbeat", AtomicU64::new(0)),
97    ("comm.cleanup_expired_quarantine", AtomicU64::new(0)),
98];
99static FORCED_COUNTS: [(&str, AtomicU64); 2] = [
100    ("comm.heartbeat", AtomicU64::new(0)),
101    ("comm.cleanup_expired_quarantine", AtomicU64::new(0)),
102];
103
104#[derive(Clone, Copy)]
105pub(super) enum AuditSuccessRowDecision {
106    Omitted,
107    SampledOut,
108    Forced,
109}
110
111impl VerbRegistry {
112    pub(super) fn record_audit_success_row_decision(
113        &self,
114        verb: &str,
115        decision: AuditSuccessRowDecision,
116    ) {
117        if self.audit_success_rows_mode != AuditSuccessRowsMode::Reduced {
118            return;
119        }
120        let counters: &[(&str, AtomicU64)] = match decision {
121            AuditSuccessRowDecision::Omitted => &OMITTED_COUNTS,
122            AuditSuccessRowDecision::SampledOut => &SAMPLED_OUT_COUNTS,
123            AuditSuccessRowDecision::Forced => &FORCED_COUNTS,
124        };
125        if let Some((_, count)) = counters.iter().find(|(name, _)| *name == verb) {
126            count.fetch_add(1, Ordering::Relaxed);
127        }
128    }
129
130    pub(super) fn audit_success_rows_omitted_counts(&self) -> [(&'static str, u64); 4] {
131        std::array::from_fn(|i| {
132            (
133                OMITTED_COUNTS[i].0,
134                OMITTED_COUNTS[i].1.load(Ordering::Relaxed),
135            )
136        })
137    }
138
139    pub(super) fn audit_success_rows_sampled_out_counts(&self) -> [(&'static str, u64); 2] {
140        std::array::from_fn(|i| {
141            (
142                SAMPLED_OUT_COUNTS[i].0,
143                SAMPLED_OUT_COUNTS[i].1.load(Ordering::Relaxed),
144            )
145        })
146    }
147
148    pub(super) fn audit_success_rows_forced_counts(&self) -> [(&'static str, u64); 2] {
149        std::array::from_fn(|i| {
150            (
151                FORCED_COUNTS[i].0,
152                FORCED_COUNTS[i].1.load(Ordering::Relaxed),
153            )
154        })
155    }
156}
157
158static SAMPLED_SEQUENCES: [(&str, AtomicU64); 2] = [
159    ("comm.heartbeat", AtomicU64::new(0)),
160    ("comm.cleanup_expired_quarantine", AtomicU64::new(0)),
161];
162
163#[derive(Clone, Copy)]
164struct Sampling {
165    every: u64,
166    seq: u64,
167    selected_by: &'static str,
168}
169
170#[derive(Clone, Copy)]
171pub(super) struct AuditSuccessRowAction {
172    skipped: bool,
173    sampling: Option<Sampling>,
174}
175
176impl AuditSuccessRowAction {
177    const KEEP: Self = Self {
178        skipped: false,
179        sampling: None,
180    };
181
182    fn skip() -> Self {
183        // Match the retained row's snapshot point without building a resource.
184        if let Some(context) = crate::usage::current() {
185            context.freeze();
186        }
187        Self {
188            skipped: true,
189            sampling: None,
190        }
191    }
192
193    pub(super) fn is_skipped(self) -> bool {
194        self.skipped
195    }
196
197    pub(super) fn resource(self, mut resource: Value) -> Value {
198        if let Some(sampling) = self.sampling {
199            resource["sampling"] = json!({
200                "every": sampling.every,
201                "seq": sampling.seq,
202                "selected_by": sampling.selected_by,
203            });
204        }
205        resource
206    }
207}
208
209fn mix64(mut value: u64) -> u64 {
210    value = (value ^ (value >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
211    value = (value ^ (value >> 27)).wrapping_mul(0x94d049bb133111eb);
212    value ^ (value >> 31)
213}
214
215impl VerbRegistry {
216    // Called only after the deferred append's existing event-store guard.
217    pub(super) fn audit_success_row_action(
218        &self,
219        verb: &str,
220        result: Option<&Value>,
221    ) -> AuditSuccessRowAction {
222        if self.audit_success_rows_mode != AuditSuccessRowsMode::Reduced {
223            return AuditSuccessRowAction::KEEP;
224        }
225        let Some(result) = result else {
226            return AuditSuccessRowAction::KEEP;
227        };
228        if self.audit_success_row_omitted_verbs.contains(verb) {
229            self.record_audit_success_row_decision(verb, AuditSuccessRowDecision::Omitted);
230            return AuditSuccessRowAction::skip();
231        }
232        let Some(&(every, forcing)) = self.audit_success_row_sampled_verbs.get(verb) else {
233            return AuditSuccessRowAction::KEEP;
234        };
235        let Some((_, sequence)) = SAMPLED_SEQUENCES.iter().find(|(name, _)| *name == verb) else {
236            return AuditSuccessRowAction::KEEP;
237        };
238        let seq = sequence.fetch_add(1, Ordering::Relaxed);
239        #[cfg(test)]
240        super::audit_success_rows_cut_tests::observe_allocation(verb, seq);
241        let selected = mix64(seq).is_multiple_of(every);
242        let forced = match forcing {
243            AuditSuccessRowForcingRule::PollNotSuccessful => {
244                result.get("outcome").and_then(Value::as_str) != Some("success")
245            }
246            AuditSuccessRowForcingRule::QuarantineChanged => {
247                result.get("deleted").and_then(Value::as_u64) != Some(0)
248                    || result.get("routed_owners_detached").and_then(Value::as_u64) != Some(0)
249            }
250        };
251        let selected_by = if selected {
252            "sample"
253        } else if forced {
254            self.record_audit_success_row_decision(verb, AuditSuccessRowDecision::Forced);
255            "forced"
256        } else {
257            self.record_audit_success_row_decision(verb, AuditSuccessRowDecision::SampledOut);
258            return AuditSuccessRowAction::skip();
259        };
260        AuditSuccessRowAction {
261            skipped: false,
262            sampling: Some(Sampling {
263                every,
264                seq,
265                selected_by,
266            }),
267        }
268    }
269}
270
271#[cfg(test)]
272mod verb_table_pin_tests {
273    use super::*;
274
275    fn names(table: &[(&'static str, AtomicU64)]) -> Vec<&'static str> {
276        table.iter().map(|(name, _)| *name).collect()
277    }
278
279    // The counter and sequence tables repeat the policy verbs as literals; a verb added to or
280    // removed from a policy table without its counter row would count nothing or sample nothing.
281    #[test]
282    fn counter_and_sequence_tables_name_exactly_the_policy_verbs() {
283        let omitted: Vec<_> = VerbRegistry::AUDIT_SUCCESS_ROW_OMITTED_VERBS
284            .iter()
285            .map(|(_, verb)| *verb)
286            .collect();
287        let sampled: Vec<_> = VerbRegistry::AUDIT_SUCCESS_ROW_SAMPLED_VERBS
288            .iter()
289            .map(|(_, verb, _, _)| *verb)
290            .collect();
291        assert_eq!(names(&OMITTED_COUNTS), omitted);
292        assert_eq!(names(&SAMPLED_OUT_COUNTS), sampled);
293        assert_eq!(names(&FORCED_COUNTS), sampled);
294        assert_eq!(names(&SAMPLED_SEQUENCES), sampled);
295    }
296}