返回 CodeWhale
turn_heartbeat.rs
根目录 / crates / engine / src / core / engine / turn_heartbeat.rs
1 //! Turn-phase heartbeat and stall self-report (#6184).
2 //!
3 //! A turn that stops producing output used to leave no trace: no log line,
4 //! nothing in `crashes/`, and a UI that could not tell a quiet model wait from
5 //! a wedged engine. The engine now publishes *where* a turn is (its phase), a
6 //! monotonic last-progress stamp, and the bound the current phase may stay
7 //! silent for. A watchdog task, independent of the turn future, turns an
8 //! overdue bounded phase into a log line, a stall record under `crashes/`, and
9 //! a status event naming the phase.
10 //!
11 //! While a request waits on the provider, the logged `bound_secs` is the
12 //! timeout that request is under (the response-header wait, then the wait for
13 //! the first stream event), and `stall_after_secs` is when this watchdog steps
14 //! in. The watchdog allows more than one header wait because the client may
15 //! send the request again inside one open (HTTP/1.1 fallback, HTTP retries);
16 //! it does not track those sends individually.
17 //!
18 //! Phases that are owned by their own bound elsewhere — a compaction pass —
19 //! are declared *parked* (`bound = None`) and never reported here; human waits
20 //! (tool approvals and `request_user_input`) pause the active phase timer until
21 //! answered or withdrawn.
22 //!
23 //! The heartbeat is shared with the UI through `EngineHandle`, so the UI's own
24 //! watchdog reads the engine's liveness directly instead of inferring it from
25 //! the stream-chunk timeout.
26
27 use std::fmt;
28 use std::sync::{Arc, Mutex};
29 use std::time::Duration;
30
31 use codewhale_runtime::stall_report::{StallReport, report_stall};
32 use tokio::sync::mpsc;
33 use tokio::time::Instant;
34 use tokio_util::sync::CancellationToken;
35
36 use crate::core::events::Event;
37
38 /// How often the watchdog samples the heartbeat.
39 pub const STALL_WATCHDOG_TICK: Duration = Duration::from_secs(5);
40 /// Bound for the engine's own between-request work (context assembly, hooks,
41 /// MCP refresh, post-stream bookkeeping). None of it waits on a provider, so a
42 /// few minutes of silence here is a wedge, not a slow model.
43 pub const PREPARING_PHASE_BOUND: Duration = Duration::from_secs(180);
44 /// Ceiling for a tool batch, including everything the engine does after a tool
45 /// returns and before it parks the batch. The phase used to carry no bound at
46 /// all ("per-tool timeouts own it"), which left exactly that post-tool window
47 /// owned by nobody: a turn wedged there produced no stall record, no status
48 /// line and no cancellation for 56 minutes, and the UI watchdog declined to
49 /// fire because the engine still looked like the owner. A generous ceiling is
50 /// enough — a tool that outlives its own timeout is already an error, and a
51 /// legitimate long build stays far below this.
52 pub const TOOLS_PHASE_BOUND: Duration = Duration::from_secs(1800);
53 /// Grace added on top of a wait's own timeout. The inner timeout should fire
54 /// first; the heartbeat only reports when that timeout itself failed to.
55 pub const STALL_BOUND_GRACE: Duration = Duration::from_secs(30);
56
57 /// Where the active turn currently is.
58 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
59 pub enum TurnPhase {
60 Idle,
61 /// Engine-local work between provider requests.
62 Preparing,
63 /// Request sent; waiting for the stream to open and produce its first event.
64 AwaitingModel,
65 /// Stream open; waiting on the next event.
66 Streaming,
67 /// Planning or executing a tool batch (bounded by [`TOOLS_PHASE_BOUND`],
68 /// paused while awaiting human approval or input).
69 Tools,
70 /// Automatic compaction pass (parked: the pass owns its bound).
71 Compacting,
72 }
73
74 impl TurnPhase {
75 #[must_use]
76 pub const fn label(self) -> &'static str {
77 match self {
78 Self::Idle => "idle",
79 Self::Preparing => "preparing the next request",
80 Self::AwaitingModel => "waiting for the model's first response",
81 Self::Streaming => "streaming the model response",
82 Self::Tools => "running tools",
83 Self::Compacting => "compacting context",
84 }
85 }
86 }
87
88 impl fmt::Display for TurnPhase {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 f.write_str(self.label())
91 }
92 }
93
94 #[derive(Debug, Clone)]
95 struct HeartbeatState {
96 phase: TurnPhase,
97 detail: Option<String>,
98 bound: Option<Duration>,
99 declared: Option<Duration>,
100 last_progress: Instant,
101 turn_id: Option<String>,
102 provider_request: Option<String>,
103 /// Bumped on every phase change or progress touch; a stall is reported at
104 /// most once per value.
105 progress_seq: u64,
106 reported_seq: Option<u64>,
107 warned_seq: Option<u64>,
108 /// Latest report, cleared by the next progress.
109 stall: Option<StallReport>,
110 human_waits: usize,
111 }
112
113 /// Point-in-time view for the UI watchdog.
114 #[derive(Debug, Clone, PartialEq, Eq)]
115 pub struct HeartbeatSnapshot {
116 pub phase: TurnPhase,
117 pub since_progress: Duration,
118 pub bound: Option<Duration>,
119 pub stall: Option<StallReport>,
120 }
121
122 impl HeartbeatSnapshot {
123 /// The engine is inside a wait it bounds itself and has not reported as
124 /// overdue. The UI must not second-guess it. Parked phases (compaction)
125 /// stay under the UI's own watchdogs.
126 #[must_use]
127 pub fn engine_owns_live_wait(&self) -> bool {
128 self.phase != TurnPhase::Idle && self.bound.is_some() && self.stall.is_none()
129 }
130 }
131
132 /// Shared turn-phase heartbeat. Cheap to update from the turn loop.
133 #[derive(Debug)]
134 pub struct TurnHeartbeat {
135 state: Mutex<HeartbeatState>,
136 }
137
138 impl Default for TurnHeartbeat {
139 fn default() -> Self {
140 Self {
141 state: Mutex::new(HeartbeatState {
142 phase: TurnPhase::Idle,
143 detail: None,
144 bound: None,
145 declared: None,
146 last_progress: Instant::now(),
147 turn_id: None,
148 provider_request: None,
149 progress_seq: 0,
150 reported_seq: None,
151 warned_seq: None,
152 stall: None,
153 human_waits: 0,
154 }),
155 }
156 }
157 }
158
159 impl TurnHeartbeat {
160 #[must_use]
161 pub fn new() -> Arc<Self> {
162 Arc::new(Self::default())
163 }
164
165 fn with_state<R>(&self, f: impl FnOnce(&mut HeartbeatState) -> R) -> R {
166 let mut guard = self
167 .state
168 .lock()
169 .unwrap_or_else(std::sync::PoisonError::into_inner);
170 f(&mut guard)
171 }
172
173 /// A new turn starts in [`TurnPhase::Preparing`].
174 pub fn begin_turn(&self, turn_id: &str) {
175 let started = self.with_state(|state| {
176 let started = state.turn_id.as_deref() != Some(turn_id);
177 state.turn_id = Some(turn_id.to_string());
178 state.provider_request = None;
179 started
180 });
181 if started {
182 tracing::info!(target: "turn", turn_id, "turn started");
183 }
184 self.enter(TurnPhase::Preparing, None, Some(PREPARING_PHASE_BOUND));
185 }
186
187 /// Enter `phase`. `bound = None` declares a parked wait that this watchdog
188 /// never reports.
189 pub fn enter(&self, phase: TurnPhase, detail: Option<String>, bound: Option<Duration>) {
190 self.enter_declared(phase, detail, bound, bound);
191 }
192
193 pub fn enter_declared(
194 &self,
195 phase: TurnPhase,
196 detail: Option<String>,
197 declared: Option<Duration>,
198 bound: Option<Duration>,
199 ) {
200 let changed = self.with_state(|state| {
201 let changed =
202 (state.phase != phase || state.detail != detail || state.declared != declared)
203 .then(|| state.turn_id.clone());
204 state.phase = phase;
205 state.detail = detail.clone();
206 state.bound = bound;
207 state.declared = declared;
208 state.last_progress = Instant::now();
209 state.progress_seq = state.progress_seq.wrapping_add(1);
210 state.stall = None;
211 changed
212 });
213 if let Some(turn_id) = changed {
214 tracing::info!(
215 target: "turn",
216 turn_id = turn_id.as_deref().unwrap_or(""),
217 phase = phase.label(),
218 detail = detail.as_deref().unwrap_or(""),
219 bound_secs = declared.map_or(0, |bound| bound.as_secs()),
220 stall_after_secs = bound.map_or(0, |bound| bound.as_secs()),
221 "turn phase"
222 );
223 }
224 }
225
226 /// Record progress inside the current phase.
227 pub fn touch(&self) {
228 self.with_state(|state| {
229 state.last_progress = Instant::now();
230 state.progress_seq = state.progress_seq.wrapping_add(1);
231 state.stall = None;
232 });
233 }
234
235 /// Stream progress: the first event of a request moves the phase from
236 /// awaiting-model to streaming with the inter-chunk bound; later events
237 /// only touch.
238 pub fn stream_progress(&self, streaming_bound: Duration) {
239 let entering = self.with_state(|state| state.phase != TurnPhase::Streaming);
240 if entering {
241 let detail = self.with_state(|state| state.detail.clone());
242 self.enter(TurnPhase::Streaming, detail, Some(streaming_bound));
243 } else {
244 self.touch();
245 }
246 }
247
248 /// Remember the provider's id for the in-flight response.
249 pub fn set_provider_request(&self, id: impl Into<String>) {
250 let id = id.into();
251 if id.is_empty() {
252 return;
253 }
254 self.with_state(|state| state.provider_request = Some(id));
255 }
256
257 pub fn begin_human_wait(&self) {
258 self.with_state(|state| {
259 state.human_waits = state.human_waits.saturating_add(1);
260 state.last_progress = Instant::now();
261 state.progress_seq = state.progress_seq.wrapping_add(1);
262 state.stall = None;
263 });
264 }
265
266 pub fn end_human_wait(&self) {
267 self.with_state(|state| {
268 state.human_waits = state.human_waits.saturating_sub(1);
269 state.last_progress = Instant::now();
270 state.progress_seq = state.progress_seq.wrapping_add(1);
271 state.stall = None;
272 });
273 }
274
275 #[must_use]
276 pub fn pause_human_wait(self: &Arc<Self>) -> HumanWaitGuard {
277 self.begin_human_wait();
278 HumanWaitGuard(Arc::clone(self))
279 }
280
281 pub fn idle(&self) {
282 self.enter(TurnPhase::Idle, None, None);
283 self.with_state(|state| state.turn_id = None);
284 }
285
286 #[must_use]
287 pub fn snapshot_at(&self, now: Instant) -> HeartbeatSnapshot {
288 self.with_state(|state| HeartbeatSnapshot {
289 phase: state.phase,
290 since_progress: if state.human_waits > 0 {
291 Duration::ZERO
292 } else {
293 now.saturating_duration_since(state.last_progress)
294 },
295 bound: state.bound,
296 stall: state.stall.clone(),
297 })
298 }
299
300 #[must_use]
301 pub fn snapshot(&self) -> HeartbeatSnapshot {
302 self.snapshot_at(Instant::now())
303 }
304
305 pub fn detect_slow_at(
306 &self,
307 now: Instant,
308 ) -> Option<(TurnPhase, Option<String>, Duration, Duration)> {
309 self.with_state(|state| {
310 let bound = state.bound?;
311 let since_progress = now.saturating_duration_since(state.last_progress);
312 if state.phase == TurnPhase::Idle
313 || state.human_waits > 0
314 || since_progress <= bound / 2
315 || state.warned_seq == Some(state.progress_seq)
316 {
317 return None;
318 }
319 state.warned_seq = Some(state.progress_seq);
320 Some((state.phase, state.detail.clone(), since_progress, bound))
321 })
322 }
323
324 /// Return a report the first time the current bounded phase is overdue.
325 pub fn detect_stall_at(&self, now: Instant) -> Option<StallReport> {
326 self.with_state(|state| {
327 if state.phase == TurnPhase::Idle
328 || state.human_waits > 0
329 || state.reported_seq == Some(state.progress_seq)
330 {
331 return None;
332 }
333 let bound = state.bound?;
334 let since_progress = now.saturating_duration_since(state.last_progress);
335 if since_progress <= bound {
336 return None;
337 }
338 state.reported_seq = Some(state.progress_seq);
339 let report = StallReport {
340 source: "engine",
341 phase: format!("while {}", state.phase.label()),
342 detail: state.detail.clone(),
343 turn_id: state.turn_id.clone(),
344 provider_request: state.provider_request.clone(),
345 since_progress,
346 bound: Some(bound),
347 };
348 state.stall = Some(report.clone());
349 Some(report)
350 })
351 }
352 }
353
354 pub struct HumanWaitGuard(Arc<TurnHeartbeat>);
355
356 impl Drop for HumanWaitGuard {
357 fn drop(&mut self) {
358 self.0.end_human_wait();
359 }
360 }
361
362 /// Aborts the wrapped task when dropped (the watchdog must not outlive the
363 /// engine that owns its heartbeat).
364 pub struct AbortOnDrop(pub tokio::task::JoinHandle<()>);
365
366 impl Drop for AbortOnDrop {
367 fn drop(&mut self) {
368 self.0.abort();
369 }
370 }
371
372 pub struct IdleOnDrop(pub Arc<TurnHeartbeat>);
373
374 impl Drop for IdleOnDrop {
375 fn drop(&mut self) {
376 self.0.idle();
377 }
378 }
379
380 /// Supervise `heartbeat` until the event channel closes: every overdue bounded
381 /// phase yields one log line, one stall record, and one status event.
382 pub fn spawn_turn_stall_watchdog(
383 heartbeat: Arc<TurnHeartbeat>,
384 tx_event: mpsc::Sender<Event>,
385 cancel: CancellationToken,
386 ) -> tokio::task::JoinHandle<()> {
387 spawn_turn_stall_watchdog_every(heartbeat, tx_event, cancel, STALL_WATCHDOG_TICK)
388 }
389
390 fn spawn_turn_stall_watchdog_every(
391 heartbeat: Arc<TurnHeartbeat>,
392 tx_event: mpsc::Sender<Event>,
393 cancel: CancellationToken,
394 tick: Duration,
395 ) -> tokio::task::JoinHandle<()> {
396 #[cfg(any(
397 test,
398 feature = "test-support",
399 all(feature = "test-thread-scoped-state", debug_assertions)
400 ))]
401 let test_dir = codewhale_runtime::stall_report::stall_record_dir();
402 tokio::spawn(async move {
403 #[cfg(any(
404 test,
405 feature = "test-support",
406 all(feature = "test-thread-scoped-state", debug_assertions)
407 ))]
408 codewhale_runtime::stall_report::set_test_stall_record_dir(test_dir);
409 let mut ticker = tokio::time::interval(tick);
410 ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
411 loop {
412 ticker.tick().await;
413 if tx_event.is_closed() {
414 break;
415 }
416 if let Some((phase, detail, since_progress, bound)) =
417 heartbeat.detect_slow_at(Instant::now())
418 {
419 tracing::warn!(
420 target: "turn",
421 phase = phase.label(),
422 detail = detail.as_deref().unwrap_or(""),
423 since_progress_secs = since_progress.as_secs(),
424 bound_secs = bound.as_secs(),
425 "turn phase has gone half its bound without progress"
426 );
427 }
428 if let Some(report) = heartbeat.detect_stall_at(Instant::now()) {
429 let record = report_stall(&report);
430 let mut line = report.status_line();
431 if let Some(path) = record {
432 line.push_str(&format!(" Stall record: {}", path.display()));
433 }
434 // Never block the watchdog on a full mailbox: a wedged
435 // consumer is exactly the case it exists to survive.
436 let _ = tx_event.try_send(Event::status(line));
437 // Reporting alone left a wedged turn running forever, which is
438 // the failure this watchdog exists to prevent: the status line
439 // scrolls and the turn still never ends. Cancelling turns the
440 // wedge into a finished turn with a stated reason.
441 cancel.cancel();
442 }
443 }
444 })
445 }
446
447 #[cfg(test)]
448 mod tests {
449 use super::*;
450 use codewhale_runtime::stall_report::set_test_stall_record_dir;
451
452 fn later(secs: u64) -> Instant {
453 Instant::now() + Duration::from_secs(secs)
454 }
455
456 #[test]
457 fn stall_bounded_phase_reports_once_per_episode() {
458 let heartbeat = TurnHeartbeat::new();
459 heartbeat.begin_turn("turn_1");
460 heartbeat.enter(
461 TurnPhase::AwaitingModel,
462 Some("deepseek/deepseek-v4-pro".into()),
463 Some(Duration::from_secs(60)),
464 );
465 assert!(heartbeat.detect_stall_at(Instant::now()).is_none());
466 let report = heartbeat
467 .detect_stall_at(later(61))
468 .expect("overdue bounded phase must report");
469 assert_eq!(report.turn_id.as_deref(), Some("turn_1"));
470 assert!(report.phase.contains("first response"), "{}", report.phase);
471 assert!(
472 heartbeat.detect_stall_at(later(120)).is_none(),
473 "once per episode"
474 );
475 assert!(!heartbeat.snapshot().engine_owns_live_wait());
476 heartbeat.touch();
477 assert!(
478 heartbeat.snapshot().engine_owns_live_wait(),
479 "progress clears the stall"
480 );
481 }
482
483 #[test]
484 fn stall_parked_phase_is_never_reported() {
485 let heartbeat = TurnHeartbeat::new();
486 heartbeat.begin_turn("turn_1");
487 heartbeat.enter(TurnPhase::Tools, Some("exec_shell".into()), None);
488 assert!(heartbeat.detect_stall_at(later(24 * 60 * 60)).is_none());
489 assert!(
490 !heartbeat.snapshot().engine_owns_live_wait(),
491 "parked phases stay under the UI's own watchdogs"
492 );
493 heartbeat.idle();
494 assert!(heartbeat.detect_stall_at(later(24 * 60 * 60)).is_none());
495 }
496
497 #[test]
498 fn stall_first_stream_event_switches_to_inter_chunk_bound() {
499 let heartbeat = TurnHeartbeat::new();
500 heartbeat.begin_turn("turn_1");
501 heartbeat.enter(
502 TurnPhase::AwaitingModel,
503 None,
504 Some(Duration::from_secs(10)),
505 );
506 heartbeat.stream_progress(Duration::from_secs(100));
507 let snapshot = heartbeat.snapshot();
508 assert_eq!(snapshot.phase, TurnPhase::Streaming);
509 assert_eq!(snapshot.bound, Some(Duration::from_secs(100)));
510 assert!(heartbeat.detect_stall_at(later(50)).is_none());
511 assert!(heartbeat.detect_stall_at(later(101)).is_some());
512 }
513
514 /// Fault injection: an inter-chunk wait that never ends produces a log
515 /// line, a `crashes/` stall record, and a status event within the bound
516 /// plus one watchdog tick.
517 #[tokio::test]
518 async fn stall_watchdog_writes_record_and_status_within_bound() {
519 let dir = tempfile::tempdir().expect("tempdir");
520 set_test_stall_record_dir(Some(dir.path().to_path_buf()));
521 let heartbeat = TurnHeartbeat::new();
522 heartbeat.begin_turn("turn_wedged");
523 let bound = Duration::from_millis(200);
524 let tick = Duration::from_millis(20);
525 heartbeat.enter(TurnPhase::Streaming, Some("mock/model".into()), Some(bound));
526 heartbeat.set_provider_request("resp_123");
527 let (tx, mut rx) = mpsc::channel(4);
528 let started = std::time::Instant::now();
529 let cancel = CancellationToken::new();
530 let watchdog =
531 spawn_turn_stall_watchdog_every(Arc::clone(&heartbeat), tx, cancel.clone(), tick);
532
533 let event = tokio::time::timeout(Duration::from_secs(10), rx.recv())
534 .await
535 .expect("stall status")
536 .expect("event");
537 let elapsed = started.elapsed();
538 assert!(elapsed >= bound, "not before the bound: {elapsed:?}");
539 let Event::Status { message } = event else {
540 panic!("expected status event");
541 };
542 assert!(
543 message.contains("Turn stalled while streaming"),
544 "{message}"
545 );
546 assert!(message.contains("Esc to cancel and retry"), "{message}");
547 assert!(
548 cancel.is_cancelled(),
549 "a reported stall must end the turn, not only describe it"
550 );
551 assert!(message.contains("Stall record:"), "{message}");
552
553 let records: Vec<_> = std::fs::read_dir(dir.path())
554 .expect("record dir")
555 .flatten()
556 .map(|entry| std::fs::read_to_string(entry.path()).expect("record"))
557 .collect();
558 assert_eq!(records.len(), 1, "exactly one record per stall episode");
559 assert!(records[0].contains("Kind: turn-stall"));
560 assert!(records[0].contains("Turn: turn_wedged"));
561 assert!(records[0].contains("Provider request: resp_123"));
562 watchdog.abort();
563 set_test_stall_record_dir(None);
564 }
565
566 #[test]
567 fn stall_human_wait_pauses_tools_phase_bound_and_resumes_with_fresh_budget() {
568 let heartbeat = TurnHeartbeat::new();
569 heartbeat.begin_turn("turn_human");
570 heartbeat.enter(
571 TurnPhase::Tools,
572 Some("request_user_input".into()),
573 Some(TOOLS_PHASE_BOUND),
574 );
575
576 let outer = heartbeat.pause_human_wait();
577 let overdue = later(TOOLS_PHASE_BOUND.as_secs() + 60);
578 assert!(heartbeat.detect_slow_at(overdue).is_none());
579 assert!(heartbeat.detect_stall_at(overdue).is_none());
580 let snap = heartbeat.snapshot_at(overdue);
581 assert_eq!(snap.phase, TurnPhase::Tools);
582 assert_eq!(snap.since_progress, Duration::ZERO);
583 assert!(snap.engine_owns_live_wait());
584
585 let nested = heartbeat.pause_human_wait();
586 drop(outer);
587 assert!(heartbeat.detect_slow_at(overdue).is_none());
588 assert!(heartbeat.detect_stall_at(overdue).is_none());
589
590 drop(nested);
591 assert!(heartbeat.detect_stall_at(Instant::now()).is_none());
592 let report = heartbeat
593 .detect_stall_at(later(TOOLS_PHASE_BOUND.as_secs() + 1))
594 .expect("post-answer tools stall must report");
595 assert_eq!(report.detail.as_deref(), Some("request_user_input"));
596 }
597
598 #[tokio::test]
599 async fn stall_watchdog_does_not_cancel_while_paused_for_human_wait() {
600 let dir = tempfile::tempdir().expect("tempdir");
601 set_test_stall_record_dir(Some(dir.path().to_path_buf()));
602 let heartbeat = TurnHeartbeat::new();
603 heartbeat.begin_turn("turn_human_watchdog");
604 let bound = Duration::from_millis(120);
605 let tick = Duration::from_millis(20);
606 heartbeat.enter(
607 TurnPhase::Tools,
608 Some("request_user_input".into()),
609 Some(bound),
610 );
611 let (tx, mut rx) = mpsc::channel(4);
612 let cancel = CancellationToken::new();
613 let watchdog =
614 spawn_turn_stall_watchdog_every(Arc::clone(&heartbeat), tx, cancel.clone(), tick);
615
616 let guard = heartbeat.pause_human_wait();
617 tokio::time::sleep(Duration::from_millis(260)).await;
618 assert!(!cancel.is_cancelled());
619 assert!(rx.try_recv().is_err());
620
621 drop(guard);
622 let event = tokio::time::timeout(Duration::from_secs(10), rx.recv())
623 .await
624 .expect("stall status after human wait ends")
625 .expect("event");
626 let Event::Status { message } = event else {
627 panic!("expected status event");
628 };
629 assert!(
630 message.contains("Turn stalled while running tools"),
631 "{message}"
632 );
633 assert!(cancel.is_cancelled());
634 watchdog.abort();
635 set_test_stall_record_dir(None);
636 }
637 }
638
638 lines RUST