| 1 | //! Post-hoc detection of foreground hangs from the journal's event stream. |
| 2 | //! |
| 3 | //! A hang is any single piece of foreground work — a task poll, an action |
| 4 | //! handler, an input dispatch, a window draw, or platform presentation — that |
| 5 | //! blocked the foreground thread for at least a threshold duration. An |
| 6 | //! interval whose total foreground spend reached the frame budget also |
| 7 | //! counts, even when no single event crossed the threshold: many small |
| 8 | //! pieces of work can drop a frame — or starve a headless app — as |
| 9 | //! thoroughly as one long stall. [`HangDetector`] drains the journal and |
| 10 | //! reports each completed activity interval containing hangs as a |
| 11 | //! [`HangIncident`]. |
| 12 | |
| 13 | use std::time::Duration; |
| 14 | |
| 15 | use scheduler::Instant; |
| 16 | use serde::Serialize; |
| 17 | |
| 18 | #[cfg(not(target_family = "wasm"))] |
| 19 | mod monitor; |
| 20 | #[cfg(not(target_family = "wasm"))] |
| 21 | pub(crate) use monitor::HangMonitor; |
| 22 | #[cfg(not(target_family = "wasm"))] |
| 23 | pub use monitor::{HangMonitorConfig, HangMonitorError, HangMonitorPoll, HangMonitorPollReason}; |
| 24 | |
| 25 | /// Version of the power/visibility-aware measurement rules. |
| 26 | pub const MEASUREMENT_VERSION: u32 = 2; |
| 27 | |
| 28 | use super::SerializedLocation; |
| 29 | use super::journal::{ |
| 30 | ForegroundEvent, ForegroundJournal, ForegroundJournalCollector, ForegroundJournalEntry, |
| 31 | FrameSnapshot, IntervalBoundary, IntervalSealer, |
| 32 | }; |
| 33 | |
| 34 | /// Detects foreground hangs by polling the journal. |
| 35 | /// |
| 36 | /// Detection is post-hoc: a hang is reported once an explicit presentation, |
| 37 | /// completed frame skip, or foreground-idle boundary completes its interval. |
| 38 | /// Work that never yields back to the foreground is not observed until it does. |
| 39 | pub struct HangDetector { |
| 40 | collector: ForegroundJournalCollector, |
| 41 | sealer: IntervalSealer, |
| 42 | threshold: Duration, |
| 43 | frame_budget: Duration, |
| 44 | first_present_at: Option<Instant>, |
| 45 | } |
| 46 | |
| 47 | /// One sealed interval that contained at least one hang. |
| 48 | #[derive(Debug, Clone)] |
| 49 | pub struct HangIncident { |
| 50 | /// The interval the hangs occurred in, including all non-hang foreground |
| 51 | /// work recorded alongside them. |
| 52 | pub snapshot: FrameSnapshot, |
| 53 | /// Which detection rule qualified the interval. |
| 54 | pub trigger: HangTrigger, |
| 55 | /// For [`HangTrigger::Threshold`], the events that blocked the foreground |
| 56 | /// for at least the detector's threshold, longest first. For |
| 57 | /// [`HangTrigger::Budget`], no event crossed the threshold and this instead |
| 58 | /// holds every event in the interval, longest first. |
| 59 | pub contributors: Vec<ForegroundEvent>, |
| 60 | } |
| 61 | |
| 62 | /// The detection rule that qualified an interval as a [`HangIncident`]. |
| 63 | /// |
| 64 | /// Recorded explicitly so consumers can separate the two classes without |
| 65 | /// re-deriving them from `stall_ms`, which stops working whenever the |
| 66 | /// detector's thresholds change. |
| 67 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 68 | #[serde(rename_all = "snake_case")] |
| 69 | pub enum HangTrigger { |
| 70 | /// A single event blocked the foreground for at least the hang threshold. |
| 71 | Threshold, |
| 72 | /// No single event crossed the threshold, but the interval's total |
| 73 | /// foreground spend reached the frame budget. |
| 74 | Budget, |
| 75 | } |
| 76 | |
| 77 | impl HangDetector { |
| 78 | /// Creates a detector reporting single events at or above `threshold` |
| 79 | /// and intervals whose total foreground spend reached `frame_budget`. |
| 80 | /// Only events recorded from this point on are observed. |
| 81 | pub fn new(journal: ForegroundJournal, threshold: Duration, frame_budget: Duration) -> Self { |
| 82 | Self { |
| 83 | collector: journal.collector(), |
| 84 | sealer: IntervalSealer::new(Instant::now()), |
| 85 | threshold, |
| 86 | frame_budget, |
| 87 | first_present_at: None, |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | /// When the first newly drawn frame observed by this detector finished |
| 92 | /// platform submission. `None` until a presentation boundary is observed. |
| 93 | pub fn first_present_at(&self) -> Option<Instant> { |
| 94 | self.first_present_at |
| 95 | } |
| 96 | |
| 97 | /// Drains newly recorded events and returns the incidents sealed since |
| 98 | /// the previous poll. |
| 99 | pub fn poll(&mut self) -> Vec<HangIncident> { |
| 100 | let drained = self.collector.collect_unseen(); |
| 101 | if self.first_present_at.is_none() { |
| 102 | self.first_present_at = drained.entries.iter().find_map(|entry| match entry { |
| 103 | ForegroundJournalEntry::Boundary(IntervalBoundary::Presented(presented)) => { |
| 104 | Some(presented.presentation.present_end) |
| 105 | } |
| 106 | _ => None, |
| 107 | }); |
| 108 | } |
| 109 | self.sealer |
| 110 | .push_entries(drained.entries) |
| 111 | .into_iter() |
| 112 | .filter_map(|snapshot| { |
| 113 | HangIncident::detect(snapshot, self.threshold, self.frame_budget) |
| 114 | }) |
| 115 | .collect() |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | /// A [`HangIncident`] in a telemetry-friendly form: timestamps and durations |
| 120 | /// in fractional milliseconds since app startup (microsecond precision), |
| 121 | /// locations as plain data, contributor count capped by the converter. |
| 122 | #[derive(Debug, Clone, Serialize)] |
| 123 | pub struct SerializedHangIncident { |
| 124 | /// Identifies the rules used to exclude interrupted measurements. |
| 125 | pub measurement_version: u32, |
| 126 | /// `"startup"` when the active window began before the first observed |
| 127 | /// newly drawn frame finished platform submission (see |
| 128 | /// [`HangDetector::first_present_at`]), otherwise `"steady"`. |
| 129 | pub phase: &'static str, |
| 130 | /// `"threshold"` or `"budget"` (see [`HangTrigger`]). |
| 131 | pub trigger: HangTrigger, |
| 132 | /// When the incident's active window started, in milliseconds since app |
| 133 | /// startup: the sealing frame's first invalidation, or the earliest |
| 134 | /// contributor's start when nothing was pending a repaint. Foreground |
| 135 | /// idle time between the previous frame and the cause is excluded. |
| 136 | pub start_ms: f64, |
| 137 | /// Length of the active window in milliseconds: from the cause to the |
| 138 | /// seal. Exceeds `stall_ms` when several stalls piled up on one frame. |
| 139 | pub active_ms: f64, |
| 140 | /// The longest single block of foreground work, in milliseconds: the |
| 141 | /// best estimate of the freeze a user perceived. Below the hang |
| 142 | /// threshold (possibly zero) when the frame budget alone triggered the |
| 143 | /// incident. |
| 144 | pub stall_ms: f64, |
| 145 | /// For presentation-sealed incidents, how long the submitted frame had |
| 146 | /// been dirty, in milliseconds. |
| 147 | pub dirty_to_present_ms: Option<f64>, |
| 148 | /// What closed the incident: `"present"`, `"frame_skipped"`, `"idle"`, or |
| 149 | /// `"power_transition"`. This labels the boundary, not the hang's cause — |
| 150 | /// the cause is the first contributor. |
| 151 | pub sealed_by: &'static str, |
| 152 | /// Fraction of the active window the foreground spent working, |
| 153 | /// `0.0..=1.0`. Low values with a high `dirty_to_present_ms` indicate |
| 154 | /// throttling or scheduling delay rather than application work. |
| 155 | pub busy_fraction: f64, |
| 156 | /// Total events recorded in the interval (before the contributor cap). |
| 157 | pub event_count: usize, |
| 158 | /// Count of task polls below the journal's floor. |
| 159 | pub small_poll_count: u64, |
| 160 | /// Total duration of task polls below the journal's floor, in milliseconds. |
| 161 | pub small_poll_total_ms: f64, |
| 162 | /// Events lost to caps or ring overwrites. |
| 163 | pub dropped_events: u64, |
| 164 | /// Whether one or more journal entries were unavailable in the interval. |
| 165 | /// Threshold-qualified contributors remain valid, but cumulative budget |
| 166 | /// conclusions and boundary attribution are not trusted across the gap. |
| 167 | pub journal_discontinuous: bool, |
| 168 | /// The incident's contributors (see [`HangIncident::contributors`]) in |
| 169 | /// start order. The cap keeps the longest ones; `stall_ms` is always |
| 170 | /// among them. |
| 171 | pub contributors: Vec<SerializedHangContributor>, |
| 172 | /// Contributors elided by the cap. |
| 173 | pub contributors_elided: usize, |
| 174 | } |
| 175 | |
| 176 | /// One hang contributor in serialized form. |
| 177 | /// |
| 178 | /// Foreground work nests: an input dispatch can synchronously draw a window, |
| 179 | /// a draw can poll a task. `depth` expresses that containment — a depth-1 |
| 180 | /// event's time is already inside some depth-0 event's duration, so summing |
| 181 | /// sibling durations across depths double-counts. |
| 182 | #[derive(Debug, Clone, Serialize)] |
| 183 | #[serde(tag = "kind", rename_all = "snake_case")] |
| 184 | pub enum SerializedHangContributor { |
| 185 | /// A foreground task poll. |
| 186 | TaskPoll { |
| 187 | /// Where the task was spawned. |
| 188 | location: SerializedLocation, |
| 189 | /// When the poll started, in milliseconds since app startup. |
| 190 | start_ms: f64, |
| 191 | /// How long the poll blocked the foreground, in milliseconds. |
| 192 | duration_ms: f64, |
| 193 | /// How many other events in the interval contain this one. |
| 194 | depth: usize, |
| 195 | }, |
| 196 | /// An action handler. |
| 197 | Action { |
| 198 | /// The action's name. |
| 199 | name: &'static str, |
| 200 | /// When the handler started, in milliseconds since app startup. |
| 201 | start_ms: f64, |
| 202 | /// How long the handler ran, in milliseconds. |
| 203 | duration_ms: f64, |
| 204 | /// How many other events in the interval contain this one. |
| 205 | depth: usize, |
| 206 | }, |
| 207 | /// A platform input dispatch. |
| 208 | Input { |
| 209 | /// The platform input variant dispatched, e.g. `"key_down"`. |
| 210 | /// Named `input_kind` because `kind` is this enum's serde tag. |
| 211 | input_kind: &'static str, |
| 212 | /// When the dispatch started, in milliseconds since app startup. |
| 213 | start_ms: f64, |
| 214 | /// How long the dispatch ran, in milliseconds. |
| 215 | duration_ms: f64, |
| 216 | /// Whether handling the input invalidated a window. |
| 217 | caused_invalidation: bool, |
| 218 | /// How many other events in the interval contain this one. |
| 219 | depth: usize, |
| 220 | }, |
| 221 | /// A window draw. |
| 222 | Draw { |
| 223 | /// The window that was drawn. |
| 224 | window_id: u64, |
| 225 | /// When the draw started, in milliseconds since app startup. |
| 226 | start_ms: f64, |
| 227 | /// How long the draw took, in milliseconds. |
| 228 | duration_ms: f64, |
| 229 | /// Time from the frame's first invalidation to the end of its draw, |
| 230 | /// in milliseconds. |
| 231 | dirty_to_draw_ms: Option<f64>, |
| 232 | /// Invalidations coalesced into the frame. |
| 233 | invalidations: u64, |
| 234 | /// How many other events in the interval contain this one. |
| 235 | depth: usize, |
| 236 | }, |
| 237 | /// Work spent submitting a frame to the platform. |
| 238 | Present { |
| 239 | /// The window whose frame was submitted. |
| 240 | window_id: u64, |
| 241 | /// When submission began, in milliseconds since app startup. |
| 242 | start_ms: f64, |
| 243 | /// How long platform submission took, in milliseconds. |
| 244 | duration_ms: f64, |
| 245 | /// How many other events in the interval contain this one. |
| 246 | depth: usize, |
| 247 | }, |
| 248 | } |
| 249 | |
| 250 | /// Milliseconds with microsecond precision: keeps `dbg!`/JSON output short |
| 251 | /// (`115.954` rather than `115.95400000000001` or `115954`). |
| 252 | fn as_millis(duration: Duration) -> f64 { |
| 253 | duration.as_micros() as f64 / 1000.0 |
| 254 | } |
| 255 | |
| 256 | impl SerializedHangIncident { |
| 257 | /// Converts an incident, keeping at most `max_contributors` contributors. |
| 258 | /// `first_present_at` is the end of the first observed newly drawn frame's |
| 259 | /// platform submission (typically [`HangDetector::first_present_at`]); |
| 260 | /// incidents whose active window begins before it are tagged `"startup"`. |
| 261 | pub fn convert( |
| 262 | startup: Instant, |
| 263 | incident: &HangIncident, |
| 264 | max_contributors: usize, |
| 265 | first_present_at: Option<Instant>, |
| 266 | ) -> Self { |
| 267 | let since_startup = |
| 268 | |instant: Instant| as_millis(instant.saturating_duration_since(startup)); |
| 269 | let snapshot = &incident.snapshot; |
| 270 | let (active_start, active_end) = incident.active_window(); |
| 271 | let active = active_end.duration_since(active_start); |
| 272 | let busy_fraction = if active.is_zero() { |
| 273 | 1.0 |
| 274 | } else { |
| 275 | snapshot |
| 276 | .occupancy_within(active_start, active_end) |
| 277 | .div_duration_f64(active) |
| 278 | .min(1.0) |
| 279 | }; |
| 280 | Self { |
| 281 | phase: match first_present_at { |
| 282 | Some(first_present_at) if active_start >= first_present_at => "steady", |
| 283 | _ => "startup", |
| 284 | }, |
| 285 | measurement_version: MEASUREMENT_VERSION, |
| 286 | trigger: incident.trigger, |
| 287 | start_ms: since_startup(active_start), |
| 288 | active_ms: as_millis(active), |
| 289 | stall_ms: incident |
| 290 | .contributors |
| 291 | .first() |
| 292 | .map(|event| as_millis(event.duration())) |
| 293 | .unwrap_or(0.0), |
| 294 | dirty_to_present_ms: match snapshot.boundary { |
| 295 | IntervalBoundary::Presented(presented) => { |
| 296 | presented.dirty_to_present_duration().map(as_millis) |
| 297 | } |
| 298 | IntervalBoundary::FrameSkipped(_) |
| 299 | | IntervalBoundary::Idle { .. } |
| 300 | | IntervalBoundary::PowerTransition { .. } => None, |
| 301 | }, |
| 302 | sealed_by: match snapshot.boundary { |
| 303 | IntervalBoundary::Presented(_) => "present", |
| 304 | IntervalBoundary::FrameSkipped(_) => "frame_skipped", |
| 305 | IntervalBoundary::Idle { .. } => "idle", |
| 306 | IntervalBoundary::PowerTransition { .. } => "power_transition", |
| 307 | }, |
| 308 | busy_fraction: (busy_fraction * 1000.0).round() / 1000.0, |
| 309 | event_count: snapshot.events.len(), |
| 310 | small_poll_count: snapshot.small_poll_summary().count, |
| 311 | small_poll_total_ms: as_millis(snapshot.small_poll_summary().total), |
| 312 | dropped_events: snapshot.dropped_events, |
| 313 | journal_discontinuous: snapshot.journal_discontinuous, |
| 314 | contributors: { |
| 315 | let mut kept: Vec<&ForegroundEvent> = incident |
| 316 | .contributors |
| 317 | .iter() |
| 318 | .take(max_contributors) |
| 319 | .collect(); |
| 320 | kept.sort_by_key(|event| event.start_time()); |
| 321 | kept.into_iter() |
| 322 | .map(|event| { |
| 323 | SerializedHangContributor::convert( |
| 324 | startup, |
| 325 | event, |
| 326 | nesting_depth(event, &snapshot.events), |
| 327 | ) |
| 328 | }) |
| 329 | .collect() |
| 330 | }, |
| 331 | contributors_elided: incident.contributors.len().saturating_sub(max_contributors), |
| 332 | } |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | /// How many events in `events` strictly contain `event`'s span. Events with |
| 337 | /// identical spans don't count as containing each other, so `event`'s own |
| 338 | /// presence in `events` contributes nothing. |
| 339 | fn nesting_depth(event: &ForegroundEvent, events: &[ForegroundEvent]) -> usize { |
| 340 | let (start, end) = (event.start_time(), event.end_time()); |
| 341 | events |
| 342 | .iter() |
| 343 | .filter(|other| { |
| 344 | let (other_start, other_end) = (other.start_time(), other.end_time()); |
| 345 | other_start <= start && end <= other_end && (other_start < start || end < other_end) |
| 346 | }) |
| 347 | .count() |
| 348 | } |
| 349 | |
| 350 | impl SerializedHangContributor { |
| 351 | fn convert(startup: Instant, event: &ForegroundEvent, depth: usize) -> Self { |
| 352 | let since_startup = |
| 353 | |instant: Instant| as_millis(instant.saturating_duration_since(startup)); |
| 354 | let duration_ms = as_millis(event.duration()); |
| 355 | match event { |
| 356 | ForegroundEvent::TaskPoll(timing) => Self::TaskPoll { |
| 357 | location: timing.location.into(), |
| 358 | start_ms: since_startup(timing.start), |
| 359 | duration_ms, |
| 360 | depth, |
| 361 | }, |
| 362 | ForegroundEvent::Action(timing) => Self::Action { |
| 363 | name: timing.name, |
| 364 | start_ms: since_startup(timing.start), |
| 365 | duration_ms, |
| 366 | depth, |
| 367 | }, |
| 368 | ForegroundEvent::Input(timing) => Self::Input { |
| 369 | input_kind: timing.kind, |
| 370 | start_ms: since_startup(timing.start), |
| 371 | duration_ms, |
| 372 | caused_invalidation: timing.caused_invalidation, |
| 373 | depth, |
| 374 | }, |
| 375 | ForegroundEvent::Draw(timing) => Self::Draw { |
| 376 | window_id: timing.window_id.as_u64(), |
| 377 | start_ms: since_startup(timing.draw_start), |
| 378 | duration_ms, |
| 379 | dirty_to_draw_ms: timing.dirty_to_draw_duration().map(as_millis), |
| 380 | invalidations: timing.invalidations, |
| 381 | depth, |
| 382 | }, |
| 383 | ForegroundEvent::Present(timing) => Self::Present { |
| 384 | window_id: timing.window_id.as_u64(), |
| 385 | start_ms: since_startup(timing.present_start), |
| 386 | duration_ms, |
| 387 | depth, |
| 388 | }, |
| 389 | ForegroundEvent::SmallPolls(flush) => { |
| 390 | // The sealer folds these out of snapshot events; a contributor |
| 391 | // can therefore never be one, but serialize defensively as an |
| 392 | // unnamed poll spanning the flush rather than panicking. |
| 393 | Self::TaskPoll { |
| 394 | location: SerializedLocation { |
| 395 | file: "<small poll summary>".into(), |
| 396 | line: 0, |
| 397 | column: 0, |
| 398 | }, |
| 399 | start_ms: since_startup(flush.since), |
| 400 | duration_ms, |
| 401 | depth, |
| 402 | } |
| 403 | } |
| 404 | } |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | impl HangIncident { |
| 409 | /// The incident's reporting window: from its earliest cause — the |
| 410 | /// sealing frame's first invalidation, or the earliest contributor's |
| 411 | /// start when no repaint was pending — to the seal. This trims |
| 412 | /// foreground-idle time between the previous frame and the cause, and |
| 413 | /// may begin before the underlying snapshot when a contributor was |
| 414 | /// already running at the previous seal. |
| 415 | pub fn active_window(&self) -> (Instant, Instant) { |
| 416 | let snapshot = &self.snapshot; |
| 417 | let dirty_at = snapshot.boundary.dirty_at(); |
| 418 | let earliest_contributor = self |
| 419 | .contributors |
| 420 | .iter() |
| 421 | .map(|event| event.start_time()) |
| 422 | .min(); |
| 423 | let start = [dirty_at, earliest_contributor] |
| 424 | .into_iter() |
| 425 | .flatten() |
| 426 | .min() |
| 427 | .unwrap_or(snapshot.interval_start); |
| 428 | (start, snapshot.interval_end()) |
| 429 | } |
| 430 | |
| 431 | /// Returns an incident when the snapshot contains at least one event |
| 432 | /// that blocked the foreground for `threshold` or longer, or when the |
| 433 | /// interval's total foreground spend — event time plus folded |
| 434 | /// small-poll time — reached `frame_budget` even though no single event |
| 435 | /// did. In the latter case every event in the interval becomes a |
| 436 | /// contributor, since no single stall explains the busy interval. |
| 437 | pub fn detect( |
| 438 | snapshot: FrameSnapshot, |
| 439 | threshold: Duration, |
| 440 | frame_budget: Duration, |
| 441 | ) -> Option<Self> { |
| 442 | let mut contributors: Vec<ForegroundEvent> = snapshot |
| 443 | .events |
| 444 | .iter() |
| 445 | .filter(|event| event.duration() >= threshold) |
| 446 | .copied() |
| 447 | .collect(); |
| 448 | let trigger = if contributors.is_empty() { |
| 449 | if snapshot.journal_discontinuous { |
| 450 | return None; |
| 451 | } |
| 452 | let spend = snapshot.occupancy_within(snapshot.interval_start, snapshot.interval_end()); |
| 453 | if spend < frame_budget { |
| 454 | return None; |
| 455 | } |
| 456 | contributors = snapshot.events.clone(); |
| 457 | HangTrigger::Budget |
| 458 | } else { |
| 459 | HangTrigger::Threshold |
| 460 | }; |
| 461 | contributors.sort_by_key(|event| std::cmp::Reverse(event.duration())); |
| 462 | Some(Self { |
| 463 | snapshot, |
| 464 | trigger, |
| 465 | contributors, |
| 466 | }) |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | #[cfg(test)] |
| 471 | mod tests { |
| 472 | use std::cell::Cell; |
| 473 | use std::rc::Rc; |
| 474 | use std::thread; |
| 475 | use std::time::Duration; |
| 476 | |
| 477 | use proptest::prelude::*; |
| 478 | use rand::prelude::*; |
| 479 | use scheduler::SpawnTime; |
| 480 | |
| 481 | use crate::{ |
| 482 | self as gpui, Context, FocusHandle, InteractiveElement, IntoElement, Modifiers, |
| 483 | MouseButton, Render, Styled, TestAppContext, VisualTestContext, Window, WindowId, div, |
| 484 | point, px, |
| 485 | }; |
| 486 | |
| 487 | use crate::profiler::{ActionTiming, FrameTiming, PresentTiming, TaskTiming, YieldTime}; |
| 488 | |
| 489 | use super::super::journal::{ |
| 490 | FRAME_DEADLINE, ForegroundEvent, ForegroundJournalEntry, FrameSkipReason, FrameSkipped, |
| 491 | FrameSnapshot, FrameStateChange, InputTiming, IntervalBoundary, IntervalSealer, |
| 492 | PlatformSignal, PollSummary, PresentedFrame, SmallPollFlush, |
| 493 | install_test_foreground_journal, record_present, |
| 494 | }; |
| 495 | use super::{ |
| 496 | HangDetector, HangIncident, HangTrigger, SerializedHangContributor, SerializedHangIncident, |
| 497 | }; |
| 498 | |
| 499 | actions!(hang_test, [HangyAction]); |
| 500 | |
| 501 | // Well above legitimate per-event work in a test app (layout of one div, |
| 502 | // empty polls), well below the injected hangs. |
| 503 | const HANG_THRESHOLD: Duration = Duration::from_millis(10); |
| 504 | // Equal to the threshold, mirroring how production wires the detector |
| 505 | // today. |
| 506 | const FRAME_BUDGET: Duration = HANG_THRESHOLD; |
| 507 | |
| 508 | #[test] |
| 509 | fn completed_skips_preserve_real_hangs_and_serialize_their_boundary() { |
| 510 | let startup = scheduler::Instant::now(); |
| 511 | let at = |ms: u64| startup + Duration::from_millis(ms); |
| 512 | let window_id = WindowId::from(1); |
| 513 | for discontinuous in [false, true] { |
| 514 | for trigger in [HangTrigger::Threshold, HangTrigger::Budget] { |
| 515 | let mut sealer = IntervalSealer::new(startup); |
| 516 | let mut entries = Vec::new(); |
| 517 | match trigger { |
| 518 | HangTrigger::Threshold => entries.push(ForegroundJournalEntry::Event( |
| 519 | task_poll_event(at(10), at(30)), |
| 520 | )), |
| 521 | HangTrigger::Budget => entries.extend([ |
| 522 | ForegroundJournalEntry::Event(task_poll_event(at(10), at(16))), |
| 523 | ForegroundJournalEntry::Event(task_poll_event(at(20), at(26))), |
| 524 | ]), |
| 525 | } |
| 526 | if discontinuous { |
| 527 | entries.push(ForegroundJournalEntry::Discontinuity { lost: 1 }); |
| 528 | } |
| 529 | entries.push(ForegroundJournalEntry::Boundary( |
| 530 | IntervalBoundary::FrameSkipped(FrameSkipped { |
| 531 | window_id, |
| 532 | at: at(60), |
| 533 | reason: FrameSkipReason::NoRenderNeeded, |
| 534 | }), |
| 535 | )); |
| 536 | let snapshots = sealer.push_entries(entries); |
| 537 | let [snapshot] = snapshots.as_slice() else { |
| 538 | panic!("expected one snapshot, got {snapshots:?}"); |
| 539 | }; |
| 540 | let incident = HangIncident::detect(snapshot.clone(), HANG_THRESHOLD, FRAME_BUDGET); |
| 541 | if discontinuous && trigger == HangTrigger::Budget { |
| 542 | assert!(incident.is_none(), "skips must not exempt journal gaps"); |
| 543 | continue; |
| 544 | } |
| 545 | let incident = incident.expect("real work still qualifies across a skip"); |
| 546 | assert_eq!(incident.trigger, trigger); |
| 547 | let serialized = SerializedHangIncident::convert(startup, &incident, 10, None); |
| 548 | assert_eq!(serialized.sealed_by, "frame_skipped"); |
| 549 | assert_eq!(serialized.dirty_to_present_ms, None); |
| 550 | assert_eq!(serialized.start_ms, 10.0); |
| 551 | assert_eq!(serialized.active_ms, 50.0); |
| 552 | assert_eq!(serialized.journal_discontinuous, discontinuous); |
| 553 | assert_eq!(serialized.event_count, incident.contributors.len()); |
| 554 | let json = serde_json::to_value(&serialized).expect("serialize incident"); |
| 555 | assert_eq!(json["sealed_by"], "frame_skipped"); |
| 556 | assert!(json["dirty_to_present_ms"].is_null()); |
| 557 | } |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | #[test] |
| 562 | fn delayed_platform_signals_without_work_are_not_hangs() { |
| 563 | let start = scheduler::Instant::now(); |
| 564 | let window_id = WindowId::from(1); |
| 565 | let mut sealer = IntervalSealer::new(start); |
| 566 | let snapshots = sealer.push_entries([ |
| 567 | ForegroundJournalEntry::PlatformSignal(PlatformSignal { |
| 568 | window_id, |
| 569 | signal_at: Some(start), |
| 570 | handled_at: start + Duration::from_secs(5), |
| 571 | source: crate::FrameRequestSource::NativeCallback, |
| 572 | }), |
| 573 | ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(FrameSkipped { |
| 574 | window_id, |
| 575 | at: start + Duration::from_secs(6), |
| 576 | reason: FrameSkipReason::NoRenderNeeded, |
| 577 | })), |
| 578 | ]); |
| 579 | assert!( |
| 580 | snapshots.is_empty(), |
| 581 | "a late signal without work seals nothing, got {snapshots:?}" |
| 582 | ); |
| 583 | } |
| 584 | |
| 585 | /// A hang that outlives the frame deadline stays in one incident with |
| 586 | /// the frame it starved: the deadline only unblocks idle boundaries, so |
| 587 | /// the eventual presentation seals the hang together with its |
| 588 | /// dirty-to-present association. |
| 589 | #[test] |
| 590 | fn a_hang_outliving_the_frame_deadline_keeps_its_frame_association() { |
| 591 | let start = scheduler::Instant::now(); |
| 592 | let window_id = WindowId::from(0x51E17); |
| 593 | let hang_end = start + FRAME_DEADLINE * 5; |
| 594 | let presented_at = hang_end + Duration::from_millis(16); |
| 595 | let (journal, _journal_guard) = install_test_foreground_journal(64, 8); |
| 596 | let mut detector = HangDetector::new(journal, HANG_THRESHOLD, FRAME_BUDGET); |
| 597 | |
| 598 | let snapshots = detector.sealer.push_entries([ |
| 599 | ForegroundJournalEntry::FrameState(FrameStateChange::Pending { |
| 600 | window_id, |
| 601 | dirty_at: start, |
| 602 | }), |
| 603 | ForegroundJournalEntry::Event(task_poll_event(start, hang_end)), |
| 604 | ]); |
| 605 | assert!(snapshots.is_empty(), "nothing seals mid-hang"); |
| 606 | |
| 607 | let snapshots = detector |
| 608 | .sealer |
| 609 | .push_entries([ForegroundJournalEntry::Boundary( |
| 610 | IntervalBoundary::Presented(PresentedFrame { |
| 611 | frame: frame(window_id, presented_at), |
| 612 | presentation: PresentTiming { |
| 613 | window_id, |
| 614 | present_start: presented_at - Duration::from_millis(1), |
| 615 | present_end: presented_at, |
| 616 | animation_interval: None, |
| 617 | }, |
| 618 | }), |
| 619 | )]); |
| 620 | let [snapshot] = snapshots.as_slice() else { |
| 621 | panic!("expected one presented snapshot, got {snapshots:?}"); |
| 622 | }; |
| 623 | let incident = HangIncident::detect(snapshot.clone(), HANG_THRESHOLD, FRAME_BUDGET) |
| 624 | .expect("the hang qualifies"); |
| 625 | assert!(matches!( |
| 626 | incident.contributors[0], |
| 627 | ForegroundEvent::TaskPoll(timing) if timing.end.0 == hang_end |
| 628 | )); |
| 629 | assert!(matches!( |
| 630 | incident.snapshot.boundary, |
| 631 | IntervalBoundary::Presented(_) |
| 632 | )); |
| 633 | } |
| 634 | |
| 635 | #[test] |
| 636 | fn serialized_incident_reports_presented_seal_fields() { |
| 637 | let startup = scheduler::Instant::now(); |
| 638 | let at = |ms: u64| startup + Duration::from_millis(ms); |
| 639 | let window_id = WindowId::from(0xF1E1D); |
| 640 | |
| 641 | let presentation = PresentTiming { |
| 642 | window_id, |
| 643 | present_start: at(380), |
| 644 | present_end: at(400), |
| 645 | animation_interval: None, |
| 646 | }; |
| 647 | let frame = FrameTiming { |
| 648 | window_id, |
| 649 | dirty_at: Some(at(100)), |
| 650 | invalidations: 3, |
| 651 | draw_start: at(350), |
| 652 | draw_end: at(380), |
| 653 | }; |
| 654 | let snapshot = FrameSnapshot { |
| 655 | interval_start: at(150), |
| 656 | boundary: IntervalBoundary::Presented(PresentedFrame { |
| 657 | frame, |
| 658 | presentation, |
| 659 | }), |
| 660 | events: vec![ |
| 661 | task_poll_event(at(150), at(300)), |
| 662 | ForegroundEvent::Action(ActionTiming { |
| 663 | name: "test::SlowAction", |
| 664 | start: at(300), |
| 665 | end: at(340), |
| 666 | }), |
| 667 | ForegroundEvent::Input(InputTiming { |
| 668 | kind: "test", |
| 669 | start: at(340), |
| 670 | end: at(345), |
| 671 | caused_invalidation: false, |
| 672 | }), |
| 673 | ForegroundEvent::Present(presentation), |
| 674 | ], |
| 675 | small_polls: vec![SmallPollFlush { |
| 676 | summary: PollSummary { |
| 677 | count: 2, |
| 678 | total: Duration::from_millis(1), |
| 679 | }, |
| 680 | since: at(105), |
| 681 | until: at(145), |
| 682 | }], |
| 683 | dropped_events: 0, |
| 684 | journal_discontinuous: false, |
| 685 | }; |
| 686 | |
| 687 | let incident = |
| 688 | HangIncident::detect(snapshot, HANG_THRESHOLD, FRAME_BUDGET).expect("has contributors"); |
| 689 | let serialized = SerializedHangIncident::convert(startup, &incident, 1, Some(at(50))); |
| 690 | |
| 691 | assert_eq!(serialized.phase, "steady"); |
| 692 | assert_eq!(serialized.trigger, HangTrigger::Threshold); |
| 693 | // The frame's first invalidation anchors the active window, not the |
| 694 | // interval start or the first contributor. |
| 695 | assert_eq!(serialized.start_ms, 100.0); |
| 696 | assert_eq!(serialized.active_ms, 300.0); |
| 697 | assert_eq!(serialized.stall_ms, 150.0); |
| 698 | assert_eq!(serialized.dirty_to_present_ms, Some(300.0)); |
| 699 | assert_eq!(serialized.sealed_by, "present"); |
| 700 | // Occupancy: poll 150ms + action 40ms + input 5ms + present 20ms + |
| 701 | // folded polls 1ms = 216ms of the 300ms window. |
| 702 | assert_eq!(serialized.busy_fraction, 0.72); |
| 703 | assert_eq!(serialized.event_count, 4); |
| 704 | assert_eq!(serialized.small_poll_count, 2); |
| 705 | assert_eq!(serialized.small_poll_total_ms, 1.0); |
| 706 | assert_eq!(serialized.dropped_events, 0); |
| 707 | // Three contributors qualify (poll, action, present); the cap keeps |
| 708 | // the longest and counts the rest. |
| 709 | assert_eq!(serialized.contributors.len(), 1); |
| 710 | assert_eq!(serialized.contributors_elided, 2); |
| 711 | assert!(matches!( |
| 712 | serialized.contributors[0], |
| 713 | SerializedHangContributor::TaskPoll { |
| 714 | start_ms, |
| 715 | duration_ms, |
| 716 | .. |
| 717 | } if start_ms == 150.0 && duration_ms == 150.0 |
| 718 | )); |
| 719 | } |
| 720 | |
| 721 | #[test] |
| 722 | fn hang_monitor_polls_on_its_interval_and_on_flush() { |
| 723 | use super::{HangMonitor, HangMonitorPollReason}; |
| 724 | |
| 725 | let (journal, _guard) = install_test_foreground_journal(64, 4); |
| 726 | // Each monitor reports on its own channel, which disconnects once the |
| 727 | // monitor's thread has exited and dropped its callback. |
| 728 | let spawn_monitor = |journal, interval| { |
| 729 | let (sender, receiver) = std::sync::mpsc::channel(); |
| 730 | let monitor = HangMonitor::spawn( |
| 731 | HangDetector::new(journal, HANG_THRESHOLD, FRAME_BUDGET), |
| 732 | interval, |
| 733 | move |poll| { |
| 734 | if !poll.incidents.is_empty() { |
| 735 | sender.send((poll.reason, poll.incidents.len())).ok(); |
| 736 | } |
| 737 | }, |
| 738 | ) |
| 739 | .expect("spawn monitor thread"); |
| 740 | (monitor, receiver) |
| 741 | }; |
| 742 | |
| 743 | let (monitor, receiver) = spawn_monitor(journal.clone(), Duration::from_millis(10)); |
| 744 | simulate_blocked_foreground_poll(HANG_THRESHOLD * 2); |
| 745 | assert_eq!( |
| 746 | receiver.recv_timeout(Duration::from_secs(10)).ok(), |
| 747 | Some((HangMonitorPollReason::Interval, 1)), |
| 748 | ); |
| 749 | drop(monitor); |
| 750 | assert_eq!( |
| 751 | receiver.recv_timeout(Duration::from_secs(10)), |
| 752 | Err(std::sync::mpsc::RecvTimeoutError::Disconnected), |
| 753 | ); |
| 754 | |
| 755 | // An interval longer than the test isolates the flush path. |
| 756 | let (monitor, receiver) = spawn_monitor(journal, Duration::from_secs(3600)); |
| 757 | simulate_blocked_foreground_poll(HANG_THRESHOLD * 2); |
| 758 | let flushed = monitor.request_flush().expect("monitor thread is running"); |
| 759 | futures::executor::block_on(flushed).expect("flush completes"); |
| 760 | assert_eq!( |
| 761 | receiver.try_recv().ok(), |
| 762 | Some((HangMonitorPollReason::Flush, 1)), |
| 763 | ); |
| 764 | |
| 765 | drop(monitor); |
| 766 | assert_eq!( |
| 767 | receiver.recv_timeout(Duration::from_secs(10)), |
| 768 | Err(std::sync::mpsc::RecvTimeoutError::Disconnected), |
| 769 | ); |
| 770 | } |
| 771 | |
| 772 | #[gpui::test] |
| 773 | fn app_flushes_its_hang_monitor_on_shutdown(cx: &mut TestAppContext) { |
| 774 | use super::{HangMonitorConfig, HangMonitorPollReason}; |
| 775 | |
| 776 | // The monitor runs on a real OS thread, so shutdown has to park until it |
| 777 | // finishes the flush, and its completion wakes the scheduler from that thread. |
| 778 | cx.executor().allow_parking(); |
| 779 | |
| 780 | let (sender, receiver) = std::sync::mpsc::channel(); |
| 781 | cx.update(|cx| { |
| 782 | cx.start_hang_monitor( |
| 783 | HangMonitorConfig { |
| 784 | threshold: HANG_THRESHOLD, |
| 785 | frame_budget: FRAME_BUDGET, |
| 786 | // Longer than the test, so only shutdown can poll. |
| 787 | interval: Duration::from_secs(3600), |
| 788 | }, |
| 789 | move |poll| { |
| 790 | sender.send(poll.reason).ok(); |
| 791 | }, |
| 792 | ) |
| 793 | .expect("start hang monitor"); |
| 794 | }); |
| 795 | assert!(receiver.try_recv().is_err()); |
| 796 | |
| 797 | cx.update(|cx| cx.shutdown()); |
| 798 | assert_eq!(receiver.try_recv().ok(), Some(HangMonitorPollReason::Flush)); |
| 799 | } |
| 800 | |
| 801 | #[gpui::test] |
| 802 | fn starting_the_hang_monitor_twice_is_rejected(cx: &mut TestAppContext) { |
| 803 | use super::{HangMonitorConfig, HangMonitorError}; |
| 804 | |
| 805 | let config = HangMonitorConfig { |
| 806 | threshold: HANG_THRESHOLD, |
| 807 | frame_budget: FRAME_BUDGET, |
| 808 | interval: Duration::from_secs(3600), |
| 809 | }; |
| 810 | cx.update(|cx| { |
| 811 | cx.start_hang_monitor(config, |_| {}) |
| 812 | .expect("start hang monitor"); |
| 813 | let second = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 814 | cx.start_hang_monitor(config, |_| {}) |
| 815 | })); |
| 816 | // Debug builds also assert, so misuse is caught during development. |
| 817 | if cfg!(debug_assertions) { |
| 818 | assert!(second.is_err()); |
| 819 | } else { |
| 820 | assert!(matches!(second, Ok(Err(HangMonitorError::AlreadyStarted)))); |
| 821 | } |
| 822 | }); |
| 823 | } |
| 824 | |
| 825 | #[test] |
| 826 | fn serialized_incident_reports_idle_seal_fields() { |
| 827 | let startup = scheduler::Instant::now(); |
| 828 | let at = |ms: u64| startup + Duration::from_millis(ms); |
| 829 | |
| 830 | let idle = FrameSnapshot { |
| 831 | interval_start: at(200), |
| 832 | boundary: IntervalBoundary::Idle { ended_at: at(260) }, |
| 833 | events: vec![task_poll_event(at(200), at(260))], |
| 834 | small_polls: Vec::new(), |
| 835 | dropped_events: 0, |
| 836 | journal_discontinuous: false, |
| 837 | }; |
| 838 | let incident = |
| 839 | HangIncident::detect(idle, HANG_THRESHOLD, FRAME_BUDGET).expect("has contributors"); |
| 840 | let serialized = SerializedHangIncident::convert(startup, &incident, 8, None); |
| 841 | assert_eq!(serialized.phase, "startup"); |
| 842 | assert_eq!(serialized.sealed_by, "idle"); |
| 843 | assert_eq!(serialized.dirty_to_present_ms, None); |
| 844 | // With no frame, the earliest contributor anchors the active window. |
| 845 | assert_eq!(serialized.start_ms, 200.0); |
| 846 | assert_eq!(serialized.active_ms, 60.0); |
| 847 | assert_eq!(serialized.stall_ms, 60.0); |
| 848 | assert_eq!(serialized.busy_fraction, 1.0); |
| 849 | } |
| 850 | |
| 851 | #[test] |
| 852 | fn phase_is_startup_until_the_first_present() { |
| 853 | let startup = scheduler::Instant::now(); |
| 854 | let at = |ms: u64| startup + Duration::from_millis(ms); |
| 855 | let snapshot = FrameSnapshot { |
| 856 | interval_start: at(500), |
| 857 | boundary: IntervalBoundary::Idle { ended_at: at(600) }, |
| 858 | events: vec![task_poll_event(at(500), at(600))], |
| 859 | small_polls: Vec::new(), |
| 860 | dropped_events: 0, |
| 861 | journal_discontinuous: false, |
| 862 | }; |
| 863 | let incident = |
| 864 | HangIncident::detect(snapshot, HANG_THRESHOLD, FRAME_BUDGET).expect("has contributors"); |
| 865 | |
| 866 | let phase = |first_present_at| { |
| 867 | SerializedHangIncident::convert(startup, &incident, 8, first_present_at).phase |
| 868 | }; |
| 869 | assert_eq!(phase(None), "startup", "nothing has been presented yet"); |
| 870 | assert_eq!( |
| 871 | phase(Some(at(700))), |
| 872 | "startup", |
| 873 | "the incident began before the first presentation" |
| 874 | ); |
| 875 | assert_eq!( |
| 876 | phase(Some(at(500))), |
| 877 | "steady", |
| 878 | "an incident beginning exactly at first presentation is steady" |
| 879 | ); |
| 880 | assert_eq!(phase(Some(at(100))), "steady"); |
| 881 | } |
| 882 | |
| 883 | /// The detector must latch the first presentation it observes and never |
| 884 | /// move it. |
| 885 | #[test] |
| 886 | fn first_present_at_latches_on_the_first_observed_presentation() { |
| 887 | let (journal, _journal_guard) = install_test_foreground_journal(64, 8); |
| 888 | let mut detector = HangDetector::new(journal, HANG_THRESHOLD, FRAME_BUDGET); |
| 889 | let window_id = WindowId::from(0x1A7C4); |
| 890 | |
| 891 | let first_present_end = scheduler::Instant::now(); |
| 892 | record_present( |
| 893 | presentation(window_id, first_present_end), |
| 894 | Some(frame(window_id, first_present_end)), |
| 895 | ); |
| 896 | detector.poll(); |
| 897 | let latched = detector |
| 898 | .first_present_at() |
| 899 | .expect("a presentation was recorded"); |
| 900 | assert_eq!(latched, first_present_end); |
| 901 | |
| 902 | record_present( |
| 903 | presentation(window_id, first_present_end + Duration::from_millis(16)), |
| 904 | Some(frame( |
| 905 | window_id, |
| 906 | first_present_end + Duration::from_millis(16), |
| 907 | )), |
| 908 | ); |
| 909 | detector.poll(); |
| 910 | assert_eq!(detector.first_present_at(), Some(latched)); |
| 911 | } |
| 912 | |
| 913 | /// The only work inside the 100ms active window here is the 50ms poll, |
| 914 | /// so the busy fraction is 0.5: the folded polls' flush span lies |
| 915 | /// entirely before the window and must contribute nothing to it |
| 916 | /// (PR #62779 review finding 5). |
| 917 | #[test] |
| 918 | fn busy_fraction_excludes_small_polls_outside_the_active_window() { |
| 919 | let startup = scheduler::Instant::now(); |
| 920 | let at = |ms: u64| startup + Duration::from_millis(ms); |
| 921 | let snapshot = FrameSnapshot { |
| 922 | interval_start: at(0), |
| 923 | boundary: IntervalBoundary::Idle { ended_at: at(1000) }, |
| 924 | events: vec![task_poll_event(at(900), at(950))], |
| 925 | // Folded polls that ran during at(0)..at(800), long before the |
| 926 | // active window opens at the contributor's start. |
| 927 | small_polls: vec![SmallPollFlush { |
| 928 | summary: PollSummary { |
| 929 | count: 500, |
| 930 | total: Duration::from_millis(400), |
| 931 | }, |
| 932 | since: at(0), |
| 933 | until: at(800), |
| 934 | }], |
| 935 | dropped_events: 0, |
| 936 | journal_discontinuous: false, |
| 937 | }; |
| 938 | |
| 939 | let incident = |
| 940 | HangIncident::detect(snapshot, HANG_THRESHOLD, FRAME_BUDGET).expect("has contributors"); |
| 941 | let serialized = SerializedHangIncident::convert(startup, &incident, 8, None); |
| 942 | |
| 943 | assert_eq!(serialized.busy_fraction, 0.5); |
| 944 | } |
| 945 | |
| 946 | /// Many sub-threshold pieces of work can drop a frame as thoroughly as |
| 947 | /// one long stall: an interval whose total foreground spend reaches the |
| 948 | /// budget is an incident even when no single event crosses the hang |
| 949 | /// threshold, and every event becomes a contributor so the report shows |
| 950 | /// what filled the interval. |
| 951 | #[test] |
| 952 | fn an_interval_of_small_work_over_budget_is_an_incident() { |
| 953 | let startup = scheduler::Instant::now(); |
| 954 | let at = |ms: u64| startup + Duration::from_millis(ms); |
| 955 | let window_id = WindowId::from(0xB0D6E7); |
| 956 | let snapshot = FrameSnapshot { |
| 957 | interval_start: at(0), |
| 958 | boundary: IntervalBoundary::Presented(PresentedFrame { |
| 959 | frame: FrameTiming { |
| 960 | window_id, |
| 961 | dirty_at: Some(at(0)), |
| 962 | invalidations: 1, |
| 963 | draw_start: at(140), |
| 964 | draw_end: at(145), |
| 965 | }, |
| 966 | presentation: PresentTiming { |
| 967 | window_id, |
| 968 | present_start: at(145), |
| 969 | present_end: at(150), |
| 970 | animation_interval: None, |
| 971 | }, |
| 972 | }), |
| 973 | events: vec![ |
| 974 | task_poll_event(at(0), at(5)), |
| 975 | task_poll_event(at(5), at(13)), |
| 976 | task_poll_event(at(13), at(18)), |
| 977 | ], |
| 978 | small_polls: Vec::new(), |
| 979 | dropped_events: 0, |
| 980 | journal_discontinuous: false, |
| 981 | }; |
| 982 | |
| 983 | let incident = HangIncident::detect(snapshot, HANG_THRESHOLD, FRAME_BUDGET) |
| 984 | .expect("foreground spend exceeded the frame budget"); |
| 985 | assert_eq!(incident.trigger, HangTrigger::Budget); |
| 986 | assert_eq!(incident.contributors.len(), 3); |
| 987 | assert_eq!( |
| 988 | incident.contributors[0].duration(), |
| 989 | Duration::from_millis(8) |
| 990 | ); |
| 991 | let serialized = SerializedHangIncident::convert(startup, &incident, 8, Some(startup)); |
| 992 | assert_eq!(serialized.trigger, HangTrigger::Budget); |
| 993 | assert_eq!(serialized.stall_ms, 8.0); |
| 994 | assert_eq!(serialized.dirty_to_present_ms, Some(150.0)); |
| 995 | assert_eq!(serialized.sealed_by, "present"); |
| 996 | } |
| 997 | |
| 998 | #[test] |
| 999 | fn a_journal_gap_suppresses_budget_inference_but_retains_observed_hangs() { |
| 1000 | let start = scheduler::Instant::now(); |
| 1001 | let at = |ms: u64| start + Duration::from_millis(ms); |
| 1002 | let mut sealer = super::super::journal::IntervalSealer::new(start); |
| 1003 | let snapshots = sealer.push_entries([ |
| 1004 | ForegroundJournalEntry::Event(task_poll_event(at(0), at(5))), |
| 1005 | ForegroundJournalEntry::Discontinuity { lost: 1 }, |
| 1006 | ForegroundJournalEntry::Event(task_poll_event(at(10), at(15))), |
| 1007 | ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { ended_at: at(15) }), |
| 1008 | ForegroundJournalEntry::Discontinuity { lost: 1 }, |
| 1009 | ForegroundJournalEntry::Event(task_poll_event(at(20), at(32))), |
| 1010 | ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { ended_at: at(32) }), |
| 1011 | ForegroundJournalEntry::Event(task_poll_event(at(40), at(52))), |
| 1012 | ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { ended_at: at(52) }), |
| 1013 | ]); |
| 1014 | let [budget_only, observed_hang, clean] = snapshots.as_slice() else { |
| 1015 | panic!("expected two discontinuous snapshots followed by a clean one"); |
| 1016 | }; |
| 1017 | |
| 1018 | assert!(budget_only.journal_discontinuous); |
| 1019 | assert_eq!(budget_only.dropped_events, 1); |
| 1020 | assert!(HangIncident::detect(budget_only.clone(), HANG_THRESHOLD, FRAME_BUDGET).is_none()); |
| 1021 | |
| 1022 | let observed_hang = |
| 1023 | HangIncident::detect(observed_hang.clone(), HANG_THRESHOLD, FRAME_BUDGET) |
| 1024 | .expect("the directly observed threshold-qualified hang remains valid"); |
| 1025 | assert!(observed_hang.snapshot.journal_discontinuous); |
| 1026 | assert_eq!(observed_hang.contributors.len(), 1); |
| 1027 | let serialized = SerializedHangIncident::convert(start, &observed_hang, 8, None); |
| 1028 | assert!(serialized.journal_discontinuous); |
| 1029 | |
| 1030 | assert!(!clean.journal_discontinuous); |
| 1031 | assert!(HangIncident::detect(clean.clone(), HANG_THRESHOLD, FRAME_BUDGET).is_some()); |
| 1032 | } |
| 1033 | |
| 1034 | /// A frame that reaches the screen late with almost no foreground work |
| 1035 | /// behind it — pure scheduling or presentation delay — is not a hang: |
| 1036 | /// the budget measures foreground spend, not dirty-to-present time. |
| 1037 | #[test] |
| 1038 | fn a_slow_frame_with_little_foreground_spend_is_not_an_incident() { |
| 1039 | let startup = scheduler::Instant::now(); |
| 1040 | let at = |ms: u64| startup + Duration::from_millis(ms); |
| 1041 | let window_id = WindowId::from(0xFA57); |
| 1042 | let snapshot = FrameSnapshot { |
| 1043 | interval_start: at(0), |
| 1044 | boundary: IntervalBoundary::Presented(PresentedFrame { |
| 1045 | frame: FrameTiming { |
| 1046 | window_id, |
| 1047 | dirty_at: Some(at(0)), |
| 1048 | invalidations: 1, |
| 1049 | draw_start: at(145), |
| 1050 | draw_end: at(147), |
| 1051 | }, |
| 1052 | presentation: PresentTiming { |
| 1053 | window_id, |
| 1054 | present_start: at(149), |
| 1055 | present_end: at(150), |
| 1056 | animation_interval: None, |
| 1057 | }, |
| 1058 | }), |
| 1059 | events: vec![task_poll_event(at(0), at(5))], |
| 1060 | small_polls: Vec::new(), |
| 1061 | dropped_events: 0, |
| 1062 | journal_discontinuous: false, |
| 1063 | }; |
| 1064 | |
| 1065 | assert!(HangIncident::detect(snapshot, HANG_THRESHOLD, FRAME_BUDGET).is_none()); |
| 1066 | } |
| 1067 | |
| 1068 | /// The budget applies to idle-sealed intervals too: a headless app (or |
| 1069 | /// a stretch with no repaint pending) can still starve the foreground |
| 1070 | /// with accumulated sub-threshold work. |
| 1071 | #[test] |
| 1072 | fn an_idle_sealed_interval_over_budget_is_an_incident() { |
| 1073 | let startup = scheduler::Instant::now(); |
| 1074 | let at = |ms: u64| startup + Duration::from_millis(ms); |
| 1075 | let snapshot = FrameSnapshot { |
| 1076 | interval_start: at(0), |
| 1077 | boundary: IntervalBoundary::Idle { ended_at: at(200) }, |
| 1078 | events: (0..10) |
| 1079 | .map(|i| task_poll_event(at(i * 20), at(i * 20 + 5))) |
| 1080 | .collect(), |
| 1081 | small_polls: Vec::new(), |
| 1082 | dropped_events: 0, |
| 1083 | journal_discontinuous: false, |
| 1084 | }; |
| 1085 | |
| 1086 | let incident = HangIncident::detect(snapshot, HANG_THRESHOLD, FRAME_BUDGET) |
| 1087 | .expect("foreground spend exceeded the frame budget"); |
| 1088 | assert_eq!(incident.contributors.len(), 10); |
| 1089 | let serialized = SerializedHangIncident::convert(startup, &incident, 8, Some(startup)); |
| 1090 | assert_eq!(serialized.sealed_by, "idle"); |
| 1091 | assert_eq!(serialized.dirty_to_present_ms, None); |
| 1092 | assert_eq!(serialized.stall_ms, 5.0); |
| 1093 | assert_eq!(serialized.contributors_elided, 2); |
| 1094 | } |
| 1095 | |
| 1096 | /// Contributors serialize in start order with their nesting depth: an |
| 1097 | /// input dispatch that synchronously drew a window reads as the input at |
| 1098 | /// depth 0 followed by the draw at depth 1, rather than two unrelated |
| 1099 | /// blocks of equal wall time. |
| 1100 | #[test] |
| 1101 | fn serialized_contributors_are_chronological_with_nesting_depths() { |
| 1102 | let startup = scheduler::Instant::now(); |
| 1103 | let at = |ms: u64| startup + Duration::from_millis(ms); |
| 1104 | let window_id = WindowId::from(0x2E57ED); |
| 1105 | let snapshot = FrameSnapshot { |
| 1106 | interval_start: at(0), |
| 1107 | boundary: IntervalBoundary::Idle { ended_at: at(80) }, |
| 1108 | events: vec![ |
| 1109 | task_poll_event(at(50), at(70)), |
| 1110 | ForegroundEvent::Input(InputTiming { |
| 1111 | kind: "mouse_move", |
| 1112 | start: at(0), |
| 1113 | end: at(40), |
| 1114 | caused_invalidation: true, |
| 1115 | }), |
| 1116 | ForegroundEvent::Draw(FrameTiming { |
| 1117 | window_id, |
| 1118 | dirty_at: Some(at(0)), |
| 1119 | invalidations: 1, |
| 1120 | draw_start: at(1), |
| 1121 | draw_end: at(39), |
| 1122 | }), |
| 1123 | ], |
| 1124 | small_polls: Vec::new(), |
| 1125 | dropped_events: 0, |
| 1126 | journal_discontinuous: false, |
| 1127 | }; |
| 1128 | |
| 1129 | let incident = |
| 1130 | HangIncident::detect(snapshot, HANG_THRESHOLD, FRAME_BUDGET).expect("has contributors"); |
| 1131 | let serialized = SerializedHangIncident::convert(startup, &incident, 8, Some(startup)); |
| 1132 | |
| 1133 | assert_eq!(serialized.stall_ms, 40.0); |
| 1134 | assert!(matches!( |
| 1135 | serialized.contributors.as_slice(), |
| 1136 | [ |
| 1137 | SerializedHangContributor::Input { |
| 1138 | input_kind: "mouse_move", |
| 1139 | depth: 0, |
| 1140 | .. |
| 1141 | }, |
| 1142 | SerializedHangContributor::Draw { depth: 1, .. }, |
| 1143 | SerializedHangContributor::TaskPoll { depth: 0, .. }, |
| 1144 | ] |
| 1145 | )); |
| 1146 | } |
| 1147 | |
| 1148 | /// Folded small polls count toward foreground spend, so an interval can |
| 1149 | /// reach the budget with no retained events at all. The incident then |
| 1150 | /// has no contributors and the small-poll summary carries the story. |
| 1151 | #[test] |
| 1152 | fn small_poll_spend_alone_can_reach_the_budget() { |
| 1153 | let startup = scheduler::Instant::now(); |
| 1154 | let at = |ms: u64| startup + Duration::from_millis(ms); |
| 1155 | let window_id = WindowId::from(0xDE1A7); |
| 1156 | let snapshot = FrameSnapshot { |
| 1157 | interval_start: at(0), |
| 1158 | boundary: IntervalBoundary::Presented(PresentedFrame { |
| 1159 | frame: FrameTiming { |
| 1160 | window_id, |
| 1161 | dirty_at: Some(at(0)), |
| 1162 | invalidations: 1, |
| 1163 | draw_start: at(148), |
| 1164 | draw_end: at(149), |
| 1165 | }, |
| 1166 | presentation: PresentTiming { |
| 1167 | window_id, |
| 1168 | present_start: at(149), |
| 1169 | present_end: at(150), |
| 1170 | animation_interval: None, |
| 1171 | }, |
| 1172 | }), |
| 1173 | events: Vec::new(), |
| 1174 | small_polls: vec![SmallPollFlush { |
| 1175 | summary: PollSummary { |
| 1176 | count: 40, |
| 1177 | total: Duration::from_millis(12), |
| 1178 | }, |
| 1179 | since: at(0), |
| 1180 | until: at(150), |
| 1181 | }], |
| 1182 | dropped_events: 0, |
| 1183 | journal_discontinuous: false, |
| 1184 | }; |
| 1185 | |
| 1186 | let incident = HangIncident::detect(snapshot, HANG_THRESHOLD, FRAME_BUDGET) |
| 1187 | .expect("small-poll spend exceeded the frame budget"); |
| 1188 | assert!(incident.contributors.is_empty()); |
| 1189 | let serialized = SerializedHangIncident::convert(startup, &incident, 8, Some(startup)); |
| 1190 | assert_eq!(serialized.stall_ms, 0.0); |
| 1191 | assert_eq!(serialized.event_count, 0); |
| 1192 | assert_eq!(serialized.small_poll_count, 40); |
| 1193 | assert_eq!(serialized.dirty_to_present_ms, Some(150.0)); |
| 1194 | assert_eq!(serialized.busy_fraction, 0.08); |
| 1195 | } |
| 1196 | |
| 1197 | proptest! { |
| 1198 | #![proptest_config(ProptestConfig { |
| 1199 | failure_persistence: None, |
| 1200 | ..ProptestConfig::default() |
| 1201 | })] |
| 1202 | |
| 1203 | #[test] |
| 1204 | fn detection_matches_threshold_and_budget_model_at_boundaries( |
| 1205 | durations_ms in prop::collection::vec(0u16..=50, 0..=16), |
| 1206 | threshold_ms in 0u16..=60, |
| 1207 | frame_budget_ms in 0u16..=500, |
| 1208 | small_poll_total_ms in 0u16..=100, |
| 1209 | ) { |
| 1210 | let origin = scheduler::Instant::now(); |
| 1211 | let mut cursor_ms = 0u64; |
| 1212 | let events = durations_ms |
| 1213 | .iter() |
| 1214 | .map(|duration_ms| { |
| 1215 | let start = origin + Duration::from_millis(cursor_ms); |
| 1216 | cursor_ms += u64::from(*duration_ms); |
| 1217 | let end = origin + Duration::from_millis(cursor_ms); |
| 1218 | cursor_ms += 1; |
| 1219 | ForegroundEvent::Input(InputTiming { |
| 1220 | kind: "test", |
| 1221 | start, |
| 1222 | end, |
| 1223 | caused_invalidation: false, |
| 1224 | }) |
| 1225 | }) |
| 1226 | .collect::<Vec<_>>(); |
| 1227 | let interval_end_ms = cursor_ms.max(1); |
| 1228 | let snapshot = FrameSnapshot { |
| 1229 | interval_start: origin, |
| 1230 | boundary: IntervalBoundary::Idle { |
| 1231 | ended_at: origin + Duration::from_millis(interval_end_ms), |
| 1232 | }, |
| 1233 | events, |
| 1234 | small_polls: vec![SmallPollFlush { |
| 1235 | summary: PollSummary { |
| 1236 | count: u64::from(small_poll_total_ms > 0), |
| 1237 | total: Duration::from_millis(u64::from(small_poll_total_ms)), |
| 1238 | }, |
| 1239 | since: origin, |
| 1240 | until: origin + Duration::from_millis(interval_end_ms), |
| 1241 | }], |
| 1242 | dropped_events: 0, |
| 1243 | journal_discontinuous: false, |
| 1244 | }; |
| 1245 | let qualifying_durations = durations_ms |
| 1246 | .iter() |
| 1247 | .copied() |
| 1248 | .filter(|duration| *duration >= threshold_ms) |
| 1249 | .collect::<Vec<_>>(); |
| 1250 | let occupancy_ms = durations_ms |
| 1251 | .iter() |
| 1252 | .map(|duration| u64::from(*duration)) |
| 1253 | .sum::<u64>() |
| 1254 | + u64::from(small_poll_total_ms); |
| 1255 | let expected_incident = |
| 1256 | !qualifying_durations.is_empty() || occupancy_ms >= u64::from(frame_budget_ms); |
| 1257 | |
| 1258 | let incident = HangIncident::detect( |
| 1259 | snapshot, |
| 1260 | Duration::from_millis(u64::from(threshold_ms)), |
| 1261 | Duration::from_millis(u64::from(frame_budget_ms)), |
| 1262 | ); |
| 1263 | prop_assert_eq!(incident.is_some(), expected_incident); |
| 1264 | |
| 1265 | if let Some(incident) = incident { |
| 1266 | let mut expected_contributors = if qualifying_durations.is_empty() { |
| 1267 | durations_ms |
| 1268 | } else { |
| 1269 | qualifying_durations |
| 1270 | }; |
| 1271 | expected_contributors.sort_unstable_by(|first, second| second.cmp(first)); |
| 1272 | let observed_contributors = incident |
| 1273 | .contributors |
| 1274 | .iter() |
| 1275 | .map(|event| event.duration().as_millis() as u16) |
| 1276 | .collect::<Vec<_>>(); |
| 1277 | prop_assert_eq!(observed_contributors, expected_contributors); |
| 1278 | } |
| 1279 | } |
| 1280 | } |
| 1281 | |
| 1282 | #[derive(Clone, Default)] |
| 1283 | struct HangControls { |
| 1284 | render: Rc<Cell<Option<Duration>>>, |
| 1285 | input: Rc<Cell<Option<Duration>>>, |
| 1286 | action: Rc<Cell<Option<Duration>>>, |
| 1287 | } |
| 1288 | |
| 1289 | struct HangyView { |
| 1290 | controls: HangControls, |
| 1291 | focus_handle: FocusHandle, |
| 1292 | } |
| 1293 | |
| 1294 | impl Render for HangyView { |
| 1295 | fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 1296 | if let Some(duration) = self.controls.render.take() { |
| 1297 | thread::sleep(duration); |
| 1298 | } |
| 1299 | let action_controls = self.controls.clone(); |
| 1300 | let input_controls = self.controls.clone(); |
| 1301 | div() |
| 1302 | .size_full() |
| 1303 | .track_focus(&self.focus_handle) |
| 1304 | .on_action(cx.listener(move |_, _: &HangyAction, _, _| { |
| 1305 | if let Some(duration) = action_controls.action.take() { |
| 1306 | thread::sleep(duration); |
| 1307 | } |
| 1308 | })) |
| 1309 | .on_mouse_down(MouseButton::Left, move |_, _, _| { |
| 1310 | if let Some(duration) = input_controls.input.take() { |
| 1311 | thread::sleep(duration); |
| 1312 | } |
| 1313 | }) |
| 1314 | } |
| 1315 | } |
| 1316 | |
| 1317 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] |
| 1318 | enum HangKind { |
| 1319 | Render, |
| 1320 | Input, |
| 1321 | Action, |
| 1322 | Poll, |
| 1323 | } |
| 1324 | |
| 1325 | /// Renders a real element tree and injects randomly ordered, randomly |
| 1326 | /// sized hangs through the production dispatch paths: view rendering |
| 1327 | /// (window draw), platform input dispatch, action dispatch, and a |
| 1328 | /// foreground task poll. Asserts the detector reports every one of them. |
| 1329 | #[gpui::test(iterations = 5)] |
| 1330 | fn detects_randomly_placed_foreground_hangs(mut rng: StdRng, cx: &mut TestAppContext) { |
| 1331 | let (journal, _journal_guard) = install_test_foreground_journal(1024, 16); |
| 1332 | let mut detector = HangDetector::new(journal, HANG_THRESHOLD, FRAME_BUDGET); |
| 1333 | |
| 1334 | let controls = HangControls::default(); |
| 1335 | let (view, cx) = cx.add_window_view(|_, cx| HangyView { |
| 1336 | controls: controls.clone(), |
| 1337 | focus_handle: cx.focus_handle(), |
| 1338 | }); |
| 1339 | view.update_in(cx, |view, window, cx| { |
| 1340 | window.focus(&view.focus_handle, cx); |
| 1341 | }); |
| 1342 | draw_window(cx); |
| 1343 | |
| 1344 | let mut injections: Vec<Injection> = Vec::new(); |
| 1345 | for _ in 0..rng.random_range(1..=4) { |
| 1346 | let duration = HANG_THRESHOLD + Duration::from_millis(rng.random_range(5..25)); |
| 1347 | let started = scheduler::Instant::now(); |
| 1348 | let kind = match rng.random_range(0..4) { |
| 1349 | 0 => { |
| 1350 | controls.render.set(Some(duration)); |
| 1351 | view.update_in(cx, |_, _, cx| cx.notify()); |
| 1352 | draw_window(cx); |
| 1353 | HangKind::Render |
| 1354 | } |
| 1355 | 1 => { |
| 1356 | controls.input.set(Some(duration)); |
| 1357 | cx.simulate_mouse_down( |
| 1358 | point(px(5.), px(5.)), |
| 1359 | MouseButton::Left, |
| 1360 | Modifiers::none(), |
| 1361 | ); |
| 1362 | HangKind::Input |
| 1363 | } |
| 1364 | 2 => { |
| 1365 | controls.action.set(Some(duration)); |
| 1366 | cx.dispatch_action(HangyAction); |
| 1367 | HangKind::Action |
| 1368 | } |
| 1369 | _ => { |
| 1370 | simulate_blocked_foreground_poll(duration); |
| 1371 | HangKind::Poll |
| 1372 | } |
| 1373 | }; |
| 1374 | injections.push(Injection { |
| 1375 | kind, |
| 1376 | duration, |
| 1377 | window: started..scheduler::Instant::now(), |
| 1378 | }); |
| 1379 | |
| 1380 | // Innocent interleaved activity that must not confuse detection. |
| 1381 | if rng.random_bool(0.5) { |
| 1382 | draw_window(cx); |
| 1383 | } |
| 1384 | if rng.random_bool(0.5) { |
| 1385 | cx.simulate_mouse_up(point(px(5.), px(5.)), MouseButton::Left, Modifiers::none()); |
| 1386 | } |
| 1387 | } |
| 1388 | |
| 1389 | // A final presentation seals whatever interval is still open. |
| 1390 | draw_window(cx); |
| 1391 | |
| 1392 | let incidents = detector.poll(); |
| 1393 | let contributors: Vec<ForegroundEvent> = incidents |
| 1394 | .iter() |
| 1395 | .flat_map(|incident| incident.contributors.iter().copied()) |
| 1396 | .collect(); |
| 1397 | |
| 1398 | for injection in &injections { |
| 1399 | assert_detected_once(injection, &contributors); |
| 1400 | } |
| 1401 | } |
| 1402 | |
| 1403 | struct Injection { |
| 1404 | kind: HangKind, |
| 1405 | duration: Duration, |
| 1406 | window: std::ops::Range<scheduler::Instant>, |
| 1407 | } |
| 1408 | |
| 1409 | /// Exactly one contributor of the injected kind must fall inside the |
| 1410 | /// injection's window, and it must be at least as long as the injected |
| 1411 | /// sleep (sleeps never wake early). Contributors outside every window are |
| 1412 | /// ignored: on a loaded machine, uninjected work can legitimately exceed |
| 1413 | /// the threshold, and reporting it is correct. |
| 1414 | fn assert_detected_once(injection: &Injection, contributors: &[ForegroundEvent]) { |
| 1415 | let Injection { |
| 1416 | kind, |
| 1417 | duration, |
| 1418 | window, |
| 1419 | } = injection; |
| 1420 | let matches: Vec<&ForegroundEvent> = contributors |
| 1421 | .iter() |
| 1422 | .filter(|event| { |
| 1423 | matches_kind(event, *kind) |
| 1424 | && window.start <= event.start_time() |
| 1425 | && event.end_time() <= window.end |
| 1426 | }) |
| 1427 | .collect(); |
| 1428 | assert_eq!( |
| 1429 | matches.len(), |
| 1430 | 1, |
| 1431 | "expected injected {kind:?} hang of {duration:?} to be reported exactly once; \ |
| 1432 | observed {:?}", |
| 1433 | matches |
| 1434 | .iter() |
| 1435 | .map(|event| event.duration()) |
| 1436 | .collect::<Vec<_>>(), |
| 1437 | ); |
| 1438 | if let Some(event) = matches.first() { |
| 1439 | assert!( |
| 1440 | event.duration() >= *duration, |
| 1441 | "injected {kind:?} hang of {duration:?} was reported as {:?}", |
| 1442 | event.duration(), |
| 1443 | ); |
| 1444 | } |
| 1445 | } |
| 1446 | |
| 1447 | fn matches_kind(event: &ForegroundEvent, kind: HangKind) -> bool { |
| 1448 | match (event, kind) { |
| 1449 | (ForegroundEvent::Draw(_), HangKind::Render) => true, |
| 1450 | (ForegroundEvent::Input(_), HangKind::Input) => true, |
| 1451 | (ForegroundEvent::Action(timing), HangKind::Action) => { |
| 1452 | timing.name.ends_with("HangyAction") |
| 1453 | } |
| 1454 | (ForegroundEvent::TaskPoll(timing), HangKind::Poll) => { |
| 1455 | timing.location.file() == file!() |
| 1456 | } |
| 1457 | _ => false, |
| 1458 | } |
| 1459 | } |
| 1460 | |
| 1461 | fn draw_window(cx: &mut VisualTestContext) { |
| 1462 | cx.update(|window, cx| { |
| 1463 | let arena_clear = window.draw(cx); |
| 1464 | window.present_if_needed(); |
| 1465 | arena_clear.clear(cx); |
| 1466 | }); |
| 1467 | } |
| 1468 | |
| 1469 | /// The deterministic test scheduler does not bracket runnables with the |
| 1470 | /// profiler hooks, so drive the same public hooks the platform |
| 1471 | /// dispatchers call around a poll that blocks the foreground. |
| 1472 | fn simulate_blocked_foreground_poll(duration: Duration) { |
| 1473 | let location = std::panic::Location::caller(); |
| 1474 | crate::profiler::update_running_task(SpawnTime(scheduler::Instant::now()), location); |
| 1475 | thread::sleep(duration); |
| 1476 | crate::profiler::save_task_timing(); |
| 1477 | } |
| 1478 | |
| 1479 | fn task_poll_event(start: scheduler::Instant, end: scheduler::Instant) -> ForegroundEvent { |
| 1480 | ForegroundEvent::TaskPoll(TaskTiming { |
| 1481 | location: std::panic::Location::caller(), |
| 1482 | spawned: SpawnTime(start), |
| 1483 | start, |
| 1484 | end: YieldTime(end), |
| 1485 | }) |
| 1486 | } |
| 1487 | |
| 1488 | fn presentation(window_id: WindowId, present_end: scheduler::Instant) -> PresentTiming { |
| 1489 | PresentTiming { |
| 1490 | window_id, |
| 1491 | present_start: present_end - Duration::from_millis(1), |
| 1492 | present_end, |
| 1493 | animation_interval: None, |
| 1494 | } |
| 1495 | } |
| 1496 | |
| 1497 | fn frame(window_id: WindowId, draw_end: scheduler::Instant) -> FrameTiming { |
| 1498 | FrameTiming { |
| 1499 | window_id, |
| 1500 | dirty_at: Some(draw_end - Duration::from_millis(2)), |
| 1501 | invalidations: 1, |
| 1502 | draw_start: draw_end - Duration::from_millis(1), |
| 1503 | draw_end, |
| 1504 | } |
| 1505 | } |
| 1506 | } |