Skip to main content

lean_ctx/core/
telemetry_failure.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Why a built-in tool call failed, as a closed class for telemetry.
4//!
5//! Only the class leaves the machine; the message it is derived from (which
6//! can name files, commands or values) never does. Matching is ordered from
7//! the most specific signal to the most generic one.
8
9use std::collections::BTreeMap;
10
11use serde::{Deserialize, Serialize};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum FailureKind {
16    /// Arguments missing, malformed or of the wrong type.
17    InvalidInput,
18    /// File, symbol, job or tool does not exist.
19    NotFound,
20    /// Path outside the jail, read-only target, OS permission.
21    Permission,
22    /// Refused by a LeanCTX policy, allowlist or gateway rule.
23    PolicyBlocked,
24    /// The call or the command it ran timed out.
25    Timeout,
26    /// An edit no longer matches the file (stale anchor, ambiguous match).
27    Conflict,
28    /// Input or output beyond a size or budget limit.
29    TooLarge,
30    /// A dependency (daemon, provider, network, runtime) is not available.
31    Unavailable,
32    /// Anything else.
33    Other,
34}
35
36pub const FAILURE_KINDS: [FailureKind; 9] = [
37    FailureKind::InvalidInput,
38    FailureKind::NotFound,
39    FailureKind::Permission,
40    FailureKind::PolicyBlocked,
41    FailureKind::Timeout,
42    FailureKind::Conflict,
43    FailureKind::TooLarge,
44    FailureKind::Unavailable,
45    FailureKind::Other,
46];
47
48impl FailureKind {
49    pub fn index(self) -> usize {
50        FAILURE_KINDS
51            .iter()
52            .position(|kind| *kind == self)
53            .unwrap_or(FAILURE_KINDS.len() - 1)
54    }
55
56    pub fn as_str(self) -> &'static str {
57        match self {
58            Self::InvalidInput => "invalid_input",
59            Self::NotFound => "not_found",
60            Self::Permission => "permission",
61            Self::PolicyBlocked => "policy_blocked",
62            Self::Timeout => "timeout",
63            Self::Conflict => "conflict",
64            Self::TooLarge => "too_large",
65            Self::Unavailable => "unavailable",
66            Self::Other => "other",
67        }
68    }
69}
70
71const RULES: &[(FailureKind, &[&str])] = &[
72    (
73        FailureKind::PolicyBlocked,
74        &[
75            "[policy blocked]",
76            "policy blocked",
77            "blocked by policy",
78            "denied by policy",
79            "allowlist",
80            "not permitted by",
81            "gateway denied",
82            "egress denied",
83        ],
84    ),
85    (
86        FailureKind::Timeout,
87        &["timed out", "timeout", "deadline exceeded"],
88    ),
89    (
90        FailureKind::Conflict,
91        &[
92            "old_string",
93            "not unique",
94            "no unique",
95            "conflict",
96            "mismatch",
97            "stale",
98            "changed since",
99            "hash does not match",
100            "anchor",
101        ],
102    ),
103    (
104        FailureKind::Permission,
105        &[
106            "permission denied",
107            "access denied",
108            "outside the project",
109            "outside project",
110            "outside of",
111            "path jail",
112            "escapes project root",
113            "read-only",
114            "readonly",
115            "operation not permitted",
116        ],
117    ),
118    (
119        FailureKind::NotFound,
120        &[
121            "not found",
122            "no such file",
123            "does not exist",
124            "doesn't exist",
125            "unknown tool",
126            "no matches",
127            "no such",
128        ],
129    ),
130    (
131        FailureKind::TooLarge,
132        &[
133            "too large",
134            "too long",
135            "exceeds",
136            "limit reached",
137            "over budget",
138        ],
139    ),
140    (
141        FailureKind::Unavailable,
142        &[
143            "unavailable",
144            "not running",
145            "connection refused",
146            "not installed",
147            "not configured",
148            "is disabled",
149            "not enabled",
150            "failed to connect",
151            "network",
152        ],
153    ),
154    (
155        FailureKind::InvalidInput,
156        &[
157            "invalid",
158            "missing required",
159            "missing field",
160            "required parameter",
161            "unknown field",
162            "unknown parameter",
163            "unknown action",
164            "expected",
165            "must be",
166            "cannot parse",
167            "failed to parse",
168        ],
169    ),
170];
171
172/// Classify a failure message; the message itself is discarded.
173pub fn classify(message: &str) -> FailureKind {
174    let lowered = message.to_ascii_lowercase();
175    RULES
176        .iter()
177        .find(|(_, needles)| needles.iter().any(|needle| lowered.contains(needle)))
178        .map_or(FailureKind::Other, |(kind, _)| *kind)
179}
180
181/// Failure counts indexed like [`FAILURE_KINDS`].
182pub type KindCounts = [u64; FAILURE_KINDS.len()];
183
184/// A failed call as telemetry sees it: its class and, when one survives
185/// scrubbing, the template of its message (see [`super::failure_template`]).
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub struct Failure {
188    pub kind: FailureKind,
189    pub template: Option<String>,
190}
191
192impl Failure {
193    /// Derive class and template locally; the message itself is dropped.
194    pub fn from_message(message: &str) -> Self {
195        Self {
196            kind: classify(message),
197            template: super::failure_template::message_template(message),
198        }
199    }
200
201    pub fn of_kind(kind: FailureKind) -> Self {
202        Self {
203            kind,
204            template: None,
205        }
206    }
207}
208
209pub fn sub_kinds(observed: &KindCounts, baseline: &KindCounts) -> KindCounts {
210    std::array::from_fn(|index| observed[index].saturating_sub(baseline[index]))
211}
212
213pub fn add_kinds(total: &mut KindCounts, delta: &KindCounts) {
214    for (slot, added) in total.iter_mut().zip(delta) {
215        *slot = slot.saturating_add(*added);
216    }
217}
218
219/// Non-zero classes for the wire, capped so they never exceed `failures`.
220pub fn wire_kinds(counts: &KindCounts, failures: u64) -> Option<BTreeMap<FailureKind, u64>> {
221    let mut remaining = failures;
222    let map: BTreeMap<_, _> = FAILURE_KINDS
223        .iter()
224        .zip(counts)
225        .filter_map(|(kind, count)| {
226            let count = (*count).min(remaining);
227            remaining -= count;
228            (count > 0).then_some((*kind, count))
229        })
230        .collect();
231    (!map.is_empty()).then_some(map)
232}
233
234/// Failure templates reported per tool and day.
235pub const MAX_FAILURE_MESSAGES: usize = 5;
236
237/// The most frequent scrubbed templates of `tool` (keys `tool\ttemplate`),
238/// counts capped so they never exceed `failures`.
239pub fn wire_messages(
240    messages: &BTreeMap<String, u64>,
241    tool: &str,
242    failures: u64,
243) -> Option<Vec<crate::core::telemetry_v2::FailureMessage>> {
244    let prefix = format!("{tool}\t");
245    let mut found: Vec<(&str, u64)> = messages
246        .iter()
247        .filter_map(|(key, count)| Some((key.strip_prefix(&prefix)?, *count)))
248        .filter(|(template, count)| *count > 0 && !template.is_empty())
249        .collect();
250    found.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
251    let mut remaining = failures;
252    let list: Vec<_> = found
253        .into_iter()
254        .take(MAX_FAILURE_MESSAGES)
255        .filter_map(|(template, count)| {
256            let count = count.min(remaining);
257            remaining -= count;
258            (count > 0).then(|| crate::core::telemetry_v2::FailureMessage {
259                template: template.to_string(),
260                count,
261            })
262        })
263        .collect();
264    (!list.is_empty()).then_some(list)
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270
271    #[test]
272    fn messages_map_to_closed_classes_most_specific_first() {
273        for (message, kind) in [
274            (
275                "[POLICY BLOCKED] command not in allowlist",
276                FailureKind::PolicyBlocked,
277            ),
278            ("command timed out after 120s", FailureKind::Timeout),
279            ("old_string not found in file", FailureKind::Conflict),
280            (
281                "CONFLICT: line 12 hash mismatch, re-read",
282                FailureKind::Conflict,
283            ),
284            ("path escapes project root: /etc", FailureKind::Permission),
285            ("Permission denied (os error 13)", FailureKind::Permission),
286            (
287                "No such file or directory (os error 2)",
288                FailureKind::NotFound,
289            ),
290            ("file is too large to read in full", FailureKind::TooLarge),
291            ("daemon not running", FailureKind::Unavailable),
292            (
293                "missing required parameter 'path'",
294                FailureKind::InvalidInput,
295            ),
296            ("invalid mode: banana", FailureKind::InvalidInput),
297            ("something odd happened", FailureKind::Other),
298            ("", FailureKind::Other),
299        ] {
300            assert_eq!(classify(message), kind, "{message}");
301        }
302    }
303
304    #[test]
305    fn every_kind_has_a_stable_wire_name_and_index() {
306        for (index, kind) in FAILURE_KINDS.iter().enumerate() {
307            assert_eq!(kind.index(), index);
308            assert_eq!(
309                serde_json::to_string(kind).unwrap(),
310                format!("\"{}\"", kind.as_str())
311            );
312        }
313    }
314}