Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

ci: engine verify workflow, suite planner and local runner

Richie McIlroy5efebd4859eb
diff --git a/.config/nextest.toml b/.config/nextest.toml
new file mode 100644
index 000000000..758fd9300
--- /dev/null
+++ b/.config/nextest.toml
@@ -0,0 +1,32 @@
+# cargo-nextest settings. The engine verification suite (scripts/verify/run.sh)
+# runs with the `default` profile locally and `ci` in engine-verify.yml.
+
+[profile.default]
+retries = 0
+fail-fast = false
+slow-timeout = { period = "60s" }
+
+# The decoder model fuzzers run 3 to 4 worker threads each.
+[[profile.default.overrides]]
+filter = 'binary_id(cap-rendering) and test(/^decoder::model::/)'
+threads-required = 3
+
+[profile.ci]
+# No retries: a flaky case is a bug. run.sh reruns failures once afterwards
+# only to label them flaky in the job summary; the job still fails.
+retries = 0
+fail-fast = false
+failure-output = "immediate-final"
+success-output = "never"
+status-level = "pass"
+final-status-level = "slow"
+slow-timeout = { period = "60s", terminate-after = 15 }
+
+[profile.ci.junit]
+path = "junit.xml"
+store-success-output = false
+store-failure-output = true
+
+[[profile.ci.overrides]]
+filter = 'binary_id(cap-rendering) and test(/^decoder::model::/)'
+threads-required = 3
diff --git a/.github/actions/engine-verify-setup/action.yml b/.github/actions/engine-verify-setup/action.yml
new file mode 100644
index 000000000..05d37d18b
--- /dev/null
+++ b/.github/actions/engine-verify-setup/action.yml
@@ -0,0 +1,80 @@
+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"
+ save-cache:
+ description: Save the Rust cache at the end of the job
+ default: "false"
+outputs:
+ 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 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:
+
+ - name: Rust cache
+ if: inputs.rust-cache == 'true'
+ uses: swatinem/rust-cache@v2
+ with:
+ prefix-key: v1-verify
+ shared-key: ${{ inputs.target }}
+ cache-bin: "false"
+ save-if: ${{ inputs.save-cache }}
+
+ - name: Native dependencies
+ shell: bash
+ env:
+ RUST_TARGET_TRIPLE: ${{ inputs.target }}
+ run: node scripts/setup.js
+
+ - 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; the key is the generator source.
+ - 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/fixture*.rs', 'crates/verify/src/catalog.rs', 'crates/verify/src/video_code.rs', 'crates/verify/src/audio_code.rs', 'crates/verify/src/media.rs', 'scripts/setup.js') }}
diff --git a/.github/workflows/engine-verify-label.yml b/.github/workflows/engine-verify-label.yml
new file mode 100644
index 000000000..fc1cfbba0
--- /dev/null
+++ b/.github/workflows/engine-verify-label.yml
@@ -0,0 +1,20 @@
+name: Engine verify (full)
+
+# Adding the `verify-full` label to a PR runs the FULL tier once. A separate
+# workflow so that adding any other label never produces a skipped (and
+# therefore passing) "Engine verify" check that would hide a failed FAST run.
+
+on:
+ pull_request:
+ types: [labeled]
+
+permissions:
+ contents: read
+ pull-requests: read
+
+jobs:
+ full:
+ if: github.event.label.name == 'verify-full'
+ uses: ./.github/workflows/engine-verify.yml
+ with:
+ tier: full
diff --git a/.github/workflows/engine-verify-os.yml b/.github/workflows/engine-verify-os.yml
new file mode 100644
index 000000000..b301cd2e2
--- /dev/null
+++ b/.github/workflows/engine-verify-os.yml
@@ -0,0 +1,190 @@
+name: Engine verify (one platform)
+
+# Called by engine-verify.yml once per platform. With one shard the build job
+# also runs the tests (no artifact round trip, one runner: macOS runners are
+# the scarce resource). With more shards it uploads a nextest archive and the
+# shard jobs run partitions of 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]"
+ save-cache:
+ type: boolean
+ default: false
+ cargo-config:
+ 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: ${{ inputs.shards > 1 && 'build' || 'build and test' }}
+ 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 }}
+ save-cache: ${{ inputs.save-cache }}
+
+ - 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
+ shell: bash
+ run: |
+ shards="${{ inputs.shards }}"
+ if (( shards > 1 )); then
+ scripts/verify/run.sh "${{ inputs.tier }}" --suites "${{ inputs.suites }}" --archive "$RUNNER_TEMP/verify.tar.zst"
+ else
+ scripts/verify/run.sh "${{ inputs.tier }}" --suites "${{ inputs.suites }}" --no-run
+ fi
+
+ - name: Upload test archive
+ if: inputs.shards > 1
+ 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
+
+ - name: Test
+ id: test
+ if: inputs.shards == 1
+ shell: bash
+ run: scripts/verify/run.sh "${{ inputs.tier }}" --suites "${{ inputs.suites }}"
+
+ - name: Summary
+ if: always() && inputs.shards == 1 && steps.test.outcome != 'skipped'
+ shell: bash
+ run: >-
+ "$(command -v python3 || command -v python)" scripts/verify/summary.py --title "${{ inputs.platform }} ${{ inputs.tier }}"
+ --junit "$CAP_VERIFY_REPORT_DIR/junit.xml" --flaky "$CAP_VERIFY_FLAKY_FILE"
+ "$CAP_VERIFY_REPORT_DIR" >> "$GITHUB_STEP_SUMMARY"
+
+ - name: Upload report
+ if: always() && inputs.shards == 1 && steps.test.outcome != 'skipped'
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
+ with:
+ name: verify-report-${{ inputs.platform }}-${{ inputs.tier }}-1
+ 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' && inputs.shards == 1
+ uses: actions/cache/save@v4
+ with:
+ path: ${{ runner.temp }}/verify-fixtures
+ key: ${{ steps.setup.outputs.fixtures-key }}
+
+ test:
+ name: shard ${{ matrix.shard }}/${{ inputs.shards }}
+ needs: build
+ if: inputs.shards > 1
+ runs-on: ${{ inputs.runner }}
+ timeout-minutes: 45
+ strategy:
+ fail-fast: false
+ matrix:
+ shard: ${{ fromJSON(inputs.shard-list) }}
+ env:
+ # Shards run prebuilt binaries: no toolchain install for rust-toolchain.toml.
+ RUSTUP_TOOLCHAIN: stable
+ 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: "false"
+
+ - 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"
+
+ - uses: actions/download-artifact@v4
+ with:
+ name: verify-archive-${{ inputs.platform }}-${{ github.run_attempt }}
+ path: ${{ runner.temp }}
+
+ - name: Test
+ id: test
+ shell: bash
+ run: >-
+ scripts/verify/run.sh "${{ inputs.tier }}" --suites "${{ inputs.suites }}"
+ --from-archive "$RUNNER_TEMP/verify.tar.zst" --partition "hash:${{ matrix.shard }}/${{ inputs.shards }}"
+
+ - 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 }} shard ${{ matrix.shard }}"
+ --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 --git a/.github/workflows/engine-verify.yml b/.github/workflows/engine-verify.yml
new file mode 100644
index 000000000..000a4d6d6
--- /dev/null
+++ b/.github/workflows/engine-verify.yml
@@ -0,0 +1,210 @@
+name: Engine verify
+
+# Oracle-based regression suite for the playback, export, recording, editing
+# and captions engines (crates/verify, crates/verify-expect, the decoder model
+# fuzzer in cap-rendering). See crates/verify/README.md.
+#
+# Tiers: FAST on every PR push; FULL with the `verify-full` label
+# (engine-verify-label.yml), in the merge queue and nightly. Only suites whose
+# code a change can reach run (scripts/verify/plan.py maps changed paths to
+# suites through the workspace dependency graph), and only on the platforms
+# where they test platform code. The "Engine verify" job is the one to require.
+
+on:
+ pull_request:
+ types: [opened, synchronize, reopened, ready_for_review]
+ merge_group:
+ schedule:
+ - cron: "23 3 * * *"
+ push:
+ branches:
+ - main
+ - ci/engine-verify
+ - ci/verify-ci
+ workflow_dispatch:
+ inputs:
+ tier:
+ description: Tier
+ type: choice
+ options: [fast, full]
+ default: full
+ suites:
+ description: "Comma-separated suites (default all, see scripts/verify/suites.json)"
+ type: string
+ default: ""
+ cargo-config:
+ description: "Extra cargo --config overrides, separated by ; (profile experiments)"
+ type: string
+ default: ""
+ workflow_call:
+ inputs:
+ tier:
+ type: string
+ default: full
+
+permissions:
+ contents: read
+ pull-requests: read
+
+concurrency:
+ group: engine-verify-${{ github.event.pull_request.number || github.ref }}-${{ inputs.tier || 'auto' }}
+ # Superseded PR pushes are cancelled; main and nightly runs finish so their
+ # caches are saved.
+ cancel-in-progress: ${{ github.event_name != 'schedule' && github.ref != 'refs/heads/main' }}
+
+jobs:
+ plan:
+ name: Plan
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ outputs:
+ run: ${{ steps.plan.outputs.run }}
+ tier: ${{ steps.tier.outputs.tier }}
+ matrix: ${{ steps.plan.outputs.matrix }}
+ save-cache: ${{ steps.tier.outputs.save-cache }}
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+
+ - name: Tier
+ id: tier
+ env:
+ INPUT_TIER: ${{ inputs.tier }}
+ EVENT: ${{ github.event_name }}
+ FULL_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'verify-full') }}
+ run: |
+ tier=fast
+ if [[ -n "$INPUT_TIER" ]]; then
+ tier="$INPUT_TIER"
+ elif [[ "$EVENT" == schedule || "$EVENT" == merge_group || "$FULL_LABEL" == true ]]; then
+ tier=full
+ fi
+ save=false
+ if [[ "$EVENT" == schedule || ( "$EVENT" == push && "$GITHUB_REF" =~ ^refs/heads/(main|ci/engine-verify|ci/verify-ci)$ ) ]]; then
+ save=true
+ fi
+ echo "tier=$tier" >> "$GITHUB_OUTPUT"
+ echo "save-cache=$save" >> "$GITHUB_OUTPUT"
+
+ - name: Changed files
+ id: files
+ env:
+ GH_TOKEN: ${{ github.token }}
+ EVENT: ${{ github.event_name }}
+ PR: ${{ github.event.pull_request.number }}
+ BEFORE: ${{ github.event.before }}
+ MQ_BASE: ${{ github.event.merge_group.base_sha }}
+ MQ_HEAD: ${{ github.event.merge_group.head_sha }}
+ SUITES: ${{ inputs.suites }}
+ run: |
+ set -euo pipefail
+ files="$RUNNER_TEMP/changed.txt"
+ scope=files
+ max=300
+ case "$EVENT" in
+ pull_request)
+ gh api "repos/$GITHUB_REPOSITORY/pulls/$PR/files" --paginate --jq '.[].filename' > "$files"
+ max=3000 ;;
+ merge_group)
+ gh api "repos/$GITHUB_REPOSITORY/compare/$MQ_BASE...$MQ_HEAD" --jq '.files[].filename' > "$files" ;;
+ push)
+ if [[ "$BEFORE" =~ ^0+$ ]]; then
+ scope=all
+ else
+ gh api "repos/$GITHUB_REPOSITORY/compare/$BEFORE...$GITHUB_SHA" --jq '.files[].filename' > "$files"
+ fi ;;
+ *) scope=all ;;
+ esac
+ echo "scope=$scope" >> "$GITHUB_OUTPUT"
+ echo "max=$max" >> "$GITHUB_OUTPUT"
+ [[ -f "$files" ]] && { echo "$(wc -l < "$files") changed files"; head -50 "$files"; } || true
+
+ - name: Plan
+ id: plan
+ env:
+ TIER: ${{ steps.tier.outputs.tier }}
+ SCOPE: ${{ steps.files.outputs.scope }}
+ MAX: ${{ steps.files.outputs.max }}
+ SUITES: ${{ inputs.suites }}
+ RUSTUP_TOOLCHAIN: stable
+ run: |
+ set -euo pipefail
+ if [[ "$SCOPE" == all ]]; then
+ python3 scripts/verify/plan.py changes --tier "$TIER" --all ${SUITES:+--suites "$SUITES"} > "$RUNNER_TEMP/plan.txt"
+ else
+ python3 scripts/verify/plan.py changes --tier "$TIER" --files "$RUNNER_TEMP/changed.txt" --max-files "$MAX" ${SUITES:+--suites "$SUITES"} > "$RUNNER_TEMP/plan.txt"
+ fi
+ cat "$RUNNER_TEMP/plan.txt"
+ cat "$RUNNER_TEMP/plan.txt" >> "$GITHUB_OUTPUT"
+ {
+ echo "## Engine verify plan ($TIER tier)"
+ grep -E '^(reason|suites)=' "$RUNNER_TEMP/plan.txt" | sed 's/^/- /'
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ verify:
+ name: ${{ matrix.platform }}
+ needs: plan
+ if: needs.plan.outputs.run == 'true'
+ strategy:
+ fail-fast: false
+ matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
+ uses: ./.github/workflows/engine-verify-os.yml
+ with:
+ platform: ${{ matrix.platform }}
+ runner: ${{ matrix.runner }}
+ target: ${{ matrix.target }}
+ tier: ${{ needs.plan.outputs.tier }}
+ suites: ${{ matrix.suites }}
+ shards: ${{ matrix.shards }}
+ shard-list: ${{ matrix.shard_list }}
+ save-cache: ${{ needs.plan.outputs.save-cache == 'true' }}
+ cargo-config: ${{ inputs.cargo-config || '' }}
+
+ gate:
+ name: Engine verify
+ needs: [plan, verify]
+ if: always()
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+ sparse-checkout: scripts/verify
+
+ - uses: actions/download-artifact@v4
+ if: needs.plan.outputs.run == 'true'
+ with:
+ pattern: verify-report-*
+ path: ${{ runner.temp }}/reports
+
+ - name: Verdict
+ env:
+ PLAN: ${{ needs.plan.result }}
+ RUN: ${{ needs.plan.outputs.run }}
+ VERIFY: ${{ needs.verify.result }}
+ TIER: ${{ needs.plan.outputs.tier }}
+ run: |
+ if [[ "$PLAN" != success ]]; then
+ echo "planning failed" >&2
+ exit 1
+ fi
+ if [[ "$RUN" != true ]]; then
+ echo "No engine code changed: nothing to verify." | tee -a "$GITHUB_STEP_SUMMARY"
+ exit 0
+ fi
+ if [[ -d "$RUNNER_TEMP/reports" ]]; then
+ for dir in "$RUNNER_TEMP"/reports/*/; do
+ name="$(basename "$dir")"
+ flaky=()
+ [[ -f "$dir/flaky.txt" ]] && flaky=(--flaky "$dir/flaky.txt")
+ python3 scripts/verify/summary.py --title "${name#verify-report-}" --junit "$dir/junit.xml" "${flaky[@]}" "$dir" >> "$GITHUB_STEP_SUMMARY"
+ echo >> "$GITHUB_STEP_SUMMARY"
+ done
+ fi
+ if [[ "$VERIFY" != success ]]; then
+ echo "engine verification $VERIFY ($TIER tier): see the platform jobs" >&2
+ exit 1
+ fi
+ echo "engine verification passed ($TIER tier)"
diff --git a/Cargo.toml b/Cargo.toml
index ec6d96553..a65433c7c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -114,6 +114,21 @@ opt-level = 2
[profile.dev.package.cap-verify]
opt-level = 3
+# Engine verification suite in CI (.github/workflows/engine-verify.yml).
+# Dependencies come from the Rust cache, so optimising them costs nothing on
+# a warm run and speeds up the cases; workspace crates rebuild on every run
+# and stay cheap to compile. No debuginfo or incremental state to cache.
+[profile.ci-verify]
+inherits = "dev"
+debug = 0
+incremental = false
+
+[profile.ci-verify.package."*"]
+opt-level = 1
+
+[profile.ci-verify.package.cap-verify]
+opt-level = 3
+
# Optimize for smaller binary size
[profile.release]
panic = "unwind"
diff --git a/scripts/verify/plan.py b/scripts/verify/plan.py
new file mode 100755
index 000000000..940bd75d3
--- /dev/null
+++ b/scripts/verify/plan.py
@@ -0,0 +1,282 @@
+#!/usr/bin/env python3
+"""Plans engine verification runs from scripts/verify/suites.json.
+
+ plan.py select --tier fast --platform linux [--suites a,b]
+ Prints three lines for run.sh: the suite names, the cargo target
+ selection and the nextest filter expression.
+
+ plan.py changes --tier fast [--files FILE | --all] [--metadata FILE]
+ Maps changed paths to suites through the workspace dependency graph
+ (`cargo metadata`) and prints GitHub step outputs: run, reason,
+ suites, matrix.
+
+ plan.py test
+ Self-test of the change mapping.
+"""
+
+import argparse
+import fnmatch
+import json
+import os
+import subprocess
+import sys
+
+ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))
+PLATFORMS = ["linux", "macos", "windows"]
+
+
+def load_config():
+ with open(os.path.join(ROOT, "scripts", "verify", "suites.json")) as f:
+ return json.load(f)
+
+
+def match(path, pattern):
+ if pattern.endswith("/**"):
+ return path.startswith(pattern[:-2])
+ return fnmatch.fnmatchcase(path, pattern)
+
+
+def suite_filter(suite):
+ parts = []
+ for binary in suite["binaries"]:
+ expr = f"binary_id({binary})"
+ if suite.get("test"):
+ expr = f"({expr} and test(={suite['test']}))"
+ parts.append(expr)
+ return " or ".join(parts)
+
+
+def select(config, tier, platform, names=None, local=False):
+ # Locally, platform-independent suites (CI runs them on linux only) run
+ # on every platform too.
+ suites = [
+ s for s in config["suites"]
+ if platform in s["platforms"][tier] or (local and s["platforms"][tier] == ["linux"])
+ ]
+ if names:
+ unknown = set(names) - {s["name"] for s in config["suites"]}
+ if unknown:
+ sys.exit(f"unknown suites: {', '.join(sorted(unknown))}")
+ suites = [s for s in suites if s["name"] in names]
+ return suites
+
+
+def cargo_args(suites):
+ packages, flags = [], []
+ for suite in suites:
+ args = suite["cargo"]
+ i = 0
+ while i < len(args):
+ if args[i] == "-p":
+ if args[i + 1] not in packages:
+ packages.append(args[i + 1])
+ i += 2
+ continue
+ if args[i] == "--test":
+ flag = ["--test", args[i + 1]]
+ i += 2
+ else:
+ flag = [args[i]]
+ i += 1
+ if flag not in flags:
+ flags.append(flag)
+ out = []
+ for package in packages:
+ out += ["-p", package]
+ for flag in flags:
+ out += flag
+ return out
+
+
+def cmd_select(args):
+ config = load_config()
+ names = [n for n in (args.suites or "").split(",") if n]
+ suites = select(config, args.tier, args.platform, names or None, args.local)
+ print(" ".join(s["name"] for s in suites))
+ print(" ".join(cargo_args(suites)))
+ print(" or ".join(f"({suite_filter(s)})" for s in suites))
+
+
+def workspace_graph(metadata):
+ """Package dirs and reverse dependencies (normal, dev and build)."""
+ dirs, deps = {}, {}
+ for package in metadata["packages"]:
+ name = package["name"]
+ dirs[name] = os.path.relpath(os.path.dirname(package["manifest_path"]), metadata["workspace_root"]).replace(os.sep, "/")
+ deps[name] = [
+ (d["name"], d.get("kind") or "normal")
+ for d in package["dependencies"]
+ if d.get("path")
+ ]
+ return dirs, deps
+
+
+def closure(root, deps):
+ """Packages whose code ends up in `root`'s tests: root's normal, dev and
+ build dependencies, then normal and build dependencies transitively."""
+ seen = {root}
+ stack = [(name, kind) for name, kind in deps.get(root, [])]
+ while stack:
+ name, _kind = stack.pop()
+ if name in seen or name not in deps:
+ continue
+ seen.add(name)
+ stack.extend((n, k) for n, k in deps[name] if k != "dev")
+ return seen
+
+
+def owning_package(path, dirs):
+ best = None
+ for name, d in dirs.items():
+ if d == ".":
+ continue
+ if path == d or path.startswith(d + "/"):
+ if best is None or len(d) > len(dirs[best]):
+ best = name
+ return best
+
+
+def affected(config, files, metadata, tier):
+ """Returns (suite names, reason)."""
+ all_names = [s["name"] for s in config["suites"]]
+ for path in files:
+ for pattern in config["always"]:
+ if match(path, pattern):
+ return all_names, f"{path} affects every suite"
+ dirs, deps = workspace_graph(metadata)
+ closures = {s["name"]: set().union(*(closure(r, deps) for r in s["roots"])) for s in config["suites"]}
+ owned = {}
+ for suite in config["suites"]:
+ for pattern in suite["own"]:
+ owned.setdefault(pattern, set()).add(suite["name"])
+ selected, reasons = set(), []
+ for path in files:
+ package = owning_package(path, dirs)
+ if package is None:
+ continue
+ owners = set()
+ for pattern, names in owned.items():
+ if match(path, pattern):
+ owners |= names
+ hits = owners if owners else {n for n, c in closures.items() if package in c}
+ if hits - selected:
+ reasons.append(f"{path} ({package}) -> {', '.join(sorted(hits))}")
+ selected |= hits
+ names = [n for n in all_names if n in selected]
+ if not names:
+ return [], "no engine code changed"
+ return names, "; ".join(reasons[:8]) + (" ..." if len(reasons) > 8 else "")
+
+
+def matrix(config, names, tier):
+ include = []
+ for platform in PLATFORMS:
+ suites = [s["name"] for s in config["suites"] if s["name"] in names and platform in s["platforms"][tier]]
+ if not suites:
+ continue
+ runner = config["runners"][platform]
+ include.append({
+ "platform": platform,
+ "runner": runner["runner"],
+ "target": runner["target"],
+ "shards": runner["shards"],
+ "shard_list": json.dumps(list(range(1, runner["shards"] + 1))),
+ "suites": ",".join(suites),
+ })
+ return {"include": include}
+
+
+def load_metadata(path):
+ if path:
+ with open(path) as f:
+ return json.load(f)
+ env = dict(os.environ)
+ env.setdefault("RUSTUP_TOOLCHAIN", "stable")
+ out = subprocess.run(
+ ["cargo", "metadata", "--no-deps", "--format-version", "1"],
+ cwd=ROOT, env=env, check=True, capture_output=True, text=True,
+ ).stdout
+ return json.loads(out)
+
+
+def cmd_changes(args):
+ config = load_config()
+ if args.all:
+ names, reason = [s["name"] for s in config["suites"]], "full run"
+ else:
+ with open(args.files) as f:
+ files = [line.strip() for line in f if line.strip()]
+ if len(files) >= args.max_files:
+ names, reason = [s["name"] for s in config["suites"]], f"{len(files)} changed files (list may be truncated)"
+ else:
+ names, reason = affected(config, files, load_metadata(args.metadata), args.tier)
+ if args.suites:
+ wanted = [n for n in args.suites.split(",") if n]
+ unknown = set(wanted) - {s["name"] for s in config["suites"]}
+ if unknown:
+ sys.exit(f"unknown suites: {', '.join(sorted(unknown))}")
+ names = [n for n in names if n in wanted]
+ reason += f" (limited to {args.suites})"
+ m = matrix(config, names, args.tier)
+ lines = {
+ "run": "true" if m["include"] else "false",
+ "reason": reason.replace("\n", " "),
+ "suites": ",".join(names),
+ "matrix": json.dumps(m, separators=(",", ":")),
+ }
+ for key, value in lines.items():
+ print(f"{key}={value}")
+
+
+def cmd_test(_args):
+ config = load_config()
+ metadata = load_metadata(None)
+ cases = [
+ (["apps/web/app/page.tsx", "README.md"], []),
+ (["crates/verify/tests/seek.rs"], ["seek"]),
+ (["crates/verify/tests/seek.rs", "crates/verify/tests/export.rs"], ["export", "seek"]),
+ (["crates/verify/src/oracle.rs"], ["verify-self", "export", "playback", "seek"]),
+ (["crates/rendering/src/decoder/ffmpeg.rs"], [s["name"] for s in config["suites"]]),
+ (["crates/video-decode/src/ffmpeg.rs"], [s["name"] for s in config["suites"]]),
+ (["Cargo.lock"], [s["name"] for s in config["suites"]]),
+ (["scripts/verify/run.sh"], [s["name"] for s in config["suites"]]),
+ (["apps/desktop-gpui/src/main.rs"], []),
+ ]
+ failed = 0
+ for files, expected in cases:
+ names, reason = affected(config, files, metadata, "fast")
+ ok = sorted(names) == sorted(expected)
+ failed += not ok
+ print(f"{'ok ' if ok else 'BAD'} {files} -> {names} ({reason})")
+ rendering_only = affected(config, ["crates/rendering/src/decoder/model/mod.rs"], metadata, "fast")[0]
+ if "decoder-model-ffmpeg" not in rendering_only:
+ failed += 1
+ print(f"BAD decoder model change -> {rendering_only}")
+ sys.exit(1 if failed else 0)
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ sub = parser.add_subparsers(dest="command", required=True)
+ p = sub.add_parser("select")
+ p.add_argument("--tier", choices=["fast", "full"], required=True)
+ p.add_argument("--platform", choices=PLATFORMS, required=True)
+ p.add_argument("--suites")
+ p.add_argument("--local", action="store_true")
+ p.set_defaults(func=cmd_select)
+ p = sub.add_parser("changes")
+ p.add_argument("--tier", choices=["fast", "full"], required=True)
+ p.add_argument("--files")
+ p.add_argument("--all", action="store_true")
+ p.add_argument("--metadata")
+ p.add_argument("--max-files", type=int, default=3000)
+ p.add_argument("--suites")
+ p.set_defaults(func=cmd_changes)
+ p = sub.add_parser("test")
+ p.set_defaults(func=cmd_test)
+ args = parser.parse_args()
+ args.func(args)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/verify/run.sh b/scripts/verify/run.sh
new file mode 100755
index 000000000..0f8ac605b
--- /dev/null
+++ b/scripts/verify/run.sh
@@ -0,0 +1,175 @@
+#!/usr/bin/env bash
+# Runs the engine verification suites, locally or in CI.
+#
+# scripts/verify/run.sh [fast|full] [options] [-- extra nextest args]
+#
+# --suites a,b only these suites (scripts/verify/suites.json);
+# default: every suite of the tier on this platform
+# --case GLOB only cases matching GLOB (CAP_VERIFY_CASE)
+# --list print the plan and exit
+# --no-run build only
+# --archive FILE build a nextest archive (CI build job)
+# --from-archive FILE run from a nextest archive (CI shard job)
+# --partition hash:M/N run one shard
+#
+# Uses cargo-nextest when installed (one process per test, parallel), else
+# runs `cargo test` per suite. Results: one JSON line per case in
+# $CAP_VERIFY_REPORT_DIR (default target/verify-report/<platform>-<tier>),
+# summarised at the end by scripts/verify/summary.py.
+#
+# Environment: CAP_VERIFY_CARGO_PROFILE (default dev; CI uses ci-verify),
+# CAP_VERIFY_NEXTEST_PROFILE (default default; CI uses ci),
+# CAP_VERIFY_FIXTURE_DIR (generated fixtures cache).
+set -euo pipefail
+
+root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+cd "$root"
+
+tier=fast
+suites=""
+mode=run
+archive=""
+partition=""
+extra=()
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ fast|full) tier="$1" ;;
+ --suites) suites="$2"; shift ;;
+ --case) export CAP_VERIFY_CASE="$2"; shift ;;
+ --list) mode=list ;;
+ --no-run) mode=build ;;
+ --archive) mode=archive; archive="$2"; shift ;;
+ --from-archive) mode=from-archive; archive="$2"; shift ;;
+ --partition) partition="$2"; shift ;;
+ --) shift; extra=("$@"); break ;;
+ -h|--help) sed -n '2,24p' "$0"; exit 0 ;;
+ *) echo "unknown argument: $1" >&2; exit 2 ;;
+ esac
+ shift
+done
+
+case "$(uname -s)" in
+ Darwin) platform=macos ;;
+ Linux) platform=linux ;;
+ MINGW*|MSYS*|CYGWIN*) platform=windows ;;
+ *) echo "unsupported platform $(uname -s)" >&2; exit 2 ;;
+esac
+
+py="$(command -v python3 || command -v python)"
+local_flag=""
+[[ -z "${CI:-}" ]] && local_flag=--local
+plan="$("$py" scripts/verify/plan.py select --tier "$tier" --platform "$platform" ${suites:+--suites "$suites"} $local_flag)"
+suite_names="$(sed -n 1p <<<"$plan")"
+read -r -a cargo_args <<<"$(sed -n 2p <<<"$plan")"
+filter="$(sed -n 3p <<<"$plan")"
+
+if [[ -z "$suite_names" ]]; then
+ echo "no $tier suites for $platform${suites:+ in $suites}"
+ exit 0
+fi
+
+# CAP_VERIFY_CARGO_CONFIG: extra `--config KEY=VALUE` overrides, `;` separated
+# (profile experiments). CAP_VERIFY_LOCKED=1 adds --locked.
+if [[ -n "${CAP_VERIFY_CARGO_CONFIG:-}" ]]; then
+ IFS=';' read -r -a overrides <<<"$CAP_VERIFY_CARGO_CONFIG"
+ for override in "${overrides[@]}"; do
+ [[ -n "$override" ]] && cargo_args+=(--config "$override")
+ done
+fi
+if [[ "${CAP_VERIFY_LOCKED:-}" == 1 ]]; then
+ cargo_args+=(--locked)
+fi
+
+profile="${CAP_VERIFY_CARGO_PROFILE:-dev}"
+nextest_profile="${CAP_VERIFY_NEXTEST_PROFILE:-default}"
+export CAP_VERIFY_TIER="$tier"
+export CAP_VERIFY_REPORT_DIR="${CAP_VERIFY_REPORT_DIR:-$root/target/verify-report/$platform-$tier}"
+
+echo "engine verify: $tier tier on $platform: $suite_names"
+if [[ "$mode" == list ]]; then
+ echo "cargo: ${cargo_args[*]}"
+ echo "filter: $filter"
+ exit 0
+fi
+
+have_nextest=0
+if command -v cargo-nextest >/dev/null 2>&1 || cargo nextest --version >/dev/null 2>&1; then
+ have_nextest=1
+fi
+
+if [[ "$mode" == archive || "$mode" == from-archive ]] && [[ $have_nextest == 0 ]]; then
+ echo "--archive and --from-archive need cargo-nextest (cargo install cargo-nextest --locked)" >&2
+ exit 2
+fi
+
+case "$mode" in
+ build)
+ if [[ $have_nextest == 1 ]]; then
+ exec cargo nextest run --cargo-profile "$profile" "${cargo_args[@]}" --no-run
+ fi
+ exec cargo test --profile "$profile" "${cargo_args[@]}" --no-run
+ ;;
+ archive)
+ exec cargo nextest archive --cargo-profile "$profile" "${cargo_args[@]}" --archive-file "$archive"
+ ;;
+esac
+
+if [[ -z "${CI:-}" ]]; then
+ rm -rf "$CAP_VERIFY_REPORT_DIR"
+fi
+mkdir -p "$CAP_VERIFY_REPORT_DIR"
+
+status=0
+started=$SECONDS
+if [[ $have_nextest == 1 ]]; then
+ run=(cargo nextest run --profile "$nextest_profile" --no-fail-fast)
+ if [[ "$mode" == from-archive ]]; then
+ # Running from an archive needs no cargo (or toolchain install).
+ if command -v cargo-nextest >/dev/null; then
+ run=(cargo-nextest nextest run --profile "$nextest_profile" --no-fail-fast)
+ fi
+ run+=(--archive-file "$archive" --workspace-remap "$root")
+ else
+ run+=(--cargo-profile "$profile" "${cargo_args[@]}")
+ fi
+ shard=()
+ [[ -n "$partition" ]] && shard=(--partition "$partition")
+ "${run[@]}" ${shard[@]+"${shard[@]}"} -E "$filter" ${extra[@]+"${extra[@]}"} || status=$?
+ # No retries: a test that fails is rerun once only to label it flaky in the
+ # summary. The run still fails.
+ junit="${CARGO_TARGET_DIR:-$root/target}/nextest/$nextest_profile/junit.xml"
+ if [[ $status != 0 && -n "${CAP_VERIFY_FLAKY_FILE:-}" && -f "$junit" ]]; then
+ cp "$junit" "$CAP_VERIFY_REPORT_DIR/junit.xml"
+ : >"$CAP_VERIFY_FLAKY_FILE"
+ while IFS=$'\t' read -r binary name; do
+ [[ -z "$binary" ]] && continue
+ echo "rerunning $binary $name once to check for flakiness"
+ if CAP_VERIFY_REPORT_DIR="$CAP_VERIFY_REPORT_DIR.rerun" "${run[@]}" -E "binary_id($binary) and test(=$name)"; then
+ echo "$binary $name" >>"$CAP_VERIFY_FLAKY_FILE"
+ fi
+ done < <("$py" -c 'import sys, xml.etree.ElementTree as ET
+for c in ET.parse(sys.argv[1]).getroot().iter("testcase"):
+ if c.find("failure") is not None or c.find("error") is not None:
+ print(c.get("classname"), c.get("name"), sep="\t")' "$CAP_VERIFY_REPORT_DIR/junit.xml" | head -n 5)
+ fi
+else
+ echo "cargo-nextest not found: running suites one by one with cargo test (cargo install cargo-nextest --locked for parallel runs)"
+ for name in $suite_names; do
+ plan_one="$("$py" scripts/verify/plan.py select --tier "$tier" --platform "$platform" --suites "$name" --local)"
+ read -r -a one_args <<<"$(sed -n 2p <<<"$plan_one")"
+ test_name="$("$py" -c 'import json,sys; c=json.load(open("scripts/verify/suites.json")); print(next(s.get("test","") for s in c["suites"] if s["name"]==sys.argv[1]))' "$name")"
+ echo "== $name"
+ if [[ -n "$test_name" ]]; then
+ cargo test --profile "$profile" "${one_args[@]}" -- --exact "$test_name" ${extra[@]+"${extra[@]}"} || status=$?
+ else
+ cargo test --profile "$profile" "${one_args[@]}" -- ${extra[@]+"${extra[@]}"} || status=$?
+ fi
+ done
+fi
+
+echo
+"$py" scripts/verify/summary.py --title "$platform $tier" --text \
+ --junit "$CAP_VERIFY_REPORT_DIR/junit.xml" ${CAP_VERIFY_FLAKY_FILE:+--flaky "$CAP_VERIFY_FLAKY_FILE"} \
+ "$CAP_VERIFY_REPORT_DIR" || true
+echo "engine verify: $tier tier on $platform finished in $((SECONDS - started)) s (exit $status)"
+exit $status
diff --git a/scripts/verify/suites.json b/scripts/verify/suites.json
new file mode 100644
index 000000000..42c0517c9
--- /dev/null
+++ b/scripts/verify/suites.json
@@ -0,0 +1,78 @@
+{
+ "_doc": "Engine verification suites. Read by scripts/verify/plan.py (CI planning, change detection) and scripts/verify/run.sh (local and CI runs). Fields: cargo = the cargo target selection that builds the suite; test = optional exact test name inside that binary; platforms = where each tier runs it (platform-independent logic runs on linux only); roots = workspace packages whose dependency closure decides whether a change can affect the suite; own = files that only affect this suite (a change confined to them selects just this suite).",
+ "suites": [
+ {
+ "name": "verify-self",
+ "about": "marker codecs, reference timeline model, oracle and report self-tests",
+ "cargo": ["-p", "cap-verify", "--lib", "--test", "codec"],
+ "binaries": ["cap-verify", "cap-verify::codec"],
+ "platforms": { "fast": ["linux"], "full": ["linux", "macos"] },
+ "roots": ["cap-verify"],
+ "own": ["crates/verify/tests/codec.rs"]
+ },
+ {
+ "name": "export",
+ "about": "every exported frame against the reference model (MP4, GIF, both decoders on macOS)",
+ "cargo": ["-p", "cap-verify", "--test", "export"],
+ "binaries": ["cap-verify::export"],
+ "platforms": { "fast": ["linux", "macos", "windows"], "full": ["linux", "macos", "windows"] },
+ "roots": ["cap-verify"],
+ "own": ["crates/verify/tests/export.rs"]
+ },
+ {
+ "name": "playback",
+ "about": "offline-driven editor playback frames against the reference model",
+ "cargo": ["-p", "cap-verify", "--test", "playback"],
+ "binaries": ["cap-verify::playback"],
+ "platforms": { "fast": ["linux", "macos"], "full": ["linux", "macos", "windows"] },
+ "roots": ["cap-verify"],
+ "own": ["crates/verify/tests/playback.rs"]
+ },
+ {
+ "name": "seek",
+ "about": "random, keyframe and scrub seeks against the reference model",
+ "cargo": ["-p", "cap-verify", "--test", "seek"],
+ "binaries": ["cap-verify::seek"],
+ "platforms": { "fast": ["linux", "macos"], "full": ["linux", "macos", "windows"] },
+ "roots": ["cap-verify"],
+ "own": ["crates/verify/tests/seek.rs"]
+ },
+ {
+ "name": "decoder-model-ffmpeg",
+ "about": "model-based fuzzing of the FFmpeg decoder's request decisions on scripted media",
+ "cargo": ["-p", "cap-rendering", "--lib"],
+ "binaries": ["cap-rendering"],
+ "test": "decoder::model::ffmpeg_answers_match_the_reference_model",
+ "platforms": { "fast": ["linux"], "full": ["linux"] },
+ "roots": ["cap-rendering"],
+ "own": []
+ },
+ {
+ "name": "decoder-model-avf",
+ "about": "model-based fuzzing of the AVAssetReader decoder's request decisions on scripted media",
+ "cargo": ["-p", "cap-rendering", "--lib"],
+ "binaries": ["cap-rendering"],
+ "test": "decoder::model::avassetreader_answers_match_the_reference_model",
+ "platforms": { "fast": ["macos"], "full": ["macos"] },
+ "roots": ["cap-rendering"],
+ "own": []
+ }
+ ],
+ "always": [
+ ".cargo/**",
+ ".config/nextest.toml",
+ ".github/workflows/engine-verify*.yml",
+ ".github/actions/**",
+ "Cargo.lock",
+ "Cargo.toml",
+ "rust-toolchain.toml",
+ "scripts/setup.js",
+ "scripts/verify/**",
+ "vendor/**"
+ ],
+ "runners": {
+ "linux": { "runner": "ubuntu-24.04", "target": "x86_64-unknown-linux-gnu", "shards": 1 },
+ "macos": { "runner": "macos-15", "target": "aarch64-apple-darwin", "shards": 1 },
+ "windows": { "runner": "windows-2022", "target": "x86_64-pc-windows-msvc", "shards": 1 }
+ }
+}
diff --git a/scripts/verify/summary.py b/scripts/verify/summary.py
new file mode 100755
index 000000000..d73c6c10d
--- /dev/null
+++ b/scripts/verify/summary.py
@@ -0,0 +1,182 @@
+#!/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 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])
+ for class_name, problem in (r.get("problems") or {}).items():
+ line = f"{class_name}: {problem}"
+ if line not in lines:
+ lines.append(line)
+ 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)"
+ )
+ 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 msg.splitlines()[-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(msg.splitlines()[-25:])
+ out.append("```")
+ 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()