"""Verify a Cube Sudoku Benchmark release. Use --z3 for independent uniqueness checks.""" import argparse from collections import Counter from concurrent.futures import ProcessPoolExecutor, as_completed from hashlib import sha256 from itertools import permutations, product import json from pathlib import Path import re SPLIT_COUNTS = {"train": 800, "validation": 100, "test": 100} TIERS = ("easy", "medium", "hard", "expert", "master") TECHNIQUES = ("naked_single", "hidden_single", "naked_subset", "pointing_subset", "hidden_subset", "x_wing", "swordfish", "jellyfish", "xy_wing") FIELDS = {"puzzle_id", "app_difficulty", "engine_rating", "givens_count", "givens", "solution"} DIGITS = set("123456789") FACE_IDS = ("x_neg", "x_pos", "y_neg", "y_pos", "z_neg", "z_pos") def check(condition, message): if not condition: raise ValueError(message) def expected_geometry(): """Reconstruct the surface and Sudoku units from the face definitions.""" coordinates, grids, units = {}, {}, set() face_axes = product(range(3), (0, 8)) for name, (axis, fixed) in zip(FACE_IDS, face_axes, strict=True): face = [] for row in range(9): face_row = [] for col in range(9): coord = [col, row] coord.insert(axis, fixed) face_row.append(coordinates.setdefault(tuple(coord), len(coordinates))) face.append(face_row) grids[name] = face units.update(tuple(sorted(line)) for line in face) units.update(tuple(sorted(line)) for line in zip(*face, strict=True)) for br, bc in product(range(0, 9, 3), repeat=2): units.add(tuple(sorted(face[r][c] for r in range(br, br + 3) for c in range(bc, bc + 3)))) return coordinates, grids, sorted(units) def cube_symmetries(coordinates): for axes in permutations(range(3)): for flips in product((False, True), repeat=3): yield [coordinates[tuple(8 - c[a] if flip else c[a] for a, flip in zip(axes, flips, strict=True))] for c in coordinates] def canonical_solution(solution, symmetries): normalized = [] for cell_order in symmetries: ordered = "".join(solution[i] for i in cell_order) labels = dict(zip(dict.fromkeys(ordered), "123456789", strict=True)) normalized.append(ordered.translate(str.maketrans(labels))) return min(normalized) def read_payload(root, name, manifest): payload = (root / name).read_bytes() metadata = manifest["files"][name] check(len(payload) == metadata["bytes"], f"Wrong file size: {name}") check(sha256(payload).hexdigest() == metadata["sha256"], f"Checksum mismatch: {name}") return payload def validate_release(root): manifest = json.loads((root / "manifest.json").read_bytes()) topology = json.loads(read_payload(root, "topology.json", manifest)) coordinates, grids, units = expected_geometry() check((len(coordinates), len(units)) == (386, 150), "Wrong number of surface cells or units") check(topology["schema_version"] == 1 and topology["face_size"] == 9 and topology["cell_count"] == 386, "Invalid topology metadata") check(topology["coordinates_xyz"] == [list(c) for c in coordinates], "Coordinate ordering mismatch") check(topology["face_grids"] == grids, "Face mapping mismatch") check(topology["units"] == [list(unit) for unit in units], "Constraint mismatch") symmetries = list(cube_symmetries(coordinates)) groups, puzzle_ids, rows = set(), set(), [] bucket_counts = {tier: Counter() for tier in TIERS} split_order = {tier: [] for tier in TIERS} prefix = manifest["split_method"]["hash_prefix"] for split, count in SPLIT_COUNTS.items(): name = split + ".jsonl" payload = read_payload(root, name, manifest) split_rows = [json.loads(line) for line in payload.splitlines()] counts = Counter(row["app_difficulty"] for row in split_rows) check(counts == {tier: count for tier in TIERS}, f"Wrong tier counts in {name}") check(manifest["files"][name]["rows"] == len(split_rows), f"Wrong row count in {name}") for row in split_rows: puzzle_id = row["puzzle_id"] check(set(row) == FIELDS, f"Wrong schema: {puzzle_id}") givens, solution = row["givens"], row["solution"] check(re.fullmatch("[0-9]{386}", givens) and re.fullmatch("[1-9]{386}", solution), f"Invalid cell sequence: {puzzle_id}") check(row["givens_count"] == 386 - givens.count("0"), f"Wrong givens count: {puzzle_id}") expected_id = "cs-" + sha256(givens.encode("ascii")).hexdigest()[:24] check(puzzle_id == expected_id and puzzle_id not in puzzle_ids, f"Wrong or duplicate ID: {puzzle_id}") puzzle_ids.add(puzzle_id) check(all(a == "0" or a == b for a, b in zip(givens, solution, strict=True)), f"Solution changes a given: {puzzle_id}") check(all({solution[i] for i in unit} == DIGITS for unit in units), f"Invalid solution: {puzzle_id}") canonical = canonical_solution(solution, symmetries) check(canonical not in groups, f"Duplicate symmetry group: {puzzle_id}") groups.add(canonical) group_hash = sha256(canonical.encode("ascii")).hexdigest() split_key = sha256((prefix + group_hash).encode("ascii")).hexdigest() tier = row["app_difficulty"] split_order[tier].append((split_key, split)) rating = row["engine_rating"] check(rating in TECHNIQUES, f"Unknown engine rating: {puzzle_id}") bucket_counts[tier][rating] += 1 rows.extend(split_rows) print(f"{split}: {len(split_rows):,} rows and balanced app tiers", flush=True) expected_splits = [split for split, count in SPLIT_COUNTS.items() for _ in range(count)] for tier, assignments in split_order.items(): check([split for _, split in sorted(assignments)] == expected_splits, f"Hash-based split assignment mismatch: {tier}") check(len(rows) == manifest["total_puzzles"] == manifest["unique_solution_groups"] == 5000, "Wrong total count") check(manifest["per_split_per_app_difficulty"] == SPLIT_COUNTS and manifest["per_app_difficulty"] == {tier: 1000 for tier in TIERS}, "Wrong manifest counts") check(bucket_counts == manifest["engine_rating_counts"], "Wrong rating histogram") print(f"{len(rows):,} valid solutions in {len(groups):,} distinct symmetry groups", flush=True) return rows, units def validate_uniqueness(batch, units, timeout_ms): from z3 import Bool, Not, Or, PbEq, SolverFor, unknown, unsat solver = SolverFor("QF_FD") solver.set(timeout=timeout_ms) cells = [[Bool(f"x_{i}_{d}") for d in range(9)] for i in range(386)] for cell in cells: solver.add(PbEq([(flag, 1) for flag in cell], 1)) for unit in units: for d in range(9): solver.add(PbEq([(cells[i][d], 1) for i in unit], 1)) for row in batch: solver.push() solver.add(*(cells[i][int(d) - 1] for i, d in enumerate(row["givens"]) if d != "0")) solver.add(Or([Not(cells[i][int(d) - 1]) for i, d in enumerate(row["solution"])])) result = solver.check() if result == unknown: solver.set(timeout=timeout_ms * 5) result = solver.check() solver.set(timeout=timeout_ms) check(result == unsat, f"{row['puzzle_id']}: alternative-solution check returned {result}") solver.pop() return len(batch) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--z3", action="store_true", help="require z3-solver and check uniqueness") parser.add_argument("--workers", type=int, default=4, help="parallel Z3 processes") parser.add_argument("--timeout-ms", type=int, default=10000, help="per-puzzle Z3 timeout") args = parser.parse_args() if args.workers < 1 or args.timeout_ms < 1: parser.error("--workers and --timeout-ms must be positive") rows, units = validate_release(Path(__file__).resolve().parent) if args.z3: batches = [rows[i:i + 250] for i in range(0, len(rows), 250)] with ProcessPoolExecutor(max_workers=args.workers) as executor: futures = [executor.submit(validate_uniqueness, batch, units, args.timeout_ms) for batch in batches] checked = 0 for future in as_completed(futures): checked += future.result() print(f"Z3 uniqueness: {checked:,}/{len(rows):,}", flush=True) if __name__ == "__main__": main()