返回 CodeWhale
session_diagnostics.rs
根目录 / crates / runtime / src / session_diagnostics.rs
1 //! Privacy-first session failure diagnostics (#2022).
2 //!
3 //! This module intentionally consumes loose JSONL event shapes instead of one
4 //! exact persisted-session schema. Runtime logs, tool audits, and future bug
5 //! exports can all emit slightly different records; the classifier only needs
6 //! redacted handles, aggregate counts, and broad failure classes.
7
8 use std::collections::{BTreeMap, BTreeSet};
9 use std::fmt;
10
11 use serde::{Deserialize, Serialize};
12 use serde_json::Value;
13
14 use codewhale_error_taxonomy::{ErrorCategory, classify_error_message};
15
16 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
17 #[serde(rename_all = "snake_case")]
18 pub enum SessionFailureClass {
19 CommandExit,
20 Network,
21 SandboxApproval,
22 MissingDependency,
23 Timeout,
24 BackgroundJob,
25 ToolSchema,
26 Model,
27 Unknown,
28 UnclosedTurn,
29 }
30
31 impl fmt::Display for SessionFailureClass {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 let label = match self {
34 Self::CommandExit => "command_exit",
35 Self::Network => "network",
36 Self::SandboxApproval => "sandbox_approval",
37 Self::MissingDependency => "missing_dependency",
38 Self::Timeout => "timeout",
39 Self::BackgroundJob => "background_job",
40 Self::ToolSchema => "tool_schema",
41 Self::Model => "model",
42 Self::Unknown => "unknown",
43 Self::UnclosedTurn => "unclosed_turn",
44 };
45 f.write_str(label)
46 }
47 }
48
49 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50 pub struct SessionFailureSource {
51 pub line: usize,
52 #[serde(skip_serializing_if = "Option::is_none")]
53 pub event: Option<String>,
54 #[serde(skip_serializing_if = "Option::is_none")]
55 pub turn_ref: Option<String>,
56 #[serde(skip_serializing_if = "Option::is_none")]
57 pub tool_name: Option<String>,
58 #[serde(skip_serializing_if = "Option::is_none")]
59 pub timestamp: Option<String>,
60 }
61
62 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63 pub struct SessionFailureSummary {
64 pub total_lines: usize,
65 pub malformed_lines: usize,
66 pub counts: BTreeMap<SessionFailureClass, usize>,
67 pub sources: BTreeMap<SessionFailureClass, Vec<SessionFailureSource>>,
68 }
69
70 impl SessionFailureSummary {
71 #[must_use]
72 #[cfg(test)]
73 pub(crate) fn count(&self, class: SessionFailureClass) -> usize {
74 self.counts.get(&class).copied().unwrap_or(0)
75 }
76
77 fn record(&mut self, class: SessionFailureClass, source: SessionFailureSource) {
78 *self.counts.entry(class).or_insert(0) += 1;
79 self.sources.entry(class).or_default().push(source);
80 }
81 }
82
83 #[must_use]
84 pub fn analyze_session_failure_jsonl(jsonl: &str) -> SessionFailureSummary {
85 let mut summary = SessionFailureSummary {
86 total_lines: 0,
87 malformed_lines: 0,
88 counts: BTreeMap::new(),
89 sources: BTreeMap::new(),
90 };
91 let mut open_turns: BTreeMap<String, SessionFailureSource> = BTreeMap::new();
92
93 for (idx, raw_line) in jsonl.lines().enumerate() {
94 let line_no = idx + 1;
95 let trimmed = raw_line.trim();
96 if trimmed.is_empty() {
97 continue;
98 }
99 summary.total_lines += 1;
100 let Ok(value) = serde_json::from_str::<Value>(trimmed) else {
101 summary.malformed_lines += 1;
102 continue;
103 };
104
105 let event = event_name(&value);
106 let turn_id = string_field_any(&value, &["turn_id", "turnId", "run_id"]);
107 let source = source_handle(line_no, &value, event.clone(), turn_id.as_deref());
108 let failure_signal = has_failure_signal(&value);
109
110 if event_matches(
111 event.as_deref(),
112 &["turn_started", "turnstarted", "turn_start"],
113 ) {
114 if let Some(turn_id) = turn_id {
115 open_turns.insert(turn_id, source);
116 }
117 continue;
118 }
119 if event_matches(
120 event.as_deref(),
121 &[
122 "turn_complete",
123 "turncompleted",
124 "turn_finished",
125 "turnfinished",
126 ],
127 ) {
128 if let Some(turn_id) = turn_id.as_ref() {
129 open_turns.remove(turn_id);
130 }
131 if failure_signal {
132 let class = classify_failure_signal(&value);
133 summary.record(class, source);
134 }
135 continue;
136 }
137
138 if failure_signal {
139 let class = classify_failure_signal(&value);
140 summary.record(class, source);
141 }
142 }
143
144 for (_, source) in open_turns {
145 summary.record(SessionFailureClass::UnclosedTurn, source);
146 }
147
148 summary
149 }
150
151 fn source_handle(
152 line: usize,
153 value: &Value,
154 event: Option<String>,
155 turn_id: Option<&str>,
156 ) -> SessionFailureSource {
157 let tool_name = string_field_any(value, &["tool_name", "toolName", "tool"])
158 .filter(|name| event.as_deref().is_none_or(|event| event != name));
159 SessionFailureSource {
160 line,
161 event,
162 turn_ref: turn_id.map(codewhale_util::utils::redacted_identifier_for_log),
163 tool_name,
164 timestamp: string_field_any(value, &["timestamp", "ts", "created_at", "createdAt"]),
165 }
166 }
167
168 fn has_failure_signal(value: &Value) -> bool {
169 numeric_field_any(value, &["exit_code", "exitCode"]).is_some_and(|code| code != 0)
170 || bool_field_any(value, &["success"]).is_some_and(|success| !success)
171 || bool_field_any(value, &["is_error", "isError"]).unwrap_or(false)
172 || failure_status(value).is_some()
173 || string_field_any(value, &["error", "stderr"]).is_some_and(|text| !text.is_empty())
174 }
175
176 fn classify_failure_signal(value: &Value) -> SessionFailureClass {
177 if let Some(message) = diagnostic_message(value) {
178 return classify_session_failure(value, &message);
179 }
180 if let Some(status) = failure_status(value) {
181 let lower = status.to_ascii_lowercase();
182 if lower.contains("timeout") || lower.contains("timed_out") {
183 return SessionFailureClass::Timeout;
184 }
185 if lower.contains("cancel") || lower.contains("background") || lower.contains("stale") {
186 return SessionFailureClass::BackgroundJob;
187 }
188 }
189 if numeric_field_any(value, &["exit_code", "exitCode"]).is_some_and(|code| code != 0) {
190 return SessionFailureClass::CommandExit;
191 }
192 SessionFailureClass::Unknown
193 }
194
195 fn is_command_exit_line(lower: &str) -> bool {
196 lower.contains("exited with code")
197 || lower.contains("non-zero")
198 || lower.contains("exit status")
199 || lower.contains("exit code")
200 }
201
202 fn failure_line(message: &str) -> &str {
203 let mut lines = message
204 .lines()
205 .map(str::trim)
206 .filter(|line| !line.is_empty());
207 let Some(first) = lines.next() else {
208 return message.trim();
209 };
210 let mut last = first;
211 let mut explicit_error = None;
212 for line in std::iter::once(first).chain(lines) {
213 last = line;
214 if explicit_error.is_none() {
215 let lower = line.to_ascii_lowercase();
216 if lower.starts_with("error:")
217 || lower.starts_with("fatal:")
218 || lower.starts_with("failed:")
219 || lower.starts_with("denied:")
220 || lower.starts_with("permission denied")
221 || lower.starts_with("command not found")
222 || lower.starts_with("no such file or directory")
223 {
224 explicit_error = Some(line);
225 }
226 }
227 }
228 if is_command_exit_line(&last.to_ascii_lowercase()) {
229 return last;
230 }
231 explicit_error.unwrap_or(first)
232 }
233
234 fn classify_session_failure(value: &Value, message: &str) -> SessionFailureClass {
235 let line = failure_line(message);
236 let lower = line.to_ascii_lowercase();
237 if lower.contains("background")
238 || lower.contains("task_shell")
239 || lower.contains("job timed out")
240 || lower.contains("job cancelled")
241 || lower.contains("stale job")
242 {
243 return SessionFailureClass::BackgroundJob;
244 }
245 if lower.contains("sandbox")
246 || lower.contains("approval")
247 || lower.contains("permission denied")
248 || lower.contains("operation not permitted")
249 || lower.contains("read-only")
250 || lower.contains("access is denied")
251 {
252 return SessionFailureClass::SandboxApproval;
253 }
254 if lower.contains("command not found")
255 || lower.contains("no such file or directory")
256 || lower.contains("missing binary")
257 || lower.contains("enoent")
258 || lower.contains("not installed")
259 {
260 return SessionFailureClass::MissingDependency;
261 }
262 if lower.contains("missing field")
263 || lower.contains("invalid tool")
264 || lower.contains("invalid input")
265 || lower.contains("schema")
266 || lower.contains("tool arguments")
267 {
268 return SessionFailureClass::ToolSchema;
269 }
270 if numeric_field_any(value, &["exit_code", "exitCode"]).is_some_and(|code| code != 0)
271 || is_command_exit_line(&lower)
272 {
273 return SessionFailureClass::CommandExit;
274 }
275 match classify_error_message(line) {
276 ErrorCategory::Network | ErrorCategory::RateLimit => SessionFailureClass::Network,
277 ErrorCategory::Timeout => SessionFailureClass::Timeout,
278 ErrorCategory::Budget => SessionFailureClass::Unknown,
279 ErrorCategory::Authorization => SessionFailureClass::SandboxApproval,
280 ErrorCategory::Authentication => SessionFailureClass::Model,
281 ErrorCategory::State => SessionFailureClass::MissingDependency,
282 ErrorCategory::Parse
283 if codewhale_error_taxonomy::unreadable_error_notice(line).is_some() =>
284 {
285 SessionFailureClass::Unknown
286 }
287 ErrorCategory::InvalidInput | ErrorCategory::Parse => SessionFailureClass::ToolSchema,
288 ErrorCategory::Tool => SessionFailureClass::CommandExit,
289 ErrorCategory::Internal if lower.contains("model") => SessionFailureClass::Model,
290 ErrorCategory::Internal => SessionFailureClass::Unknown,
291 }
292 }
293
294 fn diagnostic_message(value: &Value) -> Option<String> {
295 let mut parts = Vec::new();
296 collect_string_fields(
297 value,
298 &mut parts,
299 &[
300 "error", "message", "stderr", "reason", "result", "output", "content",
301 ],
302 0,
303 );
304 let mut seen = BTreeSet::new();
305 let deduped = parts
306 .into_iter()
307 .filter(|part| !part.trim().is_empty())
308 .filter(|part| seen.insert(part.clone()))
309 .collect::<Vec<_>>();
310 (!deduped.is_empty()).then(|| deduped.join(" "))
311 }
312
313 fn collect_string_fields(value: &Value, out: &mut Vec<String>, keys: &[&str], depth: usize) {
314 if depth > 4 {
315 return;
316 }
317 match value {
318 Value::Object(map) => {
319 for (key, value) in map {
320 if keys
321 .iter()
322 .any(|candidate| key.eq_ignore_ascii_case(candidate))
323 && let Some(text) = value.as_str()
324 {
325 out.push(text.to_string());
326 }
327 collect_string_fields(value, out, keys, depth + 1);
328 }
329 }
330 Value::Array(items) => {
331 for item in items {
332 collect_string_fields(item, out, keys, depth + 1);
333 }
334 }
335 _ => {}
336 }
337 }
338
339 fn event_name(value: &Value) -> Option<String> {
340 string_field_any(value, &["event", "type", "kind"]).map(|event| normalize_event(&event))
341 }
342
343 fn normalize_event(event: &str) -> String {
344 event
345 .trim()
346 .trim_matches('"')
347 .replace(['-', ' ', '.'], "_")
348 .to_ascii_lowercase()
349 }
350
351 fn event_matches(event: Option<&str>, aliases: &[&str]) -> bool {
352 event.is_some_and(|event| aliases.contains(&event))
353 }
354
355 fn failure_status(value: &Value) -> Option<String> {
356 string_field_any(value, &["status", "state", "outcome"]).filter(|status| {
357 let normalized = normalize_event(status);
358 matches!(
359 normalized.as_str(),
360 "failed"
361 | "failure"
362 | "error"
363 | "errored"
364 | "cancelled"
365 | "canceled"
366 | "timeout"
367 | "timed_out"
368 | "stale"
369 )
370 })
371 }
372
373 fn string_field_any(value: &Value, keys: &[&str]) -> Option<String> {
374 string_field_any_at(value, keys, 0)
375 }
376
377 fn string_field_any_at(value: &Value, keys: &[&str], depth: usize) -> Option<String> {
378 if depth > 4 {
379 return None;
380 }
381 match value {
382 Value::Object(map) => {
383 for key in keys {
384 if let Some(value) = map.iter().find_map(|(candidate, value)| {
385 candidate.eq_ignore_ascii_case(key).then_some(value)
386 }) && let Some(text) = value.as_str()
387 {
388 return Some(text.to_string());
389 }
390 }
391 for child in map.values() {
392 if let Some(found) = string_field_any_at(child, keys, depth + 1) {
393 return Some(found);
394 }
395 }
396 None
397 }
398 Value::Array(items) => items
399 .iter()
400 .find_map(|item| string_field_any_at(item, keys, depth + 1)),
401 _ => None,
402 }
403 }
404
405 fn numeric_field_any(value: &Value, keys: &[&str]) -> Option<i64> {
406 numeric_field_any_at(value, keys, 0)
407 }
408
409 fn numeric_field_any_at(value: &Value, keys: &[&str], depth: usize) -> Option<i64> {
410 if depth > 4 {
411 return None;
412 }
413 match value {
414 Value::Object(map) => {
415 for key in keys {
416 if let Some(value) = map.iter().find_map(|(candidate, value)| {
417 candidate.eq_ignore_ascii_case(key).then_some(value)
418 }) && let Some(number) = value.as_i64()
419 {
420 return Some(number);
421 }
422 }
423 for child in map.values() {
424 if let Some(found) = numeric_field_any_at(child, keys, depth + 1) {
425 return Some(found);
426 }
427 }
428 None
429 }
430 Value::Array(items) => items
431 .iter()
432 .find_map(|item| numeric_field_any_at(item, keys, depth + 1)),
433 _ => None,
434 }
435 }
436
437 fn bool_field_any(value: &Value, keys: &[&str]) -> Option<bool> {
438 bool_field_any_at(value, keys, 0)
439 }
440
441 fn bool_field_any_at(value: &Value, keys: &[&str], depth: usize) -> Option<bool> {
442 if depth > 4 {
443 return None;
444 }
445 match value {
446 Value::Object(map) => {
447 for key in keys {
448 if let Some(value) = map.iter().find_map(|(candidate, value)| {
449 candidate.eq_ignore_ascii_case(key).then_some(value)
450 }) && let Some(flag) = value.as_bool()
451 {
452 return Some(flag);
453 }
454 }
455 for child in map.values() {
456 if let Some(found) = bool_field_any_at(child, keys, depth + 1) {
457 return Some(found);
458 }
459 }
460 None
461 }
462 Value::Array(items) => items
463 .iter()
464 .find_map(|item| bool_field_any_at(item, keys, depth + 1)),
465 _ => None,
466 }
467 }
468
469 #[cfg(test)]
470 mod tests {
471 use super::*;
472
473 #[test]
474 fn bare_error_placeholder_is_not_a_schema_failure() {
475 // The taxonomy files a bare "error" under Parse so provider turns can
476 // call it unreadable; a tool that printed only that is not a schema bug.
477 let value = serde_json::json!({});
478 assert_eq!(
479 classify_session_failure(&value, "ERROR"),
480 SessionFailureClass::Unknown
481 );
482 }
483
484 #[test]
485 fn synthetic_jsonl_classifies_environment_and_tool_failures() {
486 let jsonl = r#"
487 {"event":"turn_started","turn_id":"turn-secret-1","timestamp":"2026-06-25T12:00:00Z"}
488 {"event":"tool_call_complete","turn_id":"turn-secret-1","tool_name":"exec_shell","exit_code":127,"stderr":"bash: rg: command not found"}
489 {"event":"tool_call_complete","turn_id":"turn-secret-1","tool_name":"exec_shell","exit_code":2,"stderr":"command failed with exit code 2"}
490 {"event":"tool_call_complete","turn_id":"turn-secret-1","tool_name":"web_search","error":"DNS resolution failed for api.example.test"}
491 {"event":"tool_call_complete","turn_id":"turn-secret-1","tool_name":"apply_patch","error":"Permission denied by sandbox: read-only filesystem"}
492 {"event":"tool_call_complete","turn_id":"turn-secret-1","tool_name":"exec_shell","error":"request timed out after 30s"}
493 {"event":"tool_call_complete","turn_id":"turn-secret-1","tool_name":"task_shell_wait","error":"background job timed out"}
494 {"event":"tool_call_complete","turn_id":"turn-secret-1","tool_name":"mcp_tool","error":"missing field: tool arguments"}
495 {"event":"turn_complete","turn_id":"turn-secret-1","status":"completed"}
496 {"event":"turn_started","turn_id":"turn-secret-2"}
497 not json at all
498 "#;
499
500 let summary = analyze_session_failure_jsonl(jsonl);
501
502 assert_eq!(summary.malformed_lines, 1);
503 assert_eq!(summary.count(SessionFailureClass::MissingDependency), 1);
504 assert_eq!(summary.count(SessionFailureClass::CommandExit), 1);
505 assert_eq!(summary.count(SessionFailureClass::Network), 1);
506 assert_eq!(summary.count(SessionFailureClass::SandboxApproval), 1);
507 assert_eq!(summary.count(SessionFailureClass::Timeout), 1);
508 assert_eq!(summary.count(SessionFailureClass::BackgroundJob), 1);
509 assert_eq!(summary.count(SessionFailureClass::ToolSchema), 1);
510 assert_eq!(summary.count(SessionFailureClass::UnclosedTurn), 1);
511
512 let sources = summary
513 .sources
514 .get(&SessionFailureClass::MissingDependency)
515 .expect("missing-dependency source");
516 assert_eq!(sources[0].tool_name.as_deref(), Some("exec_shell"));
517 assert!(
518 sources[0]
519 .turn_ref
520 .as_deref()
521 .is_some_and(|turn| turn.starts_with("<redacted:")),
522 "turn ids must be redacted: {sources:?}"
523 );
524 }
525
526 #[test]
527 fn successful_content_does_not_create_unknown_failure() {
528 let jsonl = r#"
529 {"event":"turn_started","turn_id":"turn-secret-1"}
530 {"event":"tool_call_complete","turn_id":"turn-secret-1","tool_name":"exec_shell","success":true,"content":"command output mentioning error budgets is still normal content"}
531 {"event":"turn_complete","turn_id":"turn-secret-1","status":"completed","message":"done"}
532 "#;
533
534 let summary = analyze_session_failure_jsonl(jsonl);
535
536 assert_eq!(summary.count(SessionFailureClass::Unknown), 0);
537 assert_eq!(summary.count(SessionFailureClass::CommandExit), 0);
538 assert_eq!(summary.count(SessionFailureClass::UnclosedTurn), 0);
539 assert!(
540 summary.counts.is_empty(),
541 "summary should be empty: {summary:?}"
542 );
543 }
544
545 #[test]
546 fn empty_error_field_is_not_a_failure_signal() {
547 let jsonl = r#"
548 {"event":"tool_call_complete","success":true,"error":"","stderr":""}
549 "#;
550
551 let summary = analyze_session_failure_jsonl(jsonl);
552
553 assert!(
554 summary.counts.is_empty(),
555 "empty error/stderr sentinels should not signal failure: {summary:?}"
556 );
557 }
558
559 #[test]
560 fn nested_generic_fields_do_not_shadow_source_handles() {
561 let jsonl = r#"
562 {"event":"tool_call_complete","turn_id":"turn-real","tool_name":"exec_shell","success":false,"payload":{"id":"nested-id","name":"nested-name","error":"nested error"}}
563 "#;
564
565 let summary = analyze_session_failure_jsonl(jsonl);
566 let source = summary
567 .sources
568 .values()
569 .flat_map(|sources| sources.iter())
570 .next()
571 .expect("failure source");
572
573 assert_eq!(source.tool_name.as_deref(), Some("exec_shell"));
574 assert!(
575 source
576 .turn_ref
577 .as_deref()
578 .is_some_and(|turn| turn.starts_with("<redacted:")),
579 "top-level turn id should be redacted and used: {source:?}"
580 );
581 }
582
583 #[test]
584 fn deeply_nested_error_field_is_ignored() {
585 let jsonl = r#"
586 {"event":"tool_call_complete","payload":{"a":{"b":{"c":{"d":{"e":{"error":"too deep"}}}}}}}
587 "#;
588
589 let summary = analyze_session_failure_jsonl(jsonl);
590
591 assert!(
592 summary.counts.is_empty(),
593 "deeply nested error fields should not signal failure: {summary:?}"
594 );
595 }
596
597 #[test]
598 fn authentication_failures_are_model_failures_not_sandbox_approval() {
599 let jsonl = r#"
600 {"event":"model_response","success":false,"error":"Authentication failed: invalid API key"}
601 "#;
602
603 let summary = analyze_session_failure_jsonl(jsonl);
604
605 assert_eq!(summary.count(SessionFailureClass::Model), 1);
606 assert_eq!(summary.count(SessionFailureClass::SandboxApproval), 0);
607 }
608
609 #[test]
610 fn shell_exited_with_code_is_command_exit_despite_noisy_stdout() {
611 let jsonl = serde_json::json!({
612 "event": "tool_error",
613 "is_error": true,
614 "message": "checking sandbox approval policy\nread-only config loaded\nno such file or directory in optional hint\n\nCommand exited with code 7"
615 })
616 .to_string();
617
618 let summary = analyze_session_failure_jsonl(&jsonl);
619
620 assert_eq!(summary.count(SessionFailureClass::CommandExit), 1);
621 assert_eq!(summary.count(SessionFailureClass::SandboxApproval), 0);
622 assert_eq!(summary.count(SessionFailureClass::MissingDependency), 0);
623 assert_eq!(summary.count(SessionFailureClass::Unknown), 0);
624 }
625 }
626
626 lines RUST