返回 CodeWhale
stall_report.rs
根目录 / crates / runtime / src / stall_report.rs
1 use std::path::PathBuf;
2 use std::time::Duration;
3
4 /// One detected stall episode.
5 #[derive(Debug, Clone, PartialEq, Eq)]
6 pub struct StallReport {
7 /// Which watchdog saw it (`engine`, `ui`, `client`).
8 pub source: &'static str,
9 pub phase: String,
10 pub detail: Option<String>,
11 pub turn_id: Option<String>,
12 /// Provider response/request id when the stream reported one, else the
13 /// route label the request went to.
14 pub provider_request: Option<String>,
15 pub since_progress: Duration,
16 pub bound: Option<Duration>,
17 }
18
19 impl StallReport {
20 /// One user-facing line: where it stalled and what to do.
21 #[must_use]
22 pub fn status_line(&self) -> String {
23 let mut line = format!(
24 "Turn stalled {} — no progress for {}s",
25 self.phase,
26 self.since_progress.as_secs()
27 );
28 if let Some(detail) = self.detail.as_deref().filter(|d| !d.is_empty()) {
29 line.push_str(&format!(" ({detail})"));
30 }
31 line.push_str(". Press Esc to cancel and retry.");
32 line
33 }
34
35 fn record_body(&self) -> String {
36 let timestamp = chrono::Utc::now().to_rfc3339();
37 let bound = self.bound.map_or_else(
38 || "none (parked)".to_string(),
39 |b| format!("{}s", b.as_secs()),
40 );
41 format!(
42 "Kind: turn-stall\nSource: {source}\nTimestamp: {timestamp}\nPhase: {phase}\n\
43 Detail: {detail}\nTurn: {turn}\nProvider request: {request}\n\
44 No progress for: {since}s\nPhase bound: {bound}\n",
45 source = self.source,
46 phase = self.phase,
47 detail = self.detail.as_deref().unwrap_or("-"),
48 turn = self.turn_id.as_deref().unwrap_or("-"),
49 request = self.provider_request.as_deref().unwrap_or("-"),
50 since = self.since_progress.as_secs(),
51 )
52 }
53 }
54
55 #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
56 thread_local! {
57 static TEST_STALL_RECORD_DIR: std::cell::RefCell<Option<PathBuf>> =
58 const { std::cell::RefCell::new(None) };
59 }
60
61 /// Route stall records for the current test thread into `dir` (tests never
62 /// write into the real `~/.codewhale/crashes`).
63 #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
64 pub fn set_test_stall_record_dir(dir: Option<PathBuf>) {
65 TEST_STALL_RECORD_DIR.with(|slot| *slot.borrow_mut() = dir);
66 }
67
68 /// The selected profile's crash directory, shared with panic dumps.
69 pub fn stall_record_dir() -> Option<PathBuf> {
70 #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
71 {
72 TEST_STALL_RECORD_DIR.with(|slot| slot.borrow().clone())
73 }
74 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
75 {
76 codewhale_config::codewhale_home()
77 .ok()
78 .map(|home| home.join("crashes"))
79 }
80 }
81
82 /// Log a stall and write its record to `crashes/<timestamp>-turn-stall-<source>.log`.
83 /// Best effort; returns the record path only when the write succeeds. The
84 /// write runs on its own short-lived thread so no caller (engine task or UI
85 /// event loop) blocks a runtime worker on unbounded disk I/O (#6149).
86 pub fn report_stall(report: &StallReport) -> Option<PathBuf> {
87 let candidate = stall_record_dir().map(|dir| {
88 let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%S%.3fZ");
89 dir.join(format!("{stamp}-turn-stall-{}.log", report.source))
90 });
91 let path = candidate.and_then(|candidate| {
92 let body = report.record_body();
93 let (tx, rx) = std::sync::mpsc::sync_channel::<std::io::Result<()>>(1);
94 let writer_path = candidate.clone();
95 let writer = std::thread::spawn(move || {
96 let written = writer_path
97 .parent()
98 .map_or(Ok(()), std::fs::create_dir_all)
99 .and_then(|()| std::fs::write(&writer_path, body));
100 if let Err(error) = &written {
101 let msg = format!(
102 "stall record was not written to {}: {error}",
103 writer_path.display()
104 );
105 tracing::warn!(target: "turn_stall", path = %writer_path.display(), %error, "stall record was not written");
106 crate::logging::warn(&msg);
107 }
108 let _ = tx.send(written);
109 });
110 // Tests read the record right after reporting; release caps the wait.
111 #[cfg(any(test, all(feature = "test-thread-scoped-state", debug_assertions)))]
112 let wrote = {
113 let _ = writer.join();
114 matches!(rx.recv(), Ok(Ok(())))
115 };
116 #[cfg(not(any(test, all(feature = "test-thread-scoped-state", debug_assertions))))]
117 let wrote = {
118 drop(writer);
119 matches!(rx.recv_timeout(Duration::from_millis(50)), Ok(Ok(())))
120 };
121 wrote.then_some(candidate)
122 });
123 let message = format!(
124 "turn stall ({source}): phase={phase} since_progress={since}s bound={bound:?} turn={turn} request={request} detail={detail} record={record}",
125 source = report.source,
126 phase = report.phase,
127 since = report.since_progress.as_secs(),
128 bound = report.bound.map(|b| b.as_secs()),
129 turn = report.turn_id.as_deref().unwrap_or("-"),
130 request = report.provider_request.as_deref().unwrap_or("-"),
131 detail = report.detail.as_deref().unwrap_or("-"),
132 record = path
133 .as_deref()
134 .map_or_else(|| "-".to_string(), |p| p.display().to_string()),
135 );
136 tracing::warn!(target: "turn_stall", "{message}");
137 crate::logging::warn(&message);
138 path
139 }
140
141 #[cfg(test)]
142 mod tests {
143 use super::*;
144
145 struct TestDirGuard;
146
147 impl Drop for TestDirGuard {
148 fn drop(&mut self) {
149 set_test_stall_record_dir(None);
150 }
151 }
152
153 fn sample_report() -> StallReport {
154 StallReport {
155 source: "engine",
156 phase: "waiting for provider".to_string(),
157 detail: Some("test detail".to_string()),
158 turn_id: Some("turn-1".to_string()),
159 provider_request: Some("req-1".to_string()),
160 since_progress: Duration::from_secs(65),
161 bound: Some(Duration::from_secs(60)),
162 }
163 }
164
165 #[test]
166 fn report_stall_returns_path_when_write_succeeds() {
167 let dir = tempfile::tempdir().expect("tempdir");
168 let _guard = TestDirGuard;
169 set_test_stall_record_dir(Some(dir.path().to_path_buf()));
170
171 let path = report_stall(&sample_report()).expect("writable dir should return receipt");
172 let body = std::fs::read_to_string(&path).expect("record should exist on disk");
173 assert!(body.contains("Kind: turn-stall"));
174 assert!(body.contains("Source: engine"));
175 }
176
177 #[test]
178 fn report_stall_returns_none_when_write_fails() {
179 let dir = tempfile::tempdir().expect("tempdir");
180 let blocker = dir.path().join("not-a-directory");
181 std::fs::write(&blocker, b"file").expect("create blocking file");
182 let _guard = TestDirGuard;
183 set_test_stall_record_dir(Some(blocker));
184
185 let receipt = report_stall(&sample_report());
186 assert!(
187 receipt.is_none(),
188 "failed write must not return a path receipt"
189 );
190 }
191 }
192
192 lines RUST