Viewing files at commit 2f5107c20e85Commit detailsView latest

Browse files
suites/merge/run_merge_suite.py 133 lines · 6.1 KB · python
1
#!/usr/bin/env python3
2
"""Differential merge-correctness suite: git merge-ort (oracle) vs Oak's merge engine.
3
4
stdout: diagnostic JSONL (one row per directional case), then nothing else.
5
--summary FILE: JSON summary (counts per class, merge-law rates, oak-wrong list).
6
Exit: 0 when no case is oak-wrong or harness-error, 1 otherwise, 2 on usage error.
7
Rows are diagnostic evidence (evidence_class diagnostic_merge_correctness); never
8
ingest them into performance reports. See suites/merge/README.md.
9
"""
10
from __future__ import annotations
11
12
import argparse
13
import fnmatch
14
import json
15
from pathlib import Path
16
import shutil
17
import sys
18
19
HERE = Path(__file__).resolve().parent
20
sys.path.insert(0, str(HERE))
21
sys.path.insert(0, str(HERE.parents[1] / "scripts"))
22
23
from mergesuite import sources  # noqa: E402
24
from mergesuite.runner import Suite, summarize  # noqa: E402
25
26
GROUPS = ("gix-tree", "gix-cartesian", "gix-text", "t64xx", "native", "generated")
27
28
29
def resolve_git(explicit: str | None) -> str:
30
    if explicit:
31
        return explicit
32
    try:
33
        from oakbench.subjects import which_measured_git
34
        found = which_measured_git()
35
    except Exception:  # pragma: no cover - oakbench import is best effort
36
        found = shutil.which("git")
37
    if not found:
38
        raise SystemExit("git not found")
39
    return found
40
41
42
def load(groups, workdir: Path, git_bin: str, home: Path, gen_count: int, gen_seed: int):
43
    scenarios = []
44
    if "gix-tree" in groups:
45
        scenarios += sources.gitoxide_tree(workdir, git_bin, home)
46
    if "gix-cartesian" in groups:
47
        scenarios += sources.gitoxide_cartesian(workdir, git_bin, home)
48
    if "gix-text" in groups:
49
        scenarios += sources.gitoxide_text(workdir, git_bin, home)
50
    if "t64xx" in groups:
51
        scenarios += sources.git_t64xx(workdir, git_bin, home)
52
    if "native" in groups:
53
        scenarios += sources.native_incidents(workdir, git_bin, home)
54
    if "generated" in groups:
55
        scenarios += sources.generated(workdir, git_bin, home, gen_count, gen_seed)
56
    return scenarios
57
58
59
def main(argv=None) -> int:
60
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
61
    ap.add_argument("--workdir", type=Path, required=True, help="scratch dir (fixtures, oak serve data, cases)")
62
    ap.add_argument("--oak-bin", default="oak")
63
    ap.add_argument("--git-bin", default=None, help="oracle git (default: real git, xcrun shim resolved)")
64
    ap.add_argument("--groups", default=",".join(GROUPS), help="comma list of " + ",".join(GROUPS))
65
    ap.add_argument("--only", default=None, help="fnmatch pattern on scenario id")
66
    ap.add_argument("--limit", type=int, default=None)
67
    ap.add_argument("--jobs", type=int, default=4)
68
    ap.add_argument("--generated-count", type=int, default=40)
69
    ap.add_argument("--generated-seed", type=int, default=20260928)
70
    ap.add_argument("--keep-equal", action="store_true", help="keep case dirs of equal-to-git cases")
71
    ap.add_argument("--summary", type=Path, default=None)
72
    ap.add_argument("--list", action="store_true", help="list scenario ids and exit")
73
    args = ap.parse_args(argv)
74
    groups = [g for g in args.groups.split(",") if g]
75
    if not set(groups) <= set(GROUPS):
76
        ap.error("unknown group")
77
    git_bin = resolve_git(args.git_bin)
78
    workdir = args.workdir.resolve()
79
    workdir.mkdir(parents=True, exist_ok=True)
80
    suite = Suite(workdir, args.oak_bin, git_bin, jobs=args.jobs, keep_equal=args.keep_equal)
81
    scenarios = load(groups, workdir / "fixtures-src", git_bin, suite.git_home,
82
                     args.generated_count, args.generated_seed)
83
    if args.only:
84
        scenarios = [s for s in scenarios if fnmatch.fnmatch(s["id"], args.only)]
85
    if args.limit:
86
        scenarios = scenarios[:args.limit]
87
    if args.list:
88
        for s in scenarios:
89
            print(s["id"] + ("  [unsupported: %s]" % s["unsupported"] if s["unsupported"] else ""))
90
        return 0
91
92
    def emit(row):
93
        print(json.dumps(row, sort_keys=True), flush=True)
94
95
    rows = suite.run(scenarios, emit)
96
    summary = summarize(rows)
97
    summary["meta"] = suite.meta
98
    summary["run_id"] = suite.run_id
99
    summary["phase2_specs_not_executed"] = [s["id"] for s in sources.PHASE2_SPECS]
100
    summary["oak_wrong"] = [{"scenario": r["scenario"], "direction": r["direction"], "reasons": r["reasons"],
101
                             "known_bug": r.get("known_bug"),
102
                             "case_dir": r.get("case_dir"), "repro": r["repro"]}
103
                            for r in rows if r["class"] == "oak-wrong"]
104
    summary["harness_errors"] = [{"scenario": r["scenario"], "direction": r["direction"], "reasons": r["reasons"]}
105
                                 for r in rows if r["class"] == "harness-error"]
106
    if args.summary:
107
        args.summary.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n")
108
    print(format_table(summary), file=sys.stderr)
109
    return 1 if summary["counts"]["oak-wrong"] or summary["counts"]["harness-error"] else 0
110
111
112
def format_table(summary: dict) -> str:
113
    classes = list(summary["counts"])
114
    lines = ["| origin | " + " | ".join(classes) + " |", "|---|" + "---|" * len(classes)]
115
    for origin, counts in sorted(summary["by_origin"].items()):
116
        lines.append(f"| {origin} | " + " | ".join(str(counts[c]) for c in classes) + " |")
117
    lines.append("| **total** | " + " | ".join(str(summary["counts"][c]) for c in classes) + " |")
118
    lines.append("")
119
    for law, v in summary["laws"].items():
120
        lines.append(f"{law}: {v['true']}/{v['measured']}")
121
    lines.append("")
122
    for bug, info in (summary.get("known_bugs") or {}).items():
123
        lines.append(f"{bug} ({info['family']}): {info['rows']} row(s) - {info['status']}")
124
    if "oak_wrong_unmapped" in summary:
125
        lines.append(f"oak-wrong rows not mapped to a known bug: {summary['oak_wrong_unmapped']}")
126
        lines.append(f"failed pulls that moved HEAD with a stale worktree: {summary['post_failure_hazard_rows']}")
127
        lines.append(f"missed conflicts by class: {summary['missed_conflict_by_class']}")
128
        lines.append(f"missed conflicts by git kind: {summary['missed_conflict_by_git_kind']}")
129
    return "\n".join(lines)
130
131
132
if __name__ == "__main__":
133
    raise SystemExit(main())