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.

12.1 KB
Raw Blame
"""``/health/trend``'s per-file movement block.

The block is headed "Largest score changes since last index" and was built by
sorting the deltas ascending and slicing the first 50 — that is, the 50
biggest *drops*. Improvements only appeared while fewer than 50 files had
regressed, so the one index that most wants to show progress, the one after a
cleanup or a re-score, is the one that hides it. And with no total beside the
slice a reader could not tell a complete list from a truncated one.

Measured on the repowise index when this was written: only 15 files moved
between the last two snapshots, so the cap was latent — but the oldest-vs-newest
comparison, which is the shape a full re-index produces, moves 183 files with
107 regressions. These construct that state rather than waiting for it.
"""

from __future__ import annotations

from datetime import UTC, datetime, timedelta

from repowise.core.persistence.crud import save_health_snapshot, upsert_repository
from repowise.server.routers.code_health.trends_routes import FILE_DELTA_LIMIT

from .conftest import create_test_repo


async def _two_snapshots(session, repo_id: str, before: dict, after: dict) -> None:
    base = datetime(2026, 1, 1, tzinfo=UTC)
    for day, scores in ((0, before), (1, after)):
        await save_health_snapshot(
            session,
            repo_id,
            hotspot_health=5.0,
            average_health=5.0,
            worst_performer_path="a.py",
            worst_performer_score=1.0,
            per_file_scores=scores,
            taken_at=base + timedelta(days=day),
        )
    await session.commit()


async def _repo(client, session, tmp_path):
    repo = await create_test_repo(client, tmp_path)
    await upsert_repository(session, name="r", local_path=repo["local_path"])
    return repo["id"]


async def test_improvements_survive_a_wall_of_regressions(client, session, tmp_path) -> None:
    """The failure the ascending sort produced, constructed exactly.

    ``FILE_DELTA_LIMIT`` + 10 files regress by a little and three improve by a
    lot. Sorted ascending, the improvements sit past the end of the slice and
    never reach the page, even though they are the largest changes in the repo.
    """
    repo_id = await _repo(client, session, tmp_path)
    before = {f"r{i}.py": 8.0 for i in range(FILE_DELTA_LIMIT + 10)}
    after = {f"r{i}.py": 7.9 for i in range(FILE_DELTA_LIMIT + 10)}
    for i in range(3):
        before[f"win{i}.py"] = 2.0
        after[f"win{i}.py"] = 9.0

    await _two_snapshots(session, repo_id, before, after)
    resp = await client.get(f"/api/repos/{repo_id}/health/trend")
    assert resp.status_code == 200, resp.text
    body = resp.json()

    paths = [d["file_path"] for d in body["file_deltas"]]
    assert [p for p in paths if p.startswith("win")] == ["win0.py", "win1.py", "win2.py"]
    # And they lead, because they are the biggest movements in either direction.
    assert paths[:3] == ["win0.py", "win1.py", "win2.py"]


async def test_the_total_counts_everything_the_slice_dropped(client, session, tmp_path) -> None:
    repo_id = await _repo(client, session, tmp_path)
    n = FILE_DELTA_LIMIT + 27
    before = {f"f{i}.py": 8.0 for i in range(n)}
    # Distinct magnitudes so the ordering is total and the slice is well-defined.
    after = {f"f{i}.py": 8.0 - (i + 1) / 100 for i in range(n)}
    await _two_snapshots(session, repo_id, before, after)

    body = (await client.get(f"/api/repos/{repo_id}/health/trend")).json()

    assert len(body["file_deltas"]) == FILE_DELTA_LIMIT
    assert body["file_deltas_total"] == n


async def test_the_total_equals_the_list_when_nothing_is_dropped(
    client, session, tmp_path
) -> None:
    """The common case, and the one that makes the UI say "all N" rather than
    "the N largest of N"."""
    repo_id = await _repo(client, session, tmp_path)
    await _two_snapshots(
        session, repo_id, {"a.py": 8.0, "b.py": 5.0}, {"a.py": 7.0, "b.py": 6.0}
    )

    body = (await client.get(f"/api/repos/{repo_id}/health/trend")).json()

    assert body["file_deltas_total"] == 2 == len(body["file_deltas"])


async def test_unchanged_files_are_not_counted_as_movement(client, session, tmp_path) -> None:
    """``file_deltas_total`` counts files that moved, not files that exist —
    otherwise "3 of 3,263" would read as though the repo barely changed.

    A guard, not a regression test: the zero-delta filter predates this change,
    so only the ``file_deltas_total`` lookup fails on revert.
    """
    repo_id = await _repo(client, session, tmp_path)
    before = {f"f{i}.py": 8.0 for i in range(20)}
    after = dict(before)
    after["f0.py"] = 6.0

    await _two_snapshots(session, repo_id, before, after)
    body = (await client.get(f"/api/repos/{repo_id}/health/trend")).json()

    assert body["file_deltas_total"] == 1


async def test_ordering_is_total_across_equal_magnitudes(client, session, tmp_path) -> None:
    """Ties broken by path, so the slice boundary cannot shuffle between
    requests — the set membership of a truncated list has to be stable."""
    repo_id = await _repo(client, session, tmp_path)
    before = {"c.py": 8.0, "a.py": 8.0, "b.py": 8.0}
    # Same magnitude, opposite directions: a |delta| sort alone is ambiguous.
    after = {"c.py": 7.0, "a.py": 9.0, "b.py": 7.0}
    await _two_snapshots(session, repo_id, before, after)

    body = (await client.get(f"/api/repos/{repo_id}/health/trend")).json()

    assert [d["file_path"] for d in body["file_deltas"]] == ["a.py", "b.py", "c.py"]


async def test_a_single_snapshot_reports_no_movement(client, session, tmp_path) -> None:
    """Zero-history edge: the block is empty and the total says so rather than
    being absent, so the UI never has to guess whether the field is missing or
    the answer is nothing."""
    repo_id = await _repo(client, session, tmp_path)
    await save_health_snapshot(
        session,
        repo_id,
        hotspot_health=5.0,
        average_health=5.0,
        worst_performer_path=None,
        worst_performer_score=None,
        per_file_scores={"a.py": 5.0},
    )
    await session.commit()

    body = (await client.get(f"/api/repos/{repo_id}/health/trend")).json()

    assert body["file_deltas"] == []
    assert body["file_deltas_total"] == 0
    assert body["snapshot_count"] == 1


async def test_history_rows_carry_the_split_and_the_maintainability_pillar(
    client, session, tmp_path
) -> None:
    """The per-point series the chart draws must survive the response model.

    These three are stored per snapshot and serialized by ``recent_kpis``, but
    the route declares a response model, so a field missing from that model is
    dropped after serialization and reaches the client as ``null`` — with the
    core unit tests still green.
    """
    repo_id = await _repo(client, session, tmp_path)
    await save_health_snapshot(
        session,
        repo_id,
        hotspot_health=5.0,
        average_health=7.0,
        worst_performer_path=None,
        worst_performer_score=None,
        per_file_scores={"a.py": 7.0},
        structure_average=1.6,
        history_average=1.4,
        maintainability_average=8.0,
    )
    await session.commit()

    body = (await client.get(f"/api/repos/{repo_id}/health/trend")).json()

    assert body["history"][0]["structure_average"] == 1.6
    assert body["history"][0]["history_average"] == 1.4
    assert body["history"][0]["maintainability_average"] == 8.0


async def test_a_narrowed_trend_blanks_the_figures_it_never_recorded(
    client, session, tmp_path
) -> None:
    """A production-scoped snapshot recorded only its own average. The rest
    describes the whole repository, so it is blanked rather than served under a
    label that would make it read as a production measurement."""
    repo_id = await _repo(client, session, tmp_path)
    await save_health_snapshot(
        session,
        repo_id,
        hotspot_health=5.0,
        average_health=7.0,
        worst_performer_path=None,
        worst_performer_score=None,
        per_file_scores={"a.py": 7.0},
        structure_average=1.6,
        history_average=1.4,
        maintainability_average=8.0,
        production_average=6.0,
    )
    await session.commit()

    body = (await client.get(f"/api/repos/{repo_id}/health/trend?scope=production")).json()

    row = body["history"][0]
    assert row["average_health"] == 6.0
    assert row["structure_average"] is None
    assert row["history_average"] is None
    assert row["maintainability_average"] is None


async def test_each_direction_keeps_half_the_slice(client, session, tmp_path) -> None:
    """The page lists "got worse" and "improved" apart. A plain top-N by size
    let many larger regressions fill the whole slice and leave the improved
    group empty beside a count saying it has rows."""
    repo_id = await _repo(client, session, tmp_path)
    before, after = {}, {}
    for i in range(FILE_DELTA_LIMIT):
        before[f"down{i:02d}.py"], after[f"down{i:02d}.py"] = 9.0, 5.0
    for i in range(30):
        before[f"up{i:02d}.py"], after[f"up{i:02d}.py"] = 5.0, 5.5
    await _two_snapshots(session, repo_id, before, after)

    body = (await client.get(f"/api/repos/{repo_id}/health/trend")).json()

    deltas = body["file_deltas"]
    half = FILE_DELTA_LIMIT // 2
    assert len(deltas) == FILE_DELTA_LIMIT
    assert sum(1 for d in deltas if d["delta"] > 0) == half
    assert sum(1 for d in deltas if d["delta"] < 0) == FILE_DELTA_LIMIT - half
    # Still largest first across the merged slice.
    assert [abs(d["delta"]) for d in deltas] == sorted((abs(d["delta"]) for d in deltas), reverse=True)
    assert body["file_deltas_worse"] == FILE_DELTA_LIMIT
    assert body["file_deltas_improved"] == 30
    assert body["file_deltas_total"] == FILE_DELTA_LIMIT + 30


async def test_a_direction_with_few_rows_leaves_its_half_to_the_other(
    client, session, tmp_path
) -> None:
    repo_id = await _repo(client, session, tmp_path)
    before = {f"d{i:02d}.py": 9.0 for i in range(FILE_DELTA_LIMIT + 5)}
    after = {p: 8.0 for p in before}
    before["up.py"], after["up.py"] = 4.0, 4.1
    await _two_snapshots(session, repo_id, before, after)

    body = (await client.get(f"/api/repos/{repo_id}/health/trend")).json()

    deltas = body["file_deltas"]
    assert len(deltas) == FILE_DELTA_LIMIT
    assert [d["file_path"] for d in deltas if d["delta"] > 0] == ["up.py"]
    assert (body["file_deltas_worse"], body["file_deltas_improved"]) == (FILE_DELTA_LIMIT + 5, 1)


async def test_the_list_defers_the_per_file_maps(session, client, tmp_path) -> None:
    """``file_maps=False`` loads every row's scalars and none of the
    repository-sized maps; the trend route then loads only the last two."""
    from sqlalchemy import inspect

    from repowise.core.persistence.crud import list_health_snapshots

    repo_id = await _repo(client, session, tmp_path)
    await _two_snapshots(session, repo_id, {"a.py": 8.0}, {"a.py": 7.0})
    session.expunge_all()

    rows = await list_health_snapshots(session, repo_id, file_maps=False)

    assert [r.average_health for r in rows] == [5.0, 5.0]
    for row in rows:
        unloaded = inspect(row).unloaded
        assert {"per_file_scores_json", "per_file_deductions_json"} <= unloaded


async def test_a_narrowed_trend_still_lists_movement(client, session, tmp_path) -> None:
    """The scoped projection reads the deferred map through its stored row."""
    repo_id = await _repo(client, session, tmp_path)
    base = datetime(2026, 1, 1, tzinfo=UTC)
    for day, score in ((0, 8.0), (1, 6.0)):
        await save_health_snapshot(
            session,
            repo_id,
            hotspot_health=5.0,
            average_health=5.0,
            worst_performer_path=None,
            worst_performer_score=None,
            per_file_scores={"src/a.py": score, "src/b.py": 5.0},
            production_average=score,
            taken_at=base + timedelta(days=day),
        )
    await session.commit()
    session.expunge_all()

    body = (await client.get(f"/api/repos/{repo_id}/health/trend?scope=production")).json()

    assert body["file_deltas"] == [
        {"file_path": "src/a.py", "before": 8.0, "after": 6.0, "delta": -2.0}
    ]
    assert body["file_deltas_worse"] == 1