diff --git a/.github/workflows/ci-retry-macos.yml b/.github/workflows/ci-retry-macos.yml index bac42b06..f991b4d2 100644 --- a/.github/workflows/ci-retry-macos.yml +++ b/.github/workflows/ci-retry-macos.yml @@ -41,7 +41,7 @@ jobs: # Jobs that did not pass, leaving out the CI gate job, which fails because of them. not_passed=$(gh api --paginate "repos/$REPO/actions/runs/$RUN_ID/attempts/$ATTEMPT/jobs?per_page=100" \ - --jq '.jobs[] | select(.name != "CI") | select(.conclusion != "success" and .conclusion != "skipped") + --jq '.jobs[] | select(.name != "CI" and .name != "Coverage floor") | select(.conclusion != "success" and .conclusion != "skipped") | {name, conclusion, runner: (.runner_name // "")}' | jq -s .) echo "Jobs that did not pass in attempt $ATTEMPT:" echo "$not_passed" | jq -r '.[] | " \(.name): \(.conclusion) (runner: \(if .runner == "" then "none" else .runner end))"' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c66492ec..1b3aca62 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -253,17 +253,33 @@ jobs: run: cargo xtask demo-check coverage: - name: coverage (warns, never blocks) + name: coverage (${{ matrix.platform }}) needs: changes if: needs.changes.outputs.code == 'true' - runs-on: ubuntu-24.04 - timeout-minutes: 60 - continue-on-error: true + strategy: + fail-fast: false + matrix: + include: + - platform: linux + runner: ubuntu-24.04 + binary: cargo-llvm-cov + - platform: windows + runner: windows-2025 + binary: cargo-llvm-cov.exe + - platform: macos + runner: macos-15 + binary: cargo-llvm-cov + runs-on: ${{ matrix.runner }} + timeout-minutes: 90 env: NC_LLVM_COV_VERSION: "0.9.1" + defaults: + run: + shell: bash steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install Linux build dependencies + if: matrix.platform == 'linux' run: | sudo apt-get update sudo apt-get install -y --no-install-recommends pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev libvulkan1 mesa-vulkan-drivers @@ -273,40 +289,59 @@ jobs: rustup component add llvm-tools - uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2 with: - key: coverage - save-if: ${{ github.ref == 'refs/heads/main' }} - # Restore the tool after rust-cache: binaries present before that action - # starts are excluded from its saved cache. Keep this cache to one file. - - name: Cache coverage tool + key: coverage-v2 + save-if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }} + - name: Restore pinned coverage tool id: coverage-tool-cache - uses: actions/cache@caa296126883cff596d87d8935842f9db880ef25 # v5 + uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5 with: - path: ~/.cargo/bin/cargo-llvm-cov - key: cargo-llvm-cov-ubuntu24-${{ runner.arch }}-${{ env.NC_LLVM_COV_VERSION }}-${{ hashFiles('rust-toolchain.toml') }} + path: ~/.cargo/bin/${{ matrix.binary }} + key: cargo-llvm-cov-${{ matrix.runner }}-${{ runner.arch }}-${{ env.NC_LLVM_COV_VERSION }}-${{ hashFiles('rust-toolchain.toml') }} - name: Ensure pinned coverage tool run: | if [[ "$(cargo llvm-cov --version 2>/dev/null || true)" != "cargo-llvm-cov $NC_LLVM_COV_VERSION" ]]; then cargo install cargo-llvm-cov --locked --version "$NC_LLVM_COV_VERSION" --force fi - coverage_tool_version="$(cargo llvm-cov --version)" - echo "$coverage_tool_version" - [[ "$coverage_tool_version" == "cargo-llvm-cov $NC_LLVM_COV_VERSION" ]] - - name: Show disk space - run: | - echo "CPUs: $(nproc)" - free -h - df -h / - - run: cargo xtask coverage + [[ "$(cargo llvm-cov --version)" == "cargo-llvm-cov $NC_LLVM_COV_VERSION" ]] + - name: Save pinned coverage tool on main + if: github.event_name == 'push' && github.ref == 'refs/heads/main' && steps.coverage-tool-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5 + with: + path: ~/.cargo/bin/${{ matrix.binary }} + key: ${{ steps.coverage-tool-cache.outputs.cache-primary-key }} + - name: Measure coverage + run: cargo xtask devx-time coverage -- cargo xtask coverage - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: coverage-linux-${{ github.run_attempt }} + name: coverage-${{ matrix.platform }} path: target/coverage-summary.json if-no-files-found: error - - name: Report missing coverage evidence + overwrite: true + retention-days: 14 + - name: Check 80% line coverage floor + run: cargo xtask coverage --check-floor + - name: Point to coverage evidence if: failure() + run: echo "::warning title=Coverage floor check failed::See the job steps for the measured percentage or the reason it is unavailable." + + coverage-floor: + name: Coverage floor + needs: [changes, coverage] + if: always() + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - name: Require coverage evidence for code changes + env: + CLASSIFICATION: ${{ needs.changes.result }} + CODE: ${{ needs.changes.outputs.code }} + COVERAGE: ${{ needs.coverage.result }} run: | - echo "::warning title=Coverage unavailable::The advisory coverage job could not produce or upload its report." - echo "Advisory coverage report unavailable. See this job's logs." >> "$GITHUB_STEP_SUMMARY" + case "$CLASSIFICATION:$CODE:$COVERAGE" in + success:true:success) echo "All desktop platforms meet the 80% total line coverage floor." ;; + success:false:skipped) echo "Only prose changed. Coverage is unchanged." ;; + *) echo "::error title=Coverage floor unavailable or unmet::See the classification and coverage jobs."; exit 1 ;; + esac # The Android app (android/): clippy for the arm64 target, which also builds every crate the # APK links, so a change that breaks the Android build fails here. The APK itself is built by diff --git a/.github/workflows/coverage-backstop.yml b/.github/workflows/coverage-backstop.yml new file mode 100644 index 00000000..954f9daa --- /dev/null +++ b/.github/workflows/coverage-backstop.yml @@ -0,0 +1,74 @@ +name: Coverage backstop + +on: + workflow_run: + workflows: [CI] + types: [completed] + branches: [main] + +permissions: {} + +concurrency: + group: coverage-backstop-main + cancel-in-progress: false + +jobs: + report: + # Only trusted pushes can file issues. Fork artifacts are never opened here. + if: >- + github.event.workflow_run.event == 'push' && + github.event.workflow_run.head_branch == 'main' && + github.event.workflow_run.head_repository.full_name == github.repository + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + actions: read + contents: read + issues: write + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + RUN_ID: ${{ github.event.workflow_run.id }} + RUN_URL: ${{ github.event.workflow_run.html_url }} + SOURCE_SHA: ${{ github.event.workflow_run.head_sha }} + steps: + - name: Report unavailable or below-floor coverage + run: | + set -euo pipefail + # Ignore CI runs already in progress when this workflow first lands. + source=$(gh api -H 'Accept: application/vnd.github.raw+json' "repos/$REPO/contents/.github/workflows/ci.yml?ref=$SOURCE_SHA") + if ! grep -Fxq ' coverage-floor:' <<< "$source"; then + exit 0 + fi + for platform in linux windows macos; do + dir=$(mktemp -d) + report="$dir/coverage-summary.json" + if gh run download "$RUN_ID" --repo "$REPO" --name "coverage-$platform" --dir "$dir" && + counts=$(jq -er ' + .data[0].totals.lines + | select(.covered | type == "number") + | select(.count | type == "number") + | select(.count > 0 and .covered >= 0 and .covered <= .count) + | select(.covered == (.covered | floor) and .count == (.count | floor)) + | [.covered, .count] | @tsv + ' "$report"); then + read -r covered count <<< "$counts" + if (( covered * 5 >= count * 4 )); then + continue + fi + evidence="Covered $covered of $count source lines, below the 80% floor." + else + evidence="No valid line coverage report was available." + fi + title="CI coverage needs attention on $platform" + body=$(printf '%s\n\nSource commit %s.\n\n[CI run %s](%s)\n' "$evidence" "$SOURCE_SHA" "$RUN_ID" "$RUN_URL") + issue=$(gh issue list --repo "$REPO" --state open --label bug --search "$title in:title" --json title,number \ + --jq ".[] | select(.title == \"$title\") | .number" | head -n 1) + if [[ -n "$issue" ]]; then + if ! gh issue view "$issue" --repo "$REPO" --json body,comments --jq '.body, .comments[].body' | grep -F "[CI run $RUN_ID]($RUN_URL)" > /dev/null; then + gh issue comment "$issue" --repo "$REPO" --body "$body" + fi + else + gh issue create --repo "$REPO" --title "$title" --label bug --body "$body" + fi + done diff --git a/SKILLS/nc-devx/SKILL.md b/SKILLS/nc-devx/SKILL.md index bac9f1b2..0d5a99f0 100644 --- a/SKILLS/nc-devx/SKILL.md +++ b/SKILLS/nc-devx/SKILL.md @@ -320,7 +320,7 @@ services or signing infrastructure without explicit owner approval. | Lane | Purpose | Trigger | Produces | Merge/deployment authority | |---|---|---|---|---| -| **1. Code quality** | fmt, clippy, static checks, docs/assets/demo checks, and coverage | Every pull request and main push as configured | Check results and diagnostics | Required quality checks; coverage remains warning-only | +| **1. Code quality** | fmt, clippy, static checks, docs/assets/demo checks, and coverage | Every pull request and main push as configured | Check results and diagnostics | Required quality checks. Baseline drops warn and the 80% floor has its own check | | **2. Platform build/test** | Prove the source builds and applicable tests pass on Linux, Windows, and macOS | Every pull request | Per-platform logs and test results | Required for merge; no installers | | **3. Packaging** | Build and inspect MSI/ZIP, Linux packages, and macOS artifacts | Manual `Packaging` workflow only | Versioned, checksumed workflow artifacts | Never publishes by itself | | **4. Installation/deployment** | Install/uninstall, first launch, notebook placement, upgrade/data persistence, then publish | Manual `Release` workflow after selecting a successful Packaging run | Installation evidence and an approved release | Only this lane may deploy or publish | diff --git a/docs/testing.md b/docs/testing.md index 6ff37188..02e7eeed 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -104,6 +104,7 @@ rustup component add llvm-tools cargo install cargo-llvm-cov --locked cargo xtask coverage # measure, and compare with docs/coverage.json cargo xtask coverage --update # measure, and make this run the new baseline +cargo xtask coverage --check-floor # check the existing report against 80% line coverage ``` Semantic UI tests run in parallel. Tests that assert rendered pixels hold the shared renderer for @@ -113,16 +114,21 @@ function and region coverage, line coverage per crate, and when and with what it measured. It covers the workspace without `xtask`. A run is compared with its own platform only, because code for one platform counts only where it is built. `--update` writes the current platform and keeps the others. `badges` holds the README figures, with "not measured" -for a platform that has no baseline yet. Linux is measured in CI; Windows on a Windows machine. +for a platform that has no baseline yet. CI measures Linux, Windows and macOS. -The comparison warns and never fails. A figure that falls by more than 0.5 points is printed -as a warning, and the task still succeeds. On a pull request the `coverage` job in -[`ci.yml`](../.github/workflows/ci.yml) runs it, shows each drop as an annotation and puts the -table on the run's summary page; the job is allowed to fail, so it never blocks a merge. It is -not part of `cargo xtask ci` or the pre-push hook, because a coverage run rebuilds everything. +Baseline drops of more than 0.5 points remain warnings. Each platform job attaches +its report and shows a coverage table in the run summary. The **Coverage floor** check in +[`ci.yml`](../.github/workflows/ci.yml) requires valid reports and at least 80% total line +coverage on each platform for code changes. It stands apart from the existing required +`CI` check during rollout so hosted measurements can be reviewed before requiring it for +merges. A trusted push to main with low or unavailable coverage files or updates a bug +via the [coverage backstop](../.github/workflows/coverage-backstop.yml). + +Coverage rebuilds the workspace with instrumentation and runs outside `cargo xtask ci` +and the pre-push hook. CI caches the pinned `cargo-llvm-cov` binary separately, after restoring the Rust dependency -cache. The key includes the Ubuntu runner, architecture, tool version and Rust toolchain. +cache. The key includes the runner image label, architecture, tool version and Rust toolchain. A cold cache installs the pinned tool; a warm cache reuses it. Both paths verify the version before running the complete coverage command. This does not install anything on a developer's machine or change the platform build/test jobs. diff --git a/xtask/src/coverage.rs b/xtask/src/coverage.rs index 5b0ae596..99ff8c09 100644 --- a/xtask/src/coverage.rs +++ b/xtask/src/coverage.rs @@ -1,4 +1,4 @@ -//! `cargo xtask coverage [--update]`: line, function and region coverage with cargo-llvm-cov, +//! `cargo xtask coverage [--update | --check-floor]`: line, function and region coverage with cargo-llvm-cov, //! compared with this platform's baseline in `docs/coverage.json`. //! //! Each platform has its own baseline, because code for one platform only (Windows' keyboard @@ -171,11 +171,38 @@ fn target_dir(root: &Path) -> PathBuf { std::env::var("CARGO_TARGET_DIR").map(PathBuf::from).unwrap_or_else(|_| root.join("target")) } +fn check_floor(report: &Value) -> Result<(), String> { + let lines = &report["data"][0]["totals"]["lines"]; + let (Some(covered), Some(count)) = (lines["covered"].as_u64(), lines["count"].as_u64()) else { + return Err("coverage evidence unavailable: the report has no total line counts".into()); + }; + if count == 0 || covered > count { + return Err("coverage evidence unavailable: invalid total line counts".into()); + } + let platform = std::env::consts::OS; + let measurement = format!("{platform} line coverage: {covered}/{count} lines ({:.3}%)", 100.0 * covered as f64 / count as f64); + if u128::from(covered) * 5 < u128::from(count) * 4 { + return Err(format!("{measurement} is below the 80% floor")); + } + println!("{measurement} meets the 80% floor"); + Ok(()) +} + +fn read_report(path: &Path) -> Result { + let text = fs::read_to_string(path).map_err(|e| format!("read {}: {e}", path.display()))?; + serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display())) +} + pub fn run(root: &Path, options: &[String]) -> Result<(), String> { + let report_path = target_dir(root).join("coverage-summary.json"); let update = match options { [] => false, [o] if o == "--update" => true, - _ => return Err("usage: cargo xtask coverage [--update]".into()), + [o] if o == "--check-floor" => { + let report = read_report(&report_path).map_err(|e| format!("coverage evidence unavailable: {e}"))?; + return check_floor(&report); + } + _ => return Err("usage: cargo xtask coverage [--update | --check-floor]".into()), }; let tool = first_line("cargo", &["llvm-cov", "--version"], root); if tool.is_empty() { @@ -183,18 +210,18 @@ pub fn run(root: &Path, options: &[String]) -> Result<(), String> { "cargo-llvm-cov is not installed. Install it with: rustup component add llvm-tools && cargo install cargo-llvm-cov --locked".into() ); } - let report_path = target_dir(root).join("coverage-summary.json"); if let Some(dir) = report_path.parent() { fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?; } let report_arg = report_path.to_string_lossy().into_owned(); + // The two test invocations share a profile set. Start it fresh for each measurement. + crate::cargo(root, &["llvm-cov", "clean", "--workspace"])?; // Pixel tests serialize their shared renderer; semantic UI tests use no renderer and can // run concurrently during coverage, matching `cargo xtask ci`. - crate::cargo(root, &["llvm-cov", "--workspace", "--exclude", "xtask", "--exclude-from-test", "notecraft-ui-egui", "--no-report"])?; - crate::cargo(root, &["llvm-cov", "--package", "notecraft-ui-egui", "--no-clean"])?; + crate::cargo(root, &["llvm-cov", "--locked", "--workspace", "--exclude", "xtask", "--exclude-from-test", "notecraft-ui-egui", "--no-report"])?; + crate::cargo(root, &["llvm-cov", "--locked", "--package", "notecraft-ui-egui", "--no-report"])?; crate::cargo(root, &["llvm-cov", "report", "--json", "--summary-only", "--output-path", &report_arg])?; - let text = fs::read_to_string(&report_path).map_err(|e| format!("read {}: {e}", report_path.display()))?; - let report: Value = serde_json::from_str(&text).map_err(|e| format!("{}: {e}", report_path.display()))?; + let report = read_report(&report_path)?; let now = summarize(&report)?; let platform = std::env::consts::OS; let shown = table(&now, platform); @@ -250,6 +277,24 @@ pub fn run(root: &Path, options: &[String]) -> Result<(), String> { mod tests { use super::*; + #[test] + fn floor_uses_unrounded_total_line_coverage() { + for (covered, count, passes) in [(801, 1000, true), (800, 1000, true), (7999, 10000, false)] { + let mut report = report(); + report["data"][0]["totals"]["lines"] = json!({"covered": covered, "count": count}); + assert_eq!(check_floor(&report).is_ok(), passes, "{covered}/{count}"); + } + } + + #[test] + fn floor_rejects_missing_empty_and_impossible_totals() { + for lines in [json!(null), json!({"count": 1}), json!({"covered": 0, "count": 0}), json!({"covered": 2, "count": 1})] { + let mut report = report(); + report["data"][0]["totals"]["lines"] = lines; + assert!(check_floor(&report).unwrap_err().contains("unavailable"), "{report}"); + } + } + fn report() -> Value { json!({"data": [{ "totals": { diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 9fc0c385..3fd5a7d4 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -14,7 +14,7 @@ //! add `--fix` to rewrite those issues //! i18n-audit check UI string IDs, hard-coded text, and locale catalog coverage //! screenshots regenerate docs/images from the real window with the headless runner -//! coverage coverage with cargo-llvm-cov, compared with docs/coverage.json (warns, never fails); +//! coverage measure coverage, compare platform baselines, or check the 80% line coverage floor; //! `--update` writes this run as the new baseline //! devx-time PHASE -- COMMAND [ARGS...] measure a build/test command and report timing regressions //! check-branch [--push] the branch and history checks of quality levels L1 and L2