Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(coverage): compare project coverage with the base and list coverage that moved outside the change (#2659)

Raghav Chamadiyaf1d4bc19b124
diff --git a/action.yml b/action.yml
index 3cfbdc6b4..4bf16c90a 100644
--- a/action.yml
+++ b/action.yml
@@ -55,6 +55,20 @@ inputs:
bug-fix history. A change with no risky file is not gated. Empty uses
coverage.fail_under_risky from .repowise/config.yaml, else no risky gate.
default: ""
+ coverage-base-report:
+ description: >-
+ Coverage reports measured at the change's base commit (the merge-base
+ with the target branch), one per line, read like coverage-report. Adds
+ project coverage at the base against the head, and the files whose
+ coverage changed outside the change.
+ default: ""
+ coverage-max-drop:
+ description: >-
+ Most project coverage may fall from the change's base, in percentage
+ points. Needs coverage-base-report (or an index that stored coverage at
+ the base). Empty uses coverage.max_drop from .repowise/config.yaml, else
+ reports without gating.
+ default: ""
doc-drift-baseline:
description: Committed doc-drift baseline file; only findings it does not list fail.
default: ""
@@ -116,6 +130,8 @@ runs:
COVERAGE_FAIL_UNDER: ${{ inputs.coverage-fail-under }}
COVERAGE_MIN_COVERABLE_LINES: ${{ inputs.coverage-min-coverable-lines }}
COVERAGE_FAIL_UNDER_RISKY: ${{ inputs.coverage-fail-under-risky }}
+ COVERAGE_BASE_REPORT: ${{ inputs.coverage-base-report }}
+ COVERAGE_MAX_DROP: ${{ inputs.coverage-max-drop }}
DOC_DRIFT_BASELINE: ${{ inputs.doc-drift-baseline }}
SECURITY_FAIL_ON: ${{ inputs.security-fail-on }}
SECURITY_BASELINE: ${{ inputs.security-baseline }}
diff --git a/ci/github/run-gates.sh b/ci/github/run-gates.sh
index 269b2cf14..40825bcc8 100644
--- a/ci/github/run-gates.sh
+++ b/ci/github/run-gates.sh
@@ -66,6 +66,10 @@ if wants coverage; then
[[ -n "$COVERAGE_FAIL_UNDER" ]] && args+=(--fail-under "$COVERAGE_FAIL_UNDER")
[[ -n "$COVERAGE_MIN_COVERABLE_LINES" ]] && args+=(--min-coverable-lines "$COVERAGE_MIN_COVERABLE_LINES")
[[ -n "$COVERAGE_FAIL_UNDER_RISKY" ]] && args+=(--fail-under-risky "$COVERAGE_FAIL_UNDER_RISKY")
+ while IFS= read -r report; do
+ [[ -n "$report" ]] && args+=(--base-report "$report")
+ done <<<"$COVERAGE_BASE_REPORT"
+ [[ -n "$COVERAGE_MAX_DROP" ]] && args+=(--max-drop "$COVERAGE_MAX_DROP")
run coverage repowise "${args[@]}"
fi
diff --git a/ci/gitlab/repowise.gitlab-ci.yml b/ci/gitlab/repowise.gitlab-ci.yml
index c31857d5c..a6aa9d02c 100644
--- a/ci/gitlab/repowise.gitlab-ci.yml
+++ b/ci/gitlab/repowise.gitlab-ci.yml
@@ -24,6 +24,10 @@
# lines than this never fails the coverage gate.
# REPOWISE_COVERAGE_FAIL_UNDER_RISKY
# Minimum patch coverage percent over risky files only.
+# REPOWISE_COVERAGE_BASE_REPORT Coverage reports measured at the merge request's base
+# commit, space separated like REPOWISE_COVERAGE_REPORT:
+# project coverage and coverage outside the change.
+# REPOWISE_COVERAGE_MAX_DROP Most project coverage may fall from the base, in points.
# REPOWISE_DOC_DRIFT_BASELINE Committed doc-drift baseline file.
# REPOWISE_SECURITY_BASELINE Committed security baseline file.
# REPOWISE_SECURITY_FAIL_ON Lowest severity that fails: high (default), med, low.
@@ -54,6 +58,8 @@ repowise-coverage:
${REPOWISE_COVERAGE_FAIL_UNDER:+--fail-under "$REPOWISE_COVERAGE_FAIL_UNDER"}
${REPOWISE_COVERAGE_MIN_COVERABLE_LINES:+--min-coverable-lines "$REPOWISE_COVERAGE_MIN_COVERABLE_LINES"}
${REPOWISE_COVERAGE_FAIL_UNDER_RISKY:+--fail-under-risky "$REPOWISE_COVERAGE_FAIL_UNDER_RISKY"}
+ ${REPOWISE_COVERAGE_BASE_REPORT:+$(printf -- '--base-report %s ' $REPOWISE_COVERAGE_BASE_REPORT)}
+ ${REPOWISE_COVERAGE_MAX_DROP:+--max-drop "$REPOWISE_COVERAGE_MAX_DROP"}
--format markdown > repowise-coverage.md
after_script:
- cat repowise-coverage.md
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index 9bcbdbd12..41bac613a 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -350,6 +350,21 @@ terminal table the same, and each GitHub annotation ends with the same phrase.
Hints are advice: a missing or unreadable index leaves them `null` and never
changes the verdict.
+### Project coverage and coverage outside the change
+
+Patch coverage cannot see a change that deletes a test, or removes a code path
+that ran other files. `--base-report PATH` takes a report measured at the
+change's base commit and adds `project`: coverage at the base and the head,
+gated by `--max-drop P` (or `coverage.max_drop`), and `outside_change`, the
+files whose coverage changed on lines the change did not touch, each loss with
+the changed files that explain it. Without a base report, an index's ingest at
+the base commit gives the totals alone, as `get_change_risk` and the REST
+endpoint do (never gated). See
+[Project coverage and coverage outside the change](../start/CI.md#project-coverage-and-coverage-outside-the-change)
+for recipes and the
+[`coverage check` reference](../reference/CLI_REFERENCE.md#repowise-coverage-check-revspec)
+for the fields.
+
A coverage.py `.coverage` database is not a text report: export it with
`coverage lcov` or `coverage xml` first.
@@ -667,6 +682,7 @@ coverage:
reingest_on_update: false
fail_under: 80 # patch-coverage gate for `coverage check` (0-100)
min_coverable_lines: 5 # small-change tolerance for that gate
+ max_drop: 0.5 # most project coverage may fall from the base, in points
gates: # path-scoped gates, judged on the files they match
- {name: api, paths: ["/services/api/"], fail_under: 85}
- {name: scripts, paths: ["/scripts/"], fail_under: 50, informational: true}
@@ -683,7 +699,7 @@ Note that `--coverage-report` is test coverage, while `--coverage` controls
|---------|--------------|
| `repowise coverage add [PATHS...]` | Ingest reports. Auto-discovers when no path is given, merges multiple, builds the per-test map when contexts are present. Flags: `--path`, `--format`, `--verbose` |
| `repowise coverage status` | Coverage summary plus test-to-code map counts. Flag: `--path` |
-| `repowise coverage check [REVSPEC]` | Patch-coverage gate for CI, no index needed. Flags: `--report`, `--report-format`, `--fail-under`, `--min-coverable-lines`, `--path`, `--format` |
+| `repowise coverage check [REVSPEC]` | Patch-coverage gate for CI, no index needed. Flags: `--report`, `--report-format`, `--fail-under`, `--min-coverable-lines`, `--fail-under-risky`, `--base-report`, `--max-drop`, `--path`, `--format` |
| `repowise coverage suggest-gates` | Propose path-scoped gates for `coverage.gates` as YAML to paste below `coverage:`; writes nothing. Flags: `--path`, `--format` |
| `repowise impacted-tests [REVSPEC]` | The tests a change exercises. Flags: `--path`, `--staged`, `--format` |
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 073378184..3c2531eae 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1355,6 +1355,8 @@ are out of scope and only counted.
| `--fail-under` | Exit 1 when patch coverage is below this percentage (0-100). Defaults to `coverage.fail_under` in `.repowise/config.yaml`; with neither set the command reports without gating |
| `--min-coverable-lines` | Small-change tolerance: a change with fewer changed executable lines than this (counting only lines the report measures, as the percentage does) is reported against the threshold but never fails (`gate` reads `too_small`). Defaults to `coverage.min_coverable_lines` |
| `--fail-under-risky` | Exit 1 when patch coverage of the risky files alone is below this percentage. Risky: hotspots or bug magnets from the index; on git alone, the top quartile of files with bug-fix history. Defaults to `coverage.fail_under_risky`. With no risky file changed the gate is not applied (`no_data`, exit `0`) |
+| `--base-report` | Report measured at the change's base commit (the merge-base for `A...B`), read like `--report`, repeatable. Adds `project` |
+| `--max-drop` | Exit 1 when project coverage falls more than this many points from the base (0-100). Defaults to `coverage.max_drop`. Needs `--base-report` or an index's ingest at the base commit |
| `--path` | A path inside the repository (defaults to cwd) |
| `--format` | `table` (default), `json`, `markdown`, or `github` |
@@ -1390,9 +1392,20 @@ per uncovered range: `range`, `symbol`, `tests`, `basis` (`per_test`,
`unmatched_report_path_count`, `ignored_file_count`, `config_errors`),
`path_gates[]` (`name`, `paths`, `threshold`, `informational`,
`measured_file_count`, `unmeasured_file_count`, `covered_line_count`,
-`coverable_line_count`, `patch_coverage_pct`, `gate`) and `risky`
+`coverable_line_count`, `patch_coverage_pct`, `gate`), `risky`
(`file_count`, `covered_line_count`, `coverable_line_count`,
-`patch_coverage_pct`, `threshold`, `gate`). Changed files and report entries
+`patch_coverage_pct`, `threshold`, `gate`) and `project`, null without a base
+measurement (`basis`: `base_report` or `history`, `base_commit`,
+`head_commit`, `base` and `head` with `covered_line_count`,
+`coverable_line_count`, `coverage_pct`, `delta_pct` in points, `max_drop`,
+`gate`, `incomparable` reasons, `outside_change_note`, and `outside_change[]`,
+null on the history basis or when most files did not line up:
+`file_path`, `status` (`changed`, `no_longer_measured`),
+`newly_uncovered_ranges`, `newly_uncovered_line_count`,
+`newly_covered_line_count`, `base_pct`, `head_pct`, `causes`: `kind`
+(`test_deleted`, `test_modified`, `dependent_changed`), `path`, `basis`
+(`per_test`, `graph`, `name`)). The markdown and `github` formats also list
+files that lost coverage outside the change. Changed files and report entries
matching `coverage.ignore` (gitignore syntax) are left out and counted as
ignored. Go coverprofile paths under a `go.mod`'s module path are mapped to
that module's directory unless the report has a per-report prefix or
@@ -1402,8 +1415,9 @@ that module's directory unless the report has a per-report prefix or
**Exit codes:** `0` the gate passes or there is nothing to judge (no
threshold, no measurable changed lines, or a change under the small-change
tolerance); `1` patch coverage is below `--fail-under`, a path-scoped gate
-that is not informational fails, or the risky files' is below
-`--fail-under-risky`; `2` the check could not run: no report found, a
+that is not informational fails, the risky files' is below
+`--fail-under-risky`, or project coverage fell more than `--max-drop` points;
+`2` the check could not run: no report found, a
`--report` path or glob matching no file, none readable, none matching a
repository file, or every entry matching `coverage.ignore`; an unknown
revision; no merge-base (a shallow clone); a single commit at a shallow
@@ -1412,7 +1426,9 @@ clone's boundary; bad config or a malformed `coverage.fail_under` /
`coverage.gates` entry (named in the message); not a git repository;
`--fail-under-risky` set on a shallow clone, or with a measured file whose
risk could not be read (unless the flat or a path-scoped gate already failed,
-which exits `1`).
+which exits `1`); under the `--max-drop` or `--base-report` flag, a base
+that is missing, not comparable with the head, or has no coverable line on a
+side (same exception; from `coverage.max_drop` alone it is a note, exit `0`).
**Path-scoped gates.** Each entry of `coverage.gates` (`name`, `paths` as
gitignore-style globs relative to the repository root, optional `fail_under`
diff --git a/docs/start/CI.md b/docs/start/CI.md
index e677b74a5..bbb8d5a31 100644
--- a/docs/start/CI.md
+++ b/docs/start/CI.md
@@ -6,6 +6,7 @@ the whole repository's past:
| Gate | Question | Needs | History |
|------|----------|-------|---------|
| `repowise coverage check` | Did the tests run the lines this change touched? | git and a coverage report | the merge-base with the target branch |
+| `repowise coverage check --max-drop P` | Did this change lower project coverage by more than P points? | git, a coverage report, and one measured at the change's base | the merge-base with the target branch |
| `repowise doc-drift --check` | Does the documentation still describe files, links and commands that exist? | git | none (full history only improves rename suggestions) |
| `repowise security check` | Did this change add a secret or a risky call? | git | every commit of the change |
| `repowise risk --fail-above-percentile P` | Is this change bigger and more spread out than P% of this repository's recent commits? | git | recent commits to rank against (at least 8) |
@@ -121,6 +122,8 @@ release the action installs.
| `coverage-fail-under` | `coverage.fail_under` | Minimum patch coverage percent. |
| `coverage-min-coverable-lines` | `coverage.min_coverable_lines` | Small-change tolerance: a change with fewer changed executable lines than this never fails. |
| `coverage-fail-under-risky` | `coverage.fail_under_risky` | Minimum patch coverage percent over risky files only: hotspots or bug magnets from the index; on git alone, the top quartile of files with bug-fix history. |
+| `coverage-base-report` | none | Reports measured at the change's base commit, one per line. See [Project coverage](#project-coverage-and-coverage-outside-the-change). |
+| `coverage-max-drop` | `coverage.max_drop` | Most project coverage may fall from the base, in percentage points. |
| `doc-drift-baseline` | none | Committed baseline file. |
| `security-fail-on` | `high` | Lowest severity that fails: `high`, `med`, `low`. |
| `security-baseline` | none | Committed baseline file. |
@@ -192,7 +195,9 @@ has no change to judge.
`REPOWISE_COVERAGE_REPORT` is space separated and may hold globs and
`path=prefix` entries; Repowise expands the globs, not the shell. Other
variables: `REPOWISE_VERSION`, `REPOWISE_COVERAGE_MIN_COVERABLE_LINES`,
-`REPOWISE_COVERAGE_FAIL_UNDER_RISKY`, `REPOWISE_DOC_DRIFT_BASELINE`,
+`REPOWISE_COVERAGE_FAIL_UNDER_RISKY`, `REPOWISE_COVERAGE_BASE_REPORT` (space
+separated, like the report list), `REPOWISE_COVERAGE_MAX_DROP`,
+`REPOWISE_DOC_DRIFT_BASELINE`,
`REPOWISE_SECURITY_BASELINE`, `REPOWISE_SECURITY_FAIL_ON`. Override any job's
`image`, `rules` or `needs` in your own file as usual.
@@ -444,6 +449,81 @@ clone, or a measured file whose risk could not be read (no git history and no
index row), exits `2`, unless the whole-change or a path-scoped gate already
failed: that failure is reported.
+### Project coverage and coverage outside the change
+
+Patch coverage cannot see a change that deletes a test or a code path other
+files relied on. Given a report measured at the change's base commit, the check
+adds project coverage at the base and the head, and lists files whose coverage
+changed outside the change with the changed test or dependent that explains it.
+
+```bash
+repowise coverage check origin/main...HEAD --report coverage/lcov.info \
+ --base-report base/lcov.info --max-drop 0.5
+```
+
+- `--max-drop P` fails when project coverage falls more than `P` points. The
+ small-change tolerance does not apply.
+- The base report must be measured at the merge-base (`A` for `A..B`). Files
+ whose lines do not line up are left out, and a note says how many.
+- Both sides must be measured the same way: the same reports of each format,
+ the same `coverage.ignore`, neither mapping fewer than half its files.
+- A base the check cannot use exits `2` under the `--max-drop` or
+ `--base-report` flag (the action's inputs), and is a note with exit `0` when
+ the gate comes from `coverage.max_drop` alone.
+
+On GitHub Actions, in a job that runs on pushes to the default branch and on
+pull requests, checked out with `fetch-depth: 0`:
+
+```yaml
+- run: pytest --cov=src --cov-report=lcov:coverage/lcov.info
+- if: github.event_name == 'push'
+ run: mkdir -p base-coverage && cp coverage/lcov.info base-coverage/
+- if: github.event_name == 'push'
+ uses: actions/cache/save@v4
+ with: {path: base-coverage, key: "coverage-${{ github.sha }}"}
+- if: github.event_name == 'pull_request'
+ id: merge-base
+ run: echo "sha=$(git merge-base "origin/$GITHUB_BASE_REF" HEAD)" >> "$GITHUB_OUTPUT"
+- if: github.event_name == 'pull_request'
+ id: base
+ uses: actions/cache/restore@v4
+ with: {path: base-coverage, key: "coverage-${{ steps.merge-base.outputs.sha }}"}
+- if: github.event_name == 'pull_request'
+ uses: repowise-dev/repowise@main
+ with:
+ checks: coverage
+ coverage-report: coverage/lcov.info
+ # Only when the base's report was found; a missing file exits 2.
+ coverage-base-report: ${{ steps.base.outputs.cache-hit == 'true' && 'base-coverage/lcov.info' || '' }}
+ coverage-max-drop: ${{ steps.base.outputs.cache-hit == 'true' && '0.5' || '' }}
+```
+
+On GitLab, the merge request job uses the target branch's latest `test`
+artifact only when it was measured at the merge-base (a rebased merge request,
+or merged-results pipelines); otherwise the check runs without a base:
+
+```yaml
+test:
+ script:
+ - pytest --cov=src --cov-report=lcov:coverage/lcov.info
+ - echo "$CI_COMMIT_SHA" > coverage/commit.txt
+ artifacts: {paths: [coverage/]}
+
+repowise-coverage:
+ needs: [test]
+ before_script:
+ - !reference [.repowise, before_script]
+ - |
+ url="$CI_API_V4_URL/projects/$CI_PROJECT_ID/jobs/artifacts/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME/download?job=test"
+ if curl -sfL --header "JOB-TOKEN: $CI_JOB_TOKEN" -o base.zip "$url" \
+ && python -m zipfile -e base.zip base \
+ && [ "$(cat base/coverage/commit.txt)" = \
+ "$(git merge-base "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME" HEAD)" ]; then
+ export REPOWISE_COVERAGE_BASE_REPORT=base/coverage/lcov.info
+ export REPOWISE_COVERAGE_MAX_DROP=0.5
+ fi
+```
+
## When a gate exits 2
| Message | Fix |
@@ -460,3 +540,6 @@ failed: that failure is reported.
| "The change-risk gate ranks the change against recent commits, and --baseline 0 turns that off." | drop `--baseline 0` |
| "The risky-file gate reads bug-fix history, and this clone is shallow." | fetch full history |
| "Could not read the risk of N changed files, so the risky-file gate cannot run." | fetch full history, or index the repository |
+| "The max-drop gate needs coverage measured at the change's base ..." | pass `--base-report`, or ingest a report at the base commit |
+| "Project coverage cannot be compared ..." | measure the base and the head the same way (same full reports, same `coverage.ignore`) |
+| "Base report: No report path matched a file in this repository." | the base report must name files the base commit tracked; check its prefix |
diff --git a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
index bae818adf..e96fc6d4c 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
@@ -10,17 +10,26 @@ executable-line data; otherwise it cannot evaluate.
Exit codes and output channels are the shared CI ones (:mod:`repowise.cli.ci`):
0 when the gate passes or there is nothing to judge, 1 when patch coverage is
below ``--fail-under``, a path-scoped gate (``coverage.gates``) that is not
-informational fails, or the risky files' is below ``--fail-under-risky``, 2
-when the check could not run (no report, a ``--report`` matching no file,
+informational fails, the risky files' is below ``--fail-under-risky``, or
+project coverage fell more than ``--max-drop`` points from the change's base,
+2 when the check could not run (no report, a ``--report`` matching no file,
unreadable report, unknown revision, missing history, bad config, risk
-unreadable or a shallow clone under ``--fail-under-risky``). A change under
-``--min-coverable-lines`` is reported against the threshold but exits 0.
+unreadable or a shallow clone under ``--fail-under-risky``, no base
+measurement under ``--max-drop``, or a base that measured something else). A
+change under ``--min-coverable-lines`` is reported against the threshold but
+exits 0.
+
+Project coverage compares the change's base with its head: a ``--base-report``
+measured at the base commit gives the totals and the files whose coverage
+changed outside the change; without one, an index's ingest at the base commit
+gives the totals alone.
"""
from __future__ import annotations
-from dataclasses import replace
+from dataclasses import dataclass, replace
from pathlib import Path
+from typing import Any
import click
from rich.markup import escape
@@ -83,6 +92,21 @@ from repowise.core.persistence.database import has_db_store
"of files with bug-fix history. No risky file changed: not applied. "
"Defaults to coverage.fail_under_risky in .repowise/config.yaml.",
)
+ "--base-report",
+ "base_reports",
+ multiple=True,
+ help="Coverage report measured at the change's base commit (the merge-base for "
+ "A...B), read like --report. Compares project coverage and lists files whose "
+ "coverage changed outside the change.",
+)
+ "--max-drop",
+ type=click.FloatRange(0, 100),
+ default=None,
+ help="Exit 1 when project coverage falls more than this many points from the "
+ "change's base. Defaults to coverage.max_drop in .repowise/config.yaml.",
+)
@click.option(
"--path",
"repo",
@@ -101,6 +125,8 @@ def coverage_check(
fail_under: float | None,
min_coverable_lines: int | None,
fail_under_risky: float | None,
+ base_reports: tuple[str, ...],
+ max_drop: float | None,
repo: str | None,
fmt: str,
) -> None:
@@ -123,19 +149,27 @@ def coverage_check(
repowise coverage check --report 'artifacts/**/lcov.info' --min-coverable-lines 5
repowise coverage check --report web/coverage/lcov.info=web
repowise coverage check HEAD --format json
+ repowise coverage check --report lcov.info --base-report base/lcov.info --max-drop 0.5
Each changed file carries its risk (git bug-fix history, plus hotspot,
bug-magnet and dependent counts when an index exists), and the rows read
riskiest first. ``--fail-under-risky`` gates the risky files alone. With an
index, each uncovered range also names the test file to extend.
+
+ ``--base-report`` (or, without one, the coverage an index stored at the
+ base commit) adds project coverage at the base against the head, which
+ ``--max-drop`` gates, and the files whose coverage changed on lines the
+ change did not touch.
"""
notices = ci_notices(fmt)
try:
- pc = _evaluate(
+ pc, head, head_reports = _evaluate(
revspec, reports, report_format, fail_under, min_coverable_lines, repo, notices
)
pc = _with_risk(repo, pc, fail_under_risky)
pc = _with_hints(repo, pc)
+ ask = _project_ask(pc, head, head_reports, base_reports, max_drop, notices)
+ pc = _with_project(pc, ask) if ask is not None else pc
except CannotEvaluateError as exc:
cannot_evaluate(fmt, exc.code, str(exc))
_emit(pc, fmt)
@@ -144,6 +178,11 @@ def coverage_check(
def _evaluate(revspec, reports, report_format, fail_under, min_coverable_lines, repo, notices):
+ """``(patch coverage, the head's resolved reports, how they were read)``.
+
+ The resolved reports are ``None`` when the coverage was read from the
+ index, and the :class:`_Reports` then names no file.
+ """
from repowise.core.analysis.patch_coverage import patch_coverage_from_resolved
root = repo_root(repo)
@@ -164,16 +203,17 @@ def _evaluate(revspec, reports, report_format, fail_under, min_coverable_lines,
# No report on disk: the index's stored coverage answers, when it can.
if notices is console:
notices.print("[dim]Reading the coverage stored in the index[/dim]")
- return _gateable(
- run_async(_stored(root, changed, label, threshold, min_coverable_lines, cfg))
- )
+ stored = run_async(_stored(root, changed, label, threshold, min_coverable_lines, cfg))
+ return _gateable(stored), None, _Reports(root, cfg, {}, report_format)
if notices is console:
# Machine formats carry the list in ``scope.reports`` instead.
notices.print(f"[dim]Reading {', '.join(escape(str(p)) for p in report_paths)}[/dim]")
- return patch_coverage_from_resolved(
+ head_reports = _Reports(root, cfg, report_prefixes, report_format)
+ resolved = _resolve_reports(head_reports, notices)
+ pc = patch_coverage_from_resolved(
changed,
- _resolve_reports(root, cfg, report_prefixes, report_format, notices),
+ resolved,
threshold=threshold,
label=label,
reports=[str(p) for p in report_paths],
@@ -181,6 +221,7 @@ def _evaluate(revspec, reports, report_format, fail_under, min_coverable_lines,
ignore=cfg.ignore,
gates=cfg.gates,
)
+ return pc, resolved, head_reports
def _first_set(flag, configured):
@@ -188,14 +229,15 @@ def _first_set(flag, configured):
return configured if flag is None else flag
-def _cli_reports(args: tuple[str, ...]) -> dict[Path, str | None]:
+def _cli_reports(args: tuple[str, ...], flag: str = "--report") -> dict[Path, str | None]:
"""``--report`` values: each a path or glob relative to cwd, optionally ``=PREFIX``.
The whole argument is expanded first, so a path or glob holding ``=``
(``artifacts/shard=1/*.info``) stays one; only when it matches nothing is
it split on the last ``=``, and the prefix applies to every file the left
side matches. One that matches no file cannot be evaluated: a report
- missing from a CI job is a broken setup, not a pass.
+ missing from a CI job is a broken setup, not a pass. *flag* names the
+ option in that message (``--base-report`` reads the same way).
"""
from repowise.core.analysis.health.coverage import expand_report_patterns
@@ -209,7 +251,7 @@ def _cli_reports(args: tuple[str, ...]) -> dict[Path, str | None]:
matches = expand_report_patterns([pattern], cwd)
if not matches:
raise CannotEvaluateError(
- "report_not_found", f"--report {arg}: no coverage report matches {pattern}."
+ "report_not_found", f"{flag} {arg}: no coverage report matches {pattern}."
)
for path in matches:
out.setdefault(path, prefix or None)
@@ -394,37 +436,58 @@ async def _read_hints(root: Path, pc, head: str | None):
return await read_test_hints(session, repo_id, pc, repo_path=str(root), head_commit=head)
-def _resolve_reports(root, cfg, report_prefixes, report_format, notices):
- """Parse the reports against the files git tracks, failing when nothing usable remains."""
+@dataclass(frozen=True)
+class _Reports:
+ """Report files and how to read them: the repository, its ``coverage:`` config, the format."""
+
+ root: Path
+ cfg: Any
+ prefixes: dict[Path, str | None]
+ report_format: str | None
+
+ def build(self, keys):
+ """``build_coverage_map`` over these reports, against the repository paths *keys*."""
+ from repowise.core.analysis.health.coverage import build_coverage_map
+
+ return build_coverage_map(
+ self.root,
+ list(self.prefixes),
+ set(keys),
+ coverage_format=self.report_format or self.cfg.format,
+ strip_prefix=self.cfg.strip_prefix,
+ path_prefix=self.cfg.path_prefix,
+ report_prefixes=self.prefixes,
+ ignore=self.cfg.ignore,
+ )
+
+
+def _resolve_reports(reports: _Reports, notices, keys=None, side: str = ""):
+ """Parse the reports against the files git tracks, failing when nothing usable remains.
+
+ *keys* are the paths to resolve against (default: what git tracks now);
+ *side* prefixes each failure, for the base report.
+ """
from repowise.core import git_refs
- from repowise.core.analysis.health.coverage import build_coverage_map
- resolved, errors = build_coverage_map(
- root,
- list(report_prefixes),
- set(git_refs.tracked_paths(str(root))),
- coverage_format=report_format or cfg.format,
- strip_prefix=cfg.strip_prefix,
- path_prefix=cfg.path_prefix,
- report_prefixes=report_prefixes,
- ignore=cfg.ignore,
- )
+ keys = git_refs.tracked_paths(str(reports.root)) if keys is None else keys
+ resolved, errors = reports.build(keys)
for path, err in errors:
notices.print(f"[yellow]{escape(path.name)}: {escape(err)}[/yellow]")
- if len(errors) == len(report_prefixes):
+ if len(errors) == len(reports.prefixes):
raise CannotEvaluateError(
- "report_unreadable", "No coverage report could be read; see the messages above."
+ "report_unreadable",
+ f"{side}No coverage report could be read; see the messages above.",
)
if not resolved.files and resolved.ignored and not resolved.total:
raise CannotEvaluateError(
"report_all_ignored",
- f"All {resolved.ignored} report entries match coverage.ignore, so nothing "
+ f"{side}All {resolved.ignored} report entries match coverage.ignore, so nothing "
"is left to measure. Narrow coverage.ignore in .repowise/config.yaml.",
)
if not resolved.files:
raise CannotEvaluateError(
"report_unmatched",
- "No report path matched a file in this repository. If the report paths "
+ f"{side}No report path matched a file in this repository. If the report paths "
"carry a build prefix, set coverage.strip_prefix in .repowise/config.yaml."
)
if resolved.mapping_partial:
@@ -436,7 +499,12 @@ def _resolve_reports(root, cfg, report_prefixes, report_format, notices):
def _coverage_config(
- root: Path, *, validate_threshold: bool, validate_min_lines: bool, validate_risky: bool = False
+ root: Path,
+ *,
+ validate_threshold: bool,
+ validate_min_lines: bool,
+ validate_risky: bool = False,
+ validate_max_drop: bool = False,
):
from repowise.core.analysis.health.coverage import CoverageConfig
from repowise.core.repo_config import RepoConfigError, load_repo_config
@@ -453,6 +521,7 @@ def _coverage_config(
for key, parsed, validate in (
("fail_under", cfg.fail_under, validate_threshold),
("fail_under_risky", cfg.fail_under_risky, validate_risky),
+ ("max_drop", cfg.max_drop, validate_max_drop),
):
if validate and block.get(key) is not None and parsed is None:
raise CannotEvaluateError(
@@ -486,17 +555,21 @@ def _emit(pc, fmt: str) -> None:
_print_summary(pc)
_print_path_gates(pc)
_print_table(pc)
+ _print_outside_change(pc)
def _print_summary(pc) -> None:
from repowise.core.analysis.patch_coverage import (
headline,
+ project_line,
risk_basis_line,
risky_line,
scope_line,
)
console.print(escape(headline(pc, markdown=False)))
+ if project := project_line(pc, markdown=False):
+ console.print(escape(project))
if risky := risky_line(pc, markdown=False):
console.print(escape(risky))
console.print(f"[dim]{escape(scope_line(pc, markdown=False))}[/dim]")
@@ -557,3 +630,336 @@ def _print_table(pc) -> None:
cells.append(escape(hint_phrase(hint)) if hint else "")
table.add_row(*cells)
console.print(table)
+
+
+def _print_outside_change(pc) -> None:
+ """The files whose coverage changed outside the change, when a base report named them."""
+ from rich.table import Table
+
+ from repowise.core.analysis.patch_coverage import indirect_row, outside_change_rows
+ from repowise.core.ci.markdown import ROW_LIMIT, more_line
+
+ rows = outside_change_rows(pc)
+ note = pc.project.outside_change_note if pc.project is not None else None
+ if note:
+ console.print(f"[dim]Coverage outside the change, files left out: {escape(note)}.[/dim]")
+ if not rows:
+ return
+ table = Table(title="Coverage outside the change", show_edge=False, pad_edge=False)
+ for name, justify in (
+ ("File", "left"),
+ ("Before", "right"),
+ ("After", "right"),
+ ("Newly uncovered lines", "left"),
+ ("Cause", "left"),
+ ):
+ table.add_column(name, justify=justify)
+ for c in rows[:ROW_LIMIT]:
+ table.add_row(*(escape(v) for v in indirect_row(c)))
+ console.print(table)
+ if len(rows) > ROW_LIMIT:
+ console.print(f"[dim]{more_line(len(rows) - ROW_LIMIT, 'files')}[/dim]")
+
+
+@dataclass(frozen=True)
+class _ProjectAsk:
+ """What a project comparison reads, and who asked for it.
+
+ *head* is the head's resolved reports (``None`` when read from the index),
+ read as *reports* says. *strict* when a flag asked (``--max-drop``,
+ ``--base-report``): a base the check cannot use then exits 2.
+ """
+
+ reports: _Reports
+ head: Any
+ base_reports: tuple[str, ...]
+ label: str
+ notices: Any
+ max_drop: float | None
+ strict: bool
+
+ @property
+ def root(self) -> Path:
+ return self.reports.root
+
+
+def _project_ask(pc, head, reports: _Reports, base_reports, max_drop, notices):
+ """The project comparison asked for, or ``None``: without ``--base-report`` or a
+ max-drop gate (flag or config) nothing is read."""
+ cfg = _coverage_config(
+ reports.root,
+ validate_threshold=False,
+ validate_min_lines=False,
+ validate_max_drop=max_drop is None,
+ )
+ strict = max_drop is not None or bool(base_reports)
+ max_drop = _first_set(max_drop, cfg.max_drop)
+ if not base_reports and max_drop is None:
+ return None
+ return _ProjectAsk(
+ reports, head, tuple(base_reports), pc.scope.label, notices, max_drop, strict
+ )
+
+
+def _with_project(pc, ask: _ProjectAsk):
+ """*pc* with project coverage at the base against the head.
+
+ A base report gives the totals and the files that changed outside the
+ change; without one, an index's ingest at the base commit gives the
+ totals. A base the check cannot use (none, incomparable, no coverable line
+ on a side) exits 2 when a flag asked for it, and is a note when only the
+ config did, or when another gate already failed: that verdict stands.
+ """
+ from repowise.core import git_refs
+
+ root = str(ask.root)
+ base_commit = git_refs.change_base(root, ask.label) or None
+ head_commit = git_refs.resolve(root, _revspec_head(ask.label)) or None
+ try:
+ measure = _report_delta if ask.base_reports else _history_delta
+ project = _usable(measure(ask, base_commit), ask.max_drop, head_commit)
+ except CannotEvaluateError as exc:
+ if ask.strict and pc.gate != "fail":
+ raise
+ _table_note(ask.notices, f"Project coverage not evaluated: {exc}")
+ return pc
+ return replace(pc, project=project)
+
+
+def _usable(project, max_drop, head_commit):
+ """*project* gated by *max_drop*, or why it cannot be judged."""
+ if project is None:
+ raise CannotEvaluateError(
+ "project_base_missing",
+ "The max-drop gate needs coverage measured at the change's base: pass it with "
+ "--base-report, or ingest one there with `repowise coverage add`.",
+ )
+ project = replace(project, max_drop=max_drop, head_commit=head_commit)
+ if project.incomparable:
+ raise CannotEvaluateError(
+ "project_scope_mismatch",
+ "Project coverage cannot be compared with the base: "
+ f"{'; '.join(project.incomparable)}.",
+ )
+ if project.gate == "no_data":
+ side = "base" if not (project.base and project.base.pct is not None) else "head"
+ raise CannotEvaluateError(
+ "project_base_missing",
+ f"Project coverage cannot be compared: the {side} measured no coverable line.",
+ )
+ return project
+
+
+def _table_note(notices, text: str) -> None:
+ # Machine formats say it with ``project: null``; the note is for a reader.
+ if notices is console:
+ notices.print(f"[dim]{escape(text)}[/dim]")
+
+
+def _revspec_head(label: str) -> str:
+ from repowise.core.analysis.change_risk.features import revspec_head
+
+ return revspec_head(label or None)
+
+
+def _report_delta(ask: _ProjectAsk, base_commit: str | None):
+ """Totals, and the files changed outside the change, from a report measured at the base.
+
+ Both sides count the same files: with a head read from the index, the
+ base keeps the files the index lists (what stored ingests resolve against),
+ plus those the change renamed or deleted, so an indexed file the head
+ ingest no longer names is still ``no_longer_measured``.
+ """
+ from repowise.core import git_refs
+ from repowise.core.analysis.patch_coverage import (
+ ProjectDelta,
+ incomparable_reasons,
+ indirect_changes,
+ project_totals,
+ )
+
+ if base_commit is None:
+ raise CannotEvaluateError(
+ "project_base_missing",
+ f"Could not find the base commit of {ask.label}, so --base-report cannot "
+ "be lined up with the change. Fetch the base branch's history.",
+ )
+ base = _resolve_reports(
+ replace(ask.reports, prefixes=_cli_reports(ask.base_reports, "--base-report")),
+ ask.notices,
+ keys=git_refs.tracked_paths_at(str(ask.root), base_commit),
+ side="Base report: ",
+ )
+ head_cov, head_scope, index_keys = _head_coverage(ask.root, ask.head)
+ diffs, renames, deleted = _change_diff(ask.root, base_commit, _revspec_head(ask.label))
+ base_cov = {fc.file_path: fc for fc in base.files}
+ if index_keys is not None:
+ base_cov = {
+ p: fc
+ for p, fc in base_cov.items()
+ if p in index_keys or p in deleted or p in renames
+ }
+ incomparable = incomparable_reasons(base.scope, head_scope)
+ rows = note = None
+ if not incomparable:
+ scan = indirect_changes(base_cov, head_cov, diffs, renames, deleted)
+ note = scan.note(base_commit)
+ if scan.rows is not None:
+ changed = set(diffs) | deleted | set(renames.values())
+ rows = _with_causes(ask.root, scan.rows, changed, deleted)
+ return ProjectDelta(
+ base=project_totals(base_cov),
+ head=project_totals(head_cov),
+ basis="base_report",
+ base_commit=base_commit,
+ incomparable=incomparable,
+ outside_change=rows,
+ outside_change_note=note,
+ )
+
+
+def _head_coverage(root: Path, head) -> tuple[dict, Any, set[str] | None]:
+ """``({path: FileCoverage}, scope, index file keys)`` of the head.
+
+ From its reports (keys ``None``: they resolved against every tracked
+ file), else from the index, with the file keys its ingests resolve against.
+ """
+ if head is not None:
+ return {fc.file_path: fc for fc in head.files}, head.scope, None
+ found = run_async(_stored_head(root))
+ if found is None:
+ raise CannotEvaluateError(
+ "index_unreadable", "Could not read the index's coverage for the head."
+ )
+ return found
+
+
+async def _stored_head(root: Path):
+ from sqlalchemy.exc import SQLAlchemyError
+
+ from repowise.cli.commands.coverage_cmd import _repo_file_keys
+ from repowise.core.analysis.patch_coverage import ingest_scope
+ from repowise.core.persistence.crud import load_file_coverage, load_newest_ingest
+
+ async with repo_index_session(root) as opened:
+ if opened is None:
+ return None
+ session, repo_id = opened
+ try:
+ ingest = await load_newest_ingest(session, repo_id)
+ files = await load_file_coverage(session, repo_id)
+ keys = await _repo_file_keys(session, repo_id)
+ except SQLAlchemyError:
+ return None
+ return files, ingest_scope(ingest) if ingest is not None else None, keys
+
+
+def _change_diff(root: Path, base_commit: str, head_rev: str):
+ """``(diffs, renames, deleted)`` from the base commit to the head, or why not."""
+ import subprocess
+
+ from repowise.core.analysis.changed_lines import change_diff
+
+ try:
+ return change_diff(str(root), base_commit, head_rev)
+ except ValueError as exc:
+ raise CannotEvaluateError("diff_failed", f"Could not diff the change: {exc}") from exc
+ except (subprocess.SubprocessError, OSError) as exc:
+ raise CannotEvaluateError("git_failed", f"Could not run git: {exc}") from exc
+
+
+def _history_delta(ask: _ProjectAsk, base_commit: str | None):
+ """Totals from the index's ingest at *base_commit*; ``None`` when there is none."""
+ if base_commit is None or not has_db_store(ask.root):
+ return None
+ found = run_async(_read_history(ask.root, ask.head, base_commit))
+ if found is None or ask.head is None:
+ return found
+ row, keys = found
+ return _report_against_ingest(ask, row, keys)
+
+
+async def _read_history(root: Path, head, base_commit: str):
+ """The stored delta when the head is stored too; else ``(base ingest, index file keys)``."""
+ from sqlalchemy.exc import SQLAlchemyError
+
+ from repowise.cli.commands.coverage_cmd import _repo_file_keys
+ from repowise.core.analysis.patch_coverage import history_delta
+ from repowise.core.persistence.crud import load_ingest_at_commit
+
+ async with repo_index_session(root) as opened:
+ if opened is None:
+ return None
+ session, repo_id = opened
+ try:
+ if head is None:
+ return await history_delta(session, repo_id, base_commit)
+ row = await load_ingest_at_commit(session, repo_id, base_commit)
+ keys = await _repo_file_keys(session, repo_id) if row is not None else set()
+ except (SQLAlchemyError, OSError):
+ # An index too old or damaged to answer has no base to offer.
+ return None
+ return None if row is None else (row, keys)
+
+
+def _report_against_ingest(ask: _ProjectAsk, row, keys):
+ """The head report's totals against a stored base ingest.
+
+ The ingest counted the files the index knows, so the head report is
+ resolved against the same keys, not against every file git tracks.
+ """
+ from repowise.core.analysis.patch_coverage import (
+ ProjectDelta,
+ incomparable_reasons,
+ ingest_scope,
+ ingest_totals,
+ project_totals,
+ )
+
+ reasons = incomparable_reasons(ingest_scope(row), ask.head.scope)
+ head_totals = None
+ if not keys:
+ reasons += ("the index lists no files to resolve the head report against",)
+ else:
+ resolved, _errors = ask.reports.build(keys)
+ head_totals = project_totals({fc.file_path: fc for fc in resolved.files})
+ return ProjectDelta(
+ base=ingest_totals(row),
+ head=head_totals,
+ basis="history",
+ base_commit=row.ingested_commit_sha,
+ incomparable=reasons,
+ )
+
+
+def _with_causes(root: Path, rows, changed: set[str], deleted: set[str]):
+ """*rows* with the changed files that explain each one's lost coverage (advice only).
+
+ From the index when one opens, else from git by name; an index that fails
+ the read leaves the causes unassessed.
+ """
+ from repowise.core.analysis.patch_coverage import apply_causes, name_causes, needs_causes
+
+ causes = None
+ if has_db_store(root):
+ try:
+ causes = run_async(_read_causes(root, rows, changed, deleted))
+ except Exception:
+ causes = None # advice: an index that breaks the read leaves causes unassessed
+ else:
+ causes = name_causes(needs_causes(rows), changed, deleted)
+ return apply_causes(rows, causes)
+
+
+async def _read_causes(root: Path, rows, changed: set[str], deleted: set[str]):
+ from repowise.core.analysis.patch_coverage import (
+ name_causes,
+ needs_causes,
+ read_indirect_causes,
+ )
+
+ async with repo_index_session(root) as opened:
+ if opened is None:
+ return name_causes(needs_causes(rows), changed, deleted)
+ session, repo_id = opened
+ return await read_indirect_causes(session, repo_id, rows, changed, deleted)
diff --git a/packages/core/alembic/versions/0084_coverage_ingest_scope.py b/packages/core/alembic/versions/0084_coverage_ingest_scope.py
new file mode 100644
index 000000000..ed819a542
--- /dev/null
+++ b/packages/core/alembic/versions/0084_coverage_ingest_scope.py
@@ -0,0 +1,46 @@
+"""coverage_ingests.scope_json: what each ingest measured, for comparing two.
+
+A project coverage delta compares the ingest at a change's base with the one at
+its head, and that is only honest when both read the same kind of reports with
+the same ``coverage.ignore``. ``scope_json`` records it per ingest. NULL on rows
+written before it: "scope unknown", which the delta reports as incomparable.
+
+Local SQLite stores never run Alembic -- ``init_db``'s reconciler issues
+additive DDL for missing columns -- so this migration exists for managed
+Postgres.
+
+Revision ID: 0084
+Revises: 0083
+Create Date: 2026-09-29
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0084"
+down_revision: str | None = "0083"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+_TABLE = "coverage_ingests"
+_COLUMN = "scope_json"
+
+
+def _columns() -> set[str]:
+ return {c["name"] for c in sa.inspect(op.get_bind()).get_columns(_TABLE)}
+
+
+def upgrade() -> None:
+ # Guarded: ``init_db``'s reconciler may already have added it on Postgres.
+ if _COLUMN not in _columns():
+ op.add_column(_TABLE, sa.Column(_COLUMN, sa.Text(), nullable=True))
+
+
+def downgrade() -> None:
+ if _COLUMN in _columns():
+ op.drop_column(_TABLE, _COLUMN)
diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.py
index 009365aae..30ef31ba5 100644
--- a/packages/core/src/repowise/core/analysis/changed_lines.py
+++ b/packages/core/src/repowise/core/analysis/changed_lines.py
@@ -320,6 +320,36 @@ def diff_since(
return parse_unified_diff(_diff(repo_path, args))
+def change_diff(
+ repo_path: str, base: str, head: str
+) -> tuple[dict[str, FileDiff], dict[str, str], set[str]]:
+ """``(diffs, renames, deleted)`` for the change from commit *base* to *head*.
+
+ *diffs* is :func:`parse_unified_diff`'s, keyed by new-side path;
+ *renames* maps each renamed file's old path to its new one; *deleted*
+ holds the old paths of deleted files. Rename detection is on for both
+ reads, whatever the user's ``diff.renames``.
+ """
+ diffs = parse_unified_diff(
+ _diff(repo_path, ["diff", "--unified=0", "-M", *DIFF_PREFIXES, base, head])
+ )
+ fields = _diff(repo_path, ["diff", "--name-status", "-z", "-M", base, head]).split("\0")
+ renames: dict[str, str] = {}
+ deleted: set[str] = set()
+ i = 0
+ while i < len(fields) - 1:
+ status = fields[i]
+ if status[:1] in ("R", "C"):
+ if status[0] == "R":
+ renames[fields[i + 1]] = fields[i + 2]
+ i += 3
+ continue
+ if status == "D":
+ deleted.add(fields[i + 1])
+ i += 2
+ return diffs, renames, deleted
+
+
def _diff(repo_path: str, args: list[str]) -> str:
"""Run a diff, turning git's refusal (e.g. no merge-base) into ``ValueError``."""
try:
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
index 9545bacbc..bd5d150e6 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
@@ -21,6 +21,7 @@ from .detector import PARSERS, detect_format, is_test_file, paired_test_file, pa
from .discovery import (
CoverageConfig,
CoverageProvenance,
+ CoverageScope,
PathGate,
ResolvedCoverage,
ResolvedTestCoverage,
@@ -54,6 +55,7 @@ __all__ = [
"CoverageDecay",
"CoverageProvenance",
"CoverageReport",
+ "CoverageScope",
"FileCoverage",
"FreshnessStatus",
"PathGate",
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
index 23a336cdd..8d5a79f76 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
@@ -28,6 +28,7 @@ from collections.abc import Iterable, Iterator, Mapping, Sequence
from dataclasses import dataclass, field
from itertools import chain
from pathlib import Path
+from typing import Any
import pathspec
@@ -140,6 +141,9 @@ class CoverageConfig:
gate_errors: tuple[str, ...] = ()
# The stricter gate over risky files only (``coverage check --fail-under-risky``).
fail_under_risky: float | None = None
+ # Most project coverage may fall from the change's base, in percentage
+ # points (``coverage check --max-drop``).
+ max_drop: float | None = None
@classmethod
def from_repo_config(cls, repo_config: dict | None) -> CoverageConfig:
@@ -171,6 +175,7 @@ class CoverageConfig:
gates=gates,
gate_errors=gate_errors,
fail_under_risky=_percent(block.get("fail_under_risky")),
+ max_drop=_percent(block.get("max_drop")),
)
def reports(self, repo_root: Path) -> dict[Path, str | None]:
@@ -382,6 +387,10 @@ class ResolvedCoverage:
# Set by :func:`resolve_reports`; consumers must flag the aggregate as
# partial rather than reporting the mapped subset's numbers as repo-wide.
mapping_partial: bool = False
+ # One format per report read, repeats kept, and the ``coverage.ignore``
+ # applied: with ``mapping_partial``, what makes two measurements comparable.
+ report_formats: list[str] = field(default_factory=list)
+ ignore: tuple[str, ...] = ()
@property
def matched(self) -> int:
@@ -401,6 +410,15 @@ class ResolvedCoverage:
ambiguous_path_count=len(self.ambiguous),
unmatched_sample=tuple((self.unmatched + self.ambiguous)[:UNMATCHED_SAMPLE_CAP]),
mapping_partial=self.mapping_partial,
+ scope=self.scope,
+ )
+
+ @property
+ def scope(self) -> CoverageScope:
+ return CoverageScope(
+ report_formats=tuple(sorted(self.report_formats)),
+ ignore=tuple(sorted(self.ignore)),
+ mapping_partial=self.mapping_partial,
)
@@ -423,6 +441,45 @@ class CoverageProvenance:
ambiguous_path_count: int | None = None
unmatched_sample: tuple[str, ...] = ()
mapping_partial: bool = False
+ # ``None`` when the writer did not resolve the reports itself.
+ scope: CoverageScope | None = None
+
+
+@dataclass(frozen=True)
+class CoverageScope:
+ """What makes two coverage measurements comparable.
+
+ *report_formats* has one entry per report read (``("lcov", "lcov")`` for
+ two lcov reports), sorted; *ignore* is the ``coverage.ignore`` applied,
+ sorted. A base and head that differ in either measured different things,
+ and a partial mapping measured a fragment, so neither delta means anything
+ (``patch_coverage.delta.incomparable_reasons``).
+ """
+
+ report_formats: tuple[str, ...] = ()
+ ignore: tuple[str, ...] = ()
+ mapping_partial: bool = False
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "report_formats": list(self.report_formats),
+ "ignore": list(self.ignore),
+ "mapping_partial": self.mapping_partial,
+ }
+
+ @classmethod
+ def from_dict(cls, data: object) -> CoverageScope | None:
+ """The scope :meth:`to_dict` wrote, ``None`` for anything else."""
+ if not isinstance(data, dict):
+ return None
+ formats, ignore = data.get("report_formats"), data.get("ignore")
+ if not isinstance(formats, list) or not isinstance(ignore, list):
+ return None
+ return cls(
+ report_formats=tuple(sorted(str(f) for f in formats)),
+ ignore=tuple(sorted(str(g) for g in ignore)),
+ mapping_partial=bool(data.get("mapping_partial", False)),
+ )
def discover_artifacts(
@@ -864,7 +921,7 @@ def resolve_reports(
"""
suffix_index = _build_suffix_index(repo_keys)
ignore_spec = pathspec.PathSpec.from_lines("gitwildmatch", ignore)
- result = ResolvedCoverage()
+ result = ResolvedCoverage(ignore=tuple(ignore))
by_key: dict[str, FileCoverage] = {}
report_file_count = 0
for report in reports:
@@ -873,6 +930,7 @@ def resolve_reports(
# not rewrite an lcov report's ``web/src/x.ts``.
modules = go_modules if report.source_format == "go-coverprofile" else ()
_note_format(result, report.source_format)
+ result.report_formats.append(report.source_format)
for fc in report.files:
report_file_count += 1
key, ambiguous, exact = _resolve_path(
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py
index 1c1e4e7ce..ff0aebf8d 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from .causes import apply_causes, name_causes, needs_causes, read_indirect_causes
from .compute import (
FilePatchCoverage,
FileStatus,
@@ -12,6 +13,16 @@ from .compute import (
compute_patch_coverage,
patch_coverage_from_resolved,
)
+from .delta import (
+ IndirectCause,
+ IndirectChange,
+ OutsideChangeScan,
+ ProjectDelta,
+ ProjectTotals,
+ incomparable_reasons,
+ indirect_changes,
+ project_totals,
+)
from .hints import (
TestHint,
attach_hints,
@@ -24,12 +35,16 @@ from .render import (
RANGE_LIMIT,
STATUS_TEXT,
attention_rows,
+ cause_words,
fmt_pct,
format_ranges,
github_annotations,
headline,
+ indirect_row,
+ outside_change_rows,
path_gate_row,
path_gate_verdict,
+ project_line,
render_markdown,
risk_basis_line,
risk_words,
@@ -45,7 +60,14 @@ from .risk import (
read_git_fix_history,
risk_unreadable,
)
-from .stored import read_index_facts, stored_patch_coverage
+from .stored import (
+ attach_history_delta,
+ history_delta,
+ ingest_scope,
+ ingest_totals,
+ read_index_facts,
+ stored_patch_coverage,
+)
__all__ = [
"RANGE_LIMIT",
@@ -56,15 +78,23 @@ __all__ = [
"GateStatus",
"GitFixHistory",
"IndexFacts",
+ "IndirectCause",
+ "IndirectChange",
+ "OutsideChangeScan",
"PatchCoverage",
"PatchScope",
"PathGateResult",
+ "ProjectDelta",
+ "ProjectTotals",
"TestHint",
+ "apply_causes",
"assess_risks",
"attach_hints",
+ "attach_history_delta",
"attach_risk",
"attention_rows",
"build_hints",
+ "cause_words",
"compute_patch_coverage",
"first_hint",
"fmt_pct",
@@ -72,11 +102,23 @@ __all__ = [
"github_annotations",
"headline",
"hint_phrase",
+ "history_delta",
+ "incomparable_reasons",
+ "indirect_changes",
+ "indirect_row",
+ "ingest_scope",
+ "ingest_totals",
+ "name_causes",
+ "needs_causes",
+ "outside_change_rows",
"patch_coverage_from_resolved",
"path_gate_row",
"path_gate_verdict",
+ "project_line",
+ "project_totals",
"read_git_fix_history",
"read_index_facts",
+ "read_indirect_causes",
"read_test_hints",
"render_markdown",
"risk_basis_line",
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/causes.py b/packages/core/src/repowise/core/analysis/patch_coverage/causes.py
new file mode 100644
index 000000000..aaf71086c
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/causes.py
@@ -0,0 +1,157 @@
+"""Which changed files explain coverage lost outside the change.
+
+Advice, never part of a verdict. For each file with newly uncovered lines
+outside the change (:func:`~.delta.indirect_changes`), the changed files that
+could have moved its coverage:
+
+* ``test_deleted`` / ``test_modified``: a test file the change deleted or
+ modified that reached the file. Measured from the per-test coverage map when
+ one is stored for it (``per_test``), else inferred from the reverse test walk
+ (``graph``).
+* ``dependent_changed``: a changed non-test file with a call or an import
+ edge into it (``graph`` covers both edge kinds).
+
+Name pairing (``name``) adds a changed test named for the file by convention:
+for a file the index names no test cause for, for every file without an
+index, and always for a test the change deleted, which an index built at the
+head no longer holds.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Collection, Iterable, Mapping
+from dataclasses import replace
+from typing import TYPE_CHECKING
+
+from ...test_paths import is_test_related_path
+from .delta import CauseBasis, IndirectCause, IndirectChange
+
+if TYPE_CHECKING:
+ from sqlalchemy.ext.asyncio import AsyncSession
+
+log = logging.getLogger(__name__)
+
+#: Files whose causes the index is asked for. Ceiling: past it, the rest get
+#: name pairing only (one ``IN`` list per graph read, bounded like the hints').
+MAX_TARGETS = 200
+
+
+def needs_causes(indirect: Iterable[IndirectChange]) -> list[str]:
+ """The files a cause is looked for: those with newly uncovered lines."""
+ return [c.file_path for c in indirect if c.newly_uncovered_ranges]
+
+
+def _test_causes(
+ tests: Collection[str],
+ changed_tests: Collection[str],
+ deleted: Collection[str],
+ basis: CauseBasis,
+) -> list[IndirectCause]:
+ return [
+ IndirectCause("test_deleted" if t in deleted else "test_modified", t, basis)
+ for t in sorted(set(tests) & set(changed_tests))
+ ]
+
+
+def name_causes(
+ files: Iterable[str], changed: Collection[str], deleted: Collection[str]
+) -> dict[str, tuple[IndirectCause, ...]]:
+ """``{file: causes}`` from git alone: changed tests named for each file."""
+ from ..test_reachability import tests_matching_by_name
+
+ tests = [p for p in changed if is_test_related_path(p)]
+ files = list(files)
+ matched = tests_matching_by_name(files, tests)
+ return {
+ f: tuple(
+ _test_causes(matched[f].all_tests or matched[f].tests, tests, deleted, "name")
+ if f in matched
+ else ()
+ )
+ for f in files
+ }
+
+
+def apply_causes(
+ indirect: Iterable[IndirectChange], causes: Mapping[str, tuple[IndirectCause, ...]] | None
+) -> tuple[IndirectChange, ...]:
+ """*indirect* with each row *causes* names carrying its causes; ``None`` changes nothing."""
+ return tuple(
+ replace(c, causes=causes[c.file_path]) if causes and c.file_path in causes else c
+ for c in indirect
+ )
+
+
+async def read_indirect_causes(
+ session: AsyncSession,
+ repository_id: str,
+ indirect: Iterable[IndirectChange],
+ changed: Collection[str],
+ deleted: Collection[str],
+) -> dict[str, tuple[IndirectCause, ...]] | None:
+ """``{file: causes}`` from the index, name pairing where it names no test; ``None`` on failure.
+
+ *changed* is every path the change touched, deleted ones included (their
+ old paths, as in *deleted*).
+ """
+ files = needs_causes(indirect)
+ if not files:
+ return {}
+ try:
+ found = await _read(session, repository_id, files[:MAX_TARGETS], changed, deleted)
+ except Exception:
+ # Advice never breaks the caller: any failure is logged and reads as unassessed.
+ log.warning("indirect_coverage_causes_failed", exc_info=True)
+ return None
+ by_name = name_causes(files, changed, deleted)
+ return {f: _merge(found.get(f, ()), by_name[f]) for f in files}
+
+
+def _merge(
+ indexed: tuple[IndirectCause, ...], by_name: tuple[IndirectCause, ...]
+) -> tuple[IndirectCause, ...]:
+ """The index's causes plus name pairing: deleted tests always, the rest when the
+ index named no test. Tests first, then dependents."""
+ tests = [c for c in indexed if c.kind != "dependent_changed"]
+ named = {c.path for c in tests}
+ extra = [
+ c for c in by_name if c.path not in named and (c.kind == "test_deleted" or not tests)
+ ]
+ return (*tests, *extra, *(c for c in indexed if c.kind == "dependent_changed"))
+
+
+async def _read(
+ session: AsyncSession,
+ repository_id: str,
+ files: list[str],
+ changed: Collection[str],
+ deleted: Collection[str],
+) -> dict[str, tuple[IndirectCause, ...]]:
+ from repowise.core.persistence.crud.analysis.coverage_map import tests_covering_files
+
+ from ..test_reachability import direct_dependents, tests_reaching_by_tier
+
+ changed_tests = {p for p in changed if is_test_related_path(p)}
+ changed_code = set(changed) - changed_tests
+ per_test = await tests_covering_files(session, repository_id, set(files))
+ reached = await tests_reaching_by_tier(session, repository_id, files)
+ dependents = await direct_dependents(session, repository_id, files)
+ out: dict[str, tuple[IndirectCause, ...]] = {}
+ for f in files:
+ if rows := per_test.get(f):
+ # A test id without a file is named by its id's path part, as the hints read it.
+ tests = {
+ r.get("test_file") or str(r.get("test_id", "")).split("::", 1)[0] for r in rows
+ }
+ causes = _test_causes(tests, changed_tests, deleted, "per_test")
+ elif (by := reached.get(f)) is not None:
+ causes = _test_causes(by.all_tests or by.tests, changed_tests, deleted, "graph")
+ else:
+ causes = []
+ causes += [
+ IndirectCause("dependent_changed", p, "graph")
+ for p in sorted((dependents.get(f, set()) & changed_code) - {f})
+ ]
+ out[f] = tuple(causes)
+ return out
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
index 67868b1c7..491f0cb8e 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
@@ -41,6 +41,7 @@ from ..health.coverage.model import FileCoverage
if TYPE_CHECKING:
from ..health.coverage.discovery import PathGate, ResolvedCoverage
+ from .delta import ProjectDelta
from .hints import TestHint
from .risk import FileRisk
@@ -201,6 +202,8 @@ class PatchCoverage:
path_gates: tuple[PathGateResult, ...] = ()
# A stricter gate over the risky files only (``risk.attach_risk``).
risky_threshold: float | None = None
+ # Project coverage at the change's base against its head (``delta``).
+ project: ProjectDelta | None = None
@property
def changed_file_count(self) -> int:
@@ -233,14 +236,18 @@ class PatchCoverage:
@property
def gate(self) -> GateStatus:
- """``flat_gate``, or ``fail`` when a path-scoped or the risky-file gate fails.
+ """``flat_gate``, or ``fail`` when a path-scoped, the risky-file or the project gate fails.
- With no flat threshold the risky-file gate's status is the verdict.
+ With no flat threshold the risky-file gate's status is the verdict, and
+ with neither, the project gate's.
"""
- if self.failing_path_gates or self.risky_gate == "fail":
+ project = self.project.gate if self.project is not None else "not_set"
+ if self.failing_path_gates or "fail" in (self.risky_gate, project):
return "fail"
- flat = self.flat_gate
- return self.risky_gate if flat == "not_set" else flat
+ for status in (self.flat_gate, self.risky_gate):
+ if status != "not_set":
+ return status
+ return project
@property
def failing_path_gates(self) -> list[PathGateResult]:
@@ -309,6 +316,7 @@ class PatchCoverage:
"scope": self.scope.to_dict(),
"path_gates": [g.to_dict() for g in self.path_gates],
"risky": self._risky_dict(),
+ "project": self.project.to_dict() if self.project is not None else None,
}
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/delta.py b/packages/core/src/repowise/core/analysis/patch_coverage/delta.py
new file mode 100644
index 000000000..fb129e97c
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/delta.py
@@ -0,0 +1,374 @@
+"""Project coverage delta and coverage outside the change.
+
+Patch coverage judges only the lines a change touched, so it misses a change
+that deletes a test file, or removes a code path that ran other files. Two
+views close that gap, both pure:
+
+* :class:`ProjectDelta`: total coverage at the change's base against its
+ head, with a tolerance gate (``max_drop``, in percentage points). The two
+ measurements must be comparable (:class:`CoverageScope`): the same kind and
+ number of reports, the same ``coverage.ignore``, neither a partial mapping.
+ Otherwise the delta is reported as incomparable and never judged.
+* :func:`indirect_changes` (``outside_change`` on the wire): files whose
+ coverage changed on lines the change did not touch, each base line moved to
+ the head through the diff
+ (:func:`~repowise.core.analysis.changed_lines.map_old_line`). Lines the
+ change touched belong to patch coverage and are left out here.
+
+The base comes from a report measured at the base commit (``base_report``:
+totals and per-file comparison) or from the stored ingest history
+(``history``: totals only).
+"""
+
+from __future__ import annotations
+
+from collections import Counter
+from collections.abc import Iterable, Mapping, Sequence
+from dataclasses import dataclass
+from typing import Any, Literal
+
+import pathspec
+
+from ..changed_lines import FileDiff, line_ranges, map_old_line
+from ..health.coverage.discovery import CoverageScope
+from ..health.coverage.model import FileCoverage
+from .compute import GateStatus, _pct, _round
+
+DeltaBasis = Literal["base_report", "history"]
+IndirectStatus = Literal["changed", "no_longer_measured"]
+CauseKind = Literal["test_deleted", "test_modified", "dependent_changed"]
+CauseBasis = Literal["per_test", "graph", "name"]
+
+
+@dataclass(frozen=True)
+class ProjectTotals:
+ """Covered and coverable lines over every measured file."""
+
+ covered_line_count: int
+ coverable_line_count: int
+
+ @property
+ def pct(self) -> float | None:
+ return _pct(self.covered_line_count, self.coverable_line_count)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "covered_line_count": self.covered_line_count,
+ "coverable_line_count": self.coverable_line_count,
+ "coverage_pct": _round(self.pct),
+ }
+
+
+def project_totals(
+ coverage: Mapping[str, FileCoverage], ignore: Sequence[str] = ()
+) -> ProjectTotals:
+ """Totals of *coverage* after *ignore*, counted the way the coverage summary counts."""
+ spec = pathspec.PathSpec.from_lines("gitwildmatch", ignore)
+ kept = [fc for path, fc in coverage.items() if not spec.match_file(path)]
+ return ProjectTotals(
+ covered_line_count=sum(_covered_count(fc) for fc in kept),
+ coverable_line_count=sum(fc.total_coverable_lines or 0 for fc in kept),
+ )
+
+
+def _covered_count(fc: FileCoverage) -> int:
+ # The stored summary's rule (``persistence.crud`` ``_covered_count``).
+ if fc.covered_line_count is not None:
+ return fc.covered_line_count
+ return round(float(fc.line_coverage_pct or 0.0) / 100.0 * (fc.total_coverable_lines or 0))
+
+
+def _file_pct(fc: FileCoverage) -> float | None:
+ return _pct(_covered_count(fc), fc.total_coverable_lines or 0)
+
+
+def incomparable_reasons(
+ base: CoverageScope | None, head: CoverageScope | None
+) -> tuple[str, ...]:
+ """Why a base and a head measurement cannot be compared; empty when they can.
+
+ ``None`` is a measurement that recorded no scope (an ingest written before
+ scopes were kept).
+ """
+ reasons = []
+ if base is None:
+ reasons.append(
+ "the base ingest predates scope records; pass --base-report, "
+ "or re-measure coverage at the base commit"
+ )
+ if head is None:
+ reasons.append("the head ingest predates scope records; re-ingest it")
+ if base is None or head is None:
+ return tuple(reasons)
+ reasons += [
+ f"the {side} report mapped fewer than half its files"
+ for side, scope in (("base", base), ("head", head))
+ if scope.mapping_partial
+ ]
+ if Counter(base.report_formats) != Counter(head.report_formats):
+ reasons.append(
+ f"the base read {_formats_text(base.report_formats)}, "
+ f"the head read {_formats_text(head.report_formats)}"
+ )
+ if sorted(base.ignore) != sorted(head.ignore):
+ reasons.append("coverage.ignore differs")
+ return tuple(reasons)
+
+
+def _formats_text(formats: Iterable[str]) -> str:
+ """``"2 lcov reports and 1 cobertura report"``; ``"no report"`` when empty."""
+ counts = Counter(formats)
+ if not counts:
+ return "no report"
+ parts = [f"{n} {fmt} report{'s' if n != 1 else ''}" for fmt, n in sorted(counts.items())]
+ return " and ".join(parts)
+
+
+@dataclass(frozen=True)
+class IndirectCause:
+ """A changed file that explains coverage lost outside the change."""
+
+ kind: CauseKind
+ path: str
+ #: ``per_test`` measured, ``graph`` inferred from the index, ``name`` a
+ #: git-only pairing of a test's name with the file's.
+ basis: CauseBasis
+
+ def to_dict(self) -> dict[str, Any]:
+ return {"kind": self.kind, "path": self.path, "basis": self.basis}
+
+
+@dataclass(frozen=True)
+class IndirectChange:
+ """One file whose coverage changed on lines the change did not touch."""
+
+ file_path: str # the head-side path
+ #: Head-side inclusive runs of lines covered at the base and not at the head.
+ newly_uncovered_ranges: tuple[tuple[int, int], ...]
+ newly_covered_line_count: int
+ base_pct: float | None
+ head_pct: float | None
+ status: IndirectStatus
+ #: ``None`` not assessed; ``()`` assessed, and nothing in the change explains it.
+ causes: tuple[IndirectCause, ...] | None = None
+
+ @property
+ def newly_uncovered_line_count(self) -> int:
+ return sum(b - a + 1 for a, b in self.newly_uncovered_ranges)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "file_path": self.file_path,
+ "status": self.status,
+ "newly_uncovered_ranges": [list(r) for r in self.newly_uncovered_ranges],
+ "newly_uncovered_line_count": self.newly_uncovered_line_count,
+ "newly_covered_line_count": self.newly_covered_line_count,
+ "base_pct": _round(self.base_pct),
+ "head_pct": _round(self.head_pct),
+ "causes": None if self.causes is None else [c.to_dict() for c in self.causes],
+ }
+
+
+#: A file is misaligned when at least this many untouched base lines, and more
+#: than :data:`MISALIGNED_SHARE` of them, land on a line the head does not count.
+MISALIGNED_MIN_LINES = 3
+MISALIGNED_SHARE = 0.10
+
+
+@dataclass(frozen=True)
+class OutsideChangeScan:
+ """:func:`indirect_changes`' answer: the rows, and the files it could not line up."""
+
+ #: ``None`` when most compared files are misaligned: the list would be noise.
+ rows: tuple[IndirectChange, ...] | None
+ #: Files whose base lines did not line up with the head; left out of *rows*.
+ misaligned: tuple[str, ...]
+ compared_file_count: int
+
+ def note(self, base_commit: str | None) -> str | None:
+ """The one project-level reason, or ``None`` when every file lined up."""
+ if not self.misaligned:
+ return None
+ at = base_commit[:7] if base_commit else "the base commit"
+ n = len(self.misaligned)
+ files = f"{n} file" if n == 1 else f"{n} files"
+ return (
+ f"the base report does not line up with {at} in {files}; "
+ "measure it at the base commit"
+ )
+
+
+def indirect_changes(
+ base_cov: Mapping[str, FileCoverage],
+ head_cov: Mapping[str, FileCoverage],
+ diffs: Mapping[str, FileDiff],
+ renames: Mapping[str, str],
+ deleted: Iterable[str],
+) -> OutsideChangeScan:
+ """Files whose coverage changed outside the change, most newly uncovered lines first.
+
+ *base_cov* is keyed by base-side path, *head_cov* and *diffs* by head-side
+ path; *renames* maps old paths to new ones and *deleted* holds the old
+ paths the change deleted. A base file with coverable lines that the head
+ report no longer names, and the change did not delete, is
+ ``no_longer_measured`` under its head-side path.
+
+ A base report measured anywhere but the base commit maps onto the wrong
+ lines, so each file's untouched base lines are checked: a misaligned file
+ is left out, and when most compared files are, no row is kept at all.
+ """
+ gone = set(deleted)
+ rows: list[IndirectChange] = []
+ misaligned: list[str] = []
+ compared = 0
+ for old_path, base_fc in base_cov.items():
+ if old_path in gone:
+ continue
+ new_path = renames.get(old_path, old_path)
+ row, counts = _file_result(new_path, base_fc, head_cov.get(new_path), diffs.get(new_path))
+ compared += counts is not None
+ if counts is not None and _is_misaligned(*counts):
+ misaligned.append(new_path)
+ elif row is not None:
+ rows.append(row)
+ return OutsideChangeScan(_kept(rows, misaligned, compared), tuple(sorted(misaligned)), compared)
+
+
+def _file_result(
+ path: str, base_fc: FileCoverage, head_fc: FileCoverage | None, diff: FileDiff | None
+) -> tuple[IndirectChange | None, tuple[int, int] | None]:
+ """``(row or None, (aligned, misaligned) or None when nothing was compared)``."""
+ if head_fc is None:
+ # Ceiling: dropping a poorly covered file raises the head's figure;
+ # this row is the only place that shows why.
+ if not base_fc.total_coverable_lines:
+ return None, None
+ return IndirectChange(path, (), 0, _file_pct(base_fc), None, "no_longer_measured"), None
+ row, aligned, astray = _compare(path, base_fc, head_fc, diff)
+ return row, (aligned, astray) if aligned + astray else None
+
+
+def _is_misaligned(aligned: int, astray: int) -> bool:
+ return astray >= MISALIGNED_MIN_LINES and astray > MISALIGNED_SHARE * (aligned + astray)
+
+
+def _kept(
+ rows: list[IndirectChange], misaligned: list[str], compared: int
+) -> tuple[IndirectChange, ...] | None:
+ """*rows*, most newly uncovered lines first; ``None`` when most files are misaligned."""
+ if misaligned and len(misaligned) * 2 > compared:
+ return None
+ return tuple(sorted(rows, key=lambda c: (-c.newly_uncovered_line_count, c.file_path)))
+
+
+def _compare(
+ path: str, base_fc: FileCoverage, head_fc: FileCoverage, diff: FileDiff | None
+) -> tuple[IndirectChange | None, int, int]:
+ """``(row or None, aligned lines, misaligned lines)`` for *path*'s untouched base lines.
+
+ A line is aligned when it lands on a line the head report counts as
+ coverable. A touched file whose line data is identical on both sides by
+ raw line number was measured at the head, not the base: all misaligned.
+ """
+ if diff and diff.hunks and _same_lines(base_fc, head_fc):
+ return None, 0, max(len(base_fc.coverable_lines), MISALIGNED_MIN_LINES)
+ head_coverable = set(head_fc.coverable_lines)
+ pairs = _untouched_lines(base_fc, diff)
+ aligned = [(old, new) for old, new in pairs if new in head_coverable]
+ lost, gained = _moved(aligned, set(base_fc.covered_lines), set(head_fc.covered_lines))
+ row = None
+ if lost or gained:
+ row = IndirectChange(
+ path, line_ranges(lost), gained, _file_pct(base_fc), _file_pct(head_fc), "changed"
+ )
+ return row, len(aligned), len(pairs) - len(aligned)
+
+
+def _untouched_lines(base_fc: FileCoverage, diff: FileDiff | None) -> list[tuple[int, int]]:
+ """``(base line, head line)`` for each coverable base line the change did not touch."""
+ touched = diff.old_ranges if diff else []
+ hunks = diff.hunks if diff else []
+ return [
+ (line, map_old_line(hunks, line) if hunks else line)
+ for line in base_fc.coverable_lines
+ if not any(a <= line <= b for a, b in touched)
+ ]
+
+
+def _moved(
+ pairs: list[tuple[int, int]], base_covered: set[int], head_covered: set[int]
+) -> tuple[list[int], int]:
+ """``(head lines newly uncovered, count newly covered)`` over aligned *pairs*."""
+ lost = [new for old, new in pairs if old in base_covered and new not in head_covered]
+ gained = sum(1 for old, new in pairs if new in head_covered and old not in base_covered)
+ return lost, gained
+
+
+def _same_lines(a: FileCoverage, b: FileCoverage) -> bool:
+ same_coverable = set(a.coverable_lines) == set(b.coverable_lines)
+ return same_coverable and set(a.covered_lines) == set(b.covered_lines)
+
+
+@dataclass(frozen=True)
+class ProjectDelta:
+ """Project coverage at the change's base against its head."""
+
+ base: ProjectTotals | None
+ head: ProjectTotals | None
+ basis: DeltaBasis
+ base_commit: str | None = None
+ head_commit: str | None = None
+ #: The most project coverage may fall, in percentage points; ``None`` ungated.
+ max_drop: float | None = None
+ #: Why the two measurements cannot be compared; empty when they can.
+ incomparable: tuple[str, ...] = ()
+ # Ceiling: ``None`` on the history basis, whose stored ingests keep
+ # repo-wide figures only, no per-file rows per commit. A base report fills it.
+ outside_change: tuple[IndirectChange, ...] | None = None
+ #: Why files were left out of ``outside_change`` (``OutsideChangeScan.note``).
+ outside_change_note: str | None = None
+
+ def _pcts(self) -> tuple[float | None, float | None]:
+ return (self.base.pct if self.base else None, self.head.pct if self.head else None)
+
+ @property
+ def delta_pct(self) -> float | None:
+ """Head minus base, in points, unrounded; ``None`` without both figures."""
+ base, head = self._pcts()
+ return None if base is None or head is None else head - base
+
+ @property
+ def gate(self) -> GateStatus:
+ """``fail`` when the head is more than ``max_drop`` points below the base.
+
+ Small-change tolerance does not apply: a small change can still delete
+ the test that ran half the project.
+ """
+ if self.max_drop is None:
+ return "not_set"
+ base, head = self._pcts()
+ if self.incomparable or base is None or head is None:
+ return "no_data"
+ # A tolerance, so an exact-boundary drop (99.9 to 99.6 at 0.3) is not
+ # failed by float error.
+ return "fail" if base - head > self.max_drop + 1e-9 else "pass"
+
+ def to_dict(self) -> dict[str, Any]:
+ delta = self.delta_pct
+ return {
+ "basis": self.basis,
+ "base_commit": self.base_commit,
+ "head_commit": self.head_commit,
+ "base": self.base.to_dict() if self.base else None,
+ "head": self.head.to_dict() if self.head else None,
+ "delta_pct": None if delta is None else round(delta, 2),
+ "max_drop": self.max_drop,
+ "gate": self.gate,
+ "incomparable": list(self.incomparable),
+ "outside_change": (
+ None
+ if self.outside_change is None
+ else [c.to_dict() for c in self.outside_change]
+ ),
+ "outside_change_note": self.outside_change_note,
+ }
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/render.py b/packages/core/src/repowise/core/analysis/patch_coverage/render.py
index e17022e2d..78e3b07c3 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/render.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/render.py
@@ -19,6 +19,7 @@ from collections.abc import Sequence
from ...ci import github
from ...ci.markdown import ROW_LIMIT, cell, details, more_line, plural
from .compute import FilePatchCoverage, PatchCoverage, PathGateResult
+from .delta import IndirectCause, IndirectChange, ProjectDelta
from .hints import RANGE_LIMIT, TestHint, first_hint, hint_phrase
from .risk import FileRisk
@@ -248,6 +249,8 @@ def attention_rows(pc: PatchCoverage) -> list[FilePatchCoverage]:
def render_markdown(pc: PatchCoverage) -> str:
"""Markdown for a CI step summary or PR comment."""
out = [headline(pc)]
+ if project := project_line(pc):
+ out += ["", project]
if risky := risky_line(pc):
out += ["", risky]
out += ["", scope_line(pc)]
@@ -257,6 +260,7 @@ def render_markdown(pc: PatchCoverage) -> str:
out += _gap_table(pc)
out += _details(pc.with_status("not_in_report"), "not in the coverage report")
out += _details(pc.with_status("no_line_data"), "in a report without line data")
+ out += _outside_section(pc)
return "\n".join(out) + "\n"
@@ -306,6 +310,10 @@ def _gap_rows(pc: PatchCoverage, rows: list[FilePatchCoverage]) -> list[str]:
return lines
+#: Warning slots kept for coverage lost outside the change; unused ones go to ranges.
+OUTSIDE_RESERVE = 3
+
+
def github_annotations(pc: PatchCoverage) -> list[str]:
"""GitHub Actions workflow commands for a change's patch coverage.
@@ -313,8 +321,9 @@ def github_annotations(pc: PatchCoverage) -> list[str]:
not informational and a failing risky-file gate; one exempted by the
small-change tolerance, and an informational gate below its threshold, is
a notice, so neither is silent. Uncovered ranges are marked riskiest file
- first, then largest range, capped at what GitHub displays, with a notice
- counting the rest.
+ first, then largest range, sharing what GitHub displays with a warning per
+ file that lost coverage outside the change (:data:`OUTSIDE_RESERVE`),
+ with one notice counting the rest.
"""
ranges = sorted(
((f, a, b) for f in pc.with_status("measured") for a, b in f.uncovered_ranges),
@@ -326,7 +335,12 @@ def github_annotations(pc: PatchCoverage) -> list[str]:
*_path_gate_annotations(pc),
*_gate_annotations(pc.risky_gate, risky_line(pc, markdown=False)),
]
- return verdict + github.cap_annotations(warnings, noun="uncovered changed ranges")
+ if pc.project is not None:
+ verdict += _gate_annotations(pc.project.gate, project_line(pc, markdown=False))
+ outside = [_outside_annotation(c) for c in _lost_outside(pc)]
+ return verdict + github.cap_shared(
+ warnings, outside, reserve=OUTSIDE_RESERVE, noun="warnings"
+ )
def _gate_annotations(gate: str, text: str) -> list[str]:
@@ -371,6 +385,156 @@ def _hint_for(f: FilePatchCoverage, a: int, b: int) -> TestHint | None:
return next((h for h in f.hints or () if h.range == (a, b)), None)
+def project_line(pc: PatchCoverage, *, markdown: bool = True) -> str:
+ """Project coverage at the head against the base, or ``""`` when not computed.
+
+ ``Project coverage 81.2% · down 0.30 points from 81.5% at a1b2c3d · within
+ the 0.5-point max-drop gate``: one shape on every surface (the UI's
+ ``projectText`` mirrors it). Incomparable measurements say why instead.
+ """
+ p = pc.project
+ if p is None:
+ return ""
+ bold = "**" if markdown else ""
+ if reason := _not_compared(p):
+ return f"{bold}Project coverage not compared:{bold} {reason}."
+ assert p.base is not None and p.head is not None # _not_compared vouches
+ head, base = p.head.pct, p.base.pct
+ parts = [
+ f"{bold}Project coverage {fmt_pct(head)}{bold}",
+ _delta_phrase(head, base, p.base_commit),
+ _gate_phrase(p.gate, p.max_drop),
+ ]
+ return " · ".join(part for part in parts if part)
+
+
+def _not_compared(p: ProjectDelta) -> str:
+ """Why the two sides were not compared, or ``""`` when they were."""
+ if p.incomparable:
+ return "; ".join(p.incomparable)
+ if p.head is None or p.head.pct is None:
+ return "the head measured no coverable line"
+ if p.base is None or p.base.pct is None:
+ return "the base measured no coverable line"
+ return ""
+
+
+def _delta_phrase(head: float, base: float, base_commit: str | None) -> str:
+ """``down 0.30 points from 81.5% at a1b2c3d``; ``unchanged`` at zero."""
+ points = round(head - base, 2)
+ change = "unchanged" if points == 0 else (
+ f"{'up' if points > 0 else 'down'} {abs(points):.2f} points"
+ )
+ at = f" at {base_commit[:7]}" if base_commit else ""
+ return f"{change} from {fmt_pct(base)}{at}"
+
+
+def _gate_phrase(gate: str, max_drop: float | None) -> str:
+ if gate == "fail":
+ return f"falls more than the {max_drop:g}-point max-drop gate allows"
+ if gate == "pass":
+ return f"within the {max_drop:g}-point max-drop gate"
+ return ""
+
+
+def outside_change_rows(pc: PatchCoverage) -> tuple[IndirectChange, ...]:
+ """The files whose coverage changed outside the change, when a base report named them."""
+ rows = pc.project.outside_change if pc.project is not None else None
+ return rows or ()
+
+
+def _lost_outside(pc: PatchCoverage) -> list[IndirectChange]:
+ """Rows that lost coverage: newly uncovered lines (most first), or no longer measured."""
+ return [
+ c
+ for c in outside_change_rows(pc)
+ if c.newly_uncovered_ranges or c.status == "no_longer_measured"
+ ]
+
+
+def cause_words(causes: tuple[IndirectCause, ...] | None) -> str:
+ """``"deleted test tests/test_a.py (by name)"``; ``"unknown"`` when not assessed."""
+ if causes is None:
+ return "unknown"
+ if not causes:
+ return "nothing in the change names it"
+ shown = [
+ f"{_CAUSE_KIND[c.kind]} {c.path} ({_CAUSE_BASIS[c.basis]})" for c in causes[:_CAUSE_LIMIT]
+ ]
+ rest = len(causes) - len(shown)
+ return ", ".join(shown) + (f", +{rest} more" if rest else "")
+
+
+_CAUSE_KIND = {
+ "test_deleted": "deleted test",
+ "test_modified": "changed test",
+ "dependent_changed": "changed dependent",
+}
+_CAUSE_BASIS = {"per_test": "measured", "graph": "inferred", "name": "by name"}
+_CAUSE_LIMIT = 2
+
+
+def indirect_row(c: IndirectChange) -> tuple[str, str, str, str, str]:
+ """``(file, before, after, newly uncovered lines, cause)`` in plain text."""
+ if c.status == "no_longer_measured":
+ after, lost = "not measured", "the head report does not name it"
+ else:
+ after = fmt_pct(c.head_pct)
+ lost = format_ranges(c.newly_uncovered_ranges, RANGE_LIMIT) or "none"
+ if c.newly_covered_line_count:
+ lost += f" ({c.newly_covered_line_count} newly covered)"
+ cause = cause_words(c.causes) if c.newly_uncovered_ranges else ""
+ return c.file_path, fmt_pct(c.base_pct), after, lost, cause
+
+
+def _outside_section(pc: PatchCoverage) -> list[str]:
+ p = pc.project
+ if p is None or (not p.outside_change and not p.outside_change_note):
+ return []
+ out = ["", "### Coverage outside the change"]
+ if p.outside_change_note:
+ out += ["", f"Files left out: {p.outside_change_note}."]
+ rows = outside_change_rows(pc)
+ if not rows:
+ return out
+ out += [
+ "",
+ "| File | Before | After | Newly uncovered lines | Cause |",
+ "|---|---|---|---|---|",
+ ]
+ for c in rows[:ROW_LIMIT]:
+ path, *rest = indirect_row(c)
+ out.append(f"| `{cell(path)}` | " + " | ".join(cell(v) for v in rest) + " |")
+ if len(rows) > ROW_LIMIT:
+ out += ["", more_line(len(rows) - ROW_LIMIT, "files")]
+ return out
+
+
+def _outside_annotation(c: IndirectChange) -> str:
+ """A file-level warning at the first line that lost coverage, or on the file."""
+ if c.status == "no_longer_measured":
+ return github.annotation(
+ "warning",
+ f"Measured at the base ({fmt_pct(c.base_pct)}), not in the head's coverage report",
+ file=c.file_path,
+ title="Coverage lost outside the change",
+ )
+ n = c.newly_uncovered_line_count
+ message = (
+ f"{plural(n, 'line')} outside the change lost coverage "
+ f"({format_ranges(c.newly_uncovered_ranges, RANGE_LIMIT)})"
+ )
+ if c.causes:
+ message += f"; cause: {cause_words(c.causes)}"
+ return github.annotation(
+ "warning",
+ message,
+ file=c.file_path,
+ line=c.newly_uncovered_ranges[0][0],
+ title="Coverage lost outside the change",
+ )
+
+
def format_ranges(ranges: Sequence[tuple[int, int]], limit: int | None = None) -> str:
"""``((1, 3), (7, 7))`` -> ``"1-3, 7"``, with ``+N more`` past *limit*."""
shown = ranges if limit is None else ranges[:limit]
diff --git a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py b/packages/core/src/repowise/core/analysis/patch_coverage/stored.py
index bce77261e..1b784f990 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/stored.py
@@ -7,13 +7,17 @@ REST API, editors) reads what ``coverage add`` or indexing stored. Both end in
from __future__ import annotations
+import json
from collections.abc import Iterable, Mapping
-from typing import TYPE_CHECKING
+from dataclasses import replace
+from typing import TYPE_CHECKING, Any
from sqlalchemy.ext.asyncio import AsyncSession
+from ..health.coverage.discovery import CoverageScope
from ..health.coverage.freshness import coverage_freshness, working_tree_freshness
from .compute import PatchCoverage, PatchScope, compute_patch_coverage
+from .delta import ProjectDelta, ProjectTotals, incomparable_reasons
from .risk import IndexFacts
if TYPE_CHECKING:
@@ -44,7 +48,8 @@ async def stored_patch_coverage(
For a change that ends in the working tree, pass *working_tree_mtime* (the
newest modification time of the changed files) instead of *head_commit*: no
commit names that code, so freshness is whether the last ingest came after
- it (``working_tree_freshness``).
+ it (``working_tree_freshness``). :func:`attach_history_delta` adds the
+ project delta.
"""
from repowise.core.persistence.crud import (
get_coverage_summary,
@@ -90,6 +95,63 @@ async def stored_patch_coverage(
)
+async def attach_history_delta(
+ session: AsyncSession, repository_id: str, pc: PatchCoverage, base_commit: str | None
+) -> PatchCoverage:
+ """*pc* with ``project``: the ingest at *base_commit* against the newest one.
+
+ Only for stored coverage current for the change (the newest ingest is then
+ the head's figure); history basis, never gated here. *pc* unchanged otherwise.
+ """
+ if not base_commit or pc.scope.freshness != "current":
+ return pc
+ return replace(pc, project=await history_delta(session, repository_id, base_commit))
+
+
+def ingest_totals(row: Any) -> ProjectTotals | None:
+ """A stored ingest's repo-wide figures; ``None`` for a row written before them."""
+ if row.covered_lines is None or row.total_lines is None:
+ return None
+ return ProjectTotals(row.covered_lines, row.total_lines)
+
+
+def ingest_scope(row: Any) -> CoverageScope | None:
+ """What a stored ingest measured; ``None`` for a row written before scopes were kept."""
+ try:
+ return CoverageScope.from_dict(json.loads(row.scope_json)) if row.scope_json else None
+ except ValueError:
+ return None
+
+
+async def history_delta(
+ session: AsyncSession,
+ repository_id: str,
+ base_commit: str,
+ *,
+ max_drop: float | None = None,
+) -> ProjectDelta | None:
+ """The ingest at *base_commit* against the newest ingest.
+
+ ``None`` when no ingest was measured at *base_commit*, or when it is the
+ head ingest itself (a working-tree change measured over its own base).
+ """
+ from repowise.core.persistence.crud import load_ingest_at_commit, load_newest_ingest
+
+ base = await load_ingest_at_commit(session, repository_id, base_commit)
+ head = await load_newest_ingest(session, repository_id)
+ if base is None or head is None or base.id == head.id:
+ return None
+ return ProjectDelta(
+ base=ingest_totals(base),
+ head=ingest_totals(head),
+ basis="history",
+ base_commit=base_commit,
+ head_commit=head.ingested_commit_sha,
+ max_drop=max_drop,
+ incomparable=incomparable_reasons(ingest_scope(base), ingest_scope(head)),
+ )
+
+
async def read_index_facts(
session: AsyncSession, repository_id: str, paths: Iterable[str]
) -> dict[str, IndexFacts]:
diff --git a/packages/core/src/repowise/core/analysis/test_reachability.py b/packages/core/src/repowise/core/analysis/test_reachability.py
index 2a1dac574..bddbc0109 100644
--- a/packages/core/src/repowise/core/analysis/test_reachability.py
+++ b/packages/core/src/repowise/core/analysis/test_reachability.py
@@ -197,6 +197,7 @@ __all__ = [
"ReachedBy",
"call_graph_from_db",
"call_graph_from_graph",
+ "direct_dependents",
"files_reached_by_tests",
"files_with_paired_tests",
"load_test_files",
@@ -591,6 +592,29 @@ async def _import_reaching(
return found
+async def direct_dependents(
+ session: AsyncSession, repo_id: str, files: list[str]
+) -> dict[str, set[str]]:
+ """Files with an import edge into each of *files*, or a call into a symbol it declares.
+
+ One hop, no tests excluded: the direct callers and importers a change to
+ them could have moved coverage through. A file with none is absent.
+ """
+ out: dict[str, set[str]] = {}
+ for dependent, dependency in await _edges_into(
+ session, repo_id, files, sorted(FILE_DEPENDENCY_EDGE_TYPES), frozenset()
+ ):
+ out.setdefault(dependency, set()).add(dependent)
+ declared = await _edges_from(session, repo_id, files, ["defines"])
+ owner = {symbol: path for path, symbol in declared}
+ for caller, callee in await _edges_into(
+ session, repo_id, sorted(owner), sorted(EXECUTION_EDGE_TYPES), UNRELIABLE_CALL_ORIGINS
+ ):
+ if (source := file_of_symbol(caller)) != owner[callee]:
+ out.setdefault(owner[callee], set()).add(source)
+ return out
+
+
def _in_clause(prefix: str, values: list[str], params: dict[str, Any]) -> str:
"""Bind *values* as ``:prefix0, :prefix1, ...`` and return the clause body."""
params.update({f"{prefix}{i}": v for i, v in enumerate(values)})
diff --git a/packages/core/src/repowise/core/ci/github.py b/packages/core/src/repowise/core/ci/github.py
index a6e228d41..bd9d14176 100644
--- a/packages/core/src/repowise/core/ci/github.py
+++ b/packages/core/src/repowise/core/ci/github.py
@@ -66,3 +66,27 @@ def cap_annotations(
if len(lines) > limit:
kept.append(notice(f"{len(lines) - limit} more {noun}, listed in the job summary"))
return kept
+
+
+def cap_shared(
+ primary: Sequence[str],
+ secondary: Sequence[str],
+ *,
+ reserve: int,
+ noun: str,
+ limit: int = ANNOTATION_LIMIT,
+) -> list[str]:
+ """Two kinds of annotation sharing one *limit*, plus one notice counting the rest.
+
+ *secondary* keeps up to *reserve* slots, more when *primary* leaves them
+ unused; *primary* takes what remains.
+ """
+ n_secondary = min(len(secondary), max(reserve, limit - len(primary)))
+ n_primary = min(len(primary), limit - n_secondary)
+ kept = [*primary[:n_primary], *secondary[:n_secondary]]
+ rest = len(primary) + len(secondary) - len(kept)
+ if rest:
+ kept.append(
+ notice(f"{rest} more {noun}; the first {limit} are listed in the job summary")
+ )
+ return kept
diff --git a/packages/core/src/repowise/core/git_refs.py b/packages/core/src/repowise/core/git_refs.py
index 5f7d5c117..bab1a04b9 100644
--- a/packages/core/src/repowise/core/git_refs.py
+++ b/packages/core/src/repowise/core/git_refs.py
@@ -18,6 +18,7 @@ __all__ = [
"BranchRef",
"ahead_behind",
"ahead_behind_many",
+ "change_base",
"changed_files",
"commit_file_sets",
"current_branch",
@@ -30,6 +31,7 @@ __all__ = [
"resolve",
"toplevel",
"tracked_paths",
+ "tracked_paths_at",
]
#: Subprocess failures that mean "no answer", not "bug": a wedged or missing
@@ -75,6 +77,29 @@ def tracked_paths(repo_path: str) -> frozenset[str]:
return frozenset(p for p in _read(repo_path, ["ls-files", "-z"]).split("\0") if p)
+def tracked_paths_at(repo_path: str, rev: str) -> frozenset[str]:
+ """Every path git tracked at *rev*, repo-relative POSIX, or empty when git cannot answer."""
+ listing = _read(repo_path, ["ls-tree", "-r", "-z", "--name-only", f"{rev}^{{tree}}"])
+ return frozenset(p for p in listing.split("\0") if p)
+
+
+def change_base(repo_path: str, revspec: str) -> str:
+ """The commit a change starts from, ``""`` when git cannot name it.
+
+ The merge-base for ``base...head``, ``base`` for ``base..head``, and a
+ single commit's first parent: the side the change's diff is taken from.
+ Unlike change risk's ``history_ref`` / ``range_anchor``, ``..`` starts at *base*
+ itself here, as the diff does, not at the merge-base.
+ """
+ parts = split_revspec(revspec)
+ if parts is None:
+ return resolve(repo_path, f"{revspec}^1")
+ base, sep, head = parts
+ if sep == "...":
+ return _read(repo_path, ["merge-base", base, head])
+ return resolve(repo_path, base)
+
+
def is_shallow(repo_path: str) -> bool:
"""Whether the clone is shallow; ``False`` when git cannot answer."""
return _read(repo_path, ["rev-parse", "--is-shallow-repository"]) == "true"
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
index c3ab83e48..7c316d3b0 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -27,6 +27,8 @@ from .coverage import (
load_coverage_history,
load_coverage_map,
load_file_coverage,
+ load_ingest_at_commit,
+ load_newest_ingest,
save_coverage_files,
)
from .coverage_map import (
@@ -175,6 +177,8 @@ __all__ = [
"load_coverage_history",
"load_coverage_map",
"load_file_coverage",
+ "load_ingest_at_commit",
+ "load_newest_ingest",
"opportunity_details",
"performance_facet_counts",
"performance_file_rollups",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py b/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py
index 3cb2fca66..14c4cf614 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py
@@ -19,6 +19,8 @@ if TYPE_CHECKING:
from .._shared import _BATCH_SIZE
#: Ingest rows kept per repo for the coverage trend; older ones are pruned on write.
+#: One row per measured commit, so identical figures can repeat; the trend read
+#: (``load_coverage_history``) collapses consecutive repeats.
COVERAGE_HISTORY_RETENTION: int = 50
@@ -36,8 +38,9 @@ async def save_coverage_files(
Mirrors the delete-then-insert pattern used by the health writers for the
per-file rows; the ingest row is appended, with the repo-wide figures of
- *files*, unless the newest one already says exactly that (then it is
- restamped), and ingests past ``COVERAGE_HISTORY_RETENTION`` are pruned.
+ *files*, unless the newest one already says exactly that at the same
+ commit (then it is restamped, see ``_record_ingest``), and ingests past
+ ``COVERAGE_HISTORY_RETENTION`` are pruned.
*files* is a list of ``FileCoverage`` dataclasses (or dicts with the
same shape). *provenance*, from a writer that resolved the report
itself, supplies the formats, the path counts and ``mapping_partial``
@@ -113,10 +116,11 @@ def _ingest_figures(
"branch_coverage_pct": branch_pct,
"covered_lines": covered,
"total_lines": total,
+ "scope_json": json.dumps(p.scope.to_dict()) if p.scope is not None else None,
}
-async def _newest_ingest(session: AsyncSession, repository_id: str) -> CoverageIngest | None:
+async def load_newest_ingest(session: AsyncSession, repository_id: str) -> CoverageIngest | None:
return (
await session.execute(
select(CoverageIngest)
@@ -135,15 +139,22 @@ async def _record_ingest(
at: datetime,
commit: str | None,
) -> None:
- """Append the ingest, or restamp the newest when it measured exactly this.
+ """Append the ingest, or restamp the newest when it measured exactly this, there.
- The same report ingested again (an update that re-ingests, a full
- re-index) is one measurement, not a new trend point.
+ The same report ingested again at the same commit (an update that
+ re-ingests, a full re-index) is one measurement, not a new trend point.
+ The same figures at another commit, or at an unknown one, are a new row:
+ restamping would move the base's measurement to the head (a project delta
+ would lose its base), or leave a commit on a row whose files name none.
"""
- newest = await _newest_ingest(session, repository_id)
- if newest is not None and all(getattr(newest, k) == v for k, v in measured.items()):
+ newest = await load_newest_ingest(session, repository_id)
+ if (
+ newest is not None
+ and commit is not None
+ and commit == newest.ingested_commit_sha
+ and all(getattr(newest, k) == v for k, v in measured.items())
+ ):
newest.ingested_at = at
- newest.ingested_commit_sha = commit
return
session.add(
CoverageIngest(
@@ -156,6 +167,23 @@ async def _record_ingest(
)
+async def load_ingest_at_commit(
+ session: AsyncSession, repository_id: str, commit_sha: str
+) -> CoverageIngest | None:
+ """The newest ingest measured at *commit_sha*, ``None`` when none was."""
+ return (
+ await session.execute(
+ select(CoverageIngest)
+ .where(
+ CoverageIngest.repository_id == repository_id,
+ CoverageIngest.ingested_commit_sha == commit_sha,
+ )
+ .order_by(CoverageIngest.ingested_at.desc(), CoverageIngest.id.desc())
+ .limit(1)
+ )
+ ).scalar_one_or_none()
+
+
async def _prune_history(session: AsyncSession, repository_id: str) -> None:
"""Drop ingests past ``COVERAGE_HISTORY_RETENTION``, oldest first."""
history = await session.execute(
@@ -490,6 +518,7 @@ async def load_coverage_history(
Rows written before the figures existed are skipped, and so are partial
ingests: their figure is a subset's coverage, not the repository's.
+ Consecutive rows with the same figures collapse into the newest of them.
"""
result = await session.execute(
select(
@@ -506,15 +535,22 @@ async def load_coverage_history(
.order_by(CoverageIngest.ingested_at.desc(), CoverageIngest.id.desc())
.limit(limit)
)
- return [
- {
+ points: list[dict[str, Any]] = []
+ for row in reversed(result.all()):
+ point = {
"ingested_at": row.ingested_at.isoformat(),
"ingested_commit_sha": row.ingested_commit_sha,
"line_coverage_pct": row.line_coverage_pct,
"branch_coverage_pct": row.branch_coverage_pct,
}
- for row in reversed(result.all())
- ]
+ figures = (row.line_coverage_pct, row.branch_coverage_pct)
+ if points and (points[-1]["line_coverage_pct"], points[-1]["branch_coverage_pct"]) == (
+ figures
+ ):
+ points[-1] = point
+ else:
+ points.append(point)
+ return points
async def get_coverage_summary(
@@ -545,7 +581,7 @@ async def get_coverage_summary(
)
if not rows:
return empty_coverage_summary()
- ingest = await _newest_ingest(session, repository_id)
+ ingest = await load_newest_ingest(session, repository_id)
covered, total, line_pct, branch_pct = _aggregate(
(_covered_count(r), r.total_coverable_lines, r.branch_coverage_pct) for r in rows
)
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 87dec9790..19f67512d 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -2264,6 +2264,9 @@ class CoverageIngest(Base):
branch_coverage_pct: Mapped[float | None] = mapped_column(Float, nullable=True)
covered_lines: Mapped[int | None] = mapped_column(Integer, nullable=True)
total_lines: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ # ``CoverageScope.to_dict()``: the reports and ignore globs measured, so a
+ # later measurement can tell whether it is comparable. NULL: not recorded.
+ scope_json: Mapped[str | None] = mapped_column(Text, nullable=True)
__table_args__ = (
Index("ix_coverage_ingests_repo_ingested", "repository_id", "ingested_at"),
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 5305e454a..37c76a35b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
@@ -1209,7 +1209,9 @@ async def _patch_coverage_block(
apply as they do in the CLI gate; path gates read ``no_data`` on stale
coverage or invalid config, which ``scope.config_errors`` names. Each row
carries its file's risk, from the index and the checkout's git history, and
- ``hints``: the test file to extend per uncovered range.
+ ``hints``: the test file to extend per uncovered range. ``project``
+ compares the ingest measured at the change's base commit with the current
+ one, when both exist (repo-wide totals only, never gated here).
With no revspec, *changed* is what a push would bring (the caller diffs
from the merge-base with the push base, *label* names it). For uncommitted
@@ -1223,6 +1225,7 @@ async def _patch_coverage_block(
from repowise.core.analysis.patch_coverage import (
assess_risks,
attach_hints,
+ attach_history_delta,
attach_risk,
attention_rows,
read_git_fix_history,
@@ -1240,6 +1243,9 @@ async def _patch_coverage_block(
mtime = await asyncio.to_thread(newest_mtime, ctx.path, changed)
else:
head_commit = git_refs.resolve(str(ctx.path), revspec_head(revspec)) or None
+ base_commit = await asyncio.to_thread(
+ _change_base, str(ctx.path), revspec, label, result.working_tree
+ )
index: dict = {}
try:
async with get_session(session_factory) as session:
@@ -1255,6 +1261,7 @@ async def _patch_coverage_block(
)
# An unreadable index row leaves risk to git alone and hints null.
if patch is not None:
+ patch = await attach_history_delta(session, repo_id, patch, base_commit)
with contextlib.suppress(SQLAlchemyError):
index = await read_index_facts(
session, repo_id, [f.file_path for f in patch.files]
@@ -1291,6 +1298,25 @@ async def _patch_coverage_block(
return block
+def _change_base(
+ repo_path: str, revspec: str | None, label: str | None, working_tree: bool
+) -> str | None:
+ """The commit the measured change starts from, ``None`` when git cannot name it.
+
+ A working-tree change starts at the merge-base with its push base when the
+ label names one (``<base>...working tree``), else at ``HEAD``.
+ """
+ from repowise.core import git_refs
+ from repowise.core.analysis.change_risk.features import split_revspec
+
+ if not working_tree:
+ return git_refs.change_base(repo_path, revspec or "HEAD") or None
+ parts = split_revspec(label or "")
+ if parts is None:
+ return git_refs.resolve(repo_path, "HEAD") or None
+ return git_refs.change_base(repo_path, f"{parts[0]}...HEAD") or None
+
+
async def _impacted_tests_block(
ctx: Any,
changed: dict[str, set[int]],
diff --git a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py b/packages/server/src/repowise/server/routers/code_health/coverage_routes.py
index 6f73c3e71..f2025a1ed 100644
--- a/packages/server/src/repowise/server/routers/code_health/coverage_routes.py
+++ b/packages/server/src/repowise/server/routers/code_health/coverage_routes.py
@@ -346,8 +346,10 @@ async def health_tests_reaching(
}
-def _read_change(local_path: str, base: str, head: str) -> tuple[dict[str, set[int]], str, str]:
- """``(changed lines, label, head sha)`` for ``base...head``; git only, run off the loop."""
+def _read_change(
+ local_path: str, base: str, head: str
+) -> tuple[dict[str, set[int]], str, str, str]:
+ """``(changed lines, label, head sha, merge-base sha)`` for ``base...head``; git only."""
import subprocess
from repowise.core import git_refs
@@ -361,7 +363,12 @@ def _read_change(local_path: str, base: str, head: str) -> tuple[dict[str, set[i
raise HTTPException(status_code=400, detail=str(exc)) from exc
except subprocess.TimeoutExpired as exc:
raise HTTPException(status_code=504, detail="git timed out reading the change") from exc
- return changed, label, git_refs.resolve(local_path, head)
+ return (
+ changed,
+ label,
+ git_refs.resolve(local_path, head),
+ git_refs.change_base(local_path, label),
+ )
@router.get(
@@ -382,7 +389,8 @@ async def health_coverage_patch(
(with ``coverage.min_coverable_lines``) on current coverage and valid
config; the whole-change threshold stays with the CLI gate. Each file row
carries its risk, from the index and the checkout's git history, and the
- test to extend per uncovered range.
+ test to extend per uncovered range. ``project`` compares the ingest
+ measured at the merge-base with the current one, when both exist.
"""
from sqlalchemy.exc import SQLAlchemyError
@@ -390,6 +398,7 @@ async def health_coverage_patch(
from repowise.core.analysis.patch_coverage import (
assess_risks,
attach_hints,
+ attach_history_delta,
attach_risk,
read_git_fix_history,
read_index_facts,
@@ -397,7 +406,9 @@ async def health_coverage_patch(
stored_patch_coverage,
)
- changed, label, head_sha = await asyncio.to_thread(_read_change, repo.local_path, base, head)
+ changed, label, head_sha, base_sha = await asyncio.to_thread(
+ _read_change, repo.local_path, base, head
+ )
patch = await stored_patch_coverage(
session,
repo.id,
@@ -408,6 +419,7 @@ async def health_coverage_patch(
)
if patch is None:
return None
+ patch = await attach_history_delta(session, repo.id, patch, base_sha or None)
paths = [f.file_path for f in patch.files]
try:
index = await read_index_facts(session, repo.id, paths)
diff --git a/packages/server/src/repowise/server/schemas/patch_coverage.py b/packages/server/src/repowise/server/schemas/patch_coverage.py
index a2eb79347..58cfde104 100644
--- a/packages/server/src/repowise/server/schemas/patch_coverage.py
+++ b/packages/server/src/repowise/server/schemas/patch_coverage.py
@@ -10,6 +10,12 @@ from pydantic import BaseModel, ConfigDict
from repowise.core.analysis.health.coverage.freshness import FreshnessStatus
from repowise.core.analysis.patch_coverage.compute import FileStatus, GateStatus
+from repowise.core.analysis.patch_coverage.delta import (
+ CauseBasis,
+ CauseKind,
+ DeltaBasis,
+ IndirectStatus,
+)
from repowise.core.analysis.patch_coverage.hints import HintBasis
from repowise.core.analysis.patch_coverage.risk import RiskBasis
@@ -128,6 +134,63 @@ class PatchCoverageRisky(_Strict):
gate: GateStatus
+class PatchCoverageProjectTotals(_Strict):
+ covered_line_count: int
+ coverable_line_count: int
+ #: 0-100, floored to two decimals; null when nothing was coverable.
+ coverage_pct: float | None
+
+
+class PatchCoverageOutsideChangeCause(_Strict):
+ """A changed file that explains coverage lost outside the change."""
+
+ kind: CauseKind
+ path: str
+ #: ``per_test`` measured, ``graph`` inferred from the index's call and
+ #: import edges, ``name`` a test named for the file.
+ basis: CauseBasis
+
+
+class PatchCoverageOutsideChange(_Strict):
+ """A file whose coverage changed on lines the change did not touch."""
+
+ file_path: str
+ #: ``no_longer_measured``: the base report named it, the head's does not.
+ status: IndirectStatus
+ #: Head-side inclusive ``[start, end]`` runs covered at the base, not at the head.
+ newly_uncovered_ranges: list[list[int]]
+ newly_uncovered_line_count: int
+ newly_covered_line_count: int
+ base_pct: float | None
+ head_pct: float | None
+ #: Null when not assessed; empty when nothing in the change explains it.
+ causes: list[PatchCoverageOutsideChangeCause] | None
+
+
+class PatchCoverageProject(_Strict):
+ """Project coverage at the change's base against its head."""
+
+ #: ``history``: stored ingests (totals only); ``base_report``: a report
+ #: measured at the base commit.
+ basis: DeltaBasis
+ base_commit: str | None
+ head_commit: str | None
+ base: PatchCoverageProjectTotals | None
+ head: PatchCoverageProjectTotals | None
+ #: Head minus base, in percentage points, rounded to two decimals.
+ delta_pct: float | None
+ max_drop: float | None
+ #: ``no_data`` when the two measurements cannot be compared.
+ gate: GateStatus
+ #: Why the base and head measured different things; empty when comparable.
+ incomparable: list[str]
+ #: Null on the history basis, which keeps no per-file rows per commit, and
+ #: when most files of the base report did not line up with the base commit.
+ outside_change: list[PatchCoverageOutsideChange] | None
+ #: Why files were left out of ``outside_change``; null when none were.
+ outside_change_note: str | None
+
+
class PatchCoverageResponse(_Strict):
patch_coverage_pct: float | None
covered_line_count: int
@@ -146,3 +209,5 @@ class PatchCoverageResponse(_Strict):
path_gates: list[PatchCoveragePathGate]
#: Null when no file's risk was assessed.
risky: PatchCoverageRisky | None
+ #: Null when no ingest was measured at the change's base.
+ project: PatchCoverageProject | None
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index fc2d22239..795994337 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -2324,6 +2324,25 @@ export interface PatchCoverageFileRisk {
reasons: string[];
}
+/** A file whose coverage changed on lines the change did not touch. */
+export interface PatchCoverageOutsideChange {
+ file_path: string;
+ status: "changed" | "no_longer_measured";
+ newly_uncovered_ranges: number[][];
+ newly_uncovered_line_count: number;
+ newly_covered_line_count: number;
+ base_pct: number | null;
+ head_pct: number | null;
+ causes: PatchCoverageOutsideChangeCause[] | null;
+}
+
+/** A changed file that explains coverage lost outside the change. */
+export interface PatchCoverageOutsideChangeCause {
+ kind: "test_deleted" | "test_modified" | "dependent_changed";
+ path: string;
+ basis: "per_test" | "graph" | "name";
+}
+
/** One path-scoped gate from ``coverage.gates``, judged on the change. */
export interface PatchCoveragePathGate {
name: string;
@@ -2338,6 +2357,27 @@ export interface PatchCoveragePathGate {
gate: "pass" | "fail" | "no_data" | "not_set" | "too_small";
}
+/** Project coverage at the change's base against its head. */
+export interface PatchCoverageProject {
+ basis: "base_report" | "history";
+ base_commit: string | null;
+ head_commit: string | null;
+ base: PatchCoverageProjectTotals | null;
+ head: PatchCoverageProjectTotals | null;
+ delta_pct: number | null;
+ max_drop: number | null;
+ gate: "pass" | "fail" | "no_data" | "not_set" | "too_small";
+ incomparable: string[];
+ outside_change: PatchCoverageOutsideChange[] | null;
+ outside_change_note: string | null;
+}
+
+export interface PatchCoverageProjectTotals {
+ covered_line_count: number;
+ coverable_line_count: number;
+ coverage_pct: number | null;
+}
+
export interface PatchCoverageResponse {
patch_coverage_pct: number | null;
covered_line_count: number;
@@ -2350,6 +2390,7 @@ export interface PatchCoverageResponse {
scope: PatchCoverageScope;
path_gates: PatchCoveragePathGate[];
risky: PatchCoverageRisky | null;
+ project: PatchCoverageProject | null;
}
/** Patch coverage over the measured files history marks as risky. */
diff --git a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx b/packages/ui/__tests__/health/patch-coverage-summary.test.tsx
index 59bbe1851..3b91647ec 100644
--- a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx
+++ b/packages/ui/__tests__/health/patch-coverage-summary.test.tsx
@@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import type {
PatchCoveragePathGate,
+ PatchCoverageProject,
PatchCoverageResponse,
} from "@repowise-dev/types/generated/http";
import {
@@ -9,6 +10,7 @@ import {
floorPct,
formatLineRanges,
hintReason,
+ projectText,
riskWords,
} from "../../src/health/patch-coverage-summary.js";
@@ -52,6 +54,28 @@ function coverage(fileCount: number): PatchCoverageResponse {
},
path_gates: [],
risky: null,
+ project: null,
+ };
+}
+
+function project(base: number, head: number, delta: number): PatchCoverageProject {
+ const totals = (pct: number) => ({
+ covered_line_count: Math.round(pct * 10),
+ coverable_line_count: 1000,
+ coverage_pct: pct,
+ });
+ return {
+ basis: "history",
+ base_commit: "a1b2c3d".padEnd(40, "0"),
+ head_commit: "h".repeat(40),
+ base: totals(base),
+ head: totals(head),
+ delta_pct: delta,
+ max_drop: null,
+ gate: "not_set",
+ incomparable: [],
+ outside_change: null,
+ outside_change_note: null,
};
}
@@ -124,6 +148,24 @@ describe("patch coverage formatting", () => {
expect(floorPct(100)).toBe("100.0");
});
+ const DOWN = "Project coverage 81.2% · down 0.30 points from 81.5% at a1b2c3d";
+ it.each([
+ [project(81.5, 81.2, -0.3), DOWN],
+ [project(80, 80.25, 0.25), "Project coverage 80.2% · up 0.25 points from 80.0% at a1b2c3d"],
+ [project(80, 80, 0), "Project coverage 80.0% · unchanged from 80.0% at a1b2c3d"],
+ [
+ { ...project(81.5, 81.2, -0.3), max_drop: 0.5, gate: "pass" as const },
+ `${DOWN} · within the 0.5-point max-drop gate`,
+ ],
+ [
+ { ...project(81.5, 81.2, -0.3), max_drop: 0.1, gate: "fail" as const },
+ `${DOWN} · falls more than the 0.1-point max-drop gate allows`,
+ ],
+ [{ ...project(80, 80, 0), base: null, delta_pct: null }, null],
+ ])("words the project delta as the core's project line (%#)", (given, expected) => {
+ expect(projectText(given)).toBe(expected);
+ });
+
it("prints single lines bare and runs as a span", () => {
expect(
formatLineRanges([
@@ -257,6 +299,31 @@ describe("PatchCoverageSummary", () => {
).toBeTruthy();
});
+ it("compares project coverage with the base under the headline", () => {
+ render(
+ <PatchCoverageSummary coverage={{ ...coverage(1), project: project(81.5, 81.2, -0.3) }} />,
+ );
+ expect(
+ screen.getByText("Project coverage 81.2% · down 0.30 points from 81.5% at a1b2c3d"),
+ ).toBeTruthy();
+ });
+
+ it("says in muted text why project coverage was not compared", () => {
+ const incomparable = {
+ ...project(81.5, 81.2, -0.3),
+ incomparable: ["the base read 1 lcov report, the head read 2 lcov reports"],
+ };
+ render(<PatchCoverageSummary coverage={{ ...coverage(1), project: incomparable }} />);
+ const line = screen.getByText(/Project coverage not compared: the base read 1 lcov/);
+ expect(line.className).toContain("text-tertiary");
+ expect(screen.queryByText(/down 0.30 points/)).toBeNull();
+ });
+
+ it("shows no project line without a base measurement", () => {
+ render(<PatchCoverageSummary coverage={coverage(1)} />);
+ expect(screen.queryByText(/Project coverage/)).toBeNull();
+ });
+
it("shows no gate list without path-scoped gates", () => {
render(<PatchCoverageSummary coverage={coverage(1)} />);
expect(screen.queryByRole("list", { name: "Path-scoped gates" })).toBeNull();
@@ -265,7 +332,7 @@ describe("PatchCoverageSummary", () => {
it("renders a response from a server older than path-scoped gates and risk", () => {
const base = coverage(1);
- const { path_gates: _gates, risky: _risky, ...older } = base;
+ const { path_gates: _gates, risky: _risky, project: _project, ...older } = base;
const { config_errors: _errors, ...olderScope } = base.scope;
render(
<PatchCoverageSummary
diff --git a/packages/ui/src/health/patch-coverage-summary.tsx b/packages/ui/src/health/patch-coverage-summary.tsx
index a3bbbc949..b9e7ccbd8 100644
--- a/packages/ui/src/health/patch-coverage-summary.tsx
+++ b/packages/ui/src/health/patch-coverage-summary.tsx
@@ -14,6 +14,10 @@
* first, in the order `repowise coverage check` uses. A line says where the
* risk came from when not every file had index data. With an index, a file
* with uncovered lines also names the test file to extend.
+ *
+ * When coverage was also stored at the change's base commit, one line under
+ * the headline compares project coverage there with the head, or says in muted
+ * text why the two measurements cannot be compared.
*/
import type { ReactNode } from "react";
@@ -21,6 +25,7 @@ import type {
PatchCoverageFile,
PatchCoverageFileRisk,
PatchCoveragePathGate,
+ PatchCoverageProject,
PatchCoverageResponse,
PatchCoverageTestHint,
} from "@repowise-dev/types/generated/http";
@@ -167,6 +172,8 @@ export function PatchCoverageSummary({
return (
<div className="flex flex-col gap-1.5">
<Headline coverage={coverage} />
+ {/* Guarded: a server older than the project delta sends no field. */}
+ <ProjectLine project={coverage.project ?? null} />
<RiskyLine risky={coverage.risky} />
<ScopeNotes coverage={coverage} />
{/* Guarded: a server older than path-scoped gates sends neither field. */}
@@ -223,6 +230,55 @@ function Headline({ coverage }: { coverage: PatchCoverageResponse }) {
);
}
+/**
+ * Project coverage at the head against the base, worded as the core's
+ * `project_line` (patch_coverage/render.py) words it: `Project coverage 81.2% ·
+ * down 0.30 points from 81.5% at a1b2c3d`, then the max-drop verdict when one
+ * was judged. `null` without both figures.
+ */
+export function projectText(project: PatchCoverageProject): string | null {
+ const head = project.head?.coverage_pct;
+ const base = project.base?.coverage_pct;
+ if (head == null || base == null || project.delta_pct == null) return null;
+ const parts = [
+ `Project coverage ${floorPct(head)}%`,
+ deltaPhrase(project.delta_pct, base, project.base_commit),
+ gatePhrase(project),
+ ];
+ return parts.filter(Boolean).join(" · ");
+}
+
+/** `down 0.30 points from 81.5% at a1b2c3d`; `unchanged` at zero. */
+function deltaPhrase(delta: number, base: number, baseCommit: string | null): string {
+ const change =
+ delta === 0 ? "unchanged" : `${delta > 0 ? "up" : "down"} ${Math.abs(delta).toFixed(2)} points`;
+ const at = baseCommit ? ` at ${baseCommit.slice(0, 7)}` : "";
+ return `${change} from ${floorPct(base)}%${at}`;
+}
+
+/** The max-drop verdict, when one was judged; `""` otherwise. */
+function gatePhrase(project: PatchCoverageProject): string {
+ if (project.gate === "fail") {
+ return `falls more than the ${project.max_drop}-point max-drop gate allows`;
+ }
+ if (project.gate === "pass") return `within the ${project.max_drop}-point max-drop gate`;
+ return "";
+}
+
+function ProjectLine({ project }: { project: PatchCoverageProject | null }) {
+ if (project == null) return null;
+ if (project.incomparable.length > 0) {
+ return (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Project coverage not compared: {project.incomparable.join("; ")}
+ </p>
+ );
+ }
+ const text = projectText(project);
+ if (text == null) return null;
+ return <p className="text-xs tabular-nums text-[var(--color-text-secondary)]">{text}</p>;
+}
+
/** Only when a risky file has changed executable lines: nothing else to report. */
function RiskyLine({ risky }: { risky: PatchCoverageResponse["risky"] | undefined }) {
if (risky == null || risky.patch_coverage_pct == null) return null;
diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsx
index 410e0f4e7..0742df19d 100644
--- a/packages/vscode/webview/src/views/risk/App.test.tsx
+++ b/packages/vscode/webview/src/views/risk/App.test.tsx
@@ -129,6 +129,7 @@ const PATCH_COVERAGE: NonNullable<RiskRangeReport["patchCoverage"]> = {
threshold: null,
gate: "not_set",
},
+ project: null,
scope: {
label: "coverage.xml",
source_formats: ["cobertura"],
diff --git a/tests/unit/analysis/test_changed_lines.py b/tests/unit/analysis/test_changed_lines.py
index 7fef179f3..303e65601 100644
--- a/tests/unit/analysis/test_changed_lines.py
+++ b/tests/unit/analysis/test_changed_lines.py
@@ -132,6 +132,35 @@ def test_changed_lines_three_dot_diffs_from_merge_base(git_repo) -> None:
assert changed_lines(str(git_repo), "main..feat")[0] == {"mod.py": {2, 3}}
+def test_change_diff_names_renames_and_deletions_and_its_base(git_repo) -> None:
+ from repowise.core import git_refs
+ from repowise.core.analysis.changed_lines import change_diff
+
+ body = "".join(f"line{i} = {i}\n" for i in range(20))
+ (git_repo / "old.py").write_text(body, encoding="utf-8")
+ (git_repo / "gone.py").write_text("x = 1\n", encoding="utf-8")
+ _git(git_repo, "add", "-A")
+ _git(git_repo, "commit", "-qm", "more")
+ _git(git_repo, "branch", "-M", "main")
+ _git(git_repo, "switch", "-qc", "feat")
+ _git(git_repo, "mv", "old.py", "new.py")
+ (git_repo / "new.py").write_text("top = 0\n" + body, encoding="utf-8")
+ _git(git_repo, "rm", "-q", "gone.py")
+ _git(git_repo, "commit", "-qam", "move")
+
+ base = git_refs.change_base(str(git_repo), "main...feat")
+ diffs, renames, deleted = change_diff(str(git_repo), base, "feat")
+
+ # A range with either separator, and a commit (its first parent), start at main.
+ starts = {git_refs.change_base(str(git_repo), rev) for rev in ("feat", "main..feat")}
+ tracked = git_refs.tracked_paths_at(str(git_repo), base)
+
+ assert starts == {base} == {git_refs.resolve(str(git_repo), "main")}
+ assert (renames, deleted) == ({"old.py": "new.py"}, {"gone.py"})
+ assert diffs["new.py"].new_lines == {1}
+ assert {"old.py", "gone.py", "mod.py"} <= tracked and "new.py" not in tracked
+
+
def test_working_tree_from_a_base_is_everything_a_push_brings(git_repo) -> None:
# The branch committed line 2 and left line 4 uncommitted; base moved line 3.
_git(git_repo, "branch", "-M", "main")
diff --git a/tests/unit/analysis/test_patch_coverage.py b/tests/unit/analysis/test_patch_coverage.py
index 8a86c7d80..5819363e4 100644
--- a/tests/unit/analysis/test_patch_coverage.py
+++ b/tests/unit/analysis/test_patch_coverage.py
@@ -240,7 +240,7 @@ def test_annotations_mark_largest_ranges_first_and_count_the_rest() -> None:
assert len(warnings) == 10
assert "line=50,endLine=54" in warnings[0]
assert lines[0].startswith("::error::Patch coverage")
- assert lines[-1].startswith("::notice::3 more uncovered changed ranges")
+ assert lines[-1] == "::notice::3 more warnings; the first 10 are listed in the job summary"
def test_markdown_lists_files_without_line_data() -> None:
diff --git a/tests/unit/analysis/test_patch_coverage_delta.py b/tests/unit/analysis/test_patch_coverage_delta.py
new file mode 100644
index 000000000..a260dfe60
--- /dev/null
+++ b/tests/unit/analysis/test_patch_coverage_delta.py
@@ -0,0 +1,401 @@
+"""Project coverage delta and coverage outside the change: the pure half."""
+
+from __future__ import annotations
+
+from dataclasses import replace
+
+import pytest
+
+from repowise.core.analysis.changed_lines import parse_unified_diff
+from repowise.core.analysis.health.coverage import CoverageScope
+from repowise.core.analysis.health.coverage import file_coverage as _fc
+from repowise.core.analysis.patch_coverage.causes import apply_causes, name_causes
+from repowise.core.analysis.patch_coverage.compute import compute_patch_coverage
+from repowise.core.analysis.patch_coverage.delta import (
+ IndirectCause,
+ IndirectChange,
+ ProjectDelta,
+ ProjectTotals,
+ incomparable_reasons,
+ indirect_changes,
+ project_totals,
+)
+from repowise.core.analysis.patch_coverage.render import (
+ github_annotations,
+ project_line,
+ render_markdown,
+)
+
+# -- totals and the gate -----------------------------------------------------
+
+
+def test_totals_sum_every_file_after_ignore() -> None:
+ coverage = {
+ "src/a.py": _fc("src/a.py", [1, 2], [1, 2, 3, 4]),
+ "src/b.py": _fc("src/b.py", [1], [1]),
+ "gen/c.py": _fc("gen/c.py", [], [1, 2, 3]),
+ }
+ totals = project_totals(coverage, ignore=["gen/"])
+
+ assert (totals.covered_line_count, totals.coverable_line_count) == (3, 5)
+ assert totals.pct == 60.0
+
+
+def test_totals_take_a_report_summary_over_the_line_sets() -> None:
+ # lcov LF/LH summaries are what the stored coverage summary counts too.
+ fc = _fc("a.py", [1], [1, 2], total=10, hit=7)
+ assert project_totals({"a.py": fc}) == ProjectTotals(7, 10)
+
+
+def _delta(base: tuple[int, int], head: tuple[int, int], **kwargs) -> ProjectDelta:
+ return ProjectDelta(
+ base=ProjectTotals(*base), head=ProjectTotals(*head), basis="base_report", **kwargs
+ )
+
+
+def test_delta_is_head_minus_base_unrounded() -> None:
+ d = _delta((800, 1000), (797, 1000))
+ assert abs(d.delta_pct - -0.3) < 1e-9
+ assert d.to_dict()["delta_pct"] == -0.3
+
+
+def test_gate_without_max_drop_is_not_set() -> None:
+ assert _delta((80, 100), (10, 100)).gate == "not_set"
+
+
+ ("base", "head", "max_drop", "gate"),
+ [
+ ((80, 100), (79, 100), 1.0, "pass"), # exactly max_drop passes
+ ((80, 100), (79, 100), 0.5, "fail"),
+ ((80, 100), (90, 100), 0.0, "pass"),
+ # 99.9 - 99.6 is 0.30000000000001137 in floats: not a failure.
+ ((9990, 10000), (9960, 10000), 0.3, "pass"),
+ ((9990, 10000), (9959, 10000), 0.3, "fail"),
+ ],
+)
+def test_gate_passes_at_exactly_max_drop_and_fails_past_it(base, head, max_drop, gate) -> None:
+ assert _delta(base, head, max_drop=max_drop).gate == gate
+
+
+def test_gate_has_no_data_without_both_sides_or_when_incomparable() -> None:
+ assert ProjectDelta(None, ProjectTotals(1, 2), "history", max_drop=1).gate == "no_data"
+ assert _delta((0, 0), (1, 2), max_drop=1).gate == "no_data"
+ assert _delta((80, 100), (10, 100), max_drop=1, incomparable=("x",)).gate == "no_data"
+
+
+def test_the_project_gate_joins_the_verdict_without_small_change_tolerance() -> None:
+ coverage = {"a.py": _fc("a.py", [1], [1])}
+ pc = compute_patch_coverage({"a.py": {1}}, coverage, min_coverable_lines=50)
+ failing = _delta((80, 100), (70, 100), max_drop=1)
+ passing = _delta((80, 100), (80, 100), max_drop=1)
+
+ # Flat and risky unset: the project gate is the verdict, small change or not.
+ assert replace(pc, project=failing).gate == "fail"
+ assert replace(pc, project=passing).gate == "pass"
+ assert replace(pc, project=None).gate == "not_set"
+ # A flat verdict stands, and a failing project gate still fails the change.
+ flat = replace(pc, threshold=50, min_coverable_lines=None)
+ assert replace(flat, project=passing).gate == "pass"
+ assert replace(flat, project=failing).gate == "fail"
+ assert replace(pc, project=failing).to_dict()["project"]["gate"] == "fail"
+ assert pc.to_dict()["project"] is None
+
+
+# -- comparability -----------------------------------------------------------
+
+
+def _scope(*formats: str, ignore=(), partial=False) -> CoverageScope:
+ return CoverageScope(tuple(sorted(formats)), tuple(sorted(ignore)), partial)
+
+
+def test_same_scope_is_comparable() -> None:
+ assert incomparable_reasons(_scope("lcov", "lcov"), _scope("lcov", "lcov")) == ()
+
+
+def test_incomparable_reasons_are_plain_sentences() -> None:
+ assert incomparable_reasons(_scope("lcov"), _scope("lcov", "lcov")) == (
+ "the base read 1 lcov report, the head read 2 lcov reports",
+ )
+ assert incomparable_reasons(_scope("lcov", ignore=["gen/"]), _scope("lcov")) == (
+ "coverage.ignore differs",
+ )
+ assert incomparable_reasons(_scope("lcov", partial=True), _scope("lcov")) == (
+ "the base report mapped fewer than half its files",
+ )
+ assert incomparable_reasons(None, _scope("lcov")) == (
+ "the base ingest predates scope records; pass --base-report, "
+ "or re-measure coverage at the base commit",
+ )
+
+
+def test_scope_round_trips_through_its_dict() -> None:
+ scope = _scope("lcov", "cobertura", ignore=["b/", "a/"], partial=True)
+ assert CoverageScope.from_dict(scope.to_dict()) == scope
+ assert CoverageScope.from_dict({"report_formats": "lcov"}) is None
+ assert CoverageScope.from_dict(None) is None
+
+
+def test_resolved_reports_record_one_format_per_report() -> None:
+ from repowise.core.analysis.health.coverage import parse_lcov, resolve_reports
+
+ lcov = "SF:a.py\nDA:1,1\nend_of_record\n"
+ resolved = resolve_reports([parse_lcov(lcov), parse_lcov(lcov)], {"a.py"}, ignore=["x/"])
+
+ assert resolved.provenance.scope == _scope("lcov", "lcov", ignore=["x/"])
+
+
+# -- coverage outside the change ---------------------------------------------
+
+# Two lines inserted above line 3 of src/a.py (old 3.. become new 5..), and
+# line 7 rewritten.
+_DIFF = """\
+--- a/src/a.py
++++ b/src/a.py
+@@ -2,0 +3,2 @@
++x = 1
++y = 2
+@@ -7 +9 @@
+-old
++new
+"""
+
+
+def _scan(base, head, diff=_DIFF, renames=None, deleted=()):
+ return indirect_changes(base, head, parse_unified_diff(diff), renames or {}, deleted)
+
+
+def _rows(*args, **kwargs):
+ return list(_scan(*args, **kwargs).rows)
+
+
+def test_lines_move_through_the_diff_before_they_are_compared() -> None:
+ base = {"src/a.py": _fc("src/a.py", [1, 3, 4, 7], [1, 3, 4, 7, 8])}
+ # At the head, old line 3 is line 5 and old 4 is 6: still covered. Old 8
+ # (new 10) is newly covered. Old 7 was rewritten (new 9): the change's own.
+ head = {"src/a.py": _fc("src/a.py", [1, 5, 6, 10], [1, 3, 4, 5, 6, 9, 10])}
+
+ (row,) = _rows(base, head)
+
+ assert row.newly_uncovered_ranges == ()
+ assert row.newly_covered_line_count == 1
+ assert row.status == "changed"
+
+
+def test_touched_lines_are_left_to_patch_coverage() -> None:
+ base = {"src/a.py": _fc("src/a.py", [7], [7])}
+ head = {"src/a.py": _fc("src/a.py", [], [9])}
+ assert _rows(base, head) == []
+
+
+def test_a_line_that_lost_coverage_is_named_at_its_head_position() -> None:
+ base = {"src/a.py": _fc("src/a.py", [3, 4], [3, 4])}
+ head = {"src/a.py": _fc("src/a.py", [], [5, 6])}
+
+ (row,) = _rows(base, head)
+
+ assert row.newly_uncovered_ranges == ((5, 6),)
+ assert (row.base_pct, row.head_pct) == (100.0, 0.0)
+
+
+def test_an_untouched_file_maps_line_for_line() -> None:
+ base = {"lib/b.py": _fc("lib/b.py", [1, 2, 3], [1, 2, 3])}
+ head = {"lib/b.py": _fc("lib/b.py", [1], [1, 2, 3])}
+
+ (row,) = _rows(base, head)
+
+ assert (row.file_path, row.newly_uncovered_ranges) == ("lib/b.py", ((2, 3),))
+
+
+def test_a_renamed_file_is_compared_under_its_new_path() -> None:
+ base = {"old/b.py": _fc("old/b.py", [1, 2], [1, 2])}
+ head = {"new/b.py": _fc("new/b.py", [1], [1, 2])}
+
+ (row,) = _rows(base, head, renames={"old/b.py": "new/b.py"})
+
+ assert (row.file_path, row.newly_uncovered_ranges) == ("new/b.py", ((2, 2),))
+
+
+def test_files_the_head_report_no_longer_measures() -> None:
+ base = {
+ "gone.py": _fc("gone.py", [1], [1]),
+ "moved.py": _fc("moved.py", [1], [1]),
+ "dropped.py": _fc("dropped.py", [1], [1, 2]),
+ "empty.py": _fc("empty.py", [], []),
+ }
+ rows = _rows(base, {}, renames={"moved.py": "elsewhere.py"}, deleted={"gone.py"})
+
+ # Deleted files are the change's own; a renamed one is reported under its
+ # new path; a file with no coverable line says nothing.
+ assert [(r.file_path, r.status, r.base_pct, r.head_pct) for r in rows] == [
+ ("dropped.py", "no_longer_measured", 50.0, None),
+ ("elsewhere.py", "no_longer_measured", 100.0, None),
+ ]
+
+
+def test_most_newly_uncovered_lines_first() -> None:
+ base = {p: _fc(p, [1, 2, 3], [1, 2, 3]) for p in ("x.py", "y.py", "z.py")}
+ head = {
+ "x.py": _fc("x.py", [1, 2], [1, 2, 3]),
+ "y.py": _fc("y.py", [], [1, 2, 3]),
+ "z.py": _fc("z.py", [1, 2, 3], [1, 2, 3]),
+ }
+ assert [r.file_path for r in _rows(base, head)] == ["y.py", "x.py"]
+
+
+_SHIFT = """\
+--- a/src/a.py
++++ b/src/a.py
+@@ -1,0 +2,3 @@
++x = 1
++y = 2
++z = 3
+"""
+
+
+def test_a_base_report_measured_at_the_head_is_left_out_with_a_reason() -> None:
+ # The same line data on both sides through a diff that shifts every line:
+ # the base report was measured at the head, not at the base commit.
+ same = _fc("src/a.py", [2, 3, 6, 9], [2, 3, 4, 5, 6, 9])
+ untouched = _fc("lib/b.py", [1, 2], [1, 2, 3])
+
+ scan = _scan(
+ {"src/a.py": same, "lib/b.py": untouched},
+ {"src/a.py": same, "lib/b.py": untouched},
+ diff=_SHIFT,
+ )
+
+ assert scan.rows == ()
+ assert scan.misaligned == ("src/a.py",)
+ assert scan.note("a1b2c3d4e5") == (
+ "the base report does not line up with a1b2c3d in 1 file; measure it at the base commit"
+ )
+
+
+def test_a_base_report_that_lines_up_nowhere_keeps_no_rows() -> None:
+ base = {"src/a.py": _fc("src/a.py", [1, 2, 3, 4], [1, 2, 3, 4])}
+ # Nothing coverable where the base's lines land: the report is from elsewhere.
+ head = {"src/a.py": _fc("src/a.py", [], [20, 21, 22, 23])}
+
+ scan = _scan(base, head, diff="")
+
+ assert scan.rows is None
+ assert scan.misaligned == ("src/a.py",)
+
+
+def test_a_few_stray_lines_do_not_make_a_file_misaligned() -> None:
+ base = {"lib/b.py": _fc("lib/b.py", list(range(1, 31)), list(range(1, 31)))}
+ # Two lines the head no longer counts: under the minimum, the file is kept.
+ head = {"lib/b.py": _fc("lib/b.py", list(range(1, 28)), list(range(1, 29)))}
+
+ scan = _scan(base, head, diff="")
+
+ assert scan.misaligned == ()
+ assert [r.newly_uncovered_ranges for r in scan.rows] == [((28, 28),)]
+
+
+# -- causes and rendering ------------------------------------------------------
+
+
+def test_name_pairing_finds_the_deleted_test_for_a_file() -> None:
+ causes = name_causes(
+ ["src/auth.py", "src/other.py"],
+ {"tests/test_auth.py", "src/cli.py"},
+ {"tests/test_auth.py"},
+ )
+ assert causes == {
+ "src/auth.py": (IndirectCause("test_deleted", "tests/test_auth.py", "name"),),
+ "src/other.py": (),
+ }
+
+
+def _with_project(rows, **kwargs):
+ coverage = {"a.py": _fc("a.py", [1], [1])}
+ pc = compute_patch_coverage({"a.py": {1}}, coverage)
+ project = _delta((800, 1000), (797, 1000), outside_change=rows, **kwargs)
+ return replace(pc, project=project)
+
+
+def test_markdown_carries_the_project_line_and_the_outside_table() -> None:
+ lost = IndirectChange("src/auth.py", ((4, 6),), 0, 90.0, 60.0, "changed")
+ rows = apply_causes(
+ [lost], {"src/auth.py": (IndirectCause("test_deleted", "tests/test_auth.py", "name"),)}
+ )
+ md = render_markdown(_with_project(rows, max_drop=0.1, base_commit="a1b2c3d4e5"))
+
+ assert (
+ "**Project coverage 79.7%** · down 0.30 points from 80.0% at a1b2c3d · "
+ "falls more than the 0.1-point max-drop gate allows"
+ ) in md
+ assert "### Coverage outside the change" in md
+ row = "| `src/auth.py` | 90.0% | 60.0% | 4-6 | deleted test tests/test_auth.py (by name) |"
+ assert row in md
+
+
+def test_markdown_says_why_files_were_left_out() -> None:
+ md = render_markdown(_with_project(None, outside_change_note="it does not line up"))
+ assert "Files left out: it does not line up." in md
+ assert "| File |" not in md
+
+
+def test_markdown_caps_the_outside_table() -> None:
+ rows = tuple(
+ IndirectChange(f"f{i:02}.py", ((1, 1),), 0, 100.0, 0.0, "changed") for i in range(12)
+ )
+ md = render_markdown(_with_project(rows))
+ assert "f09.py" in md and "f10.py" not in md
+ assert "and 2 more files." in md
+
+
+def test_project_line_words() -> None:
+ same = _with_project(None)
+
+ unchanged = replace(same, project=_delta((80, 100), (80, 100), max_drop=0.5))
+ assert project_line(unchanged, markdown=False) == (
+ "Project coverage 80.0% · unchanged from 80.0% · within the 0.5-point max-drop gate"
+ )
+ incomparable = replace(same, project=_delta((80, 100), (70, 100), incomparable=("a", "b")))
+ assert project_line(incomparable, markdown=False) == "Project coverage not compared: a; b."
+ assert project_line(replace(same, project=None)) == ""
+
+
+def test_github_warns_per_file_that_lost_coverage_and_errors_on_the_gate() -> None:
+ rows = (
+ IndirectChange("src/a.py", ((12, 14),), 0, 90.0, 60.0, "changed"),
+ IndirectChange("src/b.py", (), 3, 50.0, 80.0, "changed"),
+ )
+ lines = github_annotations(_with_project(rows, max_drop=0.1))
+
+ errors = [line for line in lines if line.startswith("::error")]
+ warnings = [line for line in lines if "Coverage lost outside the change" in line]
+ assert len(errors) == 1 and "Project coverage 79.7%" in errors[0]
+ assert len(warnings) == 1 and "file=src/a.py,line=12" in warnings[0]
+
+
+def test_a_file_no_longer_measured_is_a_file_level_warning() -> None:
+ rows = (IndirectChange("src/gone.py", (), 0, 80.0, None, "no_longer_measured"),)
+ lines = github_annotations(_with_project(rows))
+
+ (warning,) = [line for line in lines if "Coverage lost outside the change" in line]
+ assert warning.startswith("::warning file=src/gone.py,title=")
+ assert "line=" not in warning
+ # Workflow commands escape % as %25.
+ assert "Measured at the base (80.0%25), not in the head's coverage report" in warning
+
+
+def test_ranges_and_outside_warnings_share_one_annotation_budget() -> None:
+ # 12 uncovered ranges in the change, 2 files losing coverage outside it.
+ covered = []
+ coverable = list(range(1, 25, 2))
+ pc = compute_patch_coverage({"a.py": set(coverable)}, {"a.py": _fc("a.py", covered, coverable)})
+ rows = (
+ IndirectChange("x.py", ((1, 1),), 0, 100.0, 0.0, "changed"),
+ IndirectChange("y.py", ((2, 2),), 0, 100.0, 0.0, "changed"),
+ )
+ lines = github_annotations(replace(pc, project=_delta((1, 1), (1, 1), outside_change=rows)))
+
+ ranges = [line for line in lines if "title=Uncovered change::" in line]
+ outside = [line for line in lines if "Coverage lost outside the change" in line]
+ notices = [line for line in lines if line.startswith("::notice")]
+ assert (len(ranges), len(outside)) == (8, 2)
+ assert notices == ["::notice::4 more warnings; the first 10 are listed in the job summary"]
diff --git a/tests/unit/cli/test_coverage_check_cmd.py b/tests/unit/cli/test_coverage_check_cmd.py
index c6ebe701b..f969949b3 100644
--- a/tests/unit/cli/test_coverage_check_cmd.py
+++ b/tests/unit/cli/test_coverage_check_cmd.py
@@ -325,6 +325,277 @@ def test_coverage_ignore_drops_changed_files_and_report_entries(repo) -> None:
1,
0,
)
+# -- project coverage and coverage outside the change -------------------------
+
+
+def delta_repo(tmp_path):
+ """``feat`` rewrites src/app.py line 3 and deletes tests/test_lib.py."""
+ _git(tmp_path, "init", "-q", "-b", "main")
+ _git(tmp_path, "config", "user.email", "[email protected]")
+ _git(tmp_path, "config", "user.name", "t")
+ (tmp_path / "src").mkdir()
+ (tmp_path / "tests").mkdir()
+ (tmp_path / "src" / "app.py").write_text("a = 1\nb = 2\nc = 3\n", encoding="utf-8")
+ (tmp_path / "src" / "lib.py").write_text("w = 1\nx = 2\ny = 3\nz = 4\n", encoding="utf-8")
+ (tmp_path / "tests" / "test_lib.py").write_text("def test(): pass\n", encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+ _git(tmp_path, "commit", "-qm", "init")
+ _git(tmp_path, "switch", "-qc", "feat")
+ (tmp_path / "src" / "app.py").write_text("a = 1\nb = 2\nc = 33\n", encoding="utf-8")
+ _git(tmp_path, "rm", "-q", "tests/test_lib.py")
+ _git(tmp_path, "commit", "-qam", "feat")
+ return tmp_path
+
+
+def _report(repo, name: str, files: dict[str, dict[int, int]]) -> str:
+ """An lcov report at *name* with absolute paths, one record per file."""
+ records = [
+ f"SF:{repo / path}\n"
+ + "".join(f"DA:{n},{hits}\n" for n, hits in lines.items())
+ + "end_of_record\n"
+ for path, lines in files.items()
+ ]
+ out = repo / name
+ out.write_text("".join(records), encoding="utf-8")
+ return str(out)
+
+
+_APP = {1: 1, 2: 1, 3: 1}
+
+
+def _delta_reports(repo, app=_APP) -> tuple[str, str]:
+ """Base: every line covered. Head: lib.py lines 3-4 lost with the deleted test."""
+ base = _report(
+ repo, "base.lcov", {"src/app.py": _APP, "src/lib.py": dict.fromkeys(range(1, 5), 1)}
+ )
+ head = _report(
+ repo, "head.lcov", {"src/app.py": app, "src/lib.py": {1: 1, 2: 1, 3: 0, 4: 0}}
+ )
+ return base, head
+
+
+def test_a_base_report_adds_project_coverage_and_coverage_outside_the_change(
+ delta_repo,
+) -> None:
+ base, head = _delta_reports(delta_repo)
+
+ result = _run(
+ delta_repo, "main...feat", "--report", head, "--base-report", base, "--format", "json"
+ )
+
+ assert result.exit_code == 0, result.output
+ project = json.loads(result.stdout)["project"]
+ assert project["basis"] == "base_report"
+ assert (project["base"]["coverage_pct"], project["head"]["coverage_pct"]) == (100.0, 71.42)
+ assert project["delta_pct"] == -28.57
+ assert project["gate"] == "not_set"
+ (lib,) = project["outside_change"]
+ assert (lib["file_path"], lib["newly_uncovered_ranges"]) == ("src/lib.py", [[3, 4]])
+ # No index: the deleted test is paired with the file by name.
+ assert lib["causes"] == [
+ {"kind": "test_deleted", "path": "tests/test_lib.py", "basis": "name"}
+ ]
+
+
+def test_max_drop_gates_the_project_delta(delta_repo) -> None:
+ base, head = _delta_reports(delta_repo)
+ args = ("main...feat", "--report", head, "--base-report", base)
+
+ assert _run(delta_repo, *args, "--max-drop", "30").exit_code == 0
+ failed = _run(delta_repo, *args, "--max-drop", "1")
+ assert failed.exit_code == 1, failed.output
+ assert "falls more than the 1-point max-drop gate allows" in failed.output
+ assert "Coverage outside the change" in failed.output
+
+
+def test_max_drop_defaults_to_config_and_a_bad_value_exits_2(delta_repo) -> None:
+ base, head = _delta_reports(delta_repo)
+ config = delta_repo / ".repowise" / "config.yaml"
+ config.parent.mkdir()
+ args = ("main...feat", "--report", head, "--base-report", base)
+
+ config.write_text("coverage:\n max_drop: 1\n", encoding="utf-8")
+ assert _run(delta_repo, *args).exit_code == 1
+ config.write_text("coverage:\n max_drop: lots\n", encoding="utf-8")
+ bad = _run(delta_repo, *args)
+ assert bad.exit_code == 2
+ assert "coverage.max_drop must be a number" in bad.output
+
+
+def test_an_incomparable_base_report_exits_2(delta_repo) -> None:
+ base, head = _delta_reports(delta_repo)
+ copy = delta_repo / "base-copy.lcov"
+ copy.write_text((delta_repo / "base.lcov").read_text(encoding="utf-8"), encoding="utf-8")
+
+ result = _run(
+ delta_repo,
+ "main...feat",
+ "--report",
+ head,
+ "--base-report",
+ base,
+ "--base-report",
+ str(copy),
+ "--format",
+ "json",
+ )
+
+ assert result.exit_code == 2, result.output
+ error = json.loads(result.stdout)
+ assert error["error"] == "project_scope_mismatch"
+ assert "the base read 2 lcov reports, the head read 1 lcov report" in error["message"]
+
+
+def test_max_drop_without_a_base_exits_2(delta_repo) -> None:
+ _, head = _delta_reports(delta_repo)
+
+ result = _run(
+ delta_repo, "main...feat", "--report", head, "--max-drop", "1", "--format", "json"
+ )
+
+ assert result.exit_code == 2
+ assert json.loads(result.stdout)["error"] == "project_base_missing"
+
+
+def test_a_config_max_drop_without_a_base_is_a_note_not_a_failure(delta_repo) -> None:
+ _, head = _delta_reports(delta_repo)
+ config = delta_repo / ".repowise" / "config.yaml"
+ config.parent.mkdir()
+ config.write_text("coverage:\n max_drop: 1\n", encoding="utf-8")
+
+ table = _run(delta_repo, "main...feat", "--report", head)
+ data = _run(delta_repo, "main...feat", "--report", head, "--format", "json")
+
+ assert table.exit_code == 0, table.output
+ assert "Project coverage not evaluated" in table.output
+ assert data.exit_code == 0 and json.loads(data.stdout)["project"] is None
+ # The flag asks for the gate explicitly: no base cannot evaluate.
+ assert _run(delta_repo, "main...feat", "--report", head, "--max-drop", "1").exit_code == 2
+
+
+def _ask(repo, head, prefixes, base_reports=()):
+ """A project comparison over *repo*, asked for by flags, as ``coverage check`` builds it."""
+ from repowise.cli.commands import coverage_check_cmd as cmd
+ from repowise.core.analysis.health.coverage import CoverageConfig
+
+ reports = cmd._Reports(repo, CoverageConfig(), prefixes, None)
+ return cmd._ProjectAsk(
+ reports, head, tuple(base_reports), "main...feat", cmd.console, None, True
+ )
+
+
+def test_a_history_base_counts_only_the_files_the_index_lists(delta_repo) -> None:
+ import json as _json
+ from types import SimpleNamespace
+
+ from repowise.cli.commands import coverage_check_cmd as cmd
+
+ # The head report names src/lib.py too, which git tracks but the index does not list.
+ _, head_report = _delta_reports(delta_repo)
+ ask = _ask(delta_repo, None, cmd._cli_reports((head_report,)))
+ head = cmd._resolve_reports(ask.reports, cmd.console)
+ ask = _ask(delta_repo, head, ask.reports.prefixes)
+ assert {fc.file_path for fc in head.files} == {"src/app.py", "src/lib.py"}
+ # The same figures ingested at the base, over the index's one file.
+ row = SimpleNamespace(
+ covered_lines=3,
+ total_lines=3,
+ scope_json=_json.dumps(head.scope.to_dict()),
+ ingested_commit_sha="b" * 40,
+ )
+
+ project = cmd._report_against_ingest(ask, row, {"src/app.py"})
+
+ assert project.incomparable == ()
+ assert (project.head.covered_line_count, project.head.coverable_line_count) == (3, 3)
+ assert project.delta_pct == 0
+ # With no index keys there is nothing to count the head against.
+ assert cmd._report_against_ingest(ask, row, set()).incomparable
+
+
+ ("index_keys", "rows", "base_lines"),
+ [
+ # src/lib.py is not indexed: it counts on neither side and is not listed.
+ ({"src/app.py"}, [], 3),
+ # Indexed but missing from the head ingest: no longer measured, and it
+ # stays in the base total.
+ ({"src/app.py", "src/lib.py"}, [("src/lib.py", "no_longer_measured")], 7),
+ ],
+)
+def test_a_base_report_against_a_stored_head_counts_what_the_index_lists(
+ delta_repo, monkeypatch, index_keys, rows, base_lines
+) -> None:
+ from repowise.cli.commands import coverage_check_cmd as cmd
+ from repowise.core import git_refs
+ from repowise.core.analysis.health.coverage import file_coverage
+
+ base_report, _ = _delta_reports(delta_repo)
+ # The stored head measured src/app.py only; the base report also names src/lib.py.
+ # Its changed line 3 is uncovered, so the two sides differ only where the change did.
+ stored = {"src/app.py": file_coverage("src/app.py", [1, 2], [1, 2, 3])}
+ base_ask = _ask(delta_repo, None, cmd._cli_reports((base_report,)))
+ base = cmd._resolve_reports(base_ask.reports, cmd.console)
+ monkeypatch.setattr(
+ cmd, "_head_coverage", lambda _root, _head: (stored, base.scope, index_keys)
+ )
+
+ project = cmd._report_delta(
+ _ask(delta_repo, None, {}, (base_report,)),
+ git_refs.change_base(str(delta_repo), "main...feat"),
+ )
+
+ assert [(c.file_path, c.status) for c in project.outside_change] == rows
+ assert project.outside_change_note is None
+ assert (project.base.coverable_line_count, project.head.coverable_line_count) == (
+ base_lines,
+ 3,
+ )
+
+
+def test_a_failure_found_already_stands_when_there_is_no_base(delta_repo) -> None:
+ # The changed line is uncovered, so the flat gate fails before the base is looked for.
+ _, head = _delta_reports(delta_repo, app={1: 1, 2: 1, 3: 0})
+
+ result = _run(
+ delta_repo, "main...feat", "--report", head, "--fail-under", "80", "--max-drop", "1"
+ )
+
+ assert result.exit_code == 1, result.output
+ assert "below the 80.0% gate" in result.output
+ assert "Project coverage not evaluated" in result.output
+
+
+def test_markdown_and_github_carry_the_project_line_and_outside_table(
+ delta_repo, tmp_path_factory
+) -> None:
+ base, head = _delta_reports(delta_repo)
+ args = ("main...feat", "--report", head, "--base-report", base)
+ summary = tmp_path_factory.mktemp("gh") / "summary.md"
+
+ markdown = _run(delta_repo, *args, "--format", "markdown").stdout
+ github = _run(
+ delta_repo,
+ *args,
+ "--max-drop",
+ "1",
+ "--format",
+ "github",
+ env={"GITHUB_STEP_SUMMARY": str(summary)},
+ )
+
+ assert "**Project coverage 71.4%** · down 28.57 points from 100.0% at " in markdown
+ assert "### Coverage outside the change" in markdown
+ row = "| `src/lib.py` | 100.0% | 50.0% | 3-4 | deleted test tests/test_lib.py (by name) |"
+ assert row in markdown
+ assert "::warning file=src/lib.py,line=3,title=Coverage lost outside the change::" in (
+ github.stdout
+ )
+ assert "::error::Project coverage 71.4%" in github.stdout
+ assert "### Coverage outside the change" in summary.read_text(encoding="utf-8")
+
+
@pytest.fixture
def fixed_repo(tmp_path):
"""``main`` fixed src/app.py twice and src/other.py once; ``feat`` edits app lines 2-3."""
diff --git a/tests/unit/persistence/test_coverage_loaders.py b/tests/unit/persistence/test_coverage_loaders.py
index a9a5f0d29..68f86335d 100644
--- a/tests/unit/persistence/test_coverage_loaders.py
+++ b/tests/unit/persistence/test_coverage_loaders.py
@@ -23,6 +23,7 @@ from repowise.core.persistence.crud import (
load_coverage_history,
load_coverage_map,
load_file_coverage,
+ load_ingest_at_commit,
save_coverage_files,
upsert_repository,
)
@@ -117,6 +118,79 @@ async def test_stored_patch_coverage_is_none_without_coverage(async_session, rep
assert await stored_patch_coverage(async_session, repo.id, {"a.py": {1}}) is None
+async def _scoped_ingest(session, repo_id: str, lcov: str, commit: str, minute: int) -> None:
+ resolved = resolve_reports([parse_lcov(lcov)], {"src/a.py"})
+ await save_coverage_files(
+ session,
+ repo_id,
+ resolved.files,
+ source_format="lcov",
+ provenance=resolved.provenance,
+ ingested_commit_sha=commit,
+ ingested_at=_at(minute),
+ )
+
+
+async def _stored_with_base(session, repo_id: str, changed, head: str, base: str):
+ """Stored patch coverage with the project delta attached, as the read surfaces do."""
+ from repowise.core.analysis.patch_coverage import (
+ attach_history_delta,
+ stored_patch_coverage,
+ )
+
+ pc = await stored_patch_coverage(session, repo_id, changed, head_commit=head)
+ return await attach_history_delta(session, repo_id, pc, base)
+
+
+async def test_stored_patch_coverage_compares_the_ingest_at_the_base(async_session, repo) -> None:
+ await _scoped_ingest(async_session, repo.id, _LCOV, "base", 0) # 2 of 3 lines
+ worse = _LCOV.replace("DA:4,2", "DA:4,0") # 1 of 3 at the head
+ await _scoped_ingest(async_session, repo.id, worse, "head", 1)
+
+ stored = await _stored_with_base(async_session, repo.id, {"src/a.py": {1}}, "head", "base")
+
+ assert stored is not None and stored.project is not None
+ project = stored.project.to_dict()
+ assert (project["basis"], project["base_commit"], project["head_commit"]) == (
+ "history",
+ "base",
+ "head",
+ )
+ assert project["delta_pct"] == -33.33
+ # Read-only surfaces never gate, and history keeps no per-file rows.
+ assert (project["gate"], project["outside_change"], project["incomparable"]) == (
+ "not_set",
+ None,
+ [],
+ )
+
+
+async def test_stored_patch_coverage_has_no_project_without_a_base_ingest(
+ async_session, repo
+) -> None:
+ await _scoped_ingest(async_session, repo.id, _LCOV, "head", 0)
+ changed = {"src/a.py": {1}}
+
+ missing = await _stored_with_base(async_session, repo.id, changed, "head", "base")
+ stale = await _stored_with_base(async_session, repo.id, changed, "later", "head")
+
+ assert missing is not None and missing.project is None
+ # Coverage not measured at the head is not the head's figure.
+ assert stale is not None and stale.project is None
+
+
+async def test_a_base_ingest_without_a_scope_is_incomparable(async_session, repo) -> None:
+ await _ingest(async_session, repo.id, 5, 0, ingested_commit_sha="base")
+ await _scoped_ingest(async_session, repo.id, _LCOV, "head", 1)
+
+ stored = await _stored_with_base(async_session, repo.id, {"src/a.py": {1}}, "head", "base")
+
+ assert stored.project.incomparable == (
+ "the base ingest predates scope records; pass --base-report, "
+ "or re-measure coverage at the base commit",
+ )
+
+
async def test_ingest_provenance_reaches_the_summary_and_stored_patch_scope(
async_session, repo
) -> None:
@@ -292,18 +366,84 @@ async def test_reingesting_the_same_report_restamps_rather_than_appends(
) -> None:
await _ingest(async_session, repo.id, 5, 0, ingested_commit_sha="one")
await _ingest(async_session, repo.id, 6, 1, ingested_commit_sha="two")
- # An update that re-ingests, or a full re-index: the same figures again.
- await _ingest(async_session, repo.id, 6, 2, ingested_commit_sha="three")
+ # An update that re-ingests, or a full re-index: the same figures, same commit.
+ await _ingest(async_session, repo.id, 6, 2, ingested_commit_sha="two")
+ rows = (await async_session.execute(select(CoverageIngest))).scalars().all()
history = await load_coverage_history(async_session, repo.id)
+ assert len(rows) == 2
assert [(p["ingested_commit_sha"], p["line_coverage_pct"]) for p in history] == [
("one", 50.0),
- ("three", 60.0),
+ ("two", 60.0),
]
assert history[-1]["ingested_at"].startswith("2026-09-01T12:02:00")
+async def test_an_unknown_commit_appends_and_the_trend_collapses_repeats(
+ async_session, repo
+) -> None:
+ await _ingest(async_session, repo.id, 6, 0, ingested_commit_sha="one")
+ # A writer that does not know the commit: a row of its own, never "one".
+ await _ingest(async_session, repo.id, 6, 1)
+ await _ingest(async_session, repo.id, 7, 2, ingested_commit_sha="two")
+
+ rows = (
+ await async_session.execute(select(CoverageIngest).order_by(CoverageIngest.ingested_at))
+ ).scalars()
+ history = await load_coverage_history(async_session, repo.id)
+
+ assert [r.ingested_commit_sha for r in rows] == ["one", None, "two"]
+ # Consecutive identical figures read as one point, the newest of them.
+ assert [(p["ingested_commit_sha"], p["line_coverage_pct"]) for p in history] == [
+ (None, 60.0),
+ ("two", 70.0),
+ ]
+
+
+async def test_the_same_figures_at_another_commit_are_a_new_measurement(
+ async_session, repo
+) -> None:
+ # Identical coverage at a change's base and head: restamping would move the
+ # base's measurement to the head and lose the base.
+ await _ingest(async_session, repo.id, 6, 0, ingested_commit_sha="base")
+ await _ingest(async_session, repo.id, 6, 1, ingested_commit_sha="head")
+
+ history = await load_coverage_history(async_session, repo.id)
+ base = await load_ingest_at_commit(async_session, repo.id, "base")
+
+ # The trend collapses the repeat; the rows (and the base) are both kept.
+ assert [p["ingested_commit_sha"] for p in history] == ["head"]
+ assert base is not None and base.line_coverage_pct == 60.0
+ assert await load_ingest_at_commit(async_session, repo.id, "other") is None
+
+
+async def test_an_ingest_records_the_scope_it_measured(async_session, repo) -> None:
+ from repowise.core.analysis.patch_coverage import ingest_scope, ingest_totals
+
+ resolved = resolve_reports(
+ [parse_lcov(_LCOV), parse_lcov(_LCOV)], {"src/a.py"}, ignore=["gen/"]
+ )
+ await save_coverage_files(
+ async_session,
+ repo.id,
+ resolved.files,
+ source_format="lcov",
+ provenance=resolved.provenance,
+ ingested_commit_sha="abc",
+ )
+ # A writer without provenance records no scope: "scope unknown".
+ await _ingest(async_session, repo.id, 4, 1, ingested_commit_sha="def")
+
+ scoped = await load_ingest_at_commit(async_session, repo.id, "abc")
+ unscoped = await load_ingest_at_commit(async_session, repo.id, "def")
+
+ assert ingest_scope(scoped) == resolved.scope
+ assert resolved.scope.report_formats == ("lcov", "lcov")
+ assert ingest_scope(unscoped) is None
+ assert (ingest_totals(unscoped).covered_line_count, ingest_totals(unscoped).pct) == (4, 40.0)
+
+
async def test_an_ingest_with_no_coverable_lines_stays_off_the_trend(
async_session, repo
) -> None:
diff --git a/tests/unit/persistence/test_indirect_coverage_causes.py b/tests/unit/persistence/test_indirect_coverage_causes.py
new file mode 100644
index 000000000..2d694b5c9
--- /dev/null
+++ b/tests/unit/persistence/test_indirect_coverage_causes.py
@@ -0,0 +1,103 @@
+"""``read_indirect_causes`` against real index rows: per-test coverage and the graph."""
+
+from __future__ import annotations
+
+import json
+
+from repowise.core.analysis.patch_coverage import (
+ IndirectCause,
+ IndirectChange,
+ read_indirect_causes,
+)
+from repowise.core.persistence.models import GraphEdge, GraphNode, TestCoverageEntry
+from tests.unit.persistence.helpers import insert_repo
+
+
+async def _index(session, repo_id: str) -> None:
+ """tests/test_login.py calls ``login`` in src/auth.py, which src/cli.py imports
+ and src/api.py calls; tests/test_util.py ran src/util.py (per-test rows)."""
+ files = {
+ "src/auth.py": False,
+ "src/util.py": False,
+ "src/cli.py": False,
+ "src/api.py": False,
+ "tests/test_login.py": True,
+ }
+ session.add_all(
+ [
+ *(
+ GraphNode(repository_id=repo_id, node_id=path, node_type="file", is_test=is_test)
+ for path, is_test in files.items()
+ ),
+ *(
+ GraphEdge(
+ repository_id=repo_id, source_node_id=src, target_node_id=dst, edge_type=etype
+ )
+ for src, dst, etype in (
+ ("src/auth.py", "src/auth.py::login", "defines"),
+ ("tests/test_login.py", "tests/test_login.py::test_it", "defines"),
+ ("tests/test_login.py::test_it", "src/auth.py::login", "calls"),
+ ("src/cli.py", "src/auth.py", "imports"),
+ ("src/api.py::handler", "src/auth.py::login", "calls"),
+ )
+ ),
+ TestCoverageEntry(
+ repository_id=repo_id,
+ test_id="tests/test_util.py::test_x",
+ test_file="tests/test_util.py",
+ source_file="src/util.py",
+ covered_lines_json=json.dumps([3, 4]),
+ source_format="coverage.py",
+ ),
+ ]
+ )
+ await session.flush()
+
+
+def _lost(path: str) -> IndirectChange:
+ return IndirectChange(path, ((3, 4),), 0, 100.0, 50.0, "changed")
+
+
+async def test_each_file_names_the_changed_files_that_explain_it(async_session):
+ repo = await insert_repo(async_session)
+ await _index(async_session, repo.id)
+ indirect = [
+ _lost("src/auth.py"),
+ _lost("src/util.py"),
+ _lost("src/other.py"),
+ # Only gained coverage: nothing to explain.
+ IndirectChange("src/gained.py", (), 2, 50.0, 100.0, "changed"),
+ ]
+ changed = {
+ "tests/test_login.py",
+ "tests/test_util.py",
+ "tests/test_other.py",
+ "tests/test_auth.py",
+ "src/cli.py",
+ "src/api.py",
+ }
+ deleted = {"tests/test_util.py", "tests/test_other.py", "tests/test_auth.py"}
+
+ causes = await read_indirect_causes(async_session, repo.id, indirect, changed, deleted)
+
+ assert causes == {
+ # Inferred from the call graph, plus the changed importer and caller. The
+ # deleted test named for the file is added although the graph named one.
+ "src/auth.py": (
+ IndirectCause("test_modified", "tests/test_login.py", "graph"),
+ IndirectCause("test_deleted", "tests/test_auth.py", "name"),
+ IndirectCause("dependent_changed", "src/api.py", "graph"),
+ IndirectCause("dependent_changed", "src/cli.py", "graph"),
+ ),
+ # Measured: the deleted test's per-test rows ran the file.
+ "src/util.py": (IndirectCause("test_deleted", "tests/test_util.py", "per_test"),),
+ # The index no longer knows the deleted test: paired by name.
+ "src/other.py": (IndirectCause("test_deleted", "tests/test_other.py", "name"),),
+ }
+
+
+async def test_a_failed_read_leaves_causes_unassessed(async_session):
+ causes = await read_indirect_causes(
+ object(), "r", [_lost("src/a.py")], {"tests/test_a.py"}, set()
+ )
+ assert causes is None
diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.py
index 2bee81f15..c1b2c42de 100644
--- a/tests/unit/server/mcp/test_tool_change_risk.py
+++ b/tests/unit/server/mcp/test_tool_change_risk.py
@@ -441,6 +441,58 @@ async def test_patch_coverage_is_the_gate_computation_on_stored_coverage(
assert partial["gate"] == "not_set"
+async def test_patch_coverage_compares_the_ingest_at_the_change_base(
+ monkeypatch, factory, session, tmp_path
+):
+ from repowise.core import git_refs
+ from repowise.core.analysis.health.coverage import parse_lcov, resolve_reports
+ from repowise.core.persistence.crud import save_coverage_files, upsert_repository
+
+ repo = await upsert_repository(session, name="r", local_path=str(tmp_path))
+ for commit, hits in (("base0", "1"), ("abc", "0")):
+ lcov = f"SF:a.py\nDA:1,1\nDA:2,{hits}\nend_of_record\n"
+ resolved = resolve_reports([parse_lcov(lcov)], {"a.py"})
+ await save_coverage_files(
+ session,
+ repo.id,
+ resolved.files,
+ source_format="lcov",
+ provenance=resolved.provenance,
+ ingested_commit_sha=commit,
+ )
+ await session.commit()
+
+ async def _repo(_session, *_a, **_k):
+ return repo
+
+ bases = []
+
+ def _change_base(_path, revspec):
+ bases.append(revspec)
+ return "base0"
+
+ monkeypatch.setattr(tool, "_get_repo", _repo)
+ monkeypatch.setattr(git_refs, "resolve", lambda _p, _rev: "abc")
+ monkeypatch.setattr(git_refs, "change_base", _change_base)
+ ctx = SimpleNamespace(session_factory=factory, path=tmp_path)
+
+ block = await tool._patch_coverage_block(
+ ctx, {"a.py": {2}}, None, "main...HEAD", _scored(), _collector(tmp_path)
+ )
+
+ assert bases == ["main...HEAD"]
+ project = block["project"]
+ assert (project["basis"], project["base_commit"], project["head_commit"]) == (
+ "history",
+ "base0",
+ "abc",
+ )
+ assert (project["delta_pct"], project["gate"]) == (-50.0, "not_set")
+ # A working-tree change measured from a push base starts at their merge-base.
+ assert tool._change_base(str(tmp_path), None, "main...working tree", True) == "base0"
+ assert bases[-1] == "main...HEAD"
+
+
@pytest.mark.asyncio
async def test_patch_coverage_rows_carry_their_files_risk(monkeypatch, factory, session, tmp_path):
from repowise.core import git_refs
diff --git a/tests/unit/server/test_patch_coverage_schema.py b/tests/unit/server/test_patch_coverage_schema.py
index 1478b73c1..f789a36dc 100644
--- a/tests/unit/server/test_patch_coverage_schema.py
+++ b/tests/unit/server/test_patch_coverage_schema.py
@@ -2,10 +2,16 @@
from __future__ import annotations
+from dataclasses import replace
+
from repowise.core.analysis.health.coverage import PathGate, file_coverage
from repowise.core.analysis.patch_coverage import (
FileRisk,
+ IndirectCause,
+ IndirectChange,
PatchScope,
+ ProjectDelta,
+ ProjectTotals,
TestHint,
attach_hints,
attach_risk,
@@ -79,3 +85,29 @@ def test_every_to_dict_key_round_trips_through_the_response_model() -> None:
assert hinted["files"][0]["hints"][0]["basis"] == "per_test"
assert {f["file_path"] for f in hinted["files"] if f["hints"] is not None} == {"a.py"}
assert PatchCoverageResponse.model_validate(hinted).model_dump() == hinted
+
+ # With a project delta: totals, the gate and each outside-change row round-trip.
+ project = ProjectDelta(
+ base=ProjectTotals(80, 100),
+ head=ProjectTotals(79, 100),
+ basis="base_report",
+ base_commit="b" * 40,
+ head_commit="h" * 40,
+ max_drop=0.5,
+ outside_change=(
+ IndirectChange(
+ "b.py",
+ ((4, 6),),
+ 1,
+ 50.0,
+ 40.0,
+ "changed",
+ (IndirectCause("test_deleted", "tests/test_b.py", "name"),),
+ ),
+ IndirectChange("c.py", (), 0, 100.0, None, "no_longer_measured"),
+ ),
+ )
+ projected = replace(pc, project=project).to_dict()
+ assert projected["project"]["gate"] == "fail"
+ assert PatchCoverageResponse.model_validate(projected).model_dump() == projected
+ assert wire["project"] is None
diff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.py
index d0a8e3ae4..94a114e94 100644
--- a/tests/unit/server/test_risk_range.py
+++ b/tests/unit/server/test_risk_range.py
@@ -336,3 +336,43 @@ async def test_patch_coverage_rows_carry_index_risk(
assert risk["risky"] is True and risk["reasons"] == ["hotspot"]
assert data["risky"]["file_count"] == 1
assert data["risky"]["patch_coverage_pct"] == 66.66
+
+
+async def test_patch_coverage_compares_the_ingest_at_the_merge_base(
+ client: AsyncClient, session, git_repo: Path, tmp_path: Path
+) -> None:
+ from repowise.core.analysis.health.coverage import parse_lcov, resolve_reports
+ from repowise.core.persistence.crud import save_coverage_files
+
+ base = subprocess.run(
+ ["git", "rev-parse", "HEAD"], cwd=git_repo, check=True, capture_output=True, text=True
+ ).stdout.strip()
+ head = _commit(git_repo, {"src/a.py": "x = 1\ny = 2\nz = 3\n"}, "feat: add a")
+ repo = await _register(client, tmp_path)
+ url = f"/api/repos/{repo['id']}/health/coverage/patch"
+
+ async def _ingest(commit: str, hits: str) -> None:
+ lcov = f"SF:src/a.py\nDA:1,1\nDA:2,{hits}\nDA:3,0\nend_of_record\n"
+ resolved = resolve_reports([parse_lcov(lcov)], {"src/a.py"})
+ await save_coverage_files(
+ session,
+ repo["id"],
+ resolved.files,
+ source_format="lcov",
+ provenance=resolved.provenance,
+ ingested_commit_sha=commit,
+ )
+ await session.commit()
+
+ await _ingest(base, "1")
+ await _ingest(head, "0")
+ project = (await client.get(url, params={"base": base})).json()["project"]
+
+ assert (project["basis"], project["base_commit"], project["head_commit"]) == (
+ "history",
+ base,
+ head,
+ )
+ assert project["delta_pct"] == -33.33
+ assert (project["gate"], project["outside_change"]) == ("not_set", None)
diff --git a/tests/unit/test_ci_action.py b/tests/unit/test_ci_action.py
index 358c93664..9fdf2ba98 100644
--- a/tests/unit/test_ci_action.py
+++ b/tests/unit/test_ci_action.py
@@ -59,7 +59,9 @@ def test_the_gitlab_template_parses() -> None:
risk = " ".join(jobs["repowise-risk"]["script"])
assert "--fail-above-percentile" in risk and "--format markdown" in risk
assert "REPOWISE_RISK_FAIL_ABOVE_PERCENTILE" in jobs["repowise-risk"]["rules"][0]["if"]
- assert "--fail-under-risky" in " ".join(jobs["repowise-coverage"]["script"])
+ coverage = " ".join(jobs["repowise-coverage"]["script"])
+ assert "--fail-under-risky" in coverage
+ assert "--base-report" in coverage and "--max-drop" in coverage
def _gitlab_jobs() -> dict:
@@ -157,6 +159,29 @@ def test_the_default_branch_job_writes_the_doc_drift_report(tmp_path, fake_repow
assert json.loads(doc_drift.read_text(encoding="utf-8")) == json.loads(_ISSUE)
+ ("base", "expected"),
+ [
+ ("", "coverage check origin/main...HEAD --report a.info --format markdown"),
+ (
+ "base/a.info base/b.info",
+ "coverage check origin/main...HEAD --report a.info --base-report base/a.info "
+ "--base-report base/b.info --max-drop 0.5 --format markdown",
+ ),
+ ],
+)
+def test_the_gitlab_coverage_job_passes_base_reports_only_when_set(
+ tmp_path, fake_repowise, base, expected
+) -> None:
+ env = {"REPOWISE_COVERAGE_REPORT": "a.info", "REPOWISE_COVERAGE_BASE_REPORT": base}
+ if base:
+ env["REPOWISE_COVERAGE_MAX_DROP"] = "0.5"
+ code = _run_gitlab_job(tmp_path, fake_repowise, "repowise-coverage", **env)
+
+ assert code == 0
+ assert (tmp_path / "log").read_text(encoding="utf-8").split() == expected.split()
+
+
def test_the_gitlab_coverage_job_leaves_globs_to_repowise() -> None:
script = yaml.safe_load(GITLAB.read_text(encoding="utf-8"))["repowise-coverage"]["script"]
# Globbing off before the unquoted, space-split report list is expanded.
@@ -226,6 +251,8 @@ def _run(tmp_path: Path, bin_dir: Path, **env: str) -> tuple[int, str, str]:
"COVERAGE_FAIL_UNDER": "",
"COVERAGE_MIN_COVERABLE_LINES": "",
"COVERAGE_FAIL_UNDER_RISKY": "",
+ "COVERAGE_BASE_REPORT": "",
+ "COVERAGE_MAX_DROP": "",
"DOC_DRIFT_BASELINE": "",
"SECURITY_FAIL_ON": "high",
"SECURITY_BASELINE": "",
@@ -279,6 +306,22 @@ def test_inputs_reach_the_commands(tmp_path, fake_repowise) -> None:
)
+def test_base_report_inputs_reach_the_coverage_command(tmp_path, fake_repowise) -> None:
+ code, _, calls = _run(
+ tmp_path,
+ fake_repowise,
+ CHECKS="coverage",
+ COVERAGE_REPORT="lcov.info",
+ COVERAGE_BASE_REPORT="base/lcov.info\nbase/web/**/lcov.info=web",
+ COVERAGE_MAX_DROP="0.5",
+ )
+ assert code == 0
+ assert calls.strip() == (
+ "coverage check --format github --report lcov.info "
+ "--base-report base/lcov.info --base-report base/web/**/lcov.info=web --max-drop 0.5"
+ )
+
+
def test_risk_inputs_reach_the_commands(tmp_path, fake_repowise) -> None:
code, outputs, calls = _run(
tmp_path,