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.

perf(risk): reuse one baseline walk across the changes scored against it (#1589)

Raghav Chamadiyaeaba5237a69d
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 486a0f85a..5b11f1225 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -459,6 +459,12 @@ those fixes replaced (`overlapping_lines`), and how long ago the most recent
was (`last_fix_days_ago`). `total_fixes` counts distinct commits, not rows,
and `files` is capped at ten with `truncated` reporting overflow.
+Each file also carries how much of *this* change sits in it — `changed_lines`
+and `share_of_change` — with `changed_lines_in_fixed_files` as the total across
+them. That join is what lets the response say where the risk sits rather than
+only that some touched file has a past: the score is whole-change, so when one
+returned file holds at least half the changed lines, `concentration` names it.
+
`overlapping_lines` is labelled `approximate` in the payload, and that label is
load-bearing: a past fix's ranges are numbered against its own parent commit,
so anything that moved lines in between shifts them. Read it as "this
diff --git a/docs/layers/CHANGE_RISK.md b/docs/layers/CHANGE_RISK.md
index da8cba80e..f885466fe 100644
--- a/docs/layers/CHANGE_RISK.md
+++ b/docs/layers/CHANGE_RISK.md
@@ -106,6 +106,28 @@ The `repowise risk` CLI samples the repo's recent commits live (`--baseline`,
default 200) to compute this percentile; in the web UI it is precomputed from the
indexed commit history.
+### What the sample is anchored to
+
+The sample is the recent history the change is measured against, and where it
+starts depends on what is being scored:
+
+| Subject | Sample runs back from | Why |
+|---|---|---|
+| A commit already in `HEAD`'s history | `HEAD` | Ranked against how the repo commits *now*. |
+| A commit that is not (another branch) | that commit | `HEAD`'s history is not its cohort. |
+| A `base..head` range | the merge-base of the two sides | The range's own commits stay out of the distribution it is measured against. |
+| Uncommitted work | `HEAD` | Same subject, same cohort as scoring `HEAD`. |
+
+A change never ranks against itself: the target's own score is removed from the
+sample before the percentile is taken.
+
+Because the sample depends only on that anchor and the active filters, and not
+on the individual change, one walk is reused for every change scored against the
+same history in the same process. A long-running MCP server pays for the walk
+once and answers subsequent `get_change_risk` calls without repeating it. A new
+commit, a moved branch, or a different set of filters produces a different
+anchor or a different filter set, and so a fresh walk.
+
## Calibration & accuracy
Constants are learned offline against the defect corpus (AG-SZZ bug-inducing
diff --git a/packages/core/src/repowise/core/analysis/change_risk/__init__.py b/packages/core/src/repowise/core/analysis/change_risk/__init__.py
index 82b42da3b..2aedbcac5 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/__init__.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/__init__.py
@@ -9,7 +9,7 @@ and is a natural pre-merge / PR gate.
from __future__ import annotations
-from .baseline import baseline_scores
+from .baseline import baseline_samples, scores_excluding
from .features import (
WORKING_TREE_REF,
ChangeFeatures,
@@ -26,6 +26,7 @@ from .service import (
ChangeRiskResult,
change_risk_payload,
normalize_extensions,
+ range_anchor,
riskignore_patterns,
score_live_change,
)
@@ -38,7 +39,7 @@ __all__ = [
"ChangeRiskResult",
"RiskDriver",
"RiskNormalizer",
- "baseline_scores",
+ "baseline_samples",
"change_features_from_stored",
"change_risk_payload",
"extract_commit_features",
@@ -46,9 +47,11 @@ __all__ = [
"extract_worktree_features",
"features_from_file_changes",
"normalize_extensions",
+ "range_anchor",
"review_priority_classification",
"riskignore_patterns",
"score_change",
"score_live_change",
+ "scores_excluding",
"working_tree_is_dirty",
]
diff --git a/packages/core/src/repowise/core/analysis/change_risk/baseline.py b/packages/core/src/repowise/core/analysis/change_risk/baseline.py
index 2ac407aee..b0c6ff436 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/baseline.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/baseline.py
@@ -19,8 +19,10 @@ from .model import score_change
# of a default get_change_risk call and is identical for every change scored
# against the same repo state. Keyed on the *resolved anchor sha* (not the ref
# name) so a new commit on HEAD busts the entry, plus every other input that
-# changes the sample (sample size, filters, the self-excluded ref).
-_BASELINE_CACHE: dict[tuple, list[float]] = {}
+# changes the sample (sample size, filters). Deliberately NOT keyed on the
+# target being scored: the sample is stored whole and the target's own score is
+# dropped when ranking, so two changes against the same history share one walk.
+_BASELINE_CACHE: dict[tuple, list[tuple[str, float]]] = {}
# Crude bound so a long-lived MCP server that scores many distinct changes does
# not grow the memo without limit. On overflow the whole cache is dropped
# (correctness is unaffected; the next call just recomputes). Upgrade to an LRU
@@ -37,28 +39,47 @@ def _resolve_anchor_sha(repo_path: str, anchor: str) -> str | None:
"""Resolve *anchor* to a full sha for cache keying, or None if it cannot be.
check=False: a bad anchor is not fatal here - it just means we skip caching
- and let :func:`baseline_scores` compute (and degrade) as it normally would.
+ and let :func:`baseline_samples` compute (and degrade) as it normally would.
"""
sha = _git(["rev-parse", "--verify", "--quiet", anchor], repo_path, check=False).strip()
return sha or None
-def baseline_scores(
+def scores_excluding(samples: list[tuple[str, float]], excluded_ref: str) -> list[float]:
+ """Drop the target commit's own score from a sample, keeping the rest.
+
+ Self-exclusion is a rank-time filter, not a property of the sample, so the
+ walk is cached whole and each target removes only itself. *excluded_ref* is
+ a commit sha, full or abbreviated - a ref *name* matches nothing, since the
+ sample is keyed by sha. Empty means nothing to exclude (a range or an
+ uncommitted change is not in the sample to begin with). An abbreviation
+ short enough to prefix-match several shas will drop all of them.
+ """
+ if not excluded_ref:
+ return [score for _, score in samples]
+ return [
+ score
+ for sha, score in samples
+ if not (sha.startswith(excluded_ref) or excluded_ref.startswith(sha))
+ ]
+
+
+def baseline_samples(
repo_path: str,
anchor: str,
limit: int,
extensions: tuple[str, ...],
- excluded_ref: str,
exclude_patterns: tuple[str, ...] = (),
-) -> list[float]:
+) -> list[tuple[str, float]]:
"""Score the repo's recent commits to build a local risk distribution.
+ Returns ``(sha, score)`` pairs so a caller can exclude the change it is
+ ranking (see :func:`scores_excluding`) without needing a sample of its own.
+
One ``git log --numstat`` call (no per-commit author lookup), so it stays
cheap enough for a pre-merge gate. Experience is left unknown for the
baseline; the target is ranked with experience likewise unknown, so the
comparison is like-with-like: a diff-shape percentile within this repo.
- *excluded_ref* is a full or abbreviated Git ref for the target commit to
- omit from its own sample. It is unrelated to path exclusions.
*exclude_patterns* use gitignore syntax and are applied to every sampled
commit, matching the target change's filtering.
"""
@@ -77,16 +98,13 @@ def baseline_scores(
timeout=GIT_TIMEOUT_SECONDS,
).stdout
- scores: list[float] = []
+ samples: list[tuple[str, float]] = []
exclude_spec = pathspec.PathSpec.from_lines("gitwildmatch", exclude_patterns)
for block in out.split("\x1e"):
lines = block.strip().split("\n")
if not lines or not lines[0]:
continue
sha, rows = lines[0].strip(), lines[1:]
- # Do not let the target commit rank against itself (short or full ref).
- if excluded_ref and (sha.startswith(excluded_ref) or excluded_ref.startswith(sha)):
- continue
changes: list[tuple[str, int, int]] = []
for row in rows:
parts = row.split("\t")
@@ -103,36 +121,33 @@ def baseline_scores(
if not changes:
continue
feats = features_from_file_changes(changes, exp=None)
- scores.append(score_change(feats).score)
- return scores
+ samples.append((sha, score_change(feats).score))
+ return samples
-def baseline_scores_cached(
+def baseline_samples_cached(
repo_path: str,
anchor: str,
limit: int,
extensions: tuple[str, ...],
- excluded_ref: str,
exclude_patterns: tuple[str, ...] = (),
-) -> list[float]:
- """Memoized :func:`baseline_scores`, keyed on the resolved anchor sha.
+) -> list[tuple[str, float]]:
+ """Memoized :func:`baseline_samples`, keyed on the resolved anchor sha.
- Same result as :func:`baseline_scores` for the same inputs; it just skips the
- 200-commit git walk when an identical sample was already computed this
+ Same result as :func:`baseline_samples` for the same inputs; it just skips
+ the 200-commit git walk when an identical sample was already computed this
process. The anchor is resolved to a sha so ``HEAD`` (or a branch ref) busts
the entry as soon as a new commit lands. When the anchor cannot be resolved
the call falls through to an uncached computation.
"""
sha = _resolve_anchor_sha(repo_path, anchor)
if sha is None:
- return baseline_scores(
- repo_path, anchor, limit, extensions, excluded_ref, exclude_patterns
- )
- key = (repo_path, sha, limit, extensions, excluded_ref, exclude_patterns)
+ return baseline_samples(repo_path, anchor, limit, extensions, exclude_patterns)
+ key = (repo_path, sha, limit, extensions, exclude_patterns)
if key in _BASELINE_CACHE:
return _BASELINE_CACHE[key]
- scores = baseline_scores(repo_path, anchor, limit, extensions, excluded_ref, exclude_patterns)
+ samples = baseline_samples(repo_path, anchor, limit, extensions, exclude_patterns)
if len(_BASELINE_CACHE) >= _BASELINE_CACHE_MAX:
_BASELINE_CACHE.clear()
- _BASELINE_CACHE[key] = scores
- return scores
+ _BASELINE_CACHE[key] = samples
+ return samples
diff --git a/packages/core/src/repowise/core/analysis/change_risk/service.py b/packages/core/src/repowise/core/analysis/change_risk/service.py
index 4cff479ea..5a4c94e8c 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/service.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/service.py
@@ -6,10 +6,11 @@ import subprocess
from dataclasses import dataclass, replace
from pathlib import Path
-from .baseline import baseline_scores_cached
+from .baseline import baseline_samples_cached, scores_excluding
from .features import (
GIT_TIMEOUT_SECONDS,
ChangeFeatures,
+ _git,
extract_commit_features,
extract_range_features,
extract_worktree_features,
@@ -57,6 +58,44 @@ def riskignore_patterns(repo_path: str) -> tuple[str, ...]:
)
+def _commit_anchor(repo_path: str, target: str) -> tuple[str, str]:
+ """Return ``(anchor, resolved sha)`` for a commit target.
+
+ A commit in ``HEAD``'s history is ranked against the repo's current sample
+ rather than building a private one, so every such target in a process shares
+ a single walk. A commit that is not (another branch, an unrelated ref) keeps
+ its own anchor, since HEAD's history is not its cohort.
+
+ The sha comes back because self-exclusion needs it: the sample holds commit
+ shas, while the target is whatever the caller spelled — ``"HEAD"`` most of
+ the time, which matches no sha and so excluded nothing.
+ """
+ # ^{commit} peels an annotated tag to the commit it points at. Without it the
+ # tag object's own sha comes back, which is in no sample and is never equal
+ # to a merge-base, so both the anchor and the self-exclusion below miss.
+ target_sha = _git(
+ ["rev-parse", "--verify", "--quiet", f"{target}^{{commit}}"], repo_path, check=False
+ ).strip()
+ if target == "HEAD" or not target_sha:
+ return "HEAD" if target == "HEAD" else target, target_sha
+ # merge-base == the target itself is exactly "target is an ancestor of HEAD",
+ # read off stdout because _git does not surface a return code.
+ merge_base = _git(["merge-base", target, "HEAD"], repo_path, check=False).strip()
+ return ("HEAD" if merge_base == target_sha else target), target_sha
+
+
+def range_anchor(repo_path: str, base: str, head: str) -> str:
+ """Anchor a range's baseline to where its two sides diverged.
+
+ Keeps the range's own commits out of the distribution it is measured
+ against, and lets ranges off the same fork point share one memoized walk.
+ Note this also drops commits that landed on *base* after the fork: they are
+ cohort members, but including them would mean re-walking per head.
+ """
+ merge_base = _git(["merge-base", base, head], repo_path, check=False).strip()
+ return merge_base or base
+
+
def normalize_extensions(extensions: tuple[str, ...]) -> tuple[str, ...]:
"""Add a leading dot to requested suffixes, matching the CLI contract."""
return tuple(ext if ext.startswith(".") else f".{ext}" for ext in extensions)
@@ -105,26 +144,26 @@ def score_live_change(
features = extract_range_features(
repo_path, base, head, extensions=extensions, exclude_patterns=effective_excludes
)
- anchor, excluded_ref = head, ""
+ anchor, excluded_ref = range_anchor(repo_path, base, head), ""
else:
features = extract_commit_features(
repo_path, target, extensions=extensions, exclude_patterns=effective_excludes
)
- anchor, excluded_ref = target, features.ref
+ anchor, excluded_ref = _commit_anchor(repo_path, target)
risk = score_change(features)
percentile: float | None = None
priority: str | None = None
baseline_sample_size = 0
if baseline:
- scores = baseline_scores_cached(
+ samples = baseline_samples_cached(
repo_path,
anchor,
baseline,
extensions,
- excluded_ref=excluded_ref,
exclude_patterns=effective_excludes,
)
+ scores = scores_excluding(samples, excluded_ref)
baseline_sample_size = len(scores)
if len(scores) >= _MIN_BASELINE:
normalizer = RiskNormalizer.from_scores(scores)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 734f02a7e..8d70908d4 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
@@ -64,7 +64,7 @@ async def get_change_risk(
suite), never "untested", when no map is ingested.
``prior_fixes`` appears only when the changed files carry counted bug fixes:
- per-file counts, never a commit name.
+ per-file counts, never a commit name; ``concentration`` names where it sits.
Args:
revspec: Commit or ``base..head`` range to score. Omit it to score the
@@ -120,15 +120,38 @@ async def get_change_risk(
prior_fixes = await _prior_fixes_block(ctx, changed)
if prior_fixes is not None:
payload["prior_fixes"] = prior_fixes
- # source: live_git marks that this response is computed from the working
- # checkout's git, not the index, so index freshness does not apply to it.
+ # source: live_git marks that the *score* is computed from the working
+ # checkout's git. The two blocks above are index-backed, so the freshness
+ # fields do apply to them, scoped to the change's files. None (not []) when
+ # there are none, so a degraded read keeps the repo-level staleness warning
+ # instead of reading as "nothing served, nothing to warn about".
payload["_meta"] = _build_meta(
timing_ms=(time.perf_counter() - started) * 1000,
+ repository=await _repository(ctx),
+ targets=sorted(changed) or None,
extra={"source": "live_git"},
)
return payload
+async def _repository(ctx: Any) -> Any | None:
+ """The indexed repository row, or ``None`` without an index.
+
+ Only ``_meta`` needs it: the per-file blocks below resolve their own repo id
+ inside the session they query in.
+ """
+ from repowise.core.persistence.database import get_session
+
+ session_factory = getattr(ctx, "session_factory", None)
+ if session_factory is None:
+ return None
+ try:
+ async with get_session(session_factory) as session:
+ return await _get_repo(session)
+ except (LookupError, SQLAlchemyError):
+ return None
+
+
def _normalize_revspec(revspec: str | None) -> str:
"""Mirror ``score_live_change``'s three-dot handling for ``changed_lines``.
@@ -292,10 +315,22 @@ async def _prior_fixes_block(ctx: Any, changed: dict[str, set[int]]) -> dict[str
if not events:
return None
+ # Share of the change's own churn, so the fix counts below say where in this
+ # change the risk sits rather than only that some touched file has a past.
+ total_changed = sum(len(lines) for lines in changed.values())
per_file: dict[str, dict[str, Any]] = {}
for event in events:
entry = per_file.setdefault(
- event.file_path, {"file_path": event.file_path, "fix_count": 0, "overlapping_lines": 0}
+ event.file_path,
+ {
+ "file_path": event.file_path,
+ "fix_count": 0,
+ "overlapping_lines": 0,
+ "changed_lines": len(changed[event.file_path]),
+ "share_of_change": round(len(changed[event.file_path]) / total_changed, 3)
+ if total_changed
+ else 0.0,
+ },
)
entry["fix_count"] += 1
entry["overlapping_lines"] += _overlap_count(
@@ -316,11 +351,12 @@ async def _prior_fixes_block(ctx: Any, changed: dict[str, set[int]]) -> dict[str
# changed files as "3 past bug fixes". The per-file counts are per-file and
# stay as they are.
total = len({event.fix_sha for event in events})
- return {
+ block = {
"files": files[:_PRIOR_FIXES_LIMIT],
"truncated": len(files) > _PRIOR_FIXES_LIMIT,
"total_fixes": total,
"files_with_fixes": len(files),
+ "changed_lines_in_fixed_files": sum(f["changed_lines"] for f in per_file.values()),
"line_overlap": "approximate",
"summary": (
f"{total} past bug-fix commit(s) touched {len(files)} of the changed file(s). "
@@ -328,6 +364,37 @@ async def _prior_fixes_block(ctx: Any, changed: dict[str, set[int]]) -> dict[str
"parent commit); the per-file counts are not."
),
}
+ # Only over the files actually returned, so the sentence never names a path
+ # the reader cannot find anywhere else in the block.
+ concentration = _concentration(files[:_PRIOR_FIXES_LIMIT])
+ if concentration is not None:
+ block["concentration"] = concentration
+ return block
+
+
+#: A file has to carry this much of the change's lines before the response will
+#: say the risk sits there. Below it the change is spread out and naming one
+#: file would be a stronger claim than the numbers support.
+_CONCENTRATION_SHARE = 0.5
+
+
+def _concentration(files: list[dict[str, Any]]) -> str | None:
+ """Name the fix-carrying file that holds most of this change, if one does.
+
+ The score itself is whole-change, so this is the only place the response
+ says *where* the risk sits: the file with both the past and the churn.
+ """
+ if not files:
+ return None
+ # Negated path so ties break toward the first file the sorted list shows,
+ # matching the ascending file_path tiebreak the block is sorted by.
+ top = min(files, key=lambda f: (-f["share_of_change"], -f["fix_count"], f["file_path"]))
+ if top["share_of_change"] < _CONCENTRATION_SHARE:
+ return None
+ return (
+ f"{top['file_path']} carries {top['share_of_change']:.0%} of the changed lines "
+ f"and {top['fix_count']} past bug fix(es)."
+ )
def _overlap_count(changed_lines_now: set[int], old_ranges_json: str) -> int:
diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.py
index d97786573..ad180dc64 100644
--- a/packages/server/src/repowise/server/routers/git.py
+++ b/packages/server/src/repowise/server/routers/git.py
@@ -16,11 +16,13 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.change_risk import (
SCORE_UNIT,
RiskNormalizer,
- baseline_scores,
+ baseline_samples,
change_features_from_stored,
extract_range_features,
+ range_anchor,
review_priority_classification,
score_change,
+ scores_excluding,
)
from repowise.core.ingestion.git_indexer._constants import (
EVOLUTION_CATEGORIES,
@@ -688,7 +690,10 @@ def get_risk_range(
percentile: float | None = None
priority: str | None = None
if baseline:
- scores = baseline_scores(local_path, head, baseline, (), excluded_ref="")
+ # Same anchor rule as the CLI/MCP scorer, so both surfaces rank a range
+ # against the history it forked from rather than against its own commits.
+ samples = baseline_samples(local_path, range_anchor(local_path, base, head), baseline, ())
+ scores = scores_excluding(samples, "")
if len(scores) >= _MIN_BASELINE:
normalizer = RiskNormalizer.from_scores(scores)
# Rank with experience unknown, matching the baseline (diff-shape
diff --git a/tests/unit/analysis/test_change_risk.py b/tests/unit/analysis/test_change_risk.py
index 3eda9e025..84e7e103c 100644
--- a/tests/unit/analysis/test_change_risk.py
+++ b/tests/unit/analysis/test_change_risk.py
@@ -331,13 +331,13 @@ def test_baseline_cache_hits_on_second_call_and_busts_on_new_commit(
baseline.clear_baseline_cache()
calls = {"n": 0}
- real = baseline.baseline_scores
+ real = baseline.baseline_samples
def _counting(*args, **kwargs):
calls["n"] += 1
return real(*args, **kwargs)
- monkeypatch.setattr(baseline, "baseline_scores", _counting)
+ monkeypatch.setattr(baseline, "baseline_samples", _counting)
first = score_live_change(str(git_repo), "HEAD", baseline=200)
second = score_live_change(str(git_repo), "HEAD", baseline=200)
@@ -354,6 +354,55 @@ def test_baseline_cache_hits_on_second_call_and_busts_on_new_commit(
baseline.clear_baseline_cache()
+def test_baseline_cache_shared_across_distinct_commits(git_repo: Path, monkeypatch) -> None:
+ # The memo exists for the long-lived MCP server that scores many changes
+ # against one repo state. Keying it on the target defeated that, so two
+ # different merged commits must now share a single walk.
+ from repowise.core.analysis.change_risk import baseline
+
+ for i in range(10):
+ _commit(git_repo, {f"src/f{i}.py": f"x = {i}\n"}, f"feat: file {i}", author="Dev")
+ older = _commit(git_repo, {"src/a.py": "a = 1\n"}, "feat: a", author="Dev")
+ newer = _commit(git_repo, {"src/b.py": "b = 2\n"}, "feat: b", author="Dev")
+
+ baseline.clear_baseline_cache()
+ calls = {"n": 0}
+ real = baseline.baseline_samples
+
+ def _counting(*args, **kwargs):
+ calls["n"] += 1
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(baseline, "baseline_samples", _counting)
+
+ first = score_live_change(str(git_repo), older, baseline=200)
+ second = score_live_change(str(git_repo), newer, baseline=200)
+ third = score_live_change(str(git_repo), baseline=200) # clean tree -> HEAD
+
+ assert calls["n"] == 1
+ # Each still excludes only itself, so every sample is the same size.
+ assert first.baseline_sample_size == second.baseline_sample_size
+ assert third.baseline_sample_size == first.baseline_sample_size
+
+ baseline.clear_baseline_cache()
+
+
+def test_commit_does_not_rank_against_itself(git_repo: Path) -> None:
+ from repowise.core.analysis.change_risk import baseline
+
+ for i in range(10):
+ _commit(git_repo, {f"src/f{i}.py": f"x = {i}\n"}, f"feat: file {i}", author="Dev")
+
+ baseline.clear_baseline_cache()
+ samples = baseline.baseline_samples(str(git_repo), "HEAD", 200, ())
+ result = score_live_change(str(git_repo), "HEAD", baseline=200)
+
+ # The cached walk holds every commit; the ranking drops exactly one - the
+ # target - so the two sizes differ by one and no more.
+ assert result.baseline_sample_size == len(samples) - 1
+ baseline.clear_baseline_cache()
+
+
def test_baseline_cache_isolated_by_filters(git_repo: Path, monkeypatch) -> None:
# Different filters produce different samples, so they must not share a memo
# entry even at the same anchor sha.
@@ -369,13 +418,13 @@ def test_baseline_cache_isolated_by_filters(git_repo: Path, monkeypatch) -> None
baseline.clear_baseline_cache()
calls = {"n": 0}
- real = baseline.baseline_scores
+ real = baseline.baseline_samples
def _counting(*args, **kwargs):
calls["n"] += 1
return real(*args, **kwargs)
- monkeypatch.setattr(baseline, "baseline_scores", _counting)
+ monkeypatch.setattr(baseline, "baseline_samples", _counting)
score_live_change(str(git_repo), "HEAD", baseline=200)
score_live_change(str(git_repo), "HEAD", baseline=200, extensions=("py",))
diff --git a/tests/unit/server/test_risk_range.py b/tests/unit/server/test_risk_range.py
index e511417cc..49251e3d6 100644
--- a/tests/unit/server/test_risk_range.py
+++ b/tests/unit/server/test_risk_range.py
@@ -8,7 +8,7 @@ from pathlib import Path
import pytest
from httpx import AsyncClient
-from repowise.core.analysis.change_risk import baseline_scores
+from repowise.core.analysis.change_risk import baseline_samples, scores_excluding
from tests.unit.server.conftest import create_test_repo
@@ -119,16 +119,16 @@ async def test_risk_range_baseline_zero_skips_percentile(
assert data["review_priority"] is None
-def test_baseline_scores_returns_floats(git_repo: Path) -> None:
+def test_baseline_samples_pair_each_sha_with_a_float(git_repo: Path) -> None:
_commit(git_repo, {"src/d.py": "a = 1\nb = 2\n"}, "feat: add d")
_commit(git_repo, {"src/e.py": "c = 3\n"}, "fix: crash on null")
- scores = baseline_scores(str(git_repo), "HEAD", 200, (), excluded_ref="")
- assert len(scores) >= 1
- assert all(isinstance(s, float) for s in scores)
+ samples = baseline_samples(str(git_repo), "HEAD", 200, ())
+ assert len(samples) >= 1
+ assert all(isinstance(sha, str) and isinstance(score, float) for sha, score in samples)
-def test_baseline_scores_filters_excluded_paths(git_repo: Path) -> None:
+def test_baseline_samples_filters_excluded_paths(git_repo: Path) -> None:
_commit(git_repo, {"src/app.py": "a = 1\n"}, "feat: app")
_commit(
git_repo,
@@ -136,17 +136,19 @@ def test_baseline_scores_filters_excluded_paths(git_repo: Path) -> None:
"test: app",
)
- scores = baseline_scores(
- str(git_repo), "HEAD", 2, (), excluded_ref="", exclude_patterns=("tests/",)
- )
+ samples = baseline_samples(str(git_repo), "HEAD", 2, (), exclude_patterns=("tests/",))
- assert len(scores) == 1
+ assert len(samples) == 1
-def test_baseline_scores_omits_target_ref(git_repo: Path) -> None:
+def test_scores_excluding_omits_target_ref(git_repo: Path) -> None:
_commit(git_repo, {"src/app.py": "a = 1\n"}, "feat: app")
head = _commit(git_repo, {"src/next.py": "b = 2\n"}, "feat: next")
- scores = baseline_scores(str(git_repo), "HEAD", 2, (), excluded_ref=head)
+ samples = baseline_samples(str(git_repo), "HEAD", 2, ())
- assert len(scores) == 1
+ # The sample is cached whole; only the ranking drops the target itself.
+ assert len(samples) == 2
+ assert len(scores_excluding(samples, head)) == 1
+ assert len(scores_excluding(samples, head[:7])) == 1
+ assert len(scores_excluding(samples, "")) == 2