Datasets:
Tasks:
Text Classification
Modalities:
Text
Formats:
json
Languages:
English
Size:
< 1K
Tags:
code-review
defect-detection
software-engineering
label-noise
uncertainty-quantification
python
License:
| """End-to-end tests for the CoReDD evaluation. | |
| A tiny real git repository is built with pygit2 in a temp dir: one base commit and one | |
| child (the defect) that deletes two lines across two Python files. The synthetic | |
| labels.jsonl is built by lifting those edited lines through the very projection the | |
| evaluation uses, so node spans are never hard-coded and the predicted lines match by | |
| construction. A trivial noise.json drives the perturbation. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import numpy as np | |
| import pygit2 | |
| import pytest | |
| from sklearn.metrics import f1_score, matthews_corrcoef | |
| from coredd import metrics | |
| from coredd.benchmark import Benchmark, Line, Result | |
| from coredd.history import GitRepository | |
| from coredd.noise import NoiseModel | |
| from coredd.perturbation import Change, interval | |
| from coredd.projection import NodeProjection | |
| A_BASE = b"""\ | |
| def load(path): | |
| data = open(path).read() | |
| return data | |
| """ | |
| A_AFTER = b"""\ | |
| def load(path): | |
| data = open(path).read() | |
| """ | |
| B_BASE = b"""\ | |
| def save(path, data): | |
| handle = open(path, "w") | |
| handle.write(data) | |
| """ | |
| B_AFTER = b"""\ | |
| def save(path, data): | |
| handle = open(path, "w") | |
| """ | |
| def _tree(repo, files): | |
| builder = repo.TreeBuilder() | |
| for path, data in files.items(): | |
| builder.insert(path, repo.create_blob(data), pygit2.GIT_FILEMODE_BLOB) | |
| return builder.write() | |
| def scenario(tmp_path): | |
| """Build the repo and the labels, deriving node spans from the projection. | |
| Returns (root, labels_path). ``a.py`` line 3 (deleted) is the defective node; | |
| ``b.py`` line 3 (deleted) is present in N(c) but left defect-free. | |
| """ | |
| root = tmp_path / "repos" | |
| path = root / "acme" / "widget" | |
| path.mkdir(parents=True) | |
| repo = pygit2.init_repository(str(path), bare=True) | |
| sig = pygit2.Signature("t", "t@t", 0, 0) | |
| base = repo.create_commit( | |
| None, sig, sig, "base", _tree(repo, {"a.py": A_BASE, "b.py": B_BASE}), [] | |
| ) | |
| after = repo.create_commit( | |
| None, sig, sig, "after", | |
| _tree(repo, {"a.py": A_AFTER, "b.py": B_AFTER}), [base], | |
| ) | |
| base, after = str(base), str(after) | |
| projection = NodeProjection(GitRepository(repo)) | |
| a_node = projection.project(after, "a.py", 3, "base") # defective | |
| b_node = projection.project(after, "b.py", 3, "base") # defect-free | |
| assert a_node is not None and b_node is not None | |
| def node(span, defective): | |
| entry = { | |
| "path": span.path, "start": list(span.start), "end": list(span.end), | |
| "type": span.type, "base": base, "after": after, "bin": 1, | |
| } | |
| if defective: | |
| entry["provenance"] = [{"side": "base", "line": 3, "corrections": [99]}] | |
| return entry | |
| record = { | |
| "repository": "acme/widget", "pr": 1, | |
| "cutoff": "2023-01-01T00:00:00+00:00", | |
| "nodes": [node(a_node, True), node(b_node, False)], | |
| } | |
| labels = tmp_path / "labels.jsonl" | |
| labels.write_text(json.dumps(record) + "\n") | |
| return root, labels, base, after | |
| def noise(tmp_path): | |
| """A noise.json with vanishing rates: the score and interval are means and | |
| quantiles over the perturbed draws, so near-zero alpha and gamma make them | |
| reproduce the metric on the released labels.""" | |
| path = tmp_path / "noise.json" | |
| path.write_text(json.dumps({ | |
| "bins": 3, | |
| "alpha": {str(j): [0, 10_000_000] for j in range(3)}, | |
| "gamma": {str(j): [0, 10_000_000] for j in range(3)}, | |
| })) | |
| return path | |
| def noisy(tmp_path): | |
| """A noise.json with real rates: symmetric alpha, small gamma.""" | |
| path = tmp_path / "noisy.json" | |
| path.write_text(json.dumps({ | |
| "bins": 3, | |
| "alpha": {"0": [1, 1], "1": [1, 1], "2": [1, 1]}, | |
| "gamma": {"0": [1, 40], "1": [1, 40], "2": [1, 40]}, | |
| })) | |
| return path | |
| def benchmark(scenario, noise): | |
| root, labels, _, _ = scenario | |
| return Benchmark.load(repositories=root, labels=labels, noise=noise) | |
| def pred_key(scenario): | |
| """The full prediction key ``acme/widget#1@base..after`` for the fixture change.""" | |
| _, _, base, after = scenario | |
| return Benchmark.key("acme/widget", 1, base, after) | |
| def _hit_defective(): | |
| # a.py line 3 (base side) lifts to the defective node. | |
| return Line(path="a.py", line=3, side="base", score=0.9) | |
| def test_perfect_prediction_scores_one(benchmark, pred_key): | |
| result = benchmark.evaluate({pred_key: [_hit_defective()]}, metric=f1_score) | |
| assert result.score == pytest.approx(1.0) | |
| def test_empty_prediction_scores_zero(benchmark): | |
| result = benchmark.evaluate({}, metric=f1_score) | |
| assert result.score == pytest.approx(0.0) | |
| def test_missing_key_is_empty_prediction(benchmark): | |
| result = benchmark.evaluate({"other/repo#5": [_hit_defective()]}, | |
| metric=f1_score) | |
| assert result.score == pytest.approx(0.0) | |
| def test_prediction_against_wrong_diff_misses(benchmark): | |
| # Right change and lines, but a base/after that is not the released diff: the lifted | |
| # node carries the wrong (base, after) and matches no label node -> no hit. | |
| key = Benchmark.key("acme/widget", 1, "deadbeef" * 5, "cafebabe" * 5) | |
| result = benchmark.evaluate({key: [_hit_defective()]}, metric=f1_score) | |
| assert result.score == pytest.approx(0.0) | |
| def test_monte_carlo_is_deterministic(benchmark, pred_key): | |
| # Same seed reproduces score and band exactly. (Under the vanishing-noise fixture | |
| # the draws barely differ, so seed sensitivity is not asserted here; determinism | |
| # is the property that matters.) | |
| preds = {pred_key: [_hit_defective()]} | |
| a = benchmark.evaluate(preds, metric=f1_score, draws=500, seed=7) | |
| b = benchmark.evaluate(preds, metric=f1_score, draws=500, seed=7) | |
| assert a.interval == b.interval | |
| assert a.score == b.score | |
| def test_band_contains_score_and_reports_draws(benchmark, pred_key): | |
| result = benchmark.evaluate({pred_key: [_hit_defective()]}, | |
| metric=f1_score, draws=800, seed=1) | |
| lo, hi = result.interval | |
| assert lo <= hi | |
| assert result.draws == 800 | |
| def test_score_is_a_draw_statistic(scenario, noisy, pred_key): | |
| # Under real label noise the score is the mean over the perturbed draws, not the | |
| # metric on the released labels: alpha thins the marked node in many draws, so a | |
| # perfect prediction scores below 1.0 and the mean sits inside the band. | |
| root, labels, _, _ = scenario | |
| benchmark = Benchmark.load(repositories=root, labels=labels, noise=noisy) | |
| result = benchmark.evaluate({pred_key: [_hit_defective()]}, | |
| metric=f1_score, draws=500, seed=3) | |
| lo, hi = result.interval | |
| assert result.score < 1.0 | |
| assert lo <= result.score <= hi | |
| def test_metric_agnostic(benchmark, pred_key): | |
| preds = {pred_key: [_hit_defective()]} | |
| f1 = benchmark.evaluate(preds, metric=f1_score, draws=200) | |
| mcc = benchmark.evaluate(preds, metric=matthews_corrcoef, draws=200) | |
| rr = benchmark.evaluate(preds, metric=metrics.mrr, pooled=False, draws=200) | |
| accuracy = lambda yt, yp: float((np.asarray(yt) == np.asarray(yp)).mean()) | |
| acc = benchmark.evaluate(preds, metric=accuracy, draws=200) | |
| for result in (f1, mcc, rr, acc): | |
| assert isinstance(result, Result) | |
| assert not np.isnan(result.score) | |
| def _change(y_true, y_pred, scores=None): | |
| y_true = np.asarray(y_true, dtype=bool) | |
| y_pred = np.asarray(y_pred, dtype=bool) | |
| if scores is None: | |
| scores = y_pred.astype(float) | |
| return Change(y_true=y_true, y_pred=y_pred, | |
| scores=np.asarray(scores, dtype=float), | |
| bin=np.zeros(y_true.size, dtype=int)) | |
| def _noise_free(): | |
| # Beta(1, 1e7) posteriors: alpha and gamma are effectively zero, so every draw | |
| # reproduces the released labels and the aggregation is observed without noise. | |
| return NoiseModel(1, {0: (0, 10_000_000)}, {0: (0, 10_000_000)}) | |
| def test_pooled_and_per_case_aggregate_differently(): | |
| # Per case: F1 is 1.0 on the small change and 0.0 on the large one, mean 0.5. | |
| # Pooled: TP=1, FP=5, FN=1 over the concatenated nodes, F1 = 2/(2+5+1) = 0.25. | |
| changes = [ | |
| _change([1], [1]), | |
| _change([1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1]), | |
| ] | |
| pooled, _ = interval(changes, f1_score, _noise_free(), draws=20, | |
| rng=np.random.default_rng(0)) | |
| per_case, _ = interval(changes, f1_score, _noise_free(), draws=20, pooled=False, | |
| rng=np.random.default_rng(0)) | |
| assert pooled == pytest.approx(0.25) | |
| assert per_case == pytest.approx(0.5) | |
| def test_pooled_rank_metric_uses_one_global_ranking(benchmark): | |
| # Per case AUROC is undefined for both changes (a single class each), but the | |
| # pooled ranking separates the positive of one change from the negatives of the | |
| # other: positive score 0.9 above negatives 0.5 and 0.1 gives AUC 1.0. | |
| changes = [ | |
| _change([0, 0], [0, 0], scores=[0.5, 0.1]), | |
| _change([1], [1], scores=[0.9]), | |
| ] | |
| level, _ = interval(changes, metrics.auroc, _noise_free(), draws=20, | |
| rng=np.random.default_rng(0)) | |
| assert level == pytest.approx(1.0) | |
| def test_per_case_drops_undefined_changes(): | |
| # AUROC is NaN on the all-positive change and 1.0 on the separable one; the | |
| # per-case mean drops the undefined change rather than propagating NaN. | |
| changes = [ | |
| _change([1, 1], [1, 1], scores=[0.9, 0.8]), | |
| _change([1, 0], [1, 0], scores=[0.8, 0.2]), | |
| ] | |
| level, _ = interval(changes, metrics.auroc, _noise_free(), draws=20, pooled=False, | |
| rng=np.random.default_rng(0)) | |
| assert level == pytest.approx(1.0) | |
| def test_mrr_is_undefined_without_positives(): | |
| assert np.isnan(metrics.mrr([False, False], [0.5, 0.2])) | |
| def test_result_repr_format(): | |
| result = Result(score=0.62, interval=(0.55, 0.68), draws=10_000) | |
| assert repr(result) == ( | |
| "Score: 0.62\n" | |
| "95% label-uncertainty interval: [0.55, 0.68]\n" | |
| "Monte Carlo draws: 10,000" | |
| ) | |