"""term_at_open.py A finding's deadline is a property of the row, not of the report that prints it. Rules, in the order they can fail: R1 the term is fixed at open, by the window version in force on that day R2 a version never reaches backwards: rows opened before it keep their window R3 the only way to move an in-flight term is an extension event, never a field write R4 an extension must carry a closed reason, lengthen the term, and land before the deadline R5 every row lands in a printed bucket: counted + uncounted == rows read What this file cannot test: nothing here has seen a real finding table, a real extension register, or a provider. It proves the model of the rows, not the rows. Run: python3 term_at_open.py # tests + mutation table python3 term_at_open.py --tests-only """ from __future__ import annotations import subprocess import sys import tempfile import unittest from datetime import date, timedelta from typing import NamedTuple COUNTED = "counted" UNCOUNTED = "uncounted" # Closed enums. A reason outside these is refused, not stored as free text. EXT_REASONS = frozenset({"authority_order", "late_witness", "clock_defect"}) REFUSALS = frozenset( { "no_version_at_open", "extension_unknown_row", "extension_reason_unknown", "extension_not_a_stretch", "extension_after_expiry", } ) class Version(NamedTuple): version_id: str started_on: date window_days: int def _refuse(row_id, reason): assert reason in REFUSALS, reason return {"row_id": row_id, "bucket": UNCOUNTED, "reason": reason} def version_at_open(opened_on, versions): """R1/R2: the newest version that had started on or before the open date.""" candidates = [v for v in versions if v.started_on <= opened_on] if not candidates: return None return max(candidates, key=lambda v: (v.started_on, v.version_id)) def open_term(row_id, opened_on, witness_at, versions): """Pin the term once. The witness stamp is frozen here too, never looked up later.""" v = version_at_open(opened_on, versions) if v is None: return _refuse(row_id, "no_version_at_open") return { "row_id": row_id, "bucket": COUNTED, "version_id": v.version_id, "opened_on": opened_on, "witness_at": witness_at, "deadline": opened_on + timedelta(days=v.window_days), "extensions": [], } def apply_extension(term, ext): """R3/R4. Returns a refusal reason, or None after lengthening the term in place.""" if ext.get("reason") not in EXT_REASONS: return "extension_reason_unknown" if ext["granted_on"] > term["deadline"]: return "extension_after_expiry" if ext["new_deadline"] <= term["deadline"]: return "extension_not_a_stretch" term["extensions"].append( { "granted_on": ext["granted_on"], "reason": ext["reason"], "from": term["deadline"], "to": ext["new_deadline"], } ) term["deadline"] = ext["new_deadline"] return None def build_report(rows, versions, extensions): """One pass: pin every row, then apply only the extensions that pass R4. A refused extension is not a lost row: the term stands and the refusal is printed beside it. Unknown rows (a file that did not parse) are the caller's bucket to fill; that count cannot be produced from inside this function. """ terms = [] by_id = {} for r in rows: t = open_term(r["row_id"], r["opened_on"], r["witness_at"], versions) terms.append(t) if t["bucket"] == COUNTED: by_id[r["row_id"]] = t refusals = [] for e in extensions: t = by_id.get(e["row_id"]) if t is None: refusals.append({"row_id": e["row_id"], "reason": "extension_unknown_row"}) continue why = apply_extension(t, e) if why: refusals.append({"row_id": e["row_id"], "reason": why}) counts = {COUNTED: 0, UNCOUNTED: 0} for t in terms: counts[t["bucket"]] += 1 closed = len(terms) == len(rows) and counts[COUNTED] + counts[UNCOUNTED] == len(rows) return { "rows_read": len(rows), "terms": terms, "refusals": refusals, "counts": counts, "unknown": 0, "closed": closed, } # -------------------------------------------------------------------------- # Tests. Each case is chosen for the failure class it visits, not for its # position in the code: a case list reports only the first death per mutant. # -------------------------------------------------------------------------- V1 = Version("v1", date(2026, 1, 1), 7) V2 = Version("v2", date(2026, 3, 1), 30) V3 = Version("v3", date(2026, 6, 1), 3) def row(rid, opened, witness=None): return {"row_id": rid, "opened_on": opened, "witness_at": witness or opened} class TermTests(unittest.TestCase): def test_forward_only_new_version_does_not_reach_back(self): # Opened under v1 (7 days), reported after v2 exists (30 days). rep = build_report([row("r1", date(2026, 2, 1))], [V1, V2], []) t = rep["terms"][0] self.assertEqual(t["version_id"], "v1") self.assertEqual(t["deadline"], date(2026, 2, 8)) def test_version_boundary_inclusive(self): # A row opened on the day v2 starts is a v2 row, not a v1 row. rep = build_report([row("r1", date(2026, 3, 1))], [V1, V2], []) self.assertEqual(rep["terms"][0]["version_id"], "v2") self.assertEqual(rep["terms"][0]["deadline"], date(2026, 3, 31)) def test_no_version_at_open_is_uncounted_with_reason(self): rep = build_report([row("r1", date(2025, 12, 1))], [V1, V2], []) t = rep["terms"][0] self.assertEqual(t["bucket"], UNCOUNTED) self.assertEqual(t["reason"], "no_version_at_open") self.assertNotIn("deadline", t) def test_extension_lengthens_term_and_is_recorded(self): rows = [row("r1", date(2026, 2, 1))] ext = [ { "row_id": "r1", "granted_on": date(2026, 2, 5), "new_deadline": date(2026, 3, 15), "reason": "late_witness", } ] rep = build_report(rows, [V1, V2], ext) t = rep["terms"][0] self.assertEqual(t["deadline"], date(2026, 3, 15)) self.assertEqual(len(t["extensions"]), 1) self.assertEqual(t["extensions"][0]["from"], date(2026, 2, 8)) self.assertEqual(rep["refusals"], []) def test_extension_after_expiry_refused(self): # A stay granted after the deadline is a new finding, not a stay. rows = [row("r1", date(2026, 2, 1))] ext = [ { "row_id": "r1", "granted_on": date(2026, 2, 9), "new_deadline": date(2026, 4, 1), "reason": "authority_order", } ] rep = build_report(rows, [V1, V2], ext) self.assertEqual(rep["terms"][0]["deadline"], date(2026, 2, 8)) self.assertEqual(rep["refusals"][0]["reason"], "extension_after_expiry") def test_extension_shortening_refused(self): rows = [row("r1", date(2026, 2, 1))] ext = [ { "row_id": "r1", "granted_on": date(2026, 2, 3), "new_deadline": date(2026, 2, 4), "reason": "authority_order", } ] rep = build_report(rows, [V1, V2], ext) self.assertEqual(rep["terms"][0]["deadline"], date(2026, 2, 8)) self.assertEqual(rep["refusals"][0]["reason"], "extension_not_a_stretch") def test_extension_reason_closed(self): # Same row shape, different failure class: the reason, not the dates. rows = [row("r1", date(2026, 2, 1))] ext = [ { "row_id": "r1", "granted_on": date(2026, 2, 3), "new_deadline": date(2026, 3, 20), "reason": "client_asked_nicely", } ] rep = build_report(rows, [V1, V2], ext) self.assertEqual(rep["terms"][0]["deadline"], date(2026, 2, 8)) self.assertEqual(rep["refusals"][0]["reason"], "extension_reason_unknown") def test_extension_for_unknown_row_refused(self): rep = build_report([row("r1", date(2026, 2, 1))], [V1, V2], [{"row_id": "ghost", "granted_on": date(2026, 2, 3), "new_deadline": date(2026, 3, 1), "reason": "clock_defect"}]) self.assertEqual(rep["refusals"][0]["reason"], "extension_unknown_row") self.assertEqual(len(rep["terms"]), 1) def test_count_closure_on_mixed_rows(self): rows = [row("r1", date(2026, 2, 1)), row("r2", date(2025, 12, 1)), row("r3", date(2026, 6, 2))] # granted on the deadline day itself: a stay landing on the last day counts ext = [{"row_id": "r1", "granted_on": date(2026, 2, 8), "new_deadline": date(2026, 4, 1), "reason": "authority_order"}] rep = build_report(rows, [V1, V2], ext) c = rep["counts"] self.assertTrue(rep["closed"]) self.assertEqual(c[COUNTED] + c[UNCOUNTED], rep["rows_read"]) self.assertEqual(c[UNCOUNTED], 1) self.assertEqual(c[COUNTED], 2) # r1's extension lands exactly on its deadline: it is still a stay. self.assertEqual(rep["terms"][0]["deadline"], date(2026, 4, 1)) def test_report_rerun_does_not_move_terms(self): # both rows opened before V3 starts, so a later version may not touch them rows = [row("r1", date(2026, 2, 1)), row("r3", date(2026, 4, 1))] first = build_report(rows, [V1, V2], []) later = build_report(rows, [V1, V2, V3], []) self.assertEqual([t["deadline"] for t in first["terms"]], [t["deadline"] for t in later["terms"]]) self.assertEqual([t["version_id"] for t in first["terms"]], [t["version_id"] for t in later["terms"]]) def run_tests(): suite = unittest.TestLoader().loadTestsFromTestCase(TermTests) return unittest.TextTestRunner(verbosity=2).run(suite) # ==== MUTATION TABLE (not part of the code under test) ==== # One entry per line: name, old, new, kind. "real" = must die. "noop" = must # survive and be reported as escaped-inert, never as killed. MUTANTS = [ ("forward-only filter dropped", "if v.started_on <= opened_on]", "]", "real"), ("boundary made exclusive", "v.started_on <= opened_on", "v.started_on < opened_on", "real"), ("reason enum opened", 'if ext.get("reason") not in EXT_REASONS:', "if False:", "real"), ("stretch test dropped", 'if ext["new_deadline"] <= term["deadline"]:', "if False:", "real"), ("uncounted degraded to counted", '"bucket": UNCOUNTED', '"bucket": COUNTED', "real"), ("docstring reworded (control)", "A finding's deadline is a property of the row", "A finding's deadline belongs to the row", "noop"), ] def _run_source(src): with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False, encoding="utf-8") as f: f.write(src) path = f.name p = subprocess.run([sys.executable, path, "--tests-only"], capture_output=True, text=True) killed = [] for line in (p.stdout + p.stderr).splitlines(): if line.startswith("FAIL: ") or line.startswith("ERROR: "): killed.append(line.split("(")[0].split(": ")[1].strip()) return p.returncode, sorted(set(killed)) def mutation_run(): src = open(__file__, encoding="utf-8").read() code, sep, tail = src.partition(sep_line()) if not sep: print("proves nothing: marker missing") return 2 rc, _ = _run_source(src) if rc != 0: print("proves nothing: baseline is not green") return 2 print("baseline: green\n") rows = [] bad = False for name, old, new, kind in MUTANTS: n = code.count(old) if n != 1: print("proves nothing: %-32s matched %d times in the code side" % (name, n)) bad = True continue mutated = code.replace(old, new, 1) + sep + tail rc, killed = _run_source(mutated) if rc == 0: status = "escaped-inert (control)" if kind == "noop" else "ESCAPED-LIVE" if kind != "noop": bad = True else: status = "killed by " + ", ".join(killed) if killed else "killed (no test named)" rows.append((name, status)) print("%-34s %s" % ("MUTANT", "RESULT")) for name, status in rows: print("%-34s %s" % (name, status)) print("\nverdict:", "proves nothing" if bad else "all real mutants killed, control inert") return 2 if bad else 0 def sep_line(): return "# " + "====" + " MUTATION TABLE (not part of the code under test) " + "====" if __name__ == "__main__": if "--tests-only" in sys.argv: res = run_tests() sys.exit(0 if res.wasSuccessful() else 1) sys.exit(mutation_run())