"""Independent arithmetic and negative controls for the Table III audit.""" import copy from decimal import Decimal as D from fractions import Fraction as F import json from pathlib import Path import tempfile import unittest import compression as c class AuditTests(unittest.TestCase): def setUp(self): self.data = c.load(c.ROOT / "table3.json") self.report = c.calculate(self.data) def test_all_six_rows_and_exactly_one_disagreement(self): self.assertEqual(len(self.report["cases"]), 6) self.assertEqual(len(self.report["comparisons"]), 4) bad = [r for r in self.report["cases"] if not r["roundingCompatible"]] self.assertEqual([(r["dataset"], r["method"]) for r in bad], [("VM", "PC")]) self.assertEqual(bad[0]["componentSumGB"], "26.743") self.assertEqual(bad[0]["printedTotalGB"], "26.730") self.assertEqual(bad[0]["componentSumMinusPrintedGB"], "0.013") self.assertEqual(bad[0]["roundingResidualBoundGB"], "0.0030") def test_independent_integer_component_sums(self): expected = [10767, 10679, 9949, 26981, 26682, 26743] actual = [int(D(r["componentSumGB"]) * 1000) for r in self.report["cases"]] self.assertEqual(actual, expected) self.assertEqual(39 + 309 + 1244 + 25138, 26730) self.assertEqual(39 + 309 + 1244 + 25138 + 13, 26743) def test_independent_fraction_ratios_and_percentage_points(self): inputs = [(10767, 10679, "0.02"), (10767, 9949, "0.22"), (26981, 26682, "0.05"), (26981, 26743, "0.04")] for row, (before, after, points) in zip(self.report["comparisons"], inputs): exact = F(100 * (before - after), before) self.assertLess(abs(F(row["remainingReductionPercent"]) - exact), F(1, 1000000)) self.assertEqual(row["differenceOfPrintedSavingRatesPercentagePoints"], points) self.assertNotEqual(self.report["comparisons"][-1]["remainingReductionPercent"], self.report["comparisons"][-1]["remainingReductionFromPrintedTotalsPercent"]) def test_rounding_bounds_cover_extreme_ratios(self): for row in self.report["comparisons"]: low, high = map(D, row["remainingReductionRoundingEnvelopePercent"]) baseline = D(row["componentSumBeforeGB"]) after = D(row["componentSumAfterGB"]) after_error = D("0.0025") if row["method"] == "PC" else D("0.002") for b in [baseline - D("0.002"), baseline + D("0.002")]: for a in [after - after_error, after + after_error]: value = 100 * (b - a) / b self.assertGreaterEqual(value, low - D("0.000001")) self.assertLessEqual(value, high + D("0.000001")) self.assertLess(low, high) def test_inconsistent_source_total_remains_detectable(self): data = copy.deepcopy(self.data) data["datasets"][0]["rows"][2][6] = "8.949" result = c.calculate(data) bad = [r for r in result["cases"] if not r["roundingCompatible"]] self.assertEqual(len(bad), 2) self.assertEqual(bad[0]["componentSumMinusPrintedGB"], "1.000") def test_mapping_is_not_silently_removed(self): data = copy.deepcopy(self.data) data["datasets"][1]["rows"][2][5] = None with self.assertRaisesRegex(ValueError, "Mapping"): c.calculate(data) self.assertIsNone(self.data["datasets"][0]["rows"][0][5]) self.assertEqual(self.report["cases"][0]["componentCount"], 4) self.assertEqual(self.report["cases"][2]["componentCount"], 5) def test_invalid_decimal_representations(self): for value in ["NaN", "Infinity", "1e3", "-0.001", "1.00", "1.0000", " 1.000", 1.0, True, None, "١.000"]: with self.subTest(value=value), self.assertRaises(ValueError): c.decimal(value) def test_schema_column_case_and_width_fail_closed(self): for mutate in [ lambda d: d.update(schemaVersion=True), lambda d: d["columns"].reverse(), lambda d: d["datasets"].reverse(), lambda d: d["datasets"][0]["rows"].append(d["datasets"][0]["rows"][0]), lambda d: d["datasets"][0]["rows"][1].pop(), ]: data = copy.deepcopy(self.data) mutate(data) with self.assertRaises(ValueError): c.calculate(data) def test_duplicate_json_keys(self): with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "input.json" path.write_text('{"a":1,"a":2}') with self.assertRaisesRegex(ValueError, "Duplicate"): c.load(path) def test_zero_denominators_and_invalid_envelopes(self): with self.assertRaises(ValueError): c.reduction(D(0), D(0)) with self.assertRaises(ValueError): c.envelope(D("0.001"), D(1), D("0.002"), D("0.002")) data = copy.deepcopy(self.data) data["datasets"][0]["rows"][0][1:5] = ["0.000"] * 4 with self.assertRaises(ValueError): c.calculate(data) def test_generated_outputs_and_tamper_detection(self): c.verify(c.ROOT) with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) (root / "table3.json").write_bytes((c.ROOT / "table3.json").read_bytes()) expected = c.outputs(root) for name, value in expected.items(): (root / name).write_text(value) c.verify(root) for name, value in expected.items(): (root / name).write_text(value + "tampered") with self.assertRaisesRegex(ValueError, "Stale or falsified"): c.verify(root) (root / name).write_text(value) data = json.loads((root / "table3.json").read_text()) data["source"]["accessed"] = "2026-11-24" (root / "table3.json").write_text(json.dumps(data)) with self.assertRaises(ValueError): c.verify(root) def test_report_labels_cannot_disguise_empirical_evidence(self): self.assertFalse(self.report["experimentalReplication"]) self.assertFalse(self.report["dataPayloadIncluded"]) text = c.markdown(self.report) for phrase in ["not proof", "not confidence intervals", "not a new measurement", "not presented as a corrected experimental"]: self.assertIn(phrase, text) if __name__ == "__main__": unittest.main()