Viewing files at commit e70815b9044aCommit detailsView latest

Browse files
suites/merge/run_merge_suite.py 148 lines · 7.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
    ap.add_argument("--resummarize", type=Path, default=None, metavar="JSONL",
74
                    help="recompute the summary (known-bug mapping included) from an existing JSONL run; no Oak")
75
    args = ap.parse_args(argv)
76
    groups = [g for g in args.groups.split(",") if g]
77
    if not set(groups) <= set(GROUPS):
78
        ap.error("unknown group")
79
    if args.resummarize:
80
        rows = [json.loads(line) for line in args.resummarize.read_text().splitlines() if line.strip()]
81
        summary = finish_summary(summarize(rows), rows)
82
        if args.summary:
83
            args.summary.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n")
84
        print(format_table(summary), file=sys.stderr)
85
        return 1 if summary["counts"]["oak-wrong"] or summary["counts"]["harness-error"] else 0
86
    git_bin = resolve_git(args.git_bin)
87
    workdir = args.workdir.resolve()
88
    workdir.mkdir(parents=True, exist_ok=True)
89
    suite = Suite(workdir, args.oak_bin, git_bin, jobs=args.jobs, keep_equal=args.keep_equal)
90
    scenarios = load(groups, workdir / "fixtures-src", git_bin, suite.git_home,
91
                     args.generated_count, args.generated_seed)
92
    if args.only:
93
        scenarios = [s for s in scenarios if fnmatch.fnmatch(s["id"], args.only)]
94
    if args.limit:
95
        scenarios = scenarios[:args.limit]
96
    if args.list:
97
        for s in scenarios:
98
            print(s["id"] + ("  [unsupported: %s]" % s["unsupported"] if s["unsupported"] else ""))
99
        return 0
100
101
    def emit(row):
102
        print(json.dumps(row, sort_keys=True), flush=True)
103
104
    rows = suite.run(scenarios, emit)
105
    summary = finish_summary(summarize(rows), rows)
106
    summary["meta"] = suite.meta
107
    summary["run_id"] = suite.run_id
108
    if args.summary:
109
        args.summary.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n")
110
    print(format_table(summary), file=sys.stderr)
111
    return 1 if summary["counts"]["oak-wrong"] or summary["counts"]["harness-error"] else 0
112
113
114
def finish_summary(summary: dict, rows) -> dict:
115
    summary["phase2_specs_not_executed"] = [s["id"] for s in sources.PHASE2_SPECS]
116
    summary["oak_wrong"] = [{"scenario": r["scenario"], "direction": r["direction"], "reasons": r["reasons"],
117
                             "known_bug": r.get("known_bug"),
118
                             "case_dir": r.get("case_dir"), "repro": r["repro"]}
119
                            for r in rows if r["class"] == "oak-wrong"]
120
    summary["harness_errors"] = [{"scenario": r["scenario"], "direction": r["direction"], "reasons": r["reasons"]}
121
                                 for r in rows if r["class"] == "harness-error"]
122
    return summary
123
124
125
def format_table(summary: dict) -> str:
126
    classes = list(summary["counts"])
127
    lines = ["| origin | " + " | ".join(classes) + " |", "|---|" + "---|" * len(classes)]
128
    for origin, counts in sorted(summary["by_origin"].items()):
129
        lines.append(f"| {origin} | " + " | ".join(str(counts[c]) for c in classes) + " |")
130
    lines.append("| **total** | " + " | ".join(str(summary["counts"][c]) for c in classes) + " |")
131
    lines.append("")
132
    for law, v in summary["laws"].items():
133
        lines.append(f"{law}: {v['true']}/{v['measured']}")
134
    lines.append("")
135
    for bug, info in (summary.get("known_bugs") or {}).items():
136
        lines.append(f"{bug} ({info['family']}): {info['rows']} row(s), pinned {info['expected_rows']} - "
137
                     f"{info['status']}; new={len(info['new_rows'])} vanished={len(info['vanished_rows'])}")
138
    if "oak_wrong_unmapped" in summary:
139
        lines.append(f"oak-wrong rows not mapped to a known bug: {summary['oak_wrong_unmapped']}")
140
        lines.append(f"failed pulls violating 'failed sync => worktree matches HEAD' (HEAD moved or worktree "
141
                     f"left dirty): {summary['post_failure_hazard_rows']}")
142
        lines.append(f"missed conflicts by class: {summary['missed_conflict_by_class']}")
143
        lines.append(f"missed conflicts by git kind: {summary['missed_conflict_by_git_kind']}")
144
    return "\n".join(lines)
145
146
147
if __name__ == "__main__":
148
    raise SystemExit(main())