"""Replay pinned rank() with test doubles, not a trained LRB simulator. Run: python3 verify.py [--check] Needs g++ and Python 3. No network, model training or external packages. The finite timeout is corroboration; cardinality proves nontermination. """ import hashlib import json from pathlib import Path import subprocess import sys import tempfile HERE = Path(__file__).resolve().parent COMMIT = "9e8b4423383c01c4528deb447f152f0437a37c3a" HASHES = { "upstream/lrb.cpp": "2506d6156cb74659af5eabe20cf4ec7075257e72050ee5df0673397dfe37288c", "upstream/LICENSE": "70bddec1b4ddadf016ab6b85b80addc5636361f8cd066c0d828a25e504cdfb60", } CASES = [ ("untrained-63", 63, 64, False, 1, "returned", None), ("trained-63", 63, 64, True, 1, "timeout", 63), ("trained-64", 64, 64, True, 1, "returned", 64), ("trained-63-budget-63", 63, 63, True, 1, "returned", 63), ("window-boundary-63", 63, 64, True, 100, "returned", None), ("just-inside-window-63", 63, 64, True, 99, "timeout", 63), ("trained-1", 1, 64, True, 1, "timeout", 1), ("trained-65", 65, 64, True, 1, "returned", 64), ] TIMEOUT = 2 def require(condition, message): if not condition: raise RuntimeError(message) def rank_body(): for name, expected in HASHES.items(): require(hashlib.sha256((HERE/name).read_bytes()).hexdigest() == expected, "Source or license drift: " + name) source = (HERE/"upstream/lrb.cpp").read_text() start = source.index("pair LRBCache::rank() {") end = source.index("\nvoid LRBCache::evict()", start) return source[start:end].rstrip() def probe(binary, count, budget, trained, age): command = [str(binary), str(count), str(budget), str(int(trained)), str(age)] try: done = subprocess.run(command, capture_output=True, text=True, timeout=TIMEOUT) require(done.returncode == 0, done.stderr or "Probe failed") output, outcome = done.stdout, "returned" except subprocess.TimeoutExpired as error: output = error.stdout or b"" if isinstance(output, bytes): output = output.decode() outcome = "timeout" require(output.startswith("ENTER\n"), "Probe did not reach rank") predicts = [int(line.split()[1]) for line in output.splitlines() if line.startswith("PREDICT ")] returns = [line for line in output.splitlines() if line.startswith("RETURN ")] require(len(predicts) <= 1, "Unexpected prediction count") require(bool(returns) == (outcome == "returned"), "Return marker mismatch") if returns: key, pos = map(int, returns[0].split()[1:]) require(0 <= key < count and key == pos, "Victim outside resident set") return dict(outcome=outcome, prediction_rows=predicts[0] if predicts else None, return_marker=returns[0] if returns else None) def run(): rank = rank_body() # A local shadow caps every existing sample_rate use, including arrays, # prediction row count and sorting. The unmodified variant stays unchanged. patched = rank.replace("LRBCache::rank() {", """LRBCache::rank() { const auto sample_rate = std::min(this->sample_rate, static_cast(in_cache_metas.size()));""", 1) template = (HERE/"harness.cpp").read_text() require(template.count("// HESELA_RANK_FUNCTION") == 1, "Harness marker drift") rows = [] with tempfile.TemporaryDirectory(prefix="hesela-lrb-") as folder: folder = Path(folder) for optimization in ("-O0", "-O2"): binaries = {} for variant, body in (("original", rank), ("capped", patched)): cpp, binary = folder/(variant+".cpp"), folder/variant cpp.write_text(template.replace("// HESELA_RANK_FUNCTION", body)) subprocess.run(["g++", "-std=gnu++11", optimization, "-Wall", "-Wextra", str(cpp), "-o", str(binary)], check=True, capture_output=True, timeout=30) binaries[variant] = binary for name, count, budget, trained, age, expected, capped_rows in CASES: original = probe(binaries["original"], count, budget, trained, age) capped = probe(binaries["capped"], count, budget, trained, age) require(original["outcome"] == expected, name+": original outcome") require(capped["outcome"] == "returned", name+": cap did not return") require(capped["prediction_rows"] == capped_rows, name+": capped prediction rows") if expected == "timeout": require(original["prediction_rows"] is None, name+": reached prediction") else: require(original == capped, name+": existing path changed") rows.append(dict(case=name, optimization=optimization, residents=count, sample_budget=budget, model_present=trained, oldest_age_requests=age, original=original, capped=capped)) return dict(schema_version=1, contribution="isolated source-function probe", upstream_commit=COMMIT, source_hashes=HASHES, random_seed=12345, memory_window_requests=100, timeout_seconds=TIMEOUT, prediction="deterministic test double; no trained model", scope="rank() only; no trace replay, admission, training, or CDN measurements", cases=rows) if __name__ == "__main__": result = run() output = json.dumps(result, indent=2) + "\n" if "--check" in sys.argv: require(json.loads((HERE/"results.json").read_text()) == result, "Stored results drift") else: (HERE/"results.json").write_text(output) print(json.dumps(dict(passed=True, cases=len(result["cases"]), compiler=subprocess.check_output(["g++","-dumpfullversion"],text=True).strip())))