#!/usr/bin/env python3
"""CI known Mozilla defects - the list of crashes a test may meet and the matcher that reads it (stdlib only, Python >= 3.11).

A crash that comes from a defect of Mozilla's own Firefox (one the stock browser has too) is not fixed by a patch of ours (see the
engine's rule on Mozilla defects); the tests that meet it still have to say so by name and not by a threshold, a skip or a rerun.
That is this file's job. Each repository that judges crashes keeps a list (the core and the wrapper: ci/mozilla-defects.json; the series:
tools/mozilla-defects.json), a JSON array with one row per known defect. The matcher is shared: every repository reads it from the
core's main, so the judge is never the branch being judged (the way scripts/ci_regressions.py is read).

THE RULE, as a question every verdict asks of every crash:

    Does the crash match exactly an entry of ci/mozilla-defects.json (D<n>, bug, signature: process type, thread or frame, exit phase),
    and does the entry hold for the Firefox version of the engine under test?

A row:

    {"id": "D<n>", "bug": "<https://bugzilla.mozilla.org/show_bug.cgi?id=N, or empty until the bug is filed>",
     "firefox": {"from": "<major.minor>", "to": "<major.minor or major.*>"},
     "signature": {"process": "<parent|tab|gpu|rdd|socket|utility|backgroundtask|...>", "phase": "startup|run|exit",
                   "thread": "<thread name, optional>", "frames": ["<top frame>", "..."], "reason": "<optional>"},
     "seen": "<owner>/<repo>/actions/runs/<digits>[/job/<digits>]", "why": "<one line>"}

`frames` is optional: an ordered prefix of the top frames of the crashing thread. `reason` is optional: the MOZ_CRASH text, the signal or
the NTSTATUS. A signature must declare `process`, `phase` and at least one of `thread` or `frames`. Ids are unique. `firefox` is the range
of Firefox releases the row was seen on and still holds for, both ends included: `from` is a major.minor, `to` is a major.minor or
`<major>.*` (every minor of that major). The engine under test is a version string such as 159.0 or 159.0.1; only major.minor decides.

The crash record `C` is the one record a judge builds from its evidence:

    {"process": "...", "phase": "...", "thread": "...", "frames": ["<top frame first>", "..."], "reason": "..."}

EXACT means exactly that: every field the row's signature declares is equal to the crash's field (frames: the row's list equals the first
len(row frames) frames of the crash, in order, so a crash with fewer frames than the row misses). No regular expression, no wildcard, no
case folding, no substring. A field the row does not declare is not compared. A row whose range does not contain the engine cannot match.

    ci_mozilla_defects.py check --file F --engine-version V
        the schema of every row, every id once, and every row's range contains V. A row whose range does not contain V is RED: the port
        that moved the engine to V re-justifies the row for this version (a new range and a new `seen`) or drops it.
    ci_mozilla_defects.py match --file F --engine-version V --crash C.json
        the crash record C against the rows of F that hold for V. Exit 0 and one line `MATCHED D<n> (<bug or 'not filed'>): <why>`, which
        the caller prints and counts. Exit 1 and `no known defect matches: the crash stays red` with the record printed.

Exit codes: 0 ok (or matched); 1 red (a problem in the file, or no match); 2 the checker cannot run (a file that cannot be read or is
not JSON, a version that is not major.minor[.patch], a crash record that is not a record) - the caller treats 2 as red, never as a pass;
3 usage. Every problem prints one line:

    FAIL <where>: <what>. Fix: <how>. Rule: <the rule, short>

A Python API for the callers in other repositories (they import this file by path, from the core's main): `load(path)`,
`problems(rows, version, name=...)`, `match(rows, version, crash) -> row | None` and
`verdict(rows, version, crashes, measurements_complete) -> (red, lines)`. `load` and the version parsing raise `CannotRun`.

THE VERDICT RULE (`verdict`). A match excuses ONLY the crash itself. The test's own assertions still have to pass, and every measurement
must be present, compared and equal; a crash that cost a measurement (a visit that has no result, a dump that was not written) stays red
as a missing result, even when the defect matched. So the verdict is RED when any crash has no match; RED when `measurements_complete`
is False (even if every crash matched: the line names the defect that matched and says what is missing is the caller's to print); RED
when the file has any problem (including a range that does not contain the engine). Otherwise it is not red and has one line per matched
crash, naming its D<n>. Never a skip, never a threshold, never a rerun.
"""
from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path

RULE = ("Does the crash match exactly an entry of ci/mozilla-defects.json (D<n>, bug, signature: process type, thread or frame, "
        "exit phase), and does the entry hold for the Firefox version of the engine under test?")
SHORT_RULE = "known Mozilla defect, exact match and range (ci/mozilla-defects.json)"
DEFAULT_NAME = "ci/mozilla-defects.json"

PHASES = ("startup", "run", "exit")
ROW_KEYS = {"id", "bug", "firefox", "signature", "seen", "why"}
SIGNATURE_KEYS = {"process", "phase", "thread", "frames", "reason"}
CRASH_KEYS = {"process", "phase", "thread", "frames", "reason"}
_ID = re.compile(r"^D\d+$")
_BUG = re.compile(r"^https://bugzilla\.mozilla\.org/show_bug\.cgi\?id=\d+$")
_RUN = re.compile(r"^[\w.-]+/[\w.-]+/actions/runs/\d+(/job/\d+)?$")
_VERSION = re.compile(r"^(\d+)\.(\d+)(\.\d+)*$")
_FROM = re.compile(r"^(\d+)\.(\d+)$")
_TO = re.compile(r"^(\d+)\.(\d+|\*)$")
_ANY_MINOR = 10 ** 9


class CannotRun(Exception):
    """The checker cannot run (exit 2): unreadable file, not JSON, a bad version string or a bad crash record."""


def _line(where: str, what: str, fix: str) -> str:
    return "FAIL %s: %s. Fix: %s. Rule: %s" % (where, what, fix, SHORT_RULE)


def _text(value: object) -> bool:
    return isinstance(value, str) and bool(value.strip()) and "\n" not in value


def parse_version(version: object) -> tuple[int, int]:
    """major.minor of an engine version such as 159.0 or 159.0.1; CannotRun for anything else."""
    m = _VERSION.match(version) if isinstance(version, str) else None
    if not m:
        raise CannotRun("the engine version %r is not major.minor[.patch] (such as 159.0 or 159.0.1)" % (version,))
    return int(m.group(1)), int(m.group(2))


def load(path: "str | Path") -> list:
    """The rows of a defects file; CannotRun when it cannot be read or is not JSON. Not being an array is a schema problem, not here."""
    try:
        raw = Path(path).read_bytes()
    except OSError as exc:
        raise CannotRun("the file %s cannot be read (%s)" % (path, exc)) from exc
    try:
        return json.loads(raw.decode("utf-8"))
    except (UnicodeDecodeError, ValueError) as exc:
        raise CannotRun("the file %s is not JSON (%s)" % (path, exc)) from exc


def _range(row: object) -> "tuple[tuple[int, int], tuple[int, int]] | None":
    """((from major, minor), (to major, minor or _ANY_MINOR)) of a well-formed range, else None."""
    rng = row.get("firefox") if isinstance(row, dict) else None
    if not isinstance(rng, dict):
        return None
    lo, hi = rng.get("from"), rng.get("to")
    ml = _FROM.match(lo) if isinstance(lo, str) else None
    mh = _TO.match(hi) if isinstance(hi, str) else None
    if not ml or not mh:
        return None
    low = (int(ml.group(1)), int(ml.group(2)))
    high = (int(mh.group(1)), _ANY_MINOR if mh.group(2) == "*" else int(mh.group(2)))
    return (low, high) if low <= high else None


def _where(name: str, row: object, index: int) -> str:
    rid = row.get("id") if isinstance(row, dict) else None
    if isinstance(rid, str) and _ID.match(rid):
        return "%s row %s" % (name, rid)
    return "%s row #%d" % (name, index)


def _row_problems(row: object, where: str) -> list[str]:
    if not isinstance(row, dict):
        return [_line(where, "the row is not an object", "write the row as a JSON object with the fields of the format")]
    out: list[str] = []
    for key in sorted(set(row) - ROW_KEYS):
        out.append(_line(where, "unknown field %r" % key, "remove it; the format has only %s" % ", ".join(sorted(ROW_KEYS))))
    for key in sorted(ROW_KEYS - set(row)):
        out.append(_line(where, "field %r is missing" % key, "add it (`bug` may be an empty string until the bug is filed)"))
    if "id" in row and not (isinstance(row["id"], str) and _ID.match(row["id"])):
        out.append(_line(where, "field 'id' is not D<n> (%r)" % (row["id"],), "write it as D followed by digits, such as D31"))
    if "bug" in row and not (row["bug"] == "" or (isinstance(row["bug"], str) and _BUG.match(row["bug"]))):
        out.append(_line(where, "field 'bug' is neither empty nor a Bugzilla URL (%r)" % (row["bug"],),
                         "write https://bugzilla.mozilla.org/show_bug.cgi?id=<digits>, or an empty string until the bug is filed"))
    if "seen" in row and not (isinstance(row["seen"], str) and _RUN.match(row["seen"])):
        out.append(_line(where, "field 'seen' is not a run (%r)" % (row["seen"],),
                         "write <owner>/<repo>/actions/runs/<digits>[/job/<digits>]"))
    if "why" in row and not _text(row["why"]):
        out.append(_line(where, "field 'why' is empty or not one line", "write why this crash is Mozilla's in one line"))
    if "firefox" in row and _range(row) is None:
        out.append(_line(where, "field 'firefox' is not {\"from\": \"<major.minor>\", \"to\": \"<major.minor or major.*>\"} with from <= to (%r)"
                         % (row["firefox"],), "write the range of Firefox releases, both ends included, such as 159.0 to 159.*"))
    if "signature" in row:
        out.extend(_signature_problems(row["signature"], where))
    return out


def _signature_problems(sig: object, where: str) -> list[str]:
    if not isinstance(sig, dict):
        return [_line(where, "field 'signature' is not an object", "write {\"process\": ..., \"phase\": ..., \"thread\": ... or \"frames\": ...}")]
    out: list[str] = []
    for key in sorted(set(sig) - SIGNATURE_KEYS):
        out.append(_line(where, "unknown signature field %r" % key,
                         "remove it; a signature has only %s" % ", ".join(sorted(SIGNATURE_KEYS))))
    for key in ("process", "phase"):
        if key not in sig:
            out.append(_line(where, "signature field %r is missing" % key, "declare it: a signature names the process type and the phase"))
    if "thread" not in sig and "frames" not in sig:
        out.append(_line(where, "the signature declares neither 'thread' nor 'frames'",
                         "declare the crashing thread's name or the top frames (an ordered prefix): the process and the phase alone match too much"))
    if "process" in sig and not _text(sig["process"]):
        out.append(_line(where, "signature field 'process' is empty or not one line", "write the process type, such as parent or gpu"))
    if "phase" in sig and sig["phase"] not in PHASES:
        out.append(_line(where, "signature field 'phase' is %r" % (sig["phase"],), "use one of %s" % ", ".join(PHASES)))
    for key in ("thread", "reason"):
        if key in sig and not _text(sig[key]):
            out.append(_line(where, "signature field %r is empty or not one line" % key, "write the exact text, or remove the field"))
    if "frames" in sig and not (isinstance(sig["frames"], list) and sig["frames"] and all(_text(f) for f in sig["frames"])):
        out.append(_line(where, "signature field 'frames' is not a non-empty list of frame names",
                         "write the top frames of the crashing thread, top first, one string each"))
    return out


def problems(rows: object, version: str, name: str = DEFAULT_NAME) -> list[str]:
    """Every problem of the file for the engine `version`: schema, duplicate ids, and a range that does not contain the engine."""
    ver = parse_version(version)
    if not isinstance(rows, list):
        return [_line(name, "the file is not a JSON array of rows", "write the file as an array, [] when no defect is known")]
    out: list[str] = []
    seen_ids: dict[str, int] = {}
    for index, row in enumerate(rows):
        where = _where(name, row, index)
        out.extend(_row_problems(row, where))
        rid = row.get("id") if isinstance(row, dict) else None
        if isinstance(rid, str) and _ID.match(rid):
            if rid in seen_ids:
                out.append(_line(where, "the id %s is also row #%d" % (rid, seen_ids[rid]),
                                 "give every defect its own D<n>; one row per defect"))
            else:
                seen_ids[rid] = index
        rng = _range(row)
        if rng is not None and not rng[0] <= ver <= rng[1]:
            out.append(_line(where, "its range %s to %s does not contain the engine under test (%s)"
                             % (row["firefox"]["from"], row["firefox"]["to"], version),
                             "the port re-justifies the row for this version (a new range and a new `seen`) or drops it"))
    return out


def _crash_problem(crash: object) -> "str | None":
    if not isinstance(crash, dict):
        return "the crash record is not an object"
    extra = sorted(set(crash) - CRASH_KEYS)
    if extra:
        return "the crash record has unknown fields %s" % ", ".join(extra)
    for key in ("process", "phase"):
        if not isinstance(crash.get(key), str):
            return "the crash record has no string %r" % key
    for key in ("thread", "reason"):
        if key in crash and not isinstance(crash[key], str):
            return "the crash record field %r is not a string" % key
    frames = crash.get("frames", [])
    if not (isinstance(frames, list) and all(isinstance(f, str) for f in frames)):
        return "the crash record field 'frames' is not a list of strings"
    return None


def _equal(row: dict, crash: dict) -> bool:
    sig = row["signature"]
    for key in ("process", "phase", "thread", "reason"):
        if key in sig and sig[key] != crash.get(key):
            return False
    if "frames" in sig:
        frames = crash.get("frames", [])
        if frames[:len(sig["frames"])] != sig["frames"]:
            return False
    return True


def match(rows: object, version: str, crash: object) -> "dict | None":
    """The first row that holds for `version` and whose signature equals the crash field by field; None otherwise. CannotRun on a bad record."""
    ver = parse_version(version)
    bad = _crash_problem(crash)
    if bad:
        raise CannotRun(bad)
    if not isinstance(rows, list):
        return None
    for row in rows:
        if not isinstance(row, dict) or _row_problems(row, "x"):
            continue  # a malformed row never matches; `problems` is what says so
        rng = _range(row)
        if rng is None or not rng[0] <= ver <= rng[1]:
            continue
        if _equal(row, crash):
            return row
    return None


def _matched_line(row: dict) -> str:
    return "MATCHED %s (%s): %s" % (row["id"], row["bug"] or "not filed", row["why"])


def verdict(rows: object, version: str, crashes: list, measurements_complete: bool,
            name: str = DEFAULT_NAME) -> "tuple[bool, list[str]]":
    """(red, lines) of a test that met `crashes` (the crash records it found, possibly none).

    A match excuses only the crash itself. Red when any crash has no match; red when `measurements_complete` is False even if every crash
    matched; red when the file has any problem. Otherwise not red, with one MATCHED line per matched crash. No skip, no threshold, no rerun."""
    lines = problems(rows, version, name)
    red = bool(lines)
    matched: list[dict] = []
    for index, crash in enumerate(crashes):
        where = "crash #%d" % index
        try:
            row = match(rows, version, crash)
        except CannotRun as exc:
            lines.append(_line(where, "%s" % exc, "build the record {process, phase, thread, frames, reason} from the crash evidence"))
            red = True
            continue
        if row is None:
            lines.append(_line(where, "no known defect matches: the crash stays red (%s)" % json.dumps(crash, sort_keys=True),
                               "fix the product, or declare the crash as a Mozilla defect with its bug and an exact signature in %s" % name))
            red = True
        else:
            matched.append(row)
            lines.append(_matched_line(row))
    if not measurements_complete:
        red = True
        names = ", ".join(r["id"] for r in matched)
        what = ("the crash matched %s, which excuses the crash only, and a measurement is missing" % names
                if matched else "a measurement is missing")
        lines.append(_line("measurements", what,
                           "a missing result stays red: the test's own assertions and every measurement must still pass; the caller "
                           "prints which measurement is missing"))
    return red, lines


class _Parser(argparse.ArgumentParser):
    def error(self, message: str) -> None:  # usage is exit 3, as the rule of exit codes says
        self.print_usage(sys.stderr)
        sys.stderr.write("%s: error: %s\n" % (self.prog, message))
        raise SystemExit(3)


def _build_parser() -> argparse.ArgumentParser:
    ap = _Parser(prog="ci_mozilla_defects.py", description=__doc__.split("\n", 1)[0])
    sub = ap.add_subparsers(dest="mode", required=True, parser_class=_Parser)
    for mode in ("check", "match"):
        p = sub.add_parser(mode)
        p.add_argument("--file", required=True)
        p.add_argument("--engine-version", required=True)
        if mode == "match":
            p.add_argument("--crash", required=True)
    return ap


def main(argv: "list[str] | None" = None) -> int:
    args = _build_parser().parse_args(argv)
    try:
        rows = load(args.file)
        version = args.engine_version
        parse_version(version)
        found = problems(rows, version, str(args.file))
        if args.mode == "check":
            for line in found:
                print(line)
            if found:
                return 1
            print("OK ci_mozilla_defects check: %d known defect(s), every range contains the engine %s" % (len(rows), version))
            return 0
        try:
            crash = json.loads(Path(args.crash).read_text(encoding="utf-8"))
        except (OSError, ValueError) as exc:
            raise CannotRun("the crash record %s cannot be read as JSON (%s)" % (args.crash, exc)) from exc
        row = match(rows, version, crash) if not found else None
        for line in found:
            print(line)
        if row is None:
            print("no known defect matches: the crash stays red")
            print(json.dumps(crash, sort_keys=True))
            return 1
        print(_matched_line(row))
        return 0
    except CannotRun as exc:
        print(_line("ci_mozilla_defects", "cannot run: %s" % exc,
                    "give a readable JSON file, an engine version such as 159.0 and a crash record"))
        return 2


if __name__ == "__main__":
    sys.exit(main())
