"""The decision rule of README section 3, tested against a second reading of that section. decide is a pure function of the dossier, and the driver recomputes it from the transcript instead of trusting the arbiter, so the properties that matter are the ones a lying or broken agent cannot talk their way around. These tests enumerate the evidence space the seven nodes can produce and compare every status with a reference rule written here from the README table; they ask that a dossier which is missing a part abstains instead of raising, that only a boolean counts as a confirmation, that weakening the evidence never raises the assurance, that a checker which ran but did not decide blocks the answer instead of being ignored, that two confirmed solvers whose answers differ are never merged into one verdict, that a redundant description of the same set is not read as a disagreement, and that reading a dossier leaves it untouched. """ import copy import itertools from typing import Any, Dict from lgmath import agents, answers, pipeline SET_A = {"type": "set", "var": "x", "product": ["0", "-1", "0", "1"], "roots": [{"q": "-1"}, {"q": "0"}, {"q": "1"}], "runs": [[None, False, 1, False], [1, False, None, False]]} SET_A_SPLIT = {"type": "set", "var": "x", "product": ["0", "-1", "0", "1"], "roots": [{"q": "-1"}, {"q": "0"}, {"q": "1"}], "runs": [[None, False, 0, False], [0, True, 0, True], [0, False, 1, False], [1, False, None, False]]} SET_B = {"type": "set", "var": "x", "product": ["0", "-1", "0", "1"], "roots": [{"q": "-1"}, {"q": "0"}, {"q": "1"}], "runs": [[None, False, 0, False], [0, False, None, False]]} VALUE = {"type": "value", "value": "1/2"} VERDICT = {"type": "verdict", "verdict": "proved", "counterexample": None} CHECK_FIELDS = ("z3", "z3b", "exact", "sampling") TRISTATE = (True, False, None) ASSURANCE = {"VERIFIED": 3, "SINGLE_PROVER": 2, "UNKNOWN": 0} FA_STATES = ("ok", "error", "missing") FB_STATES = ("ok", "error", "not_equiv", "vars", "missing") SOLVER_STATES = ("ok", "inconclusive", "unsupported", "missing") # 26244 dossiers: every combination of the two formalizers, the two solvers and the two checkers. EVIDENCE_SPACE = list(itertools.product( FA_STATES, FB_STATES, SOLVER_STATES, SOLVER_STATES, (False, True), TRISTATE, (False, True), TRISTATE, TRISTATE, TRISTATE)) def dossier(fa: str, fb: str, sa: str, sb: str, has_verifier: bool, verifier_z3: Any, has_adversary: bool, adversary_z3b: Any, adversary_exact: Any, adversary_sampling: Any, first: Dict[str, Any] = VALUE, second: Dict[str, Any] = VALUE) -> Dict[str, Any]: """A dossier built from the shapes the seven nodes can actually leave behind.""" d: Dict[str, Any] = {"v": 1, "problem": "solve x^2 - 5*x + 6 = 0 for x"} if fa == "ok": d["fa"] = {"kind": "solve", "math": "solve ... for x", "vars": ["x"], "decls": [], "body": "true", "status": "sat"} elif fa == "error": d["fa"] = {"error": "unsupported input"} if fb != "missing": if fb == "error": d["fb"] = {"error": "cannot parse"} elif fb == "not_equiv": d["fb"] = {"equiv": "sat", "vars_match": True} elif fb == "vars": d["fb"] = {"equiv": "unsat", "vars_match": False} else: d["fb"] = {"equiv": "unsat", "vars_match": True} for name, status, answer in (("sa", sa, first), ("sb", sb, second)): if status == "missing": continue if status == "ok": d[name] = {"status": "ok", "answer": answer} else: d[name] = {"status": status, "note": "no answer"} for node, table, present in (("ver", {"z3": verifier_z3}, has_verifier), ("adv", {"z3b": adversary_z3b, "exact": adversary_exact, "sampling": adversary_sampling}, has_adversary)): if not present: continue d[node] = {"checks": {sid: dict(table) for sid in ("sa", "sb") if isinstance(d.get(sid), dict) and d[sid].get("status") == "ok"}, "selected": "sa"} return d def maximal(**overrides: Any) -> Dict[str, Any]: """The strongest evidence this topology can produce, with named parts weakened or removed. A one part name drops a whole node; a field of a check table is changed in every entry of that table, which is how the same judgement reaches both solvers.""" d = dossier("ok", "ok", "ok", "ok", True, True, True, True, True, True) for path, value in overrides.items(): parts = path.split(".") if len(parts) == 1: if value is None: d.pop(path, None) else: d[path] = value elif len(parts) == 2 and parts[1] in CHECK_FIELDS: for entry in d[parts[0]]["checks"].values(): entry[parts[1]] = value else: d[parts[0]]["checks"][parts[1]][parts[2]] = value return d def reference(d: Dict[str, Any]) -> str: """README section 3 read on its own: assurance 3 needs the two readings proven equivalent and an exact (non Z3) confirmation agreeing with a Z3 confirmation of the same answer; everything that is still consistent but decided by Z3 alone is SINGLE_PROVER; a disagreement, a refuted answer, a missing confirmation or a checker that ran without deciding is UNKNOWN. A sampling match is not a confirmation of that kind: it can refute an answer, and on its own it leaves the answer unconfirmed.""" if d.get("crash"): return "UNKNOWN" fa = d.get("fa") if not isinstance(fa, dict) or "error" in fa: return "UNKNOWN" fb = d.get("fb") cross_checked = False if fb is not None: if not isinstance(fb, dict) or "error" in fb: return "UNKNOWN" if fb.get("equiv") != "unsat" or not fb.get("vars_match"): return "UNKNOWN" cross_checked = True ver, adv = d.get("ver"), d.get("adv") accepted = [] for sid in ("sa", "sb"): candidate = d.get(sid) if not isinstance(candidate, dict) or candidate.get("status") != "ok": continue judgements = {"z3": False, "z3b": False, "exact": False} refuted = False undecided = False for table, keys, confirms_here in ( (ver, ("z3",), lambda e: e.get("z3") is True), (adv, ("z3b", "exact", "sampling"), lambda e: e.get("z3b") is True or e.get("exact") is True)): if table is None: continue entry = table.get("checks", {}).get(sid) if isinstance(table, dict) else None if not isinstance(entry, dict): undecided = True elif any(entry.get(key) is False for key in keys): refuted = True elif not confirms_here(entry): undecided = True else: for key in keys: if key in judgements: judgements[key] = judgements[key] or entry.get(key) is True if refuted or undecided or not any(judgements.values()): continue accepted.append((sid, judgements)) if not accepted: return "UNKNOWN" base = d[accepted[0][0]]["answer"] for sid, _judgements in accepted[1:]: other = d[sid]["answer"] if not isinstance(other, dict) or base.get("type") != other.get("type"): return "UNKNOWN" key = {"value": "value", "verdict": "verdict"}.get(base["type"]) if key is not None and base.get(key) != other.get(key): return "UNKNOWN" if base["type"] == "set" and not answers.canonical_equal(base, other): return "UNKNOWN" _sid, judgements = accepted[0] if cross_checked and judgements["exact"] and (judgements["z3"] or judgements["z3b"]): return "VERIFIED" return "SINGLE_PROVER" def test_status_follows_the_documented_rule_over_the_evidence_space(): tally: Dict[str, int] = {} for key in EVIDENCE_SPACE: d = dossier(*key) got = agents.decide(copy.deepcopy(d)) want = reference(d) assert got["status"] == want, "%s: the rule says %s, README says %s" % ( key, got["status"], want) assert got["assurance"] == ASSURANCE[got["status"]] tally[got["status"]] = tally.get(got["status"], 0) + 1 assert set(tally) == set(ASSURANCE), tally assert tally["VERIFIED"] > 0 and tally["SINGLE_PROVER"] > 0 def test_a_confirmation_has_to_be_a_boolean(): """A field that is merely truthy is not evidence: only True and False are read as judgements. Each case removes the other source of the same judgement, so the field under test is the one that would otherwise be missing and the assurance would be the one at stake.""" cases = (("adv.exact", "yes please", {}), ("adv.exact", 1, {}), ("adv.z3b", 1, {"ver.z3": None}), ("ver.z3", "true", {"adv.z3b": None}), ("ver.z3", 0.5, {"adv.z3b": None}), ("ver.z3", [True], {"adv.exact": None})) for path, truthy, other_side in cases: overrides = dict(other_side) overrides[path] = truthy bought = agents.decide(maximal(**overrides)) assert bought["status"] != "VERIFIED", "%s as %r lifted the assurance to 3" % (path, truthy) hollow = agents.decide(maximal(**{"ver.z3": "yes", "adv.z3b": 1, "adv.exact": "sure", "adv.sampling": 2.0})) assert hollow["status"] == "UNKNOWN" assert "could not be confirmed" in " ".join(hollow["reasons"]) def test_a_sampling_match_corroborates_but_never_confirms(): """Sampling is the cheapest of the three adversary checks, so it is enough to refute and never enough to carry a verdict: without a proof or an exact re-derivation the answer stays unconfirmed.""" only = agents.decide(maximal(**{"ver.z3": None, "adv.z3b": None, "adv.exact": None})) assert only["status"] == "UNKNOWN", only["reasons"] assert "could not be confirmed" in " ".join(only["reasons"]) refuted = agents.decide(maximal(**{"adv.sampling": False})) assert sorted(refuted["detected"]) == ["sa", "sb"], refuted["detected"] assert refuted["status"] == "UNKNOWN" def test_a_checker_that_could_not_decide_blocks_rather_than_being_ignored(): """A checker that is in the dossier is not a bystander: an inconclusive judgement blocks the answer, while a checker that is not in the dossier at all simply leaves the evidence thinner.""" for overrides in ({"ver.z3": None, "adv": None}, {"ver": None, "adv.z3b": None, "adv.exact": None}, {"ver": {}, "adv": {"checks": {}}}): got = agents.decide(maximal(**overrides)) assert got["status"] == "UNKNOWN", (overrides, got["status"], got["reasons"]) assert "was not confirmed by" in " ".join(got["reasons"]), (overrides, got["reasons"]) off = agents.decide(maximal(**{"ver": None})) assert off["status"] == "VERIFIED", off["reasons"] both_off = agents.decide(maximal(**{"ver": None, "adv": None})) assert both_off["status"] == "UNKNOWN" and "could not be confirmed" in " ".join(both_off["reasons"]) def test_a_refuted_solver_is_not_used_even_when_the_other_one_is_clean(): d = maximal(**{"ver.sb.z3": False}) got = agents.decide(d) assert got["detected"] == ["sb"], got assert got["status"] == "VERIFIED", got["reasons"] lonely = agents.decide(maximal(**{"ver.sa.z3": False, "sb": None})) assert lonely["status"] == "UNKNOWN" assert "rejected by a checker" in " ".join(lonely["reasons"]) def test_two_confirmed_solvers_have_to_agree_on_the_answer(): for first, second, expected in ((VALUE, VALUE, "VERIFIED"), (VALUE, {"type": "value", "value": "1/3"}, "UNKNOWN"), (VALUE, SET_A, "UNKNOWN"), (VERDICT, VERDICT, "VERIFIED"), (VERDICT, {"type": "verdict", "verdict": "disproved", "counterexample": {"x": "0"}}, "UNKNOWN"), (SET_A, SET_A_SPLIT, "VERIFIED"), (SET_A, SET_B, "UNKNOWN")): got = agents.decide(maximal(**{"sa": {"status": "ok", "answer": first}, "sb": {"status": "ok", "answer": second}})) assert got["status"] == expected, (first, second, got["status"], got["reasons"]) if expected == "UNKNOWN": assert "verified solvers disagree" in got["reasons"], got["reasons"] def test_weakening_the_evidence_never_raises_the_assurance(): full = agents.decide(maximal()) assert full["status"] == "VERIFIED" and full["assurance"] == 3 single = [{"adv.exact": False}, {"adv.exact": None}, {"ver.z3": False}, {"fb": {"equiv": "sat", "vars_match": True}}, {"fb": {"equiv": "unsat", "vars_match": False}}, {"fb": None}, {"ver": None}, {"adv": None}, {"ver.z3": None}, {"adv.z3b": None}, {"sa": {"status": "inconclusive", "note": "no answer"}}, {"sb": None}] for overrides in single: got = agents.decide(maximal(**overrides)) assert ASSURANCE[got["status"]] <= 3, (overrides, got["status"]) chain = ({}, {"ver.z3": None}, {"ver.z3": None, "adv.z3b": None}, {"ver.z3": None, "adv.z3b": None, "adv.exact": None}, {"ver.z3": None, "adv.z3b": None, "adv.exact": None, "ver": None, "adv": None}) levels = [ASSURANCE[agents.decide(maximal(**step))["status"]] for step in chain] assert levels == sorted(levels, reverse=True), list(zip(chain, levels)) assert levels[0] == 3 and levels[-1] == 0 def test_a_dossier_that_is_missing_a_part_abstains_instead_of_raising(): empty = ({}, {"v": 1}, {"final": {"status": "VERIFIED", "assurance": 3}}) broken = ( {"fa": None}, {"fa": "not a node"}, {"fb": "not a node"}, {"crash": "solver_a fell over"}, {"ver": "not a node", "adv": None}, {"ver": None, "adv": {"checks": None}}, {"ver": None, "adv": {"checks": "not a table"}}, {"ver": None, "adv": {"checks": {"sa": "not a check"}}}, {"sa": "not a node", "sb": None, "ver": None, "adv": None}, ) for d in empty: got = agents.decide(copy.deepcopy(d)) assert got["status"] == "UNKNOWN" and got["assurance"] == 0, d assert got["reasons"], d for overrides in broken: got = agents.decide(copy.deepcopy(maximal(**overrides))) assert got["status"] == "UNKNOWN" and got["assurance"] == 0, (overrides, got["status"]) assert got["reasons"], overrides assert got["answer"] is None and got["answer_text"] == "" and got["solver"] is None def test_an_answer_that_cannot_be_read_or_rendered_abstains(): unreadable = ( {"sa": {"status": "ok", "answer": None}}, {"sa": {"status": "ok", "answer": "not an answer"}}, {"sa": {"status": "ok", "answer": {"type": "set", "var": "x", "product": [], "roots": [], "runs": [[0, False, 1, False]]}}}, {"sa": {"status": "ok", "answer": {"type": "set", "var": "x", "product": ["1", "1"], "roots": [{"lo": "0"}], "runs": [[0, False, None, False]]}}}, ) for overrides in unreadable: got = agents.decide(copy.deepcopy(maximal(**overrides))) assert got["status"] == "UNKNOWN" and got["answer"] is None, (overrides, got) def test_the_driver_survives_a_dossier_it_cannot_read(): for overrides in ({}, {"fa": None}, {"sa": "not a node"}, {"ver": {"checks": "not a table"}}, {"sa": {"status": "ok", "answer": "not an answer"}}, {"crash": "solver_a fell over"}): shown = pipeline.checked_verdict(maximal(**overrides), [], arbiter_expected=False) assert shown["status"] in ASSURANCE, (overrides, shown) assert shown["assurance"] == ASSURANCE[shown["status"]], (overrides, shown) sound = pipeline.checked_verdict(maximal(), [], arbiter_expected=False) assert sound["status"] == "VERIFIED" and sound["assurance"] == 3, sound headless = pipeline.checked_verdict(maximal(), [{"sender": "solver_a", "claimed": "ok", "referee": "rejected"}], arbiter_expected=False) assert headless["status"] == "UNKNOWN" and headless["assurance"] == 0, headless assert "referee disagrees with the claim of: solver_a" in " ".join(headless["reasons"]) missing = pipeline.checked_verdict(maximal(), []) assert missing["status"] == "UNKNOWN" and "the arbiter produced no verdict" in missing["reasons"] def test_a_claimed_verdict_is_only_kept_when_it_is_at_least_as_cautious(): bought = maximal(**{"fb": {"equiv": "sat", "vars_match": True}}) bought["final"] = {"status": "VERIFIED", "assurance": 3, "answer": VALUE, "answer_text": "1/2", "solver": "sa", "problem_math": "", "reasons": [], "detected": []} shown = pipeline.checked_verdict(bought, []) assert shown["status"] == "UNKNOWN" and shown["assurance"] == 0, shown assert "arbiter" in shown["detected"] assert "not provably equivalent" in " ".join(shown["reasons"]) assert "arbiter and recomputed decision disagree" in " ".join(shown["reasons"]) cautious = maximal() cautious["final"] = {"status": "UNKNOWN", "assurance": 0, "answer": None, "answer_text": "", "solver": None, "problem_math": "", "reasons": ["the arbiter abstained"], "detected": []} held = pipeline.checked_verdict(cautious, []) assert held["status"] == "UNKNOWN" and held["assurance"] == 0, held assert "the arbiter abstained" in held["reasons"] agreeing = maximal() agreeing["final"] = agents.decide(copy.deepcopy(agreeing)) kept = pipeline.checked_verdict(agreeing, []) assert kept["status"] == "VERIFIED" and kept["assurance"] == 3, kept assert "arbiter and recomputed decision disagree" not in " ".join(kept["reasons"]) def test_reading_the_dossier_never_changes_it(): samples = [maximal(), dossier("ok", "missing", "ok", "missing", True, True, True, True, True, None), dossier("error", "missing", "ok", "missing", False, None, False, None, None, None), maximal(**{"crash": {"solver_a": "RecursionError: maximum recursion depth"}}), maximal(**{"sa": {"status": "ok", "answer": SET_A}, "sb": {"status": "ok", "answer": SET_A_SPLIT}})] for d in samples: before = copy.deepcopy(d) agents.decide(d) assert d == before, "decide changed the dossier it was given"