| 1 | //! A journal of foreground work and the semantic boundaries between activity intervals. |
| 2 | //! |
| 3 | //! The foreground thread records task polls, action handlers, input dispatches, |
| 4 | //! draws, and presentations as [`ForegroundEvent`]s in a bounded journal ring. |
| 5 | //! Task polls shorter than [`TASK_POLL_FLOOR`] are folded into summaries, which |
| 6 | //! bound the stream by the number of slow polls while preserving their exact |
| 7 | //! count and total duration. |
| 8 | //! |
| 9 | //! Presentation, completed frame skips, and foreground idle are explicit |
| 10 | //! [`IntervalBoundary`] entries in the same stream. Independent [`ForegroundJournalCollector`]s |
| 11 | //! feed entries to [`IntervalSealer`], a pure state machine that groups all work |
| 12 | //! preceding each boundary into a [`FrameSnapshot`]. The sealer does not infer |
| 13 | //! boundaries from elapsed time or from incidental event kinds such as draws. |
| 14 | |
| 15 | use std::cell::{RefCell, UnsafeCell}; |
| 16 | use std::collections::{HashMap, VecDeque}; |
| 17 | use std::mem::MaybeUninit; |
| 18 | use std::sync::{ |
| 19 | Arc, |
| 20 | atomic::{AtomicU64, AtomicUsize, Ordering}, |
| 21 | }; |
| 22 | use std::time::Duration; |
| 23 | |
| 24 | use gpui_util::ResultExt; |
| 25 | use scheduler::Instant; |
| 26 | |
| 27 | use super::{ActionTiming, FrameTiming, PresentTiming, TaskTiming}; |
| 28 | use crate::{App, WindowId, WindowVisibility}; |
| 29 | |
| 30 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 31 | pub(crate) enum PowerState { |
| 32 | Awake, |
| 33 | Suspended, |
| 34 | } |
| 35 | |
| 36 | /// Task polls shorter than this are folded into a [`PollSummary`] instead of |
| 37 | /// being recorded individually. This keeps the stream bounded by the number |
| 38 | /// of *slow* polls while preserving their exact count and total duration. |
| 39 | pub const TASK_POLL_FLOOR: Duration = Duration::from_micros(100); |
| 40 | |
| 41 | /// A dirty frame that has not been presented by this deadline stops blocking |
| 42 | /// foreground-idle boundaries, so a window that never presents (hidden or |
| 43 | /// occluded windows receive no frame callbacks) cannot suppress boundaries |
| 44 | /// indefinitely. Expiry only unblocks: the open interval still seals at a |
| 45 | /// presentation, completed frame skip, or idle boundary, keeping a starving |
| 46 | /// hang and the callback it starved in one interval. |
| 47 | pub const FRAME_DEADLINE: Duration = Duration::from_secs(1); |
| 48 | |
| 49 | /// Growth in [`system_suspended_time`] below this is attributed to reading |
| 50 | /// its two clocks separately (on Windows both advance only on the system |
| 51 | /// tick, up to 15.6 ms), not to a suspend. A real suspend, including freezing |
| 52 | /// and thawing processes around it, takes far longer. |
| 53 | const MIN_DETECTED_SUSPEND: Duration = Duration::from_millis(50); |
| 54 | |
| 55 | // Backstop against pathological event storms within a single interval. At the |
| 56 | // 100us floor, a fully hung second can produce at most ~10k recordable polls, |
| 57 | // so this bound is only reachable when something is already deeply wrong. |
| 58 | const MAX_INTERVAL_EVENTS: usize = 16 * 1024; |
| 59 | |
| 60 | // Allow 4MiB for the fixed ring allocation, including each slot's atomic |
| 61 | // metadata. The poll floor and frame cadence bound the event rate to roughly |
| 62 | // 10k per second in the worst case, so this holds several seconds of |
| 63 | // worst-case traffic between consumer drains. |
| 64 | const MAX_JOURNAL_ENTRIES: usize = (4 * 1024 * 1024) / core::mem::size_of::<JournalSlot>(); |
| 65 | |
| 66 | // Absorbs brief collisions with a collector reading the exact slot being |
| 67 | // wrapped. The foreground never waits for a reader; queued entries are retried |
| 68 | // in order on the next publication. |
| 69 | const MAX_PENDING_JOURNAL_ENTRIES: usize = 64; |
| 70 | |
| 71 | /// One entry in the foreground stream. |
| 72 | /// |
| 73 | /// Events are recorded in completion order (ordered by their end time). An |
| 74 | /// event that was in progress across a frame boundary (e.g. the task poll |
| 75 | /// enclosing a draw) is recorded when it *ends*, with timestamps that may |
| 76 | /// precede events recorded before it. |
| 77 | #[derive(Debug, Copy, Clone)] |
| 78 | pub enum ForegroundEvent { |
| 79 | /// A foreground task poll at least [`TASK_POLL_FLOOR`] long. |
| 80 | TaskPoll(TaskTiming), |
| 81 | /// A completed action handler. |
| 82 | Action(ActionTiming), |
| 83 | /// A dispatched platform input event. |
| 84 | Input(InputTiming), |
| 85 | /// A completed window draw. |
| 86 | Draw(FrameTiming), |
| 87 | /// Work spent submitting a frame to the platform. |
| 88 | Present(PresentTiming), |
| 89 | /// Aggregate of task polls below [`TASK_POLL_FLOOR`], flushed before the |
| 90 | /// next individually retained event or interval boundary. |
| 91 | SmallPolls(SmallPollFlush), |
| 92 | } |
| 93 | |
| 94 | impl ForegroundEvent { |
| 95 | /// When the work described by this event began. For draws this is the |
| 96 | /// start of the draw itself, not the frame's first invalidation. |
| 97 | pub fn start_time(&self) -> Instant { |
| 98 | match self { |
| 99 | Self::TaskPoll(timing) => timing.start, |
| 100 | Self::Action(timing) => timing.start, |
| 101 | Self::Input(timing) => timing.start, |
| 102 | Self::Draw(timing) => timing.draw_start, |
| 103 | Self::Present(timing) => timing.present_start, |
| 104 | Self::SmallPolls(flush) => flush.since, |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | /// When the work described by this event ended. |
| 109 | pub fn end_time(&self) -> Instant { |
| 110 | match self { |
| 111 | Self::TaskPoll(timing) => timing.end.0, |
| 112 | Self::Action(timing) => timing.end, |
| 113 | Self::Input(timing) => timing.end, |
| 114 | Self::Draw(timing) => timing.draw_end, |
| 115 | Self::Present(timing) => timing.present_end, |
| 116 | Self::SmallPolls(flush) => flush.until, |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | /// How long the work described by this event took. For |
| 121 | /// [`Self::SmallPolls`] this is the span the summary covers, not time |
| 122 | /// spent polling; use the summary's `total` for occupancy. |
| 123 | pub fn duration(&self) -> Duration { |
| 124 | self.end_time().duration_since(self.start_time()) |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | /// Timing of one platform input dispatch on a window. |
| 129 | #[derive(Debug, Copy, Clone)] |
| 130 | pub struct InputTiming { |
| 131 | /// The platform input variant dispatched (see |
| 132 | /// [`crate::PlatformInput::kind_name`]). |
| 133 | pub kind: &'static str, |
| 134 | /// When the input dispatch started. |
| 135 | pub start: Instant, |
| 136 | /// When the input dispatch finished. |
| 137 | pub end: Instant, |
| 138 | /// Whether handling the input invalidated a window. |
| 139 | pub caused_invalidation: bool, |
| 140 | } |
| 141 | |
| 142 | /// A frame callback entering the foreground, without implying foreground work. |
| 143 | #[derive(Debug, Copy, Clone)] |
| 144 | pub struct PlatformSignal { |
| 145 | /// The window receiving the callback. |
| 146 | pub window_id: WindowId, |
| 147 | /// When the platform requested the callback, if its clock is supported. |
| 148 | pub signal_at: Option<Instant>, |
| 149 | /// When foreground handling began. |
| 150 | pub handled_at: Instant, |
| 151 | /// Whether the callback came from the platform or local scheduling. |
| 152 | pub source: crate::FrameRequestSource, |
| 153 | } |
| 154 | |
| 155 | /// Why a completed frame request did not draw a new frame. |
| 156 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] |
| 157 | pub enum FrameSkipReason { |
| 158 | /// The callback completed without needing a new render. |
| 159 | NoRenderNeeded, |
| 160 | /// An inactive window deferred drawing. |
| 161 | InactiveFrameRateLimit, |
| 162 | /// Thermal throttling deferred drawing. |
| 163 | ThermalFrameRateLimit, |
| 164 | } |
| 165 | |
| 166 | /// A completed frame request that returned without drawing a new frame. |
| 167 | #[derive(Debug, Copy, Clone)] |
| 168 | pub struct FrameSkipped { |
| 169 | /// The window whose callback returned. |
| 170 | pub window_id: WindowId, |
| 171 | /// When the foreground completed this callback. |
| 172 | pub at: Instant, |
| 173 | /// Why no new frame was drawn. |
| 174 | pub reason: FrameSkipReason, |
| 175 | } |
| 176 | |
| 177 | /// Exact count and total duration of task polls below [`TASK_POLL_FLOOR`]. |
| 178 | #[derive(Debug, Copy, Clone, Default, PartialEq, Eq)] |
| 179 | pub struct PollSummary { |
| 180 | /// Number of polls below the floor. |
| 181 | pub count: u64, |
| 182 | /// Total duration of polls below the floor. |
| 183 | pub total: Duration, |
| 184 | } |
| 185 | |
| 186 | impl PollSummary { |
| 187 | fn add(&mut self, other: Self) { |
| 188 | self.count += other.count; |
| 189 | self.total += other.total; |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | /// A flushed [`PollSummary`] and the tightest span containing its folded polls. |
| 194 | #[derive(Debug, Copy, Clone)] |
| 195 | pub struct SmallPollFlush { |
| 196 | /// The folded polls. |
| 197 | pub summary: PollSummary, |
| 198 | /// When the first folded poll began. |
| 199 | pub since: Instant, |
| 200 | /// When the last folded poll ended. |
| 201 | pub until: Instant, |
| 202 | } |
| 203 | |
| 204 | /// A newly drawn frame and the platform submission that completed its interval. |
| 205 | #[derive(Debug, Copy, Clone)] |
| 206 | pub struct PresentedFrame { |
| 207 | /// The draw whose rendered scene was submitted. |
| 208 | pub frame: FrameTiming, |
| 209 | /// Work spent submitting that scene to the platform. |
| 210 | pub presentation: PresentTiming, |
| 211 | } |
| 212 | |
| 213 | impl PresentedFrame { |
| 214 | /// Time from the frame's first invalidation through platform submission. |
| 215 | pub fn dirty_to_present_duration(&self) -> Option<Duration> { |
| 216 | self.frame |
| 217 | .dirty_at |
| 218 | .map(|dirty_at| self.presentation.present_end.duration_since(dirty_at)) |
| 219 | } |
| 220 | } |
| 221 | |
| 222 | /// The semantic event that completed a foreground activity interval. |
| 223 | #[derive(Debug, Copy, Clone)] |
| 224 | pub enum IntervalBoundary { |
| 225 | /// A newly drawn frame was submitted to the platform. |
| 226 | Presented(PresentedFrame), |
| 227 | /// A callback completed without drawing, excluding reentrant callbacks. |
| 228 | FrameSkipped(FrameSkipped), |
| 229 | /// The foreground returned to an idle platform loop with no unexpired |
| 230 | /// frame pending. |
| 231 | Idle { |
| 232 | /// When the foreground went idle. |
| 233 | ended_at: Instant, |
| 234 | }, |
| 235 | /// A system suspend interrupted the measurement interval, observed either |
| 236 | /// through a power notification or through the suspend clock. |
| 237 | PowerTransition { |
| 238 | /// When the foreground noticed the suspend, through a notification or |
| 239 | /// the suspend clock. |
| 240 | ended_at: Instant, |
| 241 | }, |
| 242 | } |
| 243 | |
| 244 | impl IntervalBoundary { |
| 245 | /// When the interval ended. |
| 246 | pub fn end_time(&self) -> Instant { |
| 247 | match self { |
| 248 | Self::Presented(presented) => presented.presentation.present_end, |
| 249 | Self::FrameSkipped(skipped) => skipped.at, |
| 250 | Self::Idle { ended_at } | Self::PowerTransition { ended_at } => *ended_at, |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | /// The first invalidation of the frame satisfied by this boundary, if any. |
| 255 | pub fn dirty_at(&self) -> Option<Instant> { |
| 256 | match self { |
| 257 | Self::Presented(presented) => presented.frame.dirty_at, |
| 258 | Self::FrameSkipped(_) | Self::Idle { .. } | Self::PowerTransition { .. } => None, |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | /// A control-plane change to one window's pending-frame state. |
| 264 | #[derive(Debug, Copy, Clone)] |
| 265 | pub enum FrameStateChange { |
| 266 | /// The window has a frame waiting to be presented. |
| 267 | Pending { |
| 268 | /// The window waiting for presentation. |
| 269 | window_id: WindowId, |
| 270 | /// When this frame generation first became dirty. |
| 271 | dirty_at: Instant, |
| 272 | }, |
| 273 | /// The window closed, so any pending frame no longer blocks idle |
| 274 | /// boundaries. |
| 275 | Closed { |
| 276 | /// The window that closed. |
| 277 | window_id: WindowId, |
| 278 | /// When the window closed. |
| 279 | at: Instant, |
| 280 | }, |
| 281 | } |
| 282 | |
| 283 | /// One item retained in the foreground journal. |
| 284 | #[derive(Debug, Copy, Clone)] |
| 285 | pub enum ForegroundJournalEntry { |
| 286 | /// A completed piece of foreground work. |
| 287 | Event(ForegroundEvent), |
| 288 | /// A semantic interval boundary. |
| 289 | Boundary(IntervalBoundary), |
| 290 | /// A change to pending-frame state. This is metadata, not foreground work. |
| 291 | FrameState(FrameStateChange), |
| 292 | /// A callback entering the foreground; not work or an interval boundary. |
| 293 | PlatformSignal(PlatformSignal), |
| 294 | /// A nested frame request deferred while an enclosing draw was still running. |
| 295 | ReentrantFrameSkipped { |
| 296 | /// The window whose nested frame request was deferred. |
| 297 | window_id: WindowId, |
| 298 | /// When the nested frame request was deferred. |
| 299 | at: Instant, |
| 300 | }, |
| 301 | /// One or more logical entries were unavailable at this point in the |
| 302 | /// stream. Consumers must not infer interval boundaries across this gap. |
| 303 | Discontinuity { |
| 304 | /// Number of unavailable logical entries. |
| 305 | lost: u64, |
| 306 | }, |
| 307 | } |
| 308 | |
| 309 | /// An immutable view of one sealed foreground interval, produced by |
| 310 | /// [`IntervalSealer`]. |
| 311 | #[derive(Debug, Clone)] |
| 312 | pub struct FrameSnapshot { |
| 313 | /// When the interval started (the previous seal, or the end of the idle |
| 314 | /// stretch preceding the interval's first event). |
| 315 | pub interval_start: Instant, |
| 316 | /// The semantic event that completed the interval, including its metadata. |
| 317 | pub boundary: IntervalBoundary, |
| 318 | /// Foreground work recorded during the interval, in completion order. |
| 319 | /// [`ForegroundEvent::SmallPolls`] entries are collected into |
| 320 | /// `small_polls` instead of appearing here. |
| 321 | pub events: Vec<ForegroundEvent>, |
| 322 | /// Span-tagged aggregates of task polls below [`TASK_POLL_FLOOR`]. Spans |
| 323 | /// are retained so occupancy can apportion folded poll time to reporting |
| 324 | /// windows narrower than the interval. |
| 325 | pub small_polls: Vec<SmallPollFlush>, |
| 326 | /// Events lost to the interval's event cap, plus ring losses reported |
| 327 | /// via [`IntervalSealer::note_lost`]. |
| 328 | pub dropped_events: u64, |
| 329 | /// Whether the journal had an unobserved gap during this interval. |
| 330 | pub journal_discontinuous: bool, |
| 331 | } |
| 332 | |
| 333 | impl FrameSnapshot { |
| 334 | /// When the interval ended. |
| 335 | pub fn interval_end(&self) -> Instant { |
| 336 | self.boundary.end_time() |
| 337 | } |
| 338 | |
| 339 | /// The combined count and total of all folded sub-floor polls in the |
| 340 | /// interval. |
| 341 | pub fn small_poll_summary(&self) -> PollSummary { |
| 342 | let mut summary = PollSummary::default(); |
| 343 | for flush in &self.small_polls { |
| 344 | summary.add(flush.summary); |
| 345 | } |
| 346 | summary |
| 347 | } |
| 348 | |
| 349 | /// Total foreground time occupied within the interval: the union of the |
| 350 | /// recorded events' spans (clamped to the interval, so nested work like an |
| 351 | /// action inside an input dispatch is not double counted) plus the folded |
| 352 | /// small polls. Folded polls cannot be unioned with nested individually |
| 353 | /// timed work, so this remains a close approximation. |
| 354 | pub fn occupancy(&self) -> Duration { |
| 355 | self.occupancy_within(self.interval_start, self.interval_end()) |
| 356 | } |
| 357 | |
| 358 | /// Like [`Self::occupancy`], but measured against an arbitrary window |
| 359 | /// (e.g. a reporting window anchored at a frame's first invalidation). |
| 360 | /// Event spans are clamped to the window. Folded polls carry no |
| 361 | /// individual timestamps, so each flush's total is apportioned by how |
| 362 | /// much of its span overlaps the window — assuming the folded time is |
| 363 | /// spread uniformly across the span. |
| 364 | pub fn occupancy_within(&self, window_start: Instant, window_end: Instant) -> Duration { |
| 365 | let mut spans: Vec<(Instant, Instant)> = self |
| 366 | .events |
| 367 | .iter() |
| 368 | .map(|event| { |
| 369 | let start = event.start_time().max(window_start); |
| 370 | let end = event.end_time().min(window_end).max(start); |
| 371 | (start, end) |
| 372 | }) |
| 373 | .collect(); |
| 374 | spans.sort_by_key(|(start, _)| *start); |
| 375 | |
| 376 | let mut occupied = Duration::ZERO; |
| 377 | let mut merged_until: Option<Instant> = None; |
| 378 | for (start, end) in spans { |
| 379 | let start = match merged_until { |
| 380 | Some(merged_until) => start.max(merged_until), |
| 381 | None => start, |
| 382 | }; |
| 383 | occupied += end.duration_since(start); |
| 384 | merged_until = Some(match merged_until { |
| 385 | Some(merged_until) => merged_until.max(end), |
| 386 | None => end, |
| 387 | }); |
| 388 | } |
| 389 | |
| 390 | let apportioned_small_polls: Duration = self |
| 391 | .small_polls |
| 392 | .iter() |
| 393 | .map(|flush| { |
| 394 | let span = flush.until.duration_since(flush.since); |
| 395 | if span.is_zero() { |
| 396 | // A point-like flush lies either inside or outside the |
| 397 | // window. |
| 398 | if flush.since >= window_start && flush.since <= window_end { |
| 399 | flush.summary.total |
| 400 | } else { |
| 401 | Duration::ZERO |
| 402 | } |
| 403 | } else { |
| 404 | let overlap_start = flush.since.max(window_start); |
| 405 | let overlap_end = flush.until.min(window_end).max(overlap_start); |
| 406 | let overlap = overlap_end.duration_since(overlap_start); |
| 407 | flush.summary.total.mul_f64(overlap.div_duration_f64(span)) |
| 408 | } |
| 409 | }) |
| 410 | .sum(); |
| 411 | occupied + apportioned_small_polls |
| 412 | } |
| 413 | |
| 414 | /// The fraction of the interval the foreground spent working, in `0.0..=1.0`. |
| 415 | pub fn busy_fraction(&self) -> f64 { |
| 416 | let interval = self.interval_end().duration_since(self.interval_start); |
| 417 | if interval.is_zero() { |
| 418 | return 1.0; |
| 419 | } |
| 420 | (self.occupancy().div_duration_f64(interval)).min(1.0) |
| 421 | } |
| 422 | } |
| 423 | |
| 424 | #[derive(Clone)] |
| 425 | pub(crate) struct ForegroundRunnableCounter(Arc<AtomicUsize>); |
| 426 | |
| 427 | impl ForegroundRunnableCounter { |
| 428 | fn new() -> Self { |
| 429 | Self(Arc::new(AtomicUsize::new(0))) |
| 430 | } |
| 431 | |
| 432 | pub(crate) fn queued(&self) { |
| 433 | self.0.fetch_add(1, Ordering::Release); |
| 434 | } |
| 435 | |
| 436 | fn finished(&self) { |
| 437 | let _ = self |
| 438 | .0 |
| 439 | .fetch_update(Ordering::AcqRel, Ordering::Acquire, |count| { |
| 440 | count.checked_sub(1) |
| 441 | }); |
| 442 | } |
| 443 | |
| 444 | fn has_runnables(&self) -> bool { |
| 445 | self.0.load(Ordering::Acquire) > 0 |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | // Visibility and power changes clear `dirty_at`; `Window::refresh_visibility` |
| 450 | // re-records the frame from the window's actual dirty state afterwards. |
| 451 | struct WindowFrameState { |
| 452 | visibility: WindowVisibility, |
| 453 | dirty_at: Option<Instant>, |
| 454 | visibility_changed_at: Option<Instant>, |
| 455 | } |
| 456 | |
| 457 | impl WindowFrameState { |
| 458 | fn new(visibility: WindowVisibility) -> Self { |
| 459 | Self { |
| 460 | visibility, |
| 461 | dirty_at: None, |
| 462 | visibility_changed_at: None, |
| 463 | } |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | struct ForegroundJournalWriter { |
| 468 | foreground_runnables: ForegroundRunnableCounter, |
| 469 | publisher: JournalPublisher, |
| 470 | turn_depth: usize, |
| 471 | windows: HashMap<WindowId, WindowFrameState>, |
| 472 | power: PowerState, |
| 473 | power_changed_at: Option<Instant>, |
| 474 | read_suspended_time: fn() -> Option<Duration>, |
| 475 | suspended_time: Option<Duration>, |
| 476 | retained_since_boundary: bool, |
| 477 | small_polls: Option<SmallPollFlush>, |
| 478 | } |
| 479 | |
| 480 | impl ForegroundJournalWriter { |
| 481 | fn new(foreground_runnables: ForegroundRunnableCounter, publisher: JournalPublisher) -> Self { |
| 482 | Self { |
| 483 | foreground_runnables, |
| 484 | publisher, |
| 485 | turn_depth: 0, |
| 486 | windows: HashMap::new(), |
| 487 | power: PowerState::Awake, |
| 488 | power_changed_at: None, |
| 489 | read_suspended_time: system_suspended_time, |
| 490 | suspended_time: system_suspended_time(), |
| 491 | retained_since_boundary: false, |
| 492 | small_polls: None, |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | fn begin_turn(&mut self) { |
| 497 | self.turn_depth += 1; |
| 498 | } |
| 499 | |
| 500 | // Idle boundaries require a retained event since the last boundary, not |
| 501 | // merely folded sub-floor polls. Sporadic wake-ups (timers, file |
| 502 | // watchers) leave the foreground idle after every tiny poll; a boundary |
| 503 | // for each would re-admit to the ring the very polls the fold keeps out |
| 504 | // of it, wrapping the ring within seconds. Folded-only work is discarded |
| 505 | // at true idle so unrelated wake-ups cannot accumulate toward a later |
| 506 | // frame budget. Polls remain folded while a frame or runnable is pending. |
| 507 | fn end_turn(&mut self, ended_at: Instant) { |
| 508 | let Some(turn_depth) = self.turn_depth.checked_sub(1) else { |
| 509 | debug_assert!(false, "foreground turn must be begun before it ends"); |
| 510 | return; |
| 511 | }; |
| 512 | self.turn_depth = turn_depth; |
| 513 | if self.turn_depth > 0 |
| 514 | || self.foreground_runnables.has_runnables() |
| 515 | || self.has_unexpired_pending_frame(ended_at) |
| 516 | { |
| 517 | return; |
| 518 | } |
| 519 | if !self.retained_since_boundary { |
| 520 | self.small_polls = None; |
| 521 | return; |
| 522 | } |
| 523 | |
| 524 | self.record_entry(ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { |
| 525 | ended_at, |
| 526 | })); |
| 527 | } |
| 528 | |
| 529 | fn has_unexpired_pending_frame(&mut self, now: Instant) -> bool { |
| 530 | for window in self.windows.values_mut() { |
| 531 | if window |
| 532 | .dirty_at |
| 533 | .is_some_and(|at| now.saturating_duration_since(at) >= FRAME_DEADLINE) |
| 534 | { |
| 535 | window.dirty_at = None; |
| 536 | } |
| 537 | } |
| 538 | self.power == PowerState::Awake |
| 539 | && self |
| 540 | .windows |
| 541 | .values() |
| 542 | .any(|window| window.dirty_at.is_some()) |
| 543 | } |
| 544 | |
| 545 | fn power_transition(&mut self, power: PowerState, at: Instant) { |
| 546 | if self.power == power { |
| 547 | return; |
| 548 | } |
| 549 | self.power = power; |
| 550 | // A suspend that was notified after it happened must not be reported |
| 551 | // again by the suspend clock. A notification that precedes its |
| 552 | // suspend (macOS posts will-sleep up to 30 s early) leaves the clock |
| 553 | // to fire once more after wake, which only seals an empty interval. |
| 554 | self.suspended_time = (self.read_suspended_time)(); |
| 555 | self.interrupt_measurements(at); |
| 556 | } |
| 557 | |
| 558 | /// Interrupts measurements, as a power notification would, if the system |
| 559 | /// suspended since the previous check. Measurements that end call this |
| 560 | /// before deciding whether to keep themselves, so a suspend during them |
| 561 | /// is detected even if its notification hasn't been handled yet. |
| 562 | // |
| 563 | // Power notifications arrive on the foreground thread, so work that was |
| 564 | // running when the system suspended finishes before its notification is |
| 565 | // handled (and on Windows the notification may never arrive). |
| 566 | fn detect_suspend(&mut self, at: Instant) { |
| 567 | let Some(suspended_time) = (self.read_suspended_time)() else { |
| 568 | return; |
| 569 | }; |
| 570 | let previous = self.suspended_time.replace(suspended_time); |
| 571 | if previous |
| 572 | .is_some_and(|previous| suspended_time.saturating_sub(previous) >= MIN_DETECTED_SUSPEND) |
| 573 | { |
| 574 | self.interrupt_measurements(at); |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | /// Seals the open interval and invalidates all measurements in progress |
| 579 | /// at `at`, since they may span a suspend. |
| 580 | fn interrupt_measurements(&mut self, at: Instant) { |
| 581 | self.record_entry(ForegroundJournalEntry::Boundary( |
| 582 | IntervalBoundary::PowerTransition { ended_at: at }, |
| 583 | )); |
| 584 | self.power_changed_at = Some(at); |
| 585 | for window in self.windows.values_mut() { |
| 586 | window.dirty_at = None; |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | /// Whether work that started at `start` spans a sleep or a wake, and so |
| 591 | /// must not be measured as uninterrupted foreground work. |
| 592 | fn power_interrupted_since(&self, start: Instant) -> bool { |
| 593 | self.power == PowerState::Suspended || self.power_changed_at.is_some_and(|at| start <= at) |
| 594 | } |
| 595 | |
| 596 | fn set_visibility(&mut self, id: WindowId, visibility: WindowVisibility, at: Instant) { |
| 597 | let window = self |
| 598 | .windows |
| 599 | .entry(id) |
| 600 | .or_insert_with(|| WindowFrameState::new(visibility)); |
| 601 | if window.visibility != visibility { |
| 602 | window.visibility = visibility; |
| 603 | window.visibility_changed_at = Some(at); |
| 604 | window.dirty_at = None; |
| 605 | } |
| 606 | } |
| 607 | |
| 608 | fn fold_small_poll(&mut self, timing: TaskTiming) { |
| 609 | let flush = self.small_polls.get_or_insert(SmallPollFlush { |
| 610 | summary: PollSummary::default(), |
| 611 | since: timing.start, |
| 612 | until: timing.end.0, |
| 613 | }); |
| 614 | flush.summary.count += 1; |
| 615 | flush.summary.total += timing.poll_duration(); |
| 616 | flush.since = flush.since.min(timing.start); |
| 617 | flush.until = flush.until.max(timing.end.0); |
| 618 | } |
| 619 | |
| 620 | fn take_small_polls(&mut self) -> Option<SmallPollFlush> { |
| 621 | self.small_polls.take() |
| 622 | } |
| 623 | |
| 624 | fn record_event(&mut self, event: ForegroundEvent) { |
| 625 | self.retained_since_boundary = true; |
| 626 | self.record_entry(ForegroundJournalEntry::Event(event)); |
| 627 | } |
| 628 | |
| 629 | fn record_entry(&mut self, entry: ForegroundJournalEntry) { |
| 630 | let small_polls = self |
| 631 | .take_small_polls() |
| 632 | .map(ForegroundEvent::SmallPolls) |
| 633 | .map(ForegroundJournalEntry::Event); |
| 634 | self.publisher |
| 635 | .publish([small_polls, Some(entry)].into_iter().flatten()); |
| 636 | if matches!(entry, ForegroundJournalEntry::Boundary(_)) { |
| 637 | self.retained_since_boundary = false; |
| 638 | } |
| 639 | } |
| 640 | |
| 641 | /// Publishes a point record that is neither work nor a boundary. Folded |
| 642 | /// polls stay folded: publishing them here would let them reach the |
| 643 | /// sealer even when [`Self::end_turn`] later discards folded-only work. |
| 644 | fn record_marker(&mut self, entry: ForegroundJournalEntry) { |
| 645 | self.publisher.publish([entry]); |
| 646 | } |
| 647 | |
| 648 | fn record_frame_state(&mut self, change: FrameStateChange) { |
| 649 | self.record_entry(ForegroundJournalEntry::FrameState(change)); |
| 650 | } |
| 651 | |
| 652 | fn record_platform_signal(&mut self, signal: PlatformSignal) { |
| 653 | self.record_marker(ForegroundJournalEntry::PlatformSignal(signal)); |
| 654 | } |
| 655 | |
| 656 | /// Seals retained work at a frame request that didn't draw. Like idle |
| 657 | /// boundaries, skips require a retained event since the last boundary: |
| 658 | /// platforms that request a frame every refresh would otherwise seal an |
| 659 | /// empty interval, and flush folded polls, on every idle refresh. |
| 660 | fn record_frame_skipped(&mut self, skipped: FrameSkipped) { |
| 661 | if !self.retained_since_boundary { |
| 662 | return; |
| 663 | } |
| 664 | // Even a no-render callback can schedule or invalidate the next frame. |
| 665 | // Skipping does not establish that the window's pending demand is met. |
| 666 | self.record_entry(ForegroundJournalEntry::Boundary( |
| 667 | IntervalBoundary::FrameSkipped(skipped), |
| 668 | )); |
| 669 | } |
| 670 | |
| 671 | fn record_frame_pending(&mut self, window_id: WindowId, dirty_at: Instant) { |
| 672 | let window = self |
| 673 | .windows |
| 674 | .entry(window_id) |
| 675 | .or_insert_with(|| WindowFrameState::new(WindowVisibility::Visible)); |
| 676 | if self.power == PowerState::Suspended |
| 677 | || !window.visibility.is_visible() |
| 678 | || window |
| 679 | .dirty_at |
| 680 | .is_some_and(|at| dirty_at.saturating_duration_since(at) < FRAME_DEADLINE) |
| 681 | { |
| 682 | return; |
| 683 | } |
| 684 | |
| 685 | window.dirty_at = Some(dirty_at); |
| 686 | self.record_frame_state(FrameStateChange::Pending { |
| 687 | window_id, |
| 688 | dirty_at, |
| 689 | }); |
| 690 | } |
| 691 | |
| 692 | fn record_window_closed(&mut self, window_id: WindowId, at: Instant) { |
| 693 | self.windows.remove(&window_id); |
| 694 | self.record_frame_state(FrameStateChange::Closed { window_id, at }); |
| 695 | } |
| 696 | |
| 697 | fn record_present(&mut self, timing: PresentTiming, frame: Option<FrameTiming>) { |
| 698 | if let Some(window) = self.windows.get_mut(&timing.window_id) { |
| 699 | window.dirty_at = None; |
| 700 | } |
| 701 | if self.power_interrupted_since(timing.present_start) { |
| 702 | return; |
| 703 | } |
| 704 | match frame { |
| 705 | Some(frame) => { |
| 706 | self.record_entry(ForegroundJournalEntry::Boundary( |
| 707 | IntervalBoundary::Presented(PresentedFrame { |
| 708 | frame, |
| 709 | presentation: timing, |
| 710 | }), |
| 711 | )); |
| 712 | } |
| 713 | None => { |
| 714 | self.record_event(ForegroundEvent::Present(timing)); |
| 715 | } |
| 716 | } |
| 717 | } |
| 718 | } |
| 719 | |
| 720 | thread_local! { |
| 721 | static FOREGROUND_RUNNABLES: ForegroundRunnableCounter = ForegroundRunnableCounter::new(); |
| 722 | static FOREGROUND_JOURNAL: RefCell<Option<ForegroundJournalWriter>> = const { RefCell::new(None) }; |
| 723 | } |
| 724 | |
| 725 | pub(crate) fn foreground_runnable_counter() -> ForegroundRunnableCounter { |
| 726 | FOREGROUND_RUNNABLES.with(Clone::clone) |
| 727 | } |
| 728 | |
| 729 | /// Starts journaling on the calling thread. Called once by `App` construction |
| 730 | /// on the main thread; every other thread's recording calls are no-ops. |
| 731 | /// Idempotent so that multiple `App`s on one thread (tests) share one journal. |
| 732 | pub(crate) fn install_foreground_journal() -> ForegroundJournal { |
| 733 | let foreground_runnables = foreground_runnable_counter(); |
| 734 | FOREGROUND_JOURNAL.with(|journal| { |
| 735 | let mut journal = journal.borrow_mut(); |
| 736 | if let Some(journal) = journal.as_ref() { |
| 737 | return ForegroundJournal { |
| 738 | ring: Arc::clone(&journal.publisher.ring), |
| 739 | }; |
| 740 | } |
| 741 | |
| 742 | let (handle, publisher) = |
| 743 | ForegroundJournal::new(MAX_JOURNAL_ENTRIES, MAX_PENDING_JOURNAL_ENTRIES); |
| 744 | *journal = Some(ForegroundJournalWriter::new( |
| 745 | foreground_runnables, |
| 746 | publisher, |
| 747 | )); |
| 748 | handle |
| 749 | }) |
| 750 | } |
| 751 | |
| 752 | /// Restores the previous foreground journal on drop, so a test's writer |
| 753 | /// (turn depth, pending frames, retained-since-boundary state) never leaks |
| 754 | /// into a later test that happens to reuse the same test-harness thread. |
| 755 | #[cfg(test)] |
| 756 | pub(crate) struct TestForegroundJournalGuard { |
| 757 | previous: Option<ForegroundJournalWriter>, |
| 758 | _not_send: std::marker::PhantomData<std::rc::Rc<()>>, |
| 759 | } |
| 760 | |
| 761 | #[cfg(test)] |
| 762 | impl Drop for TestForegroundJournalGuard { |
| 763 | fn drop(&mut self) { |
| 764 | FOREGROUND_JOURNAL.with(|journal| { |
| 765 | *journal.borrow_mut() = self.previous.take(); |
| 766 | }); |
| 767 | } |
| 768 | } |
| 769 | |
| 770 | /// Installs a fresh journal for the duration of a test, isolated from |
| 771 | /// whatever a previous test left on this thread. Used by tests outside this |
| 772 | /// module (e.g. `bench_context`) that need to observe journal entries |
| 773 | /// without interference from the shared per-thread journal. |
| 774 | #[cfg(test)] |
| 775 | pub(crate) fn install_test_foreground_journal( |
| 776 | capacity: usize, |
| 777 | pending_capacity: usize, |
| 778 | ) -> (ForegroundJournal, TestForegroundJournalGuard) { |
| 779 | let foreground_runnables = foreground_runnable_counter(); |
| 780 | let (handle, publisher) = ForegroundJournal::new(capacity, pending_capacity); |
| 781 | let previous = FOREGROUND_JOURNAL.with(|journal| { |
| 782 | journal.borrow_mut().replace( |
| 783 | ForegroundJournalWriter::new(foreground_runnables, publisher).with_test_suspend_clock(), |
| 784 | ) |
| 785 | }); |
| 786 | ( |
| 787 | handle, |
| 788 | TestForegroundJournalGuard { |
| 789 | previous, |
| 790 | _not_send: std::marker::PhantomData, |
| 791 | }, |
| 792 | ) |
| 793 | } |
| 794 | |
| 795 | #[cfg(test)] |
| 796 | thread_local! { |
| 797 | static TEST_SUSPENDED_TIME: std::cell::Cell<Duration> = const { std::cell::Cell::new(Duration::ZERO) }; |
| 798 | } |
| 799 | |
| 800 | #[cfg(test)] |
| 801 | fn test_suspended_time() -> Option<Duration> { |
| 802 | Some(TEST_SUSPENDED_TIME.get()) |
| 803 | } |
| 804 | |
| 805 | /// Simulates the system spending `duration` suspended, as observed through |
| 806 | /// the suspend clock of journals using [`ForegroundJournalWriter::with_test_suspend_clock`]. |
| 807 | #[cfg(test)] |
| 808 | pub(crate) fn advance_test_suspended_time(duration: Duration) { |
| 809 | TEST_SUSPENDED_TIME.set(TEST_SUSPENDED_TIME.get() + duration); |
| 810 | } |
| 811 | |
| 812 | #[cfg(test)] |
| 813 | impl ForegroundJournalWriter { |
| 814 | /// Replaces the system suspend clock, so a real suspend during a test |
| 815 | /// can't interrupt its measurements. |
| 816 | fn with_test_suspend_clock(mut self) -> Self { |
| 817 | TEST_SUSPENDED_TIME.set(Duration::ZERO); |
| 818 | self.read_suspended_time = test_suspended_time; |
| 819 | self.suspended_time = test_suspended_time(); |
| 820 | self |
| 821 | } |
| 822 | } |
| 823 | |
| 824 | fn with_journal(f: impl FnOnce(&mut ForegroundJournalWriter)) { |
| 825 | FOREGROUND_JOURNAL.with(|journal| { |
| 826 | if let Some(journal) = journal.borrow_mut().as_mut() { |
| 827 | f(journal); |
| 828 | } |
| 829 | }); |
| 830 | } |
| 831 | |
| 832 | pub(crate) fn observe_power(cx: &App) { |
| 833 | cx.on_system_sleep(|_| { |
| 834 | record_power_transition(PowerState::Suspended); |
| 835 | }) |
| 836 | .detach(); |
| 837 | // Visibility notifications delivered during sleep may have been missed. |
| 838 | cx.on_system_wake(|cx| { |
| 839 | record_power_transition(PowerState::Awake); |
| 840 | cx.spawn(async |cx| { |
| 841 | cx.update(|cx| { |
| 842 | for handle in cx.windows() { |
| 843 | handle |
| 844 | .update(cx, |_, window, cx| window.refresh_visibility(cx)) |
| 845 | .log_err(); |
| 846 | } |
| 847 | }); |
| 848 | }) |
| 849 | .detach(); |
| 850 | }) |
| 851 | .detach(); |
| 852 | } |
| 853 | |
| 854 | /// Total time the system has spent suspended since boot, or `None` where no |
| 855 | /// clock provides it: the difference between a clock that counts suspended |
| 856 | /// time and one that doesn't. The suspend-excluding clock is read first so |
| 857 | /// read latency can't make the difference negative. Every read is served from |
| 858 | /// memory the kernel maps into the process, without a syscall. |
| 859 | #[cfg(any(target_os = "linux", target_os = "android"))] |
| 860 | fn system_suspended_time() -> Option<Duration> { |
| 861 | // CLOCK_BOOTTIME is CLOCK_MONOTONIC plus time spent suspended: |
| 862 | // https://man7.org/linux/man-pages/man2/clock_gettime.2.html |
| 863 | let awake = read_clock(libc::CLOCK_MONOTONIC)?; |
| 864 | let total = read_clock(libc::CLOCK_BOOTTIME)?; |
| 865 | Some(total.saturating_sub(awake)) |
| 866 | } |
| 867 | |
| 868 | #[cfg(target_os = "macos")] |
| 869 | fn system_suspended_time() -> Option<Duration> { |
| 870 | use std::sync::OnceLock; |
| 871 | |
| 872 | // Declared here because libc deprecates its mach bindings, and these |
| 873 | // three functions don't justify a `mach2` dependency. `<mach/mach_time.h>` |
| 874 | // documents `mach_continuous_time` as "like mach_absolute_time, but |
| 875 | // advances during sleep", so both count the same ticks: |
| 876 | // https://github.com/apple-oss-distributions/xnu/blob/main/osfmk/mach/mach_time.h |
| 877 | #[repr(C)] |
| 878 | struct MachTimebaseInfo { |
| 879 | numer: u32, |
| 880 | denom: u32, |
| 881 | } |
| 882 | unsafe extern "C" { |
| 883 | fn mach_absolute_time() -> u64; |
| 884 | fn mach_continuous_time() -> u64; |
| 885 | fn mach_timebase_info(info: *mut MachTimebaseInfo) -> i32; |
| 886 | } |
| 887 | |
| 888 | static TIMEBASE: OnceLock<Option<(u32, u32)>> = OnceLock::new(); |
| 889 | let (numer, denom) = (*TIMEBASE.get_or_init(|| { |
| 890 | let mut info = MachTimebaseInfo { numer: 0, denom: 0 }; |
| 891 | // SAFETY: `info` is a valid, writable mach_timebase_info. |
| 892 | let succeeded = unsafe { mach_timebase_info(&mut info) } == 0; |
| 893 | (succeeded && info.denom != 0).then_some((info.numer, info.denom)) |
| 894 | }))?; |
| 895 | // SAFETY: neither function has preconditions. |
| 896 | let awake = unsafe { mach_absolute_time() }; |
| 897 | // SAFETY: as above. |
| 898 | let total = unsafe { mach_continuous_time() }; |
| 899 | let nanos = u128::from(total.saturating_sub(awake)) * u128::from(numer) / u128::from(denom); |
| 900 | Some(Duration::from_nanos(u64::try_from(nanos).ok()?)) |
| 901 | } |
| 902 | |
| 903 | #[cfg(any(target_os = "linux", target_os = "android"))] |
| 904 | fn read_clock(clock: libc::clockid_t) -> Option<Duration> { |
| 905 | let mut time = libc::timespec { |
| 906 | tv_sec: 0, |
| 907 | tv_nsec: 0, |
| 908 | }; |
| 909 | // SAFETY: `time` is a valid, writable timespec. |
| 910 | if unsafe { libc::clock_gettime(clock, &mut time) } != 0 { |
| 911 | return None; |
| 912 | } |
| 913 | Some(Duration::new( |
| 914 | u64::try_from(time.tv_sec).ok()?, |
| 915 | u32::try_from(time.tv_nsec).ok()?, |
| 916 | )) |
| 917 | } |
| 918 | |
| 919 | #[cfg(target_os = "windows")] |
| 920 | fn system_suspended_time() -> Option<Duration> { |
| 921 | use windows::Win32::System::WindowsProgramming::{ |
| 922 | QueryInterruptTime, QueryUnbiasedInterruptTime, |
| 923 | }; |
| 924 | let mut awake = 0; |
| 925 | // SAFETY: `awake` is a valid, writable u64. |
| 926 | if !unsafe { QueryUnbiasedInterruptTime(&mut awake) }.as_bool() { |
| 927 | return None; |
| 928 | } |
| 929 | // SAFETY: no preconditions. |
| 930 | let total = unsafe { QueryInterruptTime() }; |
| 931 | // Both count 100 ns units; unbiased interrupt time excludes sleep and |
| 932 | // hibernation: |
| 933 | // https://learn.microsoft.com/en-us/windows/win32/sysinfo/interrupt-time |
| 934 | Some(Duration::from_nanos( |
| 935 | total.saturating_sub(awake).saturating_mul(100), |
| 936 | )) |
| 937 | } |
| 938 | |
| 939 | #[cfg(not(any( |
| 940 | target_os = "linux", |
| 941 | target_os = "android", |
| 942 | target_os = "macos", |
| 943 | target_os = "windows" |
| 944 | )))] |
| 945 | fn system_suspended_time() -> Option<Duration> { |
| 946 | None |
| 947 | } |
| 948 | |
| 949 | pub(crate) fn record_power_transition(state: PowerState) { |
| 950 | with_journal(|journal| journal.power_transition(state, Instant::now())); |
| 951 | } |
| 952 | |
| 953 | /// Whether work that started at `start` spans a sleep or a wake. Such work |
| 954 | /// is dropped rather than measured. |
| 955 | pub(crate) fn power_interrupted_since(start: Instant) -> bool { |
| 956 | let mut interrupted = false; |
| 957 | with_journal(|journal| { |
| 958 | journal.detect_suspend(Instant::now()); |
| 959 | interrupted = journal.power_interrupted_since(start); |
| 960 | }); |
| 961 | interrupted |
| 962 | } |
| 963 | |
| 964 | pub(crate) fn record_window_visibility(id: WindowId, visibility: WindowVisibility) { |
| 965 | with_journal(|journal| journal.set_visibility(id, visibility, Instant::now())); |
| 966 | } |
| 967 | |
| 968 | /// Whether a frame sample that started at `start` was measured while the |
| 969 | /// window stayed visible and the system stayed awake. |
| 970 | pub(crate) fn frame_sample_is_valid(id: WindowId, start: Instant) -> bool { |
| 971 | let mut valid = true; |
| 972 | with_journal(|journal| { |
| 973 | journal.detect_suspend(Instant::now()); |
| 974 | valid = !journal.power_interrupted_since(start) |
| 975 | && journal.windows.get(&id).is_none_or(|window| { |
| 976 | window.visibility.is_visible() |
| 977 | && window.visibility_changed_at.is_none_or(|at| start > at) |
| 978 | }); |
| 979 | }); |
| 980 | valid |
| 981 | } |
| 982 | |
| 983 | // TODO(gpui-profiler): the turn brackets in the dispatchers and |
| 984 | // WindowProfiler are bare begin/end call pairs rather than uses of this |
| 985 | // guard. A caught unwind between a pair leaves `turn_depth` (and potentially |
| 986 | // the runnable counter) permanently unbalanced, which silently disables |
| 987 | // idle boundaries for the rest of the process. Zed aborts on panics so |
| 988 | // this is latent today, but gpui-as-a-library callers may catch unwinds; |
| 989 | // route all bracketing through this guard. |
| 990 | pub(crate) struct ForegroundTurnGuard; |
| 991 | |
| 992 | impl Drop for ForegroundTurnGuard { |
| 993 | fn drop(&mut self) { |
| 994 | end_foreground_turn(); |
| 995 | } |
| 996 | } |
| 997 | |
| 998 | pub(crate) fn foreground_turn() -> ForegroundTurnGuard { |
| 999 | begin_foreground_turn(); |
| 1000 | ForegroundTurnGuard |
| 1001 | } |
| 1002 | |
| 1003 | pub(crate) fn begin_foreground_turn() { |
| 1004 | // Observing before the turn's work takes its start time means a suspend |
| 1005 | // detected here never invalidates the work that follows it. |
| 1006 | with_journal(|journal| { |
| 1007 | journal.detect_suspend(Instant::now()); |
| 1008 | journal.begin_turn(); |
| 1009 | }); |
| 1010 | } |
| 1011 | |
| 1012 | pub(crate) fn end_foreground_turn() { |
| 1013 | with_journal(|journal| journal.end_turn(Instant::now())); |
| 1014 | } |
| 1015 | |
| 1016 | pub(crate) fn record_task_poll(timing: TaskTiming) { |
| 1017 | FOREGROUND_RUNNABLES.with(ForegroundRunnableCounter::finished); |
| 1018 | with_journal(|journal| { |
| 1019 | journal.detect_suspend(timing.end.0); |
| 1020 | if journal.power_interrupted_since(timing.start) { |
| 1021 | journal.end_turn(timing.end.0); |
| 1022 | return; |
| 1023 | } |
| 1024 | if timing.poll_duration() >= TASK_POLL_FLOOR { |
| 1025 | journal.record_event(ForegroundEvent::TaskPoll(timing)); |
| 1026 | } else { |
| 1027 | journal.fold_small_poll(timing); |
| 1028 | } |
| 1029 | journal.end_turn(timing.end.0); |
| 1030 | }); |
| 1031 | } |
| 1032 | |
| 1033 | pub(crate) fn record_action(timing: ActionTiming) { |
| 1034 | with_journal(|journal| journal.record_event(ForegroundEvent::Action(timing))); |
| 1035 | } |
| 1036 | |
| 1037 | pub(crate) fn record_input(timing: InputTiming) { |
| 1038 | with_journal(|journal| journal.record_event(ForegroundEvent::Input(timing))); |
| 1039 | } |
| 1040 | |
| 1041 | pub(crate) fn record_draw(timing: FrameTiming) { |
| 1042 | with_journal(|journal| journal.record_event(ForegroundEvent::Draw(timing))); |
| 1043 | } |
| 1044 | |
| 1045 | pub(crate) fn record_present(timing: PresentTiming, frame: Option<FrameTiming>) { |
| 1046 | with_journal(|journal| journal.record_present(timing, frame)); |
| 1047 | } |
| 1048 | |
| 1049 | pub(crate) fn record_platform_signal(signal: PlatformSignal) { |
| 1050 | with_journal(|journal| journal.record_platform_signal(signal)); |
| 1051 | } |
| 1052 | |
| 1053 | pub(crate) fn record_reentrant_frame_skipped(window_id: WindowId, at: Instant) { |
| 1054 | with_journal(|journal| { |
| 1055 | journal.record_marker(ForegroundJournalEntry::ReentrantFrameSkipped { window_id, at }); |
| 1056 | }); |
| 1057 | } |
| 1058 | |
| 1059 | pub(crate) fn record_frame_skipped(window_id: WindowId, at: Instant, reason: FrameSkipReason) { |
| 1060 | with_journal(|journal| { |
| 1061 | journal.record_frame_skipped(FrameSkipped { |
| 1062 | window_id, |
| 1063 | at, |
| 1064 | reason, |
| 1065 | }) |
| 1066 | }); |
| 1067 | } |
| 1068 | |
| 1069 | pub(crate) fn record_frame_pending(window_id: WindowId, dirty_at: Instant) { |
| 1070 | with_journal(|journal| journal.record_frame_pending(window_id, dirty_at)); |
| 1071 | } |
| 1072 | |
| 1073 | pub(crate) fn record_window_closed(window_id: WindowId) { |
| 1074 | let at = Instant::now(); |
| 1075 | with_journal(|journal| journal.record_window_closed(window_id, at)); |
| 1076 | } |
| 1077 | |
| 1078 | const SLOT_WRITER: usize = 1 << (usize::BITS - 1); |
| 1079 | const SLOT_READER_MASK: usize = !SLOT_WRITER; |
| 1080 | const EMPTY_SEQUENCE: u64 = u64::MAX; |
| 1081 | |
| 1082 | struct JournalSlot { |
| 1083 | users: AtomicUsize, |
| 1084 | sequence: AtomicU64, |
| 1085 | entry: UnsafeCell<MaybeUninit<ForegroundJournalEntry>>, |
| 1086 | } |
| 1087 | |
| 1088 | // `users` ensures the entry is only read while no writer owns the slot and is |
| 1089 | // only written while no readers own it. |
| 1090 | unsafe impl Sync for JournalSlot {} |
| 1091 | |
| 1092 | impl JournalSlot { |
| 1093 | fn new() -> Self { |
| 1094 | Self { |
| 1095 | users: AtomicUsize::new(0), |
| 1096 | sequence: AtomicU64::new(EMPTY_SEQUENCE), |
| 1097 | entry: UnsafeCell::new(MaybeUninit::uninit()), |
| 1098 | } |
| 1099 | } |
| 1100 | |
| 1101 | fn try_publish(&self, sequence: u64, entry: ForegroundJournalEntry) -> bool { |
| 1102 | if self |
| 1103 | .users |
| 1104 | .compare_exchange(0, SLOT_WRITER, Ordering::Acquire, Ordering::Relaxed) |
| 1105 | .is_err() |
| 1106 | { |
| 1107 | return false; |
| 1108 | } |
| 1109 | |
| 1110 | // SAFETY: setting SLOT_WRITER from zero gives this writer exclusive |
| 1111 | // access to the slot until the Release store below. |
| 1112 | unsafe { |
| 1113 | (*self.entry.get()).write(entry); |
| 1114 | } |
| 1115 | self.sequence.store(sequence, Ordering::Relaxed); |
| 1116 | self.users.store(0, Ordering::Release); |
| 1117 | true |
| 1118 | } |
| 1119 | |
| 1120 | fn try_read(&self, expected_sequence: u64) -> Option<ForegroundJournalEntry> { |
| 1121 | let _guard = JournalSlotReadGuard::try_new(self)?; |
| 1122 | if self.sequence.load(Ordering::Relaxed) != expected_sequence { |
| 1123 | return None; |
| 1124 | } |
| 1125 | |
| 1126 | // SAFETY: a matching sequence means the slot was initialized for this |
| 1127 | // logical entry, and `guard` prevents the writer from overwriting it |
| 1128 | // until after the Copy. |
| 1129 | Some(unsafe { *(*self.entry.get()).assume_init_ref() }) |
| 1130 | } |
| 1131 | |
| 1132 | fn try_add_reader(&self) -> bool { |
| 1133 | let mut users = self.users.load(Ordering::Relaxed); |
| 1134 | loop { |
| 1135 | if users & SLOT_WRITER != 0 || users == SLOT_READER_MASK { |
| 1136 | return false; |
| 1137 | } |
| 1138 | match self.users.compare_exchange_weak( |
| 1139 | users, |
| 1140 | users + 1, |
| 1141 | Ordering::Acquire, |
| 1142 | Ordering::Relaxed, |
| 1143 | ) { |
| 1144 | Ok(_) => return true, |
| 1145 | Err(updated_users) => users = updated_users, |
| 1146 | } |
| 1147 | } |
| 1148 | } |
| 1149 | |
| 1150 | fn remove_reader(&self) { |
| 1151 | let previous = self.users.fetch_sub(1, Ordering::Release); |
| 1152 | debug_assert!( |
| 1153 | previous > 0 && previous & SLOT_WRITER == 0, |
| 1154 | "invalid slot reader state: {previous:#x}" |
| 1155 | ); |
| 1156 | } |
| 1157 | } |
| 1158 | |
| 1159 | struct JournalSlotReadGuard<'a> { |
| 1160 | slot: &'a JournalSlot, |
| 1161 | } |
| 1162 | |
| 1163 | impl<'a> JournalSlotReadGuard<'a> { |
| 1164 | fn try_new(slot: &'a JournalSlot) -> Option<Self> { |
| 1165 | if slot.try_add_reader() { |
| 1166 | Some(Self { slot }) |
| 1167 | } else { |
| 1168 | None |
| 1169 | } |
| 1170 | } |
| 1171 | } |
| 1172 | |
| 1173 | impl Drop for JournalSlotReadGuard<'_> { |
| 1174 | fn drop(&mut self) { |
| 1175 | self.slot.remove_reader(); |
| 1176 | } |
| 1177 | } |
| 1178 | |
| 1179 | struct JournalRing { |
| 1180 | slots: Box<[JournalSlot]>, |
| 1181 | finalized: AtomicU64, |
| 1182 | offered: AtomicU64, |
| 1183 | } |
| 1184 | |
| 1185 | impl JournalRing { |
| 1186 | fn new(capacity: usize) -> Self { |
| 1187 | let capacity = capacity.max(1); |
| 1188 | Self { |
| 1189 | slots: (0..capacity).map(|_| JournalSlot::new()).collect(), |
| 1190 | finalized: AtomicU64::new(0), |
| 1191 | offered: AtomicU64::new(0), |
| 1192 | } |
| 1193 | } |
| 1194 | |
| 1195 | fn capacity(&self) -> usize { |
| 1196 | self.slots.len() |
| 1197 | } |
| 1198 | |
| 1199 | fn try_publish(&self, sequence: u64, entry: ForegroundJournalEntry) -> bool { |
| 1200 | let index = (sequence % self.slots.len() as u64) as usize; |
| 1201 | self.slots[index].try_publish(sequence, entry) |
| 1202 | } |
| 1203 | |
| 1204 | fn read(&self, sequence: u64) -> Option<ForegroundJournalEntry> { |
| 1205 | let index = (sequence % self.slots.len() as u64) as usize; |
| 1206 | self.slots[index].try_read(sequence) |
| 1207 | } |
| 1208 | } |
| 1209 | |
| 1210 | struct PendingJournalEntry { |
| 1211 | sequence: u64, |
| 1212 | entry: ForegroundJournalEntry, |
| 1213 | } |
| 1214 | |
| 1215 | struct JournalPublisher { |
| 1216 | ring: Arc<JournalRing>, |
| 1217 | next_sequence: u64, |
| 1218 | pending: VecDeque<PendingJournalEntry>, |
| 1219 | dropped_after_pending: u64, |
| 1220 | pending_capacity: usize, |
| 1221 | } |
| 1222 | |
| 1223 | impl JournalPublisher { |
| 1224 | fn new(ring: Arc<JournalRing>, pending_capacity: usize) -> Self { |
| 1225 | Self { |
| 1226 | ring, |
| 1227 | next_sequence: 0, |
| 1228 | pending: VecDeque::with_capacity(pending_capacity), |
| 1229 | dropped_after_pending: 0, |
| 1230 | pending_capacity, |
| 1231 | } |
| 1232 | } |
| 1233 | |
| 1234 | fn publish(&mut self, entries: impl IntoIterator<Item = ForegroundJournalEntry>) { |
| 1235 | for entry in entries { |
| 1236 | self.flush_pending(); |
| 1237 | self.publish_one(entry); |
| 1238 | } |
| 1239 | self.flush_pending(); |
| 1240 | } |
| 1241 | |
| 1242 | fn publish_one(&mut self, entry: ForegroundJournalEntry) { |
| 1243 | let sequence = self.next_sequence; |
| 1244 | self.next_sequence += 1; |
| 1245 | self.ring |
| 1246 | .offered |
| 1247 | .store(self.next_sequence, Ordering::Release); |
| 1248 | |
| 1249 | if !self.pending.is_empty() || self.dropped_after_pending > 0 { |
| 1250 | if self.dropped_after_pending == 0 && self.pending.len() < self.pending_capacity { |
| 1251 | self.pending |
| 1252 | .push_back(PendingJournalEntry { sequence, entry }); |
| 1253 | } else { |
| 1254 | self.dropped_after_pending += 1; |
| 1255 | } |
| 1256 | return; |
| 1257 | } |
| 1258 | |
| 1259 | if self.ring.try_publish(sequence, entry) { |
| 1260 | self.ring.finalized.store(sequence + 1, Ordering::Release); |
| 1261 | } else if self.pending_capacity > 0 { |
| 1262 | self.pending |
| 1263 | .push_back(PendingJournalEntry { sequence, entry }); |
| 1264 | } else { |
| 1265 | self.dropped_after_pending = 1; |
| 1266 | } |
| 1267 | } |
| 1268 | |
| 1269 | fn flush_pending(&mut self) { |
| 1270 | while let Some(pending) = self.pending.front() { |
| 1271 | if !self.ring.try_publish(pending.sequence, pending.entry) { |
| 1272 | return; |
| 1273 | } |
| 1274 | let sequence = pending.sequence; |
| 1275 | self.pending.pop_front(); |
| 1276 | self.ring.finalized.store(sequence + 1, Ordering::Release); |
| 1277 | } |
| 1278 | |
| 1279 | if self.dropped_after_pending > 0 { |
| 1280 | self.ring |
| 1281 | .finalized |
| 1282 | .store(self.next_sequence, Ordering::Release); |
| 1283 | self.dropped_after_pending = 0; |
| 1284 | } |
| 1285 | } |
| 1286 | } |
| 1287 | |
| 1288 | /// A cloneable handle to one foreground journal stream. |
| 1289 | /// |
| 1290 | /// Each collector has an independent cursor. Collectors briefly pin one slot |
| 1291 | /// at a time and never block recording; entries they could not observe are |
| 1292 | /// reported as discontinuities. Apps on the same foreground thread share the |
| 1293 | /// stream. |
| 1294 | #[derive(Clone)] |
| 1295 | pub struct ForegroundJournal { |
| 1296 | ring: Arc<JournalRing>, |
| 1297 | } |
| 1298 | |
| 1299 | impl ForegroundJournal { |
| 1300 | fn new(capacity: usize, pending_capacity: usize) -> (Self, JournalPublisher) { |
| 1301 | let ring = Arc::new(JournalRing::new(capacity)); |
| 1302 | ( |
| 1303 | Self { |
| 1304 | ring: Arc::clone(&ring), |
| 1305 | }, |
| 1306 | JournalPublisher::new(ring, pending_capacity), |
| 1307 | ) |
| 1308 | } |
| 1309 | |
| 1310 | /// Creates an independent collector that observes entries offered after |
| 1311 | /// this call. |
| 1312 | pub fn collector(&self) -> ForegroundJournalCollector { |
| 1313 | ForegroundJournalCollector { |
| 1314 | cursor: self.ring.offered.load(Ordering::Acquire), |
| 1315 | ring: Arc::clone(&self.ring), |
| 1316 | } |
| 1317 | } |
| 1318 | } |
| 1319 | |
| 1320 | /// Entries returned by one [`ForegroundJournalCollector::collect_unseen`] call. |
| 1321 | #[derive(Debug, Default)] |
| 1322 | pub struct DrainedEntries { |
| 1323 | /// Journal entries recorded since the previous drain, in recording order, |
| 1324 | /// including synthetic [`ForegroundJournalEntry::Discontinuity`] markers at |
| 1325 | /// unavailable logical positions. |
| 1326 | pub entries: Vec<ForegroundJournalEntry>, |
| 1327 | /// Entries unavailable to this collector because they were overwritten or |
| 1328 | /// could not be published after the fixed pending queue filled. This is the |
| 1329 | /// aggregate of the discontinuity markers in `entries`. |
| 1330 | pub lost: u64, |
| 1331 | } |
| 1332 | |
| 1333 | /// Reads the foreground stream, tracking a cursor so each call to |
| 1334 | /// [`Self::collect_unseen`] returns only entries recorded since the previous |
| 1335 | /// call. Independent collectors do not affect each other. |
| 1336 | pub struct ForegroundJournalCollector { |
| 1337 | cursor: u64, |
| 1338 | ring: Arc<JournalRing>, |
| 1339 | } |
| 1340 | |
| 1341 | impl ForegroundJournalCollector { |
| 1342 | /// Returns entries recorded since the previous call (or since the |
| 1343 | /// collector was created), reporting how many were unavailable before this |
| 1344 | /// drain observed them. |
| 1345 | pub fn collect_unseen(&mut self) -> DrainedEntries { |
| 1346 | let end = self.ring.finalized.load(Ordering::Acquire); |
| 1347 | if self.cursor >= end { |
| 1348 | return DrainedEntries::default(); |
| 1349 | } |
| 1350 | let retained_start = end.saturating_sub(self.ring.capacity() as u64); |
| 1351 | let mut lost = retained_start.saturating_sub(self.cursor); |
| 1352 | self.cursor = self.cursor.max(retained_start); |
| 1353 | let mut entries = Vec::with_capacity((end - self.cursor) as usize + usize::from(lost > 0)); |
| 1354 | if lost > 0 { |
| 1355 | entries.push(ForegroundJournalEntry::Discontinuity { lost }); |
| 1356 | } |
| 1357 | |
| 1358 | while self.cursor < end { |
| 1359 | if let Some(entry) = self.ring.read(self.cursor) { |
| 1360 | entries.push(entry); |
| 1361 | } else { |
| 1362 | lost += 1; |
| 1363 | match entries.last_mut() { |
| 1364 | Some(ForegroundJournalEntry::Discontinuity { lost }) => *lost += 1, |
| 1365 | _ => entries.push(ForegroundJournalEntry::Discontinuity { lost: 1 }), |
| 1366 | } |
| 1367 | } |
| 1368 | self.cursor += 1; |
| 1369 | } |
| 1370 | |
| 1371 | DrainedEntries { entries, lost } |
| 1372 | } |
| 1373 | } |
| 1374 | |
| 1375 | /// A pure state machine that groups foreground journal entries into |
| 1376 | /// [`FrameSnapshot`]s. |
| 1377 | /// |
| 1378 | /// Feed it drained entries in recording order. Work is carried across calls |
| 1379 | /// until an explicit [`IntervalBoundary`] arrives. Idle time before an |
| 1380 | /// interval's first event is excluded without relying on an elapsed-time |
| 1381 | /// heuristic. |
| 1382 | #[derive(Debug)] |
| 1383 | pub struct IntervalSealer { |
| 1384 | interval_start: Instant, |
| 1385 | events: Vec<ForegroundEvent>, |
| 1386 | small_polls: Vec<SmallPollFlush>, |
| 1387 | dropped_events: u64, |
| 1388 | journal_discontinuous: bool, |
| 1389 | } |
| 1390 | |
| 1391 | impl IntervalSealer { |
| 1392 | /// Creates a sealer whose first interval starts at `start` (typically |
| 1393 | /// the moment the consumer's collector was created). |
| 1394 | pub fn new(start: Instant) -> Self { |
| 1395 | Self { |
| 1396 | interval_start: start, |
| 1397 | events: Vec::new(), |
| 1398 | small_polls: Vec::new(), |
| 1399 | dropped_events: 0, |
| 1400 | journal_discontinuous: false, |
| 1401 | } |
| 1402 | } |
| 1403 | |
| 1404 | /// Accounts for a loss supplied outside a collector drain. Collector losses |
| 1405 | /// are already represented by ordered discontinuity entries. |
| 1406 | pub fn note_lost(&mut self, lost: u64) { |
| 1407 | self.dropped_events += lost; |
| 1408 | self.journal_discontinuous |= lost > 0; |
| 1409 | } |
| 1410 | |
| 1411 | /// Processes a batch of drained entries, returning the snapshots completed |
| 1412 | /// by explicit boundaries. Work without a following boundary is carried |
| 1413 | /// over to subsequent calls. |
| 1414 | pub fn push_entries( |
| 1415 | &mut self, |
| 1416 | entries: impl IntoIterator<Item = ForegroundJournalEntry>, |
| 1417 | ) -> Vec<FrameSnapshot> { |
| 1418 | let mut snapshots = Vec::new(); |
| 1419 | for entry in entries { |
| 1420 | match entry { |
| 1421 | ForegroundJournalEntry::Event(event) => { |
| 1422 | if self.is_empty() { |
| 1423 | self.interval_start = self.interval_start.max(event.start_time()); |
| 1424 | } |
| 1425 | match event { |
| 1426 | ForegroundEvent::SmallPolls(flush) => self.push_small_polls(flush), |
| 1427 | event => self.push_event(event), |
| 1428 | } |
| 1429 | } |
| 1430 | ForegroundJournalEntry::Boundary(boundary) => { |
| 1431 | if let IntervalBoundary::Presented(presented) = boundary { |
| 1432 | if self.is_empty() { |
| 1433 | self.interval_start = self |
| 1434 | .interval_start |
| 1435 | .max(presented.presentation.present_start); |
| 1436 | } |
| 1437 | self.push_event(ForegroundEvent::Present(presented.presentation)); |
| 1438 | } |
| 1439 | if self.is_empty() { |
| 1440 | self.interval_start = self.interval_start.max(boundary.end_time()); |
| 1441 | } else { |
| 1442 | snapshots.push(self.seal(boundary)); |
| 1443 | } |
| 1444 | } |
| 1445 | // Pending-frame state gates boundaries on the writer side; |
| 1446 | // the entries remain in the stream for consumers that want |
| 1447 | // dirty timing, but the sealer has no use for them. |
| 1448 | ForegroundJournalEntry::FrameState(_) |
| 1449 | | ForegroundJournalEntry::PlatformSignal(_) |
| 1450 | | ForegroundJournalEntry::ReentrantFrameSkipped { .. } => {} |
| 1451 | ForegroundJournalEntry::Discontinuity { lost } => self.note_lost(lost), |
| 1452 | } |
| 1453 | } |
| 1454 | snapshots |
| 1455 | } |
| 1456 | |
| 1457 | fn is_empty(&self) -> bool { |
| 1458 | self.events.is_empty() |
| 1459 | && self.small_polls.is_empty() |
| 1460 | && self.dropped_events == 0 |
| 1461 | && !self.journal_discontinuous |
| 1462 | } |
| 1463 | |
| 1464 | fn push_event(&mut self, event: ForegroundEvent) { |
| 1465 | if self.events.len() >= MAX_INTERVAL_EVENTS { |
| 1466 | self.dropped_events += 1; |
| 1467 | } else { |
| 1468 | self.events.push(event); |
| 1469 | } |
| 1470 | } |
| 1471 | |
| 1472 | fn push_small_polls(&mut self, flush: SmallPollFlush) { |
| 1473 | if self.small_polls.len() >= MAX_INTERVAL_EVENTS |
| 1474 | && let Some(last) = self.small_polls.last_mut() |
| 1475 | { |
| 1476 | // Degrade gracefully at the cap: widen the last flush's span |
| 1477 | // instead of dropping poll time, at the cost of coarser |
| 1478 | // apportioning. |
| 1479 | last.summary.add(flush.summary); |
| 1480 | last.since = last.since.min(flush.since); |
| 1481 | last.until = last.until.max(flush.until); |
| 1482 | } else { |
| 1483 | self.small_polls.push(flush); |
| 1484 | } |
| 1485 | } |
| 1486 | |
| 1487 | fn seal(&mut self, boundary: IntervalBoundary) -> FrameSnapshot { |
| 1488 | let ended = boundary.end_time(); |
| 1489 | let snapshot = FrameSnapshot { |
| 1490 | interval_start: self.interval_start, |
| 1491 | boundary, |
| 1492 | events: std::mem::take(&mut self.events), |
| 1493 | small_polls: std::mem::take(&mut self.small_polls), |
| 1494 | dropped_events: std::mem::take(&mut self.dropped_events), |
| 1495 | journal_discontinuous: std::mem::take(&mut self.journal_discontinuous), |
| 1496 | }; |
| 1497 | self.interval_start = ended; |
| 1498 | snapshot |
| 1499 | } |
| 1500 | } |
| 1501 | |
| 1502 | #[cfg(test)] |
| 1503 | mod tests { |
| 1504 | use proptest::prelude::*; |
| 1505 | use scheduler::SpawnTime; |
| 1506 | |
| 1507 | use super::*; |
| 1508 | use crate::{WindowId, profiler::YieldTime}; |
| 1509 | |
| 1510 | #[test] |
| 1511 | fn platform_signals_are_journaled_without_sealing_or_occupying_time() { |
| 1512 | let (journal, _guard) = install_test_foreground_journal(32, 4); |
| 1513 | let mut collector = journal.collector(); |
| 1514 | let start = Instant::now(); |
| 1515 | let mut sealer = IntervalSealer::new(start); |
| 1516 | let window_id = WindowId::from(1); |
| 1517 | for source in [ |
| 1518 | crate::FrameRequestSource::NativeCallback, |
| 1519 | crate::FrameRequestSource::LocalSchedule, |
| 1520 | ] { |
| 1521 | for signal_at in [None, Some(start + Duration::from_secs(5))] { |
| 1522 | record_platform_signal(PlatformSignal { |
| 1523 | window_id, |
| 1524 | signal_at, |
| 1525 | handled_at: start + Duration::from_millis(5), |
| 1526 | source, |
| 1527 | }); |
| 1528 | let entries = collector.collect_unseen().entries; |
| 1529 | let [ForegroundJournalEntry::PlatformSignal(signal)] = entries.as_slice() else { |
| 1530 | panic!("expected a raw platform signal, got {entries:?}"); |
| 1531 | }; |
| 1532 | assert_eq!(signal.window_id, window_id); |
| 1533 | assert_eq!(signal.signal_at, signal_at); |
| 1534 | assert_eq!(signal.handled_at, start + Duration::from_millis(5)); |
| 1535 | assert_eq!(signal.source, source); |
| 1536 | assert!(sealer.push_entries(entries).is_empty()); |
| 1537 | } |
| 1538 | } |
| 1539 | let ended_at = start + Duration::from_millis(10); |
| 1540 | // An enclosing work span may complete after the callback metadata. |
| 1541 | let snapshots = sealer.push_entries([ |
| 1542 | input_entry(start, ended_at), |
| 1543 | ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { ended_at }), |
| 1544 | ]); |
| 1545 | let [snapshot] = snapshots.as_slice() else { |
| 1546 | panic!("expected one snapshot, got {snapshots:?}"); |
| 1547 | }; |
| 1548 | assert_eq!(snapshot.interval_start, start); |
| 1549 | assert_eq!(snapshot.interval_end(), ended_at); |
| 1550 | assert_eq!(snapshot.occupancy(), Duration::from_millis(10)); |
| 1551 | assert_eq!(snapshot.events.len(), 1); |
| 1552 | } |
| 1553 | |
| 1554 | #[test] |
| 1555 | fn completed_skips_seal_without_retiring_pending_demand() { |
| 1556 | let start = Instant::now(); |
| 1557 | let at = start + Duration::from_millis(10); |
| 1558 | let window_id = WindowId::from(1); |
| 1559 | for reason in [ |
| 1560 | FrameSkipReason::NoRenderNeeded, |
| 1561 | FrameSkipReason::InactiveFrameRateLimit, |
| 1562 | FrameSkipReason::ThermalFrameRateLimit, |
| 1563 | ] { |
| 1564 | let (mut writer, mut collector) = test_journal(ForegroundRunnableCounter::new()); |
| 1565 | writer.begin_turn(); |
| 1566 | writer.record_frame_pending(window_id, start); |
| 1567 | writer.record_event(ForegroundEvent::Input(InputTiming { |
| 1568 | kind: "test", |
| 1569 | start, |
| 1570 | end: start + Duration::from_millis(2), |
| 1571 | caused_invalidation: false, |
| 1572 | })); |
| 1573 | writer.record_frame_skipped(FrameSkipped { |
| 1574 | window_id, |
| 1575 | at, |
| 1576 | reason, |
| 1577 | }); |
| 1578 | |
| 1579 | let mut sealer = IntervalSealer::new(start); |
| 1580 | let snapshots = sealer.push_entries(collector.collect_unseen().entries); |
| 1581 | let [snapshot] = snapshots.as_slice() else { |
| 1582 | panic!("expected a completed skip, got {snapshots:?}"); |
| 1583 | }; |
| 1584 | assert!( |
| 1585 | matches!(snapshot.boundary, IntervalBoundary::FrameSkipped(skipped) |
| 1586 | if skipped.window_id == window_id && skipped.at == at && skipped.reason == reason) |
| 1587 | ); |
| 1588 | assert_eq!(snapshot.interval_end(), at); |
| 1589 | assert_eq!(snapshot.boundary.dirty_at(), None); |
| 1590 | assert_eq!(snapshot.occupancy(), Duration::from_millis(2)); |
| 1591 | |
| 1592 | writer.record_event(ForegroundEvent::Input(InputTiming { |
| 1593 | kind: "test", |
| 1594 | start: at, |
| 1595 | end: at + Duration::from_millis(1), |
| 1596 | caused_invalidation: false, |
| 1597 | })); |
| 1598 | writer.end_turn(at + Duration::from_millis(1)); |
| 1599 | assert!( |
| 1600 | !collector |
| 1601 | .collect_unseen() |
| 1602 | .entries |
| 1603 | .iter() |
| 1604 | .any(|entry| matches!(entry, ForegroundJournalEntry::Boundary(_))), |
| 1605 | "pending demand must still block idle boundaries" |
| 1606 | ); |
| 1607 | } |
| 1608 | } |
| 1609 | |
| 1610 | /// Platforms that request a frame every refresh skip most of them while |
| 1611 | /// idle. Those skips seal nothing and leave folded polls folded, so |
| 1612 | /// end-of-turn idle handling can still discard folded-only work. |
| 1613 | #[test] |
| 1614 | fn idle_refreshes_seal_nothing_and_keep_polls_folded() { |
| 1615 | let start = Instant::now(); |
| 1616 | let window_id = WindowId::from(1); |
| 1617 | let (mut writer, mut collector) = test_journal(ForegroundRunnableCounter::new()); |
| 1618 | for refresh in 0..3u32 { |
| 1619 | let at = start + Duration::from_millis(16) * refresh; |
| 1620 | writer.begin_turn(); |
| 1621 | writer.fold_small_poll(task_timing(at, at + Duration::from_micros(50))); |
| 1622 | writer.record_platform_signal(PlatformSignal { |
| 1623 | window_id, |
| 1624 | signal_at: Some(at), |
| 1625 | handled_at: at, |
| 1626 | source: crate::FrameRequestSource::NativeCallback, |
| 1627 | }); |
| 1628 | writer.record_frame_skipped(FrameSkipped { |
| 1629 | window_id, |
| 1630 | at, |
| 1631 | reason: FrameSkipReason::NoRenderNeeded, |
| 1632 | }); |
| 1633 | writer.end_turn(at + Duration::from_micros(60)); |
| 1634 | } |
| 1635 | |
| 1636 | let entries = collector.collect_unseen().entries; |
| 1637 | assert!( |
| 1638 | entries |
| 1639 | .iter() |
| 1640 | .all(|entry| matches!(entry, ForegroundJournalEntry::PlatformSignal(_))), |
| 1641 | "expected only platform signals, got {entries:?}" |
| 1642 | ); |
| 1643 | assert!(IntervalSealer::new(start).push_entries(entries).is_empty()); |
| 1644 | } |
| 1645 | |
| 1646 | #[test] |
| 1647 | fn reentrant_skip_does_not_seal_the_enclosing_draw() { |
| 1648 | let (journal, _guard) = install_test_foreground_journal(32, 4); |
| 1649 | let mut collector = journal.collector(); |
| 1650 | let start = Instant::now(); |
| 1651 | let window_id = WindowId::from(1); |
| 1652 | let mut sealer = IntervalSealer::new(start); |
| 1653 | record_platform_signal(PlatformSignal { |
| 1654 | window_id, |
| 1655 | signal_at: None, |
| 1656 | handled_at: start + Duration::from_millis(5), |
| 1657 | source: crate::FrameRequestSource::LocalSchedule, |
| 1658 | }); |
| 1659 | record_reentrant_frame_skipped(window_id, start + Duration::from_millis(6)); |
| 1660 | let entries = collector.collect_unseen().entries; |
| 1661 | assert!(matches!( |
| 1662 | entries.as_slice(), |
| 1663 | [ |
| 1664 | ForegroundJournalEntry::PlatformSignal(_), |
| 1665 | ForegroundJournalEntry::ReentrantFrameSkipped { |
| 1666 | window_id: skipped_window_id, |
| 1667 | at, |
| 1668 | } |
| 1669 | ] |
| 1670 | if *skipped_window_id == window_id && *at == start + Duration::from_millis(6) |
| 1671 | )); |
| 1672 | assert!(sealer.push_entries(entries).is_empty()); |
| 1673 | |
| 1674 | let frame = FrameTiming { |
| 1675 | window_id, |
| 1676 | dirty_at: Some(start), |
| 1677 | invalidations: 1, |
| 1678 | draw_start: start, |
| 1679 | draw_end: start + Duration::from_millis(20), |
| 1680 | }; |
| 1681 | record_draw(frame); |
| 1682 | record_present(presentation_timing(window_id, frame.draw_end), Some(frame)); |
| 1683 | let snapshots = sealer.push_entries(collector.collect_unseen().entries); |
| 1684 | let [snapshot] = snapshots.as_slice() else { |
| 1685 | panic!("expected the enclosing presentation, got {snapshots:?}"); |
| 1686 | }; |
| 1687 | assert!(matches!(snapshot.boundary, IntervalBoundary::Presented(_))); |
| 1688 | assert_eq!(snapshot.occupancy(), Duration::from_millis(20)); |
| 1689 | } |
| 1690 | |
| 1691 | #[gpui::test] |
| 1692 | fn wake_rechecks_native_visibility(cx: &mut crate::TestAppContext) { |
| 1693 | use crate::PlatformWindow as _; |
| 1694 | let handle = cx.add_window(|_, _| crate::Empty); |
| 1695 | let platform = cx.test_window(handle.into()); |
| 1696 | platform.on_visibility_change(Box::new(|_| {})); |
| 1697 | platform.simulate_visibility_change(WindowVisibility::Hidden); |
| 1698 | handle |
| 1699 | .update(cx, |_, window, _| assert!(window.is_visible())) |
| 1700 | .expect("window"); |
| 1701 | cx.update(|cx| { |
| 1702 | cx.system_wake_observers |
| 1703 | .clone() |
| 1704 | .retain(&(), |callback| callback(cx)) |
| 1705 | }); |
| 1706 | cx.run_until_parked(); |
| 1707 | handle |
| 1708 | .update(cx, |_, window, _| assert!(!window.is_visible())) |
| 1709 | .expect("window"); |
| 1710 | } |
| 1711 | |
| 1712 | #[test] |
| 1713 | fn power_interruption_drops_the_poll_before_small_poll_folding() { |
| 1714 | let (journal, _guard) = install_test_foreground_journal(32, 4); |
| 1715 | let mut collector = journal.collector(); |
| 1716 | let start = Instant::now(); |
| 1717 | begin_foreground_turn(); |
| 1718 | record_power_transition(PowerState::Suspended); |
| 1719 | record_power_transition(PowerState::Awake); |
| 1720 | assert!(power_interrupted_since(start)); |
| 1721 | record_task_poll(task_timing(start, start + Duration::from_micros(10))); |
| 1722 | assert!( |
| 1723 | collector |
| 1724 | .collect_unseen() |
| 1725 | .entries |
| 1726 | .iter() |
| 1727 | .all(|entry| matches!( |
| 1728 | entry, |
| 1729 | ForegroundJournalEntry::Boundary(IntervalBoundary::PowerTransition { .. }) |
| 1730 | )) |
| 1731 | ); |
| 1732 | with_journal(|writer| assert!(writer.small_polls.is_none())); |
| 1733 | begin_foreground_turn(); |
| 1734 | let start = Instant::now(); |
| 1735 | assert!(!power_interrupted_since(start)); |
| 1736 | record_task_poll(task_timing(start, start + TASK_POLL_FLOOR)); |
| 1737 | assert!( |
| 1738 | collector |
| 1739 | .collect_unseen() |
| 1740 | .entries |
| 1741 | .iter() |
| 1742 | .any(|entry| matches!( |
| 1743 | entry, |
| 1744 | ForegroundJournalEntry::Event(ForegroundEvent::TaskPoll(_)) |
| 1745 | )) |
| 1746 | ); |
| 1747 | } |
| 1748 | |
| 1749 | #[test] |
| 1750 | fn a_poll_spanning_an_unnotified_suspend_is_dropped() { |
| 1751 | let (journal, _guard) = install_test_foreground_journal(32, 4); |
| 1752 | let mut collector = journal.collector(); |
| 1753 | let window = WindowId::from(1); |
| 1754 | record_frame_pending(window, Instant::now()); |
| 1755 | begin_foreground_turn(); |
| 1756 | let start = Instant::now(); |
| 1757 | advance_test_suspended_time(Duration::from_secs(2)); |
| 1758 | record_task_poll(task_timing(start, Instant::now())); |
| 1759 | let entries = collector.collect_unseen().entries; |
| 1760 | assert!(entries.iter().any(|entry| matches!( |
| 1761 | entry, |
| 1762 | ForegroundJournalEntry::Boundary(IntervalBoundary::PowerTransition { .. }) |
| 1763 | ))); |
| 1764 | assert!(!entries.iter().any(|entry| matches!( |
| 1765 | entry, |
| 1766 | ForegroundJournalEntry::Event(ForegroundEvent::TaskPoll(_)) |
| 1767 | ))); |
| 1768 | with_journal(|writer| assert_eq!(writer.windows[&window].dirty_at, None)); |
| 1769 | |
| 1770 | begin_foreground_turn(); |
| 1771 | let start = Instant::now(); |
| 1772 | record_task_poll(task_timing(start, start + TASK_POLL_FLOOR)); |
| 1773 | let entries = collector.collect_unseen().entries; |
| 1774 | assert!(entries.iter().any(|entry| matches!( |
| 1775 | entry, |
| 1776 | ForegroundJournalEntry::Event(ForegroundEvent::TaskPoll(_)) |
| 1777 | ))); |
| 1778 | assert!(!entries.iter().any(|entry| matches!( |
| 1779 | entry, |
| 1780 | ForegroundJournalEntry::Boundary(IntervalBoundary::PowerTransition { .. }) |
| 1781 | ))); |
| 1782 | } |
| 1783 | |
| 1784 | #[test] |
| 1785 | fn suspend_clock_ignores_jitter_and_notified_suspends() { |
| 1786 | let (journal, _guard) = install_test_foreground_journal(32, 4); |
| 1787 | let mut collector = journal.collector(); |
| 1788 | record_power_transition(PowerState::Suspended); |
| 1789 | advance_test_suspended_time(Duration::from_secs(60)); |
| 1790 | record_power_transition(PowerState::Awake); |
| 1791 | advance_test_suspended_time(MIN_DETECTED_SUSPEND - Duration::from_millis(1)); |
| 1792 | begin_foreground_turn(); |
| 1793 | let start = Instant::now(); |
| 1794 | record_task_poll(task_timing(start, start + TASK_POLL_FLOOR)); |
| 1795 | let entries = collector.collect_unseen().entries; |
| 1796 | let power_transitions = entries |
| 1797 | .iter() |
| 1798 | .filter(|entry| { |
| 1799 | matches!( |
| 1800 | entry, |
| 1801 | ForegroundJournalEntry::Boundary(IntervalBoundary::PowerTransition { .. }) |
| 1802 | ) |
| 1803 | }) |
| 1804 | .count(); |
| 1805 | assert_eq!(power_transitions, 2, "only the two notifications"); |
| 1806 | assert!(entries.iter().any(|entry| matches!( |
| 1807 | entry, |
| 1808 | ForegroundJournalEntry::Event(ForegroundEvent::TaskPoll(_)) |
| 1809 | ))); |
| 1810 | } |
| 1811 | |
| 1812 | #[test] |
| 1813 | fn visibility_and_power_changes_clear_pending_frames() { |
| 1814 | let (mut writer, _) = test_journal(ForegroundRunnableCounter::new()); |
| 1815 | let start = Instant::now(); |
| 1816 | let first = WindowId::from(1); |
| 1817 | let second = WindowId::from(2); |
| 1818 | writer.set_visibility(first, WindowVisibility::Hidden, start); |
| 1819 | writer.record_frame_pending(first, start); |
| 1820 | assert!(!writer.has_unexpired_pending_frame(start)); |
| 1821 | writer.record_frame_pending(second, start); |
| 1822 | assert!(writer.has_unexpired_pending_frame(start)); |
| 1823 | writer.set_visibility(second, WindowVisibility::Hidden, start); |
| 1824 | assert!(!writer.has_unexpired_pending_frame(start)); |
| 1825 | writer.set_visibility(first, WindowVisibility::Visible, start); |
| 1826 | writer.record_frame_pending(first, start); |
| 1827 | assert!(writer.has_unexpired_pending_frame(start)); |
| 1828 | writer.power_transition(PowerState::Suspended, start); |
| 1829 | assert_eq!(writer.windows[&first].dirty_at, None); |
| 1830 | writer.record_frame_pending(first, start); |
| 1831 | assert!(!writer.has_unexpired_pending_frame(start)); |
| 1832 | // A repeated notification is not a transition. |
| 1833 | writer.power_transition(PowerState::Suspended, start + FRAME_DEADLINE); |
| 1834 | assert_eq!(writer.power_changed_at, Some(start)); |
| 1835 | writer.power_transition(PowerState::Awake, start); |
| 1836 | writer.record_frame_pending(first, start); |
| 1837 | assert!(writer.has_unexpired_pending_frame(start)); |
| 1838 | writer.record_present(presentation_timing(first, start + FRAME_DEADLINE), None); |
| 1839 | assert_eq!(writer.windows[&first].dirty_at, None); |
| 1840 | writer.record_window_closed(first, start); |
| 1841 | assert!(!writer.windows.contains_key(&first)); |
| 1842 | } |
| 1843 | |
| 1844 | #[test] |
| 1845 | fn draw_waits_for_its_presentation_boundary() { |
| 1846 | let start = Instant::now(); |
| 1847 | let input = InputTiming { |
| 1848 | kind: "test", |
| 1849 | start: start + Duration::from_millis(1), |
| 1850 | end: start + Duration::from_millis(2), |
| 1851 | caused_invalidation: true, |
| 1852 | }; |
| 1853 | let frame = FrameTiming { |
| 1854 | window_id: WindowId::from(1), |
| 1855 | dirty_at: Some(input.start), |
| 1856 | invalidations: 1, |
| 1857 | draw_start: start + Duration::from_millis(3), |
| 1858 | draw_end: start + Duration::from_millis(4), |
| 1859 | }; |
| 1860 | let presentation = PresentTiming { |
| 1861 | window_id: frame.window_id, |
| 1862 | present_start: start + Duration::from_millis(5), |
| 1863 | present_end: start + Duration::from_millis(6), |
| 1864 | animation_interval: None, |
| 1865 | }; |
| 1866 | let mut sealer = IntervalSealer::new(start); |
| 1867 | |
| 1868 | let snapshots = sealer.push_entries([ |
| 1869 | ForegroundJournalEntry::Event(ForegroundEvent::Input(input)), |
| 1870 | ForegroundJournalEntry::Event(ForegroundEvent::Draw(frame)), |
| 1871 | ]); |
| 1872 | assert!(snapshots.is_empty()); |
| 1873 | |
| 1874 | let snapshots = sealer.push_entries([ForegroundJournalEntry::Boundary( |
| 1875 | IntervalBoundary::Presented(PresentedFrame { |
| 1876 | frame, |
| 1877 | presentation, |
| 1878 | }), |
| 1879 | )]); |
| 1880 | let [snapshot] = snapshots.as_slice() else { |
| 1881 | panic!("expected one presentation-sealed snapshot, got {snapshots:?}"); |
| 1882 | }; |
| 1883 | assert_eq!(snapshot.interval_start, input.start); |
| 1884 | assert_eq!(snapshot.interval_end(), presentation.present_end); |
| 1885 | assert_eq!(snapshot.events.len(), 3); |
| 1886 | assert!(matches!( |
| 1887 | snapshot.events.last(), |
| 1888 | Some(ForegroundEvent::Present(timing)) |
| 1889 | if timing.present_duration() == Duration::from_millis(1) |
| 1890 | )); |
| 1891 | assert_eq!( |
| 1892 | match snapshot.boundary { |
| 1893 | IntervalBoundary::Presented(presented) => { |
| 1894 | presented.dirty_to_present_duration() |
| 1895 | } |
| 1896 | IntervalBoundary::FrameSkipped(_) |
| 1897 | | IntervalBoundary::Idle { .. } |
| 1898 | | IntervalBoundary::PowerTransition { .. } => None, |
| 1899 | }, |
| 1900 | Some(Duration::from_millis(5)) |
| 1901 | ); |
| 1902 | } |
| 1903 | |
| 1904 | #[test] |
| 1905 | fn outermost_turn_seals_no_frame_work_when_idle() { |
| 1906 | let start = Instant::now(); |
| 1907 | let counter = ForegroundRunnableCounter::new(); |
| 1908 | let (mut journal, mut collector) = test_journal(counter); |
| 1909 | let events = [ |
| 1910 | ForegroundEvent::Input(InputTiming { |
| 1911 | kind: "test", |
| 1912 | start, |
| 1913 | end: start + Duration::from_millis(1), |
| 1914 | caused_invalidation: false, |
| 1915 | }), |
| 1916 | ForegroundEvent::Action(ActionTiming { |
| 1917 | name: "test.action", |
| 1918 | start: start + Duration::from_millis(2), |
| 1919 | end: start + Duration::from_millis(3), |
| 1920 | }), |
| 1921 | ForegroundEvent::TaskPoll(task_timing( |
| 1922 | start + Duration::from_millis(4), |
| 1923 | start + Duration::from_millis(5), |
| 1924 | )), |
| 1925 | ]; |
| 1926 | |
| 1927 | for event in events { |
| 1928 | journal.begin_turn(); |
| 1929 | journal.record_event(event); |
| 1930 | journal.end_turn(event.end_time()); |
| 1931 | } |
| 1932 | |
| 1933 | let entries = collector.collect_unseen().entries; |
| 1934 | for event in events { |
| 1935 | assert!(entries.iter().any(|entry| { |
| 1936 | matches!( |
| 1937 | entry, |
| 1938 | ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { ended_at }) |
| 1939 | if *ended_at == event.end_time() |
| 1940 | ) |
| 1941 | })); |
| 1942 | } |
| 1943 | } |
| 1944 | |
| 1945 | #[test] |
| 1946 | fn nested_turns_only_seal_after_the_outermost_turn() { |
| 1947 | let start = Instant::now(); |
| 1948 | let (mut journal, mut collector) = test_journal(ForegroundRunnableCounter::new()); |
| 1949 | let action = ForegroundEvent::Action(ActionTiming { |
| 1950 | name: "test.action", |
| 1951 | start, |
| 1952 | end: start + Duration::from_millis(1), |
| 1953 | }); |
| 1954 | let input = ForegroundEvent::Input(InputTiming { |
| 1955 | kind: "test", |
| 1956 | start, |
| 1957 | end: start + Duration::from_millis(2), |
| 1958 | caused_invalidation: false, |
| 1959 | }); |
| 1960 | |
| 1961 | journal.begin_turn(); |
| 1962 | journal.begin_turn(); |
| 1963 | journal.record_event(action); |
| 1964 | journal.end_turn(action.end_time()); |
| 1965 | assert!(!has_boundary_at( |
| 1966 | &collector.collect_unseen().entries, |
| 1967 | action.end_time() |
| 1968 | )); |
| 1969 | |
| 1970 | journal.record_event(input); |
| 1971 | journal.end_turn(input.end_time()); |
| 1972 | assert!(collector.collect_unseen().entries.iter().any(|entry| { |
| 1973 | matches!( |
| 1974 | entry, |
| 1975 | ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { ended_at }) |
| 1976 | if *ended_at == input.end_time() |
| 1977 | ) |
| 1978 | })); |
| 1979 | } |
| 1980 | |
| 1981 | #[test] |
| 1982 | fn an_immediately_ready_runnable_prevents_an_idle_boundary_between_polls() { |
| 1983 | let start = Instant::now(); |
| 1984 | let counter = ForegroundRunnableCounter::new(); |
| 1985 | let (mut journal, mut collector) = test_journal(counter.clone()); |
| 1986 | counter.queued(); |
| 1987 | counter.queued(); |
| 1988 | |
| 1989 | let first = ForegroundEvent::TaskPoll(task_timing(start, start + Duration::from_millis(1))); |
| 1990 | journal.begin_turn(); |
| 1991 | journal.record_event(first); |
| 1992 | counter.finished(); |
| 1993 | journal.end_turn(first.end_time()); |
| 1994 | assert!(!has_boundary_at( |
| 1995 | &collector.collect_unseen().entries, |
| 1996 | first.end_time() |
| 1997 | )); |
| 1998 | |
| 1999 | let second = ForegroundEvent::TaskPoll(task_timing( |
| 2000 | start + Duration::from_millis(2), |
| 2001 | start + Duration::from_millis(3), |
| 2002 | )); |
| 2003 | journal.begin_turn(); |
| 2004 | journal.record_event(second); |
| 2005 | counter.finished(); |
| 2006 | journal.end_turn(second.end_time()); |
| 2007 | assert!(collector.collect_unseen().entries.iter().any(|entry| { |
| 2008 | matches!( |
| 2009 | entry, |
| 2010 | ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { ended_at }) |
| 2011 | if *ended_at == second.end_time() |
| 2012 | ) |
| 2013 | })); |
| 2014 | } |
| 2015 | |
| 2016 | #[test] |
| 2017 | fn a_pending_frame_prevents_idle_until_presentation() { |
| 2018 | let start = Instant::now(); |
| 2019 | let window_id = WindowId::from(0xD17A); |
| 2020 | let (mut journal, mut collector) = test_journal(ForegroundRunnableCounter::new()); |
| 2021 | journal.record_frame_pending(window_id, start); |
| 2022 | journal.begin_turn(); |
| 2023 | journal.record_event(ForegroundEvent::Input(InputTiming { |
| 2024 | kind: "test", |
| 2025 | start, |
| 2026 | end: start + Duration::from_millis(1), |
| 2027 | caused_invalidation: true, |
| 2028 | })); |
| 2029 | let input_end = start + Duration::from_millis(1); |
| 2030 | journal.end_turn(input_end); |
| 2031 | assert!(!has_boundary_at( |
| 2032 | &collector.collect_unseen().entries, |
| 2033 | input_end |
| 2034 | )); |
| 2035 | |
| 2036 | let frame = frame_timing(window_id, start, start + Duration::from_millis(2)); |
| 2037 | let presentation = presentation_timing(window_id, start + Duration::from_millis(3)); |
| 2038 | journal.record_present(presentation, Some(frame)); |
| 2039 | assert!(collector.collect_unseen().entries.iter().any(|entry| { |
| 2040 | matches!( |
| 2041 | entry, |
| 2042 | ForegroundJournalEntry::Boundary(IntervalBoundary::Presented(presented)) |
| 2043 | if presented.frame.window_id == window_id |
| 2044 | ) |
| 2045 | })); |
| 2046 | } |
| 2047 | |
| 2048 | #[test] |
| 2049 | fn a_present_without_a_draw_clears_the_window_pending_state() { |
| 2050 | let start = Instant::now(); |
| 2051 | let presented_at = start + Duration::from_millis(1); |
| 2052 | let window_id = WindowId::from(0xD17B); |
| 2053 | let (mut journal, mut collector) = test_journal(ForegroundRunnableCounter::new()); |
| 2054 | journal.record_frame_pending(window_id, start); |
| 2055 | journal.begin_turn(); |
| 2056 | journal.record_present(presentation_timing(window_id, presented_at), None); |
| 2057 | journal.end_turn(presented_at); |
| 2058 | |
| 2059 | let entries = collector.collect_unseen().entries; |
| 2060 | assert!(entries.iter().any(|entry| { |
| 2061 | matches!( |
| 2062 | entry, |
| 2063 | ForegroundJournalEntry::Event(ForegroundEvent::Present(timing)) |
| 2064 | if timing.window_id == window_id |
| 2065 | ) |
| 2066 | })); |
| 2067 | assert!(has_boundary_at(&entries, presented_at)); |
| 2068 | } |
| 2069 | |
| 2070 | /// A frame that outlives [`FRAME_DEADLINE`] no longer seals an interval |
| 2071 | /// of its own: the work that starved it and its eventual presentation |
| 2072 | /// stay in one interval, preserving the dirty-to-present association. |
| 2073 | #[test] |
| 2074 | fn a_presentation_after_the_deadline_seals_the_whole_interval() { |
| 2075 | let start = Instant::now(); |
| 2076 | let window_id = WindowId::from(0xDEA1); |
| 2077 | let presented_at = start + FRAME_DEADLINE + Duration::from_millis(250); |
| 2078 | let mut sealer = IntervalSealer::new(start); |
| 2079 | let snapshots = sealer.push_entries([ |
| 2080 | pending_frame(window_id, start), |
| 2081 | input_entry(start, start + Duration::from_millis(20)), |
| 2082 | ForegroundJournalEntry::Boundary(presented_boundary(window_id, start, presented_at)), |
| 2083 | ]); |
| 2084 | let [snapshot] = snapshots.as_slice() else { |
| 2085 | panic!("expected one presented snapshot, got {snapshots:?}"); |
| 2086 | }; |
| 2087 | assert!(matches!( |
| 2088 | snapshot.boundary, |
| 2089 | IntervalBoundary::Presented(presented) |
| 2090 | if presented.frame.window_id == window_id |
| 2091 | && presented.dirty_to_present_duration() |
| 2092 | == Some(presented_at.duration_since(start)) |
| 2093 | )); |
| 2094 | assert_eq!(snapshot.interval_end(), presented_at); |
| 2095 | assert_eq!(snapshot.events.len(), 2); |
| 2096 | } |
| 2097 | |
| 2098 | /// Frame expiry unblocks idle boundaries on the writer side: retained |
| 2099 | /// work after the deadline seals at its turn's end even though the window |
| 2100 | /// never presented. |
| 2101 | #[test] |
| 2102 | fn an_expired_frame_no_longer_blocks_idle_boundaries() { |
| 2103 | let start = Instant::now(); |
| 2104 | let window_id = WindowId::from(0xDEA2); |
| 2105 | let (mut journal, mut collector) = test_journal(ForegroundRunnableCounter::new()); |
| 2106 | journal.record_frame_pending(window_id, start); |
| 2107 | |
| 2108 | let blocked_end = start + Duration::from_millis(20); |
| 2109 | journal.begin_turn(); |
| 2110 | journal.record_event(ForegroundEvent::Input(InputTiming { |
| 2111 | kind: "test", |
| 2112 | start, |
| 2113 | end: blocked_end, |
| 2114 | caused_invalidation: true, |
| 2115 | })); |
| 2116 | journal.end_turn(blocked_end); |
| 2117 | assert!(!has_boundary_at( |
| 2118 | &collector.collect_unseen().entries, |
| 2119 | blocked_end |
| 2120 | )); |
| 2121 | |
| 2122 | let unblocked_end = start + FRAME_DEADLINE + Duration::from_millis(1); |
| 2123 | journal.begin_turn(); |
| 2124 | journal.record_event(ForegroundEvent::Input(InputTiming { |
| 2125 | kind: "test", |
| 2126 | start: start + FRAME_DEADLINE, |
| 2127 | end: unblocked_end, |
| 2128 | caused_invalidation: false, |
| 2129 | })); |
| 2130 | journal.end_turn(unblocked_end); |
| 2131 | assert!(has_boundary_at( |
| 2132 | &collector.collect_unseen().entries, |
| 2133 | unblocked_end |
| 2134 | )); |
| 2135 | } |
| 2136 | |
| 2137 | /// Closing a window clears its pending frame, so idle boundaries resume |
| 2138 | /// without waiting for the deadline. |
| 2139 | #[test] |
| 2140 | fn closing_a_window_unblocks_idle_boundaries() { |
| 2141 | let start = Instant::now(); |
| 2142 | let window_id = WindowId::from(0xDEA7); |
| 2143 | let (mut journal, mut collector) = test_journal(ForegroundRunnableCounter::new()); |
| 2144 | journal.record_frame_pending(window_id, start); |
| 2145 | journal.record_window_closed(window_id, start + Duration::from_millis(1)); |
| 2146 | |
| 2147 | let event_end = start + Duration::from_millis(2); |
| 2148 | journal.begin_turn(); |
| 2149 | journal.record_event(ForegroundEvent::Input(InputTiming { |
| 2150 | kind: "test", |
| 2151 | start: start + Duration::from_millis(1), |
| 2152 | end: event_end, |
| 2153 | caused_invalidation: false, |
| 2154 | })); |
| 2155 | journal.end_turn(event_end); |
| 2156 | assert!(has_boundary_at( |
| 2157 | &collector.collect_unseen().entries, |
| 2158 | event_end |
| 2159 | )); |
| 2160 | } |
| 2161 | |
| 2162 | /// One window presenting must not unblock idle boundaries while another |
| 2163 | /// window's unexpired frame is still pending. |
| 2164 | #[test] |
| 2165 | fn presenting_one_window_does_not_clear_another_pending_window() { |
| 2166 | let start = Instant::now(); |
| 2167 | let first_window = WindowId::from(0xDEA5); |
| 2168 | let second_window = WindowId::from(0xDEA6); |
| 2169 | let (mut journal, mut collector) = test_journal(ForegroundRunnableCounter::new()); |
| 2170 | journal.record_frame_pending(first_window, start); |
| 2171 | journal.record_frame_pending(second_window, start + Duration::from_millis(100)); |
| 2172 | journal.record_present( |
| 2173 | presentation_timing(first_window, start + Duration::from_millis(500)), |
| 2174 | Some(frame_timing( |
| 2175 | first_window, |
| 2176 | start, |
| 2177 | start + Duration::from_millis(500), |
| 2178 | )), |
| 2179 | ); |
| 2180 | |
| 2181 | let event_end = start + Duration::from_millis(620); |
| 2182 | journal.begin_turn(); |
| 2183 | journal.record_event(ForegroundEvent::Input(InputTiming { |
| 2184 | kind: "test", |
| 2185 | start: start + Duration::from_millis(600), |
| 2186 | end: event_end, |
| 2187 | caused_invalidation: false, |
| 2188 | })); |
| 2189 | journal.end_turn(event_end); |
| 2190 | |
| 2191 | let entries = collector.collect_unseen().entries; |
| 2192 | assert!(entries.iter().any(|entry| { |
| 2193 | matches!( |
| 2194 | entry, |
| 2195 | ForegroundJournalEntry::Boundary(IntervalBoundary::Presented(presented)) |
| 2196 | if presented.frame.window_id == first_window |
| 2197 | ) |
| 2198 | })); |
| 2199 | assert!(!has_boundary_at(&entries, event_end)); |
| 2200 | } |
| 2201 | |
| 2202 | #[test] |
| 2203 | fn small_polls_are_flushed_immediately_before_a_retained_event() { |
| 2204 | let start = Instant::now(); |
| 2205 | let first = task_timing( |
| 2206 | start + Duration::from_millis(1), |
| 2207 | start + Duration::from_millis(1) + Duration::from_micros(20), |
| 2208 | ); |
| 2209 | let second = task_timing( |
| 2210 | start + Duration::from_millis(3), |
| 2211 | start + Duration::from_millis(3) + Duration::from_micros(30), |
| 2212 | ); |
| 2213 | let input = InputTiming { |
| 2214 | kind: "test", |
| 2215 | start: start + Duration::from_millis(5), |
| 2216 | end: start + Duration::from_millis(6), |
| 2217 | caused_invalidation: false, |
| 2218 | }; |
| 2219 | let (mut journal, mut collector) = test_journal(ForegroundRunnableCounter::new()); |
| 2220 | |
| 2221 | journal.fold_small_poll(first); |
| 2222 | journal.fold_small_poll(second); |
| 2223 | journal.record_event(ForegroundEvent::Input(input)); |
| 2224 | |
| 2225 | let drained = collector.collect_unseen(); |
| 2226 | let input_index = drained |
| 2227 | .entries |
| 2228 | .iter() |
| 2229 | .position(|entry| { |
| 2230 | matches!( |
| 2231 | entry, |
| 2232 | ForegroundJournalEntry::Event(ForegroundEvent::Input(timing)) |
| 2233 | if timing.start == input.start |
| 2234 | ) |
| 2235 | }) |
| 2236 | .expect("input event should be retained"); |
| 2237 | let Some(ForegroundJournalEntry::Event(ForegroundEvent::SmallPolls(flush))) = input_index |
| 2238 | .checked_sub(1) |
| 2239 | .and_then(|index| drained.entries.get(index)) |
| 2240 | else { |
| 2241 | panic!("small-poll summary should immediately precede the input event"); |
| 2242 | }; |
| 2243 | assert_eq!(flush.summary.count, 2); |
| 2244 | assert_eq!(flush.summary.total, Duration::from_micros(50)); |
| 2245 | assert_eq!(flush.since, first.start); |
| 2246 | assert_eq!(flush.until, second.end.0); |
| 2247 | } |
| 2248 | |
| 2249 | #[test] |
| 2250 | fn small_polls_are_flushed_before_frame_state_changes() { |
| 2251 | let start = Instant::now(); |
| 2252 | let window_id = WindowId::from(0xDEA9); |
| 2253 | let poll = task_timing(start, start + Duration::from_micros(50)); |
| 2254 | let (mut journal, mut collector) = test_journal(ForegroundRunnableCounter::new()); |
| 2255 | journal.fold_small_poll(poll); |
| 2256 | journal.record_frame_pending(window_id, poll.end.0); |
| 2257 | |
| 2258 | let entries = collector.collect_unseen().entries; |
| 2259 | let pending_index = entries |
| 2260 | .iter() |
| 2261 | .position(|entry| { |
| 2262 | matches!( |
| 2263 | entry, |
| 2264 | ForegroundJournalEntry::FrameState(FrameStateChange::Pending { |
| 2265 | window_id: pending_window, |
| 2266 | .. |
| 2267 | }) if *pending_window == window_id |
| 2268 | ) |
| 2269 | }) |
| 2270 | .expect("pending frame should be retained"); |
| 2271 | assert!(matches!( |
| 2272 | pending_index |
| 2273 | .checked_sub(1) |
| 2274 | .and_then(|index| entries.get(index)), |
| 2275 | Some(ForegroundJournalEntry::Event(ForegroundEvent::SmallPolls(flush))) |
| 2276 | if flush.since == poll.start && flush.until == poll.end.0 |
| 2277 | )); |
| 2278 | } |
| 2279 | |
| 2280 | /// Sporadic wake-ups (a tiny folded poll after which the foreground goes |
| 2281 | /// idle, repeatedly) must write nothing to the ring and must not accumulate |
| 2282 | /// toward a later retained interval. |
| 2283 | #[test] |
| 2284 | fn sparse_small_polls_are_discarded_when_the_foreground_returns_to_idle() { |
| 2285 | let start = Instant::now(); |
| 2286 | let (mut journal, mut collector) = test_journal(ForegroundRunnableCounter::new()); |
| 2287 | let mut tiny_wake = |ended_at: Instant| { |
| 2288 | journal.begin_turn(); |
| 2289 | journal.fold_small_poll(task_timing(ended_at - Duration::from_micros(50), ended_at)); |
| 2290 | journal.end_turn(ended_at); |
| 2291 | }; |
| 2292 | |
| 2293 | for second in 1..=160 { |
| 2294 | tiny_wake(start + Duration::from_secs(second)); |
| 2295 | } |
| 2296 | let quiet = collector.collect_unseen().entries; |
| 2297 | assert!(quiet.is_empty()); |
| 2298 | |
| 2299 | // A later retained event seals normally without inheriting the earlier |
| 2300 | // folded-only wake-ups. |
| 2301 | let retained = ForegroundEvent::TaskPoll(task_timing( |
| 2302 | start + Duration::from_secs(161), |
| 2303 | start + Duration::from_secs(161) + Duration::from_millis(1), |
| 2304 | )); |
| 2305 | journal.begin_turn(); |
| 2306 | journal.record_event(retained); |
| 2307 | journal.end_turn(retained.end_time()); |
| 2308 | let entries = collector.collect_unseen().entries; |
| 2309 | assert!(has_boundary_at(&entries, retained.end_time())); |
| 2310 | assert!(!entries.iter().any(|entry| matches!( |
| 2311 | entry, |
| 2312 | ForegroundJournalEntry::Event(ForegroundEvent::SmallPolls(_)) |
| 2313 | ))); |
| 2314 | } |
| 2315 | |
| 2316 | #[test] |
| 2317 | fn note_lost_is_reported_on_the_next_snapshot_only() { |
| 2318 | let start = Instant::now(); |
| 2319 | let mut sealer = IntervalSealer::new(start); |
| 2320 | sealer.note_lost(7); |
| 2321 | |
| 2322 | let snapshots = sealer.push_entries([ |
| 2323 | input_entry(start, start + Duration::from_millis(1)), |
| 2324 | ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { |
| 2325 | ended_at: start + Duration::from_millis(1), |
| 2326 | }), |
| 2327 | input_entry( |
| 2328 | start + Duration::from_millis(2), |
| 2329 | start + Duration::from_millis(3), |
| 2330 | ), |
| 2331 | ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { |
| 2332 | ended_at: start + Duration::from_millis(3), |
| 2333 | }), |
| 2334 | ]); |
| 2335 | |
| 2336 | assert_eq!(snapshots.len(), 2); |
| 2337 | assert_eq!(snapshots[0].dropped_events, 7); |
| 2338 | assert_eq!(snapshots[1].dropped_events, 0); |
| 2339 | } |
| 2340 | |
| 2341 | /// Ring losses must be able to surface even when every retained entry was |
| 2342 | /// among the losses: a loss-only interval still seals at the next |
| 2343 | /// boundary rather than sliding away as empty. |
| 2344 | #[test] |
| 2345 | fn losses_alone_seal_a_snapshot_at_the_next_boundary() { |
| 2346 | let start = Instant::now(); |
| 2347 | let mut sealer = IntervalSealer::new(start); |
| 2348 | sealer.note_lost(3); |
| 2349 | |
| 2350 | let snapshots = |
| 2351 | sealer.push_entries([ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { |
| 2352 | ended_at: start + Duration::from_millis(1), |
| 2353 | })]); |
| 2354 | |
| 2355 | assert_eq!(snapshots.len(), 1); |
| 2356 | assert_eq!(snapshots[0].dropped_events, 3); |
| 2357 | assert!(snapshots[0].events.is_empty()); |
| 2358 | } |
| 2359 | |
| 2360 | #[test] |
| 2361 | fn interval_event_cap_counts_overflowing_events() { |
| 2362 | let start = Instant::now(); |
| 2363 | let mut sealer = IntervalSealer::new(start); |
| 2364 | let overflow = 5; |
| 2365 | let mut entries: Vec<ForegroundJournalEntry> = (0..(MAX_INTERVAL_EVENTS + overflow) as u64) |
| 2366 | .map(|i| { |
| 2367 | input_entry( |
| 2368 | start + Duration::from_micros(i), |
| 2369 | start + Duration::from_micros(i + 1), |
| 2370 | ) |
| 2371 | }) |
| 2372 | .collect(); |
| 2373 | entries.push(ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { |
| 2374 | ended_at: start + Duration::from_micros((MAX_INTERVAL_EVENTS + overflow) as u64 + 1), |
| 2375 | })); |
| 2376 | |
| 2377 | let snapshots = sealer.push_entries(entries); |
| 2378 | |
| 2379 | assert_eq!(snapshots.len(), 1); |
| 2380 | assert_eq!(snapshots[0].events.len(), MAX_INTERVAL_EVENTS); |
| 2381 | assert_eq!(snapshots[0].dropped_events, overflow as u64); |
| 2382 | } |
| 2383 | |
| 2384 | #[test] |
| 2385 | fn collect_unseen_returns_each_entry_once_in_order() { |
| 2386 | let start = Instant::now(); |
| 2387 | let (journal, mut publisher) = ForegroundJournal::new(32, 4); |
| 2388 | let mut collector = journal.collector(); |
| 2389 | let timestamps: Vec<Instant> = (0..19) |
| 2390 | .map(|i| start + Duration::from_micros(i as u64 + 1)) |
| 2391 | .collect(); |
| 2392 | publisher.publish(timestamps.iter().map(|&at| input_entry(at, at))); |
| 2393 | |
| 2394 | let ours = |entries: &[ForegroundJournalEntry]| -> Vec<Instant> { |
| 2395 | entries |
| 2396 | .iter() |
| 2397 | .filter_map(|entry| match entry { |
| 2398 | ForegroundJournalEntry::Event(ForegroundEvent::Input(timing)) |
| 2399 | if timestamps.contains(&timing.end) => |
| 2400 | { |
| 2401 | Some(timing.end) |
| 2402 | } |
| 2403 | _ => None, |
| 2404 | }) |
| 2405 | .collect() |
| 2406 | }; |
| 2407 | |
| 2408 | let drained = collector.collect_unseen(); |
| 2409 | assert_eq!(ours(&drained.entries), timestamps); |
| 2410 | |
| 2411 | // The cursor advanced past everything: a second drain sees none of |
| 2412 | // our entries again. |
| 2413 | let drained = collector.collect_unseen(); |
| 2414 | assert!(ours(&drained.entries).is_empty()); |
| 2415 | } |
| 2416 | |
| 2417 | #[test] |
| 2418 | fn concurrent_collection_preserves_the_complete_logical_sequence() { |
| 2419 | const ENTRY_COUNT: u64 = 20_000; |
| 2420 | |
| 2421 | let origin = Instant::now(); |
| 2422 | let (journal, mut publisher) = ForegroundJournal::new(8, 4); |
| 2423 | let mut collector = journal.collector(); |
| 2424 | let done = Arc::new(std::sync::atomic::AtomicBool::new(false)); |
| 2425 | let collector_done = Arc::clone(&done); |
| 2426 | let collector_task = std::thread::spawn(move || { |
| 2427 | let mut observed = Vec::new(); |
| 2428 | loop { |
| 2429 | let drained = collector.collect_unseen(); |
| 2430 | observed.extend(normalize_ring_drain(origin, drained.entries)); |
| 2431 | if collector_done.load(Ordering::Acquire) { |
| 2432 | let drained = collector.collect_unseen(); |
| 2433 | observed.extend(normalize_ring_drain(origin, drained.entries)); |
| 2434 | return (collector, observed); |
| 2435 | } |
| 2436 | std::thread::yield_now(); |
| 2437 | } |
| 2438 | }); |
| 2439 | |
| 2440 | for sequence in 0..ENTRY_COUNT { |
| 2441 | publisher.publish([ring_entry(origin, sequence)]); |
| 2442 | } |
| 2443 | done.store(true, Ordering::Release); |
| 2444 | |
| 2445 | let (mut collector, mut observed) = collector_task |
| 2446 | .join() |
| 2447 | .expect("collector thread should not panic"); |
| 2448 | publisher.flush_pending(); |
| 2449 | observed.extend(normalize_ring_drain( |
| 2450 | origin, |
| 2451 | collector.collect_unseen().entries, |
| 2452 | )); |
| 2453 | |
| 2454 | let mut expected_sequence = 0; |
| 2455 | for entry in observed { |
| 2456 | match entry { |
| 2457 | ModelDrainEntry::Entry(sequence) => { |
| 2458 | assert_eq!(sequence, expected_sequence); |
| 2459 | expected_sequence += 1; |
| 2460 | } |
| 2461 | ModelDrainEntry::Discontinuity(lost) => expected_sequence += lost, |
| 2462 | } |
| 2463 | } |
| 2464 | assert_eq!(expected_sequence, ENTRY_COUNT); |
| 2465 | assert_eq!( |
| 2466 | publisher.ring.finalized.load(Ordering::Acquire), |
| 2467 | ENTRY_COUNT |
| 2468 | ); |
| 2469 | } |
| 2470 | |
| 2471 | #[derive(Clone, Debug)] |
| 2472 | enum RingOperation { |
| 2473 | Publish, |
| 2474 | Collect(u8), |
| 2475 | NewCollector, |
| 2476 | Pin(u8), |
| 2477 | Unpin(u8), |
| 2478 | } |
| 2479 | |
| 2480 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 2481 | enum ModelDrainEntry { |
| 2482 | Entry(u64), |
| 2483 | Discontinuity(u64), |
| 2484 | } |
| 2485 | |
| 2486 | struct ModelRing { |
| 2487 | capacity: usize, |
| 2488 | pending_capacity: usize, |
| 2489 | next_sequence: u64, |
| 2490 | finalized: u64, |
| 2491 | offered: u64, |
| 2492 | slots: Vec<Option<(u64, u64)>>, |
| 2493 | pinned: Vec<bool>, |
| 2494 | pending: VecDeque<(u64, u64)>, |
| 2495 | dropped_after_pending: u64, |
| 2496 | } |
| 2497 | |
| 2498 | impl ModelRing { |
| 2499 | fn new(capacity: usize, pending_capacity: usize) -> Self { |
| 2500 | Self { |
| 2501 | capacity, |
| 2502 | pending_capacity, |
| 2503 | next_sequence: 0, |
| 2504 | finalized: 0, |
| 2505 | offered: 0, |
| 2506 | slots: vec![None; capacity], |
| 2507 | pinned: vec![false; capacity], |
| 2508 | pending: VecDeque::new(), |
| 2509 | dropped_after_pending: 0, |
| 2510 | } |
| 2511 | } |
| 2512 | |
| 2513 | fn publish(&mut self) { |
| 2514 | self.flush_pending(); |
| 2515 | let sequence = self.next_sequence; |
| 2516 | self.next_sequence += 1; |
| 2517 | self.offered = self.next_sequence; |
| 2518 | |
| 2519 | if !self.pending.is_empty() || self.dropped_after_pending > 0 { |
| 2520 | if self.dropped_after_pending == 0 && self.pending.len() < self.pending_capacity { |
| 2521 | self.pending.push_back((sequence, sequence)); |
| 2522 | } else { |
| 2523 | self.dropped_after_pending += 1; |
| 2524 | } |
| 2525 | } else { |
| 2526 | let index = sequence as usize % self.capacity; |
| 2527 | if self.pinned[index] { |
| 2528 | if self.pending_capacity > 0 { |
| 2529 | self.pending.push_back((sequence, sequence)); |
| 2530 | } else { |
| 2531 | self.dropped_after_pending = 1; |
| 2532 | } |
| 2533 | } else { |
| 2534 | self.slots[index] = Some((sequence, sequence)); |
| 2535 | self.finalized = sequence + 1; |
| 2536 | } |
| 2537 | } |
| 2538 | self.flush_pending(); |
| 2539 | } |
| 2540 | |
| 2541 | fn flush_pending(&mut self) { |
| 2542 | while let Some(&(sequence, value)) = self.pending.front() { |
| 2543 | let index = sequence as usize % self.capacity; |
| 2544 | if self.pinned[index] { |
| 2545 | return; |
| 2546 | } |
| 2547 | self.slots[index] = Some((sequence, value)); |
| 2548 | self.pending.pop_front(); |
| 2549 | self.finalized = sequence + 1; |
| 2550 | } |
| 2551 | |
| 2552 | if self.dropped_after_pending > 0 { |
| 2553 | self.finalized = self.next_sequence; |
| 2554 | self.dropped_after_pending = 0; |
| 2555 | } |
| 2556 | } |
| 2557 | |
| 2558 | fn collect(&self, cursor: &mut u64) -> (Vec<ModelDrainEntry>, u64) { |
| 2559 | let end = self.finalized; |
| 2560 | if *cursor >= end { |
| 2561 | return (Vec::new(), 0); |
| 2562 | } |
| 2563 | |
| 2564 | let retained_start = end.saturating_sub(self.capacity as u64); |
| 2565 | let mut lost = retained_start.saturating_sub(*cursor); |
| 2566 | *cursor = (*cursor).max(retained_start); |
| 2567 | let mut entries = Vec::new(); |
| 2568 | if lost > 0 { |
| 2569 | entries.push(ModelDrainEntry::Discontinuity(lost)); |
| 2570 | } |
| 2571 | while *cursor < end { |
| 2572 | let index = *cursor as usize % self.capacity; |
| 2573 | match self.slots[index] { |
| 2574 | Some((sequence, value)) if sequence == *cursor => { |
| 2575 | entries.push(ModelDrainEntry::Entry(value)); |
| 2576 | } |
| 2577 | _ => { |
| 2578 | lost += 1; |
| 2579 | match entries.last_mut() { |
| 2580 | Some(ModelDrainEntry::Discontinuity(lost)) => *lost += 1, |
| 2581 | _ => entries.push(ModelDrainEntry::Discontinuity(1)), |
| 2582 | } |
| 2583 | } |
| 2584 | } |
| 2585 | *cursor += 1; |
| 2586 | } |
| 2587 | (entries, lost) |
| 2588 | } |
| 2589 | } |
| 2590 | |
| 2591 | fn ring_entry(origin: Instant, sequence: u64) -> ForegroundJournalEntry { |
| 2592 | let at = origin + Duration::from_micros(sequence); |
| 2593 | input_entry(at, at) |
| 2594 | } |
| 2595 | |
| 2596 | fn normalize_ring_drain( |
| 2597 | origin: Instant, |
| 2598 | entries: Vec<ForegroundJournalEntry>, |
| 2599 | ) -> Vec<ModelDrainEntry> { |
| 2600 | entries |
| 2601 | .into_iter() |
| 2602 | .map(|entry| match entry { |
| 2603 | ForegroundJournalEntry::Event(ForegroundEvent::Input(timing)) => { |
| 2604 | ModelDrainEntry::Entry(timing.start.duration_since(origin).as_micros() as u64) |
| 2605 | } |
| 2606 | ForegroundJournalEntry::Discontinuity { lost } => { |
| 2607 | ModelDrainEntry::Discontinuity(lost) |
| 2608 | } |
| 2609 | other => panic!("ring property observed an unexpected entry: {other:?}"), |
| 2610 | }) |
| 2611 | .collect() |
| 2612 | } |
| 2613 | |
| 2614 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 2615 | struct NormalizedEvent { |
| 2616 | kind: u8, |
| 2617 | start: u64, |
| 2618 | end: u64, |
| 2619 | } |
| 2620 | |
| 2621 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 2622 | struct NormalizedSmallPolls { |
| 2623 | count: u64, |
| 2624 | total_micros: u64, |
| 2625 | since: u64, |
| 2626 | until: u64, |
| 2627 | } |
| 2628 | |
| 2629 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 2630 | struct NormalizedSnapshot { |
| 2631 | interval_start: u64, |
| 2632 | boundary_kind: u8, |
| 2633 | interval_end: u64, |
| 2634 | events: Vec<NormalizedEvent>, |
| 2635 | small_polls: Vec<NormalizedSmallPolls>, |
| 2636 | dropped_events: u64, |
| 2637 | journal_discontinuous: bool, |
| 2638 | } |
| 2639 | |
| 2640 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 2641 | struct NormalizedSealerTail { |
| 2642 | interval_start: u64, |
| 2643 | events: Vec<NormalizedEvent>, |
| 2644 | small_polls: Vec<NormalizedSmallPolls>, |
| 2645 | dropped_events: u64, |
| 2646 | journal_discontinuous: bool, |
| 2647 | } |
| 2648 | |
| 2649 | fn completion_order_entries( |
| 2650 | origin: Instant, |
| 2651 | specifications: &[(u8, u8, u8)], |
| 2652 | ) -> Vec<ForegroundJournalEntry> { |
| 2653 | let mut completed_at_micros = 1u64; |
| 2654 | specifications |
| 2655 | .iter() |
| 2656 | .map(|(advance, span, kind)| { |
| 2657 | completed_at_micros += u64::from(*advance) + 1; |
| 2658 | let started_at_micros = completed_at_micros.saturating_sub(u64::from(*span)); |
| 2659 | let start = origin + Duration::from_micros(started_at_micros); |
| 2660 | let end = origin + Duration::from_micros(completed_at_micros); |
| 2661 | match kind % 7 { |
| 2662 | 0 => input_entry(start, end), |
| 2663 | 1 => ForegroundJournalEntry::Event(ForegroundEvent::Action(ActionTiming { |
| 2664 | name: "test.action", |
| 2665 | start, |
| 2666 | end, |
| 2667 | })), |
| 2668 | 2 => ForegroundJournalEntry::Event(ForegroundEvent::TaskPoll(task_timing( |
| 2669 | start, end, |
| 2670 | ))), |
| 2671 | 3 => { |
| 2672 | ForegroundJournalEntry::Event(ForegroundEvent::SmallPolls(SmallPollFlush { |
| 2673 | summary: PollSummary { |
| 2674 | count: u64::from(*span % 5) + 1, |
| 2675 | total: Duration::from_micros(u64::from(*span)), |
| 2676 | }, |
| 2677 | since: start, |
| 2678 | until: end, |
| 2679 | })) |
| 2680 | } |
| 2681 | 4 => pending_frame(WindowId::from(completed_at_micros), start), |
| 2682 | 5 => ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { ended_at: end }), |
| 2683 | _ => ForegroundJournalEntry::Boundary(presented_boundary( |
| 2684 | WindowId::from(completed_at_micros), |
| 2685 | start, |
| 2686 | end, |
| 2687 | )), |
| 2688 | } |
| 2689 | }) |
| 2690 | .collect() |
| 2691 | } |
| 2692 | |
| 2693 | fn normalize_event(origin: Instant, event: ForegroundEvent) -> NormalizedEvent { |
| 2694 | let kind = match event { |
| 2695 | ForegroundEvent::TaskPoll(_) => 0, |
| 2696 | ForegroundEvent::Action(_) => 1, |
| 2697 | ForegroundEvent::Input(_) => 2, |
| 2698 | ForegroundEvent::Draw(_) => 3, |
| 2699 | ForegroundEvent::Present(_) => 4, |
| 2700 | ForegroundEvent::SmallPolls(_) => 5, |
| 2701 | }; |
| 2702 | NormalizedEvent { |
| 2703 | kind, |
| 2704 | start: event.start_time().duration_since(origin).as_micros() as u64, |
| 2705 | end: event.end_time().duration_since(origin).as_micros() as u64, |
| 2706 | } |
| 2707 | } |
| 2708 | |
| 2709 | fn normalize_small_polls(origin: Instant, flush: SmallPollFlush) -> NormalizedSmallPolls { |
| 2710 | NormalizedSmallPolls { |
| 2711 | count: flush.summary.count, |
| 2712 | total_micros: flush.summary.total.as_micros() as u64, |
| 2713 | since: flush.since.duration_since(origin).as_micros() as u64, |
| 2714 | until: flush.until.duration_since(origin).as_micros() as u64, |
| 2715 | } |
| 2716 | } |
| 2717 | |
| 2718 | fn normalize_snapshot(origin: Instant, snapshot: &FrameSnapshot) -> NormalizedSnapshot { |
| 2719 | NormalizedSnapshot { |
| 2720 | interval_start: snapshot.interval_start.duration_since(origin).as_micros() as u64, |
| 2721 | boundary_kind: match snapshot.boundary { |
| 2722 | IntervalBoundary::Idle { .. } => 0, |
| 2723 | IntervalBoundary::Presented(_) => 1, |
| 2724 | IntervalBoundary::PowerTransition { .. } => 2, |
| 2725 | IntervalBoundary::FrameSkipped(_) => 3, |
| 2726 | }, |
| 2727 | interval_end: snapshot.interval_end().duration_since(origin).as_micros() as u64, |
| 2728 | events: snapshot |
| 2729 | .events |
| 2730 | .iter() |
| 2731 | .copied() |
| 2732 | .map(|event| normalize_event(origin, event)) |
| 2733 | .collect(), |
| 2734 | small_polls: snapshot |
| 2735 | .small_polls |
| 2736 | .iter() |
| 2737 | .copied() |
| 2738 | .map(|flush| normalize_small_polls(origin, flush)) |
| 2739 | .collect(), |
| 2740 | dropped_events: snapshot.dropped_events, |
| 2741 | journal_discontinuous: snapshot.journal_discontinuous, |
| 2742 | } |
| 2743 | } |
| 2744 | |
| 2745 | fn normalize_tail(origin: Instant, sealer: &IntervalSealer) -> NormalizedSealerTail { |
| 2746 | NormalizedSealerTail { |
| 2747 | interval_start: sealer.interval_start.duration_since(origin).as_micros() as u64, |
| 2748 | events: sealer |
| 2749 | .events |
| 2750 | .iter() |
| 2751 | .copied() |
| 2752 | .map(|event| normalize_event(origin, event)) |
| 2753 | .collect(), |
| 2754 | small_polls: sealer |
| 2755 | .small_polls |
| 2756 | .iter() |
| 2757 | .copied() |
| 2758 | .map(|flush| normalize_small_polls(origin, flush)) |
| 2759 | .collect(), |
| 2760 | dropped_events: sealer.dropped_events, |
| 2761 | journal_discontinuous: sealer.journal_discontinuous, |
| 2762 | } |
| 2763 | } |
| 2764 | |
| 2765 | fn reference_seal( |
| 2766 | origin: Instant, |
| 2767 | entries: &[ForegroundJournalEntry], |
| 2768 | ) -> (Vec<NormalizedSnapshot>, NormalizedSealerTail) { |
| 2769 | let mut interval_start = 0; |
| 2770 | let mut events = Vec::new(); |
| 2771 | let mut small_polls = Vec::new(); |
| 2772 | let mut snapshots = Vec::new(); |
| 2773 | let mut dropped_events = 0; |
| 2774 | let mut journal_discontinuous = false; |
| 2775 | |
| 2776 | for entry in entries { |
| 2777 | match *entry { |
| 2778 | ForegroundJournalEntry::Event(event) => { |
| 2779 | let event_start = event.start_time().duration_since(origin).as_micros() as u64; |
| 2780 | if events.is_empty() |
| 2781 | && small_polls.is_empty() |
| 2782 | && dropped_events == 0 |
| 2783 | && !journal_discontinuous |
| 2784 | { |
| 2785 | interval_start = interval_start.max(event_start); |
| 2786 | } |
| 2787 | match event { |
| 2788 | ForegroundEvent::SmallPolls(flush) => { |
| 2789 | small_polls.push(normalize_small_polls(origin, flush)); |
| 2790 | } |
| 2791 | event => events.push(normalize_event(origin, event)), |
| 2792 | } |
| 2793 | } |
| 2794 | ForegroundJournalEntry::Boundary(boundary) => { |
| 2795 | if let IntervalBoundary::Presented(presented) = boundary { |
| 2796 | let present = ForegroundEvent::Present(presented.presentation); |
| 2797 | if events.is_empty() |
| 2798 | && small_polls.is_empty() |
| 2799 | && dropped_events == 0 |
| 2800 | && !journal_discontinuous |
| 2801 | { |
| 2802 | interval_start = |
| 2803 | interval_start |
| 2804 | .max(present.start_time().duration_since(origin).as_micros() |
| 2805 | as u64); |
| 2806 | } |
| 2807 | events.push(normalize_event(origin, present)); |
| 2808 | } |
| 2809 | |
| 2810 | let interval_end = |
| 2811 | boundary.end_time().duration_since(origin).as_micros() as u64; |
| 2812 | if events.is_empty() |
| 2813 | && small_polls.is_empty() |
| 2814 | && dropped_events == 0 |
| 2815 | && !journal_discontinuous |
| 2816 | { |
| 2817 | interval_start = interval_start.max(interval_end); |
| 2818 | } else { |
| 2819 | snapshots.push(NormalizedSnapshot { |
| 2820 | interval_start, |
| 2821 | boundary_kind: match boundary { |
| 2822 | IntervalBoundary::Idle { .. } => 0, |
| 2823 | IntervalBoundary::Presented(_) => 1, |
| 2824 | IntervalBoundary::PowerTransition { .. } => 2, |
| 2825 | IntervalBoundary::FrameSkipped(_) => 3, |
| 2826 | }, |
| 2827 | interval_end, |
| 2828 | events: std::mem::take(&mut events), |
| 2829 | small_polls: std::mem::take(&mut small_polls), |
| 2830 | dropped_events: std::mem::take(&mut dropped_events), |
| 2831 | journal_discontinuous: std::mem::take(&mut journal_discontinuous), |
| 2832 | }); |
| 2833 | interval_start = interval_end; |
| 2834 | } |
| 2835 | } |
| 2836 | ForegroundJournalEntry::FrameState(_) |
| 2837 | | ForegroundJournalEntry::PlatformSignal(_) |
| 2838 | | ForegroundJournalEntry::ReentrantFrameSkipped { .. } => {} |
| 2839 | ForegroundJournalEntry::Discontinuity { lost } => { |
| 2840 | dropped_events += lost; |
| 2841 | journal_discontinuous = true; |
| 2842 | } |
| 2843 | } |
| 2844 | } |
| 2845 | |
| 2846 | ( |
| 2847 | snapshots, |
| 2848 | NormalizedSealerTail { |
| 2849 | interval_start, |
| 2850 | events, |
| 2851 | small_polls, |
| 2852 | dropped_events, |
| 2853 | journal_discontinuous, |
| 2854 | }, |
| 2855 | ) |
| 2856 | } |
| 2857 | |
| 2858 | fn reference_occupancy_micros( |
| 2859 | event_spans: &[(u8, u8)], |
| 2860 | small_poll_spans: &[(u8, u8, u8)], |
| 2861 | window_start: u8, |
| 2862 | window_end: u8, |
| 2863 | ) -> u64 { |
| 2864 | let mut clamped_spans = event_spans |
| 2865 | .iter() |
| 2866 | .map(|&(first, second)| { |
| 2867 | let start = first.min(second).max(window_start); |
| 2868 | let end = first.max(second).min(window_end).max(start); |
| 2869 | (start, end) |
| 2870 | }) |
| 2871 | .collect::<Vec<_>>(); |
| 2872 | clamped_spans.sort_unstable(); |
| 2873 | |
| 2874 | let mut occupied = 0u64; |
| 2875 | let mut merged_until = None; |
| 2876 | for (start, end) in clamped_spans { |
| 2877 | let start = merged_until.map_or(start, |until| start.max(until)); |
| 2878 | occupied += u64::from(end.saturating_sub(start)); |
| 2879 | merged_until = Some(merged_until.map_or(end, |until| until.max(end))); |
| 2880 | } |
| 2881 | |
| 2882 | occupied |
| 2883 | + small_poll_spans |
| 2884 | .iter() |
| 2885 | .map(|&(first, second, factor)| { |
| 2886 | let since = first.min(second); |
| 2887 | let until = first.max(second); |
| 2888 | if since == until { |
| 2889 | if since >= window_start && since <= window_end { |
| 2890 | u64::from(factor) |
| 2891 | } else { |
| 2892 | 0 |
| 2893 | } |
| 2894 | } else { |
| 2895 | let overlap_start = since.max(window_start); |
| 2896 | let overlap_end = until.min(window_end).max(overlap_start); |
| 2897 | u64::from(overlap_end - overlap_start) * u64::from(factor) |
| 2898 | } |
| 2899 | }) |
| 2900 | .sum::<u64>() |
| 2901 | } |
| 2902 | |
| 2903 | #[derive(Debug, Clone)] |
| 2904 | struct WriterOperation { |
| 2905 | kind: u8, |
| 2906 | advance: u16, |
| 2907 | argument: u8, |
| 2908 | } |
| 2909 | |
| 2910 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 2911 | enum WriterEntry { |
| 2912 | Input(u64), |
| 2913 | SmallPolls { |
| 2914 | count: u64, |
| 2915 | total_micros: u64, |
| 2916 | since: u64, |
| 2917 | until: u64, |
| 2918 | }, |
| 2919 | Pending { |
| 2920 | window: u64, |
| 2921 | at: u64, |
| 2922 | }, |
| 2923 | Closed { |
| 2924 | window: u64, |
| 2925 | at: u64, |
| 2926 | }, |
| 2927 | Present { |
| 2928 | window: u64, |
| 2929 | at: u64, |
| 2930 | }, |
| 2931 | Presented { |
| 2932 | window: u64, |
| 2933 | at: u64, |
| 2934 | }, |
| 2935 | Idle(u64), |
| 2936 | } |
| 2937 | |
| 2938 | #[derive(Default)] |
| 2939 | struct ModelSmallPolls { |
| 2940 | count: u64, |
| 2941 | total_micros: u64, |
| 2942 | since: u64, |
| 2943 | until: u64, |
| 2944 | } |
| 2945 | |
| 2946 | #[derive(Default)] |
| 2947 | struct ModelWriter { |
| 2948 | turn_depth: usize, |
| 2949 | runnables: usize, |
| 2950 | pending_frames: HashMap<u64, u64>, |
| 2951 | retained_since_boundary: bool, |
| 2952 | small_polls: Option<ModelSmallPolls>, |
| 2953 | entries: Vec<WriterEntry>, |
| 2954 | } |
| 2955 | |
| 2956 | impl ModelWriter { |
| 2957 | fn record_entry(&mut self, entry: WriterEntry) { |
| 2958 | if let Some(small_polls) = self.small_polls.take() { |
| 2959 | self.entries.push(WriterEntry::SmallPolls { |
| 2960 | count: small_polls.count, |
| 2961 | total_micros: small_polls.total_micros, |
| 2962 | since: small_polls.since, |
| 2963 | until: small_polls.until, |
| 2964 | }); |
| 2965 | } |
| 2966 | let boundary = matches!(entry, WriterEntry::Presented { .. } | WriterEntry::Idle(_)); |
| 2967 | self.entries.push(entry); |
| 2968 | if boundary { |
| 2969 | self.retained_since_boundary = false; |
| 2970 | } |
| 2971 | } |
| 2972 | |
| 2973 | fn record_input(&mut self, at: u64) { |
| 2974 | self.retained_since_boundary = true; |
| 2975 | self.record_entry(WriterEntry::Input(at)); |
| 2976 | } |
| 2977 | |
| 2978 | fn fold_small_poll(&mut self, since: u64, until: u64) { |
| 2979 | let small_polls = self.small_polls.get_or_insert(ModelSmallPolls { |
| 2980 | since, |
| 2981 | until, |
| 2982 | ..ModelSmallPolls::default() |
| 2983 | }); |
| 2984 | small_polls.count += 1; |
| 2985 | small_polls.total_micros += until - since; |
| 2986 | small_polls.since = small_polls.since.min(since); |
| 2987 | small_polls.until = small_polls.until.max(until); |
| 2988 | } |
| 2989 | |
| 2990 | fn record_pending(&mut self, window: u64, at: u64) { |
| 2991 | let should_record = self |
| 2992 | .pending_frames |
| 2993 | .get(&window) |
| 2994 | .is_none_or(|previous| at.saturating_sub(*previous) >= 1_000_000); |
| 2995 | if should_record { |
| 2996 | self.pending_frames.insert(window, at); |
| 2997 | self.record_entry(WriterEntry::Pending { window, at }); |
| 2998 | } |
| 2999 | } |
| 3000 | |
| 3001 | fn record_closed(&mut self, window: u64, at: u64) { |
| 3002 | self.pending_frames.remove(&window); |
| 3003 | self.record_entry(WriterEntry::Closed { window, at }); |
| 3004 | } |
| 3005 | |
| 3006 | fn record_present(&mut self, window: u64, at: u64, has_frame: bool) { |
| 3007 | if has_frame { |
| 3008 | self.pending_frames.remove(&window); |
| 3009 | self.record_entry(WriterEntry::Presented { window, at }); |
| 3010 | } else { |
| 3011 | self.pending_frames.remove(&window); |
| 3012 | self.retained_since_boundary = true; |
| 3013 | self.record_entry(WriterEntry::Present { window, at }); |
| 3014 | } |
| 3015 | } |
| 3016 | |
| 3017 | fn end_turn(&mut self, at: u64) { |
| 3018 | if self.turn_depth == 0 { |
| 3019 | return; |
| 3020 | } |
| 3021 | self.turn_depth -= 1; |
| 3022 | if self.turn_depth > 0 || self.runnables > 0 { |
| 3023 | return; |
| 3024 | } |
| 3025 | self.pending_frames |
| 3026 | .retain(|_, dirty_at| at.saturating_sub(*dirty_at) < 1_000_000); |
| 3027 | if !self.pending_frames.is_empty() { |
| 3028 | return; |
| 3029 | } |
| 3030 | if !self.retained_since_boundary { |
| 3031 | self.small_polls = None; |
| 3032 | return; |
| 3033 | } |
| 3034 | self.record_entry(WriterEntry::Idle(at)); |
| 3035 | } |
| 3036 | } |
| 3037 | |
| 3038 | fn normalize_writer_entries( |
| 3039 | origin: Instant, |
| 3040 | entries: Vec<ForegroundJournalEntry>, |
| 3041 | ) -> Vec<WriterEntry> { |
| 3042 | let at = |instant: Instant| instant.duration_since(origin).as_micros() as u64; |
| 3043 | entries |
| 3044 | .into_iter() |
| 3045 | .map(|entry| match entry { |
| 3046 | ForegroundJournalEntry::Event(ForegroundEvent::Input(timing)) => { |
| 3047 | WriterEntry::Input(at(timing.end)) |
| 3048 | } |
| 3049 | ForegroundJournalEntry::Event(ForegroundEvent::SmallPolls(flush)) => { |
| 3050 | WriterEntry::SmallPolls { |
| 3051 | count: flush.summary.count, |
| 3052 | total_micros: flush.summary.total.as_micros() as u64, |
| 3053 | since: at(flush.since), |
| 3054 | until: at(flush.until), |
| 3055 | } |
| 3056 | } |
| 3057 | ForegroundJournalEntry::Event(ForegroundEvent::Present(timing)) => { |
| 3058 | WriterEntry::Present { |
| 3059 | window: timing.window_id.as_u64(), |
| 3060 | at: at(timing.present_end), |
| 3061 | } |
| 3062 | } |
| 3063 | ForegroundJournalEntry::FrameState(FrameStateChange::Pending { |
| 3064 | window_id, |
| 3065 | dirty_at, |
| 3066 | }) => WriterEntry::Pending { |
| 3067 | window: window_id.as_u64(), |
| 3068 | at: at(dirty_at), |
| 3069 | }, |
| 3070 | ForegroundJournalEntry::FrameState(FrameStateChange::Closed { |
| 3071 | window_id, |
| 3072 | at: closed_at, |
| 3073 | }) => WriterEntry::Closed { |
| 3074 | window: window_id.as_u64(), |
| 3075 | at: at(closed_at), |
| 3076 | }, |
| 3077 | ForegroundJournalEntry::Boundary(IntervalBoundary::Presented(presented)) => { |
| 3078 | WriterEntry::Presented { |
| 3079 | window: presented.frame.window_id.as_u64(), |
| 3080 | at: at(presented.presentation.present_end), |
| 3081 | } |
| 3082 | } |
| 3083 | ForegroundJournalEntry::Boundary(IntervalBoundary::Idle { ended_at }) => { |
| 3084 | WriterEntry::Idle(at(ended_at)) |
| 3085 | } |
| 3086 | other => panic!("writer property emitted an unexpected entry: {other:?}"), |
| 3087 | }) |
| 3088 | .collect() |
| 3089 | } |
| 3090 | |
| 3091 | proptest! { |
| 3092 | #![proptest_config(ProptestConfig { |
| 3093 | failure_persistence: None, |
| 3094 | ..ProptestConfig::default() |
| 3095 | })] |
| 3096 | |
| 3097 | #[test] |
| 3098 | fn ring_matches_reference_model_under_wrap_collisions_and_independent_cursors( |
| 3099 | capacity in 1usize..=8, |
| 3100 | pending_capacity in 0usize..=4, |
| 3101 | operations in prop::collection::vec( |
| 3102 | prop_oneof![ |
| 3103 | 5 => Just(RingOperation::Publish), |
| 3104 | 3 => any::<u8>().prop_map(RingOperation::Collect), |
| 3105 | 1 => Just(RingOperation::NewCollector), |
| 3106 | 2 => any::<u8>().prop_map(RingOperation::Pin), |
| 3107 | 2 => any::<u8>().prop_map(RingOperation::Unpin), |
| 3108 | ], |
| 3109 | 1..=128, |
| 3110 | ), |
| 3111 | ) { |
| 3112 | let origin = Instant::now(); |
| 3113 | let (journal, mut publisher) = ForegroundJournal::new(capacity, pending_capacity); |
| 3114 | let mut collectors = vec![journal.collector()]; |
| 3115 | let mut model_collectors = vec![0]; |
| 3116 | let mut model = ModelRing::new(capacity, pending_capacity); |
| 3117 | let mut pins: Vec<Option<JournalSlotReadGuard<'_>>> = |
| 3118 | (0..capacity).map(|_| None).collect(); |
| 3119 | |
| 3120 | for operation in operations { |
| 3121 | match operation { |
| 3122 | RingOperation::Publish => { |
| 3123 | let sequence = model.next_sequence; |
| 3124 | publisher.publish([ring_entry(origin, sequence)]); |
| 3125 | model.publish(); |
| 3126 | } |
| 3127 | RingOperation::Collect(collector) => { |
| 3128 | let index = usize::from(collector) % collectors.len(); |
| 3129 | let drained = collectors[index].collect_unseen(); |
| 3130 | let (expected_entries, expected_lost) = |
| 3131 | model.collect(&mut model_collectors[index]); |
| 3132 | let observed_entries = normalize_ring_drain(origin, drained.entries); |
| 3133 | prop_assert_eq!(observed_entries, expected_entries); |
| 3134 | prop_assert_eq!(drained.lost, expected_lost); |
| 3135 | } |
| 3136 | RingOperation::NewCollector if collectors.len() < 4 => { |
| 3137 | collectors.push(journal.collector()); |
| 3138 | model_collectors.push(model.offered); |
| 3139 | } |
| 3140 | RingOperation::NewCollector => {} |
| 3141 | RingOperation::Pin(slot) => { |
| 3142 | let index = usize::from(slot) % capacity; |
| 3143 | if pins[index].is_none() { |
| 3144 | pins[index] = JournalSlotReadGuard::try_new(&journal.ring.slots[index]); |
| 3145 | prop_assert!(pins[index].is_some()); |
| 3146 | model.pinned[index] = true; |
| 3147 | } |
| 3148 | } |
| 3149 | RingOperation::Unpin(slot) => { |
| 3150 | let index = usize::from(slot) % capacity; |
| 3151 | pins[index].take(); |
| 3152 | model.pinned[index] = false; |
| 3153 | } |
| 3154 | } |
| 3155 | |
| 3156 | prop_assert_eq!(publisher.next_sequence, model.next_sequence); |
| 3157 | prop_assert_eq!( |
| 3158 | publisher.ring.offered.load(Ordering::Acquire), |
| 3159 | model.offered |
| 3160 | ); |
| 3161 | prop_assert_eq!( |
| 3162 | publisher.ring.finalized.load(Ordering::Acquire), |
| 3163 | model.finalized |
| 3164 | ); |
| 3165 | prop_assert_eq!( |
| 3166 | publisher |
| 3167 | .pending |
| 3168 | .iter() |
| 3169 | .map(|entry| entry.sequence) |
| 3170 | .collect::<Vec<_>>(), |
| 3171 | model |
| 3172 | .pending |
| 3173 | .iter() |
| 3174 | .map(|(sequence, _)| *sequence) |
| 3175 | .collect::<Vec<_>>() |
| 3176 | ); |
| 3177 | prop_assert_eq!( |
| 3178 | publisher.dropped_after_pending, |
| 3179 | model.dropped_after_pending |
| 3180 | ); |
| 3181 | } |
| 3182 | |
| 3183 | for pin in &mut pins { |
| 3184 | pin.take(); |
| 3185 | } |
| 3186 | model.pinned.fill(false); |
| 3187 | publisher.flush_pending(); |
| 3188 | model.flush_pending(); |
| 3189 | |
| 3190 | for (collector, model_cursor) in collectors.iter_mut().zip(&mut model_collectors) { |
| 3191 | let drained = collector.collect_unseen(); |
| 3192 | let (expected_entries, expected_lost) = model.collect(model_cursor); |
| 3193 | let observed_entries = normalize_ring_drain(origin, drained.entries); |
| 3194 | prop_assert_eq!(observed_entries, expected_entries); |
| 3195 | prop_assert_eq!(drained.lost, expected_lost); |
| 3196 | } |
| 3197 | } |
| 3198 | |
| 3199 | #[test] |
| 3200 | fn a_presentation_seals_exactly_once_regardless_of_delay( |
| 3201 | present_delay_micros in 1u64..=2_000_000 |
| 3202 | ) { |
| 3203 | let start = Instant::now(); |
| 3204 | let window_id = WindowId::from(0xDEA8); |
| 3205 | let presented_at = start + Duration::from_micros(present_delay_micros); |
| 3206 | let mut sealer = IntervalSealer::new(start); |
| 3207 | let snapshots = sealer.push_entries([ |
| 3208 | pending_frame(window_id, start), |
| 3209 | input_entry(start, start + Duration::from_micros(1)), |
| 3210 | ForegroundJournalEntry::Boundary(presented_boundary( |
| 3211 | window_id, |
| 3212 | start, |
| 3213 | presented_at, |
| 3214 | )), |
| 3215 | ]); |
| 3216 | |
| 3217 | prop_assert_eq!(snapshots.len(), 1); |
| 3218 | prop_assert!(matches!( |
| 3219 | snapshots[0].boundary, |
| 3220 | IntervalBoundary::Presented(_) |
| 3221 | )); |
| 3222 | prop_assert_eq!(snapshots[0].interval_end(), presented_at); |
| 3223 | } |
| 3224 | |
| 3225 | #[test] |
| 3226 | fn completion_order_sealer_matches_reference_under_arbitrary_batching( |
| 3227 | specifications in prop::collection::vec((0u8..16, 0u8..128, any::<u8>()), 1..=96), |
| 3228 | batch_sizes in prop::collection::vec(1usize..=12, 1..=24), |
| 3229 | ) { |
| 3230 | let origin = Instant::now(); |
| 3231 | let entries = completion_order_entries(origin, &specifications); |
| 3232 | let (expected_snapshots, expected_tail) = reference_seal(origin, &entries); |
| 3233 | |
| 3234 | let mut one_batch_sealer = IntervalSealer::new(origin); |
| 3235 | let one_batch_snapshots = one_batch_sealer |
| 3236 | .push_entries(entries.iter().copied()) |
| 3237 | .iter() |
| 3238 | .map(|snapshot| normalize_snapshot(origin, snapshot)) |
| 3239 | .collect::<Vec<_>>(); |
| 3240 | prop_assert_eq!(&one_batch_snapshots, &expected_snapshots); |
| 3241 | prop_assert_eq!(&normalize_tail(origin, &one_batch_sealer), &expected_tail); |
| 3242 | |
| 3243 | let mut batched_sealer = IntervalSealer::new(origin); |
| 3244 | let mut batched_snapshots = Vec::new(); |
| 3245 | let mut offset = 0; |
| 3246 | let mut batch_index = 0; |
| 3247 | while offset < entries.len() { |
| 3248 | let batch_size = batch_sizes[batch_index % batch_sizes.len()]; |
| 3249 | let batch_end = (offset + batch_size).min(entries.len()); |
| 3250 | batched_snapshots.extend( |
| 3251 | batched_sealer |
| 3252 | .push_entries(entries[offset..batch_end].iter().copied()) |
| 3253 | .iter() |
| 3254 | .map(|snapshot| normalize_snapshot(origin, snapshot)), |
| 3255 | ); |
| 3256 | offset = batch_end; |
| 3257 | batch_index += 1; |
| 3258 | } |
| 3259 | prop_assert_eq!(batched_snapshots, expected_snapshots); |
| 3260 | prop_assert_eq!(normalize_tail(origin, &batched_sealer), expected_tail); |
| 3261 | } |
| 3262 | |
| 3263 | #[test] |
| 3264 | fn occupancy_matches_interval_union_and_fold_apportionment( |
| 3265 | event_spans in prop::collection::vec((0u8..=128, 0u8..=128), 0..=16), |
| 3266 | small_poll_spans in prop::collection::vec( |
| 3267 | (0u8..=128, 0u8..=128, 0u8..=4), |
| 3268 | 0..=12, |
| 3269 | ), |
| 3270 | window in (0u8..=128, 0u8..=128), |
| 3271 | ) { |
| 3272 | let origin = Instant::now(); |
| 3273 | let window_start_micros = window.0.min(window.1); |
| 3274 | let window_end_micros = window.0.max(window.1); |
| 3275 | let events = event_spans |
| 3276 | .iter() |
| 3277 | .map(|&(first, second)| { |
| 3278 | let start = origin + Duration::from_micros(u64::from(first.min(second))); |
| 3279 | let end = origin + Duration::from_micros(u64::from(first.max(second))); |
| 3280 | ForegroundEvent::Input(InputTiming { |
| 3281 | kind: "test", |
| 3282 | start, |
| 3283 | end, |
| 3284 | caused_invalidation: false, |
| 3285 | }) |
| 3286 | }) |
| 3287 | .collect(); |
| 3288 | let small_polls = small_poll_spans |
| 3289 | .iter() |
| 3290 | .map(|&(first, second, factor)| { |
| 3291 | let since_micros = first.min(second); |
| 3292 | let until_micros = first.max(second); |
| 3293 | let span_micros = u64::from(until_micros - since_micros); |
| 3294 | let total_micros = if span_micros == 0 { |
| 3295 | u64::from(factor) |
| 3296 | } else { |
| 3297 | span_micros * u64::from(factor) |
| 3298 | }; |
| 3299 | SmallPollFlush { |
| 3300 | summary: PollSummary { |
| 3301 | count: 1, |
| 3302 | total: Duration::from_micros(total_micros), |
| 3303 | }, |
| 3304 | since: origin + Duration::from_micros(u64::from(since_micros)), |
| 3305 | until: origin + Duration::from_micros(u64::from(until_micros)), |
| 3306 | } |
| 3307 | }) |
| 3308 | .collect(); |
| 3309 | let snapshot = FrameSnapshot { |
| 3310 | interval_start: origin, |
| 3311 | boundary: IntervalBoundary::Idle { |
| 3312 | ended_at: origin + Duration::from_micros(128), |
| 3313 | }, |
| 3314 | events, |
| 3315 | small_polls, |
| 3316 | dropped_events: 0, |
| 3317 | journal_discontinuous: false, |
| 3318 | }; |
| 3319 | let expected_micros = reference_occupancy_micros( |
| 3320 | &event_spans, |
| 3321 | &small_poll_spans, |
| 3322 | window_start_micros, |
| 3323 | window_end_micros, |
| 3324 | ); |
| 3325 | let observed = snapshot.occupancy_within( |
| 3326 | origin + Duration::from_micros(u64::from(window_start_micros)), |
| 3327 | origin + Duration::from_micros(u64::from(window_end_micros)), |
| 3328 | ); |
| 3329 | |
| 3330 | prop_assert_eq!(observed, Duration::from_micros(expected_micros)); |
| 3331 | |
| 3332 | let full_expected = |
| 3333 | reference_occupancy_micros(&event_spans, &small_poll_spans, 0, 128); |
| 3334 | prop_assert_eq!(snapshot.occupancy(), Duration::from_micros(full_expected)); |
| 3335 | prop_assert!((0.0..=1.0).contains(&snapshot.busy_fraction())); |
| 3336 | prop_assert_eq!( |
| 3337 | snapshot.busy_fraction(), |
| 3338 | (full_expected as f64 / 128.0).min(1.0) |
| 3339 | ); |
| 3340 | } |
| 3341 | |
| 3342 | #[test] |
| 3343 | fn writer_matches_state_model_across_turn_frame_and_runnable_transitions( |
| 3344 | operations in prop::collection::vec( |
| 3345 | (any::<u8>(), any::<u16>(), any::<u8>()).prop_map( |
| 3346 | |(kind, advance, argument)| WriterOperation { |
| 3347 | kind, |
| 3348 | advance, |
| 3349 | argument, |
| 3350 | }, |
| 3351 | ), |
| 3352 | 1..=128, |
| 3353 | ), |
| 3354 | ) { |
| 3355 | let origin = Instant::now(); |
| 3356 | let counter = ForegroundRunnableCounter::new(); |
| 3357 | let (mut writer, mut collector) = test_journal(counter.clone()); |
| 3358 | let mut model = ModelWriter::default(); |
| 3359 | let mut at_micros = 100u64; |
| 3360 | |
| 3361 | for operation in operations { |
| 3362 | if operation.advance % 16 == 0 { |
| 3363 | at_micros += FRAME_DEADLINE.as_micros() as u64; |
| 3364 | } else { |
| 3365 | at_micros += u64::from(operation.advance) + 1; |
| 3366 | } |
| 3367 | let at = origin + Duration::from_micros(at_micros); |
| 3368 | let window_id = WindowId::from(u64::from(operation.argument % 4)); |
| 3369 | let window = window_id.as_u64(); |
| 3370 | |
| 3371 | match operation.kind % 10 { |
| 3372 | 0 => { |
| 3373 | writer.begin_turn(); |
| 3374 | model.turn_depth += 1; |
| 3375 | } |
| 3376 | 1 if model.turn_depth > 0 => { |
| 3377 | writer.end_turn(at); |
| 3378 | model.end_turn(at_micros); |
| 3379 | } |
| 3380 | 1 => {} |
| 3381 | 2 => { |
| 3382 | writer.record_event(ForegroundEvent::Input(InputTiming { |
| 3383 | kind: "test", |
| 3384 | start: at, |
| 3385 | end: at, |
| 3386 | caused_invalidation: false, |
| 3387 | })); |
| 3388 | model.record_input(at_micros); |
| 3389 | } |
| 3390 | 3 => { |
| 3391 | let duration_micros = u64::from(operation.argument % 100); |
| 3392 | writer.fold_small_poll(task_timing( |
| 3393 | at - Duration::from_micros(duration_micros), |
| 3394 | at, |
| 3395 | )); |
| 3396 | model.fold_small_poll( |
| 3397 | at_micros - duration_micros, |
| 3398 | at_micros, |
| 3399 | ); |
| 3400 | } |
| 3401 | 4 => { |
| 3402 | counter.queued(); |
| 3403 | model.runnables += 1; |
| 3404 | } |
| 3405 | 5 if model.runnables > 0 => { |
| 3406 | counter.finished(); |
| 3407 | model.runnables -= 1; |
| 3408 | } |
| 3409 | 5 => {} |
| 3410 | 6 => { |
| 3411 | writer.record_frame_pending(window_id, at); |
| 3412 | model.record_pending(window, at_micros); |
| 3413 | } |
| 3414 | 7 => { |
| 3415 | writer.record_window_closed(window_id, at); |
| 3416 | model.record_closed(window, at_micros); |
| 3417 | } |
| 3418 | 8 => { |
| 3419 | writer.record_present( |
| 3420 | presentation_timing(window_id, at), |
| 3421 | Some(frame_timing(window_id, at, at)), |
| 3422 | ); |
| 3423 | model.record_present(window, at_micros, true); |
| 3424 | } |
| 3425 | _ => { |
| 3426 | writer.record_present(presentation_timing(window_id, at), None); |
| 3427 | model.record_present(window, at_micros, false); |
| 3428 | } |
| 3429 | } |
| 3430 | |
| 3431 | let drained = collector.collect_unseen(); |
| 3432 | prop_assert_eq!(drained.lost, 0); |
| 3433 | prop_assert_eq!( |
| 3434 | normalize_writer_entries(origin, drained.entries), |
| 3435 | std::mem::take(&mut model.entries) |
| 3436 | ); |
| 3437 | prop_assert_eq!(writer.turn_depth, model.turn_depth); |
| 3438 | prop_assert_eq!(writer.retained_since_boundary, model.retained_since_boundary); |
| 3439 | prop_assert_eq!( |
| 3440 | writer |
| 3441 | .windows |
| 3442 | .values() |
| 3443 | .filter(|window| window.dirty_at.is_some()) |
| 3444 | .count(), |
| 3445 | model.pending_frames.len() |
| 3446 | ); |
| 3447 | } |
| 3448 | } |
| 3449 | } |
| 3450 | |
| 3451 | fn test_journal( |
| 3452 | foreground_runnables: ForegroundRunnableCounter, |
| 3453 | ) -> (ForegroundJournalWriter, ForegroundJournalCollector) { |
| 3454 | let (journal, publisher) = ForegroundJournal::new(256, 8); |
| 3455 | let collector = journal.collector(); |
| 3456 | ( |
| 3457 | ForegroundJournalWriter::new(foreground_runnables, publisher).with_test_suspend_clock(), |
| 3458 | collector, |
| 3459 | ) |
| 3460 | } |
| 3461 | |
| 3462 | fn has_boundary_at(entries: &[ForegroundJournalEntry], at: Instant) -> bool { |
| 3463 | entries.iter().any(|entry| { |
| 3464 | matches!(entry, ForegroundJournalEntry::Boundary(boundary) if boundary.end_time() == at) |
| 3465 | }) |
| 3466 | } |
| 3467 | |
| 3468 | fn input_entry(start: Instant, end: Instant) -> ForegroundJournalEntry { |
| 3469 | ForegroundJournalEntry::Event(ForegroundEvent::Input(InputTiming { |
| 3470 | kind: "test", |
| 3471 | start, |
| 3472 | end, |
| 3473 | caused_invalidation: false, |
| 3474 | })) |
| 3475 | } |
| 3476 | |
| 3477 | fn pending_frame(window_id: WindowId, dirty_at: Instant) -> ForegroundJournalEntry { |
| 3478 | ForegroundJournalEntry::FrameState(FrameStateChange::Pending { |
| 3479 | window_id, |
| 3480 | dirty_at, |
| 3481 | }) |
| 3482 | } |
| 3483 | |
| 3484 | fn frame_timing(window_id: WindowId, dirty_at: Instant, draw_end: Instant) -> FrameTiming { |
| 3485 | FrameTiming { |
| 3486 | window_id, |
| 3487 | dirty_at: Some(dirty_at), |
| 3488 | invalidations: 1, |
| 3489 | draw_start: draw_end, |
| 3490 | draw_end, |
| 3491 | } |
| 3492 | } |
| 3493 | |
| 3494 | fn presentation_timing(window_id: WindowId, present_end: Instant) -> PresentTiming { |
| 3495 | PresentTiming { |
| 3496 | window_id, |
| 3497 | present_start: present_end, |
| 3498 | present_end, |
| 3499 | animation_interval: None, |
| 3500 | } |
| 3501 | } |
| 3502 | |
| 3503 | fn presented_boundary( |
| 3504 | window_id: WindowId, |
| 3505 | dirty_at: Instant, |
| 3506 | present_end: Instant, |
| 3507 | ) -> IntervalBoundary { |
| 3508 | IntervalBoundary::Presented(PresentedFrame { |
| 3509 | frame: frame_timing(window_id, dirty_at, present_end), |
| 3510 | presentation: presentation_timing(window_id, present_end), |
| 3511 | }) |
| 3512 | } |
| 3513 | |
| 3514 | fn task_timing(start: Instant, end: Instant) -> TaskTiming { |
| 3515 | TaskTiming { |
| 3516 | location: std::panic::Location::caller(), |
| 3517 | spawned: SpawnTime(start), |
| 3518 | start, |
| 3519 | end: YieldTime(end), |
| 3520 | } |
| 3521 | } |
| 3522 | } |