#!/usr/bin/env python3 """Replay pinned, unmodified FrequencySketch Java code, not a full cache benchmark.""" import argparse from datetime import datetime, timezone import hashlib import json from pathlib import Path import subprocess import tempfile from urllib.request import urlopen COMMIT = "5227a98b51e02b4d4fbfc2b0e33c362a138f51b1" SOURCE_URL = ( "https://raw.githubusercontent.com/ben-manes/caffeine/" + COMMIT + "/caffeine/src/main/java/com/github/benmanes/caffeine/cache/FrequencySketch.java" ) SOURCE_SHA256 = "1e8d23ba8f59cc792f681319458d0b3583e13b83a50c351952eab70a849bd142" PACKAGE = "com.github.benmanes.caffeine.cache" # Only two non-sketch helpers and a compile-time annotation are substituted. # The narrow helper accepts only the capacity exercised by this replay. HELPER = """package com.github.benmanes.caffeine.cache; final class Caffeine { static void requireArgument(boolean condition) { if (!condition) throw new IllegalArgumentException(); } static int ceilingPowerOfTwo(int value) { if (value != 64) throw new IllegalArgumentException("Replay supports capacity 64 only"); return 64; } } """ ANNOTATION = "package com.google.errorprone.annotations; public @interface Var {}" HARNESS = r''' package com.github.benmanes.caffeine.cache; import java.util.Arrays; public final class AgingReplay { record Key(int identity) { @Override public int hashCode() { return 42; } } static void require(boolean value, String label) { if (!value) throw new IllegalStateException(label); } static FrequencySketch fresh() { FrequencySketch sketch = new FrequencySketch(); sketch.ensureCapacity(64); require(sketch.table.length == 64 && sketch.sampleSize == 640, "configuration"); return sketch; } static int repeat(FrequencySketch sketch, Object key, int calls) { int resets = 0; for (int i = 0; i < calls; i++) { int before = sketch.size; sketch.increment(key); if (sketch.size < before) resets++; } return resets; } public static void main(String[] args) { FrequencySketch hot = fresh(); Key first = new Key(1); int resets = repeat(hot, first, 100000); require(hot.frequency(first) == 15 && hot.size == 15 && resets == 0, "hot saturation"); long[] saturated = hot.table.clone(); int extraResets = repeat(hot, first, 1000); require(Arrays.equals(saturated, hot.table) && hot.size == 15, "saturated no-op"); FrequencySketch collision = fresh(); Key second = new Key(2); require(!first.equals(second) && first.hashCode() == second.hashCode(), "distinct colliding keys"); repeat(collision, first, 15); int beforeFirstAccess = collision.frequency(second); long[] beforeCollision = collision.table.clone(); int collisionResets = repeat(collision, second, 1000); require(beforeFirstAccess == 15 && collision.frequency(second) == 15, "collision estimate"); require(Arrays.equals(beforeCollision, collision.table) && collision.size == 15, "collision does not advance sample"); FrequencySketch sequential = fresh(); int firstResetCall = 0; for (int i = 0; i < 2000; i++) { int before = sequential.size; sequential.increment(Integer.valueOf(i)); if (sequential.size < before) { firstResetCall = i + 1; break; } } require(firstResetCall > 0 && sequential.size < 640, "positive automatic-reset control"); FrequencySketch explicit = fresh(); repeat(explicit, first, 15); explicit.reset(); int afterResetFrequency = explicit.frequency(first); int afterResetSize = explicit.size; require(afterResetFrequency == 7 && afterResetSize == 7, "explicit odd-counter reset"); repeat(explicit, first, 8); require(explicit.frequency(first) == 15 && explicit.size == 15, "increments resume"); System.out.printf(""" { "capacity_entries": 64, "sample_size": 640, "hot_key": {"calls": 100000, "frequency": %d, "sample_counter": %d, "automatic_resets": %d, "extra_saturated_calls": 1000, "extra_automatic_resets": %d, "table_unchanged": true}, "hash_collision": {"first_key_calls": 15, "second_key_calls": 1000, "second_estimate_before_first_access": %d, "second_estimate_after": %d, "sample_counter": %d, "automatic_resets": %d, "table_unchanged": true}, "sequential_keys": {"start": 0, "step": 1, "first_automatic_reset_call": %d, "sample_counter_after": %d}, "explicit_reset": {"calls_before": 15, "frequency_after": %d, "sample_counter_after": %d, "calls_after": 8, "final_frequency": %d, "final_sample_counter": %d} } """, hot.frequency(first), hot.size, resets, extraResets, beforeFirstAccess, collision.frequency(second), collision.size, collisionResets, firstResetCall, sequential.size, afterResetFrequency, afterResetSize, explicit.frequency(first), explicit.size); } } ''' def verified_source(data): if hashlib.sha256(data).hexdigest() != SOURCE_SHA256: raise ValueError("Pinned FrequencySketch SHA-256 mismatch") return data def run(source_file=None): if source_file is None: with urlopen(SOURCE_URL, timeout=30) as response: data = response.read(65537) else: data = Path(source_file).read_bytes() data = verified_source(data) with tempfile.TemporaryDirectory(prefix="hesela-caffeine-aging-") as temp: root = Path(temp) package = root.joinpath(*PACKAGE.split(".")) package.mkdir(parents=True) (package / "FrequencySketch.java").write_bytes(data) (package / "Caffeine.java").write_text(HELPER, encoding="utf8") (package / "AgingReplay.java").write_text(HARNESS, encoding="utf8") annotation = root / "com/google/errorprone/annotations/Var.java" annotation.parent.mkdir(parents=True) annotation.write_text(ANNOTATION, encoding="utf8") compiled = root / "classes" sources = sorted(str(path) for path in root.rglob("*.java")) subprocess.run(["javac", "-d", str(compiled), *sources], check=True, capture_output=True, text=True, timeout=30) result = subprocess.run(["java", "-cp", str(compiled), PACKAGE + ".AgingReplay"], check=True, capture_output=True, text=True, timeout=30) runtime = subprocess.run(["java", "-version"], check=True, capture_output=True, text=True, timeout=10) return { "schema_version": 1, "observation_type": "isolated-native-source-replay", "generated_at": datetime.now(timezone.utc).isoformat(), "source": {"commit": COMMIT, "url": SOURCE_URL, "sha256": SOURCE_SHA256, "license": "Apache-2.0", "tag": "v3.2.3"}, "runtime": runtime.stderr.strip().splitlines(), "method": { "unmodified_class": "FrequencySketch", "substitutions": [ "Two Caffeine helpers: argument validation and capacity-64 power-of-two result.", "Compile-time Var annotation; no sketch method is substituted." ], "workload": "Constructed deterministic direct method calls; no random sampling.", "limits": [ "Not the complete Caffeine cache, its access-event delivery, or eviction policy.", "No throughput, hit-ratio, hardware, wall-clock aging, or collision-rate estimate.", "Explicit reset is a separate control, not an observed automatic reset." ] }, "observations": json.loads(result.stdout) } def verify_observations(actual, expected): for key in ("schema_version", "observation_type", "source", "method", "observations"): if actual[key] != expected[key]: raise ValueError("Replay mismatch: " + key) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source-file", type=Path, help="Offline pinned Java source") parser.add_argument("--output", type=Path) parser.add_argument("--verify", type=Path, help="Compare results, allowing a different runtime/date") args = parser.parse_args() result = run(args.source_file) if args.verify: verify_observations(result, json.loads(args.verify.read_text(encoding="utf8"))) serialized = json.dumps(result, indent=2) + "\n" if args.output: args.output.write_text(serialized, encoding="utf8") print(serialized, end="") if __name__ == "__main__": main()