Skip to main content

alpha2_render/
submission_clock.rs

1//! How long each recent renderer submission 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`].
8
9use std::cell::Cell;
10use std::collections::VecDeque;
11use std::sync::{Arc, Mutex};
12
13use web_time::Instant;
14
15/// Submissions kept; enough to cover the last frames' submissions.
16const KEPT: usize = 4 * crate::submission_planner::MAX_BANDS as usize;
17
18/// The frame a submission belongs to, as its caller knows it.
19#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
20pub struct FrameMark {
21    /// The frame's timeline time, in ticks.
22    pub time_ticks: i64,
23    /// The frame's index in the export, when it is one.
24    pub frame_index: Option<u64>,
25}
26
27/// The longest recent submission and what it rendered.
28#[derive(Clone, Debug, PartialEq)]
29pub struct SubmissionReport {
30    /// GPU time in milliseconds; for one still running, the time so far.
31    pub gpu_ms: f64,
32    /// The frame it rendered, when the caller marked one.
33    pub frame: Option<FrameMark>,
34    /// The effects it ran, as `id@version`.
35    pub effects: Vec<String>,
36    /// Predicted GPU time in milliseconds, when the frame was planned.
37    pub predicted_ms: Option<f64>,
38}
39
40#[derive(Debug)]
41struct Entry {
42    submitted_at: Instant,
43    done_at: Option<Instant>,
44    frame: Option<FrameMark>,
45    effects: Vec<String>,
46    predicted_ms: Option<f64>,
47}
48
49#[derive(Debug, Default)]
50struct ClockState {
51    /// Sequence number of `entries[0]`.
52    first: u64,
53    recorded: u64,
54    completed: u64,
55    watched: Vec<(u64, PreviousCompletion)>,
56    entries: VecDeque<Entry>,
57    frame: Option<FrameMark>,
58    effects: Vec<String>,
59}
60
61/// The renderer's recent submissions and when each finished.
62#[derive(Debug, Default)]
63pub(crate) struct SubmissionClock {
64    state: Mutex<ClockState>,
65}
66
67impl SubmissionClock {
68    fn state(&self) -> std::sync::MutexGuard<'_, ClockState> {
69        self.state
70            .lock()
71            .unwrap_or_else(std::sync::PoisonError::into_inner)
72    }
73
74    /// Marks the frame the next submissions render, until another is marked.
75    pub(crate) fn mark_frame(&self, frame: Option<FrameMark>) {
76        self.state().frame = frame;
77    }
78
79    /// Notes an effect the next submission runs.
80    pub(crate) fn note_effect(&self, effect: &crate::EffectId) {
81        let name = format!("{}@{}", effect.as_str(), effect.version());
82        let mut state = self.state();
83        if !state.effects.contains(&name) {
84            state.effects.push(name);
85        }
86    }
87
88    /// Records a submission made at `at` and returns its sequence number for [`Self::complete`],
89    /// also watching for the completion of the submission before it when `watch_previous` and
90    /// that is still running.
91    pub(crate) fn record(
92        &self,
93        at: Instant,
94        predicted_ms: Option<f64>,
95        watch_previous: bool,
96    ) -> Recorded {
97        let mut state = self.state();
98        let queue_idle = state.completed == state.recorded;
99        let previous = (watch_previous && !queue_idle).then(|| {
100            let watch = PreviousCompletion::default();
101            let sequence = state.recorded - 1;
102            state.watched.push((sequence, watch.clone()));
103            watch
104        });
105        state.recorded += 1;
106        let effects = std::mem::take(&mut state.effects);
107        let frame = state.frame;
108        state.entries.push_back(Entry {
109            submitted_at: at,
110            done_at: None,
111            frame,
112            effects,
113            predicted_ms,
114        });
115        if state.entries.len() > KEPT {
116            state.entries.pop_front();
117            state.first += 1;
118        }
119        Recorded {
120            sequence: state.recorded - 1,
121            queue_idle,
122            previous,
123        }
124    }
125
126    /// Records that submission `sequence` finished at `at`, seen `as_it_happens` or not; the
127    /// queue completes in order, so all earlier ones have too.
128    pub(crate) fn complete(&self, sequence: u64, at: Instant, as_it_happens: bool) {
129        let mut state = self.state();
130        state.completed = state.completed.max(sequence + 1);
131        state.watched.retain(|(watched, completion)| {
132            if *watched > sequence {
133                return true;
134            }
135            completion.set(at, as_it_happens && *watched == sequence);
136            false
137        });
138        let Some(position) = sequence.checked_sub(state.first) else {
139            return;
140        };
141        let Ok(position) = usize::try_from(position) else {
142            return;
143        };
144        for entry in state.entries.iter_mut().take(position + 1) {
145            entry.done_at.get_or_insert(at);
146        }
147    }
148
149    /// Each kept submission's GPU time, oldest first: finished ones in full, the oldest unfinished
150    /// up to `now`, later unfinished ones not at all.
151    fn spans(state: &ClockState, now: Instant) -> Vec<(f64, &Entry)> {
152        let mut spans = Vec::new();
153        let mut previous_done: Option<Instant> = None;
154        for entry in &state.entries {
155            let start =
156                previous_done.map_or(entry.submitted_at, |done| done.max(entry.submitted_at));
157            let Some(done) = entry.done_at else {
158                spans.push((milliseconds(now.saturating_duration_since(start)), entry));
159                break;
160            };
161            spans.push((milliseconds(done.saturating_duration_since(start)), entry));
162            previous_done = Some(done);
163        }
164        spans
165    }
166
167    /// The kept submission with the longest GPU time, counting a running one up to `now`.
168    pub(crate) fn longest_at(&self, now: Instant) -> Option<SubmissionReport> {
169        let state = self.state();
170        Self::spans(&state, now)
171            .into_iter()
172            .max_by(|(a, _), (b, _)| a.total_cmp(b))
173            .map(|(gpu_ms, entry)| SubmissionReport {
174                gpu_ms,
175                frame: entry.frame,
176                effects: entry.effects.clone(),
177                predicted_ms: entry.predicted_ms,
178            })
179    }
180
181    /// Summed GPU time of `sequences` once all finished and are still kept. Late completions shift
182    /// time between consecutive submissions but not out of the sum, so a frame's total holds.
183    pub(crate) fn gpu_ms(&self, sequences: std::ops::Range<u64>) -> Option<f64> {
184        let state = self.state();
185        let first = state.first;
186        let spans = Self::spans(&state, Instant::now());
187        let mut total = 0.0;
188        let mut counted = 0;
189        for (position, (ms, entry)) in spans.into_iter().enumerate() {
190            let sequence = first + u64::try_from(position).unwrap_or(u64::MAX);
191            if sequences.contains(&sequence) {
192                entry.done_at?;
193                total += ms;
194                counted += 1;
195            }
196        }
197        (counted == sequences.end.saturating_sub(sequences.start)).then_some(total)
198    }
199
200    /// [`Self::longest_at`] now.
201    pub(crate) fn longest(&self) -> Option<SubmissionReport> {
202        self.longest_at(Instant::now())
203    }
204
205    /// The longest recent submission if it ran at least [`alpha2_gpu::hung_threshold_ms`], which
206    /// implicates this renderer's own work in a loss.
207    pub(crate) fn hung(&self) -> Option<SubmissionReport> {
208        self.longest()
209            .filter(|report| report.gpu_ms >= f64::from(alpha2_gpu::hung_threshold_ms()))
210    }
211}
212
213#[derive(Clone, Debug)]
214pub(crate) struct Recorded {
215    pub(crate) sequence: u64,
216    pub(crate) queue_idle: bool,
217    pub(crate) previous: Option<PreviousCompletion>,
218}
219
220impl Recorded {
221    pub(crate) fn started(&self, at: Instant) -> Option<Instant> {
222        if self.queue_idle {
223            return Some(at);
224        }
225        let (done, as_it_happens) = self.previous.as_ref()?.get()?;
226        as_it_happens.then(|| done.max(at))
227    }
228}
229
230#[derive(Clone, Debug, Default)]
231pub(crate) struct PreviousCompletion(Arc<Mutex<Option<(Instant, bool)>>>);
232
233impl PreviousCompletion {
234    fn set(&self, at: Instant, as_it_happens: bool) {
235        *self
236            .0
237            .lock()
238            .unwrap_or_else(std::sync::PoisonError::into_inner) = Some((at, as_it_happens));
239    }
240
241    fn get(&self) -> Option<(Instant, bool)> {
242        *self
243            .0
244            .lock()
245            .unwrap_or_else(std::sync::PoisonError::into_inner)
246    }
247}
248
249thread_local! {
250    static WAITING: Cell<Option<(usize, u64)>> = const { Cell::new(None) };
251}
252
253impl SubmissionClock {
254    fn address(self: &Arc<Self>) -> usize {
255        Arc::as_ptr(self) as usize
256    }
257
258    pub(crate) fn sees_as_it_happens(self: &Arc<Self>, sequence: u64) -> bool {
259        WAITING
260            .get()
261            .is_some_and(|(clock, waited)| clock == self.address() && sequence >= waited)
262    }
263}
264
265#[cfg(not(target_arch = "wasm32"))]
266struct Waiting(Option<(usize, u64)>);
267
268#[cfg(not(target_arch = "wasm32"))]
269impl Waiting {
270    fn on(clock: usize, sequence: u64) -> Self {
271        Self(WAITING.replace(Some((clock, sequence))))
272    }
273}
274
275#[cfg(not(target_arch = "wasm32"))]
276impl Drop for Waiting {
277    fn drop(&mut self) {
278        WAITING.set(self.0);
279    }
280}
281
282#[derive(Clone, Debug)]
283#[cfg_attr(
284    target_arch = "wasm32",
285    expect(dead_code, reason = "a browser cannot wait for a submission")
286)]
287pub(crate) struct ClockedSubmission {
288    pub(crate) index: wgpu::SubmissionIndex,
289    clock: Arc<SubmissionClock>,
290    sequence: u64,
291}
292
293impl ClockedSubmission {
294    pub(crate) const fn new(
295        index: wgpu::SubmissionIndex,
296        clock: Arc<SubmissionClock>,
297        sequence: u64,
298    ) -> Self {
299        Self {
300            index,
301            clock,
302            sequence,
303        }
304    }
305
306    /// # Errors
307    /// [`crate::RenderError::GpuTimeout`] past `timeout`, or
308    /// [`crate::RenderError::TextureReadback`] when polling fails.
309    #[cfg(not(target_arch = "wasm32"))]
310    pub(crate) fn wait(
311        &self,
312        gpu: &alpha2_gpu::GpuContext,
313        timeout: std::time::Duration,
314    ) -> Result<(), crate::RenderError> {
315        gpu.device()
316            .poll(wgpu::PollType::Poll)
317            .map_err(crate::error::poll_error)?;
318        let _waiting = Waiting::on(self.clock.address(), self.sequence);
319        gpu.device()
320            .poll(wgpu::PollType::Wait {
321                submission_index: Some(self.index.clone()),
322                timeout: Some(timeout),
323            })
324            .map_err(crate::error::poll_error)?;
325        Ok(())
326    }
327}
328
329fn milliseconds(duration: std::time::Duration) -> f64 {
330    duration.as_secs_f64() * 1_000.0
331}
332
333#[cfg(test)]
334mod tests {
335    use std::time::Duration;
336
337    use super::*;
338
339    /// Submissions made at once run back to back; each starts where the previous ended.
340    #[test]
341    fn gpu_time_excludes_queueing_behind_earlier_submissions() {
342        let clock = SubmissionClock::default();
343        let start = Instant::now();
344        let at = |ms: u64| start + Duration::from_millis(ms);
345        let first = clock.record(at(0), None, false).sequence;
346        let second = clock.record(at(0), None, false).sequence;
347        let third = clock.record(at(0), None, false).sequence;
348        clock.complete(first, at(10), false);
349        clock.complete(second, at(400), false);
350        clock.complete(third, at(405), false);
351        let longest = clock.longest_at(at(1_000)).expect("submissions");
352        assert!((longest.gpu_ms - 390.0).abs() < 0.5, "{longest:?}");
353        // Submitted after the queue went idle, so it starts at its own submit.
354        let fourth = clock.record(at(2_000), None, false).sequence;
355        clock.complete(fourth, at(2_005), false);
356        assert!((clock.longest_at(at(3_000)).expect("kept").gpu_ms - 390.0).abs() < 0.5);
357        let _ = clock.record(at(3_000), None, false).sequence;
358        assert!((clock.longest_at(at(3_700)).expect("running").gpu_ms - 700.0).abs() < 0.5);
359    }
360
361    #[test]
362    fn a_completion_finishes_every_earlier_submission() {
363        let clock = SubmissionClock::default();
364        let start = Instant::now();
365        let first = clock.record(start, None, false).sequence;
366        let second = clock.record(start, None, false).sequence;
367        clock.complete(second, start + Duration::from_millis(8), false);
368        let _ = first;
369        assert_eq!(
370            clock
371                .longest_at(start + Duration::from_secs(5))
372                .map(|r| r.gpu_ms.round()),
373            Some(8.0)
374        );
375    }
376
377    #[test]
378    fn a_frames_gpu_time_survives_completions_seen_together() {
379        let clock = SubmissionClock::default();
380        let start = Instant::now();
381        let at = |ms: u64| start + Duration::from_millis(ms);
382        let earlier = clock.record(at(0), None, false).sequence;
383        clock.complete(earlier, at(5), false);
384        let first = clock.record(at(10), Some(100.0), false).sequence;
385        let second = clock.record(at(10), Some(100.0), false).sequence;
386        assert_eq!(clock.gpu_ms(first..second + 1), None, "not finished");
387        // Both seen at 210 ms: the first takes the whole span, and the sum is unchanged.
388        clock.complete(second, at(210), false);
389        let total = clock.gpu_ms(first..second + 1).expect("finished");
390        assert!((total - 200.0).abs() < 0.5, "{total}");
391        assert_eq!(
392            clock
393                .longest_at(at(300))
394                .and_then(|report| report.predicted_ms),
395            Some(100.0)
396        );
397    }
398
399    #[test]
400    fn the_clock_keeps_the_frame_and_effects_of_each_submission() {
401        let clock = SubmissionClock::default();
402        let start = Instant::now();
403        clock.mark_frame(Some(FrameMark {
404            time_ticks: 4_000,
405            frame_index: Some(1),
406        }));
407        clock.note_effect(&crate::EffectId::from_static("blur", 2));
408        let heavy = clock.record(start, None, false).sequence;
409        clock.complete(heavy, start + Duration::from_millis(30), false);
410        let light = clock
411            .record(start + Duration::from_millis(40), None, false)
412            .sequence;
413        clock.complete(light, start + Duration::from_millis(41), false);
414        let report = clock
415            .longest_at(start + Duration::from_millis(50))
416            .expect("kept");
417        assert_eq!(report.effects, ["blur@2"]);
418        assert_eq!(report.frame.and_then(|frame| frame.frame_index), Some(1));
419    }
420
421    #[test]
422    fn a_submission_starts_on_an_idle_queue_only_once_every_earlier_one_completed() {
423        let clock = SubmissionClock::default();
424        let start = Instant::now();
425        let first = clock.record(start, None, false);
426        assert!(first.queue_idle);
427        let second = clock.record(start, None, false);
428        assert!(!second.queue_idle);
429        clock.complete(first.sequence, start, false);
430        assert!(!clock.record(start, None, false).queue_idle);
431        clock.complete(second.sequence + 1, start, false);
432        assert!(clock.record(start, None, false).queue_idle);
433    }
434
435    #[test]
436    fn only_completions_inside_a_wait_on_them_or_earlier_ones_are_seen_as_they_happen() {
437        let clock = Arc::new(SubmissionClock::default());
438        let other = Arc::new(SubmissionClock::default());
439        assert!(!clock.sees_as_it_happens(0));
440        WAITING.set(Some((clock.address(), 5)));
441        assert!(!clock.sees_as_it_happens(4));
442        assert!(clock.sees_as_it_happens(5));
443        assert!(clock.sees_as_it_happens(6));
444        assert!(!other.sees_as_it_happens(6));
445        WAITING.set(None);
446    }
447
448    #[test]
449    fn a_frame_behind_a_completion_seen_as_it_happened_starts_at_that_completion() {
450        let clock = SubmissionClock::default();
451        let start = Instant::now();
452        let at = |ms: u64| start + Duration::from_millis(ms);
453        let first = clock.record(at(0), None, false);
454        assert_eq!(first.started(at(0)), Some(at(0)));
455        let behind = clock.record(at(1), None, true);
456        let late = clock.record(at(2), None, true);
457        assert_eq!(behind.started(at(1)), None, "not complete yet");
458        clock.complete(first.sequence, at(10), true);
459        clock.complete(behind.sequence, at(30), false);
460        assert_eq!(behind.started(at(1)), Some(at(10)));
461        assert_eq!(late.started(at(2)), None, "seen late");
462        clock.complete(late.sequence, at(35), true);
463        assert!(clock.record(at(40), None, true).previous.is_none());
464    }
465}