#!/usr/bin/env python3
"""regcheck: compare a Go repo's benchmarks between two commits.

Part of regression detector, https://sophie-reade.pages.dev/regression-detector/

It builds the test binaries for both commits, then runs them alternately
(base, head, head, base, ...) in the same session, so machine noise and slow
drift hit both sides equally. The two sets of samples are compared per
benchmark and per metric (ns/op, B/op, allocs/op, MB/s, ...) with the same
statistics the detector uses on Pebble and S2:

  - Mann-Whitney U for "did it really change", robust to skewed timings
  - Hodges-Lehmann shift for "by how much"
  - Benjamini-Hochberg so many benchmarks don't mean many false alarms
  - each benchmark's own noise as the minimum change worth flagging

Pure standard library, Python 3.8+. Needs git and go on PATH.

Usage (from the repository root):
  python3 regcheck.py --base <sha> --head <sha> [--packages ./...] [--bench .]
"""
import argparse
import json
import math
import os
import random
import re
import shutil
import statistics
import subprocess
import sys
import tempfile
import time
from collections import Counter, defaultdict
from datetime import datetime, timezone

VERSION = "1.0"
VIEWER_URL = "https://sophie-reade.pages.dev/regression-detector/report/"

BENCH_FUNC = re.compile(r"^func\s+(Benchmark\w*)\s*\(\s*\w+\s+\*testing\.B\s*\)", re.M)
BENCH_LINE = re.compile(r"^(Benchmark\S+?)(?:-(\d+))?\s+(\d+)\s+(.+)$")


def log(msg):
    print("[regcheck] " + msg, flush=True)


def sh(cmd, cwd=None, env=None, timeout=None, check=True):
    p = subprocess.run(cmd, cwd=cwd, env=env, timeout=timeout,
                       stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    if check and p.returncode != 0:
        raise RuntimeError("%s failed (exit %d)\n%s" % (" ".join(cmd), p.returncode,
                                                       (p.stderr or p.stdout)[-4000:]))
    return p


# ---------------------------------------------------------------- statistics
# Same primitives as the detector's analysis/stats.py.

def mann_whitney_u(x, y):
    """Two-sided Mann-Whitney U with tie-corrected normal approximation."""
    n1, n2 = len(x), len(y)
    if n1 == 0 or n2 == 0:
        return 1.0
    combined = sorted([(v, 0) for v in x] + [(v, 1) for v in y], key=lambda t: t[0])
    ranks = [0.0] * len(combined)
    i = 0
    while i < len(combined):
        j = i
        while j + 1 < len(combined) and combined[j + 1][0] == combined[i][0]:
            j += 1
        for k in range(i, j + 1):
            ranks[k] = (i + j + 2) / 2.0
        i = j + 1
    ties = sum(t ** 3 - t for t in Counter(v for v, _ in combined).values())
    r1 = sum(r for r, (_, g) in zip(ranks, combined) if g == 0)
    u1 = r1 - n1 * (n1 + 1) / 2.0
    n = n1 + n2
    var = (n1 * n2 / 12.0) * ((n + 1) - ties / (n * (n - 1))) if n > 1 else 0.0
    if var <= 0:
        return 1.0
    z = (u1 - n1 * n2 / 2.0) / math.sqrt(var)
    return max(0.0, min(1.0, 2.0 * (1.0 - 0.5 * (1.0 + math.erf(abs(z) / math.sqrt(2.0))))))


def hodges_lehmann(x, y):
    """Median of all pairwise differences (y - x): robust size of the shift."""
    return statistics.median([b - a for a in x for b in y])


def benjamini_hochberg(pvals, alpha):
    n = len(pvals)
    order = sorted(range(n), key=lambda i: pvals[i])
    last = -1
    for rank, idx in enumerate(order):
        if pvals[idx] <= (rank + 1) / n * alpha:
            last = rank
    sig = [False] * n
    for rank in range(last + 1):
        sig[order[rank]] = True
    return sig


def bootstrap_ci(x, y, iters=2000, seed=7):
    """95% interval for the % change in medians, by resampling both sides."""
    mx = statistics.median(x)
    if mx == 0:
        return None
    rng = random.Random(seed)
    out = []
    for _ in range(iters):
        bx = statistics.median([rng.choice(x) for _ in x])
        by = statistics.median([rng.choice(y) for _ in y])
        if bx != 0:
            out.append((by - bx) / bx * 100.0)
    if not out:
        return None
    out.sort()
    return [out[int(0.025 * (len(out) - 1))], out[int(0.975 * (len(out) - 1))]]


def spread_pct(v):
    """Robust noise as % of the median (MAD scaled to match a std dev)."""
    med = statistics.median(v)
    if med == 0:
        return 0.0
    mad = statistics.median([abs(a - med) for a in v])
    return 1.4826 * mad / abs(med) * 100.0


# ---------------------------------------------------------------- git / go

def commit_info(repo, ref):
    sha = sh(["git", "rev-parse", "--verify", ref + "^{commit}"], cwd=repo).stdout.strip()
    out = sh(["git", "log", "-1", "--format=%s%x00%cI", sha], cwd=repo).stdout.rstrip("\n")
    subject, date = out.split("\x00")
    return {"ref": ref, "sha": sha, "subject": subject, "date": date}


def repo_name(repo, override):
    if override:
        return override
    if os.environ.get("GITHUB_REPOSITORY"):
        return os.environ["GITHUB_REPOSITORY"]
    p = sh(["git", "remote", "get-url", "origin"], cwd=repo, check=False)
    m = re.search(r"github\.com[:/](.+?)(?:\.git)?$", p.stdout.strip())
    return m.group(1) if m else os.path.basename(os.path.abspath(repo))


def bench_packages(moddir, patterns, top_pattern):
    """import path -> dir, for packages whose test files define a matching benchmark."""
    fmt = '{{.ImportPath}}\t{{.Dir}}\t{{join .TestGoFiles ","}}\t{{join .XTestGoFiles ","}}'
    p = sh(["go", "list", "-e", "-f", fmt] + patterns, cwd=moddir)
    try:
        want = re.compile(top_pattern)
    except re.error:
        want = None
    found = {}
    for line in p.stdout.splitlines():
        parts = line.split("\t")
        if len(parts) != 4:
            continue
        path, pdir, t1, t2 = parts
        for name in filter(None, (t1 + "," + t2).split(",")):
            try:
                with open(os.path.join(pdir, name), encoding="utf-8", errors="replace") as f:
                    names = BENCH_FUNC.findall(f.read())
            except OSError:
                continue
            if any(want is None or want.search(n) for n in names):
                found[path] = pdir
                break
    return found


def build_side(label, moddir, pkgs, bindir):
    """Compile one test binary per package. Returns {path: (binary, dir)} and errors."""
    os.makedirs(bindir, exist_ok=True)
    built, errors = {}, []
    for i, (path, pdir) in enumerate(sorted(pkgs.items())):
        out = os.path.join(bindir, "pkg%03d.test" % i)
        log("build %s  %s" % (label, path))
        p = sh(["go", "test", "-c", "-o", out, path], cwd=moddir, check=False)
        if p.returncode != 0 or not os.path.exists(out):
            errors.append({"side": label, "package": path,
                           "error": (p.stderr or p.stdout).strip()[-2000:]})
            continue
        built[path] = (out, pdir)
    return built, errors


def parse_bench(text):
    """Go benchmark output -> [(name, unit, value)]."""
    rows = []
    for line in text.splitlines():
        m = BENCH_LINE.match(line.strip())
        if not m:
            continue
        name, rest = m.group(1), m.group(4).split()
        for k in range(0, len(rest) - 1, 2):
            try:
                rows.append((name, rest[k + 1], float(rest[k])))
            except ValueError:
                break
    return rows


def run_binary(binary, pdir, bench, benchtime, timeout_min):
    cmd = [binary, "-test.run=^$", "-test.bench=" + bench, "-test.benchmem",
           "-test.count=1", "-test.benchtime=" + benchtime,
           "-test.timeout=%dm" % timeout_min]
    p = subprocess.run(cmd, cwd=pdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                       text=True, timeout=timeout_min * 60 + 60)
    return p.returncode, p.stdout


# ---------------------------------------------------------------- analysis

def higher_is_better(unit):
    return unit.endswith("/s")


def analyze(samples, alpha, min_effect):
    """samples[(pkg, bench, unit)] = {"base": [...], "head": [...]} -> result rows."""
    rows = []
    for (pkg, bench, unit), s in sorted(samples.items()):
        b, h = s.get("base", []), s.get("head", [])
        if len(b) < 3 or len(h) < 3:
            continue
        mb, mh = statistics.median(b), statistics.median(h)
        shift = hodges_lehmann(b, h)
        effect = shift / abs(mb) * 100.0 if mb != 0 else (0.0 if shift == 0 else None)
        noise = max(spread_pct(b), spread_pct(h))
        exact = unit in ("allocs/op", "B/op")
        floor = 0.5 if exact else min_effect
        rows.append({
            "package": pkg, "benchmark": bench, "unit": unit,
            "better": "higher" if higher_is_better(unit) else "lower",
            "base": {"median": mb, "noise_pct": round(spread_pct(b), 3), "samples": b},
            "head": {"median": mh, "noise_pct": round(spread_pct(h), 3), "samples": h},
            "shift": shift,
            "change_pct": None if effect is None else round(effect, 3),
            "ci_pct": bootstrap_ci(b, h),
            "p_value": mann_whitney_u(b, h),
            "threshold_pct": round(max(floor, noise), 3),
        })
    sig = benjamini_hochberg([r["p_value"] for r in rows], alpha) if rows else []
    for r, s in zip(rows, sig):
        worse = (r["shift"] < 0) if r["better"] == "higher" else (r["shift"] > 0)
        big = r["change_pct"] is None or abs(r["change_pct"]) >= r["threshold_pct"]
        if r["shift"] == 0:
            status = "unchanged"
        elif s and big:
            status = "regression" if worse else "improvement"
        elif big and r["p_value"] < alpha:
            status = "unclear"
        else:
            status = "unchanged"
        r["significant"] = s
        r["status"] = status
    return rows


def fmt_num(v):
    if v is None:
        return "-"
    if abs(v) >= 100:
        return "{:,.0f}".format(v)
    return "{:.3g}".format(v)


def summary_md(rep):
    c = rep["counts"]
    base, head = rep["base"], rep["head"]
    lines = [
        "## Regression check: `%s` → `%s`" % (base["sha"][:10], head["sha"][:10]),
        "",
        "**%d regression%s**, %d improvement%s, %d unclear, %d unchanged "
        "(%d comparisons, %d rounds each side)." % (
            c["regression"], "" if c["regression"] == 1 else "s",
            c["improvement"], "" if c["improvement"] == 1 else "s",
            c["unclear"], c["unchanged"], len(rep["results"]), rep["settings"]["rounds"]),
        "",
    ]
    flagged = [r for r in rep["results"] if r["status"] != "unchanged"]
    order = {"regression": 0, "unclear": 1, "improvement": 2}
    flagged.sort(key=lambda r: (order[r["status"]], -abs(r["change_pct"] or 1e9)))
    if flagged:
        lines += ["| | Benchmark | Metric | Base | Head | Change | p |",
                  "|---|---|---|---:|---:|---:|---:|"]
        icon = {"regression": "🔴", "improvement": "🟢", "unclear": "⚪"}
        for r in flagged[:40]:
            if r["change_pct"] is None:
                ch = "%+g" % (r["head"]["median"] - r["base"]["median"])
            else:
                ch = "%+.1f%%" % r["change_pct"]
            lines.append("| %s | `%s` | %s | %s | %s | %s | %.2g |" % (
                icon[r["status"]], r["benchmark"], r["unit"], fmt_num(r["base"]["median"]),
                fmt_num(r["head"]["median"]), ch, r["p_value"]))
        if len(flagged) > 40:
            lines.append("")
            lines.append("…and %d more in the full report." % (len(flagged) - 40))
    if rep["build_errors"]:
        lines += ["", "**%d package(s) failed to build** and were skipped; see the report." %
                  len(rep["build_errors"])]
    for n in rep["notes"]:
        lines += ["", "> " + n]
    lines += ["", "Full report: download the `regression-report` artifact below and drop it on %s" % VIEWER_URL]
    return "\n".join(lines) + "\n"


# ---------------------------------------------------------------- main

def main():
    ap = argparse.ArgumentParser(description="Compare a Go repo's benchmarks between two commits.")
    ap.add_argument("--base", required=True, help="older commit (sha, tag or branch)")
    ap.add_argument("--head", required=True, help="newer commit")
    ap.add_argument("--packages", default="./...", help="go package pattern(s), space separated")
    ap.add_argument("--bench", default=".", help="go -bench regex")
    ap.add_argument("--rounds", type=int, default=10, help="samples per side")
    ap.add_argument("--benchtime", default="500ms", help="go -benchtime per sample, e.g. 500ms or 100x")
    ap.add_argument("--alpha", type=float, default=0.05, help="false discovery rate")
    ap.add_argument("--min-effect", type=float, default=3.0, help="smallest timing change (%%) worth flagging")
    ap.add_argument("--budget-minutes", type=float, default=60, help="shrink rounds (min 5) to fit this")
    ap.add_argument("--module-dir", default=".", help="folder with go.mod, relative to the repo root")
    ap.add_argument("--repo", default="", help="name shown in the report (default: from git)")
    ap.add_argument("--out", default="regression-report.json")
    ap.add_argument("--summary", default="", help="also write a Markdown summary here")
    ap.add_argument("--raw-dir", default="", help="also save raw benchmark output here")
    ap.add_argument("--fail-on-regression", action="store_true")
    a = ap.parse_args()

    repo = sh(["git", "rev-parse", "--show-toplevel"]).stdout.strip()
    base, head = commit_info(repo, a.base), commit_info(repo, a.head)
    log("base %s  %s" % (base["sha"][:10], base["subject"]))
    log("head %s  %s" % (head["sha"][:10], head["subject"]))
    patterns = a.packages.split()
    top = a.bench.split("/")[0]
    notes = []

    work = tempfile.mkdtemp(prefix="regcheck-")
    trees = {}
    try:
        for side, info in (("base", base), ("head", head)):
            wt = os.path.join(work, side)
            sh(["git", "worktree", "add", "--detach", "--force", wt, info["sha"]], cwd=repo)
            trees[side] = wt

        pkgs, built, errors = {}, {}, []
        for side in ("base", "head"):
            moddir = os.path.join(trees[side], a.module_dir)
            if not os.path.isfile(os.path.join(moddir, "go.mod")):
                raise SystemExit("no go.mod in %s at %s commit; set --module-dir" % (a.module_dir, side))
            pkgs[side] = bench_packages(moddir, patterns, top)
            log("%s: %d package(s) with matching benchmarks" % (side, len(pkgs[side])))
        common = set(pkgs["base"]) & set(pkgs["head"])
        only = sorted((set(pkgs["base"]) | set(pkgs["head"])) - common)
        if only:
            notes.append("%d package(s) have matching benchmarks on one side only and were skipped: %s"
                         % (len(only), ", ".join(only[:10]) + (" …" if len(only) > 10 else "")))
        if not common:
            raise SystemExit("no package has benchmarks matching %r at both commits" % a.bench)
        for side in ("base", "head"):
            moddir = os.path.join(trees[side], a.module_dir)
            built[side], errs = build_side(side, moddir, {p: pkgs[side][p] for p in common},
                                           os.path.join(work, "bin-" + side))
            errors += errs
        runnable = sorted(set(built["base"]) & set(built["head"]))
        if not runnable:
            raise SystemExit("nothing built on both sides; first error:\n" +
                             (errors[0]["error"] if errors else "unknown"))

        samples = defaultdict(lambda: defaultdict(list))
        raw = {"base": [], "head": []}
        run_errors = []
        rounds = a.rounds
        started = time.time()
        r = 0
        while r < rounds:
            order = ("base", "head") if r % 2 == 0 else ("head", "base")
            for pkg in runnable:
                for side in order:
                    binary, pdir = built[side][pkg]
                    code, out = run_binary(binary, pdir, a.bench, a.benchtime, 30)
                    raw[side].append("# round %d  %s\n%s" % (r + 1, pkg, out))
                    if code != 0 and r == 0:
                        run_errors.append({"side": side, "package": pkg, "error": out.strip()[-2000:]})
                    for name, unit, val in parse_bench(out):
                        samples[(pkg, name, unit)][side].append(val)
                if r == 0 and time.time() - started > a.budget_minutes * 60 / 5:
                    msg = ("Too many benchmarks for a %g-minute budget: one round alone would take "
                           "over %g minutes, so 5 rounds won't fit. Narrow the benchmark regex or "
                           "packages, shorten the time per sample, or raise the budget."
                           % (a.budget_minutes, a.budget_minutes / 5))
                    if a.summary:
                        with open(a.summary, "a", encoding="utf-8") as f:
                            f.write("## Regression check stopped\n\n" + msg + "\n")
                    raise SystemExit(msg)
            r += 1
            if r == 1:
                per_round = time.time() - started
                fit = int(a.budget_minutes * 60 // max(per_round, 1e-6))
                log("round 1 took %.0fs" % per_round)
                if fit < rounds:
                    new = max(5, fit)
                    if new < rounds:
                        notes.append("Rounds cut from %d to %d to fit the %g-minute budget "
                                     "(one round took %.0fs). Fewer rounds means only larger "
                                     "changes can be confirmed." % (rounds, new, a.budget_minutes, per_round))
                        rounds = new
            log("round %d/%d done" % (r, rounds))

        results = analyze(samples, a.alpha, a.min_effect)
        counts = Counter(x["status"] for x in results)
        cpu = ""
        try:
            with open("/proc/cpuinfo") as f:
                m = re.search(r"model name\s*:\s*(.+)", f.read())
                cpu = m.group(1).strip() if m else ""
        except OSError:
            pass
        gh = os.environ.get("GITHUB_RUN_ID")
        report = {
            "tool": "regression detector / regcheck", "version": VERSION,
            "generated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
            "repo": repo_name(repo, a.repo), "base": base, "head": head,
            "settings": {"packages": a.packages, "bench": a.bench, "rounds": rounds,
                         "benchtime": a.benchtime, "alpha": a.alpha, "min_effect_pct": a.min_effect,
                         "module_dir": a.module_dir},
            "environment": {
                "go": sh(["go", "version"]).stdout.strip(), "cpu": cpu, "cores": os.cpu_count(),
                "runner": "GitHub Actions (%s)" % os.environ.get("RUNNER_OS", "?") if gh else "a local machine",
                "run_url": ("%s/%s/actions/runs/%s" % (os.environ.get("GITHUB_SERVER_URL", "https://github.com"),
                                                       os.environ.get("GITHUB_REPOSITORY", ""), gh)) if gh else None,
                "minutes": round((time.time() - started) / 60, 1),
            },
            "counts": {k: counts.get(k, 0) for k in ("regression", "improvement", "unclear", "unchanged")},
            "results": results,
            "build_errors": errors,
            "run_errors": run_errors,
            "notes": notes,
        }
        with open(a.out, "w") as f:
            json.dump(report, f, indent=1)
        log("wrote %s" % a.out)
        md = summary_md(report)
        if a.summary:
            with open(a.summary, "a", encoding="utf-8") as f:
                f.write(md)
        print(md)
        if a.raw_dir:
            os.makedirs(a.raw_dir, exist_ok=True)
            for side in raw:
                with open(os.path.join(a.raw_dir, side + ".txt"), "w") as f:
                    f.write("\n".join(raw[side]))
        if a.fail_on_regression and report["counts"]["regression"]:
            sys.exit(1)
    finally:
        for wt in trees.values():
            sh(["git", "worktree", "remove", "--force", wt], cwd=repo, check=False)
        shutil.rmtree(work, ignore_errors=True)


if __name__ == "__main__":
    main()
