#!/usr/bin/env python3 """Self-test for count.py. Three layers, all exact: * the fixture files, through the CLI (exit code, stdout shape, count); * hand-built adversarial configurations with hand-checked answers; * a fuzz comparison against an independent O(n^3) reference that computes the exact circumcentre of every triple and keeps those of radius exactly 1. Run: python3 test_count.py """ import importlib.util import json import math import os import random import subprocess import sys from fractions import Fraction if hasattr(sys, "set_int_max_str_digits"): sys.set_int_max_str_digits(0) HERE = os.path.dirname(os.path.abspath(__file__)) COUNT = os.path.join(HERE, "count.py") # The fixtures live in the route (../..); this checkout is shared with other # agents and has been switched to another branch mid-run, which removes them # from the working tree. A byte-identical copy taken from # origin/rusirui-repro-verifier is kept in ./fixtures and used only as fallback. REPO_FIXTURES = os.path.abspath(os.path.join(HERE, "..", "..", "fixtures")) LOCAL_FIXTURES = os.path.join(HERE, "fixtures") FIXTURES = REPO_FIXTURES if os.path.isdir(REPO_FIXTURES) else LOCAL_FIXTURES CASES = os.path.join(HERE, "cases") failures = [] def check(condition, label, detail=""): if condition: return True failures.append(f"{label}: {detail}" if detail else label) return False def load_impl(): spec = importlib.util.spec_from_file_location("count_impl_pairs", COUNT) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module impl = load_impl() # ---------------------------------------------------------------- reference def reference_centres(points): """Exact centres of all radius-1 circles through >= 3 points, O(n^3). Independent of count.py: for every triple it computes the circumcentre by Cramer's rule on the perpendicular-bisector system (integer arithmetic on the scaled points) and keeps it when the squared radius is exactly 1. """ n = len(points) scale = 1 for x, y in points: scale = scale * x.denominator // math.gcd(scale, x.denominator) scale = scale * y.denominator // math.gcd(scale, y.denominator) xs = [int(x * scale) for x, _ in points] ys = [int(y * scale) for _, y in points] target = scale * scale found = set() for i in range(n): ax, ay = xs[i], ys[i] a2 = ax * ax + ay * ay for j in range(i + 1, n): bx, by = xs[j], ys[j] b2 = bx * bx + by * by for k in range(j + 1, n): cx, cy = xs[k], ys[k] d = 2 * ((bx - ax) * (cy - ay) - (by - ay) * (cx - ax)) if d == 0: continue c2 = cx * cx + cy * cy nx = a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by) ny = a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax) # centre = (nx/d, ny/d) in scaled coordinates, i.e. /scale in real ones if (ax * d - nx) ** 2 + (ay * d - ny) ** 2 == target * d * d: found.add((Fraction(nx, d * scale), Fraction(ny, d * scale))) return sorted(found) # ---------------------------------------------------------------------- cli def run_cli(path, cwd=None): return subprocess.run( [sys.executable, COUNT, path], capture_output=True, text=True, encoding="utf-8", cwd=cwd, ) def run_valid(path, cwd=None): proc = run_cli(path, cwd) if proc.returncode != 0: raise AssertionError(f"{path}: expected exit 0, got {proc.returncode}: {proc.stderr!r}") raw = proc.stdout.strip() if not raw or "\n" in raw: raise AssertionError(f"{path}: stdout must be one JSON line, got {proc.stdout!r}") document = json.loads(raw) if set(document) != {"n", "unit_circles", "centers"}: raise AssertionError(f"{path}: unexpected keys {sorted(document)}") if not isinstance(document["n"], int) or not isinstance(document["unit_circles"], int): raise AssertionError(f"{path}: n / unit_circles must be JSON integers") if document["unit_circles"] != len(document["centers"]): raise AssertionError(f"{path}: unit_circles != len(centers)") return document def run_invalid(path): proc = run_cli(path) if proc.returncode != 1: return False, f"expected exit 1, got {proc.returncode}" if proc.stdout != "": return False, f"expected empty stdout, got {proc.stdout!r}" if not proc.stderr.strip(): return False, "expected a reason on stderr" return True, proc.stderr.strip() def write_case(name, document): os.makedirs(CASES, exist_ok=True) path = os.path.join(CASES, name + ".json") with open(path, "w", encoding="utf-8") as handle: json.dump(document, handle, indent=2) handle.write("\n") return path def config(points, claimed=0, schema=1): return {"schema": schema, "points": points, "unit_circles": claimed} # ---------------------------------------------------------------- fixtures SAMPLE_ACCEPT = ["collinear", "dedup", "grid", "nonunit", "rational-center", "three"] SAMPLE_REJECT = ["collinear", "duplicate", "float", "nearly-unit", "overcount", "undercount"] def fixture_rows(): rows = [] for name in SAMPLE_ACCEPT: path = os.path.join(FIXTURES, "samples", "accept", name, "configuration.json") claimed = json.load(open(path, encoding="utf-8"))["unit_circles"] doc = run_valid(path) ok = check(doc["unit_circles"] == claimed, f"accept/{name} count", f"{doc['unit_circles']} != {claimed}") rows.append((os.path.relpath(path, FIXTURES), 0, doc["unit_circles"], claimed, ok)) for name in SAMPLE_REJECT: path = os.path.join(FIXTURES, "samples", "reject", name, "configuration.json") claimed = json.load(open(path, encoding="utf-8"))["unit_circles"] if name in ("duplicate", "float"): ok, detail = run_invalid(path) check(ok, f"reject/{name} invalid", detail) rows.append((os.path.relpath(path, FIXTURES), 1, "n/a", claimed, ok)) else: doc = run_valid(path) ok = check(doc["unit_circles"] != claimed, f"reject/{name} mismatch", f"{doc['unit_circles']} == {claimed}") rows.append((os.path.relpath(path, FIXTURES), 0, doc["unit_circles"], claimed, ok)) path = os.path.join(FIXTURES, "grid80", "configuration.json") claimed = json.load(open(path, encoding="utf-8"))["unit_circles"] doc = run_valid(path) check(doc["n"] == 80, "grid80 n", str(doc["n"])) rows.append((os.path.relpath(path, FIXTURES), 0, doc["unit_circles"], claimed, True)) return rows, doc def fixture_crosscheck(grid80_doc): """Every valid fixture, plus grid80, must match the O(n^3) reference exactly.""" paths = [] for name in SAMPLE_ACCEPT: paths.append(os.path.join(FIXTURES, "samples", "accept", name, "configuration.json")) for name in ("collinear", "nearly-unit", "overcount", "undercount"): paths.append(os.path.join(FIXTURES, "samples", "reject", name, "configuration.json")) paths.append(os.path.join(FIXTURES, "grid80", "configuration.json")) for path in paths: document = json.load(open(path, encoding="utf-8")) points = [(impl._coordinate(p[0], "x"), impl._coordinate(p[1], "y")) for p in document["points"]] got = [(cx, cy) for cx, cy, _ in impl.count_unit_circles(points)] want = reference_centres(points) check(got == want, f"reference mismatch {os.path.basename(os.path.dirname(path))}", f"{len(got)} vs {len(want)}") # grid80 through the reference too (82k triples, integer arithmetic) document = json.load(open(os.path.join(FIXTURES, "grid80", "configuration.json"), encoding="utf-8")) points = [(Fraction(p[0]), Fraction(p[1])) for p in document["points"]] want = reference_centres(points) check(len(want) == grid80_doc["unit_circles"], "grid80 reference", f"{len(want)} != {grid80_doc['unit_circles']}") # ------------------------------------------------------------- adversarial def adversarial_cases(): rows = [] def case(name, points, expected_count, expected_centres=None, note=""): path = write_case(name, config(points, claimed=999)) doc = run_valid(path) ok = check(doc["unit_circles"] == expected_count, f"adversarial {name} count", f"{doc['unit_circles']} != {expected_count}") if expected_centres is not None: ok = check(doc["centers"] == expected_centres, f"adversarial {name} centres", f"{doc['centers']} != {expected_centres}") and ok # independent reference on the same set pts = [(impl._coordinate(p[0], "x"), impl._coordinate(p[1], "y")) for p in points] ref = reference_centres(pts) ok = check([(cx, cy) for cx, cy, _ in impl.count_unit_circles(pts)] == ref, f"adversarial {name} reference", f"{len(ref)} circles") and ok rows.append((name, expected_count, doc["unit_circles"], note, ok)) return doc # A1: eight rational points on one unit circle; two distinct unit circles # meet in at most two points, so exactly one circle is counted. case("many-on-one-circle", [ [1, 0], [0, 1], [-1, 0], [0, -1], ["3/5", "4/5"], ["-3/5", "4/5"], ["4/5", "3/5"], ["3/5", "-4/5"], ], 1, [["0", "0"]], "8 cocircular rational points -> 1") # A2: a chord of length exactly 2 forces the centre to be the midpoint; # the two points plus each apex give one circle each way, same centre. case("diameter-chord", [[0, 0], [2, 0], [1, 1], [1, -1]], 1, [["1", "0"]], "d2 = 4 branch, centre is the midpoint") # A3: three collinear points lie on no circle. case("three-collinear", [[0, 0], [1, 0], [2, 0]], 0, [], "no circle") # A4: unit square. Every triple has circumcentre (1/2,1/2) and radius # sqrt(2)/2, not 1; the unit circles through (0,0),(1,0) have irrational # centres and contain no third rational point. case("unit-square", [[0, 0], [1, 0], [0, 1], [1, 1]], 0, [], "irrational centres cannot carry three rational points") # A5: d2 = 4/5 is not a rational square and 4-d2 = 16/5 is not either, yet # (4-d2)/d2 = 4 is a square, so the centre is rational. A test that asks # only whether 4-d2 is a square misses this circle. case("non-square-chord-rational-centre", [[0, 0], ["2/5", "4/5"], ["-3/5", "-1/5"]], 1, [["-3/5", "4/5"]], "centre rational although d2 and 4-d2 are not squares") # A6: four points on which each 3-subset has its own unit circle: the two # unit circles sharing the chord (4/5, +-3/5) and two more through the # apexes (1,0) and (13/5,0). case("two-circles-shared-chord", [["4/5", "3/5"], ["4/5", "-3/5"], [1, 0], ["13/5", 0]], 4, [["0", "0"], ["8/5", "0"], ["9/5", "-3/5"], ["9/5", "3/5"]], "four 3-subsets, four centres") # A7: the same circle described by non-reduced coordinates everywhere. case("non-reduced-input", [["2/2", "0/1"], ["0/1", "3/3"], ["-4/4", "0/1"]], 1, [["0", "0"]], "coordinates reduced on input") # A8: four Pythagorean points on the unit circle centred at (1/5, 1/5). case("scaled-pythagorean", [["4/5", 1], [1, "4/5"], ["-2/5", 1], ["4/5", "-3/5"]], 1, [["1/5", "1/5"]], "circle centre (1/5,1/5)") # A9: negative centres print as "-2" and "-7/5" (reduced, sign on top). case("negative-integral-centre", [[-1, 3], [-3, 3], [-2, 4], [-2, 2]], 1, [["-2", "3"]], "integral negative centre") case("negative-fraction-centre", [["-4/5", "7/5"], ["-3/5", "6/5"], ["-2/1", "7/5"]], 1, [["-7/5", "3/5"]], "fractional negative centre") return rows # ------------------------------------------------------------------- fuzz def lcm(a, b): return a * b // math.gcd(a, b) def structured_points(rng, centre, how_many, noise): """Points on the unit circle centred at `centre`, plus random noise.""" a, b = centre points = set() tries = 0 while len(points) < how_many and tries < 400: tries += 1 u = rng.randint(-7, 7) v = rng.randint(1, 7) norm = u * u + v * v px = Fraction(a) + Fraction(v * v - u * u, norm) py = Fraction(b) + Fraction(2 * u * v, norm) points.add((px, py)) while len(points) < how_many + noise: points.add((Fraction(rng.randint(-6, 6), rng.choice([1, 2, 3, 4])), Fraction(rng.randint(-6, 6), rng.choice([1, 2, 3, 4])))) return sorted(points) def fuzz(rounds=200, seed=20261128): rng = random.Random(seed) bad = 0 for round_index in range(rounds): mode = round_index % 5 if mode == 0: n = rng.randint(3, 9) points = set() while len(points) < n: points.add((Fraction(rng.randint(-10, 10), rng.choice([1, 2, 3, 4, 5, 6])), Fraction(rng.randint(-10, 10), rng.choice([1, 2, 3, 4, 5, 6])))) points = sorted(points) elif mode == 1: centre = (Fraction(rng.randint(-3, 3), rng.choice([1, 2, 3])), Fraction(rng.randint(-3, 3), rng.choice([1, 2, 3]))) points = structured_points(rng, centre, rng.randint(3, 6), rng.randint(0, 3)) elif mode == 2: # collinear on a rational line: no circles at all slope = Fraction(rng.randint(-3, 3), rng.choice([1, 2, 3])) intercept = Fraction(rng.randint(-3, 3), rng.choice([1, 2, 3])) n = rng.randint(3, 8) xs = rng.sample(range(-9, 10), n) points = sorted((Fraction(x), slope * x + intercept) for x in xs) elif mode == 3: # lattice points, where many unit circles occur n = rng.randint(3, 12) pool = [(Fraction(x), Fraction(y)) for x in range(-4, 5) for y in range(-4, 5)] points = sorted(rng.sample(pool, n)) else: # two structured circles plus noise c1 = (Fraction(rng.randint(-2, 2)), Fraction(rng.randint(-2, 2))) c2 = (Fraction(rng.randint(-2, 2), 2), Fraction(rng.randint(-2, 2), 2)) points = sorted(set(structured_points(rng, c1, rng.randint(3, 5), 1) + structured_points(rng, c2, rng.randint(3, 5), 1))) if len(points) < 3: continue got = [(cx, cy) for cx, cy, _ in impl.count_unit_circles(points)] want = reference_centres(points) if got != want: bad += 1 check(False, f"fuzz round {round_index}", f"{len(got)} != {len(want)} on {points}") if bad > 3: break check(bad == 0, "fuzz all rounds", f"{bad} mismatches") return rounds # --------------------------------------------------------------- validity def validity_cases(): rows = [] def invalid(name, document, note=""): path = write_case(name, document) ok, detail = run_invalid(path) check(ok, f"invalid {name}", detail) rows.append((name, ok, note)) return ok def valid(name, document, expected=None, note=""): path = write_case(name, document) try: doc = run_valid(path) except AssertionError as exc: check(False, f"valid {name}", str(exc)) rows.append((name, False, note)) return if expected is not None: check(doc["unit_circles"] == expected, f"valid {name} count", f"{doc['unit_circles']} != {expected}") rows.append((name, True, note)) valid("minimum-three", config([[0, 0], [1, 0], ["1/2", "0/1"]], 0), 0, "n = 3, distinct and collinear") invalid("two-points", config([[0, 0], [1, 0]]), "n < 3") invalid("eighty-one-points", config([[x, 0] for x in range(81)]), "n > 80") invalid("schema-two", config([[0, 0], [1, 0], [2, 2]], schema=2), "schema != 1") invalid("schema-float", config([[0, 0], [1, 0], [2, 2]], schema=1.0), "schema 1.0") invalid("schema-string", config([[0, 0], [1, 0], [2, 2]], schema="1"), "schema '1'") invalid("schema-bool", config([[0, 0], [1, 0], [2, 2]], schema=True), "schema true") invalid("top-level-array", [[0, 0], [1, 0], [2, 2]], "not an object") invalid("float-x", config([[1.0, 0], [0, 1], [-1, 0]]), "JSON float") invalid("float-y", config([[0, 0], [1, 0], [0, 1.5]]), "JSON float") invalid("bool-coordinate", config([[0, 0], [1, 0], [True, 2]]), "JSON boolean") invalid("null-coordinate", config([[0, 0], [1, 0], [None, 2]]), "null") invalid("decimal-string", config([[0, 0], [1, 0], ["1.5/2", 0]]), "decimal in string") invalid("exponent-string", config([[0, 0], [1, 0], ["1e3/2", 0]]), "exponent in string") invalid("whitespace-string", config([[0, 0], [1, 0], [" 1/2", 0]]), "leading space") invalid("trailing-string", config([[0, 0], [1, 0], ["1/2 ", 0]]), "trailing space") invalid("zero-denominator", config([[0, 0], [1, 0], ["1/0", 0]]), "q = 0") invalid("negative-denominator", config([[0, 0], [1, 0], ["1/-2", 0]]), "q < 0") invalid("plain-integer-string", config([[0, 0], [1, 0], ["2", 0]]), "string not p/q") invalid("plus-sign", config([[0, 0], [1, 0], ["+1/2", 0]]), "plus sign (rejected)") invalid("double-slash", config([[0, 0], [1, 0], ["1//2", 0]]), "1//2") invalid("duplicate-reduced", config([[1, 0], ["2/2", 0], [0, 1]]), "duplicate after reduction") invalid("duplicate-fraction", config([["1/3", 0], [2, 0], ["2/6", 0], [0, 1]]), "duplicate after reduction") invalid("point-length-1", config([[0, 0], [1, 0], [2]]), "point with one coordinate") invalid("point-length-3", config([[0, 0], [1, 0], [2, 2, 2]]), "point with three coordinates") invalid("point-not-array", config([[0, 0], [1, 0], 7]), "point not an array") invalid("points-not-array", {"schema": 1, "points": "nope", "unit_circles": 0}, "points not an array") invalid("missing-points", {"schema": 1, "unit_circles": 0}, "points missing") # coordinates beyond CPython's default 4300-digit int-string limit stay exact huge = int("9" * 5000) valid("huge-json-integer", config([[0, 0], [1, 0], [huge, 0]], 0), 0, "5000-digit JSON integer coordinate") valid("huge-string-fraction", config([[0, 0], [1, 0], ["1" + "0" * 5000 + "/" + "3" + "0" * 5000, 0]], 0), 0, "5000-digit fraction string, reduces to 1/3") # deeply nested JSON is not a configuration, not a crash deep = os.path.join(CASES, "deeply-nested.json") with open(deep, "w", encoding="utf-8") as handle: handle.write("[" * 5000 + "]" * 5000) ok, detail = run_invalid(deep) check(ok, "invalid deeply-nested", detail) rows.append(("deeply-nested", ok, "recursion guard")) # not JSON at all os.makedirs(CASES, exist_ok=True) broken = os.path.join(CASES, "broken.json") with open(broken, "w", encoding="utf-8") as handle: handle.write("{not json") ok, detail = run_invalid(broken) check(ok, "invalid broken-json", detail) rows.append(("broken-json", ok, "not JSON")) missing = os.path.join(CASES, "does-not-exist.json") if os.path.exists(missing): os.remove(missing) ok, detail = run_invalid(missing) check(ok, "invalid missing-file", detail) rows.append(("missing-file", ok, "unreadable")) # a valid n = 80 configuration and a very large coordinate points = [[x, y] for x in range(10) for y in range(8)] valid("eighty-points", config(points, 76), 76, "n = 80 upper bound (same 10x8 grid as grid80)") valid("huge-coordinates", config([[0, 0], ["10000000000000000000000000000000001/10000000000000000000000000000000000", 0], [1, 0]], 0), 0, "big integers stay exact") # non-reduced input accepted and reduced on the way out path = write_case("non-reduced-valid", config([["10/10", "0/7"], ["0/9", "6/6"], ["-2/2", "0/5"]], 999)) doc = run_valid(path) check(doc["centers"] == [["0", "0"]], "non-reduced centres", str(doc["centers"])) check(doc["unit_circles"] == 1, "non-reduced count", str(doc["unit_circles"])) rows.append(("non-reduced-valid", True, "(1,0),(0,1),(-1,0) from non-reduced strings")) return rows def cwd_cases(): """count.py must work from any working directory.""" path = os.path.join(FIXTURES, "samples", "accept", "three", "configuration.json") ok = True for cwd in (os.path.abspath(os.path.join(HERE, "..", "..", "..", "..")), os.path.abspath(os.sep)): try: doc = run_valid(path, cwd=cwd) ok = check(doc["unit_circles"] == 1, f"cwd {cwd}", str(doc)) and ok except AssertionError as exc: ok = check(False, f"cwd {cwd}", str(exc)) and ok return ok # ------------------------------------------------------------------- main def main(): print("== fixtures ==") rows, grid80 = fixture_rows() for path, code, computed, claimed, ok in rows: print(f"{path} | {code} | {computed} | {claimed} | {'ok' if ok else 'FAIL'}") print() print("== fixture cross-check against O(n^3) circumcentre reference ==") fixture_crosscheck(grid80) print("done" if not failures else "FAILED") print() print("== adversarial cases ==") for name, expected, computed, note, ok in adversarial_cases(): print(f"{name} | expected {expected} | computed {computed} | {'ok' if ok else 'FAIL'} | {note}") print() print("== validity cases ==") for name, ok, note in validity_cases(): print(f"{name} | {'ok' if ok else 'FAIL'} | {note}") print() print("== working directory ==") cwd_cases() print("done") print() print("== fuzz vs reference ==") rounds = fuzz() print(f"{rounds} rounds done") print() if failures: print(f"FAILURES ({len(failures)}):") for item in failures: print(" -", item) return 1 print("ALL CHECKS PASSED") return 0 if __name__ == "__main__": sys.exit(main())