Viewing files at commit 5717cc9fc7edCommit detailsView latest

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