An open source, non-profit web search engine
Coverage: combine Python and Rust totals, add GitLab job
blueheron78615fb455b864a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 4d2e29d..ea78ca5 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -84,6 +84,10 @@ jobs:#----------------------------------------------- name: Install Rust toolchainuses: dtolnay/rust-toolchain@stable+ with:+ components: llvm-tools-preview+ - name: Install cargo-llvm-cov+ uses: taiki-e/install-action@cargo-llvm-cov#----------------------------------------------# install dependencies@@ -114,19 +118,15 @@ jobs:#----------------------------------------------- name: Check the crawler entry point imports standalonerun: uv run python -c "from mwmbl.crawl import run"- - name: Run tests with coverage+ - name: Run Python and Rust tests with coverageenv:DATABASE_URL: postgres://postgres:postgres@localhost:5432/test_mwmblDJANGO_SETTINGS_MODULE: mwmbl.settings_testTEST_REDIS_URL: redis://localhost:6379/15- run: |- uv run pytest \- --cov=mwmbl \- --cov-report=term-missing \- --cov-report=xml+ run: make coverage- name: Upload coverage to Codecovif: github.event_name == 'push' || github.event.pull_request.head.repo.fork == falseuses: codecov/codecov-action@v5with:- files: ./coverage.xml+ files: ./coverage/python.xml,./coverage/rust.lcovfail_ci_if_error: falsediff --git a/.gitignore b/.gitignoreindex 5e0cd86..6fb741b 100644--- a/.gitignore+++ b/.gitignore@@ -53,6 +53,7 @@ htmlcov/.cachenosetests.xmlcoverage.xml+coverage/*.cover*.py,cover.hypothesis/diff --git a/.gitlab-ci.yml b/.gitlab-ci.ymlnew file mode 100644index 0000000..da8c827--- /dev/null+++ b/.gitlab-ci.yml@@ -0,0 +1,50 @@+stages:+ - test++coverage:+ stage: test+ image: ghcr.io/astral-sh/uv:python3.11-bookworm-slim+ services:+ - name: postgres:15+ alias: postgres+ - name: redis:7+ alias: redis+ variables:+ POSTGRES_DB: test_mwmbl+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_HOST_AUTH_METHOD: trust+ DATABASE_URL: postgres://postgres@postgres:5432/test_mwmbl+ TEST_REDIS_URL: redis://redis:6379/15+ DJANGO_SETTINGS_MODULE: mwmbl.settings_test+ CARGO_HOME: "$CI_PROJECT_DIR/.cargo"+ cache:+ key:+ files:+ - uv.lock+ - mwmbl_rank/Cargo.lock+ paths:+ - .cache/uv+ - .cargo/+ - mwmbl_rank/target/+ before_script:+ - apt-get update+ - apt-get install --yes --no-install-recommends build-essential curl patchelf pkg-config libssl-dev+ - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal+ - export PATH="$CARGO_HOME/bin:$PATH"+ - rustup component add llvm-tools-preview+ - cargo install cargo-llvm-cov --locked+ - uv sync --group dev+ - uv run maturin develop+ script:+ - export PATH="$CARGO_HOME/bin:$PATH"+ - make coverage+ coverage: '/TOTAL COVERAGE: ([0-9]+(?:\.[0-9]+)?)%/'+ artifacts:+ when: always+ paths:+ - coverage/+ reports:+ coverage_report:+ coverage_format: cobertura+ path: coverage/python.xmldiff --git a/Makefile b/Makefileindex 9dc9f47..1bf0c40 100644--- a/Makefile+++ b/Makefile@@ -29,6 +29,10 @@ DATABASE_URL ?=REDIS_URL ?= redis://127.0.0.1:6379# A Redis database the tests flush, so keep it apart from REDIS_URL's.TEST_REDIS_URL ?= redis://127.0.0.1:6379/15+# Python tests that cross into the mwmbl_rank extension, run against the instrumented build.+RUST_COVERAGE_TESTS ?= test/test_rust_features.py test/test_rust_pipeline.py test/test_indexer.py \+ test/test_index_page_api.py test/test_index_page_writes.py test/test_copy_index.py+CARGO_HOME ?= $(HOME)/.cargoDJANGO_SETTINGS_MODULE ?= mwmbl.settings_dev@@ -39,7 +43,8 @@ DJANGO_SETTINGS_MODULE ?= mwmbl.settings_devSODIR := .venv/lib/python3.11/site-packages/mwmbl_rankXGB_SO := mwmbl_rank/target/release/deps/libxgboost.so-.PHONY: help install install-hooks patch-xgboost migrate test test-file coverage coverage-quick run run-background \+.PHONY: help install install-hooks patch-xgboost migrate test test-file coverage coverage-python coverage-rust \+ coverage-quick run run-background \check fix format format-check lint lint-fix typecheck typecheck-all lockedhelp:@@ -48,7 +53,9 @@ help:@echo " migrate Apply Django migrations"@echo " test Run the full test suite (set DATABASE_URL to a PostgreSQL database)"@echo " test-file FILE Run a specific test file, e.g. make test-file FILE=test/test_search_api_key.py"- @echo " coverage Run tests with coverage report (terminal + HTML)"+ @echo " coverage Run Python and Rust coverage and print a combined line-weighted total"+ @echo " coverage-python Run Python tests with terminal, XML, and HTML coverage reports"+ @echo " coverage-rust Run Rust unit tests and write an LCOV report (needs cargo-llvm-cov)"@echo " coverage-quick Run tests with coverage report (terminal only, faster)"@echo " run Start the Django development server"@echo " run-background Start the background task processor"@@ -91,9 +98,35 @@ test-file:DATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" TEST_REDIS_URL="$(TEST_REDIS_URL)" \uv run pytest $(FILE) -v $(PYTEST_ARGS)-coverage:+coverage: coverage-python coverage-rust+ uv run python scripts/combine_coverage.py coverage/python.xml coverage/rust.lcov++coverage-python:+ @mkdir -p coverageDATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" TEST_REDIS_URL="$(TEST_REDIS_URL)" \- uv run pytest --cov=mwmbl --cov-report=term-missing --cov-report=html --ignore=mwmbl_rank/vendor $(PYTEST_ARGS)+ uv run pytest --cov=mwmbl --cov-report=term-missing --cov-report=xml:coverage/python.xml \+ --cov-report=html:coverage/python-html --ignore=mwmbl_rank/vendor $(PYTEST_ARGS)++coverage-rust:+ @PATH="$(CARGO_HOME)/bin:$(PATH)" cargo llvm-cov --version >/dev/null 2>&1 || { \+ echo "cargo-llvm-cov is required: rustup component add llvm-tools-preview && cargo install cargo-llvm-cov --locked"; \+ exit 1; \+ }+ @mkdir -p coverage+ @set -eu; \+ PATH="$(CARGO_HOME)/bin:$(PATH)"; \+ export PATH PYO3_PYTHON="$(CURDIR)/.venv/bin/python"; \+ eval "$$(cd mwmbl_rank && cargo llvm-cov show-env --sh)"; \+ cargo llvm-cov clean --manifest-path mwmbl_rank/Cargo.toml --workspace; \+ cargo test --manifest-path mwmbl_rank/Cargo.toml --lib; \+ uv run --no-sync maturin develop; \+ DATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" TEST_REDIS_URL="$(TEST_REDIS_URL)" \+ uv run --no-sync pytest $(RUST_COVERAGE_TESTS); \+ cargo llvm-cov report \+ --manifest-path mwmbl_rank/Cargo.toml \+ --lcov \+ --output-path "$(CURDIR)/coverage/rust.lcov" \+ --ignore-filename-regex '(/vendor/|/.cargo/registry/)'coverage-quick:DATABASE_URL="$(DATABASE_URL)" REDIS_URL="$(REDIS_URL)" TEST_REDIS_URL="$(TEST_REDIS_URL)" \diff --git a/README.md b/README.mdindex 4403039..41387f7 100644--- a/README.md+++ b/README.md@@ -40,6 +40,13 @@ DocumentationAll documentation is at [https://book.mwmbl.org](https://book.mwmbl.org).+Development coverage+====================++`make coverage` measures the Python and Rust code and prints a combined,+executable-line-weighted percentage. See [the coverage guide](docs/coverage.md)+for prerequisites, exclusions, and CI details.+Crawling========@@ -200,4 +207,3 @@ Acknowledgements================Many thanks to [Mohamed Alm](https://github.com/theonlyalm) for security consultations and recommendations.-diff --git a/docs/coverage.md b/docs/coverage.mdnew file mode 100644index 0000000..9c84a27--- /dev/null+++ b/docs/coverage.md@@ -0,0 +1,89 @@+# Code coverage++## Run it locally++Install the Rust coverage tool once:++```sh+rustup component add llvm-tools-preview+cargo install cargo-llvm-cov --locked+```++If Cargo reports that its binary directory is not on `PATH`, add+`$HOME/.cargo/bin`; the Make target also checks that standard location.++Then run:++```sh+DATABASE_URL="postgres://user@/mwmbl_test" make coverage+```++This writes:++- `coverage/python.xml` and `coverage/python-html/` for Python;+- `coverage/rust.lcov` for Rust; and+- Python, Rust, and combined totals to the terminal.++The combined percentage is `(covered Python lines + covered Rust lines) /+(executable Python lines + executable Rust lines)`. Weighting by executable+lines prevents a small language component from counting as much as a large one.+Python and Rust results are also printed separately because the combined number+must not hide a weak component.++The Rust target runs both native unit tests and the Python integration tests+against an instrumented PyO3 extension. Measuring only `cargo test` would miss+the extension boundary even though the Python suite exercises it. The Python tests+that import `mwmbl_rank` are listed in `RUST_COVERAGE_TESTS` in the Makefile; add a+test file there when it is the only thing exercising a Rust path. The Make target+uses `uv run --no-sync` because a plain `uv run` silently rebuilds the extension+without instrumentation, which makes `index.rs` and `lib.rs` read as 0%.++If the Python suite fails on background-task or dedupe tests with surprising row+counts, the reused test database (`--reuse-db`) is stale; run once with+`PYTEST_ARGS=--create-db`.++## What counts++Coverage should measure behavior that can regress. Migrations are generated+history, ASGI/WSGI modules are framework launchers, and `indexer/paths.py` is+declarative machine-specific path configuration, so they are omitted.+Type-check-only blocks and abstract method bodies are excluded as structurally+unreachable code.++Constructors, properties, serializers, database helpers, management commands,+and index tools are not excluded just because they are short or inconvenient to+test. They contain behavior and should remain visible in the report. Empty+constructors need no special pattern: coverage.py only counts executable+statements, not a function declaration with no body.++The useful ceiling is reached when the remaining misses are failure handling+that cannot be triggered deterministically or environment-specific integration+paths. For this project, aim for at least 85% in each language before considering+further exclusions. Prioritize uncovered decisions in API permissions, views,+ranking, crawling, moderation, and external-source adapters over tests that only+call trivial accessors.++The baseline when this workflow was introduced was 70.83% Python, 66.36% Rust,+and 70.42% combined; including the extension-boundary tests lifts Rust to 91.6% and+the combined figure to 72.7%. The largest actionable Python gaps were `platform/api.py`,+`views.py`, moderation training, crawler retrieval, and crawler application+behavior. Standalone ranking-evaluation reports also account for many misses;+test maintained reports through their parsing and scoring functions, and delete+obsolete reports rather than hiding them from coverage.++## CI and badges++GitHub Actions uploads both reports to Codecov. Codecov combines them and drives+the badge in the main README.++The GitLab coverage job prints a line such as `TOTAL COVERAGE: 82.14%`; its+`coverage` expression makes that value available to GitLab's built-in badge.+For a mirror at `https://gitlab.com/<namespace>/<project>`, the badge URL is:++```text+https://gitlab.com/<namespace>/<project>/badges/main/coverage.svg+```++Replace the namespace and project with the mirror's actual path. This repository+currently has no GitLab remote, so committing a concrete GitLab badge URL would+create a broken badge.diff --git a/pyproject.toml b/pyproject.tomlindex fb3788f..d520ff6 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -131,13 +131,13 @@ omit = ["mwmbl/migrations/*","mwmbl/asgi.py","mwmbl/wsgi.py",- "mwmbl/database.py",- "mwmbl/indexer/domains/*",- "mwmbl/indexer/fsqueue.py",- "mwmbl/indexer/links.py","mwmbl/indexer/paths.py",- "mwmbl/management/commands/train_*.py",- "mwmbl/management/commands/backfill_*.py",+]++[tool.coverage.report]+exclude_also = [+ "if TYPE_CHECKING:",+ "@(abc\\.)?abstractmethod",][tool.ruff]diff --git a/scripts/combine_coverage.py b/scripts/combine_coverage.pynew file mode 100644index 0000000..1598d03--- /dev/null+++ b/scripts/combine_coverage.py@@ -0,0 +1,83 @@+#!/usr/bin/env python3+"""Combine coverage.py XML and cargo-llvm-cov LCOV line coverage."""++import argparse+import xml.etree.ElementTree as ET+from dataclasses import dataclass+from pathlib import Path+++@dataclass(frozen=True)+class Coverage:+ covered: int+ total: int++ @property+ def percent(self) -> float:+ if self.total == 0:+ raise ValueError("Coverage report has no executable lines")+ return self.covered / self.total * 100+++def read_python_coverage(path: Path) -> Coverage:+ root = ET.parse(path).getroot()+ return Coverage(+ covered=int(root.attrib["lines-covered"]),+ total=int(root.attrib["lines-valid"]),+ )+++def read_rust_coverage(path: Path) -> Coverage:+ source_file: str | None = None+ line_hits: dict[tuple[str, int], int] = {}++ for raw_line in path.read_text().splitlines():+ if raw_line.startswith("SF:"):+ source_file = raw_line[3:]+ elif raw_line.startswith("DA:"):+ if source_file is None:+ raise ValueError(f"{path}: DA record before SF record")+ line_number, hits, *_ = raw_line[3:].split(",")+ key = (source_file, int(line_number))+ line_hits[key] = max(line_hits.get(key, 0), int(hits))+ elif raw_line == "end_of_record":+ source_file = None++ if not line_hits:+ raise ValueError(f"{path}: no Rust line coverage records")++ return Coverage(+ covered=sum(hits > 0 for hits in line_hits.values()),+ total=len(line_hits),+ )+++def combine_coverage(python: Coverage, rust: Coverage) -> Coverage:+ return Coverage(+ covered=python.covered + rust.covered,+ total=python.total + rust.total,+ )+++def format_coverage(name: str, coverage: Coverage) -> str:+ return f"{name}: {coverage.covered}/{coverage.total} lines ({coverage.percent:.2f}%)"+++def main() -> None:+ parser = argparse.ArgumentParser()+ parser.add_argument("python_xml", type=Path)+ parser.add_argument("rust_lcov", type=Path)+ args = parser.parse_args()++ python = read_python_coverage(args.python_xml)+ rust = read_rust_coverage(args.rust_lcov)+ combined = combine_coverage(python, rust)++ print(format_coverage("Python", python))+ print(format_coverage("Rust", rust))+ print(format_coverage("Combined", combined))+ print(f"TOTAL COVERAGE: {combined.percent:.2f}%")+++if __name__ == "__main__":+ main()diff --git a/test/test_combine_coverage.py b/test/test_combine_coverage.pynew file mode 100644index 0000000..cf79b50--- /dev/null+++ b/test/test_combine_coverage.py@@ -0,0 +1,53 @@+from pathlib import Path++import pytest++from scripts.combine_coverage import Coverage, combine_coverage, read_python_coverage, read_rust_coverage+++def test_read_python_coverage(tmp_path: Path):+ report = tmp_path / "coverage.xml"+ report.write_text('<coverage lines-valid="10" lines-covered="7" />')++ assert read_python_coverage(report) == Coverage(covered=7, total=10)+++def test_read_rust_coverage_deduplicates_lines(tmp_path: Path):+ report = tmp_path / "coverage.lcov"+ report.write_text(+ "\n".join(+ [+ "SF:/project/src/lib.rs",+ "DA:10,0",+ "DA:11,2",+ "end_of_record",+ "SF:/project/src/lib.rs",+ "DA:10,1",+ "DA:11,0",+ "end_of_record",+ "SF:/project/src/text.rs",+ "DA:10,0",+ "end_of_record",+ ]+ )+ )++ assert read_rust_coverage(report) == Coverage(covered=2, total=3)+++def test_read_rust_coverage_rejects_empty_report(tmp_path: Path):+ report = tmp_path / "coverage.lcov"+ report.write_text("TN:\n")++ with pytest.raises(ValueError, match="no Rust line coverage records"):+ read_rust_coverage(report)+++def test_combined_coverage_weights_executable_lines():+ python = Coverage(covered=70, total=100)+ rust = Coverage(covered=18, total=20)++ combined = combine_coverage(python, rust)++ assert combined == Coverage(covered=88, total=120)+ assert combined.percent == pytest.approx(73.333333)