"""ack_bucket.py A refusal needs somewhere to land. v8's ack side raises on a digest it cannot read. A raise prints no number, and no number is not a refusal with a reason: the input disappears and the run still looks like it certified something. This module gives the refused row its own printed bucket and a closed reason enum, so the total stays whole: counted + uncounted + unknown == rows read. Two properties are the point: 1. The mutant that matters ("degrade to counted") is caught by the count, not by the absence of an exception. 2. Adding a reason is a visible diff in REASONS, not a new silent path. Usage: python3 ack_bucket.py --selftest python3 ack_bucket.py --mutate degrade # must exit non-zero python3 ack_bucket.py --mutate skip # must exit non-zero """ import re import sys # closed enum. a reason not listed here cannot be produced. REASONS = ("pre_format", "version", "corrupted", "empty") # the one pre-check that is allowed before the count: the input's shape. # it decides nothing about a single row and can only tighten. def check_header(fieldnames): if "digest" not in (fieldnames or ()): raise SystemExit("refused: input has no digest column (header=%r)" % (fieldnames,)) return True def classify(digest): """One row in, exactly one bucket out. Never raises on data.""" if not isinstance(digest, str): return ("unknown", "not_a_string") if digest == "": return ("uncounted", "empty") if ":" not in digest: return ("uncounted", "pre_format") version, _, hexpart = digest.partition(":") if version != "v2": return ("uncounted", "version") if len(hexpart) != 64 or not re.fullmatch(r"[0-9a-f]{64}", hexpart): return ("uncounted", "corrupted") return ("counted", None) def build(rows): """Rows are dicts with a 'digest' key. Returns a report dict.""" out = {"counted": 0, "uncounted": {r: 0 for r in REASONS}, "unknown": []} for row in rows: bucket, reason = classify(row.get("digest")) if bucket == "counted": out["counted"] += 1 elif bucket == "uncounted": if reason not in out["uncounted"]: # an unlisted reason is a programmer error, not a data case. raise SystemExit("refused: reason %r is not in the enum" % (reason,)) out["uncounted"][reason] += 1 else: out["unknown"].append(reason) out["rows"] = len(rows) return out def print_report(rep): lines = ["acks read %d" % rep["rows"], "counted %d" % rep["counted"], "uncounted %d" % sum(rep["uncounted"].values())] for r in REASONS: lines.append(" %-11s %d" % (r, rep["uncounted"][r])) lines.append("unknown %d" % len(rep["unknown"])) total = rep["counted"] + sum(rep["uncounted"].values()) + len(rep["unknown"]) lines.append("total %d" % total) for u in rep["unknown"]: lines.append(" unknown: " + u) if rep["unknown"]: lines.append("count stops: unknown rows are not a reason") return "\n".join(lines) def exits_clean(rep): return len(rep["unknown"]) == 0 and \ rep["counted"] + sum(rep["uncounted"].values()) == rep["rows"] # ---------------------------------------------------------------- tests GOOD = "v2:" + "a" * 64 def test_all_valid(): rep = build([{"digest": GOOD}] * 3) assert rep["counted"] == 3, rep assert exits_clean(rep) def test_one_row_missing_reason_still_prints_a_total(): # the test the guard needed: one bad row among n. Assert the numbers, # not the raise. This kills both "skipped the row" and "degraded to # counted" in one line. rows = [{"digest": GOOD}, {"digest": GOOD}, {"digest": "v3:" + "a" * 64}] rep = build(rows) text = print_report(rep) assert "counted 2" in text, text assert "uncounted 1" in text, text assert "version 1" in text, text assert "total 3" in text, text assert exits_clean(rep) def test_every_reason_has_a_witness(): cases = { "pre_format": "abc", "version": "v1:" + "a" * 64, "corrupted": "v2:" + "A" * 64, "empty": "", } for reason, digest in cases.items(): rep = build([{"digest": digest}]) assert rep["uncounted"][reason] == 1, (reason, rep) assert exits_clean(rep), (reason, rep) def test_header_refusal_is_a_pre_check_and_cannot_tighten_a_row(): try: check_header(["amount", "settled_at"]) except SystemExit as e: assert "no digest column" in str(e), e else: raise AssertionError("header check returned instead of refusing") assert check_header(["digest"]) is True def test_unknown_stops_the_count(): rep = build([{"digest": GOOD}, {"digest": None}]) assert rep["unknown"] == ["not_a_string"], rep assert not exits_clean(rep) def test_unlisted_reason_is_refused(): orig = classify try: globals()["classify"] = lambda d: ("uncounted", "brand_new_path") build([{"digest": GOOD}]) except SystemExit as e: assert "not in the enum" in str(e), e else: raise AssertionError("unlisted reason was accepted") finally: globals()["classify"] = orig # ------------------------------------------------------------- mutants def mut_degrade(rows): """a corrupt digest counted as if it were usable.""" out, unc = 0, 0 for row in rows: d = row.get("digest") if isinstance(d, str) and ":" in d and d.split(":", 1)[0] == "v2": out += 1 elif classify(d)[0] == "uncounted": unc += 1 return {"rows": len(rows), "counted": out, "uncounted": {r: 0 for r in REASONS} | {"corrupted": 0}, "unknown": []} def mut_skip(rows): """the old behaviour: a row that raises is dropped from the run.""" rep = {"rows": len(rows), "counted": 0, "uncounted": {r: 0 for r in REASONS}, "unknown": []} for row in rows: d = row.get("digest") try: bucket, reason = classify(d) except ValueError: continue if isinstance(d, str) and ":" in d and d.split(":", 1)[0] == "v2" and \ re.fullmatch(r"[0-9a-f]{64}", d.split(":", 1)[1]): rep["counted"] += 1 return rep MUTANTS = {"degrade": mut_degrade, "skip": mut_skip} def selftest(): tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")] for t in tests: t() print("ok " + t.__name__) rows = [{"digest": GOOD}, {"digest": GOOD}, {"digest": "v2:" + "A" * 64}] print("") print(print_report(build(rows))) print("") print("%d tests, all green" % len(tests)) def _asserted(text): """the count the suite requires, as a tuple worth comparing.""" return ("counted 2" in text and "uncounted 1" in text and "corrupted 1" in text and "total 3" in text) def run_mutant(name): rows = [{"digest": GOOD}, {"digest": GOOD}, {"digest": "v2:" + "A" * 64}] base = print_report(build(rows)) text = print_report(MUTANTS[name](rows)) print(text) if text == base: # the control: a change nobody made is not a kill. print("") print("mutant %s: did not apply, so it proves nothing" % name) return 2 if _asserted(text): print("") print("mutant %s: escaped-live (count did not catch it)" % name) return 1 # name the line that differs; the kill is a count, not a stack trace. diff = [l for l in text.splitlines() if l not in base.splitlines() and l.strip()] print("") print("mutant %s: killed by the count" % name) for d in diff: print(" witness: " + d) return 0 if __name__ == "__main__": if "--selftest" in sys.argv: selftest() sys.exit(0) if "--mutate" in sys.argv: sys.exit(run_mutant(sys.argv[sys.argv.index("--mutate") + 1])) print(__doc__)