# SPDX-License-Identifier: CC0-1.0 """Independent exact-integer checks; Python 3 standard library only.""" from decimal import Decimal, localcontext from fractions import Fraction from math import comb, isclose from pathlib import Path import json import sys def require(condition, message): if not condition: raise ValueError(message) def exact_series(bits, keys, hashes): # S(t, j) counts partitions of insertion addresses into nonempty classes. stirling = [0] * (bits + 1) stirling[0] = 1 falling = [1] for j in range(1, bits + 1): falling.append(falling[-1] * (bits - j + 1)) results = [Fraction(0)] for t in range(1, keys * hashes + 1): for j in range(min(t, bits), 0, -1): stirling[j] = j * stirling[j] + stirling[j - 1] stirling[0] = 0 if t % hashes == 0: numerator = sum(j ** hashes * falling[j] * stirling[j] for j in range(1, min(t, bits) + 1)) results.append(Fraction(numerator, bits ** (t + hashes))) return results def exact_query(bits, keys, hashes): # Condition on d distinct QUERY addresses; use inclusion-exclusion to cover # all of them with the insertion draws. Integer arithmetic avoids cancellation. stirling = [1] + [0] * hashes for t in range(1, hashes + 1): for d in range(t, 0, -1): stirling[d] = d * stirling[d] + stirling[d - 1] stirling[0] = 0 numerator, falling = 0, 1 for d in range(1, min(hashes, bits) + 1): falling *= bits - d + 1 covered = sum((-1) ** j * comb(d, j) * (bits - j) ** (keys * hashes) for j in range(d + 1)) numerator += stirling[d] * falling * covered return Fraction(numerator, bits ** (hashes * (keys + 1))) def expected_mean(bits, keys, hashes, blocks=1): untouched_by_key = 1 - (1 - Fraction(bits - 1, bits) ** hashes) / blocks return bits * (1 - untouched_by_key ** keys) def check_fields(record, fields, label): require(type(record) is dict and set(record) == set(fields), label + ": missing or unknown fields") def check_geometry(record, expected, label): for field, value in expected.items(): actual = record[field] if type(value) is int: require(type(actual) is int and actual == value, label + ": unexpected " + field) else: require(type(actual) is list and len(actual) == len(value), label + ": unexpected " + field + " length") require(all(type(a) in (int, float) and a == b for a, b in zip(actual, value)), label + ": unexpected " + field) def verify(receipt): # This validates the published v1 example packet, not arbitrary user models. require(type(receipt) is dict and type(receipt.get("schemaVersion")) is int and receipt["schemaVersion"] == 1, "unsupported receipt schema") results = receipt.get("results") check_fields(results, ("finite", "blocked", "observed"), "results") require(type(results["finite"]) is list and len(results["finite"]) == 5, "finite: expected all five published cases") require(type(results["observed"]) is list and len(results["observed"]) == 4, "observed: expected all four published cases") check_fields(results["blocked"], ("global", "fixedEqualLoad", "randomBlockLoad"), "blocked") checks, checked_values = [], 0 def check(label, expected, actual, tolerance=2e-14, upper=1): nonlocal checked_values require(type(actual) in (int, float) and 0 <= actual <= upper + tolerance, label + ": expected a finite in-range number") delta = abs(float(expected) - actual) require(isclose(float(expected), actual, rel_tol=0, abs_tol=tolerance), label + ": probability mismatch" if label.endswith(".fpr") else label + ": value mismatch") checked_values += 1 return delta finite_fields = ("bits", "distinctKeys", "hashes", "fpr", "meanOccupied", "probabilityMass", "meanFillPower", "exponentialApproximation") def check_finite(label, row, geometry): check_fields(row, finite_fields, label) bits, keys, hashes = geometry check_geometry(row, dict(bits=bits, distinctKeys=keys, hashes=hashes), label) delta = check(label + ".fpr", exact_query(bits, keys, hashes), row["fpr"]) mean = expected_mean(bits, keys, hashes) check(label + ".meanOccupied", mean, row["meanOccupied"], bits * 2e-14, bits) check(label + ".probabilityMass", 1, row["probabilityMass"]) check(label + ".meanFillPower", (mean / bits) ** hashes, row["meanFillPower"]) with localcontext() as context: context.prec = 60 approximate = (1 - (-Decimal(keys * hashes) / bits).exp()) ** hashes check(label + ".exponentialApproximation", approximate, row["exponentialApproximation"]) checks.append({"case": label, "absoluteDifference": delta}) for index, geometry in enumerate(((2, 1, 2), (8, 1, 2), (64, 8, 4), (512, 64, 4), (4096, 512, 4))): check_finite("finite-" + str(index), results["finite"][index], geometry) check_finite("global", results["blocked"]["global"], (512, 64, 4)) check_finite("fixedEqualLoad", results["blocked"]["fixedEqualLoad"], (64, 8, 4)) row = results["blocked"]["randomBlockLoad"] check_fields(row, ("blockBits", "blocks", "distinctKeys", "hashes", "fpr", "meanOccupied", "probabilityMass"), "randomBlockLoad") check_geometry(row, dict(blockBits=64, blocks=8, distinctKeys=64, hashes=4), "randomBlockLoad") n, b = row["distinctKeys"], row["blocks"] series = exact_series(row["blockBits"], n, row["hashes"]) probability = sum((Fraction(comb(n, j) * (b - 1) ** (n - j), b ** n) * series[j] for j in range(n + 1)), Fraction(0)) delta = check("randomBlockLoad.fpr", probability, row["fpr"]) check("randomBlockLoad.meanOccupied", expected_mean(row["blockBits"], n, row["hashes"], b), row["meanOccupied"], row["blockBits"] * 2e-14, row["blockBits"]) check("randomBlockLoad.probabilityMass", 1, row["probabilityMass"]) checks.append({"case": "randomBlockLoad", "absoluteDifference": delta}) observed = (([4, 4], [0.5, 0.5]), ([0, 8], [0.5, 0.5]), ([0, 8], [0.9, 0.1]), ([0, 8], [0.1, 0.9])) for index, (occupied, weights) in enumerate(observed): row = results["observed"][index] label = "observed-" + str(index) check_fields(row, ("occupied", "blockBits", "hashes", "weights", "fpr"), label) check_geometry(row, dict(occupied=occupied, blockBits=8, hashes=2, weights=weights), label) probability = sum((Fraction(str(w)) * Fraction(x, row["blockBits"]) ** row["hashes"] for x, w in zip(row["occupied"], row["weights"])), Fraction(0)) delta = check(label + ".fpr", probability, row["fpr"]) checks.append({"case": label, "absoluteDifference": delta}) return {"python": sys.version.split()[0], "method": "Exact rational probabilities and means; 60-digit Decimal exponential approximation. Rounded only for comparison.", "checkedCases": len(checks), "checkedValues": checked_values, "checks": checks} def unique_object(pairs): result = {} for key, value in pairs: require(key not in result, "duplicate JSON key: " + key) result[key] = value return result def reject_constant(value): raise ValueError("nonstandard JSON number: " + value) if __name__ == "__main__": path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_name("bloom-finite.json") receipt = json.loads(path.read_text(), object_pairs_hook=unique_object, parse_constant=reject_constant) print(json.dumps(verify(receipt), indent=2))