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): report branches on changed lines beside patch coverage, with partly taken lines and a branch gate (#2664)

Raghav Chamadiya0a3bf0c5f58d
diff --git a/action.yml b/action.yml
index 4bf16c90a..2627494ca 100644
--- a/action.yml
+++ b/action.yml
@@ -55,6 +55,15 @@ 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-fail-under-branches:
+ description: >-
+ Minimum percent of branches taken on changed lines, judged beside patch
+ coverage and never blended into it. A change with no branching line is
+ not gated; a report without per-line branch data fails the step as
+ cannot evaluate (exit 2). Empty uses coverage.fail_under_branches from
+ .repowise/config.yaml (where missing branch data is only a note), else
+ no branch gate.
+ default: ""
coverage-base-report:
description: >-
Coverage reports measured at the change's base commit (the merge-base
@@ -130,6 +139,7 @@ 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_FAIL_UNDER_BRANCHES: ${{ inputs.coverage-fail-under-branches }}
COVERAGE_BASE_REPORT: ${{ inputs.coverage-base-report }}
COVERAGE_MAX_DROP: ${{ inputs.coverage-max-drop }}
DOC_DRIFT_BASELINE: ${{ inputs.doc-drift-baseline }}
diff --git a/ci/github/run-gates.sh b/ci/github/run-gates.sh
index 40825bcc8..d7beb8db0 100644
--- a/ci/github/run-gates.sh
+++ b/ci/github/run-gates.sh
@@ -66,6 +66,7 @@ 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")
+ [[ -n "$COVERAGE_FAIL_UNDER_BRANCHES" ]] && args+=(--fail-under-branches "$COVERAGE_FAIL_UNDER_BRANCHES")
while IFS= read -r report; do
[[ -n "$report" ]] && args+=(--base-report "$report")
done <<<"$COVERAGE_BASE_REPORT"
diff --git a/ci/gitlab/repowise.gitlab-ci.yml b/ci/gitlab/repowise.gitlab-ci.yml
index a6aa9d02c..1f575ac95 100644
--- a/ci/gitlab/repowise.gitlab-ci.yml
+++ b/ci/gitlab/repowise.gitlab-ci.yml
@@ -24,6 +24,8 @@
# lines than this never fails the coverage gate.
# REPOWISE_COVERAGE_FAIL_UNDER_RISKY
# Minimum patch coverage percent over risky files only.
+# REPOWISE_COVERAGE_FAIL_UNDER_BRANCHES
+# Minimum percent of branches taken on changed lines.
# 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.
@@ -58,6 +60,7 @@ 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_FAIL_UNDER_BRANCHES:+--fail-under-branches "$REPOWISE_COVERAGE_FAIL_UNDER_BRANCHES"}
${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
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index 41bac613a..3d6bdba28 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -315,8 +315,8 @@ gate, a path-scoped gate that is not informational, or the risky gate fails;
the flat gate's own rule is unchanged. No risky file with a changed executable
line leaves the risky gate not applied (`no_data`, exit `0`). With the flag
set, a shallow clone or a measured row whose risk could not be read exits `2`,
-unless the flat or a path-scoped gate already failed, which is then reported
-as the failure.
+unless the flat, a path-scoped or the branch gate already failed, which is
+then reported as the failure.
### Where to add the test
@@ -350,6 +350,18 @@ 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.
+### Branches on changed lines
+
+When the report has per-line branch data, `coverage check` also reports the
+branches taken on changed lines, beside patch coverage and never blended with
+it, and lists lines that ran with a branch never taken as partly taken
+(`branches` and each row's `partial_ranges` in `json`, the REST response and
+`get_change_risk`; `null` when not measured, never 0%). Stored coverage keeps
+per-line branches, so the stored path reports the same. `--fail-under-branches
+PCT` (or `coverage.fail_under_branches`) gates it. See
+[Branches on changed lines](../start/CI.md#branches-on-changed-lines) and the
+[`coverage check` reference](../reference/CLI_REFERENCE.md#repowise-coverage-check-revspec).
+
### Project coverage and coverage outside the change
Patch coverage cannot see a change that deletes a test, or removes a code path
@@ -699,7 +711,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`, `--fail-under-risky`, `--base-report`, `--max-drop`, `--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`, `--fail-under-branches`, `--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 3327cfd82..1f4132719 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1367,6 +1367,7 @@ 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`) |
+| `--fail-under-branches` | Exit 1 when the share of branches taken on changed lines is below this percentage (0-100), never blended with patch coverage. Defaults to `coverage.fail_under_branches`. No changed branching line: 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) |
@@ -1387,8 +1388,10 @@ change the verdict.
uncovered range, first; titled "Uncovered change in a risky file" for a risky
one), a `::notice` counting the rest, an `::error::` for each gate that fails
(the whole change, each path-scoped gate that is not informational, the
-risky-file gate), a `::notice::` per informational gate below its threshold,
-and a `::notice::` when the small-change tolerance exempts a gate, then
+risky-file gate, the branch gate), a `::notice::` per informational gate below
+its threshold, a `::notice::` when the small-change tolerance exempts a gate or
+a branch gate was set but not applied, a `::warning` titled "Partly taken
+branch" per partly taken range (sharing the cap), then
appends the markdown summary to `$GITHUB_STEP_SUMMARY` when set. `json`
carries `patch_coverage_pct`, `covered_line_count`, `coverable_line_count`,
`threshold`, `min_coverable_lines`, `gate` (`pass`, `fail`, `no_data`,
@@ -1396,12 +1399,14 @@ carries `patch_coverage_pct`, `covered_line_count`, `coverable_line_count`,
(`measured`, `not_in_report`, `no_line_data`, `no_coverable_changes`,
`out_of_scope`), `files[]` (`file_path`, `status`, `changed_line_count`,
`coverable_line_count`, `covered_line_count`, `patch_coverage_pct`,
-`uncovered_ranges`, `risk`: `fix_pressure`, `dependents`, `hotspot`,
+`uncovered_ranges`, `branch_taken`, `branch_total`, `partial_ranges` (0 and
+empty without branch data), `risk`: `fix_pressure`, `dependents`, `hotspot`,
`bug_magnet`, `basis`, `risky`, `reasons`; `hints`, null without an index, one
per uncovered range: `range`, `symbol`, `tests`, `basis` (`per_test`,
`call_graph`, `import_graph`, `none`), `total`), `scope` (`label`,
`source_formats`, `reports`, `report_path_count`,
-`unmatched_report_path_count`, `ignored_file_count`, `config_errors`),
+`unmatched_report_path_count`, `ignored_file_count`, `config_errors`,
+`branch_data`: `per_line`, `none` or `stored_before`),
`path_gates[]` (`name`, `paths`, `threshold`, `informational`,
`measured_file_count`, `unmeasured_file_count`, `covered_line_count`,
`coverable_line_count`, `patch_coverage_pct`, `gate`), `risky`
@@ -1416,8 +1421,11 @@ null on the history basis or when most files did not line up:
`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
+(`per_test`, `graph`, `name`)), and `branches`, null when no changed line has
+branch data and no branch gate was set (`branch_taken`, `branch_total`,
+`branch_coverage_pct`, `partial_line_count`, `threshold`, `gate`). 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
@@ -1428,19 +1436,23 @@ that module's directory unless the report has a per-report prefix or
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, the risky files' is below
-`--fail-under-risky`, or project coverage fell more than `--max-drop` points;
+`--fail-under-risky`, the branches taken on changed lines are below
+`--fail-under-branches`, 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
clone's boundary; bad config or a malformed `coverage.fail_under` /
-`coverage.min_coverable_lines` / `coverage.fail_under_risky`, or an unusable
+`coverage.min_coverable_lines` / `coverage.fail_under_risky` /
+`coverage.fail_under_branches`, or an unusable
`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`); 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`).
+risk could not be read (unless the flat, a path-scoped or the branch gate
+already failed, which exits `1`); `--fail-under-branches` over coverage with
+no per-line branch data (`no_branch_data`; from `coverage.fail_under_branches`
+alone it is a note, exit `0`); 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 1ddd50abf..ff4c773ac 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 --fail-under-branches P` | Did the tests take the branches of the lines this change touched? | git and a report with per-line branch data | 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 |
@@ -123,6 +124,7 @@ 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-fail-under-branches` | `coverage.fail_under_branches` | Minimum percent of branches taken on changed lines. |
| `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. |
@@ -266,6 +268,7 @@ coverage:
fail_under: 80
min_coverable_lines: 5 # small-change tolerance
fail_under_risky: 90 # optional, see Risk-weighted patch coverage
+ fail_under_branches: 70 # optional, see Branches on changed lines
```
With `min_coverable_lines` set, a change touching fewer changed executable
@@ -447,8 +450,29 @@ when any gate fails. It follows the same rules as the others, the whole
change's small-change tolerance included. A change that touches no risky file
leaves it not applied (`no_data`, exit `0`). With the gate set, a shallow
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.
+index row), exits `2`, unless the whole-change, a path-scoped or the branch
+gate already failed: that failure is reported.
+
+### Branches on changed lines
+
+When the report has per-line branch data (lcov `BRDA`, Cobertura
+`condition-coverage`, JaCoCo branch counters, Clover `cond`), the check also
+reports "Branches on changed lines 70.0% (7 of 10 taken; 2 lines partly
+taken)". A partly taken line ran with a branch never taken: it gets a "Partly
+taken" column and, on GitHub, a "Partly taken branch" warning.
+`--fail-under-branches P` (`coverage-fail-under-branches`,
+`coverage.fail_under_branches`) gates the share.
+
+- Line and branch coverage are reported side by side, never blended.
+- The small-change tolerance applies, and counts changed lines, not branches.
+- No changed line with branches: "not measured", never 0%, and the gate is not
+ applied (exit `0`).
+- Coverage with no per-line branch data (a Go coverprofile, coverage.py without
+ `--branch`, stored coverage ingested before branches were kept) exits `2`
+ under the flag, unless another gate already failed, and is a note with exit
+ `0` from the config key alone.
+- Several reports merge per line by the most branches taken and seen, so the
+ share is a lower bound.
### Project coverage and coverage outside the change
@@ -541,6 +565,8 @@ repowise-coverage:
| "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 coverage report has no per-line branch data, so --fail-under-branches cannot be judged." | turn on branch coverage in the test run, or drop the flag |
+| "The stored coverage predates per-line branch data ..." | re-run `repowise coverage add` with the report |
| "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 e96fc6d4c..ada3bc1b2 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_check_cmd.py
@@ -10,11 +10,13 @@ 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, the risky files' is below ``--fail-under-risky``, or
+informational fails, the risky files' is below ``--fail-under-risky``, the
+share of branches taken on changed lines is below ``--fail-under-branches``, 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``, no base
+unreadable or a shallow clone under ``--fail-under-risky``, coverage with no
+per-line branch data under ``--fail-under-branches``, 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.
@@ -92,6 +94,16 @@ 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.",
)
+ "--fail-under-branches",
+ type=click.FloatRange(0, 100),
+ default=None,
+ help="Exit 1 when the share of branches taken on changed lines is below this "
+ "percentage. Reported beside patch coverage, never blended into it. A change with "
+ "no branching line is not gated; a report with no per-line branch data exits 2. "
+ "Defaults to coverage.fail_under_branches in .repowise/config.yaml (from config "
+ "alone, a report without branch data is a note).",
+)
@click.option(
"--base-report",
"base_reports",
@@ -125,6 +137,7 @@ def coverage_check(
fail_under: float | None,
min_coverable_lines: int | None,
fail_under_risky: float | None,
+ fail_under_branches: float | None,
base_reports: tuple[str, ...],
max_drop: float | None,
repo: str | None,
@@ -164,12 +177,20 @@ def coverage_check(
notices = ci_notices(fmt)
try:
pc, head, head_reports = _evaluate(
- revspec, reports, report_format, fail_under, min_coverable_lines, repo, notices
+ revspec,
+ reports,
+ report_format,
+ fail_under,
+ min_coverable_lines,
+ fail_under_branches,
+ 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
+ _require_branch_data(pc, strict=fail_under_branches is not None)
except CannotEvaluateError as exc:
cannot_evaluate(fmt, exc.code, str(exc))
_emit(pc, fmt)
@@ -177,7 +198,16 @@ def coverage_check(
raise click.exceptions.Exit(EXIT_GATE_FAILED)
-def _evaluate(revspec, reports, report_format, fail_under, min_coverable_lines, repo, notices):
+def _evaluate(
+ revspec,
+ reports,
+ report_format,
+ fail_under,
+ min_coverable_lines,
+ fail_under_branches,
+ 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
@@ -190,10 +220,12 @@ def _evaluate(revspec, reports, report_format, fail_under, min_coverable_lines,
root,
validate_threshold=fail_under is None,
validate_min_lines=min_coverable_lines is None,
+ validate_branches=fail_under_branches is None,
)
# A flag overrides its config key.
threshold = _first_set(fail_under, cfg.fail_under)
min_coverable_lines = _first_set(min_coverable_lines, cfg.min_coverable_lines)
+ branch_threshold = _first_set(fail_under_branches, cfg.fail_under_branches)
report_prefixes = _cli_reports(reports) if reports else cfg.reports(root)
report_paths = list(report_prefixes)
if not report_paths and not has_db_store(root):
@@ -204,7 +236,8 @@ def _evaluate(revspec, reports, report_format, fail_under, min_coverable_lines,
if notices is console:
notices.print("[dim]Reading the coverage stored in the index[/dim]")
stored = run_async(_stored(root, changed, label, threshold, min_coverable_lines, cfg))
- return _gateable(stored), None, _Reports(root, cfg, {}, report_format)
+ pc = replace(_gateable(stored), branch_threshold=branch_threshold)
+ return pc, 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]")
@@ -221,7 +254,7 @@ def _evaluate(revspec, reports, report_format, fail_under, min_coverable_lines,
ignore=cfg.ignore,
gates=cfg.gates,
)
- return pc, resolved, head_reports
+ return replace(pc, branch_threshold=branch_threshold), resolved, head_reports
def _first_set(flag, configured):
@@ -339,11 +372,40 @@ def _with_risk(repo, pc, fail_under_risky):
git, index = _read_risk(root, pc.scope.label or None, paths)
pc = attach_risk(pc, assess_risks(paths, git, index), risky_threshold=threshold)
# A failure the flat or a path-scoped gate already found stands and is reported.
- if threshold is not None and pc.flat_gate != "fail" and not pc.failing_path_gates:
+ if (
+ threshold is not None
+ and "fail" not in (pc.flat_gate, pc.branch_gate)
+ and not pc.failing_path_gates
+ ):
_require_trusted_risk(root, pc)
return pc
+def _require_branch_data(pc, *, strict: bool) -> None:
+ """Raise when ``--fail-under-branches`` asked for a gate the coverage cannot judge.
+
+ Coverage with no per-line branch data at all is a setup problem: exit 2 when
+ the flag asked, unless another gate already failed (that verdict stands).
+ From config alone the branch line says the gate was not applied. A change
+ with no branching line has nothing to judge and passes.
+ """
+ data = pc.scope.branch_data
+ if not strict or data == "per_line" or pc.gate == "fail":
+ return
+ if data == "stored_before":
+ raise CannotEvaluateError(
+ "no_branch_data",
+ "The stored coverage predates per-line branch data, so --fail-under-branches "
+ "cannot be judged. Re-run `repowise coverage add` with the report, or pass it "
+ "with --report.",
+ )
+ raise CannotEvaluateError(
+ "no_branch_data",
+ "The coverage report has no per-line branch data, so --fail-under-branches cannot "
+ "be judged. Produce the report with branch coverage turned on.",
+ )
+
+
def _risky_threshold(root: Path, flag: float | None) -> float | None:
"""``--fail-under-risky``, else ``coverage.fail_under_risky`` (validated)."""
if flag is not None:
@@ -505,6 +567,7 @@ def _coverage_config(
validate_min_lines: bool,
validate_risky: bool = False,
validate_max_drop: bool = False,
+ validate_branches: bool = False,
):
from repowise.core.analysis.health.coverage import CoverageConfig
from repowise.core.repo_config import RepoConfigError, load_repo_config
@@ -522,6 +585,7 @@ def _coverage_config(
("fail_under", cfg.fail_under, validate_threshold),
("fail_under_risky", cfg.fail_under_risky, validate_risky),
("max_drop", cfg.max_drop, validate_max_drop),
+ ("fail_under_branches", cfg.fail_under_branches, validate_branches),
):
if validate and block.get(key) is not None and parsed is None:
raise CannotEvaluateError(
@@ -560,6 +624,7 @@ def _emit(pc, fmt: str) -> None:
def _print_summary(pc) -> None:
from repowise.core.analysis.patch_coverage import (
+ branch_line,
headline,
project_line,
risk_basis_line,
@@ -572,6 +637,8 @@ def _print_summary(pc) -> None:
console.print(escape(project))
if risky := risky_line(pc, markdown=False):
console.print(escape(risky))
+ if branches := branch_line(pc, markdown=False):
+ console.print(escape(branches))
console.print(f"[dim]{escape(scope_line(pc, markdown=False))}[/dim]")
if basis := risk_basis_line(pc):
console.print(f"[dim]{escape(basis)}.[/dim]")
@@ -597,41 +664,60 @@ def _print_path_gates(pc) -> None:
def _print_table(pc) -> None:
from rich.table import Table
- from repowise.core.analysis.patch_coverage import (
- RANGE_LIMIT,
- STATUS_TEXT,
- attention_rows,
- first_hint,
- format_ranges,
- hint_phrase,
- risk_words,
- )
+ from repowise.core.analysis.patch_coverage import attention_rows
rows = attention_rows(pc)
if not rows:
return
- with_hint = any(f.hints for f in rows)
+ columns = _table_columns(pc, rows)
table = Table(show_edge=False, pad_edge=False)
- table.add_column("File")
- table.add_column("Risk")
- table.add_column("Covered", justify="right")
- table.add_column("Uncovered changed lines")
- if with_hint:
- table.add_column("Extend")
+ for name, justify, _ in columns:
+ table.add_column(name, justify=justify)
for f in rows:
- if f.status == "measured":
- covered = f"{f.covered_line_count} of {f.coverable_line_count}"
- gaps = format_ranges(f.uncovered_ranges, RANGE_LIMIT)
- else:
- covered, gaps = "", STATUS_TEXT[f.status]
- cells = [escape(f.file_path), escape(risk_words(f.risk)), covered, gaps]
- if with_hint:
- hint = first_hint(f)
- cells.append(escape(hint_phrase(hint)) if hint else "")
- table.add_row(*cells)
+ table.add_row(*(fill(f) for _, _, fill in columns))
console.print(table)
+def _table_columns(pc, rows) -> list:
+ """``(header, justify, cell)`` per column; Partly taken and Extend only when filled."""
+ from repowise.core.analysis.patch_coverage import RANGE_LIMIT, format_ranges, risk_words
+
+ columns = [
+ ("File", "left", lambda f: escape(f.file_path)),
+ ("Risk", "left", lambda f: escape(risk_words(f.risk))),
+ ("Covered", "right", _covered_cell),
+ ("Uncovered changed lines", "left", _gaps_cell),
+ ]
+ if pc.partial_line_count > 0:
+ columns.append(
+ ("Partly taken", "left", lambda f: format_ranges(f.partial_ranges, RANGE_LIMIT))
+ )
+ if any(f.hints for f in rows):
+ columns.append(("Extend", "left", _extend_cell))
+ return columns
+
+
+def _covered_cell(f) -> str:
+ if f.status != "measured":
+ return ""
+ return f"{f.covered_line_count} of {f.coverable_line_count}"
+
+
+def _gaps_cell(f) -> str:
+ from repowise.core.analysis.patch_coverage import RANGE_LIMIT, STATUS_TEXT, format_ranges
+
+ if f.status != "measured":
+ return STATUS_TEXT[f.status]
+ return format_ranges(f.uncovered_ranges, RANGE_LIMIT)
+
+
+def _extend_cell(f) -> str:
+ from repowise.core.analysis.patch_coverage import first_hint, hint_phrase
+
+ hint = first_hint(f)
+ return escape(hint_phrase(hint)) if hint else ""
+
+
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
diff --git a/packages/core/alembic/versions/0085_coverage_branch_lines.py b/packages/core/alembic/versions/0085_coverage_branch_lines.py
new file mode 100644
index 000000000..f10713f05
--- /dev/null
+++ b/packages/core/alembic/versions/0085_coverage_branch_lines.py
@@ -0,0 +1,46 @@
+"""coverage_files.branch_lines_json: branches per line, for changed-line branch coverage.
+
+``branch_lines_json`` holds ``{"line": [taken, total]}`` for the lines a report
+gives branch counts for, so patch coverage can report partly taken branches on
+changed lines. NULL when the report carried no per-line branch data (or the row
+predates the column).
+
+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: 0085
+Revises: 0084
+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 = "0085"
+down_revision: str | None = "0084"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+_TABLE = "coverage_files"
+_COLUMN = "branch_lines_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/health/coverage/clover.py b/packages/core/src/repowise/core/analysis/health/coverage/clover.py
index 62444ec82..e1efa4312 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/clover.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/clover.py
@@ -18,7 +18,17 @@ Clover layout (abbreviated):
We trust the per-line elements over the ``<metrics>`` summary so coverage
percentages match what gets highlighted in the dashboard. Branch coverage
-is derived from ``type="cond"`` lines (truecount + falsecount).
+is derived from ``type="cond"`` lines, whose two attributes mean one of two
+things depending on the writer:
+
+* evaluation counts (the original format): ``truecount`` / ``falsecount``
+ are how often the condition was true / false, so a line has two branches
+ and each is taken when its count is above zero;
+* branch counts: ``truecount`` is branches covered and ``falsecount``
+ branches not covered, so the line has ``truecount + falsecount``
+ branches. That writer marks its reports with a fixed
+ ``<project name="All files">`` and ``clover="3.2.0"`` on the root; both
+ must be present.
"""
from __future__ import annotations
@@ -27,12 +37,22 @@ from pathlib import Path
from .model import CoverageReport, FileCoverage, file_coverage, parse_xml
+#: The markers the branch-count writer always emits (see the module docstring).
+_BRANCH_COUNT_PROJECT = "All files"
+_BRANCH_COUNT_VERSION = "3.2.0"
+
def parse_clover(text: str) -> CoverageReport:
root = parse_xml(text)
if root is None:
return CoverageReport(source_format="clover", files=[])
+ project = root.find("project")
+ branch_counts = (
+ project is not None
+ and project.get("name") == _BRANCH_COUNT_PROJECT
+ and root.get("clover") == _BRANCH_COUNT_VERSION
+ )
files: list[FileCoverage] = []
for file_el in root.iter("file"):
path = file_el.get("path") or file_el.get("name") or ""
@@ -43,6 +63,7 @@ def parse_clover(text: str) -> CoverageReport:
coverable: set[int] = set()
branches_found = 0
branches_hit = 0
+ branch_lines: dict[int, tuple[int, int]] = {}
for line in file_el.iter("line"):
try:
@@ -64,8 +85,11 @@ def parse_clover(text: str) -> CoverageReport:
fc = int(line.get("falsecount", "0"))
except ValueError:
tc, fc = 0, 0
- branches_found += 2
- branches_hit += (1 if tc > 0 else 0) + (1 if fc > 0 else 0)
+ taken, total = (tc, tc + fc) if branch_counts else ((tc > 0) + (fc > 0), 2)
+ branches_found += total
+ branches_hit += taken
+ if total:
+ branch_lines[line_no] = (taken, total)
files.append(
file_coverage(
@@ -74,6 +98,7 @@ def parse_clover(text: str) -> CoverageReport:
coverable,
branches_found=branches_found,
branches_hit=branches_hit,
+ branch_lines=branch_lines,
)
)
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py b/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py
index 2d435139e..e8ff57042 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/cobertura.py
@@ -29,8 +29,9 @@ from __future__ import annotations
import re
from dataclasses import dataclass, field
from pathlib import Path
+from xml.etree import ElementTree as ET
-from .model import CoverageReport, file_coverage, parse_xml
+from .model import CoverageReport, FileCoverage, file_coverage, parse_xml
_CONDITION_RE = re.compile(r"\((\d+)\s*/\s*(\d+)\)")
@@ -42,53 +43,75 @@ def parse_cobertura(text: str) -> CoverageReport:
# Aggregate by filename: several <class> rows can share one file.
per_file: dict[str, _FileLines] = {}
-
for cls in root.iter("class"):
filename = cls.get("filename") or ""
- if not filename:
- continue
- bucket = per_file.setdefault(Path(filename).as_posix(), _FileLines())
- for line in cls.iter("line"):
- try:
- line_no = int(line.get("number", "0"))
- hits = int(line.get("hits", "0"))
- except ValueError:
- continue
- if line_no <= 0:
- continue
- bucket.coverable.add(line_no)
- if hits > 0:
- bucket.covered.add(line_no)
-
- if line.get("branch") == "true":
- m = _CONDITION_RE.search(line.get("condition-coverage", ""))
- if m:
- bucket.branches_hit += int(m.group(1))
- bucket.branches_found += int(m.group(2))
- else:
- bucket.branches_found += 2
- bucket.branches_hit += 2 if hits > 0 else 0
+ if filename:
+ bucket = per_file.setdefault(Path(filename).as_posix(), _FileLines())
+ for line in cls.iter("line"):
+ bucket.add_line(line)
# Filenames are relative to one of these; the resolver tries each.
roots = tuple(
dict.fromkeys(s.text.strip() for s in root.iter("source") if s.text and s.text.strip())
)
- files = [
- file_coverage(
- path,
- b.covered,
- b.coverable,
- branches_found=b.branches_found,
- branches_hit=b.branches_hit,
- )
- for path, b in per_file.items()
- ]
+ files = [b.file_coverage(path) for path, b in per_file.items()]
return CoverageReport(source_format="cobertura", files=files, source_roots=roots)
+def _line_hits(line: ET.Element) -> tuple[int, int] | None:
+ """``(line number, hits)`` of a ``<line>``, ``None`` when unreadable."""
+ try:
+ line_no = int(line.get("number", "0"))
+ hits = int(line.get("hits", "0"))
+ except ValueError:
+ return None
+ return (line_no, hits) if line_no > 0 else None
+
+
+def _condition(line: ET.Element) -> tuple[int, int] | None:
+ """``(taken, total)`` from ``condition-coverage="50% (1/2)"``, ``None`` without it."""
+ m = _CONDITION_RE.search(line.get("condition-coverage", ""))
+ return (int(m.group(1)), int(m.group(2))) if m else None
+
+
@dataclass
class _FileLines:
covered: set[int] = field(default_factory=set)
coverable: set[int] = field(default_factory=set)
+ # Branches on lines without ``condition-coverage`` (two assumed per line).
branches_found: int = 0
branches_hit: int = 0
+ branch_lines: dict[int, tuple[int, int]] = field(default_factory=dict)
+
+ def add_line(self, line: ET.Element) -> None:
+ parsed = _line_hits(line)
+ if parsed is None:
+ return
+ line_no, hits = parsed
+ self.coverable.add(line_no)
+ if hits > 0:
+ self.covered.add(line_no)
+ if line.get("branch") == "true":
+ self._add_branches(line_no, hits, _condition(line))
+
+ def _add_branches(self, line_no: int, hits: int, condition: tuple[int, int] | None) -> None:
+ if condition is None:
+ # No per-line figure to keep: the file total assumes two branches.
+ self.branches_found += 2
+ self.branches_hit += 2 if hits > 0 else 0
+ return
+ taken, total = condition
+ if total:
+ # A line repeated across <class> rows takes the max, never the sum.
+ prev_taken, prev_total = self.branch_lines.get(line_no, (0, 0))
+ self.branch_lines[line_no] = (max(prev_taken, taken), max(prev_total, total))
+
+ def file_coverage(self, path: str) -> FileCoverage:
+ return file_coverage(
+ path,
+ self.covered,
+ self.coverable,
+ branches_found=self.branches_found + sum(t for _, t in self.branch_lines.values()),
+ branches_hit=self.branches_hit + sum(h for h, _ in self.branch_lines.values()),
+ branch_lines=self.branch_lines,
+ )
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 8d5a79f76..9b848f2c2 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
@@ -144,6 +144,8 @@ class CoverageConfig:
# Most project coverage may fall from the change's base, in percentage
# points (``coverage check --max-drop``).
max_drop: float | None = None
+ # Least share of branches taken on changed lines (``--fail-under-branches``).
+ fail_under_branches: float | None = None
@classmethod
def from_repo_config(cls, repo_config: dict | None) -> CoverageConfig:
@@ -176,6 +178,7 @@ class CoverageConfig:
gate_errors=gate_errors,
fail_under_risky=_percent(block.get("fail_under_risky")),
max_drop=_percent(block.get("max_drop")),
+ fail_under_branches=_percent(block.get("fail_under_branches")),
)
def reports(self, repo_root: Path) -> dict[Path, str | None]:
@@ -869,6 +872,11 @@ def _merge_into(dst: FileCoverage, src: FileCoverage) -> None:
if dst.branch_coverage_pct is None
else max(dst.branch_coverage_pct, src.branch_coverage_pct)
)
+ # Branches are not identified across reports, so the per-line max is a lower bound.
+ for line, (taken, total) in src.branch_lines.items():
+ prev_taken, prev_total = dst.branch_lines.get(line, (0, 0))
+ dst.branch_lines[line] = (max(prev_taken, taken), max(prev_total, total))
+ dst.branch_lines = dict(sorted(dst.branch_lines.items()))
def _note_format(result: ResolvedCoverage, source_format: str | None) -> None:
@@ -891,6 +899,7 @@ def _merge_keyed(by_key: dict[str, FileCoverage], key: str, fc: FileCoverage) ->
total_coverable_lines=fc.total_coverable_lines,
coverable_lines=list(fc.coverable_lines),
covered_line_count=fc.covered_line_count,
+ branch_lines=dict(fc.branch_lines),
)
if key in by_key:
_merge_into(by_key[key], resolved_fc)
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/jacoco.py b/packages/core/src/repowise/core/analysis/health/coverage/jacoco.py
index f650f795b..a0feaf99f 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/jacoco.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/jacoco.py
@@ -91,6 +91,7 @@ def parse_jacoco(text: str) -> CoverageReport:
coverable,
branches_found=sum(t for t, _ in branches.values()),
branches_hit=sum(h for _, h in branches.values()),
+ branch_lines={nr: (hit, total) for nr, (total, hit) in branches.items()},
)
for path, (covered, coverable, branches) in merged.items()
# No executable lines (e.g. an interface) means unmeasured, not 0%.
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/lcov.py b/packages/core/src/repowise/core/analysis/health/coverage/lcov.py
index 2a41474ab..eedcca150 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/lcov.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/lcov.py
@@ -34,10 +34,12 @@ def parse_lcov(text: str) -> CoverageReport:
branches_hit = 0
explicit_lf: int | None = None
explicit_lh: int | None = None
+ # line -> (taken, total) from BRDA records; ``-`` (never evaluated) is not taken.
+ branch_lines: dict[int, tuple[int, int]] = {}
def flush() -> None:
nonlocal current_path, covered_lines, total_lines
- nonlocal branches_found, branches_hit, explicit_lf, explicit_lh
+ nonlocal branches_found, branches_hit, explicit_lf, explicit_lh, branch_lines
if current_path is None:
return
files.append(
@@ -49,6 +51,7 @@ def parse_lcov(text: str) -> CoverageReport:
branches_hit=branches_hit,
total=explicit_lf,
hit=explicit_lh,
+ branch_lines=branch_lines,
)
)
current_path = None
@@ -58,6 +61,7 @@ def parse_lcov(text: str) -> CoverageReport:
branches_hit = 0
explicit_lf = None
explicit_lh = None
+ branch_lines = {}
for raw_line in text.splitlines():
line = raw_line.strip()
@@ -85,9 +89,13 @@ def parse_lcov(text: str) -> CoverageReport:
elif tag == "BRDA":
parts = rest.split(",")
if len(parts) == 4:
+ taken = parts[3] not in ("-", "0")
branches_found += 1
- if parts[3] not in ("-", "0"):
- branches_hit += 1
+ branches_hit += taken
+ with contextlib.suppress(ValueError):
+ line_no = int(parts[0])
+ prev_taken, prev_total = branch_lines.get(line_no, (0, 0))
+ branch_lines[line_no] = (prev_taken + taken, prev_total + 1)
elif tag == "LF":
with contextlib.suppress(ValueError):
explicit_lf = int(rest)
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/model.py b/packages/core/src/repowise/core/analysis/health/coverage/model.py
index a6bc022fa..5c2861675 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/model.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/model.py
@@ -26,6 +26,10 @@ class FileCoverage:
``covered_line_count`` is the numerator of ``line_coverage_pct``, kept so
aggregates never derive it back from the rounded percentage. ``None``
when the source stated a percentage rather than a count.
+
+ ``branch_lines`` maps a line to ``(taken, total)`` branches on it. Empty
+ means the report carried no per-line branch data, not that no line
+ branches; ``branch_coverage_pct`` stays the file-level figure.
"""
file_path: str
@@ -35,6 +39,7 @@ class FileCoverage:
total_coverable_lines: int = 0
coverable_lines: list[int] = field(default_factory=list)
covered_line_count: int | None = None
+ branch_lines: dict[int, tuple[int, int]] = field(default_factory=dict)
def file_coverage(
@@ -46,6 +51,7 @@ def file_coverage(
branches_hit: int = 0,
total: int | None = None,
hit: int | None = None,
+ branch_lines: dict[int, tuple[int, int]] | None = None,
) -> FileCoverage:
"""Build a :class:`FileCoverage` from line sets, the one place percentages are derived.
@@ -67,6 +73,7 @@ def file_coverage(
total_coverable_lines=n_total,
coverable_lines=sorted(coverable_set),
covered_line_count=n_hit,
+ branch_lines=dict(sorted((branch_lines or {}).items())),
)
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 ff0aebf8d..9f6f8e6a0 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/__init__.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from .causes import apply_causes, name_causes, needs_causes, read_indirect_causes
from .compute import (
+ BranchData,
FilePatchCoverage,
FileStatus,
GateStatus,
@@ -35,6 +36,7 @@ from .render import (
RANGE_LIMIT,
STATUS_TEXT,
attention_rows,
+ branch_line,
cause_words,
fmt_pct,
format_ranges,
@@ -72,6 +74,7 @@ from .stored import (
__all__ = [
"RANGE_LIMIT",
"STATUS_TEXT",
+ "BranchData",
"FilePatchCoverage",
"FileRisk",
"FileStatus",
@@ -93,6 +96,7 @@ __all__ = [
"attach_history_delta",
"attach_risk",
"attention_rows",
+ "branch_line",
"build_hints",
"cause_words",
"compute_patch_coverage",
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 491f0cb8e..ab5b1f6a9 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/compute.py
@@ -22,6 +22,16 @@ report format carries "file present, nothing executed".
Path-scoped gates (``coverage.gates``) apply the same rule to the measured
files their globs match. One that fails and is not informational fails the
change, whatever the whole-change figure says.
+
+Branch coverage on changed lines is reported beside the line figure, never
+blended into it: a changed ``if`` whose other way never ran is covered as a
+line and "partly taken" as a branch. The share counts the branches on every
+changed executable line the report gives branch counts for, executed or not,
+and every line that lowers it is shown: a line that never ran is uncovered, a
+line that ran with fewer branches taken than it has is partly taken. With no
+such line it is not measured (``None``), never 0%. ``scope.branch_data`` says
+whether that is because the coverage carries no per-line branch data at all
+(a setup problem) or because no changed line branches.
"""
from __future__ import annotations
@@ -46,6 +56,10 @@ if TYPE_CHECKING:
from .risk import FileRisk
FileStatus = Literal["measured", "not_in_report", "no_line_data", "no_coverable_changes"]
+#: Whether the coverage read carries per-line branch counts: ``per_line`` it
+#: does, ``none`` the report has none, ``stored_before`` the stored rows were
+#: written before per-line branches were kept.
+BranchData = Literal["per_line", "none", "stored_before"]
GateStatus = Literal["pass", "fail", "no_data", "not_set", "too_small"]
@@ -60,6 +74,11 @@ class FilePatchCoverage:
covered_line_count: int = 0
# Inclusive (start, end) runs of changed, executable, unexecuted lines.
uncovered_ranges: tuple[tuple[int, int], ...] = ()
+ # Branches on the changed executable lines the report gives branch counts for.
+ branch_taken: int = 0
+ branch_total: int = 0
+ # Inclusive runs of changed lines that ran with fewer branches taken than they have.
+ partial_ranges: tuple[tuple[int, int], ...] = ()
# What history says about the file (``risk.attach_risk``); ``None`` unread.
risk: FileRisk | None = None
# Where to add a test per uncovered range (``hints.attach_hints``); ``None``
@@ -83,6 +102,9 @@ class FilePatchCoverage:
"covered_line_count": self.covered_line_count,
"patch_coverage_pct": _round(self.patch_coverage_pct),
"uncovered_ranges": [list(r) for r in self.uncovered_ranges],
+ "branch_taken": self.branch_taken,
+ "branch_total": self.branch_total,
+ "partial_ranges": [list(r) for r in self.partial_ranges],
"risk": self.risk.to_dict() if self.risk is not None else None,
"hints": None if self.hints is None else [h.to_dict() for h in self.hints],
}
@@ -112,6 +134,8 @@ class PatchScope:
# Invalid ``coverage.gates`` entries, one message each. The CLI refuses to
# run on them; read-only surfaces carry them and judge no path gate.
config_errors: tuple[str, ...] = ()
+ # Derived from the coverage by :func:`compute_patch_coverage` when unset.
+ branch_data: BranchData | None = None
def to_dict(self) -> dict[str, Any]:
return {
@@ -125,6 +149,7 @@ class PatchScope:
"freshness": self.freshness,
"ignored_file_count": self.ignored_file_count,
"config_errors": list(self.config_errors),
+ "branch_data": self.branch_data,
}
@@ -204,6 +229,8 @@ class PatchCoverage:
risky_threshold: float | None = None
# Project coverage at the change's base against its head (``delta``).
project: ProjectDelta | None = None
+ # The gate over branches on changed lines, judged apart from the line gates.
+ branch_threshold: float | None = None
@property
def changed_file_count(self) -> int:
@@ -236,18 +263,21 @@ class PatchCoverage:
@property
def gate(self) -> GateStatus:
- """``flat_gate``, or ``fail`` when a path-scoped, the risky-file or the project gate fails.
+ """``flat_gate``, or ``fail`` when a path-scoped, the risky-file, the branch or the
+ project gate fails.
- With no flat threshold the risky-file gate's status is the verdict, and
- with neither, the project gate's.
+ With no flat threshold the risky-file gate's status is the verdict, then
+ the branch gate's, then the project gate's.
"""
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):
+ # In precedence order; the first gate with a verdict decides.
+ verdicts = [self.flat_gate, self.risky_gate, self.branch_gate, project]
+ if self.failing_path_gates or "fail" in verdicts:
return "fail"
- for status in (self.flat_gate, self.risky_gate):
- if status != "not_set":
- return status
- return project
+ # An unapplied branch gate gives way to a project verdict.
+ if project != "not_set" and verdicts[2] == "no_data":
+ verdicts[2] = "not_set"
+ return next((v for v in verdicts if v != "not_set"), "not_set")
@property
def failing_path_gates(self) -> list[PathGateResult]:
@@ -285,6 +315,34 @@ class PatchCoverage:
self.small_change,
)
+ @property
+ def branch_taken(self) -> int:
+ return sum(f.branch_taken for f in self.with_status("measured"))
+
+ @property
+ def branch_total(self) -> int:
+ return sum(f.branch_total for f in self.with_status("measured"))
+
+ @property
+ def branch_pct(self) -> float | None:
+ """Taken share of the branches on changed lines; ``None`` when none carries any."""
+ return _pct(self.branch_taken, self.branch_total)
+
+ @property
+ def branch_gate(self) -> GateStatus:
+ """``branch_threshold`` over branches on changed lines, by the one gate rule.
+
+ Not measured is ``no_data``, never a failure. The whole change's
+ small-change tolerance applies, as it does to the line gate.
+ """
+ return _gate(
+ self.branch_threshold, self.branch_taken, self.branch_total, self.small_change
+ )
+
+ @property
+ def partial_line_count(self) -> int:
+ return sum(b - a + 1 for f in self.files for a, b in f.partial_ranges)
+
def with_status(self, status: FileStatus) -> list[FilePatchCoverage]:
return [f for f in self.files if f.status == status]
@@ -301,6 +359,19 @@ class PatchCoverage:
"gate": self.risky_gate,
}
+ def _branches_dict(self) -> dict[str, Any] | None:
+ # Null when no changed line carries branch data and no branch gate asked.
+ if not self.branch_total and self.branch_threshold is None:
+ return None
+ return {
+ "branch_taken": self.branch_taken,
+ "branch_total": self.branch_total,
+ "branch_coverage_pct": _round(self.branch_pct),
+ "partial_line_count": self.partial_line_count,
+ "threshold": self.branch_threshold,
+ "gate": self.branch_gate,
+ }
+
def to_dict(self) -> dict[str, Any]:
counts = {status: len(self.with_status(status)) for status in get_args(FileStatus)}
counts["out_of_scope"] = self.out_of_scope_count
@@ -317,6 +388,7 @@ class PatchCoverage:
"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,
+ "branches": self._branches_dict(),
}
@@ -344,6 +416,7 @@ def compute_patch_coverage(
"""
measured_suffixes = {PurePosixPath(p).suffix for p in report_paths or coverage}
ignore_spec = pathspec.PathSpec.from_lines("gitwildmatch", ignore)
+ scope = _with_branch_data(scope or PatchScope(), coverage)
files: list[FilePatchCoverage] = []
out_of_scope = ignored = 0
for path in sorted(changed):
@@ -360,7 +433,7 @@ def compute_patch_coverage(
files=tuple(files),
threshold=threshold,
out_of_scope_count=out_of_scope,
- scope=replace(scope or PatchScope(), ignored_file_count=ignored),
+ scope=replace(scope, ignored_file_count=ignored),
min_coverable_lines=min_coverable_lines,
)
small = pc.small_change
@@ -369,6 +442,14 @@ def compute_patch_coverage(
)
+def _with_branch_data(scope: PatchScope, coverage: Mapping[str, FileCoverage]) -> PatchScope:
+ """*scope* with ``branch_data`` derived from *coverage* when the caller left it unset."""
+ if scope.branch_data is not None:
+ return scope
+ per_line = any(fc.branch_lines for fc in coverage.values())
+ return replace(scope, branch_data="per_line" if per_line else "none")
+
+
def patch_coverage_from_resolved(
changed: Mapping[str, Iterable[int]],
resolved: ResolvedCoverage,
@@ -422,6 +503,8 @@ def _file_patch(path: str, lines: set[int], fc: FileCoverage) -> FilePatchCovera
if not coverable:
return FilePatchCoverage(path, "no_coverable_changes", len(lines))
covered = coverable.intersection(fc.covered_lines)
+ branched = {n: fc.branch_lines[n] for n in coverable if n in fc.branch_lines}
+ partial = (n for n, (taken, total) in branched.items() if n in covered and taken < total)
return FilePatchCoverage(
path,
"measured",
@@ -429,6 +512,9 @@ def _file_patch(path: str, lines: set[int], fc: FileCoverage) -> FilePatchCovera
coverable_line_count=len(coverable),
covered_line_count=len(covered),
uncovered_ranges=line_ranges(coverable - covered),
+ branch_taken=sum(taken for taken, _ in branched.values()),
+ branch_total=sum(total for _, total in branched.values()),
+ partial_ranges=line_ranges(partial),
)
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 78e3b07c3..9cb4711cd 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/render.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/render.py
@@ -5,7 +5,9 @@ written to be read once and acted on: the verdict in words on the first line
with its denominator, the diff, report and file counts on the second, and
detail only for what needs attention. A passing change with no gaps is two
lines. A file the report never named reads "not in report", never 0%. With
-an index, each gap names the test to extend (``hints``).
+an index, each gap names the test to extend (``hints``). Branches on changed
+lines get their own line, and a "Partly taken" column lists changed lines
+that ran with a branch never taken, only when there is one.
Workflow-command and markdown mechanics (escaping, caps, collapsed lists)
come from :mod:`repowise.core.ci`, shared with every other CI gate.
@@ -14,7 +16,7 @@ come from :mod:`repowise.core.ci`, shared with every other CI gate.
from __future__ import annotations
import math
-from collections.abc import Sequence
+from collections.abc import Callable, Sequence
from ...ci import github
from ...ci.markdown import ROW_LIMIT, cell, details, more_line, plural
@@ -152,6 +154,44 @@ def risky_line(pc: PatchCoverage, *, markdown: bool = True) -> str:
)
+def branch_line(pc: PatchCoverage, *, markdown: bool = True) -> str:
+ """Branches on changed lines, or ``""`` when not measured and no branch gate asked.
+
+ Unmeasured, it says why: coverage with no per-line branch data (a setup
+ problem), or a change with no branching line (nothing to judge).
+ """
+ pct = pc.branch_pct
+ if pct is None:
+ if pc.branch_threshold is None:
+ return ""
+ reason = _BRANCH_UNMEASURED[pc.scope.branch_data or "none"]
+ return (
+ f"Branches on changed lines: {reason}. The "
+ f"{fmt_pct(pc.branch_threshold)} branch gate was not applied."
+ )
+ bold = "**" if markdown else ""
+ text = (
+ f"{bold}Branches on changed lines {fmt_pct(pct)}{bold} ({pc.branch_taken} of "
+ f"{pc.branch_total} taken"
+ )
+ if n := pc.partial_line_count:
+ text += f"; {plural(n, 'line')} partly taken"
+ return text + ")" + _gate_suffix(
+ pc.branch_gate, pc.branch_threshold, pc.min_coverable_lines, "branch gate"
+ )
+
+
+#: Why no changed line has a branch figure, by ``scope.branch_data``.
+_BRANCH_UNMEASURED = {
+ "none": "not measured (the coverage report has no per-line branch data)",
+ "stored_before": (
+ "not measured (the stored coverage predates per-line branch data; "
+ "re-run `repowise coverage add`)"
+ ),
+ "per_line": "no changed executable line has branches",
+}
+
+
def risk_order_key(f: FilePatchCoverage) -> tuple:
"""Risky first, then fix pressure, then dependents, then uncovered lines."""
risk = f.risk or FileRisk()
@@ -232,12 +272,17 @@ def scope_line(pc: PatchCoverage, *, markdown: bool = True) -> str:
def attention_rows(pc: PatchCoverage) -> list[FilePatchCoverage]:
- """Files a reader should look at: uncovered changes first, then unmeasurable ones.
+ """Files a reader should look at: uncovered changes first, then files whose only
+ gap is a partly taken branch, then unmeasurable ones.
- Within each group the riskiest file leads (:func:`risk_order_key`).
+ Within each group the riskiest file leads (:func:`risk_order_key`), the
+ order the annotations use.
"""
- gaps = sorted(
- (f for f in pc.with_status("measured") if f.uncovered_line_count), key=risk_order_key
+ measured = pc.with_status("measured")
+ gaps = sorted((f for f in measured if f.uncovered_line_count), key=risk_order_key)
+ gaps += sorted(
+ (f for f in measured if f.partial_ranges and not f.uncovered_line_count),
+ key=risk_order_key,
)
unmeasured = sorted(
pc.with_status("not_in_report") + pc.with_status("no_line_data"),
@@ -253,6 +298,8 @@ def render_markdown(pc: PatchCoverage) -> str:
out += ["", project]
if risky := risky_line(pc):
out += ["", risky]
+ if branches := branch_line(pc):
+ out += ["", branches]
out += ["", scope_line(pc)]
if basis := risk_basis_line(pc):
out += ["", basis + "."]
@@ -278,7 +325,8 @@ def _path_gate_table(pc: PatchCoverage) -> list[str]:
def _gap_table(pc: PatchCoverage) -> list[str]:
- """Files with uncovered changed lines, riskiest first; a Risk column once risk is read."""
+ """Files with uncovered or partly taken changed lines, riskiest first; a Risk column
+ once risk is read."""
gaps = [f for f in attention_rows(pc) if f.status == "measured"]
if not gaps:
return []
@@ -289,27 +337,44 @@ def _gap_table(pc: PatchCoverage) -> list[str]:
def _gap_rows(pc: PatchCoverage, rows: list[FilePatchCoverage]) -> list[str]:
- """The uncovered-lines table; Risk and Extend columns only when something fills them."""
- with_risk = any(f.risk is not None for f in pc.files)
- with_hint = any(f.hints for f in rows)
- head = ["File", *(["Risk"] if with_risk else []), "Uncovered changed lines", "Covered"]
- head += ["Extend"] if with_hint else []
- lines = ["| " + " | ".join(head) + " |", "|" + "---|" * len(head)]
+ """The uncovered-lines table, one column per :func:`_gap_columns` entry."""
+ columns = _gap_columns(pc, rows)
+ lines = [
+ "| " + " | ".join(name for name, _ in columns) + " |",
+ "|" + "---|" * len(columns),
+ ]
for f in rows:
- cells = [f"`{cell(f.file_path)}`"]
- cells += [cell(risk_words(f.risk))] if with_risk else []
- cells += [
- format_ranges(f.uncovered_ranges, RANGE_LIMIT),
- f"{f.covered_line_count} of {f.coverable_line_count}",
- ]
- if with_hint:
- hint = first_hint(f)
- # The phrase's backticks are code spans; everything between is escaped.
- cells.append("`".join(cell(p) for p in hint_phrase(hint).split("`")) if hint else "")
- lines.append("| " + " | ".join(cells) + " |")
+ lines.append("| " + " | ".join(fill(f) for _, fill in columns) + " |")
return lines
+_GapColumn = tuple[str, Callable[[FilePatchCoverage], str]]
+
+
+def _gap_columns(pc: PatchCoverage, rows: list[FilePatchCoverage]) -> list[_GapColumn]:
+ """``(header, cell)`` per column; Risk, Partly taken and Extend only when filled."""
+ columns: list[_GapColumn] = [("File", lambda f: f"`{cell(f.file_path)}`")]
+ if any(f.risk is not None for f in pc.files):
+ columns.append(("Risk", lambda f: cell(risk_words(f.risk))))
+ columns.append(
+ ("Uncovered changed lines", lambda f: format_ranges(f.uncovered_ranges, RANGE_LIMIT))
+ )
+ if pc.partial_line_count > 0:
+ columns.append(("Partly taken", lambda f: format_ranges(f.partial_ranges, RANGE_LIMIT)))
+ columns.append(("Covered", lambda f: f"{f.covered_line_count} of {f.coverable_line_count}"))
+ if any(f.hints for f in rows):
+ columns.append(("Extend", _extend_cell))
+ return columns
+
+
+def _extend_cell(f: FilePatchCoverage) -> str:
+ hint = first_hint(f)
+ if hint is None:
+ return ""
+ # The phrase's backticks are code spans; everything between is escaped.
+ return "`".join(cell(p) for p in hint_phrase(hint).split("`"))
+
+
#: Warning slots kept for coverage lost outside the change; unused ones go to ranges.
OUTSIDE_RESERVE = 3
@@ -320,8 +385,10 @@ def github_annotations(pc: PatchCoverage) -> list[str]:
A failed gate is an error, and so is each failing path-scoped gate that is
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, sharing what GitHub displays with a warning per
+ a notice, so neither is silent; the branch gate reads the same way, and a
+ branch gate that was set but not applied is a notice too.
+ Uncovered ranges are marked riskiest file first, then largest range, then
+ each partly taken branch 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.
"""
@@ -330,11 +397,20 @@ def github_annotations(pc: PatchCoverage) -> list[str]:
key=lambda r: (*risk_order_key(r[0])[:3], r[1] - r[2], r[0].file_path, r[1]),
)
warnings = [_range_annotation(f, a, b) for f, a, b in ranges]
+ # Partly taken branches after every uncovered range: a line that never ran is worse.
+ warnings += [
+ _partial_annotation(f, a, b)
+ for f in sorted(pc.with_status("measured"), key=risk_order_key)
+ for a, b in f.partial_ranges
+ ]
verdict = [
*_gate_annotations(pc.flat_gate, _flat_headline(pc, markdown=False)),
*_path_gate_annotations(pc),
*_gate_annotations(pc.risky_gate, risky_line(pc, markdown=False)),
+ *_gate_annotations(pc.branch_gate, branch_line(pc, markdown=False)),
]
+ if pc.branch_threshold is not None and pc.branch_gate == "no_data":
+ verdict.append(github.notice(branch_line(pc, markdown=False)))
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)]
@@ -380,6 +456,17 @@ def _range_annotation(f: FilePatchCoverage, a: int, b: int) -> str:
)
+def _partial_annotation(f: FilePatchCoverage, a: int, b: int) -> str:
+ return github.annotation(
+ "warning",
+ f"Changed {_span(a, b)} ran, but not every branch was taken by tests",
+ file=f.file_path,
+ line=a,
+ end_line=b,
+ title="Partly taken branch",
+ )
+
+
def _hint_for(f: FilePatchCoverage, a: int, b: int) -> TestHint | None:
"""The hint for range ``(a, b)``, when the index gave one."""
return next((h for h in f.hints or () if h.range == (a, b)), None)
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 1b784f990..1699df654 100644
--- a/packages/core/src/repowise/core/analysis/patch_coverage/stored.py
+++ b/packages/core/src/repowise/core/analysis/patch_coverage/stored.py
@@ -16,7 +16,7 @@ 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 .compute import BranchData, PatchCoverage, PatchScope, compute_patch_coverage
from .delta import ProjectDelta, ProjectTotals, incomparable_reasons
from .risk import IndexFacts
@@ -91,10 +91,27 @@ async def stored_patch_coverage(
measured_commit=commit,
freshness=freshness,
config_errors=cfg.gate_errors,
+ branch_data=await _stored_branch_data(session, repository_id, rows),
),
)
+async def _stored_branch_data(
+ session: AsyncSession, repository_id: str, rows: list[Any]
+) -> BranchData:
+ """Whether the stored rows keep per-line branch counts, and if not, why.
+
+ Rows with a file-level branch figure but no per-line counts predate them.
+ Ceiling: a report that states only file-level figures reads the same way.
+ """
+ from repowise.core.persistence.crud import has_branch_lines
+
+ if await has_branch_lines(session, repository_id):
+ return "per_line"
+ legacy = any(row.branch_coverage_pct is not None for row in rows)
+ return "stored_before" if legacy else "none"
+
+
async def attach_history_delta(
session: AsyncSession, repository_id: str, pc: PatchCoverage, base_commit: str | None
) -> PatchCoverage:
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 7c316d3b0..bd4536ed3 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -23,6 +23,7 @@ from .coverage import (
empty_coverage_summary,
file_coverage_from_row,
get_coverage_summary,
+ has_branch_lines,
load_coverage_for_repo,
load_coverage_history,
load_coverage_map,
@@ -167,6 +168,7 @@ __all__ = [
"get_scored_file_paths",
"get_symbol_names",
"get_test_coverage_summary",
+ "has_branch_lines",
"is_new_doc_drift_row",
"list_evidence_for_opportunities",
"list_health_snapshots",
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 14c4cf614..1225cd160 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/coverage.py
@@ -241,11 +241,14 @@ def _row_columns(f: Any) -> dict[str, Any]:
"total_coverable_lines": int(f.total_coverable_lines or 0),
"covered_line_count": _covered_count(f),
"coverable_lines_json": json.dumps(list(getattr(f, "coverable_lines", None) or [])),
+ "branch_lines_json": _branch_json(getattr(f, "branch_lines", None)),
}
data = dict(f)
for key in ("covered_lines", "coverable_lines"):
if key in data:
data[f"{key}_json"] = json.dumps(list(data.pop(key) or []))
+ if "branch_lines" in data:
+ data["branch_lines_json"] = _branch_json(data.pop("branch_lines"))
columns = {
k: v for k, v in data.items() if k not in _INGEST_COLUMNS and hasattr(CoverageFile, k)
}
@@ -256,8 +259,8 @@ def _row_columns(f: Any) -> dict[str, Any]:
return columns
-#: Every column of ``CoverageFile`` except the two line-set blobs
-#: (``covered_lines_json``, ``coverable_lines_json``). They dominate the table:
+#: Every column of ``CoverageFile`` except the per-line blobs (``covered_lines_json``,
+#: ``coverable_lines_json``, ``branch_lines_json``). They dominate the table:
#: the covered set alone was 467 KB of the 549 KB stored for this repo's 1,401
#: rows, and only line-level readers need them.
_COVERAGE_SCALAR_COLUMNS = (
@@ -303,10 +306,10 @@ async def load_coverage_for_repo(
"""Coverage rows for a repo, optionally scoped to *file_paths*.
``include_covered_lines=False`` returns ``Row`` objects carrying every
- column except the two line-set blobs. They are attribute-accessed exactly
- like the ORM entities, so a caller that reads named fields needs no change
- — but a caller that touches ``covered_lines_json`` or
- ``coverable_lines_json`` must ask for them.
+ column except the per-line blobs. They are attribute-accessed exactly
+ like the ORM entities, so a caller that reads named fields needs no change,
+ but a caller that touches ``covered_lines_json``,
+ ``coverable_lines_json`` or ``branch_lines_json`` must ask for them.
"""
q = (
select(CoverageFile)
@@ -321,6 +324,21 @@ async def load_coverage_for_repo(
return list(result.all())
+def _branch_json(lines: dict | None) -> str | None:
+ """``{"line": [taken, total]}`` compact, ``None`` when there is no per-line branch data."""
+ if not lines:
+ return None
+ return json.dumps({str(k): list(v) for k, v in lines.items()}, separators=(",", ":"))
+
+
+def _branch_lines(raw: str | None) -> dict[int, tuple[int, int]]:
+ try:
+ data = json.loads(raw) if raw else {}
+ return {int(k): (int(v[0]), int(v[1])) for k, v in data.items()}
+ except (ValueError, TypeError, AttributeError, IndexError):
+ return {}
+
+
def _line_list(raw: str | None) -> list[int]:
try:
return [int(n) for n in json.loads(raw)] if raw else []
@@ -407,6 +425,7 @@ def file_coverage_from_row(row: Any) -> FileCoverage:
total_coverable_lines=row.total_coverable_lines or 0,
coverable_lines=_line_list(getattr(row, "coverable_lines_json", None)),
covered_line_count=getattr(row, "covered_line_count", None),
+ branch_lines=_branch_lines(getattr(row, "branch_lines_json", None)),
)
@@ -421,6 +440,19 @@ async def load_file_coverage(
return {row.file_path: file_coverage_from_row(row) for row in rows}
+async def has_branch_lines(session: AsyncSession, repository_id: str) -> bool:
+ """Whether any stored row keeps per-line branch counts."""
+ found = await session.scalar(
+ select(CoverageFile.id)
+ .where(
+ CoverageFile.repository_id == repository_id,
+ CoverageFile.branch_lines_json.is_not(None),
+ )
+ .limit(1)
+ )
+ return found is not None
+
+
async def load_coverage_map(session: AsyncSession, repository_id: str) -> dict[str, dict]:
"""Stored coverage in the shape ``HealthAnalyzer`` takes as ``coverage_map``."""
from repowise.core.analysis.health.coverage.model import coverage_map_entry
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 19f67512d..fc2db694f 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -2215,6 +2215,9 @@ class CoverageFile(Base):
# tell an uncovered changed line from a changed comment. "[]" means the
# report did not say (or the row predates the column), never "none".
coverable_lines_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
+ # Branches per line, ``{"line": [taken, total]}``. NULL when the report
+ # carried no per-line branch data (or the row predates the column).
+ branch_lines_json: Mapped[str | None] = mapped_column(Text, nullable=True)
# True when the ingest that wrote these rows mapped fewer than half of the
# report's files to the repo tree (severe path-mapping loss). The rows are
# still written — a partial report is better than none — but consumers
diff --git a/packages/server/src/repowise/server/mcp_server/_change_health.py b/packages/server/src/repowise/server/mcp_server/_change_health.py
index 3519f2d04..c9bf32df3 100644
--- a/packages/server/src/repowise/server/mcp_server/_change_health.py
+++ b/packages/server/src/repowise/server/mcp_server/_change_health.py
@@ -86,7 +86,7 @@ def _render_action(action: ReviewAction, inspected: int) -> str | None:
def patch_coverage_action(block: dict[str, Any] | None) -> str | None:
- """The next action for uncovered changed lines, or ``None`` when there are none.
+ """The next action for uncovered changed lines (else partly taken ones), ``None`` without.
Names the scope and the tests to extend from the rows' hints, riskiest
file first, so the agent writes the missing test where the suite already
@@ -94,7 +94,7 @@ def patch_coverage_action(block: dict[str, Any] | None) -> str | None:
"""
uncovered = block["coverable_line_count"] - block["covered_line_count"] if block else 0
if uncovered <= 0:
- return None
+ return _partial_action(block)
lines = f"{uncovered} changed executable line{'' if uncovered == 1 else 's'}"
lines += _scope_words(block["scope"].get("label") or "")
if block["scope"]["freshness"] == "stale":
@@ -111,6 +111,24 @@ def patch_coverage_action(block: dict[str, Any] | None) -> str | None:
return text + "add tests for them (patch_coverage.files)"
+def _partial_action(block: dict[str, Any] | None) -> str | None:
+ """The next action when every changed line ran but some took only part of their branches."""
+ partial = _partial_line_count(block)
+ if not partial or block["scope"]["freshness"] == "stale":
+ return None
+ lines = f"{partial} changed line{'' if partial == 1 else 's'}"
+ lines += _scope_words(block["scope"].get("label") or "")
+ return (
+ f"{lines} ran with a branch no test took; add tests for the other way through "
+ "(patch_coverage.files[].partial_ranges)"
+ )
+
+
+def _partial_line_count(block: dict[str, Any] | None) -> int:
+ branches = (block or {}).get("branches") or {}
+ return branches.get("partial_line_count") or 0
+
+
def _hinted_tests(rows: list[dict[str, Any]]) -> list[str]:
"""Each hint's first test, in row order (riskiest file first), once each."""
firsts = (hint["tests"][0] for row in rows for hint in row.get("hints") or () if hint["tests"])
diff --git a/packages/server/src/repowise/server/schemas/patch_coverage.py b/packages/server/src/repowise/server/schemas/patch_coverage.py
index 58cfde104..bef710690 100644
--- a/packages/server/src/repowise/server/schemas/patch_coverage.py
+++ b/packages/server/src/repowise/server/schemas/patch_coverage.py
@@ -9,7 +9,7 @@ from __future__ import annotations
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.compute import BranchData, FileStatus, GateStatus
from repowise.core.analysis.patch_coverage.delta import (
CauseBasis,
CauseKind,
@@ -67,6 +67,13 @@ class PatchCoverageFile(_Strict):
patch_coverage_pct: float | None
#: Inclusive ``[start, end]`` runs of changed, executable, unexecuted lines.
uncovered_ranges: list[list[int]]
+ #: Branches on the changed executable lines the report gives branch counts
+ #: for; both 0 without branch data.
+ branch_taken: int
+ branch_total: int
+ #: Inclusive ``[start, end]`` runs of changed lines that ran with fewer
+ #: branches taken than they have; empty without branch data.
+ partial_ranges: list[list[int]]
#: Null when the file's risk was not assessed.
risk: PatchCoverageFileRisk | None
#: One per uncovered range (the first eight); null without an index.
@@ -99,6 +106,9 @@ class PatchCoverageScope(_Strict):
#: Invalid ``coverage.gates`` entries, one message each; while any is
#: present no path-scoped gate is judged.
config_errors: list[str]
+ #: ``per_line`` when the coverage carries per-line branch counts; ``none``
+ #: or ``stored_before`` (stored rows predate them) when it does not.
+ branch_data: BranchData | None
class PatchCoveragePathGate(_Strict):
@@ -134,6 +144,21 @@ class PatchCoverageRisky(_Strict):
gate: GateStatus
+class PatchCoverageBranches(_Strict):
+ """Branches on changed lines, reported beside patch coverage, never blended into it."""
+
+ branch_taken: int
+ branch_total: int
+ #: 0-100, floored to two decimals; null when no changed line has branch data.
+ branch_coverage_pct: float | None
+ #: Changed lines that ran with fewer branches taken than they have.
+ partial_line_count: int
+ threshold: float | None
+ #: ``no_data`` when no changed line has branch data; ``too_small`` under the
+ #: whole change's small-change tolerance.
+ gate: GateStatus
+
+
class PatchCoverageProjectTotals(_Strict):
covered_line_count: int
coverable_line_count: int
@@ -200,7 +225,7 @@ class PatchCoverageResponse(_Strict):
#: missed threshold reads ``too_small`` and does not fail.
min_coverable_lines: int | None
#: Fails when the flat gate, a path-scoped gate that is not informational,
- #: or the risky-file gate fails.
+ #: the risky-file, the branch or the max-drop gate fails.
gate: GateStatus
file_counts: PatchCoverageFileCounts
files: list[PatchCoverageFile]
@@ -211,3 +236,5 @@ class PatchCoverageResponse(_Strict):
risky: PatchCoverageRisky | None
#: Null when no ingest was measured at the change's base.
project: PatchCoverageProject | None
+ #: Null when no changed line has per-line branch data and no branch gate was set.
+ branches: PatchCoverageBranches | None
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 795994337..de31b3bbf 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -2294,6 +2294,16 @@ export interface Paginated_SymbolResponse_ {
next_offset?: number | null;
}
+/** Branches on changed lines, reported beside patch coverage, never blended into it. */
+export interface PatchCoverageBranches {
+ branch_taken: number;
+ branch_total: number;
+ branch_coverage_pct: number | null;
+ partial_line_count: number;
+ threshold: number | null;
+ gate: "pass" | "fail" | "no_data" | "not_set" | "too_small";
+}
+
export interface PatchCoverageFile {
file_path: string;
status: "measured" | "not_in_report" | "no_line_data" | "no_coverable_changes";
@@ -2302,6 +2312,9 @@ export interface PatchCoverageFile {
covered_line_count: number;
patch_coverage_pct: number | null;
uncovered_ranges: number[][];
+ branch_taken: number;
+ branch_total: number;
+ partial_ranges: number[][];
risk: PatchCoverageFileRisk | null;
hints: PatchCoverageTestHint[] | null;
}
@@ -2391,6 +2404,7 @@ export interface PatchCoverageResponse {
path_gates: PatchCoveragePathGate[];
risky: PatchCoverageRisky | null;
project: PatchCoverageProject | null;
+ branches: PatchCoverageBranches | null;
}
/** Patch coverage over the measured files history marks as risky. */
@@ -2414,6 +2428,7 @@ export interface PatchCoverageScope {
freshness: "current" | "stale" | "unknown";
ignored_file_count: number;
config_errors: string[];
+ branch_data: "per_line" | "none" | "stored_before" | null;
}
/** Where to extend the tests for one uncovered range. */
diff --git a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx b/packages/ui/__tests__/health/patch-coverage-summary.test.tsx
index 3b91647ec..7253ec7b4 100644
--- a/packages/ui/__tests__/health/patch-coverage-summary.test.tsx
+++ b/packages/ui/__tests__/health/patch-coverage-summary.test.tsx
@@ -7,6 +7,7 @@ import type {
} from "@repowise-dev/types/generated/http";
import {
PatchCoverageSummary,
+ branchText,
floorPct,
formatLineRanges,
hintReason,
@@ -37,6 +38,9 @@ function coverage(fileCount: number): PatchCoverageResponse {
covered_line_count: 1,
patch_coverage_pct: 50,
uncovered_ranges: [[i + 1, i + 1]],
+ branch_taken: 0,
+ branch_total: 0,
+ partial_ranges: [],
risk: null,
hints: null,
})),
@@ -51,10 +55,12 @@ function coverage(fileCount: number): PatchCoverageResponse {
freshness: "current",
ignored_file_count: 0,
config_errors: [],
+ branch_data: "none",
},
path_gates: [],
risky: null,
project: null,
+ branches: null,
};
}
@@ -193,6 +199,46 @@ describe("PatchCoverageSummary", () => {
expect(screen.getByText("and 2 more")).toBeTruthy();
});
+ it("reports branches on changed lines and lists partly taken files after uncovered ones", () => {
+ const base = coverage(2);
+ const [uncovered, file] = base.files;
+ const branches = {
+ branch_taken: 3,
+ branch_total: 4,
+ branch_coverage_pct: 75,
+ partial_line_count: 1,
+ threshold: null,
+ gate: "not_set" as const,
+ };
+ const { container } = render(
+ <PatchCoverageSummary
+ coverage={{
+ ...base,
+ files: [
+ uncovered!,
+ {
+ ...file!,
+ // Sorts first by path, but a partly taken branch comes after an uncovered line.
+ file_path: "src/a.ts",
+ uncovered_ranges: [],
+ branch_taken: 3,
+ branch_total: 4,
+ partial_ranges: [[12, 12]],
+ },
+ ],
+ branches,
+ }}
+ />,
+ );
+ expect(
+ screen.getByText("Branches on changed lines 75.0% · 3 of 4 taken · 1 line partly taken"),
+ ).toBeTruthy();
+ expect(listedPaths(container)).toEqual(["src/f0.ts", "src/a.ts"]);
+ expect(screen.getByText("partly taken 12")).toBeTruthy();
+ // Not measured is no line at all, never 0%.
+ expect(branchText({ ...branches, branch_coverage_pct: null })).toBeNull();
+ });
+
it("states the denominator and stays quiet when coverage is current", () => {
render(<PatchCoverageSummary coverage={coverage(1)} />);
expect(screen.getByText("1 of 2 changed executable lines covered")).toBeTruthy();
@@ -218,6 +264,9 @@ describe("PatchCoverageSummary", () => {
[3, 3],
[7, 9],
],
+ branch_taken: 0,
+ branch_total: 0,
+ partial_ranges: [],
risk: null,
hints: null,
},
@@ -229,6 +278,9 @@ describe("PatchCoverageSummary", () => {
covered_line_count: 0,
patch_coverage_pct: null,
uncovered_ranges: [],
+ branch_taken: 0,
+ branch_total: 0,
+ partial_ranges: [],
risk: null,
hints: null,
},
diff --git a/packages/ui/src/health/patch-coverage-summary.tsx b/packages/ui/src/health/patch-coverage-summary.tsx
index b9e7ccbd8..384b941e5 100644
--- a/packages/ui/src/health/patch-coverage-summary.tsx
+++ b/packages/ui/src/health/patch-coverage-summary.tsx
@@ -18,10 +18,16 @@
* 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.
+ *
+ * When the report carries per-line branch data, one line gives the share of
+ * branches taken on changed lines, beside the line figure and never blended
+ * into it, and a file row also names its "partly taken" lines: changed lines
+ * that ran with some branch never taken. Those rows follow the uncovered ones.
*/
import type { ReactNode } from "react";
import type {
+ PatchCoverageBranches,
PatchCoverageFile,
PatchCoverageFileRisk,
PatchCoveragePathGate,
@@ -175,6 +181,8 @@ export function PatchCoverageSummary({
{/* Guarded: a server older than the project delta sends no field. */}
<ProjectLine project={coverage.project ?? null} />
<RiskyLine risky={coverage.risky} />
+ {/* Guarded: a server older than branch coverage sends no field. */}
+ <BranchLine branches={coverage.branches ?? null} />
<ScopeNotes coverage={coverage} />
{/* Guarded: a server older than path-scoped gates sends neither field. */}
<PathGates
@@ -187,11 +195,31 @@ export function PatchCoverageSummary({
);
}
-/** Measured files with uncovered changed lines, riskiest first. */
+/** A server older than branch coverage sends no `partial_ranges`. */
+function partialRanges(file: PatchCoverageFile): number[][] {
+ return file.partial_ranges ?? [];
+}
+
+/** Measured files with uncovered lines, then those whose only gap is a partly
+ * taken branch, each riskiest first: the core's order. */
function uncoveredFiles(files: PatchCoverageFile[]): PatchCoverageFile[] {
+ const rank = (f: PatchCoverageFile) => Number(f.uncovered_ranges.length === 0);
return files
- .filter((f) => f.status === "measured" && f.uncovered_ranges.length > 0)
- .sort(byRisk);
+ .filter(
+ (f) =>
+ f.status === "measured" &&
+ (f.uncovered_ranges.length > 0 || partialRanges(f).length > 0),
+ )
+ .sort((a, b) => rank(a) - rank(b) || byRisk(a, b));
+}
+
+/** `lines 3, 7-9 · partly taken 12`: the uncovered runs, then the partly taken ones. */
+function gapText(file: PatchCoverageFile): string {
+ const parts = [];
+ if (file.uncovered_ranges.length) parts.push(`lines ${formatLineRanges(file.uncovered_ranges)}`);
+ const partial = partialRanges(file);
+ if (partial.length) parts.push(`partly taken ${formatLineRanges(partial)}`);
+ return parts.join(" · ");
}
/** Not-in-report files before those without line data, then by risk: the core's order. */
@@ -291,6 +319,22 @@ function RiskyLine({ risky }: { risky: PatchCoverageResponse["risky"] | undefine
);
}
+/** Only when a changed line has branch data: not measured is no line, never 0%. */
+export function branchText(branches: PatchCoverageBranches): string | null {
+ const pct = branches.branch_coverage_pct;
+ if (pct == null) return null;
+ const partial = branches.partial_line_count
+ ? ` · ${plural(branches.partial_line_count, "line")} partly taken`
+ : "";
+ return `Branches on changed lines ${floorPct(pct)}% · ${branches.branch_taken} of ${branches.branch_total} taken${partial}`;
+}
+
+function BranchLine({ branches }: { branches: PatchCoverageBranches | null }) {
+ const text = branches == null ? null : branchText(branches);
+ if (text == null) return null;
+ return <p className="text-xs tabular-nums text-[var(--color-text-secondary)]">{text}</p>;
+}
+
/** What to read the figures with: stale or partial evidence, ignored files, risk basis. */
function ScopeNotes({ coverage }: { coverage: PatchCoverageResponse }) {
const { scope } = coverage;
@@ -429,7 +473,7 @@ function UncoveredList({
<FileRow
key={f.file_path}
file={f}
- trailing={`lines ${formatLineRanges(f.uncovered_ranges)}`}
+ trailing={gapText(f)}
hint={firstHint(f)}
onOpenFile={onOpenFile}
/>
diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsx
index 0742df19d..6929db1ec 100644
--- a/packages/vscode/webview/src/views/risk/App.test.tsx
+++ b/packages/vscode/webview/src/views/risk/App.test.tsx
@@ -90,6 +90,9 @@ const PATCH_COVERAGE: NonNullable<RiskRangeReport["patchCoverage"]> = {
[3, 3],
[7, 9],
],
+ branch_taken: 0,
+ branch_total: 0,
+ partial_ranges: [],
risk: {
fix_pressure: 2,
dependents: 5,
@@ -117,6 +120,9 @@ const PATCH_COVERAGE: NonNullable<RiskRangeReport["patchCoverage"]> = {
covered_line_count: 0,
patch_coverage_pct: null,
uncovered_ranges: [],
+ branch_taken: 0,
+ branch_total: 0,
+ partial_ranges: [],
risk: null,
hints: null,
},
@@ -130,6 +136,7 @@ const PATCH_COVERAGE: NonNullable<RiskRangeReport["patchCoverage"]> = {
gate: "not_set",
},
project: null,
+ branches: null,
scope: {
label: "coverage.xml",
source_formats: ["cobertura"],
@@ -141,6 +148,7 @@ const PATCH_COVERAGE: NonNullable<RiskRangeReport["patchCoverage"]> = {
freshness: "stale",
ignored_file_count: 0,
config_errors: [],
+ branch_data: "none",
},
path_gates: [
{
diff --git a/tests/fixtures/coverage/sample.clover-counts.xml b/tests/fixtures/coverage/sample.clover-counts.xml
new file mode 100644
index 000000000..ab5d8dca9
--- /dev/null
+++ b/tests/fixtures/coverage/sample.clover-counts.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<coverage generated="1700000000000" clover="3.2.0">
+ <project timestamp="1700000000000" name="All files">
+ <metrics statements="4" coveredstatements="3" conditionals="6" coveredconditionals="3" methods="1" coveredmethods="1" elements="11" coveredelements="7" complexity="0" loc="4" ncloc="4" packages="1" files="1" classes="1"/>
+ <file name="util.ts" path="/work/app/src/util.ts">
+ <metrics statements="4" coveredstatements="3" conditionals="6" coveredconditionals="3" methods="1" coveredmethods="1"/>
+ <line num="1" count="3" type="stmt"/>
+ <line num="2" count="3" type="cond" truecount="1" falsecount="3"/>
+ <line num="3" count="2" type="cond" truecount="2" falsecount="0"/>
+ <line num="4" count="0" type="stmt"/>
+ </file>
+ </project>
+</coverage>
diff --git a/tests/unit/analysis/test_patch_coverage_branches.py b/tests/unit/analysis/test_patch_coverage_branches.py
new file mode 100644
index 000000000..e8f845646
--- /dev/null
+++ b/tests/unit/analysis/test_patch_coverage_branches.py
@@ -0,0 +1,279 @@
+"""Branch coverage on changed lines: per-line branch data from each parser to the gate."""
+
+from __future__ import annotations
+
+from dataclasses import replace
+from pathlib import Path
+
+from repowise.core.analysis.health.coverage import (
+ file_coverage,
+ parse_clover,
+ parse_cobertura,
+ parse_go_coverprofile,
+ parse_jacoco,
+ parse_lcov,
+ resolve_reports,
+)
+from repowise.core.analysis.patch_coverage import (
+ ProjectDelta,
+ ProjectTotals,
+ attention_rows,
+ branch_line,
+ compute_patch_coverage,
+ github_annotations,
+ headline,
+ render_markdown,
+)
+
+FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "coverage"
+
+
+def _files(report) -> dict:
+ return {f.file_path: f for f in report.files}
+
+
+def _read(name: str) -> str:
+ return (FIXTURES / name).read_text(encoding="utf-8")
+
+
+def test_lcov_groups_brda_by_line_and_never_evaluated_is_not_taken() -> None:
+ text = (
+ "SF:a.py\nDA:3,1\nDA:5,0\nDA:7,1\n"
+ "BRDA:3,0,0,2\nBRDA:3,0,1,0\n" # one of two taken
+ "BRDA:5,0,0,-\nBRDA:5,0,1,-\n" # the line never ran
+ "BRDA:7,0,0,1\nBRDA:7,0,1,4\n" # both taken
+ "end_of_record\n"
+ )
+ (a,) = parse_lcov(text).files
+
+ assert a.branch_lines == {3: (1, 2), 5: (0, 2), 7: (2, 2)}
+ assert a.branch_coverage_pct == 50.0 # file-level figure unchanged
+
+
+def test_cobertura_reads_condition_coverage_per_line() -> None:
+ foo = _files(parse_cobertura(_read("sample.cobertura.xml")))["src/foo.py"]
+ assert foo.branch_lines == {3: (1, 2)}
+
+
+def test_cobertura_takes_the_max_of_a_line_repeated_across_classes() -> None:
+ line = '<line number="3" hits="1" branch="true" condition-coverage="{}"/>'
+ text = (
+ "<coverage><packages><package><classes>"
+ f'<class filename="a.py"><lines>{line.format("50% (1/2)")}</lines></class>'
+ f'<class filename="a.py"><lines>{line.format("100% (2/2)")}</lines></class>'
+ "</classes></package></packages></coverage>"
+ )
+ (a,) = parse_cobertura(text).files
+
+ assert a.branch_lines == {3: (2, 2)}
+ assert a.branch_coverage_pct == 100.0 # never summed to 3 of 4
+
+
+def test_jacoco_counts_covered_and_missed_branches_and_merges_groups() -> None:
+ bar = _files(parse_jacoco(_read("sample.jacoco.xml")))["com/foo/Bar.java"]
+ # Line 7: 0 of 2 in one group, 1 of 2 in the other: the max.
+ assert bar.branch_lines == {5: (1, 2), 7: (1, 2)}
+
+
+def test_clover_evaluation_counts_give_two_branches_a_line() -> None:
+ # truecount / falsecount are how often the condition was true / false.
+ y = _files(parse_clover(_read("sample.clover.xml")))["src/y.ts"]
+ assert y.branch_lines == {3: (1, 2)}
+ assert y.branch_coverage_pct == 50.0
+
+
+def test_clover_branch_counts_read_covered_and_not_covered() -> None:
+ # A report marked by its fixed project name and root version: truecount is
+ # branches covered, falsecount branches not covered.
+ (util,) = parse_clover(_read("sample.clover-counts.xml")).files
+
+ assert util.branch_lines == {2: (1, 4), 3: (2, 2)}
+ assert util.branch_coverage_pct == 50.0
+
+
+def test_the_project_name_alone_does_not_mean_branch_counts() -> None:
+ text = _read("sample.clover-counts.xml").replace(' clover="3.2.0"', "")
+ (util,) = parse_clover(text).files
+
+ assert util.branch_lines == {2: (2, 2), 3: (1, 2)}
+
+
+def test_formats_without_branch_data_carry_none() -> None:
+ (go,) = parse_go_coverprofile("mode: set\nm/a.go:1.1,3.2 2 1\n").files
+ assert go.branch_lines == {}
+ bar = _files(parse_cobertura(_read("sample.cobertura.xml")))["src/bar.py"]
+ assert bar.branch_lines == {}
+
+
+def test_merge_takes_the_most_taken_and_the_most_seen_per_line() -> None:
+ first = parse_lcov("SF:a.py\nDA:1,1\nDA:2,1\nBRDA:1,0,0,1\nBRDA:1,0,1,0\nend_of_record\n")
+ second = parse_lcov(
+ "SF:a.py\nDA:1,1\nDA:2,1\nBRDA:1,0,0,0\nBRDA:1,0,1,1\n"
+ "BRDA:2,0,0,1\nBRDA:2,0,1,0\nBRDA:2,0,2,0\nend_of_record\n"
+ )
+
+ (merged,) = resolve_reports([first, second], {"a.py"}).files
+
+ assert merged.branch_lines == {1: (1, 2), 2: (1, 3)}
+
+
+def test_merge_keeps_a_line_only_one_report_has_branch_data_for() -> None:
+ with_branches = parse_lcov("SF:a.py\nDA:1,1\nBRDA:1,0,0,1\nBRDA:1,0,1,0\nend_of_record\n")
+ lines_only = parse_lcov("SF:a.py\nDA:1,1\nDA:2,1\nend_of_record\n")
+
+ for order in ([with_branches, lines_only], [lines_only, with_branches]):
+ (merged,) = resolve_reports(order, {"a.py"}).files
+ assert merged.branch_lines == {1: (1, 2)}
+
+
+def _branchy(path: str = "src/a.py"):
+ # Lines 1-6 executable; 6 never ran. 2 is partly taken, 4 fully taken,
+ # 5 ran without taking a branch, 6 has branches but never ran.
+ return {
+ path: file_coverage(
+ path,
+ [1, 2, 3, 4, 5],
+ [1, 2, 3, 4, 5, 6],
+ branch_lines={2: (1, 2), 4: (2, 2), 5: (0, 2), 6: (0, 2)},
+ )
+ }
+
+
+def test_partly_taken_lines_ran_and_the_share_covers_every_changed_line() -> None:
+ pc = compute_patch_coverage({"src/a.py": {2, 3, 4}}, _branchy())
+
+ (f,) = pc.files
+ assert (f.branch_taken, f.branch_total) == (3, 4)
+ assert f.partial_ranges == ((2, 2),)
+ assert pc.patch_coverage_pct == 100.0 # the line figure is untouched
+ assert pc.branch_pct == 75.0
+ assert pc.partial_line_count == 1
+ assert pc.scope.branch_data == "per_line"
+ assert pc.to_dict()["branches"] == {
+ "branch_taken": 3,
+ "branch_total": 4,
+ "branch_coverage_pct": 75.0,
+ "partial_line_count": 1,
+ "threshold": None,
+ "gate": "not_set",
+ }
+
+
+def test_a_line_that_ran_with_no_branch_taken_is_partly_taken_one_that_never_ran_is_not() -> None:
+ pc = compute_patch_coverage({"src/a.py": {5, 6}}, _branchy())
+
+ (f,) = pc.files
+ assert f.partial_ranges == ((5, 5),)
+ assert f.uncovered_ranges == ((6, 6),)
+ # Both lower the share, and each is shown as one or the other.
+ assert (f.branch_taken, f.branch_total) == (0, 4)
+
+
+def test_no_changed_line_branching_is_nothing_to_judge() -> None:
+ pc = compute_patch_coverage({"src/a.py": {1, 3}}, _branchy())
+
+ assert pc.branch_pct is None
+ assert pc.to_dict()["branches"] is None
+ assert branch_line(pc) == ""
+
+ gated = replace(pc, branch_threshold=80)
+ assert gated.branch_gate == "no_data"
+ assert gated.gate == "no_data" # not applied, never a failure
+ assert gated.to_dict()["branches"]["branch_coverage_pct"] is None
+ assert branch_line(gated) == (
+ "Branches on changed lines: no changed executable line has branches. "
+ "The 80.0% branch gate was not applied."
+ )
+
+
+def test_coverage_without_per_line_branch_data_says_so() -> None:
+ cov = {"src/a.py": file_coverage("src/a.py", [1], [1])}
+ gated = replace(compute_patch_coverage({"src/a.py": {1}}, cov), branch_threshold=80)
+
+ assert gated.scope.branch_data == "none"
+ assert branch_line(gated).startswith(
+ "Branches on changed lines: not measured (the coverage report has no per-line "
+ "branch data)"
+ )
+ stored = replace(gated, scope=replace(gated.scope, branch_data="stored_before"))
+ assert "re-run `repowise coverage add`" in branch_line(stored)
+
+
+def test_an_unapplied_branch_gate_is_a_github_notice() -> None:
+ cov = {"src/a.py": file_coverage("src/a.py", [1], [1])}
+ gated = replace(compute_patch_coverage({"src/a.py": {1}}, cov), branch_threshold=80)
+
+ notices = [line for line in github_annotations(gated) if line.startswith("::notice")]
+ assert notices == [
+ "::notice::Branches on changed lines: not measured (the coverage report has no "
+ "per-line branch data). The 80.0%25 branch gate was not applied." # % escaped
+ ]
+
+
+def test_the_branch_gate_fails_the_change_beside_a_passing_line_gate() -> None:
+ pc = compute_patch_coverage({"src/a.py": {2, 3, 4}}, _branchy(), threshold=80)
+
+ assert replace(pc, branch_threshold=70).gate == "pass"
+ failed = replace(pc, branch_threshold=80)
+ assert (failed.flat_gate, failed.branch_gate, failed.gate) == ("pass", "fail", "fail")
+ assert "below the 80.0% branch gate" in branch_line(failed, markdown=False)
+ # The headline stays the line figure: the two are never blended.
+ assert headline(failed).startswith("**Patch coverage 100.0%**")
+
+
+def test_an_unapplied_branch_gate_gives_way_to_the_project_verdict() -> None:
+ pc = compute_patch_coverage({"src/a.py": {1, 3}}, _branchy())
+ project = ProjectDelta(ProjectTotals(80, 100), ProjectTotals(80, 100), "history", max_drop=1)
+
+ assert replace(pc, branch_threshold=80, project=project).gate == "pass"
+
+
+def test_the_small_change_tolerance_applies_to_the_branch_gate() -> None:
+ pc = compute_patch_coverage(
+ {"src/a.py": {2, 3, 4}}, _branchy(), min_coverable_lines=5
+ )
+ small = replace(pc, branch_threshold=80)
+
+ assert small.branch_gate == "too_small"
+ assert small.gate == "too_small"
+
+
+def test_partly_taken_files_follow_uncovered_ones_and_get_a_column() -> None:
+ cov = {**_branchy("src/a.py"), "src/b.py": file_coverage("src/b.py", [1], [1, 2])}
+ pc = compute_patch_coverage({"src/a.py": {2, 3}, "src/b.py": {1, 2}}, cov)
+
+ # a.py sorts first by name, but an uncovered line outranks a partly taken branch.
+ assert [f.file_path for f in attention_rows(pc)] == ["src/b.py", "src/a.py"]
+ md = render_markdown(pc)
+ assert "**Branches on changed lines 50.0%** (1 of 2 taken; 1 line partly taken)" in md
+ assert "| File | Uncovered changed lines | Partly taken | Covered |" in md
+ assert "| `src/a.py` | | 2 | 2 of 2 |" in md
+
+
+def test_no_partly_taken_column_without_a_partly_taken_line() -> None:
+ md = render_markdown(compute_patch_coverage({"src/a.py": {4, 6}}, _branchy()))
+
+ assert "Branches on changed lines 50.0%" in md
+ assert "Partly taken" not in md
+
+
+def test_github_warns_per_partly_taken_range_after_the_uncovered_ones() -> None:
+ cov = {
+ "src/a.py": file_coverage(
+ "src/a.py", [1, 2, 4], [1, 2, 3, 4], branch_lines={2: (1, 2), 4: (1, 3)}
+ )
+ }
+ pc = replace(
+ compute_patch_coverage({"src/a.py": {1, 2, 3, 4}}, cov), branch_threshold=90
+ )
+
+ lines = github_annotations(pc)
+
+ assert lines[0].startswith("::error::Branches on changed lines 40.0%")
+ uncovered, *partial = lines[1:]
+ assert "title=Uncovered change" in uncovered
+ assert [line.split("::", 2)[1] for line in partial] == [
+ "warning file=src/a.py,line=2,endLine=2,title=Partly taken branch",
+ "warning file=src/a.py,line=4,endLine=4,title=Partly taken branch",
+ ]
+ assert partial[0].endswith("Changed line 2 ran, but not every branch was taken by tests")
diff --git a/tests/unit/cli/test_coverage_check_cmd.py b/tests/unit/cli/test_coverage_check_cmd.py
index f969949b3..42f62021a 100644
--- a/tests/unit/cli/test_coverage_check_cmd.py
+++ b/tests/unit/cli/test_coverage_check_cmd.py
@@ -802,6 +802,142 @@ def test_stored_coverage_is_not_gated_when_stale_or_without_line_data() -> None:
assert missing.value.code == "no_report"
+# -- branches on changed lines ----------------------------------------------
+
+
+def _branch_lcov(repo) -> str:
+ """Every changed line of src/app.py ran; line 2 took one of its two branches."""
+ path = repo / "coverage.lcov"
+ path.write_text(
+ f"SF:{repo / 'src' / 'app.py'}\nDA:1,1\nDA:2,1\nDA:3,1\n"
+ "BRDA:2,0,0,1\nBRDA:2,0,1,0\nBRDA:3,0,0,1\nBRDA:3,0,1,1\nend_of_record\n",
+ encoding="utf-8",
+ )
+ return str(path)
+
+
+def test_branches_on_changed_lines_are_reported_beside_patch_coverage(repo) -> None:
+ report = _branch_lcov(repo)
+ data = _check_json(repo, report)
+
+ assert data["patch_coverage_pct"] == 100.0
+ assert data["branches"] == {
+ "branch_taken": 3,
+ "branch_total": 4,
+ "branch_coverage_pct": 75.0,
+ "partial_line_count": 1,
+ "threshold": None,
+ "gate": "not_set",
+ }
+ assert data["scope"]["branch_data"] == "per_line"
+ (app,) = [f for f in data["files"] if f["file_path"] == "src/app.py"]
+ assert app["partial_ranges"] == [[2, 2]]
+
+ table = _run(repo, "main...feat", "--report", report)
+ assert "Branches on changed lines 75.0% (3 of 4 taken; 1 line partly taken)" in table.output
+ assert "Partly taken" in table.output
+
+
+def test_fail_under_branches_gates_the_branch_share(repo) -> None:
+ report = _branch_lcov(repo)
+
+ passed = _run(repo, "main...feat", "--report", report, "--fail-under-branches", "75")
+ assert passed.exit_code == 0
+ failed = _run(repo, "main...feat", "--report", report, "--fail-under-branches", "80")
+ assert failed.exit_code == 1
+ assert "below the 80.0% branch gate" in failed.output
+
+
+def test_fail_under_branches_defaults_to_config_and_a_bad_value_exits_2(repo) -> None:
+ config = repo / ".repowise" / "config.yaml"
+ config.parent.mkdir()
+ config.write_text("coverage:\n fail_under_branches: 80\n", encoding="utf-8")
+ report = _branch_lcov(repo)
+ assert _run(repo, "main...feat", "--report", report).exit_code == 1
+
+ config.write_text("coverage:\n fail_under_branches: lots\n", encoding="utf-8")
+ bad = _run(repo, "main...feat", "--report", report)
+ assert bad.exit_code == 2
+ assert "coverage.fail_under_branches must be a number" in bad.output
+ # The flag overrides the unusable config value.
+ flagged = _run(repo, "main...feat", "--report", report, "--fail-under-branches", "50")
+ assert flagged.exit_code == 0
+
+
+def test_the_branch_flag_over_a_report_without_branch_data_exits_2(repo) -> None:
+ report = _lcov(repo, {1: 1, 2: 1, 3: 1})
+ result = _run(repo, "main...feat", "--report", report, "--fail-under-branches", "80")
+
+ assert result.exit_code == 2
+ assert "no per-line branch data" in result.output
+ assert _check_json(repo, report)["branches"] is None
+
+
+def test_the_branch_flag_does_not_hide_a_failure_already_found(repo) -> None:
+ report = _lcov(repo, {1: 1, 2: 1, 3: 0})
+ args = ("--fail-under", "90", "--fail-under-branches", "80")
+ assert _run(repo, "main...feat", "--report", report, *args).exit_code == 1
+
+
+def test_a_config_branch_gate_over_a_report_without_branch_data_is_a_note(
+ repo, tmp_path_factory
+) -> None:
+ config = repo / ".repowise" / "config.yaml"
+ config.parent.mkdir()
+ config.write_text("coverage:\n fail_under_branches: 80\n", encoding="utf-8")
+ report = _lcov(repo, {1: 1, 2: 1, 3: 1})
+
+ table = _run(repo, "main...feat", "--report", report)
+ assert table.exit_code == 0
+ assert "Branches on changed lines: not measured" in table.output
+
+ summary = tmp_path_factory.mktemp("gh") / "summary.md"
+ github = _run(
+ repo,
+ "main...feat",
+ "--report",
+ report,
+ "--format",
+ "github",
+ env={"GITHUB_STEP_SUMMARY": str(summary)},
+ )
+ assert github.exit_code == 0
+ assert "::notice::Branches on changed lines: not measured" in github.stdout
+
+
+def _stored_branchy(monkeypatch, branch_data: str | None) -> None:
+ """Stored coverage, current at the head: src/app.py line 2 took 1 of 2 branches."""
+ from repowise.cli.commands import coverage_check_cmd
+ from repowise.core.analysis.health.coverage import file_coverage
+ from repowise.core.analysis.patch_coverage import PatchScope, compute_patch_coverage
+
+ lines = {2: (1, 2)} if branch_data is None else {}
+ cov = {"src/app.py": file_coverage("src/app.py", [2, 3], [2, 3], branch_lines=lines)}
+ scope = PatchScope(label="main...feat", freshness="current", branch_data=branch_data)
+
+ async def _stored(root, changed, label, threshold, min_lines, cfg):
+ return compute_patch_coverage(changed, cov, threshold=threshold, scope=scope)
+
+ monkeypatch.setattr(coverage_check_cmd, "has_db_store", lambda root: True)
+ monkeypatch.setattr(coverage_check_cmd, "_stored", _stored)
+
+
+def test_stored_coverage_takes_the_branch_flag(repo, monkeypatch) -> None:
+ _stored_branchy(monkeypatch, None)
+
+ result = _run(repo, "main...feat", "--fail-under-branches", "80")
+ assert result.exit_code == 1, result.output
+ assert "below the 80.0% branch gate" in result.output
+
+
+def test_stored_coverage_from_before_per_line_branches_exits_2(repo, monkeypatch) -> None:
+ _stored_branchy(monkeypatch, "stored_before")
+
+ result = _run(repo, "main...feat", "--fail-under-branches", "80")
+ assert result.exit_code == 2
+ assert "Re-run `repowise coverage add`" in result.output
+
+
# -- path-scoped gates -------------------------------------------------------
diff --git a/tests/unit/persistence/test_coverage_loaders.py b/tests/unit/persistence/test_coverage_loaders.py
index 68f86335d..3dffca534 100644
--- a/tests/unit/persistence/test_coverage_loaders.py
+++ b/tests/unit/persistence/test_coverage_loaders.py
@@ -46,6 +46,50 @@ async def test_executable_lines_survive_a_round_trip(async_session, repo) -> Non
assert loaded == {"src/a.py": fc}
+async def test_branch_lines_survive_a_round_trip(async_session, repo) -> None:
+ fc = file_coverage(
+ "src/a.py", [1, 4], [1, 3, 4], branches_found=4, branches_hit=3,
+ branch_lines={1: (1, 2), 4: (2, 2)},
+ )
+ await save_coverage_files(async_session, repo.id, [fc], source_format="lcov")
+
+ (row,) = await load_coverage_for_repo(async_session, repo.id)
+ assert row.branch_lines_json == '{"1":[1,2],"4":[2,2]}'
+ assert await load_file_coverage(async_session, repo.id) == {"src/a.py": fc}
+
+
+async def test_stored_patch_coverage_carries_the_branches(async_session, repo) -> None:
+ from repowise.core.analysis.patch_coverage import stored_patch_coverage
+
+ fc = file_coverage("src/a.py", [1, 2], [1, 2], branch_lines={2: (1, 2)})
+ await save_coverage_files(
+ async_session, repo.id, [fc], source_format="lcov", ingested_commit_sha="abc"
+ )
+ stored = await stored_patch_coverage(
+ async_session, repo.id, {"src/a.py": {1, 2}}, head_commit="abc"
+ )
+
+ assert stored is not None
+ assert stored.files[0].partial_ranges == ((2, 2),)
+ assert stored.to_dict()["branches"]["branch_coverage_pct"] == 50.0
+ assert stored.scope.branch_data == "per_line"
+
+
[email protected](("branches_found", "expected"), [(2, "stored_before"), (0, "none")])
+async def test_stored_rows_without_per_line_branches_say_why(
+ async_session, repo, branches_found, expected
+) -> None:
+ from repowise.core.analysis.patch_coverage import stored_patch_coverage
+
+ # A file-level branch figure with no per-line counts: written before they were kept.
+ fc = file_coverage("src/a.py", [1], [1], branches_found=branches_found, branches_hit=1)
+ await save_coverage_files(async_session, repo.id, [fc], source_format="lcov")
+ stored = await stored_patch_coverage(async_session, repo.id, {"src/a.py": {1}})
+
+ assert stored is not None
+ assert stored.scope.branch_data == expected
+
+
async def test_stored_map_matches_the_resolved_map(async_session, repo) -> None:
resolved = resolve_reports([parse_lcov(_LCOV)], {"src/a.py"})
await save_coverage_files(
diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.py
index c1b2c42de..1a1db8bf5 100644
--- a/tests/unit/server/mcp/test_tool_change_risk.py
+++ b/tests/unit/server/mcp/test_tool_change_risk.py
@@ -737,6 +737,17 @@ def test_the_directive_names_the_scope_and_the_tests_to_extend():
)
+def test_the_directive_names_partly_taken_lines_when_every_changed_line_ran():
+ from repowise.server.mcp_server._change_health import patch_coverage_action
+
+ block = {**_patch_block(3, 3), "branches": {"partial_line_count": 2}}
+ assert patch_coverage_action(block) == (
+ "2 changed lines since origin/main ran with a branch no test took; add tests "
+ "for the other way through (patch_coverage.files[].partial_ranges)"
+ )
+ assert patch_coverage_action({**block, "branches": None}) is None
+
+
def _git(cwd, *args: str) -> None:
subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True)
diff --git a/tests/unit/server/test_patch_coverage_schema.py b/tests/unit/server/test_patch_coverage_schema.py
index f789a36dc..c288f95ed 100644
--- a/tests/unit/server/test_patch_coverage_schema.py
+++ b/tests/unit/server/test_patch_coverage_schema.py
@@ -111,3 +111,13 @@ def test_every_to_dict_key_round_trips_through_the_response_model() -> None:
assert projected["project"]["gate"] == "fail"
assert PatchCoverageResponse.model_validate(projected).model_dump() == projected
assert wire["project"] is None
+
+
+def test_branches_on_changed_lines_round_trip_through_the_response_model() -> None:
+ coverage = {"a.py": file_coverage("a.py", [1, 2], [1, 2], branch_lines={2: (1, 2)})}
+ pc = replace(compute_patch_coverage({"a.py": {1, 2}}, coverage), branch_threshold=80)
+ wire = pc.to_dict()
+
+ assert wire["branches"]["gate"] == "fail"
+ assert wire["files"][0]["partial_ranges"] == [[2, 2]]
+ assert PatchCoverageResponse.model_validate(wire).model_dump() == wire
diff --git a/tests/unit/test_ci_action.py b/tests/unit/test_ci_action.py
index 9fdf2ba98..776a52d83 100644
--- a/tests/unit/test_ci_action.py
+++ b/tests/unit/test_ci_action.py
@@ -61,6 +61,7 @@ def test_the_gitlab_template_parses() -> None:
assert "REPOWISE_RISK_FAIL_ABOVE_PERCENTILE" in jobs["repowise-risk"]["rules"][0]["if"]
coverage = " ".join(jobs["repowise-coverage"]["script"])
assert "--fail-under-risky" in coverage
+ assert "--fail-under-branches" in coverage
assert "--base-report" in coverage and "--max-drop" in coverage
@@ -251,6 +252,7 @@ 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_FAIL_UNDER_BRANCHES": "",
"COVERAGE_BASE_REPORT": "",
"COVERAGE_MAX_DROP": "",
"DOC_DRIFT_BASELINE": "",
@@ -322,6 +324,14 @@ def test_base_report_inputs_reach_the_coverage_command(tmp_path, fake_repowise)
)
+def test_branch_input_reaches_the_coverage_command(tmp_path, fake_repowise) -> None:
+ code, _, calls = _run(
+ tmp_path, fake_repowise, CHECKS="coverage", COVERAGE_FAIL_UNDER_BRANCHES="70"
+ )
+ assert code == 0
+ assert calls.strip() == "coverage check --format github --fail-under-branches 70"
+
+
def test_risk_inputs_reach_the_commands(tmp_path, fake_repowise) -> None:
code, outputs, calls = _run(
tmp_path,