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.

fix(coverage): stamp on-disk reports at the commit they measured, not live HEAD (#3901) (#3935)

Ensar99c81ff27da3
diff --git a/packages/cli/src/repowise/cli/commands/coverage_cmd.py b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
index e1cc48325..4f8cdc2cd 100644
--- a/packages/cli/src/repowise/cli/commands/coverage_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/coverage_cmd.py
@@ -146,6 +146,8 @@ def coverage_add(
build_coverage_map,
discover_artifacts,
expand_report_args,
+ measurement_commit,
+ oldest_report_time,
parse_contexts_file,
prefix_hint,
report_origin_dir,
@@ -217,9 +219,11 @@ def coverage_add(
# working tree. They diverge when you commit, run your tests, then
# ``coverage add`` without an intervening ``repowise update`` — the
# report would be labelled with the older indexed commit (issue
- # #1747). Live HEAD is the right answer for a provenance field:
- # it is the tree the coverage was measured against. Resolve it
- # from disk — the same source the health pass uses.
+ # #1747). HEAD is the right answer for a report written since the
+ # last commit; one left over from earlier measures the tree as of
+ # its own date, so the stamp moves back to the commit that was HEAD
+ # then (issue #3901). Resolve both from disk — the same source the
+ # health pass uses.
head_sha = (
get_head_commit(Path(repo_path))
or getattr(repo_row, "head_commit", None)
@@ -252,6 +256,10 @@ def coverage_add(
map_records: list = []
map_format: str | None = None
map_readable = False
+ # Reports that gave the map rows, for the stamp below: a leftover
+ # artifact with no contexts (or none that mapped) is not a
+ # measurement this ingest describes.
+ map_paths: list[Path] = []
map_skipped: list[str] = []
for report_path in report_paths:
creport = parse_contexts_file(report_path)
@@ -277,6 +285,8 @@ def coverage_add(
)
if rtc.mapping_partial:
map_skipped.extend(rtc.unmatched + rtc.ambiguous)
+ if rtc.records:
+ map_paths.append(report_path)
map_records.extend(rtc.records)
map_format = map_format or creport.source_format
@@ -301,13 +311,22 @@ def coverage_add(
return False
agg_matched = 0
+ # Both writes stamp the commit that was HEAD when their own reports
+ # were written (#3901), and each asks only about the files that
+ # actually gave it rows: an unreadable or context-free artifact left
+ # beside a fresh report must not pull a valid ingest back to the
+ # stale one's date. *resolved* carries the aggregate's parsed set,
+ # ``map_paths`` the per-test one; an empty set answers ``None`` and
+ # keeps HEAD, which is what a report written just now is.
+ agg_sha = measurement_commit(repo_path, resolved.measured_at, head_sha)
+ map_sha = measurement_commit(repo_path, oldest_report_time(map_paths), head_sha)
if resolved.files:
await save_coverage_files(
session,
repo_row.id,
resolved.files,
source_format=resolved.source_format or "lcov",
- ingested_commit_sha=head_sha,
+ ingested_commit_sha=agg_sha,
provenance=resolved.provenance,
)
agg_matched = resolved.matched
@@ -327,7 +346,7 @@ def coverage_add(
repo_row.id,
map_records,
source_format=map_format or "coverage.py",
- ingested_commit_sha=head_sha,
+ ingested_commit_sha=map_sha,
)
extra = f" ({saved.merged} repeated record(s) merged)" if saved.merged else ""
console.print(
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index d511efa18..e2fd2688e 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -1015,6 +1015,7 @@ async def _rescore_health_from_db(
from repowise.core.analysis.communities import file_community_labels
from repowise.core.analysis.health import HealthAnalyzer
from repowise.core.analysis.health.config import HealthConfig
+ from repowise.core.analysis.health.coverage import measurement_commit
from repowise.core.analysis.health.history_refresh import (
BLAME_MARKERS,
git_meta_rows_to_map,
@@ -1156,15 +1157,21 @@ async def _rescore_health_from_db(
# ``repo.head_commit`` column. The column names the last
# *indexed* commit; the coverage just scored describes the
# working tree, and the two diverge when the tree moved after
- # the last index (issue #1747). Live HEAD is the provenance
- # answer: it is the tree the coverage was measured against.
+ # the last index (issue #1747). HEAD is the right answer for a
+ # report written since the last commit; one left over from
+ # earlier measures the tree as of its own date, so the stamp
+ # moves back to the commit that was HEAD then (issue #3901).
live_head = get_head_commit(Path(repo_path)) or getattr(repo, "head_commit", None)
await save_coverage_files(
session,
repo_id,
coverage.files,
source_format=coverage.source_format or "lcov",
- ingested_commit_sha=live_head,
+ ingested_commit_sha=measurement_commit(
+ repo_path,
+ getattr(coverage.provenance, "measured_at", None),
+ live_head,
+ ),
provenance=coverage.provenance,
)
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
index dfe5381db..495a589e8 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/__init__.py
@@ -32,13 +32,14 @@ from .discovery import (
expand_report_args,
expand_report_patterns,
normalize_report_path,
+ oldest_report_time,
prefix_hint,
report_origin_dir,
resolve_reports,
resolve_test_reports,
suggest_prefixes,
)
-from .freshness import FreshnessStatus, coverage_freshness
+from .freshness import FreshnessStatus, coverage_freshness, measurement_commit
from .goprofile import parse_go_coverprofile
from .jacoco import parse_jacoco
from .lcov import parse_lcov
@@ -78,8 +79,10 @@ __all__ = [
"expand_report_patterns",
"file_coverage",
"is_test_file",
+ "measurement_commit",
"measurement_ref",
"normalize_report_path",
+ "oldest_report_time",
"parse",
"parse_apex",
"parse_apex_contexts",
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 0ee11e802..aaf56afd4 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/discovery.py
@@ -477,6 +477,12 @@ class ResolvedCoverage:
withheld: bool = False
# With ``mapping_partial``, the :func:`suggest_prefixes` answer (``None``: abstained).
suggested_prefixes: tuple[str, str] | None = None
+ # When the reports actually read were written, as the oldest of their mtimes.
+ # A report found on disk is a measurement from the last time the suite ran,
+ # which can be long before the commit now at HEAD; the writers stamp the
+ # ingest against this rather than live HEAD so drift reads forward from the
+ # right commit (#3901). ``None`` when nothing was read from disk.
+ measured_at: datetime | None = None
@property
def matched(self) -> int:
@@ -497,6 +503,7 @@ class ResolvedCoverage:
unmatched_sample=tuple((self.unmatched + self.ambiguous)[:UNMATCHED_SAMPLE_CAP]),
mapping_partial=self.mapping_partial,
scope=self.scope,
+ measured_at=self.measured_at,
)
@property
@@ -529,6 +536,11 @@ class CoverageProvenance:
mapping_partial: bool = False
# ``None`` when the writer did not resolve the reports itself.
scope: CoverageScope | None = None
+ # When the reports were written (the oldest of their mtimes), so the writer
+ # can stamp the ingest at the commit the measurement describes instead of
+ # the one that happens to be HEAD now (#3901). Transient: the stored columns
+ # keep their shapes, and ``ingested_at`` stays the ingest time.
+ measured_at: datetime | None = None
@dataclass(frozen=True)
@@ -1318,6 +1330,7 @@ def build_coverage_map(
"""
prefixes = report_prefixes or {}
parsed: list[CoverageReport] = []
+ parsed_paths: list[Path] = []
errors: list[tuple[Path, str]] = []
for path in report_paths:
if is_coverage_data_file(path):
@@ -1338,6 +1351,7 @@ def build_coverage_map(
report.origin_dir = report_origin_dir(path, repo_root)
report.path_prefix = prefixes.get(path)
parsed.append(report)
+ parsed_paths.append(path)
resolved = resolve_reports(
parsed,
repo_keys,
@@ -1353,9 +1367,31 @@ def build_coverage_map(
)
if resolved.mapping_partial and not allow_partial:
resolved.coverage_map, resolved.files, resolved.withheld = {}, [], True
+ # Only the reports that were actually read: one unreadable or empty
+ # artifact must not drag the whole measurement back to its own date. A
+ # withheld mapping contributed no rows at all, so it reports no time.
+ resolved.measured_at = None if resolved.withheld else oldest_report_time(parsed_paths)
return resolved, errors
+def oldest_report_time(paths: Iterable[Path]) -> datetime | None:
+ """The oldest mtime among *paths*, as an aware UTC datetime.
+
+ A coverage report is written when the suite runs, not when repowise reads
+ it, so the oldest of several merged reports is the one whose lines have had
+ the most chance to move since. ``None`` when *paths* is empty or none of
+ them can be stat'ed: the caller then stamps with live HEAD, which is what a
+ report written just now is anyway.
+ """
+ times: list[float] = []
+ for path in paths:
+ try:
+ times.append(path.stat().st_mtime)
+ except OSError:
+ continue
+ return datetime.fromtimestamp(min(times), UTC) if times else None
+
+
def report_origin_dir(path: Path, repo_root: Path) -> str | None:
"""*path*'s directory relative to *repo_root* (POSIX), ``None`` outside it or at its root."""
try:
diff --git a/packages/core/src/repowise/core/analysis/health/coverage/freshness.py b/packages/core/src/repowise/core/analysis/health/coverage/freshness.py
index dcd6590a3..5d2a62deb 100644
--- a/packages/core/src/repowise/core/analysis/health/coverage/freshness.py
+++ b/packages/core/src/repowise/core/analysis/health/coverage/freshness.py
@@ -17,9 +17,40 @@ from datetime import UTC, datetime
from pathlib import Path
from typing import Literal
+from .decay import measurement_ref
+
FreshnessStatus = Literal["current", "stale", "unknown"]
+def measurement_commit(
+ repo_root: str | Path | None,
+ measured_at: datetime | None,
+ head_sha: str | None,
+) -> str | None:
+ """The commit a coverage ingest should record itself against.
+
+ A report discovered on disk measures the tree as it stood when the suite
+ last ran, which can be commits behind the HEAD of the index being built
+ alongside it. Stamping live HEAD there makes the forward drift measure
+ (:func:`decay_since`, which diffs from the recorded commit) read zero drift
+ for lines that have since moved, and applies the stored percentages to
+ lines that are no longer the ones it counted (#3901).
+
+ So the answer is the commit that was HEAD at *measured_at*. That resolves to
+ HEAD itself for a report written since the last commit, which keeps the
+ previous behaviour for the common case of a fresh ``coverage lcov`` run
+ straight before indexing.
+
+ *head_sha* is returned whenever the time is unknown — a writer that did not
+ resolve the reports itself, a report that cannot be stat'ed, a repository
+ git cannot answer for. Guessing HEAD is no worse than what every writer did
+ before; the honest ``None`` case is when there is no HEAD either.
+ """
+ if repo_root is None or measured_at is None:
+ return head_sha
+ return measurement_ref(str(repo_root), None, measured_at) or head_sha
+
+
def coverage_freshness(
measured_commit: str | None, reference_commit: str | None
) -> FreshnessStatus:
diff --git a/packages/core/src/repowise/core/pipeline/persist/__init__.py b/packages/core/src/repowise/core/pipeline/persist/__init__.py
index 25e3d44ce..772422fa1 100644
--- a/packages/core/src/repowise/core/pipeline/persist/__init__.py
+++ b/packages/core/src/repowise/core/pipeline/persist/__init__.py
@@ -55,6 +55,7 @@ from .graph import (
)
from .health import (
_analyzed_commit,
+ _analyzed_repo_path,
refresh_governance_findings,
save_full_health_report,
snapshot_health_from_store,
diff --git a/packages/core/src/repowise/core/pipeline/persist/analysis.py b/packages/core/src/repowise/core/pipeline/persist/analysis.py
index 0684a3aea..2bd2e8435 100644
--- a/packages/core/src/repowise/core/pipeline/persist/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/persist/analysis.py
@@ -24,6 +24,7 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
decisions/governance are idempotent. Intended to run once the analysis
phase has fully completed.
"""
+ from repowise.core.analysis.health.coverage import measurement_commit
from repowise.core.persistence.crud import (
replace_doc_drift_guarded,
save_coverage_files,
@@ -69,13 +70,22 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
# Resolved coverage rows, when a report was ingested this run.
coverage_files = getattr(hr, "coverage_files", None)
if coverage_files:
+ prov = getattr(hr, "coverage_provenance", None)
+ # A report found on disk measures the tree as of its own write
+ # time, not of HEAD (#3901); HEAD is right only for a report
+ # written since the last commit, which measurement_commit also
+ # answers. ``ingested_at`` stays the ingest time.
await save_coverage_files(
session,
repo_id,
coverage_files,
source_format=getattr(hr, "coverage_format", None) or "lcov",
- ingested_commit_sha=head_sha,
- provenance=getattr(hr, "coverage_provenance", None),
+ ingested_commit_sha=measurement_commit(
+ await _persist._analyzed_repo_path(session, repo_id),
+ getattr(prov, "measured_at", None),
+ head_sha,
+ ),
+ provenance=prov,
)
# Per-function blame rollup (FULL tier only; empty otherwise).
fn_blame_rows = getattr(hr, "function_blame_rows", None)
diff --git a/packages/core/src/repowise/core/pipeline/persist/health.py b/packages/core/src/repowise/core/pipeline/persist/health.py
index 95f73d959..d0cee6705 100644
--- a/packages/core/src/repowise/core/pipeline/persist/health.py
+++ b/packages/core/src/repowise/core/pipeline/persist/health.py
@@ -16,6 +16,24 @@ from .prune import path_liveness
logger = structlog.get_logger("repowise.core.pipeline.persist")
+async def _analyzed_repo_path(session: Any, repo_id: str) -> Path | None:
+ """The working tree the health pass scored, read from the repository row.
+
+ The same source :func:`_analyzed_commit` takes HEAD from, so a commit stamp
+ and the tree it names cannot disagree. The pipeline result is not that
+ source: the resume checkpoint hands ``persist_analysis`` a view of the
+ reports only, which carries no path.
+ """
+ from repowise.core.persistence.models import Repository
+
+ try:
+ repo = await session.get(Repository, repo_id)
+ local_path = getattr(repo, "local_path", None) if repo else None
+ return Path(local_path) if local_path else None
+ except Exception:
+ return None
+
+
async def _analyzed_commit(session: Any, repo_id: str) -> str | None:
"""Live HEAD of the repo being indexed, for stamping health rows.
@@ -26,15 +44,10 @@ async def _analyzed_commit(session: Any, repo_id: str) -> str | None:
is honest, while a wrong sha would not be. Both index paths read it here;
the pipeline result carries no sha, so the full path used to stamp ``NULL``.
"""
- from repowise.core.persistence.models import Repository
from repowise.core.workspace.update import get_head_commit
- try:
- repo = await session.get(Repository, repo_id)
- local_path = getattr(repo, "local_path", None) if repo else None
- return get_head_commit(Path(local_path)) if local_path else None
- except Exception:
- return None
+ local_path = await _analyzed_repo_path(session, repo_id)
+ return get_head_commit(local_path) if local_path is not None else None
async def snapshot_health_from_store(session: Any, repo_id: str) -> None:
diff --git a/tests/unit/cli/test_coverage_cmd.py b/tests/unit/cli/test_coverage_cmd.py
index 94da8016c..ef386fbbe 100644
--- a/tests/unit/cli/test_coverage_cmd.py
+++ b/tests/unit/cli/test_coverage_cmd.py
@@ -215,6 +215,109 @@ def test_coverage_add_stamps_live_head_not_stored_column(tmp_path, monkeypatch)
assert recorded["sha"] != _FakeRepoRow.head_commit
+def test_coverage_add_stamps_a_leftover_report_at_the_commit_it_measured(
+ tmp_path, monkeypatch
+) -> None:
+ """Regression for the P1 on #3935: the stamp follows the reports that gave
+ rows, not every file discovery turned up.
+
+ Two commits a week apart, a report from the first afternoon, and an empty
+ leftover from months ago sitting in the same directory. The aggregate is
+ measured at the first commit, so that is what gets stamped — live HEAD
+ would strand the drift check on a tree the report never saw. The leftover
+ is skipped by the parser, so its date must not enter the arithmetic: had it,
+ no commit would predate it and the writer would fall back to live HEAD.
+ """
+ import os
+ from datetime import UTC, datetime
+
+ import git as gitpython
+
+ from repowise.cli.commands import coverage_cmd
+
+ repo = gitpython.Repo.init(tmp_path)
+ with repo.config_writer() as cw:
+ cw.set_value("user", "name", "Alice")
+ cw.set_value("user", "email", "[email protected]")
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "foo.py").write_text("x = 1\n")
+ repo.index.add(["src/foo.py"])
+ july = int(datetime(2026, 7, 3, 12, 0, tzinfo=UTC).timestamp())
+ measured_at_commit = repo.index.commit(
+ "feat: add foo",
+ commit_date=datetime.fromtimestamp(july, UTC).strftime("%Y-%m-%d %H:%M:%S +0000"),
+ author_date=datetime.fromtimestamp(july, UTC).strftime("%Y-%m-%d %H:%M:%S +0000"),
+ ).hexsha
+
+ lcov = tmp_path / "coverage" / "lcov.info"
+ lcov.parent.mkdir()
+ lcov.write_text("TN:\nSF:src/foo.py\nDA:1,2\nLF:1\nLH:1\nend_of_record\n")
+ # Written by the suite an hour after that commit.
+ run = july + 3600
+ os.utime(lcov, (run, run))
+ # A leftover nobody deleted, months older and yielding nothing.
+ stale = tmp_path / "coverage" / "stale.info"
+ stale.write_text("")
+ old = int(datetime(2020, 1, 1, tzinfo=UTC).timestamp())
+ os.utime(stale, (old, old))
+
+ (tmp_path / "src" / "bar.py").write_text("y = 2\n")
+ repo.index.add(["src/bar.py"])
+ live_head = repo.index.commit("feat: add bar").hexsha
+ repo.close()
+
+ class _FakeRepoRow:
+ id = "repo-1"
+ head_commit = None
+
+ recorded: dict = {}
+
+ async def _fake_save_coverage_files(session, repository_id, files, **kwargs):
+ recorded["sha"] = kwargs.get("ingested_commit_sha")
+
+ class _FakeSession:
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *exc):
+ return False
+
+ async def _fake_get_repository_by_path(session, local_path):
+ return _FakeRepoRow()
+
+ monkeypatch.setattr(
+ "repowise.core.persistence.crud.get_repository_by_path",
+ _fake_get_repository_by_path,
+ )
+ monkeypatch.setattr(
+ "repowise.core.persistence.crud.save_coverage_files", _fake_save_coverage_files
+ )
+
+ async def _fake_repo_file_keys(session, repo_id):
+ return {"src/foo.py", "src/bar.py"}
+
+ monkeypatch.setattr(coverage_cmd, "_repo_file_keys", _fake_repo_file_keys)
+ monkeypatch.setattr(coverage_cmd, "get_db_url_for_repo", lambda path: "sqlite:///:memory:")
+
+ async def _no_reconcile(_url):
+ return None
+
+ monkeypatch.setattr(coverage_cmd, "reconcile_schema_best_effort", _no_reconcile)
+ monkeypatch.setattr("repowise.core.persistence.create_engine", lambda url: object())
+ monkeypatch.setattr(
+ "repowise.core.persistence.create_session_factory", lambda engine: object()
+ )
+ monkeypatch.setattr("repowise.core.persistence.get_session", lambda sf: _FakeSession())
+
+ result = CliRunner().invoke(
+ cli, ["coverage", "add", str(lcov), str(stale), "--path", str(tmp_path)]
+ )
+
+ assert result.exit_code == 0, result.output
+ assert recorded["sha"] == measured_at_commit
+ assert recorded["sha"] != live_head
+
+
def _fake_ingest(monkeypatch: pytest.MonkeyPatch, tmp_path, keys: set[str]) -> list:
"""Run `coverage add` against *tmp_path* with *keys* indexed; returns the stored rows."""
diff --git a/tests/unit/health/test_coverage_decay.py b/tests/unit/health/test_coverage_decay.py
index 32cf2ccfd..83faec9e5 100644
--- a/tests/unit/health/test_coverage_decay.py
+++ b/tests/unit/health/test_coverage_decay.py
@@ -13,6 +13,7 @@ from repowise.core.analysis.health.coverage import (
DRIFT_PCT,
decay_for_file,
decay_since,
+ measurement_commit,
measurement_ref,
)
@@ -195,3 +196,77 @@ def test_naive_timestamp_is_read_as_utc_not_local(git_repo) -> None:
aware = measurement_ref(str(git_repo), None, now)
naive = measurement_ref(str(git_repo), None, now.replace(tzinfo=None))
assert aware == naive
+
+
+# --- the commit a writer stamps a report with (issue #3901) -----------------
+
+
+def _commit_all_lines_moved(repo, *, when: str) -> str:
+ """Rewrite every line of ``mod.py`` and commit at *when*; returns the new HEAD."""
+ (repo / "mod.py").write_text("p = 10\nq = 20\nr = 30\ns = 40\n", encoding="utf-8")
+ _git(repo, "add", "-A")
+ _git(repo, "commit", "-qm", "rewrite mod.py", when=when)
+ return _git(repo, "rev-parse", "HEAD").strip()
+
+
+def test_measurement_commit_names_the_commit_that_headed_when_the_report_ran(
+ git_repo,
+) -> None:
+ """A report left on disk describes its own date, not the index's HEAD.
+
+ This is the defect: every writer stamped live HEAD, so the forward drift
+ read — which diffs the covered lines from the recorded commit to HEAD —
+ started at a commit that did not exist when the suite ran. It reported
+ zero decay for lines that had all since moved.
+ """
+ first = _git(git_repo, "rev-parse", "HEAD").strip()
+ head = _commit_all_lines_moved(
+ git_repo, when=(datetime.now(UTC) + timedelta(hours=1)).isoformat()
+ )
+ covered = {"mod.py": {1, 2, 3, 4}}
+
+ stamped = measurement_commit(git_repo, datetime.now(UTC), head)
+ assert stamped == first
+
+ # Non-vacuous: the right commit exposes decay the wrong one hides.
+ from_base = decay_since(str(git_repo), stamped, covered)["mod.py"]
+ assert (from_base.confirmed, from_base.invalidated) == (0, 4)
+ from_head = decay_since(str(git_repo), head, covered)["mod.py"]
+ assert (from_head.confirmed, from_head.invalidated) == (4, 0)
+
+
+def test_a_report_written_after_the_last_commit_still_stamps_head(git_repo) -> None:
+ """The common case keeps its behaviour: ``coverage lcov`` and then index.
+
+ The commit that headed at the report's time is HEAD itself, so a fresh
+ report is not pulled back to an ancestor — which is why this fix costs
+ nothing for the shape every writer already got right.
+ """
+ head = _git(git_repo, "rev-parse", "HEAD").strip()
+ assert measurement_commit(git_repo, datetime.now(UTC), head) == head
+
+
+def test_measurement_commit_falls_back_to_head_without_a_time(git_repo) -> None:
+ """A writer that did not resolve the reports knows nothing about their date.
+
+ ``None`` *measured_at* covers both that and a report that cannot be
+ stat'ed; HEAD is what those writers stamped before, and the honest answer
+ is still HEAD when there is no HEAD either.
+ """
+ head = _git(git_repo, "rev-parse", "HEAD").strip()
+ assert measurement_commit(git_repo, None, head) == head
+ assert measurement_commit(None, datetime.now(UTC), head) == head
+ assert measurement_commit(git_repo, None, None) is None
+
+
+def test_an_unreachable_history_falls_back_to_head(git_repo, tmp_path) -> None:
+ """git cannot place the measurement in either case; the ingest still has a commit.
+
+ A report older than every commit predates the history, and a directory
+ that is not a repository has none to search. Returning HEAD matches what
+ every writer did before the fix rather than dropping the stamp.
+ """
+ head = _git(git_repo, "rev-parse", "HEAD").strip()
+ ancient = datetime(2000, 1, 1, tzinfo=UTC)
+ assert measurement_commit(git_repo, ancient, head) == head
+ assert measurement_commit(tmp_path / "not-a-repo", datetime.now(UTC), head) == head
diff --git a/tests/unit/health/test_coverage_discovery.py b/tests/unit/health/test_coverage_discovery.py
index 8958a4ae3..73e946153 100644
--- a/tests/unit/health/test_coverage_discovery.py
+++ b/tests/unit/health/test_coverage_discovery.py
@@ -7,6 +7,8 @@ repowise's canonical repo-relative POSIX key, so we must reconcile absolute
from __future__ import annotations
+import os
+from datetime import UTC, datetime
from pathlib import Path
from repowise.core.analysis.health.coverage import (
@@ -17,6 +19,7 @@ from repowise.core.analysis.health.coverage import (
discover_artifacts,
expand_report_patterns,
normalize_report_path,
+ oldest_report_time,
prefix_hint,
resolve_reports,
suggest_prefixes,
@@ -799,3 +802,99 @@ def test_source_roots_win_over_the_report_directory() -> None:
)
res = resolve_reports([report], keys)
assert list(res.coverage_map) == ["packages/api/src/x.py"]
+
+
+# ---------------------------------------------------------------------------
+# measured_at — when the reports on disk were written (issue #3901)
+# ---------------------------------------------------------------------------
+
+_LCOV_AB = "SF:src/a.py\nDA:1,1\nend_of_record\n"
+_LCOV_CD = "SF:src/c.py\nDA:1,1\nend_of_record\n"
+# Two suite runs a week apart, so "oldest" and "newest" are unambiguous.
+_JULY = datetime(2026, 7, 3, 12, 0, tzinfo=UTC)
+_JULY_10 = datetime(2026, 7, 10, 12, 0, tzinfo=UTC)
+
+
+def _aged(path: Path, text: str, *, when: datetime) -> Path:
+ """Write *text* to *path* and set its mtime to *when*.
+
+ A report's mtime is the only record of when the suite ran, so the fixture
+ has to age it deliberately rather than inherit "now" from the checkout.
+ """
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ stamp = when.timestamp()
+ os.utime(path, (stamp, stamp))
+ return path
+
+
+def test_oldest_report_time_is_the_oldest_of_several(tmp_path: Path) -> None:
+ late = _aged(tmp_path / "coverage" / "lcov.info", _LCOV_AB, when=_JULY_10)
+ early = _aged(tmp_path / "coverage" / "other.info", _LCOV_CD, when=_JULY)
+
+ assert oldest_report_time([late, early]) == _JULY
+ assert oldest_report_time([early, late]) == _JULY
+ assert oldest_report_time([late]) == _JULY_10
+
+
+def test_oldest_report_time_is_none_when_nothing_can_be_read(tmp_path: Path) -> None:
+ """No report, no time: the writer keeps stamping HEAD instead of guessing.
+
+ A missing path here is a report deleted between discovery and the stamp,
+ which must not read as a measurement from some unknowable date.
+ """
+ assert oldest_report_time([]) is None
+ assert oldest_report_time([tmp_path / "gone.info"]) is None
+
+
+def test_build_coverage_map_carries_the_oldest_report_date(tmp_path: Path) -> None:
+ first = _aged(tmp_path / "coverage" / "lcov.info", _LCOV_AB, when=_JULY)
+ second = _aged(tmp_path / "coverage" / "later.info", _LCOV_CD, when=_JULY_10)
+
+ resolved, errors = build_coverage_map(tmp_path, [first, second], {"src/a.py", "src/c.py"})
+ assert not errors
+ assert resolved.measured_at == _JULY
+ # The provenance is what the writers read, so the date has to survive it.
+ assert resolved.provenance.measured_at == _JULY
+
+
+def test_a_contribution_less_report_does_not_date_the_measurement(tmp_path: Path) -> None:
+ """An artifact that yields no entries is not part of the measurement.
+
+ A stale leftover — an unparseable or empty report someone forgot to
+ delete — must not drag the whole ingest back to its own date, which would
+ strand every line check on a commit it never described.
+ """
+ stale = _aged(tmp_path / "coverage" / "stale.info", "", when=datetime(2020, 1, 1, tzinfo=UTC))
+ current = _aged(tmp_path / "coverage" / "lcov.info", _LCOV_AB, when=_JULY_10)
+
+ resolved, errors = build_coverage_map(tmp_path, [stale, current], {"src/a.py"})
+ assert [p for p, _ in errors] == [stale]
+ assert resolved.measured_at == _JULY_10
+
+
+def test_build_coverage_map_without_a_readable_report_has_no_date(tmp_path: Path) -> None:
+ resolved, errors = build_coverage_map(tmp_path, [], {"src/a.py"})
+ assert not errors
+ assert resolved.measured_at is None
+ assert resolved.provenance.measured_at is None
+
+
+def test_a_withheld_report_has_no_measurement_to_stamp(tmp_path: Path) -> None:
+ """Nothing was parsed into rows, so there is no commit to date them by.
+
+ A withheld mapping writes no aggregate rows, and the one writer that could
+ still read *measured_at* would find a date for a measurement that was
+ refused. ``--allow-partial`` keeps the rows, so it keeps the date too.
+ """
+ lcov = "SF:/ci/build/src/a.py\nDA:1,1\nend_of_record\nSF:/ci/other/b.py\nDA:1,1\nend_of_record\nSF:/ci/other/c.py\nDA:1,1\nend_of_record\n"
+ refused = _aged(tmp_path / "coverage" / "lcov.info", lcov, when=_JULY)
+
+ withheld, _ = build_coverage_map(tmp_path, [refused], {"src/a.py"})
+ assert withheld.withheld is True
+ assert withheld.measured_at is None
+ assert withheld.provenance.measured_at is None
+
+ kept, _ = build_coverage_map(tmp_path, [refused], {"src/a.py"}, allow_partial=True)
+ assert kept.withheld is False and kept.files
+ assert kept.measured_at == _JULY
diff --git a/tests/unit/persistence/test_persist_analysis_coverage_stamp.py b/tests/unit/persistence/test_persist_analysis_coverage_stamp.py
new file mode 100644
index 000000000..b99ebb985
--- /dev/null
+++ b/tests/unit/persistence/test_persist_analysis_coverage_stamp.py
@@ -0,0 +1,193 @@
+"""The commit a coverage ingest records itself against.
+
+A report found on disk measures the tree as of the run that wrote it, which
+can be commits behind the HEAD being indexed alongside it. The writers used to
+stamp live HEAD unconditionally, so the forward drift read diffed from a commit
+that did not exist when the suite ran and reported zero (#3901).
+"""
+
+from __future__ import annotations
+
+import os
+import subprocess
+from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
+
+import pytest
+from sqlalchemy import select
+
+from repowise.core.analysis.health.coverage import CoverageProvenance
+from repowise.core.analysis.health.coverage.model import FileCoverage
+from repowise.core.persistence.models import CoverageFile, CoverageIngest
+from repowise.core.pipeline.persist import persist_analysis
+from tests.unit.persistence.helpers import insert_repo
+
+_PATH = "src/app.py"
+
+
+def _git(cwd, *args: str, when: str | None = None) -> str:
+ """Run git in *cwd*. *when* pins both dates, since ``rev-list --before``
+ filters on the committer date and ``git commit --date`` only sets the
+ author one."""
+ env = None
+ if when is not None:
+ env = {**os.environ, "GIT_COMMITTER_DATE": when, "GIT_AUTHOR_DATE": when}
+ return subprocess.run(
+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True, env=env
+ ).stdout
+
+
+def git_repo(tmp_path):
+ """Two commits, the second dated an hour into the future.
+
+ The future date is what makes the fixture deterministic: "now" then sits
+ strictly between the two, so a report stamped now resolves to the first
+ commit instead of whichever side of a real commit time the run lands on.
+ """
+ _git(tmp_path, "init", "-q")
+ _git(tmp_path, "config", "user.email", "[email protected]")
+ _git(tmp_path, "config", "user.name", "t")
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "app.py").write_text("a = 1\nb = 2\nc = 3\n", encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+ _git(tmp_path, "commit", "-qm", "init")
+ later = (datetime.now(UTC) + timedelta(hours=1)).isoformat()
+ (tmp_path / "src" / "app.py").write_text("x = 10\ny = 20\nz = 30\n", encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+ _git(tmp_path, "commit", "-qm", "rewrite", when=later)
+ return tmp_path
+
+
+def _result(measured_at: datetime | None = None) -> SimpleNamespace:
+ """A pipeline result carrying only what the analysis phase reads.
+
+ *measured_at* is the report's own write time, which the discovery layer
+ puts on the provenance; ``None`` means the writer never resolved one.
+ Deliberately no ``repo_path``: that is the shape the resume checkpoint
+ hands over, and the reason the tree has to come from the repository row.
+ """
+ return SimpleNamespace(
+ dead_code_report=None,
+ decision_report=None,
+ health_report=SimpleNamespace(
+ metrics=[
+ {
+ "file_path": _PATH,
+ "score": 5.0,
+ "max_ccn": 3,
+ "max_nesting": 1,
+ "nloc": 40,
+ "duplication_pct": 0.0,
+ "has_test_file": False,
+ "line_coverage_pct": None,
+ "branch_coverage_pct": None,
+ "module": "src",
+ }
+ ],
+ findings=[],
+ refactoring_suggestions=[],
+ performance_plan_policy=None,
+ kpis={},
+ coverage_files=[
+ FileCoverage(
+ file_path=_PATH,
+ line_coverage_pct=100.0,
+ branch_coverage_pct=None,
+ covered_lines=[1, 2, 3],
+ total_coverable_lines=3,
+ )
+ ],
+ coverage_format="lcov",
+ coverage_provenance=CoverageProvenance(
+ source_formats=("lcov",), measured_at=measured_at
+ ),
+ function_blame_rows=None,
+ ),
+ )
+
+
+async def _ingest_stamps(session, repo_id: str) -> list[str | None]:
+ rows = (
+ (
+ await session.execute(
+ select(CoverageIngest).where(CoverageIngest.repository_id == repo_id)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ assert rows, "the analysis phase must have written an ingest row"
+ return [row.ingested_commit_sha for row in rows]
+
+
+async def _file_stamps(session, repo_id: str) -> set[str | None]:
+ rows = (
+ (
+ await session.execute(
+ select(CoverageFile).where(CoverageFile.repository_id == repo_id)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ assert rows, "the analysis phase must have written coverage rows"
+ return {row.ingested_commit_sha for row in rows}
+
+
+class TestMeasuredCommitStamp:
+ async def test_a_report_older_than_head_is_stamped_where_it_measured(
+ self, async_session, git_repo
+ ):
+ """The defect: an on-disk report was recorded at HEAD, so drift read zero.
+
+ The ingest has to name the commit that headed when the suite ran, which
+ is what lets ``decay_since`` diff the covered lines forward from there
+ and see that all three of them have since moved.
+ """
+ head, first = _git(git_repo, "rev-list", "HEAD").strip().split()
+ repo = await insert_repo(async_session, local_path=str(git_repo))
+ await persist_analysis(_result(datetime.now(UTC)), async_session, repo.id)
+
+ assert await _ingest_stamps(async_session, repo.id) == [first]
+ assert await _file_stamps(async_session, repo.id) == {first}
+ assert head != first
+
+ async def test_a_report_written_since_the_last_commit_still_stamps_head(
+ self, async_session, git_repo
+ ):
+ """A fresh ``coverage lcov`` straight before indexing keeps today's answer.
+
+ The commit that headed at its time is HEAD, so the fix costs nothing for
+ the case every writer already got right; this test is what stops a later
+ tightening from pulling fresh reports back to their parent.
+ """
+ head = _git(git_repo, "rev-parse", "HEAD").strip()
+ repo = await insert_repo(async_session, local_path=str(git_repo))
+ await persist_analysis(
+ _result(datetime.now(UTC) + timedelta(hours=2)), async_session, repo.id
+ )
+ assert await _ingest_stamps(async_session, repo.id) == [head]
+
+ async def test_a_writer_that_does_not_know_the_time_stamps_head(
+ self, async_session, git_repo
+ ):
+ """Unknown is not "as old as the filesystem": a report dated now, and no
+ date at all, both stay at HEAD."""
+ head = _git(git_repo, "rev-parse", "HEAD").strip()
+ repo = await insert_repo(async_session, local_path=str(git_repo))
+ await persist_analysis(_result(None), async_session, repo.id)
+ assert await _ingest_stamps(async_session, repo.id) == [head]
+
+ async def test_the_stamp_needs_no_repo_path_on_the_result(self, async_session, git_repo):
+ """The tree comes from the repository row, because the result has none.
+
+ Reading the path off the pipeline result resolved nothing on the resume
+ path, so one run wrote two ingests of the same measurement — one at HEAD,
+ one at the report's commit — and split the trend across them.
+ """
+ first = _git(git_repo, "rev-parse", "HEAD~1").strip()
+ repo = await insert_repo(async_session, local_path=str(git_repo))
+ assert not hasattr(_result(), "repo_path")
+ await persist_analysis(_result(datetime.now(UTC)), async_session, repo.id)
+ assert await _ingest_stamps(async_session, repo.id) == [first]