Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

ci(verify): integrate platform evidence and isolate recorded fixtures

Richie McIlroye75678623ec3
diff --cc .github/actions/engine-verify-setup/action.yml
index 1aea8b53d,000000000..bbd14a3f7
mode 100644,000000..100644
--- a/.github/actions/engine-verify-setup/action.yml
+++ b/.github/actions/engine-verify-setup/action.yml
@@@ -1,129 -1,0 +1,129 @@@
+name: Engine verify setup
+description: Toolchain, cargo-nextest, Rust cache, native deps and fixture cache for the engine verification suite
+inputs:
+ target:
+ description: Rust target triple
+ required: true
+ tier:
+ description: fast or full (fixture cache key)
+ required: true
+ rust-cache:
+ description: Restore the Rust build cache (build jobs only)
+ default: "true"
+outputs:
+ build-cache-key:
+ description: Key to save the build cache under
+ value: ${{ steps.build-key.outputs.key }}
+ build-cache-hit:
+ description: Whether the build cache was restored exactly
+ value: ${{ steps.build-cache.outputs.cache-hit }}
+ fixtures-hit:
+ description: Whether the fixture cache was restored exactly
+ value: ${{ steps.fixtures.outputs.cache-hit }}
+ fixtures-key:
+ description: Fixture cache key
+ value: ${{ steps.fixtures.outputs.cache-primary-key }}
+runs:
+ using: composite
+ steps:
+ # Only what the suite's dependency closure links against (no webkit/gtk),
+ # plus lavapipe for software Vulkan rendering.
+ - name: Linux packages
+ if: runner.os == 'Linux'
+ shell: bash
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y -qq --no-install-recommends \
+ libasound2-dev libasound2-plugins libpipewire-0.3-dev libspa-0.2-dev libclang-dev \
+ libx11-dev libxrandr-dev libxcb1-dev libxcb-randr0-dev libxcb-shm0-dev \
+ libxcb-xfixes0-dev libxfixes-dev libwayland-dev libxkbcommon-dev \
+ libdbus-1-dev libudev-dev libva-dev mesa-vulkan-drivers libvulkan1 >/dev/null
+
+ - name: Rust toolchain
+ if: inputs.rust-cache == 'true'
+ uses: dtolnay/[email protected]
+ with:
+ targets: ${{ inputs.target }}
+
+ - name: cargo-nextest
+ uses: taiki-e/install-action@v2
+ with:
+
+ # One cache entry per OS per day (saved by main, nightly and the CI dev
+ # branches), restored by PRs. Unlike swatinem/rust-cache it includes the
+ # workspace crates and is refreshed daily even when Cargo.lock is
+ # unchanged, so a PR only rebuilds what changed since the last save. The
+ # chain restarts every ISO week so stale artifacts cannot pile up.
+ - name: Build cache key
+ id: build-key
+ if: inputs.rust-cache == 'true'
+ shell: bash
+ run: |
+ base="verify-build-v3-${{ inputs.target }}-$(date -u +%G-W%V)"
+ echo "base=$base" >> "$GITHUB_OUTPUT"
+ echo "key=$base-${{ hashFiles('Cargo.lock', 'Cargo.toml', 'rust-toolchain.toml') }}-$(date -u +%Y%m%d)" >> "$GITHUB_OUTPUT"
+
+ - name: Restore build cache
+ id: build-cache
+ if: inputs.rust-cache == 'true'
+ uses: actions/cache/restore@v4
+ with:
+ path: |
+ ~/.cargo/registry/index/
+ ~/.cargo/registry/cache/
+ ~/.cargo/git/db/
+ target/ci-verify/
+ key: ${{ steps.build-key.outputs.key }}
+ restore-keys: |
+ ${{ steps.build-key.outputs.base }}-${{ hashFiles('Cargo.lock', 'Cargo.toml', 'rust-toolchain.toml') }}-
+ ${{ steps.build-key.outputs.base }}-
+
+ # Unchanged workspace crates are reused from the cache instead of being
+ # rebuilt because the checkout touched every file (scripts/verify/mtime.py).
+ - name: Reuse unchanged workspace crates
+ if: inputs.rust-cache == 'true'
+ shell: bash
+ run: |
+ "$(command -v python3 || command -v python)" scripts/verify/mtime.py apply target/ci-verify/verify-src-manifest.txt
+
+ - name: Native dependencies
+ shell: bash
+ env:
+ RUST_TARGET_TRIPLE: ${{ inputs.target }}
+ run: node scripts/setup.js
+
+ - name: FFmpeg libraries on the loader path (Linux)
+ if: runner.os == 'Linux'
+ shell: bash
+ run: echo "LD_LIBRARY_PATH=${{ github.workspace }}/target/native-deps/lib" >> "$GITHUB_ENV"
+
+ # The app ships DXC next to its executable and cap-rendering looks for it
+ # next to the test binary or in its profile dir; setup.js only fills
+ # target/debug and target/release. Without it wgpu falls back to FXC.
+ - name: DXC for the ci-verify profile (Windows)
+ if: runner.os == 'Windows'
+ shell: bash
+ run: |
+ mkdir -p target/ci-verify
+ cp target/native-deps/dxc/dxcompiler.dll target/native-deps/dxc/dxil.dll target/ci-verify/
+
+ - name: FFmpeg DLLs on PATH (Windows)
+ if: runner.os == 'Windows'
+ shell: pwsh
+ run: Add-Content -Path $env:GITHUB_PATH -Value "${{ github.workspace }}\target\ffmpeg\bin"
+
+ - name: Fixture location
+ shell: bash
+ run: echo "CAP_VERIFY_FIXTURE_DIR=${{ runner.temp }}/verify-fixtures" >> "$GITHUB_ENV"
+
+ # Fixtures are generated by code (including the real-pipeline Studio and
+ # Instant recordings, ~1 min of real-time capture); the key is the whole
+ # verify crate source plus the native deps. Exact key only: a fixture made
+ # by an older generator is never reused.
+ - name: Restore fixtures
+ id: fixtures
+ uses: actions/cache/restore@v4
+ with:
+ path: ${{ runner.temp }}/verify-fixtures
- key: verify-fixtures-v1-${{ runner.os }}-${{ inputs.tier }}-${{ hashFiles('crates/verify/src/**', 'crates/verify/Cargo.toml', 'scripts/setup.js') }}
++ key: verify-fixtures-v1-${{ runner.os }}-${{ inputs.tier }}-${{ hashFiles('crates/**/src/**', 'crates/**/Cargo.toml', 'Cargo.lock', 'scripts/setup.js') }}
diff --cc .github/workflows/engine-verify-os.yml
index 0151f4652,000000000..ed0c21030
mode 100644,000000..100644
--- a/.github/workflows/engine-verify-os.yml
+++ b/.github/workflows/engine-verify-os.yml
@@@ -1,202 -1,0 +1,217 @@@
+name: Engine verify (one platform)
+
+# Called by engine-verify.yml once per platform. Cases are split across
+# `shards` jobs by a stable hash of the case id (CAP_VERIFY_SHARD), so a suite
+# whose test functions loop over many cases still spreads evenly.
+#
+# By default every shard builds for itself: with the Rust cache and
+# scripts/verify/mtime.py a warm build only compiles what changed, which is
+# cheaper than an artifact round trip and a second runner queue. With
+# `archive: true` one job builds a nextest archive and the shards run it.
+
+on:
+ workflow_call:
+ inputs:
+ platform:
+ type: string
+ required: true
+ runner:
+ type: string
+ required: true
+ target:
+ type: string
+ required: true
+ tier:
+ type: string
+ required: true
+ suites:
+ type: string
+ required: true
+ shards:
+ type: number
+ default: 1
+ shard-list:
+ type: string
+ default: "[1]"
+ archive:
+ type: boolean
+ default: false
+ save-cache:
+ type: boolean
+ default: false
+ cargo-config:
+ type: string
+ default: ""
+ cargo-log:
+ type: string
+ default: ""
+
+permissions:
+ contents: read
+
+env:
+ CARGO_TERM_COLOR: always
+ CARGO_INCREMENTAL: "0"
+ RUST_BACKTRACE: "1"
+ CAP_VERIFY_CARGO_PROFILE: ci-verify
+ CAP_VERIFY_NEXTEST_PROFILE: ci
+ CAP_VERIFY_LOCKED: "1"
+ CAP_VERIFY_CARGO_CONFIG: ${{ inputs.cargo-config }}
+
+jobs:
+ build:
+ name: build
+ if: inputs.archive
+ runs-on: ${{ inputs.runner }}
+ timeout-minutes: 60
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+
+ - name: Setup
+ id: setup
+ uses: ./.github/actions/engine-verify-setup
+ with:
+ target: ${{ inputs.target }}
+ tier: ${{ inputs.tier }}
+
+ - name: Build archive
+ shell: bash
+ run: scripts/verify/run.sh "${{ inputs.tier }}" --suites "${{ inputs.suites }}" --archive "$RUNNER_TEMP/verify.tar.zst"
+
+ - name: Record sources of the cached build
+ if: inputs.save-cache && steps.setup.outputs.build-cache-hit != 'true'
+ shell: bash
+ run: |
+ "$(command -v python3 || command -v python)" scripts/verify/mtime.py record target/ci-verify/verify-src-manifest.txt
+
+ - name: Save build cache
+ if: inputs.save-cache && steps.setup.outputs.build-cache-hit != 'true'
+ uses: actions/cache/save@v4
+ with:
+ path: |
+ ~/.cargo/registry/index/
+ ~/.cargo/registry/cache/
+ ~/.cargo/git/db/
+ target/ci-verify/
+ key: ${{ steps.setup.outputs.build-cache-key }}
+
+ - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ with:
+ name: verify-archive-${{ inputs.platform }}-${{ github.run_attempt }}
+ path: ${{ runner.temp }}/verify.tar.zst
+ retention-days: 1
+ compression-level: 0
+
+ test:
+ name: ${{ inputs.shards > 1 && format('test {0}/{1}', matrix.shard, inputs.shards) || 'build and test' }}
+ needs: build
+ if: always() && (needs.build.result == 'success' || needs.build.result == 'skipped')
+ runs-on: ${{ inputs.runner }}
+ timeout-minutes: 60
+ strategy:
+ fail-fast: false
+ matrix:
+ shard: ${{ fromJSON(inputs.shard-list) }}
+ env:
+ CAP_VERIFY_SHARD: ${{ inputs.shards > 1 && format('{0}/{1}', matrix.shard, inputs.shards) || '' }}
++ CAP_VERIFY_TRACE_BLEND: ${{ inputs.platform == 'macos' && '1' || '' }}
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+
+ - name: Setup
+ id: setup
+ uses: ./.github/actions/engine-verify-setup
+ with:
+ target: ${{ inputs.target }}
+ tier: ${{ inputs.tier }}
+ rust-cache: ${{ !inputs.archive }}
+
+ - name: Report location
+ shell: bash
+ run: |
+ echo "CAP_VERIFY_REPORT_DIR=$RUNNER_TEMP/verify-report" >> "$GITHUB_ENV"
+ echo "CAP_VERIFY_FLAKY_FILE=$RUNNER_TEMP/verify-report/flaky.txt" >> "$GITHUB_ENV"
+
+ - name: Build
+ if: ${{ !inputs.archive }}
+ shell: bash
+ env:
+ CARGO_LOG: ${{ inputs.cargo-log }}
+ run: scripts/verify/run.sh "${{ inputs.tier }}" --suites "${{ inputs.suites }}" --no-run
+
+ - name: Record sources of the cached build
+ if: ${{ !inputs.archive && inputs.save-cache && matrix.shard == 1 && steps.setup.outputs.build-cache-hit != 'true' }}
+ shell: bash
+ run: |
+ "$(command -v python3 || command -v python)" scripts/verify/mtime.py record target/ci-verify/verify-src-manifest.txt
+
+ - name: Save build cache
+ if: ${{ !inputs.archive && inputs.save-cache && matrix.shard == 1 && steps.setup.outputs.build-cache-hit != 'true' }}
+ uses: actions/cache/save@v4
+ with:
+ path: |
+ ~/.cargo/registry/index/
+ ~/.cargo/registry/cache/
+ ~/.cargo/git/db/
+ target/ci-verify/
+ key: ${{ steps.setup.outputs.build-cache-key }}
+
+ - name: Download archive
+ if: inputs.archive
+ uses: actions/download-artifact@v4
+ with:
+ name: verify-archive-${{ inputs.platform }}-${{ github.run_attempt }}
+ path: ${{ runner.temp }}
+
++ - name: Prepare recorded fixtures without concurrent rendering
++ if: contains(format(',{0},', inputs.suites), ',export,')
++ shell: bash
++ env:
++ CAP_VERIFY_TIER: ${{ inputs.tier }}
++ run: |
++ if [[ "${{ inputs.archive }}" == true ]]; then
++ cargo-nextest nextest run --profile ci --archive-file "$RUNNER_TEMP/verify.tar.zst" --workspace-remap "$GITHUB_WORKSPACE" \
++ --run-ignored ignored-only -E 'binary_id(cap-verify::export) and test(=prepare_recorded_fixtures)'
++ else
++ cargo nextest run --profile ci --cargo-profile ci-verify --locked -p cap-verify --test export \
++ --run-ignored ignored-only -E 'test(=prepare_recorded_fixtures)'
++ fi
++
+ - name: Test
+ id: test
+ shell: bash
+ run: |
+ if [[ "${{ inputs.archive }}" == true ]]; then
+ scripts/verify/run.sh "${{ inputs.tier }}" --suites "${{ inputs.suites }}" --from-archive "$RUNNER_TEMP/verify.tar.zst"
+ else
+ scripts/verify/run.sh "${{ inputs.tier }}" --suites "${{ inputs.suites }}"
+ fi
+
+ - name: Summary
+ if: always() && steps.test.outcome != 'skipped'
+ shell: bash
+ run: >-
+ "$(command -v python3 || command -v python)" scripts/verify/summary.py
+ --title "${{ inputs.platform }} ${{ inputs.tier }}${{ inputs.shards > 1 && format(' shard {0}/{1}', matrix.shard, inputs.shards) || '' }}"
+ --junit "$CAP_VERIFY_REPORT_DIR/junit.xml" --flaky "$CAP_VERIFY_FLAKY_FILE"
+ "$CAP_VERIFY_REPORT_DIR" >> "$GITHUB_STEP_SUMMARY"
+
+ - name: Upload report
+ if: always() && steps.test.outcome != 'skipped'
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ with:
+ name: verify-report-${{ inputs.platform }}-${{ inputs.tier }}-${{ matrix.shard }}
+ path: ${{ runner.temp }}/verify-report
+ if-no-files-found: ignore
+ retention-days: 14
+
+ - name: Save fixtures
+ if: always() && inputs.save-cache && steps.setup.outputs.fixtures-hit != 'true' && matrix.shard == 1
+ uses: actions/cache/save@v4
+ with:
+ path: ${{ runner.temp }}/verify-fixtures
+ key: ${{ steps.setup.outputs.fixtures-key }}
diff --cc Cargo.lock
index 8ec4d3f4e,c398b37ac..3c5bd2acf
--- a/Cargo.lock
+++ b/Cargo.lock
@@@ -2175,6 -2173,8 +2175,7 @@@ dependencies =
"serde_json",
"tempfile",
"tokio",
- "toml 0.8.2",
+ "tracing-subscriber",
"workspace-hack",
]
diff --cc crates/verify-expect/src/lib.rs
index 762678636,000000000..15796f9cc
mode 100644,000000..100644
--- a/crates/verify-expect/src/lib.rs
+++ b/crates/verify-expect/src/lib.rs
@@@ -1,847 -1,0 +1,901 @@@
+//! Strict expected failures and case records shared by every engine
+//! verification suite (the `cap-verify` oracle tests, the decoder model
+//! fuzzer, the upload fault suite).
+//!
+//! Each suite keeps one TOML file of `[[xfail]]` entries:
+//!
+//! ```toml
+//! [[xfail]]
+//! case = "export/early-camera/full/*" # case id, `*` globs allowed
+//! class = "future" # failure class that must still occur
+//! platforms = ["macos"] # optional, absent = every platform
+//! seeds = "0 3-7" # optional, seeded suites only
+//! flaky = true # optional, may pass (state the rate)
+//! reason = "what is wrong"
+//! link = "https://github.com/CapSoftware/Cap/pull/2595" # empty = no fix yet
+//! ```
+//!
+//! The verdict is strict both ways. A failure class (or seed) that is not
+//! listed fails the run, and a listed, non-flaky class (or seed) that no
+//! longer fails also fails the run ("remove this xfail"), so fixes stay
+//! locked in.
+//!
+//! Every suite writes one JSON line per case ([`Record`]) to
+//! `CAP_VERIFY_REPORT_DIR` when it is set. The `cap-verify-expect` binary
+//! rewrites the expectations files from those records (`bless`), and
+//! `scripts/verify/summary.py` turns them into the CI job summary.
+
+use std::{
+ collections::{BTreeMap, BTreeSet},
+ fmt::Write as _,
+ io::Write as _,
+ path::{Path, PathBuf},
+};
+
+use serde::{Deserialize, Serialize};
+
+pub const PLATFORMS: [&str; 3] = ["linux", "macos", "windows"];
+
+pub fn platform() -> &'static str {
+ if cfg!(target_os = "macos") {
+ "macos"
+ } else if cfg!(target_os = "windows") {
+ "windows"
+ } else {
+ "linux"
+ }
+}
+
+/// One strict expected failure.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Xfail {
+ pub case: String,
+ pub class: String,
+ /// Empty means every platform.
+ pub platforms: Vec<String>,
+ /// `None` means the class must occur (on any seed, for seeded suites).
+ pub seeds: Option<BTreeSet<u64>>,
+ pub flaky: bool,
+ pub reason: String,
+ pub link: String,
+}
+
+impl Xfail {
+ pub fn applies_on(&self, platform: &str) -> bool {
+ self.platforms.is_empty() || self.platforms.iter().any(|p| p == platform)
+ }
+
+ pub fn matches(&self, case: &str, platform: &str) -> bool {
+ self.applies_on(platform) && glob_match(&self.case, case)
+ }
+
+ fn effective_platforms(&self) -> BTreeSet<String> {
+ if self.platforms.is_empty() {
+ PLATFORMS.iter().map(|p| p.to_string()).collect()
+ } else {
+ self.platforms.iter().cloned().collect()
+ }
+ }
+
+ fn with_platforms(&self, platforms: BTreeSet<String>) -> Self {
+ let all = platforms.len() == PLATFORMS.len();
+ Self {
+ platforms: if all {
+ Vec::new()
+ } else {
+ platforms.into_iter().collect()
+ },
+ ..self.clone()
+ }
+ }
+}
+
+/// `*` matches any run of characters (including `/`).
+pub fn glob_match(pattern: &str, text: &str) -> bool {
+ let parts: Vec<&str> = pattern.split('*').collect();
+ if parts.len() == 1 {
+ return pattern == text;
+ }
+ let Some(mut rest) = text.strip_prefix(parts[0]) else {
+ return false;
+ };
+ let last = parts.len() - 1;
+ for part in &parts[1..last] {
+ let Some(at) = rest.find(part) else {
+ return false;
+ };
+ rest = &rest[at + part.len()..];
+ }
+ rest.ends_with(parts[last])
+}
+
+/// Case selection shared by every suite:
+/// - `CAP_VERIFY_CASE`: comma-separated globs; only matching cases run.
+/// - `CAP_VERIFY_SKIP`: comma-separated globs; matching cases are skipped
+/// (the per-platform FAST tier trims in `scripts/verify/suites.json`).
+/// - `CAP_VERIFY_SHARD=i/n`: only cases whose id hashes to shard `i` (1-based)
+/// of `n` run, so one suite can be split across CI jobs case by case.
+pub fn case_selected(id: &str) -> bool {
+ let env = |name: &str| std::env::var(name).ok().filter(|v| !v.trim().is_empty());
+ let globs = |value: String| -> Vec<String> {
+ value
+ .split(',')
+ .map(|p| p.trim().to_string())
+ .filter(|p| !p.is_empty())
+ .collect()
+ };
+ if let Some(only) = env("CAP_VERIFY_CASE")
+ && !globs(only).iter().any(|p| glob_match(p, id))
+ {
+ return false;
+ }
+ if let Some(skip) = env("CAP_VERIFY_SKIP")
+ && globs(skip).iter().any(|p| glob_match(p, id))
+ {
+ return false;
+ }
+ match env("CAP_VERIFY_SHARD").and_then(|v| parse_shard(&v)) {
+ Some((index, count)) => shard_of(id, count) == index,
+ None => true,
+ }
+}
+
+fn parse_shard(value: &str) -> Option<(u64, u64)> {
+ let (index, count) = value.trim().split_once('/')?;
+ let (index, count) = (index.parse().ok()?, count.parse().ok()?);
+ (count >= 1 && (1..=count).contains(&index)).then_some((index, count))
+}
+
+/// 1-based shard of a case id (FNV-1a, stable across platforms and runs).
+pub fn shard_of(id: &str, count: u64) -> u64 {
+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
+ for byte in id.bytes() {
+ hash ^= u64::from(byte);
+ hash = hash.wrapping_mul(0x0100_0000_01b3);
+ }
+ hash % count.max(1) + 1
+}
+
+pub fn parse_seeds(text: &str) -> Result<BTreeSet<u64>, String> {
+ let mut seeds = BTreeSet::new();
+ for item in text.split_whitespace() {
+ let parse = |value: &str| {
+ value
+ .parse::<u64>()
+ .map_err(|_| format!("bad seed {value:?}"))
+ };
+ match item.split_once('-') {
+ Some((first, last)) => seeds.extend(parse(first)?..=parse(last)?),
+ None => {
+ seeds.insert(parse(item)?);
+ }
+ }
+ }
+ Ok(seeds)
+}
+
+pub fn format_seeds(seeds: &BTreeSet<u64>) -> String {
+ let mut runs: Vec<(u64, u64)> = Vec::new();
+ for &seed in seeds {
+ match runs.last_mut() {
+ Some((_, last)) if *last + 1 == seed => *last = seed,
+ _ => runs.push((seed, seed)),
+ }
+ }
+ runs.iter()
+ .map(|&(first, last)| match last - first {
+ 0 => first.to_string(),
+ 1 => format!("{first} {last}"),
+ _ => format!("{first}-{last}"),
+ })
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawXfail {
+ case: String,
+ class: String,
+ #[serde(default)]
+ platforms: Vec<String>,
+ seeds: Option<String>,
+ #[serde(default)]
+ flaky: bool,
+ reason: String,
+ #[serde(default)]
+ link: String,
+}
+
+#[derive(Deserialize)]
+#[serde(deny_unknown_fields)]
+struct RawFile {
+ #[serde(default)]
+ xfail: Vec<RawXfail>,
+}
+
+pub fn parse(text: &str) -> Result<Vec<Xfail>, String> {
+ let file: RawFile = toml::from_str(text).map_err(|e| e.to_string())?;
+ file.xfail
+ .into_iter()
+ .map(|raw| {
+ if raw.case.is_empty() || raw.class.is_empty() || raw.reason.is_empty() {
+ return Err(format!(
+ "xfail {:?}/{:?}: case, class and reason are required",
+ raw.case, raw.class
+ ));
+ }
+ if let Some(bad) = raw
+ .platforms
+ .iter()
+ .find(|p| !PLATFORMS.contains(&p.as_str()))
+ {
+ return Err(format!(
+ "xfail {}: unknown platform {bad:?} (use {PLATFORMS:?})",
+ raw.case
+ ));
+ }
+ let seeds = raw
+ .seeds
+ .as_deref()
+ .map(parse_seeds)
+ .transpose()
+ .map_err(|e| format!("xfail {}: {e}", raw.case))?;
+ Ok(Xfail {
+ case: raw.case,
+ class: raw.class,
+ platforms: raw.platforms,
+ seeds,
+ flaky: raw.flaky,
+ reason: raw.reason,
+ link: raw.link,
+ })
+ })
+ .collect()
+}
+
+/// Loads an expectations file. A missing file is an empty list; a malformed
+/// one panics with the path, since a silently ignored entry would hide a
+/// regression.
+pub fn load(path: &Path) -> Vec<Xfail> {
+ match std::fs::read_to_string(path) {
+ Ok(text) => parse(&text).unwrap_or_else(|e| panic!("{}: {e}", path.display())),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
+ Err(e) => panic!("{}: {e}", path.display()),
+ }
+}
+
+fn quote(value: &str) -> String {
+ let mut out = String::with_capacity(value.len() + 2);
+ out.push('"');
+ for c in value.chars() {
+ match c {
+ '"' => out.push_str("\\\""),
+ '\\' => out.push_str("\\\\"),
+ '\n' => out.push_str("\\n"),
+ '\t' => out.push_str("\\t"),
+ c if c.is_control() => {
+ let _ = write!(out, "\\u{:04X}", c as u32);
+ }
+ c => out.push(c),
+ }
+ }
+ out.push('"');
+ out
+}
+
+/// Renders entries in the canonical layout (one key per line, fixed order).
+pub fn render(entries: &[Xfail]) -> String {
+ let mut out = String::new();
+ for x in entries {
+ out.push_str("[[xfail]]\n");
+ let _ = writeln!(out, "case = {}", quote(&x.case));
+ let _ = writeln!(out, "class = {}", quote(&x.class));
+ if !x.platforms.is_empty() {
+ let platforms: Vec<String> = x.platforms.iter().map(|p| quote(p)).collect();
+ let _ = writeln!(out, "platforms = [{}]", platforms.join(", "));
+ }
+ if let Some(seeds) = &x.seeds {
+ let _ = writeln!(out, "seeds = {}", quote(&format_seeds(seeds)));
+ }
+ if x.flaky {
+ out.push_str("flaky = true\n");
+ }
+ let _ = writeln!(out, "reason = {}", quote(&x.reason));
+ let _ = writeln!(out, "link = {}", quote(&x.link));
+ out.push('\n');
+ }
+ out
+}
+
+/// The comment block before the first entry, kept when a file is rewritten.
+pub fn header(text: &str) -> String {
+ let mut out = String::new();
+ for line in text.lines() {
+ if line.trim() == "[[xfail]]" {
+ break;
+ }
+ out.push_str(line);
+ out.push('\n');
+ }
+ let trimmed = out.trim_end();
+ if trimmed.is_empty() {
+ String::new()
+ } else {
+ format!("{trimmed}\n\n")
+ }
+}
+
+/// Failures seen in a run: `(case, class) -> failing seeds`. Unseeded suites
+/// use an empty seed set.
+pub type Observed = BTreeMap<(String, String), BTreeSet<u64>>;
+
+/// Cases that ran: `case -> seeds that ran` (`None` for unseeded cases).
+pub type Ran = BTreeMap<String, Option<BTreeSet<u64>>>;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Unexpected {
+ pub case: String,
+ pub class: String,
+ /// Seeds not covered by any xfail (empty for unseeded cases).
+ pub seeds: BTreeSet<u64>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Fixed {
+ pub xfail: Xfail,
+ pub case: String,
+ /// Listed seeds that passed; `None` when the class did not occur at all.
+ pub seeds: Option<BTreeSet<u64>>,
+}
+
+impl Fixed {
+ pub fn message(&self, file: &str) -> String {
+ let seeds = match &self.seeds {
+ Some(seeds) => format!(" for seeds {}", format_seeds(seeds)),
+ None => String::new(),
+ };
+ format!(
+ "{} no longer fails with {}{seeds}: remove this xfail from {file} ({})",
+ self.case, self.xfail.class, self.xfail.reason
+ )
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Verdict {
+ pub unexpected: Vec<Unexpected>,
+ pub fixed: Vec<Fixed>,
+}
+
+impl Verdict {
+ pub fn ok(&self) -> bool {
+ self.unexpected.is_empty() && self.fixed.is_empty()
+ }
+}
+
+fn covered_by<'a>(
+ xfails: impl Iterator<Item = &'a Xfail>,
+ case: &str,
+ class: &str,
+ platform: &str,
+ seeds: &BTreeSet<u64>,
+) -> BTreeSet<u64> {
+ let mut covered = BTreeSet::new();
+ for x in xfails.filter(|x| x.class == class && x.matches(case, platform)) {
+ match &x.seeds {
+ None => return seeds.clone(),
+ Some(listed) => covered.extend(listed.intersection(seeds).copied()),
+ }
+ }
+ covered
+}
+
+/// Compares the failures of a run with the expectations, on `platform`.
+pub fn judge(xfails: &[Xfail], platform: &str, ran: &Ran, observed: &Observed) -> Verdict {
+ let mut verdict = Verdict::default();
+ for ((case, class), seeds) in observed {
+ let has_entry = xfails
+ .iter()
+ .any(|x| x.class == *class && x.matches(case, platform));
+ if !has_entry {
+ verdict.unexpected.push(Unexpected {
+ case: case.clone(),
+ class: class.clone(),
+ seeds: seeds.clone(),
+ });
+ continue;
+ }
+ let covered = covered_by(xfails.iter(), case, class, platform, seeds);
+ let uncovered: BTreeSet<u64> = seeds.difference(&covered).copied().collect();
+ if !uncovered.is_empty() {
+ verdict.unexpected.push(Unexpected {
+ case: case.clone(),
+ class: class.clone(),
+ seeds: uncovered,
+ });
+ }
+ }
+ for x in xfails.iter().filter(|x| !x.flaky && x.applies_on(platform)) {
+ for (case, ran_seeds) in ran.iter().filter(|(case, _)| glob_match(&x.case, case)) {
+ let seen = observed.get(&(case.clone(), x.class.clone()));
+ let seeds = match (&x.seeds, seen) {
+ (None, None) => None,
+ (None, Some(_)) => continue,
+ (Some(listed), seen) => {
+ let passed: BTreeSet<u64> = listed
+ .iter()
+ .filter(|seed| ran_seeds.as_ref().is_none_or(|ran| ran.contains(seed)))
+ .filter(|seed| seen.is_none_or(|seen| !seen.contains(seed)))
+ .copied()
+ .collect();
+ if passed.is_empty() {
+ continue;
+ }
+ Some(passed)
+ }
+ };
+ verdict.fixed.push(Fixed {
+ xfail: x.clone(),
+ case: case.clone(),
+ seeds,
+ });
+ }
+ }
+ verdict
+}
+
+/// Rewrites `xfails` so that this platform's run passes exactly, without
+/// touching what other platforms or cases that did not run expect. Reasons
+/// and links of replaced entries are kept; new failures get the reason
+/// `TODO: <problem>` from `problems`.
+pub fn bless(
+ xfails: &[Xfail],
+ platform: &str,
+ ran: &Ran,
+ observed: &Observed,
+ problems: &BTreeMap<(String, String), String>,
+) -> Vec<Xfail> {
+ let mut out: Vec<Xfail> = Vec::new();
+ let mut kept_here: Vec<Xfail> = Vec::new();
+ for x in xfails {
+ let matched: Vec<(&String, &Option<BTreeSet<u64>>)> = ran
+ .iter()
+ .filter(|(case, _)| glob_match(&x.case, case))
+ .collect();
+ if !x.applies_on(platform) || matched.is_empty() || x.flaky {
+ out.push(x.clone());
+ if x.applies_on(platform) {
+ kept_here.push(x.clone());
+ }
+ continue;
+ }
+ let still_exact = matched.iter().all(|(case, ran_seeds)| {
+ let seen = observed.get(&((*case).clone(), x.class.clone()));
+ match (&x.seeds, seen) {
+ (_, None) => false,
+ (None, Some(_)) => true,
+ (Some(listed), Some(seen)) => listed
+ .iter()
+ .filter(|s| ran_seeds.as_ref().is_none_or(|r| r.contains(s)))
+ .all(|s| seen.contains(s)),
+ }
+ });
+ if still_exact {
+ out.push(x.clone());
+ kept_here.push(x.clone());
+ continue;
+ }
+ let mut others = x.effective_platforms();
+ others.remove(platform);
+ if !others.is_empty() {
+ out.push(x.with_platforms(others));
+ }
+ if let Some(listed) = &x.seeds {
+ for (case, ran_seeds) in &matched {
+ let not_ran: BTreeSet<u64> = listed
+ .iter()
+ .filter(|s| ran_seeds.as_ref().is_some_and(|r| !r.contains(s)))
+ .copied()
+ .collect();
+ if !not_ran.is_empty() {
+ let entry = Xfail {
+ case: (*case).clone(),
+ seeds: Some(not_ran),
+ platforms: vec![platform.to_string()],
+ ..x.clone()
+ };
+ out.push(entry.clone());
+ kept_here.push(entry);
+ }
+ }
+ }
+ }
+ for ((case, class), seeds) in observed {
+ let covered = covered_by(kept_here.iter(), case, class, platform, seeds);
+ let fully = kept_here
+ .iter()
+ .any(|x| x.class == *class && x.matches(case, platform) && x.seeds.is_none());
+ if fully || (!seeds.is_empty() && covered == *seeds) {
+ continue;
+ }
+ let missing: BTreeSet<u64> = seeds.difference(&covered).copied().collect();
+ let previous = xfails
+ .iter()
+ .find(|x| x.class == *class && glob_match(&x.case, case));
+ let entry = Xfail {
+ case: case.clone(),
+ class: class.clone(),
+ platforms: vec![platform.to_string()],
+ seeds: (!seeds.is_empty()).then_some(missing),
+ flaky: false,
+ reason: previous.map_or_else(
+ || {
+ format!(
+ "TODO: {}",
+ problems
+ .get(&(case.clone(), class.clone()))
+ .map_or("describe the failure", |p| p.as_str())
+ )
+ },
+ |x| x.reason.clone(),
+ ),
+ link: previous.map_or_else(String::new, |x| x.link.clone()),
+ };
+ out.push(entry);
+ }
+ coalesce(out)
+}
+
+/// Merges entries that differ only in platforms or in seeds of the same
+/// case, then sorts them.
+fn coalesce(entries: Vec<Xfail>) -> Vec<Xfail> {
+ let mut by_seeds: Vec<Xfail> = Vec::new();
+ for x in entries {
+ if let Some(existing) = by_seeds.iter_mut().find(|e| {
+ e.case == x.case
+ && e.class == x.class
+ && e.flaky == x.flaky
+ && e.reason == x.reason
+ && e.link == x.link
+ && e.platforms == x.platforms
+ && e.seeds.is_some()
+ && x.seeds.is_some()
+ }) {
+ if let (Some(a), Some(b)) = (&mut existing.seeds, &x.seeds) {
+ a.extend(b.iter().copied());
+ }
+ } else {
+ by_seeds.push(x);
+ }
+ }
+ let mut merged: Vec<Xfail> = Vec::new();
+ for x in by_seeds {
+ if let Some(existing) = merged.iter_mut().find(|e| {
+ e.case == x.case
+ && e.class == x.class
+ && e.seeds == x.seeds
+ && e.flaky == x.flaky
+ && e.reason == x.reason
+ && e.link == x.link
+ }) {
+ let mut platforms = existing.effective_platforms();
+ platforms.extend(x.effective_platforms());
+ *existing = existing.with_platforms(platforms);
+ } else {
+ merged.push(x);
+ }
+ }
+ merged.sort_by(|a, b| {
+ (&a.case, &a.class, a.effective_platforms()).cmp(&(
+ &b.case,
+ &b.class,
+ b.effective_platforms(),
+ ))
+ });
+ merged.dedup();
+ merged
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Outcome {
+ Pass,
+ Xfail,
+ Fail,
+ Xpass,
++ Unsupported,
+}
+
+/// One case's result, written as a JSON line to `CAP_VERIFY_REPORT_DIR`.
+/// Suites may add fields (for example per-stream mismatch lists); readers
+/// ignore what they do not know.
+#[derive(Clone, Debug, Serialize, Deserialize)]
+pub struct Record {
+ pub suite: String,
+ /// Expectations file, relative to the repository root.
+ pub expectations: String,
+ pub case: String,
+ pub platform: String,
+ #[serde(default)]
+ pub tier: String,
+ pub outcome: Outcome,
+ /// Failure class -> failing seeds (empty for unseeded cases).
+ #[serde(default)]
+ pub failures: BTreeMap<String, BTreeSet<u64>>,
+ /// Seeds that ran, for seeded cases.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub seeds_ran: Option<BTreeSet<u64>>,
+ /// First problem per class, used as the draft reason when blessing.
+ #[serde(default)]
+ pub problems: BTreeMap<String, String>,
+ #[serde(default)]
+ pub summary: String,
+ #[serde(default)]
+ pub repro: String,
+ #[serde(default)]
+ pub seconds: f64,
+}
+
+pub fn report_dir() -> Option<PathBuf> {
+ std::env::var_os("CAP_VERIFY_REPORT_DIR")
+ .filter(|dir| !dir.is_empty())
+ .map(PathBuf::from)
+}
+
+/// Appends records to `<CAP_VERIFY_REPORT_DIR>/<suite>-<pid>.jsonl` (no-op
+/// when the variable is unset). Any extra JSON fields in `extra` are merged
+/// into each line.
+pub fn write_records(records: &[(Record, serde_json::Value)]) {
+ let Some(dir) = report_dir() else {
+ return;
+ };
- let _ = std::fs::create_dir_all(&dir);
++ write_records_to(&dir, records);
++}
++
++fn write_records_to(dir: &Path, records: &[(Record, serde_json::Value)]) {
++ static WRITER: std::sync::Mutex<()> = std::sync::Mutex::new(());
++ let _guard = WRITER.lock().expect("report writer lock");
++ std::fs::create_dir_all(dir).expect("create report directory");
+ let Some((first, _)) = records.first() else {
+ return;
+ };
+ let file = dir.join(format!("{}-{}.jsonl", first.suite, std::process::id()));
- let Ok(mut f) = std::fs::OpenOptions::new()
++ let mut file = std::fs::OpenOptions::new()
+ .create(true)
+ .append(true)
+ .open(file)
- else {
- return;
- };
++ .expect("open report file");
+ for (record, extra) in records {
- let Ok(mut value) = serde_json::to_value(record) else {
- continue;
- };
++ let mut value = serde_json::to_value(record).expect("serialize report record");
+ if let (Some(map), Some(extra)) = (value.as_object_mut(), extra.as_object()) {
+ for (k, v) in extra {
+ map.entry(k.clone()).or_insert_with(|| v.clone());
+ }
+ }
- let _ = writeln!(f, "{value}");
++ let line = format!("{value}\n");
++ file.write_all(line.as_bytes())
++ .expect("write report record");
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn set(seeds: &[u64]) -> BTreeSet<u64> {
+ seeds.iter().copied().collect()
+ }
+
+ fn entry(case: &str, class: &str, platforms: &[&str], seeds: Option<&[u64]>) -> Xfail {
+ Xfail {
+ case: case.into(),
+ class: class.into(),
+ platforms: platforms.iter().map(|p| p.to_string()).collect(),
+ seeds: seeds.map(set),
+ flaky: false,
+ reason: "r".into(),
+ link: String::new(),
+ }
+ }
+
++ #[test]
++ fn concurrent_reports_remain_complete_json_lines() {
++ let dir = std::env::temp_dir().join(format!(
++ "cap-verify-reports-{}-{}",
++ std::process::id(),
++ std::time::SystemTime::now()
++ .duration_since(std::time::UNIX_EPOCH)
++ .unwrap()
++ .as_nanos()
++ ));
++ std::thread::scope(|scope| {
++ for writer in 0..8 {
++ let dir = &dir;
++ scope.spawn(move || {
++ for index in 0..50 {
++ let record = Record {
++ suite: "concurrent".into(),
++ expectations: "expectations.toml".into(),
++ case: format!("{writer}/{index}"),
++ platform: "windows".into(),
++ tier: "fast".into(),
++ outcome: Outcome::Unsupported,
++ failures: BTreeMap::new(),
++ seeds_ran: None,
++ problems: BTreeMap::new(),
++ summary: "test record".repeat(100),
++ repro: String::new(),
++ seconds: 0.0,
++ };
++ write_records_to(dir, &[(record, serde_json::json!({"writer": writer}))]);
++ }
++ });
++ }
++ });
++ let file = dir.join(format!("concurrent-{}.jsonl", std::process::id()));
++ let text = std::fs::read_to_string(file).unwrap();
++ let cases: BTreeSet<String> = text
++ .lines()
++ .map(|line| {
++ let record: Record = serde_json::from_str(line).unwrap();
++ assert_eq!(record.outcome, Outcome::Unsupported);
++ record.case
++ })
++ .collect();
++ assert_eq!(text.lines().count(), 400);
++ assert_eq!(cases.len(), 400);
++ std::fs::remove_dir_all(dir).unwrap();
++ }
++
+ #[test]
+ fn globs() {
+ assert!(glob_match("export/*", "export/basic/mp4"));
+ assert!(glob_match("export/*/avf", "export/jitter/avf"));
+ assert!(!glob_match("export/*/avf", "export/jitter/ffmpeg"));
+ assert!(glob_match("a*b*c", "abc"));
+ assert!(!glob_match("a*b*c", "acb"));
+ assert!(glob_match("a", "a"));
+ assert!(!glob_match("a", "ab"));
+ }
+
+ #[test]
+ fn shards_partition_cases() {
+ let ids: Vec<String> = (0..200).map(|i| format!("export/case-{i}/avf")).collect();
+ let mut counts = [0usize; 3];
+ for id in &ids {
+ let shard = shard_of(id, 3);
+ assert!((1..=3).contains(&shard));
+ counts[(shard - 1) as usize] += 1;
+ }
+ assert!(counts.iter().all(|&n| n > 40), "{counts:?}");
+ assert_eq!(parse_shard("2/3"), Some((2, 3)));
+ assert_eq!(parse_shard("4/3"), None);
+ assert_eq!(parse_shard("0/3"), None);
+ }
+
+ #[test]
+ fn seed_lists_round_trip() {
+ let seeds = parse_seeds("0 2 3 5-9 12").unwrap();
+ assert_eq!(seeds, set(&[0, 2, 3, 5, 6, 7, 8, 9, 12]));
+ assert_eq!(format_seeds(&seeds), "0 2 3 5-9 12");
+ }
+
+ #[test]
+ fn file_round_trips_and_rejects_typos() {
+ let entries = vec![
+ entry("a/*", "stale", &["macos"], Some(&[1, 2, 3])),
+ Xfail {
+ flaky: true,
+ reason: "quote \" and \\ ok".into(),
+ link: "https://x".into(),
+ ..entry("b", "future", &[], None)
+ },
+ ];
+ assert_eq!(parse(&render(&entries)).unwrap(), entries);
+ assert!(parse("[[xfail]]\ncase = \"a\"\nclas = \"x\"\nreason = \"r\"\n").is_err());
+ assert!(
+ parse(
+ "[[xfail]]\ncase = \"a\"\nclass = \"x\"\nreason = \"r\"\nplatforms = [\"osx\"]\n"
+ )
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn strict_in_both_directions_per_seed() {
+ let xfails = vec![entry("a", "stale", &[], Some(&[1, 2]))];
+ let ran = Ran::from([("a".to_string(), Some(set(&[0, 1, 2, 3])))]);
+ let observed = Observed::from([(("a".into(), "stale".into()), set(&[2, 3]))]);
+ let verdict = judge(&xfails, "linux", &ran, &observed);
+ assert_eq!(verdict.unexpected.len(), 1);
+ assert_eq!(verdict.unexpected[0].seeds, set(&[3]));
+ assert_eq!(verdict.fixed.len(), 1);
+ assert_eq!(verdict.fixed[0].seeds, Some(set(&[1])));
+ }
+
+ #[test]
+ fn seeds_that_did_not_run_are_not_fixed() {
+ let xfails = vec![entry("a", "stale", &[], Some(&[1, 50]))];
+ let ran = Ran::from([("a".to_string(), Some(set(&[0, 1, 2])))]);
+ let observed = Observed::from([(("a".into(), "stale".into()), set(&[1]))]);
+ assert!(judge(&xfails, "linux", &ran, &observed).ok());
+ }
+
+ #[test]
+ fn unseeded_globs_and_platforms() {
+ let xfails = vec![
+ entry("export/x/*", "future", &["macos"], None),
+ Xfail {
+ flaky: true,
+ ..entry("seek/y", "stale", &[], None)
+ },
+ ];
+ let ran = Ran::from([
+ ("export/x/avf".to_string(), None),
+ ("export/x/ffmpeg".to_string(), None),
+ ("seek/y".to_string(), None),
+ ]);
+ let observed = Observed::from([(("export/x/avf".into(), "future".into()), set(&[]))]);
+ let verdict = judge(&xfails, "macos", &ran, &observed);
+ assert!(verdict.unexpected.is_empty());
+ assert_eq!(verdict.fixed.len(), 1);
+ assert_eq!(verdict.fixed[0].case, "export/x/ffmpeg");
+ let verdict = judge(&xfails, "linux", &ran, &observed);
+ assert_eq!(verdict.unexpected.len(), 1);
+ assert!(verdict.fixed.is_empty());
+ }
+
+ #[test]
+ fn bless_only_touches_this_platform() {
+ let xfails = vec![
+ entry("a", "stale", &[], None),
+ entry("b", "future", &[], Some(&[1, 2, 40])),
+ entry("c", "stale", &["windows"], None),
+ ];
+ let ran = Ran::from([
+ ("a".to_string(), None),
+ ("b".to_string(), Some(set(&[0, 1, 2, 3]))),
+ ("c".to_string(), None),
+ ("d".to_string(), None),
+ ]);
+ let observed = Observed::from([
+ (("b".into(), "future".into()), set(&[2, 3])),
+ (("d".into(), "missing".into()), set(&[])),
+ ]);
+ let problems =
+ BTreeMap::from([(("d".into(), "missing".into()), "3 frames missing".into())]);
+ let blessed = bless(&xfails, "macos", &ran, &observed, &problems);
+ assert!(
+ judge(&blessed, "macos", &ran, &observed).ok(),
+ "{blessed:#?}"
+ );
+ let a: Vec<&Xfail> = blessed.iter().filter(|x| x.case == "a").collect();
+ assert_eq!(a.len(), 1);
+ assert_eq!(a[0].platforms, vec!["linux", "windows"]);
+ assert!(blessed.contains(&entry("c", "stale", &["windows"], None)));
+ let b_mac: Vec<&Xfail> = blessed
+ .iter()
+ .filter(|x| x.case == "b" && x.applies_on("macos"))
+ .collect();
+ assert_eq!(b_mac.len(), 1);
+ assert_eq!(b_mac[0].seeds, Some(set(&[2, 3, 40])));
+ let d = blessed.iter().find(|x| x.case == "d").unwrap();
+ assert_eq!(d.reason, "TODO: 3 frames missing");
+ assert_eq!(d.platforms, vec!["macos"]);
+ assert_eq!(
+ bless(&blessed, "macos", &ran, &observed, &problems),
+ blessed,
+ "blessing twice changes nothing"
+ );
+ }
+
+ #[test]
+ fn bless_merges_platforms_back() {
+ let xfails = vec![entry("a", "stale", &["linux", "windows"], None)];
+ let ran = Ran::from([("a".to_string(), None)]);
+ let observed = Observed::from([(("a".into(), "stale".into()), set(&[]))]);
+ let blessed = bless(&xfails, "macos", &ran, &observed, &BTreeMap::new());
+ assert_eq!(blessed, vec![entry("a", "stale", &[], None)]);
+ }
+}
diff --cc crates/verify-expect/src/main.rs
index f20da19dd,000000000..f058fffb8
mode 100644,000000..100644
--- a/crates/verify-expect/src/main.rs
+++ b/crates/verify-expect/src/main.rs
@@@ -1,157 -1,0 +1,160 @@@
+//! `cap-verify-expect check <file>...` validates expectations files.
+//! `cap-verify-expect bless <report dir or .jsonl>...` rewrites every
+//! expectations file named in the records so those runs pass exactly. Records
+//! from several platforms (for example the CI report artifacts of all three
+//! OSes) can be blessed in one call; each platform only changes its own
+//! entries.
+
+use std::{
+ collections::{BTreeMap, BTreeSet},
+ path::{Path, PathBuf},
+ process::ExitCode,
+};
+
- use cap_verify_expect::{Observed, Ran, Record, bless, header, load, parse, render};
++use cap_verify_expect::{Observed, Outcome, Ran, Record, bless, header, load, parse, render};
+
+fn collect(path: &Path, out: &mut Vec<PathBuf>) {
+ if path.is_dir() {
+ let Ok(entries) = std::fs::read_dir(path) else {
+ return;
+ };
+ let mut entries: Vec<PathBuf> = entries.flatten().map(|e| e.path()).collect();
+ entries.sort();
+ for entry in entries {
+ collect(&entry, out);
+ }
+ } else if path.extension().is_some_and(|ext| ext == "jsonl") {
+ out.push(path.to_path_buf());
+ }
+}
+
+fn repo_root() -> PathBuf {
+ std::env::var_os("CAP_VERIFY_ROOT")
+ .map(PathBuf::from)
+ .unwrap_or_else(|| Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."))
+}
+
+#[derive(Default)]
+struct Run {
+ ran: Ran,
+ observed: Observed,
+ problems: BTreeMap<(String, String), String>,
+}
+
+fn bless_command(inputs: &[String]) -> ExitCode {
+ let mut files = Vec::new();
+ for input in inputs {
+ collect(Path::new(input), &mut files);
+ }
+ if files.is_empty() {
+ eprintln!("no .jsonl records under {inputs:?}");
+ return ExitCode::FAILURE;
+ }
+ let mut runs: BTreeMap<String, BTreeMap<String, Run>> = BTreeMap::new();
+ for file in &files {
+ let text = std::fs::read_to_string(file).unwrap_or_default();
+ for line in text.lines().filter(|l| !l.trim().is_empty()) {
+ let record: Record = match serde_json::from_str(line) {
+ Ok(record) => record,
+ Err(e) => {
+ eprintln!("{}: skipping a record: {e}", file.display());
+ continue;
+ }
+ };
++ if record.outcome == Outcome::Unsupported {
++ continue;
++ }
+ let run = runs
+ .entry(record.expectations.clone())
+ .or_default()
+ .entry(record.platform.clone())
+ .or_default();
+ let ran = run.ran.entry(record.case.clone()).or_insert(None);
+ if let Some(seeds) = &record.seeds_ran {
+ ran.get_or_insert_with(BTreeSet::new).extend(seeds);
+ }
+ for (class, seeds) in &record.failures {
+ run.observed
+ .entry((record.case.clone(), class.clone()))
+ .or_default()
+ .extend(seeds);
+ if let Some(problem) = record.problems.get(class) {
+ run.problems
+ .entry((record.case.clone(), class.clone()))
+ .or_insert_with(|| problem.clone());
+ }
+ }
+ }
+ }
+ let root = repo_root();
+ for (expectations, platforms) in &runs {
+ let path = root.join(expectations);
+ let text = std::fs::read_to_string(&path).unwrap_or_default();
+ let before = load(&path);
+ let mut entries = before.clone();
+ for (platform, run) in platforms {
+ entries = bless(&entries, platform, &run.ran, &run.observed, &run.problems);
+ }
+ let added = entries.iter().filter(|e| !before.contains(e)).count();
+ let removed = before.iter().filter(|e| !entries.contains(e)).count();
+ let platform_list: Vec<&String> = platforms.keys().collect();
+ if added == 0 && removed == 0 {
+ println!("{expectations}: unchanged ({platform_list:?})");
+ continue;
+ }
+ if let Err(e) = std::fs::write(&path, format!("{}{}", header(&text), render(&entries))) {
+ eprintln!("{}: {e}", path.display());
+ return ExitCode::FAILURE;
+ }
+ println!(
+ "{expectations}: {removed} entries removed or changed, {added} written ({platform_list:?}); review the diff and fill in TODO reasons"
+ );
+ }
+ ExitCode::SUCCESS
+}
+
+fn check_command(paths: &[String]) -> ExitCode {
+ let mut ok = true;
+ for path in paths {
+ match std::fs::read_to_string(path)
+ .map_err(|e| e.to_string())
+ .and_then(|t| parse(&t))
+ {
+ Ok(entries) => {
+ let todo = entries
+ .iter()
+ .filter(|e| e.reason.starts_with("TODO"))
+ .count();
+ if todo > 0 {
+ eprintln!("{path}: {todo} entries still have a TODO reason");
+ ok = false;
+ } else {
+ println!("{path}: {} entries", entries.len());
+ }
+ }
+ Err(e) => {
+ eprintln!("{path}: {e}");
+ ok = false;
+ }
+ }
+ }
+ if ok {
+ ExitCode::SUCCESS
+ } else {
+ ExitCode::FAILURE
+ }
+}
+
+fn main() -> ExitCode {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ match args.split_first() {
+ Some((command, rest)) if command == "bless" && !rest.is_empty() => bless_command(rest),
+ Some((command, rest)) if command == "check" && !rest.is_empty() => check_command(rest),
+ _ => {
+ eprintln!(
+ "usage: cap-verify-expect bless <report dir | .jsonl>...\n cap-verify-expect check <expectations.toml>..."
+ );
+ ExitCode::from(2)
+ }
+ }
+}
diff --cc crates/verify/expectations.toml
index 235580785,1dd424897..d8db99017
--- a/crates/verify/expectations.toml
+++ b/crates/verify/expectations.toml
@@@ -173,61 -170,14 +174,68 @@@ reason = "On the macos-15 runner (parav
link = "https://github.com/CapSoftware/Cap/pull/2603"
[[xfail]]
- case = "seek/seek-*/keyframes60/ffmpeg"
+ case = "seek/seek-native/keyframes60/ffmpeg"
class = "stale"
platforms = ["linux", "windows"]
- reason = "NEW: FFmpeg decoder seeks near the start show frame 0 (frame 124 at 60 fps shows source 0 instead of 61) and one keyframe seek answers one frame stale (linux runner; the x264 fallback fixture)"
+ reason = "NEW: FFmpeg decoder. Off macOS this fixture is libx264 (the AVFoundation encoder is unavailable), so its keyframe set and shuffled request order differ from macOS. Requests 366 (6.1 s), 1, 124 (all 60 fps seeks): 124 shows source frame 0 for 61, the first-frame shortcut bug of seek/seek-gop/home-then-play30/ffmpeg. Request 490 shows 243 for 244: the 2-frame backward lookback tolerance. seek-gop/keyframes60/ffmpeg passes on both. Identical on Linux and Windows, 3 of 3 runs each"
+ link = ""
+[[xfail]]
+case = "editing/mapping/duration-covered"
+class = "coverage"
+reason = "NEW: a fullscreen text segment (a hold) left past the end of the clips (place a text card near the end, then trim or delete clips; clip edits do not ripple text segments) still adds its length to TimelineConfiguration::duration(), but get_frame_mapping returns None from the content end on, so the hold and the time before it have no source frame. Minimal repro: Hold at 0.92 of a 7 s clip, then trim the clip end"
+link = ""
+
+[[xfail]]
+case = "editing/export/hold-past-end"
+class = "frame-count"
+reason = "NEW: same as editing/mapping/duration-covered, end to end: a 1 s fullscreen text at 5.4 s and the clip trimmed to 3.2 s give a 4.2 s timeline, but the export stops at the first unmapped frame: 96 frames instead of 126, and the text card is never rendered"
+link = ""
+
+[[xfail]]
+case = "captions/app/segmentation/unicode"
+class = "caption-segments"
+reason = "NEW (minor): caption chunking decides that a boundary word is a weak one-letter word with String::len() (bytes), so a one-letter word outside ASCII such as the French preposition 'à' is not weak and a caption can end on it (apps/desktop-gpui/src/transcription.rs caption_boundary_word_is_weak). Repro: cargo test --manifest-path apps/desktop-gpui/Cargo.toml --bin cap-gpui segmentation_matches_reference_unicode -- --nocapture"
+link = ""
+
+[[xfail]]
+case = "captions/legacy-migration/ends-at-timeline-end"
+class = "caption-migration"
+reason = "NEW (minor): loading a legacy (output-timed) project drops a caption that ends exactly at the timeline end: synchronize_captions maps each end through source_start + (end - start) / timescale, which rounds just below the timeline end after a clip transition (clips 41/15 s and 82/15 s, 0.2 s transition: 7.9999999 < 8.0), so the end does not map and the whole caption is discarded"
+link = ""
+
+[[xfail]]
+case = "editing/export/multi-segment/seed-7"
+class = "stale"
+reason = "FFmpeg decoder (full tier): after the timeline played clip 0 from 1.68 s to its end and then transitions back into clip 0 at 0 s, the 10 frames after the transition show source frame 0 instead of 20-29 (deterministic). Same mechanism as the seek/*/storm*/ffmpeg xfail: backward seeks near the start answer frame 0"
+link = ""
+
+[[xfail]]
+case = "editing/export/same-clip-transition/forward/ffmpeg"
+class = "stale"
+reason = "NEW: FFmpeg decoder, cross-fade between two parts of the same recording clip (0-2 s, then 3-5.5 s, 0.8 s transition): the export reads one decoder at two positions interleaved and every third blend frame takes the far side from the near position (frame 37: incoming should be source 90, shows 35; up to 55 source frames stale). Deterministic; AVAssetReader passes this case (its 60 fps variant is the */basic/transition/*60*/avf xfail)"
+link = ""
+
+[[xfail]]
+case = "editing/export/basic/seed-5"
+class = "stale"
+reason = "FFmpeg decoder, same-clip cross-fade (see editing/export/same-clip-transition/forward/ffmpeg): blend frame 53 one source frame stale"
+link = ""
+
+[[xfail]]
+case = "editing/export/basic/seed-23"
+class = "stale"
+reason = "FFmpeg decoder (full tier), same-clip cross-fade (see editing/export/same-clip-transition/forward/ffmpeg): blend frames up to 70 source frames stale"
+link = ""
+
+[[xfail]]
+case = "editing/export/multi-segment/seed-7"
+class = "unreadable"
+reason = "FFmpeg decoder (full tier): one blend frame of the transition back into clip 0 mixes two stale frames and its marker is unreadable (same bug as the stale entry above)"
+link = ""
++
+ [[xfail]]
+ case = "seek/seek-gop/home-then-play30/ffmpeg"
+ class = "stale"
+ reason = "NEW: FFmpeg decoder freezes on the first frame after a jump to the start. Seek 6.1 s, seek 0, seek 2.0 s and play: 31 of 122 frames show source frame 0 (up to 89 frames stale, about 1 s frozen). A request at grid 0..2 is answered by the first-frame shortcut (ffmpeg.rs, requested_frame <= MAX_FRAME_LOOKBACK_TOLERANCE) without resetting the reader, which stays near 6 s, and last_sent_frame becomes frame 0; the next request is then not 'far forward' of frame 0 (< FRAME_CACHE_SIZE), so no reset happens, the reader vends frames past the request and the answer falls back to last_sent_frame (frame 0) until playback outruns FRAME_CACHE_SIZE. Main decoder on Linux and on Windows without a D3D11 video device; macOS AVAssetReader passes. Minimal: CAP_VERIFY_SEEK_SCRIPT='seek-gop@60:6.1,0.0167,2.0667' (third request shows frame 0 for 61)"
+ link = ""
diff --cc crates/verify/src/pipeline.rs
index 456fbb899,aef09b782..3a5fc462c
--- a/crates/verify/src/pipeline.rs
+++ b/crates/verify/src/pipeline.rs
@@@ -405,9 -405,28 +405,30 @@@ async fn record_segment
})
}
--/// Records a Studio project (one recording segment per spec segment, like
--/// pause/resume) into `dir`.
+ /// The emitters sleep until each frame's time. Windows wakes timers on its
+ /// default 15.6 ms tick, which by itself makes frames up to a tick late
+ /// (more under load); the product raises the timer resolution the same way
+ /// for playback and export.
+ fn high_resolution_timer() {
+ #[cfg(windows)]
+ {
+ #[link(name = "winmm")]
+ unsafe extern "system" {
+ fn timeBeginPeriod(period: u32) -> u32;
+ }
+ static ONCE: std::sync::Once = std::sync::Once::new();
- ONCE.call_once(|| unsafe {
- timeBeginPeriod(1);
++ ONCE.call_once(|| {
++ assert_eq!(
++ unsafe { timeBeginPeriod(1) },
++ 0,
++ "set Windows timer resolution"
++ );
+ });
+ }
+ }
+
pub async fn record_studio(spec: &RecordedSpec, dir: &Path) -> anyhow::Result<()> {
+ high_resolution_timer();
crate::media::init();
if dir.exists() {
std::fs::remove_dir_all(dir)?;
diff --cc crates/verify/src/report.rs
index de8ee4e50,4d0e421a9..d67618c45
--- a/crates/verify/src/report.rs
+++ b/crates/verify/src/report.rs
@@@ -63,10 -57,11 +63,13 @@@ pub struct Case
pub streams: Vec<StreamReport>,
pub problems: Vec<String>,
/// Failure classes seen (see `expectations.toml`).
- pub classes: std::collections::BTreeSet<String>,
+ pub classes: BTreeSet<String>,
+ /// First problem per class (the draft reason when blessing).
+ class_problems: BTreeMap<String, String>,
pub notes: Vec<String>,
+ /// Set when this runner cannot run the case at all (for example no
+ /// D3D11 video device for Media Foundation on a GPU-less Windows VM).
+ pub unsupported: Option<String>,
}
impl Case {
@@@ -79,8 -74,23 +82,24 @@@
streams: Vec::new(),
problems: Vec::new(),
classes: Default::default(),
+ class_problems: Default::default(),
notes: Vec::new(),
+ unsupported: None,
+ }
+ }
+
+ /// Marks the case as impossible on this machine. With
+ /// `CAP_VERIFY_REQUIRE_SUPPORTED=1` (runners that must have every path)
+ /// it is a failure of class `unsupported` instead.
+ pub fn unsupported(&mut self, reason: impl Into<String>) {
+ let reason = reason.into();
+ if std::env::var("CAP_VERIFY_REQUIRE_SUPPORTED").as_deref() == Ok("1") {
+ self.problem(
+ "unsupported",
+ format!("unsupported on this machine: {reason}"),
+ );
+ } else {
+ self.unsupported = Some(reason);
}
}
@@@ -159,44 -215,29 +178,45 @@@ fn repro_command(id: &str) -> String
)
}
-/// Whether a case id is selected by `CAP_VERIFY_CASE` (glob, default all).
+/// Whether a case runs: `CAP_VERIFY_CASE`, `CAP_VERIFY_SKIP` and
+/// `CAP_VERIFY_SHARD` (see `cap_verify_expect::case_selected`).
pub fn selected(id: &str) -> bool {
- match std::env::var("CAP_VERIFY_CASE") {
- Ok(pattern) if !pattern.is_empty() => pattern.split(',').any(|p| glob_match(p, id)),
- _ => true,
- }
+ cap_verify_expect::case_selected(id)
}
-fn write_result(result: &CaseResult) {
- let Some(dir) = std::env::var_os("CAP_VERIFY_REPORT_DIR") else {
- return;
+fn write_result(result: &CaseResult, classes: &BTreeMap<String, String>) {
+ use cap_verify_expect::{Outcome, Record};
+ let record = Record {
+ suite: "cap-verify".into(),
+ expectations: EXPECTATIONS.into(),
+ case: result.id.clone(),
+ platform: result.platform.clone(),
+ tier: match result.tier {
+ Tier::Fast => "fast".into(),
+ Tier::Full => "full".into(),
+ },
+ outcome: match result.outcome.as_str() {
+ "pass" => Outcome::Pass,
++ "unsupported" => Outcome::Unsupported,
+ "xfail" => Outcome::Xfail,
+ "XPASS" => Outcome::Xpass,
+ _ => Outcome::Fail,
+ },
+ failures: classes
+ .keys()
+ .map(|class| (class.clone(), Default::default()))
+ .collect(),
+ seeds_ran: None,
+ problems: classes.clone(),
+ summary: result.summary.clone(),
+ repro: result.repro.clone(),
+ seconds: result.seconds,
};
- let dir = PathBuf::from(dir);
- let _ = std::fs::create_dir_all(&dir);
- let file = dir.join(format!("{}.jsonl", std::process::id()));
- if let Ok(mut f) = std::fs::OpenOptions::new()
- .create(true)
- .append(true)
- .open(file)
- && let Ok(line) = serde_json::to_string(result)
- {
- let _ = writeln!(f, "{line}");
- }
+ let extra = serde_json::json!({
+ "streams": result.streams,
+ "notes": result.notes,
+ });
+ cap_verify_expect::write_records(&[(record, extra)]);
}
/// Settles a case against the expectations file. Returns an error message
@@@ -205,17 -246,18 +225,19 @@@ pub fn settle(case: Case) -> Result<Cas
let xfails = xfails_for(&case.id);
let failed = case.failed();
let repro = repro_command(&case.id);
- let unexpected: Vec<&String> = case
+ let platform = platform();
+ let ran = cap_verify_expect::Ran::from([(case.id.clone(), None)]);
+ let observed: cap_verify_expect::Observed = case
.classes
.iter()
- .filter(|class| !xfails.iter().any(|x| &x.class == *class))
- .collect();
- let fixed: Vec<&Xfail> = xfails
- .iter()
- .filter(|x| !x.flaky && !case.classes.contains(&x.class))
+ .map(|class| ((case.id.clone(), class.clone()), Default::default()))
.collect();
+ let verdict = cap_verify_expect::judge(&xfails, platform, &ran, &observed);
+ let unexpected: Vec<&String> = verdict.unexpected.iter().map(|u| &u.class).collect();
+ let fixed: Vec<&Xfail> = verdict.fixed.iter().map(|f| &f.xfail).collect();
- let outcome = if !unexpected.is_empty() {
+ let outcome = if case.unsupported.is_some() && !failed {
+ "unsupported"
+ } else if !unexpected.is_empty() {
"FAIL"
} else if !fixed.is_empty() {
"XPASS"
@@@ -243,11 -287,15 +267,11 @@@
x.link
));
}
- let blessing = std::env::var_os("CAP_VERIFY_BLESS").is_some();
- if blessing && failed {
- bless(&case);
- }
let result = CaseResult {
id: case.id.clone(),
- platform: platform().to_string(),
+ platform: platform.to_string(),
tier: tier(),
- passed: matches!(outcome, "pass" | "xfail"),
- passed: blessing || matches!(outcome, "pass" | "xfail" | "unsupported"),
++ passed: matches!(outcome, "pass" | "xfail" | "unsupported"),
summary: summary.clone(),
streams: case.streams,
notes: case.notes,
diff --cc crates/verify/tests/common/mod.rs
index 2c84eda88,67aa9d6a0..fa051b2e9
--- a/crates/verify/tests/common/mod.rs
+++ b/crates/verify/tests/common/mod.rs
@@@ -269,10 -380,10 +380,32 @@@ pub fn read_expecting
img: &impl video_code::PixelSource,
expectation: &cap_verify::model::FrameExpectation,
) -> FrameReadout {
-- FrameReadout {
++ let readout = FrameReadout {
screen: oracle::read_expecting(img, StreamKind::Screen, &expectation.screen),
camera: oracle::read_expecting(img, StreamKind::Camera, &expectation.camera),
++ };
++ if std::env::var("CAP_VERIFY_TRACE_BLEND").as_deref() == Ok("1") {
++ for (kind, expected, observed) in [
++ (StreamKind::Screen, &expectation.screen, &readout.screen),
++ (StreamKind::Camera, &expectation.camera, &readout.camera),
++ ] {
++ if matches!(expected, StreamExpectation::Blend { .. })
++ && let Ok(cells) = video_code::read_cells(img, kind)
++ {
++ eprintln!(
++ "[cap-verify-blend] {}",
++ serde_json::json!({
++ "stream": kind,
++ "expected": expected,
++ "observed": observed,
++ "contrast": cells.contrast,
++ "levels": cells.levels,
++ })
++ );
++ }
++ }
}
++ readout
}
/// Checks a sequential output (export or sequential playback) frame by frame
diff --cc crates/verify/tests/export.rs
index 8c9b192dc,dd8b07e4c..03954ff1f
--- a/crates/verify/tests/export.rs
+++ b/crates/verify/tests/export.rs
@@@ -332,6 -335,6 +335,18 @@@ fn across_segments(config: &mut Project
);
}
++#[test]
++#[ignore]
++fn prepare_recorded_fixtures() {
++ common::recorded(&catalog::recorded_studio(report::tier()));
++ for spec in catalog::instant_variants(report::tier()) {
++ cap_verify::fixture::ensure_fixture_keyed(spec.cache_key(), |dir| {
++ common::runtime().block_on(cap_verify::pipeline::record_instant(&spec, dir))
++ })
++ .expect("instant fixture");
++ }
++}
++
/// A Studio project recorded through the real recording pipeline.
#[test]
fn recorded_studio() {
diff --cc scripts/verify/summary.py
index 0f2bb9e8b,000000000..9c5cab1f8
mode 100755,000000..100755
--- a/scripts/verify/summary.py
+++ b/scripts/verify/summary.py
@@@ -1,196 -1,0 +1,204 @@@
+#!/usr/bin/env python3
+"""Summarises engine verification records (JSON lines written to
+CAP_VERIFY_REPORT_DIR by every suite) as GitHub job-summary markdown or
+plain text.
+
+ summary.py [--title T] [--text] [--junit FILE]... [--flaky FILE] DIR...
+
+Exit status is 0; the test runner's own exit status decides the job.
+"""
+
+import argparse
+import glob
+import json
+import os
+import xml.etree.ElementTree as ET
+
+MAX_MISMATCHES = 12
+MAX_CASES = 40
+
+
+def load_records(dirs):
+ records = []
+ for d in dirs:
+ for path in sorted(glob.glob(os.path.join(d, "**", "*.jsonl"), recursive=True)):
+ with open(path, encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if not line:
+ continue
+ try:
+ r = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ r["case"] = r.get("case") or r.get("id", "?")
+ r["outcome"] = str(r.get("outcome", "?")).lower()
+ records.append(r)
+ return records
+
+
+def junit_failures(paths):
+ """(test name, message) for failed or errored junit test cases."""
+ out = []
+ for path in paths:
+ if not os.path.exists(path):
+ continue
+ for case in ET.parse(path).getroot().iter("testcase"):
+ for tag in ("failure", "error"):
+ node = case.find(tag)
+ if node is not None:
+ text = (node.text or node.get("message") or "").strip()
+ out.append((f"{case.get('classname', '')} {case.get('name', '')}".strip(), text))
+ break
+ return out
+
+
+def crash_excerpt(msg, limit):
+ """The first panic (message and a few lines after it), else the tail."""
+ lines = msg.splitlines()
+ for i, line in enumerate(lines):
+ if "panicked at" in line or "error:" in line.lower():
+ excerpt = []
+ for follow in lines[i:i + 12]:
+ if "stack backtrace" in follow.lower():
+ break
+ excerpt.append(follow)
+ return excerpt
+ return lines[-limit:]
+
+
+def frame(m):
+ def fmt(v):
+ return "none" if v is None else f"seg {v[0]} frame {v[1]}"
+ delta = f", {m['delta']:+d} source frames" if m.get("delta") is not None else ""
+ detail = f" ({m['detail']})" if m.get("detail") else ""
+ return (
+ f"output frame {m.get('output_frame')} at {m.get('time_secs', 0):.3f} s: {m.get('kind')} "
+ f"expected {fmt(m.get('expected'))}, got {fmt(m.get('observed'))}{delta}{detail}"
+ )
+
+
+def details(r):
+ lines = []
+ summary = (r.get("summary") or "").strip()
+ if summary:
+ lines.extend(summary.splitlines())
+ for stream in r.get("streams") or []:
+ mismatches = stream.get("mismatches") or []
+ if not mismatches:
+ continue
+ name = stream.get("stream") or "stream"
+ lines.append(f"{name}: first {min(len(mismatches), MAX_MISMATCHES)} of {len(mismatches)} mismatches")
+ lines.extend(" " + frame(m) for m in mismatches[:MAX_MISMATCHES])
+ if not r.get("streams"):
+ for class_name, problem in (r.get("problems") or {}).items():
+ if problem not in summary:
+ lines.append(f"{class_name}: {problem}")
+ return lines
+
+
+def render(records, title, junit, flaky, text):
+ counts = {}
+ for r in records:
+ counts[r["outcome"]] = counts.get(r["outcome"], 0) + 1
+ bad = [r for r in records if r["outcome"] in ("fail", "xpass")]
+ xfails = [r for r in records if r["outcome"] == "xfail"]
+ seconds = sum(float(r.get("seconds") or 0) for r in records)
+ head = (
+ f"{len(records)} cases: {counts.get('pass', 0)} pass, {counts.get('xfail', 0)} expected failures, "
- f"{counts.get('fail', 0)} FAILED, {counts.get('xpass', 0)} unexpectedly passing ({seconds:.0f} s of case time)"
++ f"{counts.get('fail', 0)} FAILED, {counts.get('xpass', 0)} unexpectedly passing, "
++ f"{counts.get('unsupported', 0)} unsupported ({seconds:.0f} s of case time)"
+ )
+ recorded = {r["case"] for r in records}
+ crashed = [(name, msg) for name, msg in junit if not any(c in msg for c in recorded)]
+ out = []
+ if text:
+ out.append(f"== engine verify {title}: {head}")
+ for r in bad:
+ out.append(f"{r['outcome'].upper()} {r['case']}")
+ out.extend(" " + line for line in details(r))
+ if r.get("repro"):
+ out.append(f" repro: {r['repro']}")
+ for name, msg in crashed:
+ out.append(f"TEST FAILED {name}")
+ out.extend(" " + line for line in crash_excerpt(msg, 15))
+ for name in flaky:
+ out.append(f"FLAKY {name}: failed, then passed when rerun (still a failure: fix the cause)")
+ return "\n".join(out)
+
+ icon = "FAILED" if bad or crashed else "passed"
+ out.append(f"## Engine verify, {title}: {icon}")
+ out.append("")
+ out.append(head)
+ out.append("")
+ if flaky:
+ out.append("### Flaky")
+ out.append("Failed, then passed when rerun once. The job still fails: find the nondeterminism.")
+ out.extend(f"- `{name}`" for name in flaky)
+ out.append("")
+ if bad:
+ out.append("### Failures")
+ for r in bad[:MAX_CASES]:
+ kind = "unexpectedly passes" if r["outcome"] == "xpass" else "FAILED"
+ out.append(f"**`{r['case']}`** {kind} ({float(r.get('seconds') or 0):.1f} s)")
+ out.append("```text")
+ out.extend(details(r)[:MAX_MISMATCHES * 3])
+ out.append("```")
+ if r.get("repro"):
+ out.append(f"Repro: `{r['repro']}`")
+ out.append("")
+ if len(bad) > MAX_CASES:
+ out.append(f"... and {len(bad) - MAX_CASES} more (see the report artifact)")
+ if crashed:
+ out.append("### Tests that failed without a case record")
+ for name, msg in crashed[:MAX_CASES]:
+ out.append(f"**`{name}`**")
+ out.append("```text")
+ out.extend(crash_excerpt(msg, 25))
+ out.append("```")
++ unsupported = [r for r in records if r["outcome"] == "unsupported"]
++ if unsupported:
++ out.append(f"<details><summary>Unsupported on this runner ({len(unsupported)})</summary>")
++ out.append("")
++ out.extend(f"- `{r['case']}`: {r.get('summary', '')}" for r in unsupported)
++ out.append("")
++ out.append("</details>")
+ if xfails:
+ out.append(f"<details><summary>Expected failures ({len(xfails)})</summary>")
+ out.append("")
+ out.append("| Case | Classes | Summary |")
+ out.append("| --- | --- | --- |")
+ for r in xfails:
+ classes = ", ".join(sorted((r.get("failures") or {}).keys())) or "-"
+ summary = (r.get("summary") or "").splitlines()[0:1]
+ summary = summary[0].replace("|", "\\|")[:200] if summary else ""
+ out.append(f"| `{r['case']}` | {classes} | {summary} |")
+ out.append("")
+ out.append("</details>")
+ slow = sorted(records, key=lambda r: -float(r.get("seconds") or 0))[:10]
+ if slow:
+ out.append("<details><summary>Slowest cases</summary>")
+ out.append("")
+ out.extend(f"- {float(r.get('seconds') or 0):.1f} s `{r['case']}`" for r in slow)
+ out.append("")
+ out.append("</details>")
+ return "\n".join(out)
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument("dirs", nargs="+")
+ parser.add_argument("--title", default="")
+ parser.add_argument("--text", action="store_true")
+ parser.add_argument("--junit", action="append", default=[])
+ parser.add_argument("--flaky", help="file with one flaky test name per line")
+ args = parser.parse_args()
+ flaky = []
+ if args.flaky and os.path.exists(args.flaky):
+ with open(args.flaky) as f:
+ flaky = [line.strip() for line in f if line.strip()]
+ print(render(load_records(args.dirs), args.title, junit_failures(args.junit), flaky, args.text))
+
+
+if __name__ == "__main__":
+ main()