"""The public benchmark API. ``Benchmark.load`` reads the released labels and the noise model; ``evaluate`` scores a candidate's predictions and returns a point score with a label-uncertainty interval. A candidate predicts **lines** (``Line(path, line, side, score)``). CoReDD lifts each line to the syntax node that carries it -- the same projection that built the labels -- and scores on **nodes**: the released defective nodes are the truth, the predicted-onto nodes are the prediction. The uncertainty comes from perturbing the truth (see ``perturbation``). """ from __future__ import annotations import json from collections.abc import Iterable, Mapping from dataclasses import dataclass from pathlib import Path import numpy as np from sklearn.metrics import f1_score from coredd.noise import NoiseModel from coredd.perturbation import Change, interval from coredd.history import RepositorySet @dataclass(frozen=True) class Line: """A predicted line: a file, a line number, its diff side, and a score. ``side`` is ``"after"`` for an added/context line or ``"base"`` for a deleted line. ``score`` is the prediction's confidence, used by rank metrics; it defaults to 1.0 so a bare hit still ranks above the unpredicted nodes (score 0). """ path: str line: int side: str score: float = 1.0 @dataclass(frozen=True) class Result: """A benchmark score with its label-uncertainty band.""" score: float interval: tuple[float, float] draws: int level: float = 0.95 def __repr__(self) -> str: pct = int(round(self.level * 100)) return ( f"Score: {self.score:.2f}\n" f"{pct}% label-uncertainty interval: " f"[{self.interval[0]:.2f}, {self.interval[1]:.2f}]\n" f"Monte Carlo draws: {self.draws:,}" ) class Benchmark: """The released benchmark: labels, noise model, and repository clones.""" def __init__(self, records: list[dict], repositories: RepositorySet, noise_path: Path) -> None: self._records = records self._repositories = repositories self._noise_path = noise_path self._by_key = { self.key(record["repository"], record["pr"]): record for record in records } @classmethod def load(cls, repositories: str | Path, *, labels: str | Path, noise: str | Path) -> "Benchmark": """Load the benchmark against local clones under *repositories*. ``labels`` (the released ``labels.jsonl``) and ``noise`` (the ``noise.json`` noise model) are the benchmark's released data files and are supplied by the caller; both are required. """ records = _read_labels(labels) return cls(records, RepositorySet(repositories), Path(noise)) @staticmethod def key(repository: str, pr: int, base: str | None = None, after: str | None = None) -> str: """The prediction key for a change. ``owner/repo#pr`` maps the prediction to a change; the optional ``@base..after`` suffix names the diff the prediction is made against, and both SHAs flow through to the node match. Omit them to build the mapping key used to index a change; supply them (a released node's ``base``/``after``) to predict. """ change = f"{repository}#{pr}" if base is not None and after is not None: return f"{change}@{base}..{after}" return change def evaluate(self, predictions: Mapping[str, Iterable[Line]], *, metric=f1_score, pooled: bool = True, draws: int = 10_000, seed: int | None = 0) -> Result: """Score *predictions* and return the point score with its uncertainty band. ``predictions`` maps a change key (:meth:`key`, ``owner/repo#pr``) to its predicted lines; a change absent from the map is scored with no prediction. Score and interval are the mean and the [2.5%, 97.5%] quantile of the metric over the Monte Carlo draws that perturb the labels at the audited rates. Scoring is over the candidate syntax nodes N(c) of each change. With ``pooled`` (the default) the metric runs once over the nodes of every change pooled into one population; with ``pooled=False`` it runs per change and is averaged equally across changes, dropping changes where it is undefined (NaN) -- the form per-case metrics such as :func:`coredd.metrics.mrr` are reported in. """ prepared = _normalise(predictions) empty = _Prediction(base=None, after=None, lines=[]) noise = NoiseModel.load(self._noise_path) changes = [ self._change(record, prepared.get(key, empty)) for key, record in self._by_key.items() ] rng = np.random.default_rng(seed) score, band = interval(changes, metric, noise, draws=draws, pooled=pooled, rng=rng) return Result(score=score, interval=band, draws=draws) def _change(self, record: dict, prediction: "_Prediction") -> Change: nodes = record["nodes"] projection = self._repositories.projection(record["repository"]) predicted = self._predict(projection, prediction) return self._node_change(nodes, predicted) def _predict(self, projection, prediction: "_Prediction") -> dict: # A prediction carries the (base, after) diff it is made against, in the key # ``owner/repo#pr@base..after``. Lines are lifted against that after commit, and # the resulting node keeps the (base, after) so it matches a label node only when # both the span and the diff agree -- a prediction against a different diff hits # nothing. Lines that lift to no node (blank/comment/non-Python) drop out. scores: dict[tuple, float] = {} if prediction.after is None: return scores for line in prediction.lines: # A prediction may name a commit the local clone does not have (a wrong or # unknown diff); that lifts to nothing rather than raising -- it simply hits # no label node. try: node = projection.project( prediction.after, line.path, line.line, line.side ) except (ValueError, KeyError): continue if node is None: continue key = (node.path, node.start, node.end, prediction.base, prediction.after) scores[key] = max(scores.get(key, float("-inf")), line.score) return scores def _node_change(self, nodes: list[dict], predicted: dict) -> Change: y_true, y_pred, scores, bins = [], [], [], [] for node in nodes: key = ( node["path"], tuple(node["start"]), tuple(node["end"]), node["base"], node["after"], ) hit = key in predicted y_true.append("provenance" in node) y_pred.append(hit) scores.append(predicted[key] if hit else 0.0) bins.append(int(node["bin"])) return Change( y_true=np.asarray(y_true, dtype=bool), y_pred=np.asarray(y_pred, dtype=bool), scores=np.asarray(scores, dtype=float), bin=np.asarray(bins, dtype=int), ) @dataclass(frozen=True) class _Prediction: """A change's predicted lines together with the diff they are made against.""" base: str | None after: str | None lines: list[Line] def _normalise( predictions: Mapping[str, Iterable[Line]], ) -> dict[str, "_Prediction"]: # The key is ``owner/repo#pr@base..after``: the ``owner/repo#pr`` part maps the # prediction to a change, and the ``@base..after`` part names the diff it is made # against. Both SHAs flow through to the node match, so a prediction against a # different diff than the released one lifts to nodes that match nothing. prepared: dict[str, "_Prediction"] = {} for key, lines in predictions.items(): change, _, diff = key.partition("@") base, after = (None, None) if diff: base, _, after = diff.partition("..") base, after = base or None, after or None prepared[change] = _Prediction(base=base, after=after, lines=list(lines)) return prepared def _read_labels(labels: str | Path) -> list[dict]: text = Path(labels).read_text(encoding="utf-8") return [json.loads(line) for line in text.splitlines() if line.strip()]