Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

test(recording): make sync-matrix skips and overload tolerance honest

Richie McIlroy43439ceba978
diff --git a/crates/recording/tests/sync_matrix.rs b/crates/recording/tests/sync_matrix.rs
index 7a7e84ad1..674ae7ea4 100644
--- a/crates/recording/tests/sync_matrix.rs
+++ b/crates/recording/tests/sync_matrix.rs
@@ -34,6 +34,10 @@ const CONTENT_SECS: f64 = 4.0;
/// pts). Covers warmup anchoring, emission jitter and encoder rounding,
/// plus scheduler noise on shared CI runners.
const ABS_TOLERANCE_SECS: f64 = 0.25;
+/// The drift tracker deliberately re-pins pts toward the wall clock by up to
+/// this much; heavy over-delivery cases get it as designed headroom on top of
+/// the base tolerance. Keep in step with the tracker's re-pin cap.
+const DRIFT_REPIN_CAP_SECS: f64 = 0.1;
/// Tolerance for the relative structure (pts deltas vs sent deltas), which is
/// what actually determines sync drift. The bug class this guards against
/// produces errors of a second or more.
@@ -256,17 +260,27 @@ async fn run_video_case(case: VideoCase) -> Result<String, String> {
let timestamps = Timestamps::now();
let sent = case.sent.clone();
+ // Set once the pipeline consumer exists. The emitter starts before the
+ // pipeline build so the builder can own the channel receiver; frames
+ // scheduled during the build window back up in the bounded channel and
+ // their lateness is structural, not a runner stall. Only lateness on
+ // frames due after this instant means the runner actually stalled.
+ let built_at: std::sync::Arc<std::sync::OnceLock<std::time::Instant>> =
+ std::sync::Arc::new(std::sync::OnceLock::new());
let emit = {
let sent = sent.clone();
let base = timestamps.instant();
let (width, height, content) = (case.width, case.height, case.content);
let mut rng = Rng(case.rng_seed);
+ let built_at = built_at.clone();
tokio::spawn(async move {
let mut max_late = 0.0f64;
for (i, &ts) in sent.iter().enumerate() {
let due = base + Duration::from_secs_f64(ts);
tokio::time::sleep_until(due.into()).await;
- max_late = max_late.max(due.elapsed().as_secs_f64());
+ if built_at.get().is_some_and(|built| due >= *built) {
+ max_late = max_late.max(due.elapsed().as_secs_f64());
+ }
let frame = FFmpegVideoFrame {
inner: make_video_frame(width, height, i as u64, content, &mut rng),
timestamp: Timestamp::Instant(due),
@@ -295,6 +309,7 @@ async fn run_video_case(case: VideoCase) -> Result<String, String> {
builder.build::<Mp4Muxer>(()).await
}
.map_err(|e| format!("pipeline build: {e}"))?;
+ let _ = built_at.set(std::time::Instant::now());
let max_emit_late = emit.await.map_err(|e| format!("emit join: {e}"))?;
// The verification below assumes frames were emitted in real time; when a
@@ -345,7 +360,7 @@ async fn run_video_case(case: VideoCase) -> Result<String, String> {
// headroom on top of that designed deviation has to be wider.
let over_delivery = f64::from(case.delivered_fps) / f64::from(case.fps.max(1));
let base_rel_tolerance = if over_delivery > 4.0 {
- 0.25
+ REL_TOLERANCE_SECS + DRIFT_REPIN_CAP_SECS
} else {
REL_TOLERANCE_SECS
};
@@ -362,9 +377,11 @@ async fn run_video_case(case: VideoCase) -> Result<String, String> {
let coverage = pts.len() as f64 / sent.len() as f64;
if !overload_case || coverage < 0.9 || pts.len() > sent.len() {
return Err(format!(
- "frame count mismatch: sent {} frames, container has {}",
+ "frame count mismatch: sent {} frames, container has {} \
+ (missing sent indices: {})",
sent.len(),
- pts.len()
+ pts.len(),
+ unmatched_sent_indices(&sent, &pts, 1.0 / f64::from(case.delivered_fps.max(1)))
));
}
@@ -372,6 +389,8 @@ async fn run_video_case(case: VideoCase) -> Result<String, String> {
let pts_origin = pts[0];
let mut max_rel: f64 = 0.0;
let mut j = 0usize;
+ let mut last_matched: Option<usize> = None;
+ let mut reused_matches = 0usize;
for (i, &p) in pts.iter().enumerate() {
let rel_p = p - pts_origin;
while j + 1 < sent.len()
@@ -380,6 +399,15 @@ async fn run_video_case(case: VideoCase) -> Result<String, String> {
{
j += 1;
}
+ // Muxed frames should each consume their own sent timestamp.
+ // Occasional double-maps are nearest-neighbor ambiguity under
+ // jittered over-delivery; MANY frames sharing sent instants is
+ // the burst-clustering failure shape that nearest-matching alone
+ // would score as zero error. Budget, don't forbid.
+ if last_matched == Some(j) {
+ reused_matches += 1;
+ }
+ last_matched = Some(j);
let rel = (rel_p - (sent[j] - sent_origin)).abs();
max_rel = max_rel.max(rel);
if rel > rel_tolerance {
@@ -390,6 +418,41 @@ async fn run_video_case(case: VideoCase) -> Result<String, String> {
));
}
}
+ if reused_matches * 10 > pts.len() {
+ return Err(format!(
+ "{reused_matches} of {} muxed frames share a nearest sent timestamp — \
+ pts clustered under overload",
+ pts.len()
+ ));
+ }
+
+ // Drops shorten coverage but must not shrink the recorded span
+ // beyond the dropped tail/head, and must never stretch it.
+ if let Some((first, last)) = finished.video_timestamp_span {
+ let span = (last - first).as_secs_f64();
+ let expected = sent.last().unwrap() - sent[0];
+ if span > expected + 0.25 || span < expected - 0.5 {
+ return Err(format!(
+ "video_timestamp_span {span:.3}s does not match sent span \
+ {expected:.3}s under overload"
+ ));
+ }
+ } else {
+ return Err("video_timestamp_span missing".to_string());
+ }
+
+ // Gap preservation still holds under drops: dropping frames can only
+ // widen a container gap, so a collapsed gap is a real timestamp bug.
+ let max_sent_gap = sent.windows(2).map(|w| w[1] - w[0]).fold(0.0, f64::max);
+ if max_sent_gap > 1.0 {
+ let max_pts_gap = pts.windows(2).map(|w| w[1] - w[0]).fold(0.0, f64::max);
+ if max_pts_gap < max_sent_gap * 0.9 {
+ return Err(format!(
+ "{max_sent_gap:.2}s capture gap collapsed to {max_pts_gap:.3}s \
+ in the container under overload"
+ ));
+ }
+ }
return Ok(format!(
"{} of {} frames muxed under {}fps overload (drops allowed), max rel err {max_rel:.3}s",
@@ -1144,6 +1207,57 @@ fn read_audio_stats(path: &Path) -> Result<(f64, u16, f64), String> {
Ok((samples as f64 / f64::from(rate), channels, rms))
}
+/// On a frame-count mismatch, name WHICH sent frames never reached the
+/// container: a leading run ("0-4") means a startup stall/race, a spread
+/// ("7, 23, 41") means mid-stream drops. Greedy monotone matcher — pts and
+/// sent are both origin-normalized and sorted, a pts within 0.6 periods of
+/// the sent slot consumes it.
+fn unmatched_sent_indices(sent: &[f64], pts: &[f64], period: f64) -> String {
+ let Some(&sent0) = sent.first() else {
+ return "none".to_string();
+ };
+ let pts0 = pts.first().copied().unwrap_or(0.0);
+ let window = period * 0.6;
+ let mut missing: Vec<usize> = Vec::new();
+ let mut i = 0usize;
+ for (k, &s) in sent.iter().enumerate() {
+ let rel_s = s - sent0;
+ while i < pts.len() && (pts[i] - pts0) < rel_s - window {
+ i += 1;
+ }
+ if i < pts.len() && ((pts[i] - pts0) - rel_s).abs() <= window {
+ i += 1;
+ } else {
+ missing.push(k);
+ }
+ }
+ if missing.is_empty() {
+ return "none (pts shifted rather than missing)".to_string();
+ }
+ let mut runs: Vec<String> = Vec::new();
+ let mut start = missing[0];
+ let mut prev = missing[0];
+ for &m in &missing[1..] {
+ if m == prev + 1 {
+ prev = m;
+ continue;
+ }
+ runs.push(if start == prev {
+ format!("{start}")
+ } else {
+ format!("{start}-{prev}")
+ });
+ start = m;
+ prev = m;
+ }
+ runs.push(if start == prev {
+ format!("{start}")
+ } else {
+ format!("{start}-{prev}")
+ });
+ runs.join(", ")
+}
+
fn record(results: &mut Vec<CaseResult>, name: String, outcome: Result<String, String>) {
eprintln!(
"{name}: {}",
@@ -1248,6 +1362,12 @@ fn random_audio_case(rng: &mut Rng) -> AudioCase {
/// would pay that stall, overflow the muxer's bounded channel, and drop its
/// startup frames (observed as the 15fps/fragmented case losing 3-22 of 60
/// frames depending on load).
+///
+/// The warm-up must run PAST the first segment cut, not just the first
+/// accepted frame: VideoToolbox defers parts of session bring-up until real
+/// packets flow, and the DASH muxer's first segment write has its own
+/// first-use cost. A 3-frame warm-up stopped before either happened and the
+/// first real case still stalled 1-3s on fast machines running newer macOS.
async fn warm_up_video_encoder() {
let Ok(temp) = tempfile::tempdir() else {
return;
@@ -1268,10 +1388,12 @@ async fn warm_up_video_encoder() {
else {
return;
};
- for i in 0..3u64 {
+ // 2.2s of timestamps crosses the 2s segment boundary; frames are pushed
+ // as fast as the encoder accepts them (no real-time pacing needed).
+ for i in 0..66u64 {
let frame = FFmpegVideoFrame {
inner: make_video_frame(160, 120, i, Content::Flat, &mut rng),
- timestamp: Timestamp::Instant(base + Duration::from_millis(i * 30)),
+ timestamp: Timestamp::Instant(base + Duration::from_millis(i * 33)),
};
if tx.send_async(frame).await.is_err() {
break;
@@ -1282,8 +1404,40 @@ async fn warm_up_video_encoder() {
let _ = pipeline.stop().await;
}
+/// One retry for a failed video case. A cold system pays one-time costs
+/// (VideoToolbox service bring-up, first DASH segment write) INSIDE the
+/// pipeline where no emitter-side guard can see them; the muxer's stall
+/// budget then drops frames mid-case exactly as production would, and the
+/// case fails on count with a contiguous missing run. That never repeats on
+/// a warm system, while a real timestamp/drop regression reproduces
+/// immediately — so a retried pass is labeled loudly instead of hidden.
+async fn run_video_case_with_cold_retry(case: VideoCase) -> Result<String, String> {
+ match run_video_case(case.clone()).await {
+ Ok(detail) => Ok(detail),
+ Err(first_error) => {
+ eprintln!("case failed cold ({first_error}); retrying once on a warm pipeline");
+ run_video_case(case)
+ .await
+ .map(|detail| {
+ format!("passed on retry after cold-start failure ({first_error}); {detail}")
+ })
+ .map_err(|second_error| {
+ format!("failed twice: {second_error} (first: {first_error})")
+ })
+ }
+ }
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn synthetic_device_matrix_preserves_sync() {
+ // Silent without RUST_LOG; with it, pipeline drop/stall warnings become
+ // visible so a failing case can be diagnosed instead of re-guessed.
+ tracing_subscriber::fmt()
+ .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
+ .with_test_writer()
+ .try_init()
+ .ok();
+
let mut results: Vec<CaseResult> = Vec::new();
warm_up_video_encoder().await;
@@ -1326,7 +1480,8 @@ async fn synthetic_device_matrix_preserves_sync() {
scenario.name(),
if fragmented { "fragmented" } else { "mp4" }
);
- let outcome = run_video_case(VideoCase::curated(fps, scenario, fragmented)).await;
+ let outcome =
+ run_video_case_with_cold_retry(VideoCase::curated(fps, scenario, fragmented)).await;
record(&mut results, name, outcome);
}
@@ -1364,7 +1519,7 @@ async fn synthetic_device_matrix_preserves_sync() {
scenario.name(),
if fragmented { "fragmented" } else { "mp4" }
);
- let outcome = run_video_case(VideoCase::mismatch(
+ let outcome = run_video_case_with_cold_retry(VideoCase::mismatch(
nominal, delivered, scenario, fragmented,
))
.await;
@@ -1456,7 +1611,7 @@ async fn synthetic_device_matrix_preserves_sync() {
);
// Run both legs concurrently, as a real recording does.
let (video_outcome, audio_outcome) =
- tokio::join!(run_video_case(video), run_audio_case(audio));
+ tokio::join!(run_video_case_with_cold_retry(video), run_audio_case(audio));
let outcome = match (video_outcome, audio_outcome) {
(Ok(v), Ok(a)) => Ok(format!("video: {v}; audio: {a}")),
(Err(e), _) => Err(format!("video leg: {e}")),
@@ -1492,4 +1647,17 @@ async fn synthetic_device_matrix_preserves_sync() {
.collect::<Vec<_>>()
.join("\n")
);
+
+ // Environment skips are a pressure valve, not a pass: if half the matrix
+ // skipped, the run proves nothing and must be loud about it.
+ let skipped = results
+ .iter()
+ .filter(|r| r.detail.contains("skipped:"))
+ .count();
+ assert!(
+ skipped * 2 <= results.len(),
+ "{skipped} of {} matrix cases skipped on environment grounds — runner too \
+ degraded for this run to verify anything",
+ results.len()
+ );
}