Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3,546 changes: 3,546 additions & 0 deletions docs/bench/per-merge.csv

Large diffs are not rendered by default.

534 changes: 534 additions & 0 deletions docs/bench/summary.json

Large diffs are not rendered by default.

9 changes: 9 additions & 0 deletions docs/methodology.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Devscope P3 backtest

Held-out median Lift@3: **1.36** (95% bootstrap CI 0.00-3.41).

Relative to size-only median Recall@3: **-3.3%**. Product gate: **FAIL**.

Eligible held-out repositories: **6**.

The headline is computed only on repositories excluded entirely from fitting. Features use strict `landed_at < as_of`; labels may use fixes landing within the following 12 months. Raw merge-level results are in `per-merge.csv`.
96 changes: 96 additions & 0 deletions scripts/preindex-corpus.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""Pre-index approved corpus clones while the replay harness is developed."""

from __future__ import annotations

import argparse
import json
import os
import subprocess
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any

from devscope.bench.corpus import load_corpus, validate_corpus
from devscope.bench.replay import HISTORY_DAYS, TRAIN_DAYS
from devscope.index.git_reader import GitReader
from devscope.index.incremental import RepositoryIndexer

# Two 18-month training spans are replayed. Each point also needs the product's
# three-year history window, and the buffer crosses quiet periods at the boundary.
BENCHMARK_DAYS = 2 * TRAIN_DAYS + HISTORY_DAYS + 120


def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--clone-root", type=Path, required=True)
parser.add_argument("--cache-dir", type=Path, required=True)
parser.add_argument("--hydrate", action="store_true")
parser.add_argument("--repo", action="append", dest="repos")
parser.add_argument("--max-commits", type=int, default=100_000)
args = parser.parse_args()
corpus = load_corpus()
errors = validate_corpus(corpus)
if errors or corpus["status"] != "approved":
raise SystemExit("Corpus is not approved: " + "; ".join(errors))
repositories = [
repo
for repo in corpus["repositories"]
if not args.repos or str(repo["repo"]) in set(args.repos)
]
if args.repos and len(repositories) != len(set(args.repos)):
raise SystemExit("One or more --repo values are not in the approved corpus")
if args.hydrate:
with ThreadPoolExecutor(max_workers=4) as executor:
list(executor.map(lambda repo: hydrate(args.clone_root, repo), repositories))
os.environ["DEVSCOPE_CACHE_DIR"] = str(args.cache_dir)
for number, repo in enumerate(repositories, start=1):
name = str(repo["repo"])
clone = args.clone_root / name.replace("/", "__")
pinned_at = GitReader(clone).commit_info(str(repo["sha"])).committed_at
result = RepositoryIndexer(
clone,
ref=str(repo["sha"]),
since=f"@{pinned_at - BENCHMARK_DAYS * 86_400}",
max_commits=args.max_commits,
).build()
print(
json.dumps(
{
"position": number,
"total": len(repositories),
"repo": name,
"commits": result.total_commits,
"bug_intro": result.bug_intro_rows,
"rebuilt": result.rebuilt,
}
),
flush=True,
)


def hydrate(clone_root: Path, repo: dict[str, Any]) -> None:
"""Materialize promised objects for one pinned audit clone."""
name = str(repo["repo"])
clone = clone_root / name.replace("/", "__")
shallow = subprocess.run(
["git", "rev-parse", "--is-shallow-repository"],
cwd=clone,
check=True,
capture_output=True,
text=True,
).stdout.strip() == "true"
command = ["git", "fetch", "--no-filter"]
command.append("--unshallow" if shallow else "--refetch")
command.extend(["origin", str(repo["sha"])])
subprocess.run(
command,
cwd=clone,
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
print(json.dumps({"hydrated": name}), flush=True)


if __name__ == "__main__":
main()
17 changes: 9 additions & 8 deletions src/devscope/bench/corpus.yaml
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
{
"schema_version": 1,
"status": "proposal-awaiting-approval",
"status": "approved",
"pinned_at": "2026-12-04",
"history_window_commits": 5000,
"benchmark_max_commits": 100000,
"fix_sample_seed": "sha256(repo)",
"holdout": {
"seed": 20261204,
"size": 10,
"repositories": [
"aio-libs/aiohttp",
"BurntSushi/ripgrep",
"caddyserver/caddy",
"clap-rs/clap",
"go-gitea/gitea",
"hashicorp/terraform",
"gin-gonic/gin",
"gohugoio/hugo",
"pallets/flask",
"rayon-rs/rayon",
"realm/SwiftLint",
"scikit-learn/scikit-learn",
"serde-rs/serde",
"vercel/next.js"
]
},
Expand Down Expand Up @@ -63,9 +64,9 @@
{"repo":"apple/swift-nio","sha":"5f7d2719adbfb1b53cf5e733aa5952e20398b130","branch":"main","language":"Swift","commit_count":3105,"merge_styles":["squash","rebase"],"single_project":true,"vendored_generated_percent":0.0,"history_flags":[],"fix_audit":{"match_rate":0.1072,"sample_size":20,"real_fixes":19}},
{"repo":"onevcat/Kingfisher","sha":"e46d4dcfc4279a2d2ab92b8ff69595a7ce77144b","branch":"master","language":"Swift","commit_count":3662,"merge_styles":["merge"],"single_project":true,"vendored_generated_percent":0.0,"history_flags":[],"fix_audit":{"match_rate":0.1991,"sample_size":20,"real_fixes":17}},
{"repo":"realm/SwiftLint","sha":"a272b909774cbeec37f71d31295ff2b718f8ecbd","branch":"main","language":"Swift","commit_count":7688,"merge_styles":["squash"],"single_project":true,"vendored_generated_percent":0.0,"history_flags":[],"fix_audit":{"match_rate":0.1528,"sample_size":20,"real_fixes":19}},
{"repo":"Moya/Moya","sha":"24c26671a2f0fc26b53c9fa2410c97987fb0f05a","branch":"master","language":"Swift","commit_count":3475,"merge_styles":["merge"],"single_project":true,"vendored_generated_percent":0.0,"history_flags":[],"fix_audit":{"match_rate":0.1096,"sample_size":20,"real_fixes":17}},
{"repo":"Quick/Quick","sha":"2b4547b230e94d84320724fd6df65e418b058be2","branch":"main","language":"Swift","commit_count":2197,"merge_styles":["merge"],"single_project":true,"vendored_generated_percent":0.0,"history_flags":[],"fix_audit":{"match_rate":0.0719,"sample_size":20,"real_fixes":17}},
{"repo":"ReactiveX/RxSwift","sha":"3e33f90c1bcd3cdea25bdb49bd4a594a50c3ab84","branch":"main","language":"Swift","commit_count":3758,"merge_styles":["squash","rebase"],"single_project":true,"vendored_generated_percent":0.0,"history_flags":[],"fix_audit":{"match_rate":0.1629,"sample_size":20,"real_fixes":16}},
{"repo":"swiftlang/sourcekit-lsp","sha":"0f328e45b1bba45ad6e97ae535dade8722c6edb2","branch":"main","language":"Swift","commit_count":4909,"window_commits":3075,"merge_styles":["merge"],"single_project":true,"vendored_generated_percent":0.0,"history_flags":[],"fix_audit":{"match_rate":0.1014,"sample_size":20,"real_fixes":15}},
{"repo":"swiftlang/swift-package-manager","sha":"9997f60c212707745c3e1c6fcbb8089a76042bb6","branch":"main","language":"Swift","commit_count":9394,"window_commits":2107,"merge_styles":["merge","squash","rebase"],"single_project":true,"vendored_generated_percent":0.0,"history_flags":[],"fix_audit":{"match_rate":0.1336,"sample_size":20,"real_fixes":17}},
{"repo":"apple/swift-collections","sha":"1fafba0208bc3daf47ecd707fc41d2f40c4337e7","branch":"main","language":"Swift","commit_count":2276,"window_commits":1317,"merge_styles":["merge","rebase"],"single_project":true,"vendored_generated_percent":0.0,"history_flags":[],"fix_audit":{"match_rate":0.1366,"sample_size":20,"real_fixes":18}},
{"repo":"nicklockwood/SwiftFormat","sha":"d5ca3e440886ea8b3d5b405928b1dae5e80d7ce2","branch":"main","language":"Swift","commit_count":3141,"merge_styles":["squash","rebase"],"single_project":true,"vendored_generated_percent":0.0,"history_flags":["formatter-project: verify mass formatting commits are ignored"],"fix_audit":{"match_rate":0.3684,"sample_size":20,"real_fixes":19}},

{"repo":"BurntSushi/ripgrep","sha":"3e85c6c148fdce38a99ceeb9d2780dc7b03b4a4f","branch":"master","language":"Rust","commit_count":2381,"merge_styles":["squash","rebase"],"single_project":true,"vendored_generated_percent":0.0,"history_flags":[],"fix_audit":{"match_rate":0.1004,"sample_size":20,"real_fixes":18}},
Expand Down
131 changes: 131 additions & 0 deletions src/devscope/bench/fit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
"""Offline global logistic fitting and Platt calibration for P3."""

from __future__ import annotations

import json
import math
import statistics
from pathlib import Path
from typing import Any

from devscope.bench.replay import ReplayRow

FEATURES = (
"defect_density",
"recent_fix_count",
"churn_90d",
"distinct_authors_12m",
"author_prior_commits",
"lines_changed",
"missing_cochange",
"blast_radius",
"uncovered_added_lines",
)


def fit_global(rows: list[ReplayRow], corpus_shas: dict[str, str]) -> dict[str, Any]:
"""Fit weights and global Platt calibration, excluding held-out repositories."""
training = [row for row in rows if row.split == "train" and not row.holdout]
if not training or not any(row.bug_lines > 0 for row in training):
raise ValueError("Training data needs both labelled and unlabelled files")
stats = _standardization(training)
matrix = [_vector(row, stats) for row in training]
labels = [1.0 if row.bug_lines > 0 else 0.0 for row in training]
weights, intercept = _logistic_fit(matrix, labels)
raw = [intercept + sum(weight * value for weight, value in zip(weights, vector)) for vector in matrix]
platt_slope, platt_intercept = _platt_fit(raw, labels)
return {
"fitted": True,
"intercept": intercept,
"weights": dict(zip(FEATURES, weights)),
"standardization": stats,
"platt": {"slope": platt_slope, "intercept": platt_intercept},
"corpus_shas": dict(sorted(corpus_shas.items())),
}


def write_weights(path: Path, weights: dict[str, Any]) -> None:
path.write_text(json.dumps(weights, indent=2, sort_keys=True) + "\n", encoding="utf-8")


def raw_score(row: ReplayRow, config: dict[str, Any]) -> float:
result = float(config["intercept"])
for name, weight in config["weights"].items():
value = row.features.get(name)
if value is None:
continue
stats = config["standardization"][name]
result += float(weight) * (float(value) - stats["mean"]) / stats["scale"]
return result


def _standardization(rows: list[ReplayRow]) -> dict[str, dict[str, float]]:
result: dict[str, dict[str, float]] = {}
for name in FEATURES:
values = []
for row in rows:
value = row.features.get(name)
if value is not None:
values.append(float(value))
mean = statistics.fmean(values) if values else 0.0
scale = statistics.pstdev(values) if len(values) > 1 else 1.0
result[name] = {"mean": mean, "scale": max(scale, 1e-9)}
return result


def _vector(row: ReplayRow, stats: dict[str, dict[str, float]]) -> list[float]:
result: list[float] = []
for name in FEATURES:
value = row.features.get(name)
result.append(
0.0
if value is None
else (float(value) - stats[name]["mean"]) / stats[name]["scale"]
)
return result


def _logistic_fit(matrix: list[list[float]], labels: list[float]) -> tuple[list[float], float]:
weights = [0.0] * len(FEATURES)
intercept = 0.0
positives = max(1.0, sum(labels))
positive_weight = (len(labels) - positives) / positives
for iteration in range(800):
gradients = [0.0] * len(weights)
intercept_gradient = 0.0
rate = 0.08 / math.sqrt(1.0 + iteration / 50)
for vector, label in zip(matrix, labels):
prediction = _sigmoid(intercept + sum(a * b for a, b in zip(weights, vector)))
weight = positive_weight if label else 1.0
error = (prediction - label) * weight
intercept_gradient += error
for index, value in enumerate(vector):
gradients[index] += error * value
count = float(len(labels))
intercept -= rate * intercept_gradient / count
for index in range(len(weights)):
weights[index] -= rate * (gradients[index] / count + 0.001 * weights[index])
return weights, intercept


def _platt_fit(raw: list[float], labels: list[float]) -> tuple[float, float]:
slope, intercept = 1.0, 0.0
for iteration in range(500):
slope_gradient = 0.0
intercept_gradient = 0.0
rate = 0.05 / math.sqrt(1.0 + iteration / 50)
for score, label in zip(raw, labels):
error = _sigmoid(slope * score + intercept) - label
slope_gradient += error * score
intercept_gradient += error
count = float(len(labels))
slope -= rate * slope_gradient / count
intercept -= rate * intercept_gradient / count
return max(slope, 1e-9), intercept


def _sigmoid(value: float) -> float:
if value >= 0:
return 1.0 / (1.0 + math.exp(-value))
exp = math.exp(value)
return exp / (1.0 + exp)
103 changes: 103 additions & 0 deletions src/devscope/bench/metrics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
"""Leakage-free benchmark metrics and deterministic bootstrap summaries."""

from __future__ import annotations

import random
import statistics
from collections.abc import Callable, Sequence
from dataclasses import dataclass


@dataclass(frozen=True)
class MethodResult:
repo: str
unit: str
method: str
recall_at_3: float
popt: float
bug_lines: int
changed_files: int


def recall_at_k(ranking: Sequence[str], bug_lines: dict[str, int], k: int = 3) -> float:
"""Return the share of labelled bug lines found in the first ``k`` files."""
total = sum(max(0, value) for value in bug_lines.values())
if total == 0:
return 0.0
found = sum(max(0, bug_lines.get(path, 0)) for path in ranking[:k])
return found / total


def lift_at_k(
ranking: Sequence[str], random_recall: float, bug_lines: dict[str, int], k: int = 3
) -> float:
"""Return recall lift over the mean random baseline."""
recall = recall_at_k(ranking, bug_lines, k)
return recall / random_recall if random_recall > 0 else 0.0


def effort_aware_popt(
ranking: Sequence[str], bug_lines: dict[str, int], changed_lines: dict[str, int]
) -> float:
"""Return normalized area under the cumulative bug-lines/effort curve."""
paths = [path for path in ranking if path in changed_lines]
total_bugs = sum(max(0, bug_lines.get(path, 0)) for path in paths)
total_effort = sum(max(1, changed_lines[path]) for path in paths)
if total_bugs == 0 or total_effort == 0:
return 0.0

def area(order: Sequence[str]) -> float:
x = 0.0
y = 0.0
result = 0.0
for path in order:
next_x = x + max(1, changed_lines[path]) / total_effort
next_y = y + max(0, bug_lines.get(path, 0)) / total_bugs
result += (next_x - x) * (y + next_y) / 2.0
x, y = next_x, next_y
return result

optimal = sorted(paths, key=lambda path: (-bug_lines.get(path, 0), changed_lines[path], path))
worst = list(reversed(optimal))
low, high = area(worst), area(optimal)
return 0.0 if high == low else max(0.0, min(1.0, (area(paths) - low) / (high - low)))


def random_recall_mean(
paths: Sequence[str], bug_lines: dict[str, int], *, shuffles: int = 100, seed: int
) -> float:
"""Return a reproducible mean random Recall@3."""
rng = random.Random(seed)
values: list[float] = []
for _ in range(shuffles):
order = list(paths)
rng.shuffle(order)
values.append(recall_at_k(order, bug_lines))
return statistics.fmean(values) if values else 0.0


def bootstrap_median_ci(
values: Sequence[float], *, seed: int = 20261204, samples: int = 10_000
) -> tuple[float, float, float]:
"""Return median and percentile 95% bootstrap confidence interval."""
if not values:
return (0.0, 0.0, 0.0)
rng = random.Random(seed)
medians = sorted(
statistics.median(rng.choices(values, k=len(values))) for _ in range(samples)
)
return (
float(statistics.median(values)),
float(medians[int(0.025 * (samples - 1))]),
float(medians[int(0.975 * (samples - 1))]),
)


def repo_medians(
results: Sequence[MethodResult], value: Callable[[MethodResult], float]
) -> dict[str, float]:
"""Aggregate merge-level values within repositories before corpus statistics."""
grouped: dict[str, list[float]] = {}
for result in results:
grouped.setdefault(result.repo, []).append(value(result))
return {repo: float(statistics.median(items)) for repo, items in grouped.items()}
Loading
Loading