""" Settlement record + render, and a mutation harness that actually runs the tests. Four-field settlement (call_id, reference_rev, settled_at, value), verdict derived at read time by render() over the (commit, settlement) pair. Expiry carries an owner; the owner bounds the comparison only if that owner can invalidate the basis. The harness below is the point of this file: every mutant is a variant implementation executed against the same test list. A mutant is caught when at least one test fails, not when the mutant's own function says so. A no-op mutation must survive; if it is reported caught, the harness is broken. Run: python3 settlement.py (exit 0 iff every invariant holds) """ import functools import inspect from dataclasses import dataclass, fields from decimal import Decimal from datetime import datetime, timedelta SETTLEMENT_FIELDS = {"call_id", "reference_rev", "settled_at", "value"} # -------------------------------------------------------------------------- # the implementation under test # -------------------------------------------------------------------------- SOURCE = r''' from dataclasses import dataclass, fields from decimal import Decimal from datetime import datetime, timedelta SETTLEMENT_FIELDS = {"call_id", "reference_rev", "settled_at", "value"} def dt(s): return datetime.fromisoformat(s.replace("Z", "+00:00")) @dataclass(frozen=True) class Expiry: at: datetime owner: str @dataclass(frozen=True) class Commit: call_id: str reference_rev: int observed_at: datetime value: Decimal expiry: Expiry = None @dataclass(frozen=True) class Settlement: call_id: str reference_rev: int settled_at: datetime value: Decimal @dataclass(frozen=True) class Ack: digest: str holder: str def render(commit, settlement, now, invalidators): """now and invalidators are required: the function under test does not supply the clock, and does not default the parties that can invalidate the basis.""" if settlement is None or settlement.call_id != commit.call_id: age = int((now - commit.observed_at).total_seconds() // 60) return "NO_SETTLEMENT basis=%d age=%dm" % (commit.reference_rev, age) if settlement.reference_rev != commit.reference_rev: return ("NOT_COMPARABLE reason=reference_mismatch %d:%d" % (commit.reference_rev, settlement.reference_rev)) if commit.expiry is not None and settlement.settled_at > commit.expiry.at: if commit.expiry.owner in invalidators: return ("NOT_COMPARABLE reason=expired owner=%s at=%s" % (commit.expiry.owner, commit.expiry.at.isoformat())) return ("NOT_COMPARABLE reason=expiry_owner_cannot_invalidate owner=%s" % commit.expiry.owner) delta = settlement.value - commit.value if delta == 0: return "PASS basis=%d delta=0.00 settled_in_window" % commit.reference_rev return "FAIL basis=%d delta=%s" % (commit.reference_rev, delta) def provenance(digest, ack, attempts): if ack is not None and ack.digest == digest and ack.holder != "operator": return "witnessed" if attempts: return "issued" return "self_attested" ''' def load(source): ns = {} exec(compile(source, "", "exec"), ns) return ns # -------------------------------------------------------------------------- # fixtures and tests, written against a namespace so they can run on any variant # -------------------------------------------------------------------------- def fixtures(ns): C = ns["Commit"]("c1", 8812, ns["dt"]("2026-11-12T06:00:00Z"), ns["Decimal"]("100.00"), ns["Expiry"](ns["dt"]("2026-11-12T06:15:00Z"), "issuer")) S = ns["Settlement"] return dict( C=C, C_NOEXP=ns["Commit"]("c1", 8812, ns["dt"]("2026-11-12T06:00:00Z"), ns["Decimal"]("100.00"), None), S_OK=S("c1", 8812, ns["dt"]("2026-11-12T06:04:12Z"), ns["Decimal"]("100.00")), S_LOW=S("c1", 8812, ns["dt"]("2026-11-12T06:04:12Z"), ns["Decimal"]("97.00")), S_HIGH=S("c1", 8812, ns["dt"]("2026-11-12T06:04:12Z"), ns["Decimal"]("103.00")), S_EDGE=S("c1", 8812, ns["dt"]("2026-11-12T06:04:12Z"), ns["Decimal"]("100.001")), S_STALE=S("c1", 8900, ns["dt"]("2026-11-12T06:04:12Z"), ns["Decimal"]("100.00")), S_LATE=S("c1", 8812, ns["dt"]("2026-11-12T07:41:03Z"), ns["Decimal"]("100.00")), t=ns["dt"], D=ns["Decimal"], ) def test_equal(ns): f = fixtures(ns) assert ns["render"](f["C"], f["S_OK"], f["t"]("2026-11-12T06:10:00Z"), {"issuer"}) == "PASS basis=8812 delta=0.00 settled_in_window" def test_unequal(ns): f = fixtures(ns) assert ns["render"](f["C"], f["S_LOW"], f["t"]("2026-11-12T06:10:00Z"), {"issuer"}) == "FAIL basis=8812 delta=-3.00" def test_overpayment(ns): # the other side of the comparison: the -3.00 row above kills nothing at # `delta >= 0`, because a threshold that lets a shortfall pass is still a # threshold that fails this one. One overpayment row kills it. f = fixtures(ns) assert ns["render"](f["C"], f["S_HIGH"], f["t"]("2026-11-12T06:10:00Z"), {"issuer"}) == "FAIL basis=8812 delta=3.00" def test_extra_decimal(ns): # widest edge: an amount that differs only below the second decimal, of the # kind a ledger that rounds before comparing would call equal. Exact # equality must fail it. f = fixtures(ns) assert ns["render"](f["C"], f["S_EDGE"], f["t"]("2026-11-12T06:10:00Z"), {"issuer"}) == "FAIL basis=8812 delta=0.001" def test_no_settlement_3a(ns): # case 3a: read at 06:20 against a commit observed at 06:00 is 20 minutes f = fixtures(ns) assert ns["render"](f["C"], None, f["t"]("2026-11-12T06:20:00Z"), {"issuer"}) == "NO_SETTLEMENT basis=8812 age=20m" def test_no_settlement_clock_is_the_callers(ns): f = fixtures(ns) a = ns["render"](f["C"], None, f["t"]("2026-11-12T06:20:00Z"), {"issuer"}) b = ns["render"](f["C"], None, f["t"]("2026-11-12T06:35:00Z"), {"issuer"}) assert a.endswith("age=20m") and b.endswith("age=35m") def test_reference_mismatch(ns): f = fixtures(ns) assert ns["render"](f["C"], f["S_STALE"], f["t"]("2026-11-12T06:10:00Z"), {"issuer"}).startswith("NOT_COMPARABLE reason=reference_mismatch 8812:8900") def test_expired_issuer_bounds_merchant_basis(ns): # the issuer's authorisation clock governs a merchant comparison because the # issuer can invalidate the basis, even though the issuer is not the counterparty f = fixtures(ns) assert ns["render"](f["C"], f["S_LATE"], f["t"]("2026-11-12T08:00:00Z"), {"issuer", "rail"}).startswith("NOT_COMPARABLE reason=expired owner=issuer") def test_expiry_owner_who_cannot_invalidate(ns): f = fixtures(ns) assert ns["render"](f["C"], f["S_LATE"], f["t"]("2026-11-12T08:00:00Z"), {"rail"}).startswith("NOT_COMPARABLE reason=expiry_owner_cannot_invalidate") def test_no_expiry_means_no_window(ns): # the expiry branch is `if commit.expiry is not None and ...`. Every fixture # above carries a window, so without this one the whole branch is never # given a None and a mutant that inverts the test would still be green. f = fixtures(ns) assert ns["render"](f["C_NOEXP"], f["S_LATE"], f["t"]("2026-11-12T08:00:00Z"), {"issuer"}) == "PASS basis=8812 delta=0.00 settled_in_window" def test_settlement_is_four_fields(ns): assert {x.name for x in ns["fields"](ns["Settlement"])} == ns["SETTLEMENT_FIELDS"] def test_commit_has_no_label(ns): assert "provenance" not in {x.name for x in ns["fields"](ns["Commit"])} def test_settlement_has_no_verdict(ns): names = {x.name for x in ns["fields"](ns["Settlement"])} assert not names & {"verdict", "status", "delta"} def test_render_takes_no_defaults(ns): # a default clock or a default invalidator set is a record that supplies its # own basis; no call that always passes them can fail on it sig = inspect.signature(ns["render"]) for name in ("now", "invalidators"): assert sig.parameters[name].default is inspect.Parameter.empty def test_render_refuses_a_missing_clock(ns): # a fallback clock is invisible to every test that always supplies one, so the # suite needs the test where the argument is absent and refusal is the answer f = fixtures(ns) try: ns["render"](f["C"], None, None, {"issuer"}) except (TypeError, ValueError): return raise AssertionError("render invented a clock instead of refusing") def test_provenance_degrades(ns): P, Ack = ns["provenance"], ns["Ack"] assert P("d1", None, 0) == "self_attested" assert P("d1", None, 3) == "issued" assert P("d1", Ack("d1", "operator"), 1) == "issued" # holder is the writer assert P("d1", Ack("d1", "client-a"), 1) == "witnessed" assert P("d1", Ack("d2", "client-a"), 1) == "issued" # digest mismatch def test_expiry_with_no_invalidator_set(ns): # an empty invalidator set is what a caller holds when it knows of no party # that can invalidate the basis. This is the value the census never visited: # invalidators is supplied in 9/9 call sites with 3 distinct non-empty sets, # so `invalidators = invalidators or {"issuer"}` stays invisible to every # assertion above and to all eight mutants. This test kills it. f = fixtures(ns) assert ns["render"](f["C"], f["S_LATE"], f["t"]("2026-11-12T08:00:00Z"), set()).startswith("NOT_COMPARABLE reason=expiry_owner_cannot_invalidate") # The census rule is "a required parameter must be bound to a falsy value at # least once". One parameter cannot satisfy it and the exemption is a claim # that has to be earned, not asserted: `commit` is a record, never falsy, so its # domain is its fields. The test below fails if the exempt set grows or if the # field domain it points at is not actually exercised. CENSUS_EXEMPT = {"commit": "record, never falsy; domain is its fields (expiry=None in test_no_expiry_means_no_window)"} def test_census_no_required_parameter_is_only_ever_supplied_whole(ns): # THE SHAPE TEST. A row states a value at a call site; this states which # values the call set never visits. It wraps render, replays every other # test in this module through the wrapper, and records for each required # parameter whether any call in the suite ever bound it to a falsy value # (an empty invalidator set, no clock) or omitted it so that it must raise. # # A parameter that appears in 100% of calls holding only truthy values is # untested and reported as covered. That is not a corner case: the empty # set is what a caller holds before anything has been classified. # # This test's own trigger is the rule: the property cannot be written as a # row. Removing the falsy-value test for any parameter makes this one fail # and name the parameter. real = ns["render"] sig = inspect.signature(real) params = [n for n, p in sig.parameters.items() if p.default is inspect.Parameter.empty] falsy = {n: False for n in params} @functools.wraps(real) def spy(*args, **kwargs): bound = dict(zip(params, args)) bound.update({k: v for k, v in kwargs.items() if k in params}) for n, v in bound.items(): if not v: falsy[n] = True return real(*args, **kwargs) for t in TESTS: if t is test_census_no_required_parameter_is_only_ever_supplied_whole: continue shadow = dict(ns) shadow["render"] = spy try: t(shadow) except Exception: pass # behaviour is other tests' business; presence is this one's unvisited = [n for n in params if not falsy[n] and n not in CENSUS_EXEMPT] assert not unvisited, ( "required parameter(s) supplied in every call with a truthy value, so no " "test in this suite can fail on them: %s" % ", ".join(unvisited)) # exemptions must be earned: a fixed set, and the field domain it names # must actually be visited assert set(CENSUS_EXEMPT) <= set(params), "exemption names a parameter that does not exist" assert set(CENSUS_EXEMPT) == {"commit"}, ( "the exempt set changed; a new exemption is a new untested domain") assert fixtures(ns)["C_NOEXP"].expiry is None, ( "exempted parameter's domain hole is not visited by any fixture") TESTS = [ test_equal, test_unequal, test_overpayment, test_extra_decimal, test_no_settlement_3a, test_no_settlement_clock_is_the_callers, test_reference_mismatch, test_expired_issuer_bounds_merchant_basis, test_expiry_owner_who_cannot_invalidate, test_expiry_with_no_invalidator_set, test_no_expiry_means_no_window, test_settlement_is_four_fields, test_commit_has_no_label, test_settlement_has_no_verdict, test_render_takes_no_defaults, test_render_refuses_a_missing_clock, test_provenance_degrades, test_census_no_required_parameter_is_only_ever_supplied_whole, ] # -------------------------------------------------------------------------- # mutations: source substitutions, each applied to the module text # -------------------------------------------------------------------------- MUTATIONS = [ ("delta: threshold instead of equality", ' if delta == 0:', ' if delta >= 0:'), ("delta: tolerance band 0.005", ' if delta == 0:', ' if abs(delta) < Decimal("0.005"):'), ("delta: tolerance band 0.05", ' if delta == 0:', ' if abs(delta) < Decimal("0.05"):'), ("rev rewritten to match at settlement", 'if settlement.reference_rev != commit.reference_rev:', 'if False:'), ("one window for every party", 'if commit.expiry is not None and settlement.settled_at > commit.expiry.at:', 'if commit.expiry is not None and settlement.settled_at > commit.expiry.at + timedelta(minutes=120):'), ("stored delta", ' value: Decimal\n\n\n@dataclass(frozen=True)\nclass Ack:', ' value: Decimal\n delta: Decimal = Decimal("0.00")\n\n\n@dataclass(frozen=True)\nclass Ack:'), ("provenance label written by the writer", ' expiry: Expiry = None', ' expiry: Expiry = None\n provenance: str = "witnessed"'), ("render supplies its own clock", ' if settlement is None or settlement.call_id != commit.call_id:\n age', ' now = now or commit.observed_at + timedelta(minutes=30)\n if settlement is None or settlement.call_id != commit.call_id:\n age'), ("expiry owner ignored, counterparty rule back", 'if commit.expiry.owner in invalidators:', 'if True:'), ("holder check dropped", 'and ack.holder != "operator"', ''), ("invalidator set filled when empty", ' if settlement.reference_rev != commit.reference_rev:', ' invalidators = invalidators or {"issuer"}\n\n if settlement.reference_rev != commit.reference_rev:'), ("required parameter gets a default", 'def render(commit, settlement, now, invalidators):', 'def render(commit, settlement, now, invalidators={"issuer"}):'), ("expiry branch inverted", 'if commit.expiry is not None and settlement.settled_at > commit.expiry.at:', 'if commit.expiry is None or settlement.settled_at > commit.expiry.at:'), ("verdict field stored on the settlement", ' settled_at: datetime\n value: Decimal\n\n\n@dataclass(frozen=True)\nclass Ack:', ' settled_at: datetime\n value: Decimal\n verdict: str = "PASS"\n\n\n@dataclass(frozen=True)\nclass Ack:'), ] def run_suite(ns): failures = [] for t in TESTS: try: t(ns) except AssertionError as e: failures.append((t.__name__, str(e))) except Exception as e: failures.append((t.__name__, "error: %r" % (e,))) return failures def main(): base = load(SOURCE) base_fail = run_suite(base) print("baseline: %d/%d pass" % (len(TESTS) - len(base_fail), len(TESTS))) for n, m in base_fail: print(" baseline failure %s: %s" % (n, m)) escaped, caught = [], [] for name, old, new in MUTATIONS: if old not in SOURCE: raise SystemExit("mutation did not apply, so it proves nothing: %s" % name) src = SOURCE.replace(old, new, 1) fails = run_suite(load(src)) if fails: caught.append((name, [f[0] for f in fails])) else: escaped.append(name) # the no-op mutation must escape. a harness that reports this caught is # measuring itself, not the tests. noop_src = "# a mutation that changes no behaviour\n" + SOURCE noop_caught = bool(run_suite(load(noop_src))) print("mutants caught: %d/%d" % (len(caught), len(MUTATIONS))) for name, ts in caught: print(" caught %-45s by %s" % (name, ", ".join(ts[:3]))) print("escaped: %s" % (escaped or "none")) print("no-op mutation escaped (harness is not self-agreeing): %s" % (not noop_caught)) # the shape test has to be able to fail on a change that no value test sees: # drop the empty-invalidator-set test from the suite (a suite edit, not a # source edit) and require the census to name the parameter it lost. whole = list(TESTS) TESTS[:] = [t for t in whole if t.__name__ != "test_expiry_with_no_invalidator_set"] try: lost = run_suite(load(SOURCE)) finally: TESTS[:] = whole named = [m for n, m in lost if n.startswith("test_census")] print("suite edit (empty set test removed) -> census:", named[0] if named else "SILENT (shape test is decoration)") ok = not base_fail and not escaped and not noop_caught and bool(named) print("RESULT:", "OK" if ok else "BROKEN") return 0 if ok else 1 if __name__ == "__main__": raise SystemExit(main())