Skip to main content

usbdac_core/
feedback_diagnostics.rs

1//! Bounded evidence from a stream's dedicated USB feedback endpoint.
2
3use parking_lot::Mutex;
4use std::collections::VecDeque;
5use std::fmt;
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::time::Instant;
8
9const STARTUP_ENTRIES: usize = 128;
10const RECENT_ENTRIES: usize = 2_048;
11const UNDERRUN_STARTUP_ENTRIES: usize = 16;
12const UNDERRUN_RECENT_ENTRIES: usize = 64;
13
14/// What happened to a packet while it was examined for explicit feedback.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16#[non_exhaustive]
17pub enum ExplicitFeedbackOutcome {
18    Valid,
19    Empty,
20    TransferFailed,
21    PacketFailed,
22    InvalidLength,
23    InvalidEncoding,
24    RateOutOfRange,
25    PacketCapacityExceeded,
26    TimebaseCandidate,
27}
28
29impl ExplicitFeedbackOutcome {
30    pub fn code(self) -> &'static str {
31        match self {
32            Self::Valid => "valid",
33            Self::Empty => "empty",
34            Self::TransferFailed => "transfer_failed",
35            Self::PacketFailed => "packet_failed",
36            Self::InvalidLength => "invalid_length",
37            Self::InvalidEncoding => "invalid_encoding",
38            Self::RateOutOfRange => "rate_out_of_range",
39            Self::PacketCapacityExceeded => "packet_capacity_exceeded",
40            Self::TimebaseCandidate => "timebase_candidate",
41        }
42    }
43
44    fn index(self) -> usize {
45        match self {
46            Self::Valid => 0,
47            Self::Empty => 1,
48            Self::TransferFailed => 2,
49            Self::PacketFailed => 3,
50            Self::InvalidLength => 4,
51            Self::InvalidEncoding => 5,
52            Self::RateOutOfRange => 6,
53            Self::PacketCapacityExceeded => 7,
54            Self::TimebaseCandidate => 8,
55        }
56    }
57}
58
59/// The most recent packet observed for one feedback outcome.
60#[derive(Debug, Clone, Copy, PartialEq)]
61#[non_exhaustive]
62pub struct ExplicitFeedbackPacket {
63    pub outcome: ExplicitFeedbackOutcome,
64    pub transfer_status: i32,
65    /// The libusb packet status, or `None` when no packet status was reported.
66    pub packet_status: Option<i32>,
67    pub requested_bytes: usize,
68    pub actual_bytes: usize,
69    pub frames_per_out_service: Option<f64>,
70    pub decoded_rate_hz: Option<f64>,
71    bytes: [u8; 8],
72    byte_count: usize,
73}
74
75impl ExplicitFeedbackPacket {
76    #[allow(clippy::too_many_arguments)]
77    pub(crate) fn new(
78        outcome: ExplicitFeedbackOutcome,
79        transfer_status: i32,
80        packet_status: Option<i32>,
81        requested_bytes: usize,
82        actual_bytes: usize,
83        raw_bytes: &[u8],
84        decoded: Option<(f64, f64)>,
85    ) -> Self {
86        let mut bytes = [0; 8];
87        let byte_count = raw_bytes.len().min(bytes.len());
88        bytes[..byte_count].copy_from_slice(&raw_bytes[..byte_count]);
89        Self {
90            outcome,
91            transfer_status,
92            packet_status,
93            requested_bytes,
94            actual_bytes,
95            frames_per_out_service: decoded.map(|(frames, _)| frames),
96            decoded_rate_hz: decoded.map(|(_, rate)| rate),
97            bytes,
98            byte_count,
99        }
100    }
101
102    /// Up to eight bytes from the feedback IN endpoint. No audio OUT payload.
103    pub fn raw_bytes(&self) -> &[u8] {
104        &self.bytes[..self.byte_count]
105    }
106}
107
108/// Feedback endpoint geometry and observations for one stream. Status counts
109/// are indexed by libusb transfer status (0 completed, 1 error, 2 timed out,
110/// 3 cancelled, 4 stall, 5 no device, 6 overflow). Index 7 is unknown or
111/// unreported. An interrupt transfer has no separate packet status.
112#[derive(Debug, Default, Clone, Copy, PartialEq)]
113#[non_exhaustive]
114pub struct ExplicitFeedbackDiagnostics {
115    pub endpoint: u8,
116    pub transfer_type: &'static str,
117    pub link_speed: &'static str,
118    pub interface_number: u8,
119    pub alt_setting: u8,
120    pub out_endpoint: u8,
121    pub nominal_rate_hz: u32,
122    pub out_service_interval_us: u32,
123    pub out_max_packet_bytes: usize,
124    pub out_bytes_per_frame: usize,
125    pub feedback_interval: u8,
126    pub feedback_refresh: u8,
127    pub feedback_service_interval_us: u32,
128    pub feedback_max_packet_bytes: usize,
129    pub requested_packet_bytes: usize,
130    pub transfer_slots: usize,
131    pub packets_per_transfer: usize,
132    pub transfer_timeout_ms: u32,
133    pub per_service_interval_quirk: bool,
134    pub post_alt_readback_hz: Option<u32>,
135    pub timebase: Option<&'static str>,
136    pub inferred_timebase: bool,
137    /// The current stream validated units already learned on this DAC session.
138    pub reused_timebase: bool,
139    pub successful_submissions: u64,
140    pub submit_failures: u64,
141    /// libusb submission error code, separate from completion status.
142    pub last_submit_error: Option<i32>,
143    pub transfer_status_counts: [u64; 8],
144    pub packet_status_counts: [u64; 8],
145    pub accepted_reports: u64,
146    /// Accepted unsmoothed observations, in frames per OUT service interval.
147    pub rate_samples: u64,
148    pub rate_min_frames: f64,
149    pub rate_max_frames: f64,
150    pub rate_mean_frames: f64,
151    /// Population variance before the configured timing policy. No audible
152    /// smoothing tradeoff is inferred.
153    pub rate_variance_frames: f64,
154    pub empty_polls: u64,
155    pub rejected_reports: u64,
156    pub(crate) samples: [Option<ExplicitFeedbackPacket>; 9],
157}
158
159impl ExplicitFeedbackDiagnostics {
160    /// One latest observation per outcome, including bytes from rejected reports.
161    pub fn packet_samples(&self) -> impl Iterator<Item = &ExplicitFeedbackPacket> {
162        self.samples.iter().flatten()
163    }
164
165    pub(crate) fn record_submit(&mut self, result: i32) {
166        if result == 0 {
167            self.successful_submissions = self.successful_submissions.saturating_add(1);
168        } else {
169            self.submit_failures = self.submit_failures.saturating_add(1);
170            self.last_submit_error = Some(result);
171        }
172    }
173
174    fn count_status(counts: &mut [u64; 8], status: Option<i32>) {
175        let index = match status {
176            Some(code @ 0..=6) => code as usize,
177            _ => 7,
178        };
179        counts[index] = counts[index].saturating_add(1);
180    }
181
182    pub(crate) fn record_transfer(&mut self, status: i32) {
183        Self::count_status(&mut self.transfer_status_counts, Some(status));
184    }
185
186    pub(crate) fn record_packet(&mut self, sample: ExplicitFeedbackPacket, is_iso: bool) {
187        if is_iso {
188            Self::count_status(&mut self.packet_status_counts, sample.packet_status);
189        }
190        let slot = &mut self.samples[sample.outcome.index()];
191        // On a transfer error preserve any observed payload in preference to
192        // a following descriptor with no bytes.
193        if sample.outcome != ExplicitFeedbackOutcome::TransferFailed
194            || sample.actual_bytes > 0
195            || slot.map_or(true, |previous| previous.actual_bytes == 0)
196        {
197            *slot = Some(sample);
198        }
199    }
200}
201
202/// An observation from the selected USB feedback path.
203#[derive(Debug, Clone, Copy, PartialEq)]
204#[non_exhaustive]
205pub enum FeedbackTraceEvent {
206    Submit {
207        slot: Option<usize>,
208        status: i32,
209    },
210    Completion {
211        slot: Option<usize>,
212        status: i32,
213        actual_bytes: usize,
214    },
215    ExplicitPacket {
216        index: usize,
217        sample: ExplicitFeedbackPacket,
218    },
219    ImplicitSource {
220        interface_number: u8,
221        alt_setting: u8,
222        endpoint: u8,
223        service_interval_us: u32,
224        max_packet_bytes: usize,
225        bytes_per_frame: usize,
226    },
227    ImplicitPacket {
228        index: usize,
229        status: i32,
230        requested_bytes: usize,
231        actual_bytes: usize,
232    },
233    Lock {
234        locked: bool,
235        stale: bool,
236    },
237    Timebase {
238        unit: &'static str,
239        inferred: bool,
240    },
241    /// Selected policy, retained before the first explicit report arrives.
242    ExplicitFeedbackPolicy {
243        smoothing: crate::FeedbackSmoothing,
244    },
245    /// The validated selected report and the actual fractional scheduling rate.
246    /// Raw feedback statistics remain independent of the configured filter.
247    ExplicitFeedbackRate {
248        smoothing: crate::FeedbackSmoothing,
249        reported_frames_per_out_service: f64,
250        applied_frames_per_out_service: f64,
251        applied_rate_hz: f64,
252    },
253    CompatibilityFallback {
254        tier: crate::CompatibilityFallbackTier,
255        reason: &'static str,
256    },
257    /// Session-local observation only; never a persisted device rule.
258    ClockReadbackSuggestion {
259        control_interface: u8,
260        clock_entity: u8,
261        strikes: u8,
262    },
263}
264
265/// A record in the trace, timed from stream creation using a monotonic clock.
266#[derive(Debug, Clone, Copy, PartialEq)]
267#[non_exhaustive]
268pub struct FeedbackTraceEntry {
269    pub elapsed_us: u64,
270    pub event: FeedbackTraceEvent,
271}
272
273/// A worker-observed transition into or out of an underrun episode.
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275#[non_exhaustive]
276pub enum UnderrunEdgeKind {
277    /// A prepared transfer first required underrun padding.
278    Started,
279    /// A later prepared transfer no longer required underrun padding.
280    Recovered,
281}
282impl UnderrunEdgeKind {
283    pub fn code(self) -> &'static str {
284        match self {
285            Self::Started => "started",
286            Self::Recovered => "recovered",
287        }
288    }
289}
290
291/// Relaxed atomic snapshots taken at the observed worker edge, after preparing the transfer.
292/// `elapsed_us` shares the exact origin of the enclosing feedback trace. Sample counts
293/// are interleaved ring samples; frame counters use the stream's native counter rate.
294#[derive(Debug, Clone, Copy, PartialEq, Eq)]
295pub struct UnderrunEdge {
296    pub elapsed_us: u64,
297    pub kind: UnderrunEdgeKind,
298    pub underrun_transfers: u64,
299    pub buffered_samples: usize,
300    pub capacity_samples: usize,
301    pub channels: usize,
302    pub producer_frames: u64,
303    pub played_frames: u64,
304    pub inflight_frames: u64,
305    pub flush_epoch: u64,
306    pub transfer_queue_depth: usize,
307}
308
309/// Evidence of an isochronous OUT submit failure or its one retry. The slot
310/// and generation pair joins both attempts within the same stream.
311#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
312#[non_exhaustive]
313pub struct IsoSubmitIncident {
314    pub elapsed_us: u64,
315    pub interface_number: u8,
316    pub alt_setting: u8,
317    pub endpoint_address: u8,
318    pub slot: usize,
319    pub generation: u64,
320    pub attempt: u8,
321    pub libusb_status: Option<i32>,
322    /// Unmodified backend diagnostic, if emitted for this exact submit.
323    pub native_error: Option<String>,
324    pub outcome: &'static str,
325    pub packets: usize,
326    pub service_interval_us: u32,
327    pub queued_slots: usize,
328    pub adaptive_queue_us: u64,
329    pub max_event_pump_elapsed_us: u64,
330    pub max_worker_loop_gap_us: u64,
331    pub lost_frames: u64,
332}
333
334const ISO_SUBMIT_INCIDENTS: usize = 32;
335
336/// A shareable support capture for the most recent stream of a DAC session.
337#[derive(Debug, Clone, PartialEq)]
338#[non_exhaustive]
339pub struct FeedbackTrace {
340    /// In-process monotonic origin shared by feedback entries and underrun edges.
341    /// This instant has no portable UTC representation; compute offsets in-process.
342    pub started_at: Instant,
343    pub format: crate::StreamFormat,
344    pub explicit: Option<ExplicitFeedbackDiagnostics>,
345    pub entries: Vec<FeedbackTraceEntry>,
346    /// Observations overwritten at the retention limit or missed during an export.
347    pub dropped_entries: u64,
348    /// First and recent underrun edges, independently retained from feedback events.
349    pub underrun_edges: Vec<UnderrunEdge>,
350    /// Underrun edges overwritten or missed due to a concurrent snapshot.
351    pub underrun_dropped: u64,
352    pub iso_submit_incidents: Vec<IsoSubmitIncident>,
353    pub iso_submit_dropped: u64,
354    pub failure: Option<String>,
355}
356
357#[derive(Debug)]
358pub(crate) struct FeedbackRecorder {
359    started_at: Instant,
360    dropped: AtomicU64,
361    history: Mutex<History>,
362    underrun_dropped: AtomicU64,
363    underruns: Mutex<UnderrunHistory>,
364    iso_submit_dropped: AtomicU64,
365    iso_submits: Mutex<VecDeque<IsoSubmitIncident>>,
366}
367
368#[derive(Debug)]
369struct History {
370    startup: Vec<FeedbackTraceEntry>,
371    recent: VecDeque<FeedbackTraceEntry>,
372    failure: Option<String>,
373}
374
375#[derive(Debug)]
376struct UnderrunHistory {
377    startup: Vec<UnderrunEdge>,
378    recent: VecDeque<UnderrunEdge>,
379}
380
381impl FeedbackRecorder {
382    pub(crate) fn new(started_at: Instant) -> Self {
383        Self {
384            started_at,
385            dropped: AtomicU64::new(0),
386            underrun_dropped: AtomicU64::new(0),
387            iso_submit_dropped: AtomicU64::new(0),
388            iso_submits: Mutex::new(VecDeque::with_capacity(ISO_SUBMIT_INCIDENTS)),
389            underruns: Mutex::new(UnderrunHistory {
390                startup: Vec::with_capacity(UNDERRUN_STARTUP_ENTRIES),
391                recent: VecDeque::with_capacity(UNDERRUN_RECENT_ENTRIES),
392            }),
393            history: Mutex::new(History {
394                startup: Vec::with_capacity(STARTUP_ENTRIES),
395                recent: VecDeque::with_capacity(RECENT_ENTRIES),
396                failure: None,
397            }),
398        }
399    }
400
401    /// Preserve a bounded, deterministic startup snapshot before recent traffic
402    /// can overwrite it. A closed stream's exported trace retains these facts.
403    pub(crate) fn record_clock_readback_suggestions(
404        &self,
405        suggestions: impl IntoIterator<Item = ((u8, u8), u8)>,
406    ) {
407        let mut suggestions: Vec<_> = suggestions
408            .into_iter()
409            .filter(|(_, strikes)| *strikes >= 3)
410            .collect();
411        suggestions.sort_unstable_by_key(|(identity, _)| *identity);
412        for ((control_interface, clock_entity), strikes) in suggestions.into_iter().take(16) {
413            self.record(FeedbackTraceEvent::ClockReadbackSuggestion {
414                control_interface,
415                clock_entity,
416                strikes,
417            });
418        }
419    }
420
421    pub(crate) fn record(&self, event: FeedbackTraceEvent) {
422        self.record_at(Instant::now(), event);
423    }
424
425    pub(crate) fn record_at(&self, timestamp: Instant, event: FeedbackTraceEvent) {
426        let Some(mut history) = self.history.try_lock() else {
427            self.dropped.fetch_add(1, Ordering::Relaxed);
428            return;
429        };
430        let entry = FeedbackTraceEntry {
431            elapsed_us: timestamp
432                .saturating_duration_since(self.started_at)
433                .as_micros()
434                .min(u128::from(u64::MAX)) as u64,
435            event,
436        };
437        if history.startup.len() < STARTUP_ENTRIES {
438            history.startup.push(entry);
439        } else {
440            if history.recent.len() == RECENT_ENTRIES {
441                history.recent.pop_front();
442                self.dropped.fetch_add(1, Ordering::Relaxed);
443            }
444            history.recent.push_back(entry);
445        }
446    }
447
448    /// Try to retain an edge without blocking or allocating on the USB worker.
449    pub(crate) fn record_underrun_at(&self, timestamp: Instant, mut edge: UnderrunEdge) {
450        edge.elapsed_us = timestamp
451            .saturating_duration_since(self.started_at)
452            .as_micros()
453            .min(u128::from(u64::MAX)) as u64;
454        let Some(mut history) = self.underruns.try_lock() else {
455            self.underrun_dropped.fetch_add(1, Ordering::Relaxed);
456            return;
457        };
458        if history.startup.len() < UNDERRUN_STARTUP_ENTRIES {
459            history.startup.push(edge);
460        } else {
461            if history.recent.len() == UNDERRUN_RECENT_ENTRIES {
462                history.recent.pop_front();
463                self.underrun_dropped.fetch_add(1, Ordering::Relaxed);
464            }
465            history.recent.push_back(edge);
466        }
467    }
468
469    pub(crate) fn underrun_snapshot(&self) -> (Vec<UnderrunEdge>, u64) {
470        let history = self.underruns.lock();
471        (
472            history
473                .startup
474                .iter()
475                .chain(&history.recent)
476                .copied()
477                .collect(),
478            self.underrun_dropped.load(Ordering::Relaxed),
479        )
480    }
481
482    pub(crate) fn record_iso_submit(&self, mut incident: IsoSubmitIncident) {
483        incident.elapsed_us = Instant::now()
484            .saturating_duration_since(self.started_at)
485            .as_micros()
486            .min(u128::from(u64::MAX)) as u64;
487        let Some(mut entries) = self.iso_submits.try_lock() else {
488            self.iso_submit_dropped.fetch_add(1, Ordering::Relaxed);
489            return;
490        };
491        if entries.len() == ISO_SUBMIT_INCIDENTS {
492            entries.pop_front();
493            self.iso_submit_dropped.fetch_add(1, Ordering::Relaxed);
494        }
495        entries.push_back(incident);
496    }
497
498    pub(crate) fn fail(&self, reason: &str) {
499        self.history.lock().failure = Some(reason.to_owned());
500    }
501
502    pub(crate) fn snapshot(
503        &self,
504        format: crate::StreamFormat,
505        explicit: Option<ExplicitFeedbackDiagnostics>,
506    ) -> FeedbackTrace {
507        let history = self.history.lock();
508        let (underrun_edges, underrun_dropped) = self.underrun_snapshot();
509        FeedbackTrace {
510            started_at: self.started_at,
511            format,
512            explicit,
513            entries: history
514                .startup
515                .iter()
516                .chain(&history.recent)
517                .copied()
518                .collect(),
519            dropped_entries: self.dropped.load(Ordering::Relaxed),
520            underrun_edges,
521            underrun_dropped,
522            iso_submit_incidents: self.iso_submits.lock().iter().cloned().collect(),
523            iso_submit_dropped: self.iso_submit_dropped.load(Ordering::Relaxed),
524            failure: history.failure.clone(),
525        }
526    }
527}
528
529impl fmt::Display for ExplicitFeedbackDiagnostics {
530    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
531        write!(
532            f,
533            concat!(
534                "feedback ep=0x{:02x} {} {} if={} alt={} bInterval={} refresh={} poll={}us ",
535                "request={}B x{} slots={} descriptor={}B timeout={}ms out=0x{:02x} {}us ",
536                "capacity={}B stride={}B nominal={}Hz clock_readback={:?} ",
537                "timebase={:?} inferred={} reused={} per_service_quirk={} ",
538                "submits={} submit_failures={} last_submit_error={:?} ",
539                "transfer_statuses={:?} packet_statuses={:?} accepted={} empty={} rejected={}"
540            ),
541            self.endpoint,
542            self.transfer_type,
543            self.link_speed,
544            self.interface_number,
545            self.alt_setting,
546            self.feedback_interval,
547            self.feedback_refresh,
548            self.feedback_service_interval_us,
549            self.requested_packet_bytes,
550            self.packets_per_transfer,
551            self.transfer_slots,
552            self.feedback_max_packet_bytes,
553            self.transfer_timeout_ms,
554            self.out_endpoint,
555            self.out_service_interval_us,
556            self.out_max_packet_bytes,
557            self.out_bytes_per_frame,
558            self.nominal_rate_hz,
559            self.post_alt_readback_hz,
560            self.timebase,
561            self.inferred_timebase,
562            self.reused_timebase,
563            self.per_service_interval_quirk,
564            self.successful_submissions,
565            self.submit_failures,
566            self.last_submit_error,
567            self.transfer_status_counts,
568            self.packet_status_counts,
569            self.accepted_reports,
570            self.empty_polls,
571            self.rejected_reports,
572        )?;
573        for packet in self.packet_samples() {
574            write!(
575                f,
576                " {}(transfer={} packet={:?} bytes={}/{} raw={:02x?} rate={:?} frames={:?})",
577                packet.outcome.code(),
578                packet.transfer_status,
579                packet.packet_status,
580                packet.actual_bytes,
581                packet.requested_bytes,
582                packet.raw_bytes(),
583                packet.decoded_rate_hz,
584                packet.frames_per_out_service,
585            )?;
586        }
587        Ok(())
588    }
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594
595    fn edge() -> UnderrunEdge {
596        UnderrunEdge {
597            elapsed_us: 0,
598            kind: UnderrunEdgeKind::Started,
599            underrun_transfers: 1,
600            buffered_samples: 4,
601            capacity_samples: 100,
602            channels: 2,
603            producer_frames: 8,
604            played_frames: 4,
605            inflight_frames: 2,
606            flush_epoch: 0,
607            transfer_queue_depth: 3,
608        }
609    }
610    #[test]
611    fn underrun_history_has_independent_bounded_first_and_recent_edges() {
612        let start = Instant::now();
613        let recorder = FeedbackRecorder::new(start);
614        for n in 0..(STARTUP_ENTRIES + RECENT_ENTRIES + 5) {
615            recorder.record_at(
616                start + std::time::Duration::from_micros(n as u64),
617                FeedbackTraceEvent::Submit {
618                    slot: None,
619                    status: 0,
620                },
621            );
622        }
623        let count = UNDERRUN_STARTUP_ENTRIES + UNDERRUN_RECENT_ENTRIES + 3;
624        for n in 0..count {
625            recorder.record_underrun_at(start + std::time::Duration::from_micros(n as u64), edge());
626        }
627        let (events, dropped) = recorder.underrun_snapshot();
628        assert_eq!(
629            events.len(),
630            UNDERRUN_STARTUP_ENTRIES + UNDERRUN_RECENT_ENTRIES
631        );
632        assert_eq!(events[0].elapsed_us, 0);
633        assert_eq!(
634            events[UNDERRUN_STARTUP_ENTRIES].elapsed_us,
635            (UNDERRUN_STARTUP_ENTRIES + 3) as u64
636        );
637        assert_eq!(events.last().unwrap().elapsed_us, (count - 1) as u64);
638        assert_eq!(dropped, 3);
639        assert_eq!(recorder.dropped.load(Ordering::Relaxed), 5);
640        let held = recorder.underruns.lock();
641        recorder.record_underrun_at(start, edge());
642        drop(held);
643        assert_eq!(recorder.underrun_snapshot().1, 4);
644    }
645
646    #[test]
647    fn preserves_startup_and_latest_observations_with_bounded_storage() {
648        let start = Instant::now();
649        let recorder = FeedbackRecorder::new(start);
650        let total = STARTUP_ENTRIES + RECENT_ENTRIES + 5;
651        for n in 0..total {
652            recorder.record_at(
653                start + std::time::Duration::from_micros(n as u64),
654                FeedbackTraceEvent::Submit {
655                    slot: None,
656                    status: 0,
657                },
658            );
659        }
660        recorder.fail("feedback deadline");
661        let history = recorder.history.lock();
662        assert_eq!(history.startup.len(), STARTUP_ENTRIES);
663        assert_eq!(history.startup[0].elapsed_us, 0);
664        assert_eq!(history.recent.len(), RECENT_ENTRIES);
665        assert_eq!(
666            history.recent.front().unwrap().elapsed_us,
667            (STARTUP_ENTRIES + 5) as u64
668        );
669        assert_eq!(
670            history.recent.back().unwrap().elapsed_us,
671            (total - 1) as u64
672        );
673        assert_eq!(recorder.dropped.load(Ordering::Relaxed), 5);
674        assert_eq!(history.failure.as_deref(), Some("feedback deadline"));
675    }
676}
677
678#[cfg(test)]
679mod compatibility_suggestion_trace_tests {
680    use super::*;
681    #[test]
682    fn three_strike_suggestions_stay_bounded_and_survive_recent_history_overwrite() {
683        let recorder = FeedbackRecorder::new(Instant::now());
684        let events = crate::events::EventHub::start();
685        crate::events::CompatibilityAdmissions::new(false, true, true, false, None).publish(
686            true,
687            &events,
688            Some(&recorder),
689        );
690        events.shutdown();
691        let suggestions = (0..32u8).map(|interface| ((interface, 7), 3));
692        recorder.record_clock_readback_suggestions(suggestions.chain([((99, 1), 2)]));
693        for _ in 0..(STARTUP_ENTRIES + RECENT_ENTRIES + 8) {
694            recorder.record(FeedbackTraceEvent::Lock {
695                locked: true,
696                stale: false,
697            });
698        }
699        let history = recorder.history.lock();
700        let suggestions: Vec<_> = history
701            .startup
702            .iter()
703            .filter_map(|entry| match entry.event {
704                FeedbackTraceEvent::ClockReadbackSuggestion {
705                    control_interface,
706                    clock_entity,
707                    strikes,
708                } => Some((control_interface, clock_entity, strikes)),
709                _ => None,
710            })
711            .collect();
712        assert_eq!(
713            suggestions,
714            (0..16u8)
715                .map(|interface| (interface, 7, 3))
716                .collect::<Vec<_>>()
717        );
718        assert!(history.startup.iter().any(|entry|matches!(entry.event,
719            FeedbackTraceEvent::CompatibilityFallback {tier:crate::CompatibilityFallbackTier::UnverifiedClock,reason} if !reason.is_empty())));
720    }
721}