Skip to main content

alpha2_render/
submission_clock.rs

1//! How long recent renderer submissions kept the GPU busy.
2//!
3//! Windows resets a GPU whose submission exceeds its timeout, and a reset device's DX12 fence
4//! reads complete, so the loss looks like dropped work. The submissions' run times tell the two
5//! apart. Each submission's GPU time runs from the later of its submit and the previous
6//! submission's end to its own completion callback, so queueing is excluded. Callback latency
7//! (poll or event loop) is small beside [`alpha2_gpu::hung_threshold_ms`]. Completions one poll
8//! delivers together tell only their total, so such submissions are judged as one group.
9
10use std::cell::Cell;
11use std::collections::VecDeque;
12use std::sync::{Arc, Mutex};
13
14use web_time::Instant;
15
16pub(crate) const RECENT_SUBMISSIONS_KEPT: usize = 256;
17const MOST_SUBMISSIONS_KEPT: usize = 65_536;
18
19/// The frame a submission belongs to, as its caller knows it.
20#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
21pub struct FrameMark {
22    /// The frame's timeline time, in ticks.
23    pub time_ticks: i64,
24    /// The frame's index in the export, when it is one.
25    pub frame_index: Option<u64>,
26}
27
28/// The recent submission, or group of submissions completed together, that kept the GPU busy
29/// longest, and what it rendered.
30#[derive(Clone, Debug, PartialEq)]
31pub struct SubmissionReport {
32    /// GPU time in milliseconds of all `submissions` together; for one still running, the time so
33    /// far.
34    pub gpu_ms: f64,
35    /// Whether `gpu_ms` is measured: its start and its last completion were each seen as they
36    /// happened. Otherwise a completion was seen late and `gpu_ms` is an upper bound.
37    pub measured: bool,
38    /// Submissions whose completions were seen together, so only their total is known; 1 for a
39    /// submission timed on its own.
40    pub submissions: u32,
41    /// The frame the first of them rendered, when the caller marked one.
42    pub frame: Option<FrameMark>,
43    /// The effects they ran, as `id@version`.
44    pub effects: Vec<String>,
45    /// Their predicted GPU time in milliseconds, when their frames were planned.
46    pub predicted_ms: Option<f64>,
47}
48
49impl SubmissionReport {
50    /// The [`crate::RenderError::GpuDeviceHung`] this report makes of a device loss.
51    #[must_use]
52    pub fn hung_error(&self) -> crate::RenderError {
53        crate::RenderError::GpuDeviceHung {
54            frame: self.frame.and_then(|frame| frame.frame_index),
55            time_ticks: self.frame.map(|frame| frame.time_ticks),
56            #[expect(
57                clippy::cast_possible_truncation,
58                clippy::cast_sign_loss,
59                reason = "clamped to whole milliseconds in u32"
60            )]
61            gpu_ms: self.gpu_ms.round().clamp(0.0, f64::from(u32::MAX)) as u32,
62            submissions: self.submissions,
63            measured: self.measured,
64            watchdog_ms: alpha2_gpu::watchdog_ms(),
65        }
66    }
67}
68
69#[derive(Copy, Clone, Debug)]
70struct Stamp {
71    at: Instant,
72    seen_as_it_happened: bool,
73    recorded_when_seen: u64,
74}
75
76impl Stamp {
77    fn seen_with(&self, other: &Self) -> bool {
78        !self.seen_as_it_happened && self.recorded_when_seen == other.recorded_when_seen
79    }
80}
81
82#[derive(Debug)]
83struct Entry {
84    submitted_at: Instant,
85    done: Option<Stamp>,
86    frame: Option<FrameMark>,
87    effects: Vec<String>,
88    predicted_ms: Option<f64>,
89}
90
91#[derive(Copy, Clone, Debug, Default)]
92enum Before {
93    #[default]
94    Nothing,
95    Completed(Stamp),
96    Running,
97}
98
99impl Before {
100    fn start_of(self, entry: &Entry) -> (Instant, bool) {
101        match self {
102            Self::Completed(stamp) if stamp.at > entry.submitted_at => {
103                (stamp.at, stamp.seen_as_it_happened)
104            }
105            Self::Nothing | Self::Completed(_) => (entry.submitted_at, true),
106            Self::Running => (entry.submitted_at, false),
107        }
108    }
109}
110
111#[derive(Copy, Clone, Debug)]
112struct Group {
113    first: usize,
114    len: usize,
115    gpu_ms: f64,
116    measured: bool,
117}
118
119#[derive(Debug, Default)]
120struct ClockState {
121    /// Sequence number of `entries[0]`.
122    first: u64,
123    forgotten: Before,
124    recorded: u64,
125    completed: u64,
126    watched: Vec<(u64, PreviousCompletion)>,
127    entries: VecDeque<Entry>,
128    frame: Option<FrameMark>,
129}
130
131impl ClockState {
132    fn group_at(&self, first: usize) -> Option<(usize, Stamp)> {
133        let mut last = first;
134        let mut end = self.entries.get(first)?.done?;
135        while let Some(next) = self.entries.get(last + 1).and_then(|entry| entry.done)
136            && end.seen_with(&next)
137        {
138            last += 1;
139            end = next;
140        }
141        Some((last, end))
142    }
143
144    fn groups(&self, now: Instant) -> Vec<Group> {
145        let mut groups = Vec::new();
146        let mut before = self.forgotten;
147        let mut first = 0;
148        while let Some(entry) = self.entries.get(first) {
149            let (start, start_seen) = before.start_of(entry);
150            let Some((last, end)) = self.group_at(first) else {
151                groups.push(Group {
152                    first,
153                    len: 1,
154                    gpu_ms: milliseconds(now.saturating_duration_since(start)),
155                    measured: false,
156                });
157                break;
158            };
159            groups.push(Group {
160                first,
161                len: last - first + 1,
162                gpu_ms: milliseconds(end.at.saturating_duration_since(start)),
163                measured: start_seen && end.seen_as_it_happened,
164            });
165            before = Before::Completed(end);
166            first = last + 1;
167        }
168        groups
169    }
170
171    fn members(&self, group: Group) -> impl Iterator<Item = &Entry> {
172        self.entries.range(group.first..group.first + group.len)
173    }
174
175    fn predicted_ms(&self, group: Group) -> Option<f64> {
176        self.members(group)
177            .filter_map(|entry| entry.predicted_ms)
178            .reduce(|a, b| a + b)
179    }
180
181    fn proves_a_hang(&self, group: Group, threshold_ms: f64) -> bool {
182        group.gpu_ms >= threshold_ms
183            && (group.len == 1
184                || group.gpu_ms > alpha2_gpu::MARGIN * self.predicted_ms(group).unwrap_or(0.0))
185    }
186
187    fn report(&self, group: Group) -> SubmissionReport {
188        let mut effects: Vec<String> = Vec::new();
189        for effect in self.members(group).flat_map(|entry| &entry.effects) {
190            if !effects.contains(effect) {
191                effects.push(effect.clone());
192            }
193        }
194        SubmissionReport {
195            gpu_ms: group.gpu_ms,
196            measured: group.measured,
197            submissions: u32::try_from(group.len).unwrap_or(u32::MAX),
198            frame: self.entries[group.first].frame,
199            effects,
200            predicted_ms: self.predicted_ms(group),
201        }
202    }
203
204    fn forget_front(&mut self, count: usize) {
205        for _ in 0..count {
206            let Some(forgotten) = self.entries.pop_front() else {
207                return;
208            };
209            self.forgotten = forgotten.done.map_or(Before::Running, Before::Completed);
210            self.first += 1;
211        }
212    }
213
214    fn forget(&mut self) {
215        loop {
216            let kept = self.entries.len();
217            if kept > MOST_SUBMISSIONS_KEPT {
218                self.forget_front(kept - MOST_SUBMISSIONS_KEPT);
219                continue;
220            }
221            match self.group_at(0) {
222                Some((last, _)) if kept - (last + 1) >= RECENT_SUBMISSIONS_KEPT => {
223                    self.forget_front(last + 1);
224                }
225                _ => return,
226            }
227        }
228    }
229}
230
231/// The renderer's recent submissions and when each finished.
232#[derive(Debug, Default)]
233pub(crate) struct SubmissionClock {
234    state: Mutex<ClockState>,
235}
236
237impl SubmissionClock {
238    fn state(&self) -> std::sync::MutexGuard<'_, ClockState> {
239        self.state
240            .lock()
241            .unwrap_or_else(std::sync::PoisonError::into_inner)
242    }
243
244    /// Marks the frame the next submissions render, until another is marked.
245    pub(crate) fn mark_frame(&self, frame: Option<FrameMark>) {
246        self.state().frame = frame;
247    }
248
249    /// Records a submission made at `at` that runs `effects` and returns its sequence number for
250    /// [`Self::complete`], also watching for the completion of the submission before it when
251    /// `watch_previous` and that is still running.
252    pub(crate) fn record(
253        &self,
254        at: Instant,
255        predicted_ms: Option<f64>,
256        effects: Vec<String>,
257        watch_previous: bool,
258    ) -> Recorded {
259        let mut state = self.state();
260        let queue_idle = state.completed == state.recorded;
261        let previous = (watch_previous && !queue_idle).then(|| {
262            let watch = PreviousCompletion::default();
263            let sequence = state.recorded - 1;
264            state.watched.push((sequence, watch.clone()));
265            watch
266        });
267        state.recorded += 1;
268        let frame = state.frame;
269        state.entries.push_back(Entry {
270            submitted_at: at,
271            done: None,
272            frame,
273            effects,
274            predicted_ms,
275        });
276        state.forget();
277        Recorded {
278            sequence: state.recorded - 1,
279            queue_idle,
280            previous,
281        }
282    }
283
284    /// Records that submission `sequence` finished at `at`, seen `as_it_happens` or not; the
285    /// queue completes in order, so all earlier ones have too.
286    pub(crate) fn complete(&self, sequence: u64, at: Instant, as_it_happens: bool) {
287        let mut state = self.state();
288        state.completed = state.completed.max(sequence + 1);
289        state.watched.retain(|(watched, completion)| {
290            if *watched > sequence {
291                return true;
292            }
293            completion.set(at, as_it_happens && *watched == sequence);
294            false
295        });
296        let Some(position) = sequence.checked_sub(state.first) else {
297            return;
298        };
299        let Ok(position) = usize::try_from(position) else {
300            return;
301        };
302        let recorded_when_seen = state.recorded;
303        let last = position.min(state.entries.len().saturating_sub(1));
304        for (index, entry) in state.entries.iter_mut().take(position + 1).enumerate() {
305            entry.done.get_or_insert(Stamp {
306                at,
307                seen_as_it_happened: as_it_happens && index == last,
308                recorded_when_seen,
309            });
310        }
311    }
312
313    /// Each kept submission's GPU time, oldest first: finished ones in full, the oldest unfinished
314    /// up to `now`, later unfinished ones not at all.
315    fn spans(state: &ClockState, now: Instant) -> Vec<(f64, &Entry)> {
316        let mut spans = Vec::new();
317        let mut before = state.forgotten;
318        for entry in &state.entries {
319            let (start, _) = before.start_of(entry);
320            let Some(done) = entry.done else {
321                spans.push((milliseconds(now.saturating_duration_since(start)), entry));
322                break;
323            };
324            spans.push((
325                milliseconds(done.at.saturating_duration_since(start)),
326                entry,
327            ));
328            before = Before::Completed(done);
329        }
330        spans
331    }
332
333    /// The kept submission or group with the longest GPU time, counting a running one up to
334    /// `now`.
335    pub(crate) fn longest_at(&self, now: Instant) -> Option<SubmissionReport> {
336        let state = self.state();
337        state
338            .groups(now)
339            .into_iter()
340            .max_by(|a, b| a.gpu_ms.total_cmp(&b.gpu_ms))
341            .map(|group| state.report(group))
342    }
343
344    /// Summed GPU time of `sequences` once all finished and are still kept. Late completions shift
345    /// time between consecutive submissions but not out of the sum, so a frame's total holds.
346    pub(crate) fn gpu_ms(&self, sequences: std::ops::Range<u64>) -> Option<f64> {
347        let state = self.state();
348        let first = state.first;
349        let spans = Self::spans(&state, Instant::now());
350        let mut total = 0.0;
351        let mut counted = 0;
352        for (position, (ms, entry)) in spans.into_iter().enumerate() {
353            let sequence = first + u64::try_from(position).unwrap_or(u64::MAX);
354            if sequences.contains(&sequence) {
355                entry.done?;
356                total += ms;
357                counted += 1;
358            }
359        }
360        (counted == sequences.end.saturating_sub(sequences.start)).then_some(total)
361    }
362
363    /// [`Self::longest_at`] now.
364    pub(crate) fn longest(&self) -> Option<SubmissionReport> {
365        self.longest_at(Instant::now())
366    }
367
368    fn hung_at(&self, now: Instant, threshold_ms: f64) -> Option<SubmissionReport> {
369        let state = self.state();
370        state
371            .groups(now)
372            .into_iter()
373            .filter(|group| state.proves_a_hang(*group, threshold_ms))
374            .max_by(|a, b| a.gpu_ms.total_cmp(&b.gpu_ms))
375            .map(|group| state.report(group))
376    }
377
378    #[cfg(test)]
379    pub(crate) fn kept_seen_as_they_happened(&self) -> Vec<Option<bool>> {
380        self.state()
381            .entries
382            .iter()
383            .map(|entry| entry.done.map(|stamp| stamp.seen_as_it_happened))
384            .collect()
385    }
386
387    #[cfg(test)]
388    pub(crate) fn kept_effects(&self) -> Vec<Vec<String>> {
389        self.state()
390            .entries
391            .iter()
392            .map(|entry| entry.effects.clone())
393            .collect()
394    }
395
396    /// The longest kept submission or group that implicates this renderer's own work in a loss.
397    pub(crate) fn hung(&self) -> Option<SubmissionReport> {
398        self.hung_at(Instant::now(), f64::from(alpha2_gpu::hung_threshold_ms()))
399    }
400}
401
402#[derive(Clone, Debug)]
403pub(crate) struct Recorded {
404    pub(crate) sequence: u64,
405    pub(crate) queue_idle: bool,
406    pub(crate) previous: Option<PreviousCompletion>,
407}
408
409impl Recorded {
410    pub(crate) fn started(&self, at: Instant) -> Option<Instant> {
411        if self.queue_idle {
412            return Some(at);
413        }
414        let (done, as_it_happens) = self.previous.as_ref()?.get()?;
415        as_it_happens.then(|| done.max(at))
416    }
417}
418
419#[derive(Clone, Debug, Default)]
420pub(crate) struct PreviousCompletion(Arc<Mutex<Option<(Instant, bool)>>>);
421
422impl PreviousCompletion {
423    fn set(&self, at: Instant, as_it_happens: bool) {
424        *self
425            .0
426            .lock()
427            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some((at, as_it_happens));
428    }
429
430    fn get(&self) -> Option<(Instant, bool)> {
431        *self
432            .0
433            .lock()
434            .unwrap_or_else(std::sync::PoisonError::into_inner)
435    }
436}
437
438thread_local! {
439    static WAITING: Cell<Option<(usize, u64)>> = const { Cell::new(None) };
440}
441
442impl SubmissionClock {
443    fn address(self: &Arc<Self>) -> usize {
444        Arc::as_ptr(self) as usize
445    }
446
447    pub(crate) fn sees_as_it_happens(self: &Arc<Self>, sequence: u64) -> bool {
448        WAITING
449            .get()
450            .is_some_and(|(clock, waited)| clock == self.address() && sequence >= waited)
451    }
452}
453
454#[cfg(not(target_arch = "wasm32"))]
455struct Waiting(Option<(usize, u64)>);
456
457#[cfg(not(target_arch = "wasm32"))]
458impl Waiting {
459    fn on(clock: usize, sequence: u64) -> Self {
460        Self(WAITING.replace(Some((clock, sequence))))
461    }
462}
463
464#[cfg(not(target_arch = "wasm32"))]
465impl Drop for Waiting {
466    fn drop(&mut self) {
467        WAITING.set(self.0);
468    }
469}
470
471#[derive(Clone, Debug)]
472#[cfg_attr(
473    target_arch = "wasm32",
474    expect(dead_code, reason = "a browser cannot wait for a submission")
475)]
476pub(crate) struct ClockedSubmission {
477    pub(crate) index: wgpu::SubmissionIndex,
478    clock: Arc<SubmissionClock>,
479    sequence: u64,
480    earlier: Vec<(wgpu::SubmissionIndex, u64)>,
481}
482
483impl ClockedSubmission {
484    pub(crate) const fn new(
485        index: wgpu::SubmissionIndex,
486        clock: Arc<SubmissionClock>,
487        sequence: u64,
488    ) -> Self {
489        Self {
490            index,
491            clock,
492            sequence,
493            earlier: Vec::new(),
494        }
495    }
496
497    pub(crate) fn after(mut self, earlier: Vec<(wgpu::SubmissionIndex, u64)>) -> Self {
498        self.earlier = earlier;
499        self
500    }
501
502    /// # Errors
503    /// [`crate::RenderError::GpuTimeout`] past `timeout`, or
504    /// [`crate::RenderError::TextureReadback`] when polling fails.
505    #[cfg(not(target_arch = "wasm32"))]
506    pub(crate) fn wait(
507        &self,
508        gpu: &alpha2_gpu::GpuContext,
509        timeout: std::time::Duration,
510    ) -> Result<(), crate::RenderError> {
511        let deadline = Instant::now() + timeout;
512        gpu.device()
513            .poll(wgpu::PollType::Poll)
514            .map_err(crate::error::poll_error)?;
515        let last = (self.index.clone(), self.sequence);
516        wait_in_order(
517            &self.clock,
518            self.earlier.iter().chain(std::iter::once(&last)),
519            deadline,
520            |index, remaining| {
521                gpu.device()
522                    .poll(wgpu::PollType::Wait {
523                        submission_index: Some(index.clone()),
524                        timeout: Some(remaining),
525                    })
526                    .map(drop)
527                    .map_err(crate::error::poll_error)
528            },
529        )
530    }
531}
532
533#[cfg(not(target_arch = "wasm32"))]
534fn wait_in_order<'a, T: 'a>(
535    clock: &Arc<SubmissionClock>,
536    waited: impl Iterator<Item = &'a (T, u64)>,
537    deadline: Instant,
538    mut block: impl FnMut(&T, std::time::Duration) -> Result<(), crate::RenderError>,
539) -> Result<(), crate::RenderError> {
540    for (submission, sequence) in waited {
541        let _waiting = Waiting::on(clock.address(), *sequence);
542        block(
543            submission,
544            deadline.saturating_duration_since(Instant::now()),
545        )?;
546    }
547    Ok(())
548}
549
550fn milliseconds(duration: std::time::Duration) -> f64 {
551    duration.as_secs_f64() * 1_000.0
552}
553
554#[cfg(test)]
555mod tests {
556    use std::time::Duration;
557
558    use super::*;
559
560    #[test]
561    fn a_wait_in_order_stamps_completions_delivered_while_it_blocks_however_they_are_batched() {
562        let clock = Arc::new(SubmissionClock::default());
563        let start = Instant::now();
564        let sequences = (0..7)
565            .map(|_| clock.record(start, Some(1.0), Vec::new(), false).sequence)
566            .collect::<Vec<_>>();
567        let deliver = |sequence: u64| {
568            clock.complete(sequence, Instant::now(), clock.sees_as_it_happens(sequence));
569        };
570        deliver(sequences[0]);
571        let batches = [&sequences[1..2], &sequences[2..5], &sequences[5..7]];
572        let mut delivered = batches.iter();
573        let mut remaining = Vec::new();
574        let waited = sequences[1..]
575            .iter()
576            .map(|sequence| ((), *sequence))
577            .collect::<Vec<_>>();
578        let timeout = Duration::from_secs(5);
579        wait_in_order(&clock, waited.iter(), start + timeout, |(), left| {
580            remaining.push(left);
581            if let Some(batch) = delivered.next() {
582                batch.iter().copied().for_each(deliver);
583            }
584            Ok(())
585        })
586        .expect("waits");
587        assert!(remaining.windows(2).all(|pair| pair[1] <= pair[0]) && remaining[0] <= timeout);
588        let seen = clock
589            .state()
590            .entries
591            .iter()
592            .map(|entry| entry.done.map(|stamp| stamp.seen_as_it_happened))
593            .collect::<Vec<_>>();
594        assert_eq!(
595            seen,
596            [Some(false)]
597                .into_iter()
598                .chain(std::iter::repeat_n(Some(true), 6))
599                .collect::<Vec<_>>(),
600            "only the completion delivered before the wait is late"
601        );
602    }
603
604    /// Submissions made at once run back to back; each starts where the previous ended.
605    #[test]
606    fn gpu_time_excludes_queueing_behind_earlier_submissions() {
607        let clock = SubmissionClock::default();
608        let start = Instant::now();
609        let at = |ms: u64| start + Duration::from_millis(ms);
610        let first = clock.record(at(0), None, Vec::new(), false).sequence;
611        let second = clock.record(at(0), None, Vec::new(), false).sequence;
612        let third = clock.record(at(0), None, Vec::new(), false).sequence;
613        clock.complete(first, at(10), true);
614        clock.complete(second, at(400), true);
615        clock.complete(third, at(405), true);
616        let longest = clock.longest_at(at(1_000)).expect("submissions");
617        assert!((longest.gpu_ms - 390.0).abs() < 0.5, "{longest:?}");
618        assert!(longest.measured, "{longest:?}");
619        // Submitted after the queue went idle, so it starts at its own submit.
620        let fourth = clock.record(at(2_000), None, Vec::new(), false).sequence;
621        clock.complete(fourth, at(2_005), false);
622        assert!((clock.longest_at(at(3_000)).expect("kept").gpu_ms - 390.0).abs() < 0.5);
623        let _ = clock.record(at(3_000), None, Vec::new(), false).sequence;
624        assert!((clock.longest_at(at(3_700)).expect("running").gpu_ms - 700.0).abs() < 0.5);
625    }
626
627    #[test]
628    fn a_completion_finishes_every_earlier_submission() {
629        let clock = SubmissionClock::default();
630        let start = Instant::now();
631        let first = clock.record(start, None, Vec::new(), false).sequence;
632        let second = clock.record(start, None, Vec::new(), false).sequence;
633        clock.complete(second, start + Duration::from_millis(8), false);
634        let _ = first;
635        assert_eq!(
636            clock
637                .longest_at(start + Duration::from_secs(5))
638                .map(|r| r.gpu_ms.round()),
639            Some(8.0)
640        );
641    }
642
643    #[test]
644    fn a_frames_gpu_time_survives_completions_seen_together() {
645        let clock = SubmissionClock::default();
646        let start = Instant::now();
647        let at = |ms: u64| start + Duration::from_millis(ms);
648        let earlier = clock.record(at(0), None, Vec::new(), false).sequence;
649        clock.complete(earlier, at(5), false);
650        let first = clock
651            .record(at(10), Some(100.0), Vec::new(), false)
652            .sequence;
653        let second = clock
654            .record(at(10), Some(100.0), Vec::new(), false)
655            .sequence;
656        assert_eq!(clock.gpu_ms(first..second + 1), None, "not finished");
657        clock.complete(second, at(210), false);
658        let total = clock.gpu_ms(first..second + 1).expect("finished");
659        assert!((total - 200.0).abs() < 0.5, "{total}");
660        let report = clock.longest_at(at(300)).expect("kept");
661        assert_eq!(report.submissions, 2, "{report:?}");
662        assert_eq!(report.predicted_ms, Some(200.0));
663    }
664
665    #[test]
666    fn the_clock_keeps_the_frame_and_effects_of_each_submission() {
667        let clock = SubmissionClock::default();
668        let start = Instant::now();
669        clock.mark_frame(Some(FrameMark {
670            time_ticks: 4_000,
671            frame_index: Some(1),
672        }));
673        let heavy = clock
674            .record(start, None, vec!["blur@2".to_owned()], false)
675            .sequence;
676        clock.complete(heavy, start + Duration::from_millis(30), false);
677        let light = clock
678            .record(start + Duration::from_millis(40), None, Vec::new(), false)
679            .sequence;
680        clock.complete(light, start + Duration::from_millis(41), false);
681        let report = clock
682            .longest_at(start + Duration::from_millis(50))
683            .expect("kept");
684        assert_eq!(report.effects, ["blur@2"]);
685        assert_eq!(report.frame.and_then(|frame| frame.frame_index), Some(1));
686    }
687
688    #[test]
689    fn a_submission_starts_on_an_idle_queue_only_once_every_earlier_one_completed() {
690        let clock = SubmissionClock::default();
691        let start = Instant::now();
692        let first = clock.record(start, None, Vec::new(), false);
693        assert!(first.queue_idle);
694        let second = clock.record(start, None, Vec::new(), false);
695        assert!(!second.queue_idle);
696        clock.complete(first.sequence, start, false);
697        assert!(!clock.record(start, None, Vec::new(), false).queue_idle);
698        clock.complete(second.sequence + 1, start, false);
699        assert!(clock.record(start, None, Vec::new(), false).queue_idle);
700    }
701
702    #[test]
703    fn only_completions_inside_a_wait_on_them_or_earlier_ones_are_seen_as_they_happen() {
704        let clock = Arc::new(SubmissionClock::default());
705        let other = Arc::new(SubmissionClock::default());
706        assert!(!clock.sees_as_it_happens(0));
707        WAITING.set(Some((clock.address(), 5)));
708        assert!(!clock.sees_as_it_happens(4));
709        assert!(clock.sees_as_it_happens(5));
710        assert!(clock.sees_as_it_happens(6));
711        assert!(!other.sees_as_it_happens(6));
712        WAITING.set(None);
713    }
714
715    #[test]
716    fn a_frame_behind_a_completion_seen_as_it_happened_starts_at_that_completion() {
717        let clock = SubmissionClock::default();
718        let start = Instant::now();
719        let at = |ms: u64| start + Duration::from_millis(ms);
720        let first = clock.record(at(0), None, Vec::new(), false);
721        assert_eq!(first.started(at(0)), Some(at(0)));
722        let behind = clock.record(at(1), None, Vec::new(), true);
723        let late = clock.record(at(2), None, Vec::new(), true);
724        assert_eq!(behind.started(at(1)), None, "not complete yet");
725        clock.complete(first.sequence, at(10), true);
726        clock.complete(behind.sequence, at(30), false);
727        assert_eq!(behind.started(at(1)), Some(at(10)));
728        assert_eq!(late.started(at(2)), None, "seen late");
729        clock.complete(late.sequence, at(35), true);
730        assert!(
731            clock
732                .record(at(40), None, Vec::new(), true)
733                .previous
734                .is_none()
735        );
736    }
737
738    #[test]
739    fn the_oldest_kept_submission_does_not_count_its_wait_behind_a_forgotten_one() {
740        let clock = SubmissionClock::default();
741        let start = Instant::now();
742        let at = |ms: u64| start + Duration::from_millis(ms);
743        let submitted = u64::try_from(RECENT_SUBMISSIONS_KEPT).expect("fits") + 9;
744        let sequences: Vec<u64> = (0..submitted)
745            .map(|_| clock.record(at(0), None, Vec::new(), false).sequence)
746            .collect();
747        for (finished, sequence) in (1..).zip(&sequences) {
748            clock.complete(*sequence, at(10 * finished), true);
749        }
750        let longest = clock.longest_at(at(10 * submitted + 1)).expect("kept");
751        assert!(
752            (longest.gpu_ms - 10.0).abs() < 0.5,
753            "every submission ran 10 ms: {longest:?}"
754        );
755    }
756
757    #[test]
758    fn a_submission_kept_after_forgotten_ones_starts_where_the_last_forgotten_one_completed() {
759        let clock = SubmissionClock::default();
760        let start = Instant::now();
761        let at = |ms: u64| start + Duration::from_millis(ms);
762        let submitted = u64::try_from(RECENT_SUBMISSIONS_KEPT).expect("fits") + 9;
763        let mut previous = None;
764        for finished in 1..=submitted {
765            let sequence = clock.record(at(0), None, Vec::new(), false).sequence;
766            if let Some(previous) = previous.replace(sequence) {
767                clock.complete(previous, at(10 * (finished - 1)), true);
768            }
769        }
770        clock.complete(previous.expect("recorded"), at(10 * submitted), true);
771        let longest = clock.longest_at(at(10 * submitted + 1)).expect("kept");
772        assert!(
773            (longest.gpu_ms - 10.0).abs() < 0.5,
774            "every submission ran 10 ms: {longest:?}"
775        );
776        assert_eq!(clock.state().entries.len(), RECENT_SUBMISSIONS_KEPT);
777    }
778
779    #[test]
780    fn a_running_submission_is_still_named_however_many_were_submitted_behind_it() {
781        let clock = SubmissionClock::default();
782        let start = Instant::now();
783        let at = |ms: u64| start + Duration::from_millis(ms);
784        clock.mark_frame(Some(FrameMark {
785            time_ticks: 28_000,
786            frame_index: Some(7),
787        }));
788        let long = clock
789            .record(at(0), Some(100.0), vec!["blur@2".to_owned()], false)
790            .sequence;
791        clock.mark_frame(Some(FrameMark {
792            time_ticks: 32_000,
793            frame_index: Some(8),
794        }));
795        let mut last = long;
796        for _ in 0..RECENT_SUBMISSIONS_KEPT {
797            last = clock.record(at(1), Some(100.0), Vec::new(), false).sequence;
798        }
799        let running = clock.longest_at(at(3_000)).expect("kept");
800        assert_eq!(
801            running.frame.and_then(|frame| frame.frame_index),
802            Some(7),
803            "{running:?}"
804        );
805        for sequence in long..=last {
806            clock.complete(sequence, at(3_000), false);
807        }
808        let report = clock.longest_at(at(3_001)).expect("kept");
809        assert_eq!(
810            report.frame.and_then(|frame| frame.frame_index),
811            Some(7),
812            "{report:?}"
813        );
814        assert_eq!(report.effects, ["blur@2"]);
815        assert!((report.gpu_ms - 3_000.0).abs() < 0.5, "{report:?}");
816    }
817
818    #[test]
819    fn draws_read_after_the_frame_behind_them_are_kept_however_many_submissions_it_makes() {
820        let clock = SubmissionClock::default();
821        let start = Instant::now();
822        let at = |ms: u64| start + Duration::from_millis(ms);
823        let first = clock.record(at(0), None, Vec::new(), false).sequence;
824        let second = clock.record(at(0), None, Vec::new(), false).sequence;
825        for _ in 0..RECENT_SUBMISSIONS_KEPT {
826            let _ = clock.record(at(1), Some(1.0), Vec::new(), false);
827        }
828        clock.complete(first, at(5), false);
829        clock.complete(second, at(10), false);
830        let total = clock.gpu_ms(first..second + 1);
831        assert!(
832            total.is_some_and(|ms| (ms - 10.0).abs() < 0.5),
833            "the draws ran 10 ms: {total:?}"
834        );
835    }
836
837    #[test]
838    fn past_the_memory_cap_the_oldest_submission_is_forgotten_even_while_it_runs() {
839        let clock = SubmissionClock::default();
840        let start = Instant::now();
841        for _ in 0..=MOST_SUBMISSIONS_KEPT {
842            let _ = clock.record(start, None, Vec::new(), false);
843        }
844        let state = clock.state();
845        assert_eq!(state.entries.len(), MOST_SUBMISSIONS_KEPT);
846        assert_eq!(state.first, 1);
847    }
848
849    #[test]
850    fn submissions_completed_together_are_one_group_judged_against_their_prediction() {
851        let clock = SubmissionClock::default();
852        let start = Instant::now();
853        let at = |ms: u64| start + Duration::from_millis(ms);
854        let sequences: Vec<u64> = (0..10)
855            .map(|_| clock.record(at(0), Some(100.0), Vec::new(), false).sequence)
856            .collect();
857        for sequence in &sequences {
858            clock.complete(*sequence, at(1_000), *sequence == sequences[9]);
859        }
860        let report = clock.longest_at(at(1_001)).expect("kept");
861        assert_eq!(report.submissions, 10, "{report:?}");
862        assert!((report.gpu_ms - 1_000.0).abs() < 0.5, "{report:?}");
863        assert_eq!(report.predicted_ms, Some(1_000.0));
864        assert_eq!(clock.hung_at(at(1_001), 1_000.0), None);
865        let late: Vec<u64> = (0..10)
866            .map(|_| {
867                clock
868                    .record(at(1_000), Some(100.0), Vec::new(), false)
869                    .sequence
870            })
871            .collect();
872        for sequence in &late {
873            clock.complete(*sequence, at(3_001), false);
874        }
875        let hung = clock
876            .hung_at(at(3_002), 1_000.0)
877            .expect("past twice its prediction");
878        assert_eq!(hung.submissions, 10, "{hung:?}");
879        assert!((hung.gpu_ms - 2_001.0).abs() < 0.5, "{hung:?}");
880    }
881
882    #[test]
883    fn a_submission_timed_on_its_own_is_hung_at_the_threshold_whatever_its_prediction() {
884        let clock = SubmissionClock::default();
885        let start = Instant::now();
886        let at = |ms: u64| start + Duration::from_millis(ms);
887        let alone = clock.record(at(0), Some(900.0), Vec::new(), false).sequence;
888        clock.complete(alone, at(1_000), true);
889        let hung = clock.hung_at(at(1_001), 1_000.0).expect("hung");
890        assert_eq!(hung.submissions, 1, "{hung:?}");
891        assert_eq!(clock.hung_at(at(1_001), 1_001.0), None);
892    }
893
894    #[test]
895    fn submissions_completed_together_without_a_prediction_are_hung_at_the_threshold() {
896        let clock = SubmissionClock::default();
897        let start = Instant::now();
898        let at = |ms: u64| start + Duration::from_millis(ms);
899        let first = clock.record(at(0), None, Vec::new(), false).sequence;
900        let second = clock.record(at(0), None, Vec::new(), false).sequence;
901        clock.complete(first, at(1_000), false);
902        clock.complete(second, at(1_000), false);
903        let hung = clock.hung_at(at(1_001), 1_000.0).expect("hung");
904        assert_eq!(hung.submissions, 2, "{hung:?}");
905    }
906
907    #[test]
908    fn completions_seen_after_a_later_submit_or_as_they_happened_are_not_grouped() {
909        let clock = SubmissionClock::default();
910        let start = Instant::now();
911        let at = |ms: u64| start + Duration::from_millis(ms);
912        let first = clock.record(at(0), Some(1.0), Vec::new(), false).sequence;
913        let second = clock.record(at(0), Some(1.0), Vec::new(), false).sequence;
914        clock.complete(first, at(400), true);
915        clock.complete(second, at(400), false);
916        let third = clock.record(at(0), Some(1.0), Vec::new(), false).sequence;
917        let fourth = clock.record(at(401), Some(1.0), Vec::new(), false).sequence;
918        clock.complete(third, at(402), false);
919        let _ = clock.record(at(403), Some(1.0), Vec::new(), false);
920        clock.complete(fourth, at(1_402), false);
921        let report = clock.longest_at(at(1_403)).expect("kept");
922        assert_eq!(report.submissions, 1, "{report:?}");
923        assert!((report.gpu_ms - 1_000.0).abs() < 0.5, "{report:?}");
924        assert!(clock.hung_at(at(1_403), 1_000.0).is_some());
925    }
926
927    #[test]
928    fn a_group_of_completions_is_forgotten_whole_once_enough_later_submissions_are_kept() {
929        let clock = SubmissionClock::default();
930        let start = Instant::now();
931        let at = |ms: u64| start + Duration::from_millis(ms);
932        let together = RECENT_SUBMISSIONS_KEPT + 44;
933        let sequences: Vec<u64> = (0..together)
934            .map(|_| clock.record(at(0), Some(1.0), Vec::new(), false).sequence)
935            .collect();
936        for sequence in &sequences {
937            clock.complete(*sequence, at(5_000), false);
938        }
939        for later in 1..RECENT_SUBMISSIONS_KEPT {
940            let sequence = clock.record(at(5_000), None, Vec::new(), false).sequence;
941            clock.complete(sequence, at(5_000), true);
942            assert_eq!(clock.state().entries.len(), together + later);
943        }
944        let report = clock.longest_at(at(5_001)).expect("kept");
945        assert_eq!(
946            report.submissions,
947            u32::try_from(together).expect("fits"),
948            "{report:?}"
949        );
950        let _ = clock.record(at(5_000), None, Vec::new(), false);
951        assert_eq!(clock.state().entries.len(), RECENT_SUBMISSIONS_KEPT);
952    }
953
954    #[test]
955    fn a_time_is_measured_only_between_completions_seen_as_they_happened() {
956        let clock = SubmissionClock::default();
957        let start = Instant::now();
958        let at = |ms: u64| start + Duration::from_millis(ms);
959        let seen = clock.record(at(0), None, Vec::new(), false).sequence;
960        let late = clock.record(at(0), None, Vec::new(), false).sequence;
961        clock.complete(seen, at(100), true);
962        clock.complete(late, at(300), false);
963        let late_report = clock.longest_at(at(301)).expect("kept");
964        assert!(!late_report.measured, "{late_report:?}");
965        assert!((late_report.gpu_ms - 200.0).abs() < 0.5, "{late_report:?}");
966        let after_late = clock.record(at(250), None, Vec::new(), false).sequence;
967        clock.complete(after_late, at(700), true);
968        let report = clock.longest_at(at(701)).expect("kept");
969        assert!((report.gpu_ms - 400.0).abs() < 0.5, "{report:?}");
970        assert!(
971            !report.measured,
972            "it starts at a completion seen late: {report:?}"
973        );
974        let idle = clock.record(at(800), None, Vec::new(), false).sequence;
975        clock.complete(idle, at(1_400), true);
976        let report = clock.longest_at(at(1_401)).expect("kept");
977        assert!((report.gpu_ms - 600.0).abs() < 0.5, "{report:?}");
978        assert!(report.measured, "{report:?}");
979    }
980}