Viewing files at commit c467b16393a4Commit detailsView latest

Browse files
suites/merge/run_merge_suite.py 166 lines · 8.4 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 SCHEMA_VERSION, Suite, stale_schema_rows, 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
    ap.add_argument("--allow-stale-schema", action="store_true",
76
                    help="with --resummarize: summarize rows written under an older row/reason schema anyway "
77
                         "(known-bug statuses become 'indeterminate'); default refuses")
78
    args = ap.parse_args(argv)
79
    groups = [g for g in args.groups.split(",") if g]
80
    if not set(groups) <= set(GROUPS):
81
        ap.error("unknown group")
82
    if args.resummarize:
83
        rows = [json.loads(line) for line in args.resummarize.read_text().splitlines() if line.strip()]
84
        if not rows:
85
            print(f"resummarize: {args.resummarize} holds no rows; nothing to summarize", file=sys.stderr)
86
            return 2
87
        stale = stale_schema_rows(rows)
88
        if stale:
89
            newer = [v for v in stale if v != "missing" and v.isdigit() and int(v) > SCHEMA_VERSION]
90
            what = ("were written by a NEWER merge suite than this one, not on" if newer and len(newer) == len(stale)
91
                    else "predate" if not newer else "do not match")
92
            print(f"resummarize: {sum(stale.values())}/{len(rows)} row(s) {what} merge-suite row/reason schema "
93
                  f"v{SCHEMA_VERSION} (found {stale}); their reasons cannot be mapped to the current known-bug "
94
                  "patterns, so a missing bug would read as 'fixed'. Re-run the suite"
95
                  + (" (--allow-stale-schema given: statuses reported as indeterminate)."
96
                     if args.allow_stale_schema else ", or pass --allow-stale-schema."), file=sys.stderr)
97
            if not args.allow_stale_schema:
98
                return 2
99
        summary = finish_summary(summarize(rows), rows)
100
        if args.summary:
101
            args.summary.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n")
102
        print(format_table(summary), file=sys.stderr)
103
        return 1 if summary["counts"]["oak-wrong"] or summary["counts"]["harness-error"] else 0
104
    git_bin = resolve_git(args.git_bin)
105
    workdir = args.workdir.resolve()
106
    workdir.mkdir(parents=True, exist_ok=True)
107
    suite = Suite(workdir, args.oak_bin, git_bin, jobs=args.jobs, keep_equal=args.keep_equal)
108
    scenarios = load(groups, workdir / "fixtures-src", git_bin, suite.git_home,
109
                     args.generated_count, args.generated_seed)
110
    if args.only:
111
        scenarios = [s for s in scenarios if fnmatch.fnmatch(s["id"], args.only)]
112
    if args.limit:
113
        scenarios = scenarios[:args.limit]
114
    if args.list:
115
        for s in scenarios:
116
            print(s["id"] + ("  [unsupported: %s]" % s["unsupported"] if s["unsupported"] else ""))
117
        return 0
118
119
    def emit(row):
120
        print(json.dumps(row, sort_keys=True), flush=True)
121
122
    rows = suite.run(scenarios, emit)
123
    summary = finish_summary(summarize(rows), rows)
124
    summary["meta"] = suite.meta
125
    summary["run_id"] = suite.run_id
126
    if args.summary:
127
        args.summary.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n")
128
    print(format_table(summary), file=sys.stderr)
129
    return 1 if summary["counts"]["oak-wrong"] or summary["counts"]["harness-error"] else 0
130
131
132
def finish_summary(summary: dict, rows) -> dict:
133
    summary["phase2_specs_not_executed"] = [s["id"] for s in sources.PHASE2_SPECS]
134
    summary["oak_wrong"] = [{"scenario": r["scenario"], "direction": r["direction"], "reasons": r["reasons"],
135
                             "known_bug": r.get("known_bug"),
136
                             "case_dir": r.get("case_dir"), "repro": r["repro"]}
137
                            for r in rows if r["class"] == "oak-wrong"]
138
    summary["harness_errors"] = [{"scenario": r["scenario"], "direction": r["direction"], "reasons": r["reasons"]}
139
                                 for r in rows if r["class"] == "harness-error"]
140
    return summary
141
142
143
def format_table(summary: dict) -> str:
144
    classes = list(summary["counts"])
145
    lines = ["| origin | " + " | ".join(classes) + " |", "|---|" + "---|" * len(classes)]
146
    for origin, counts in sorted(summary["by_origin"].items()):
147
        lines.append(f"| {origin} | " + " | ".join(str(counts[c]) for c in classes) + " |")
148
    lines.append("| **total** | " + " | ".join(str(summary["counts"][c]) for c in classes) + " |")
149
    lines.append("")
150
    for law, v in summary["laws"].items():
151
        lines.append(f"{law}: {v['true']}/{v['measured']}")
152
    lines.append("")
153
    for bug, info in (summary.get("known_bugs") or {}).items():
154
        lines.append(f"{bug} ({info['family']}): {info['rows']} row(s), pinned {info['expected_rows']} - "
155
                     f"{info['status']}; new={len(info['new_rows'])} vanished={len(info['vanished_rows'])}")
156
    if "oak_wrong_unmapped" in summary:
157
        lines.append(f"oak-wrong rows not mapped to a known bug: {summary['oak_wrong_unmapped']}")
158
        lines.append(f"failed pulls violating 'failed sync => worktree matches HEAD' (HEAD moved or worktree "
159
                     f"left dirty): {summary['post_failure_hazard_rows']}")
160
        lines.append(f"missed conflicts by class: {summary['missed_conflict_by_class']}")
161
        lines.append(f"missed conflicts by git kind: {summary['missed_conflict_by_git_kind']}")
162
    return "\n".join(lines)
163
164
165
if __name__ == "__main__":
166
    raise SystemExit(main())