#!/usr/bin/env python3 """Grade 5 Track 1 Experiment: Cache Consistency, Stampede Protection, Read-After-Write, and Cache Restart Recovery.""" import base64 from concurrent.futures import ThreadPoolExecutor import json import subprocess import sys import time import urllib.request import uuid BASE_URL = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080" def call_api(method, path, body=None, headers=None): h = {"Accept": "application/json"} data = None if body is not None: data = json.dumps(body).encode("utf-8") h["Content-Type"] = "application/json" if headers: h.update(headers) req = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method) t0 = time.perf_counter() with urllib.request.urlopen(req, timeout=10) as resp: raw = resp.read() elapsed_ms = (time.perf_counter() - t0) * 1000.0 payload = json.loads(raw.decode("utf-8")) if raw else None return resp.code, payload, elapsed_ms def run_cmd(cmd): res = subprocess.run(cmd, shell=True, capture_output=True, text=True) if res.returncode != 0: raise RuntimeError(f"Command failed ({cmd}): {res.stderr}") return res.stdout.strip() def percentile(sorted_vals, pct): if not sorted_vals: return 0.0 idx = min(len(sorted_vals) - 1, max(0, int(round((pct / 100.0) * (len(sorted_vals) - 1))))) return round(sorted_vals[idx], 3) def main(): u_name = f"track1_{uuid.uuid4().hex[:8]}" pw = "Track1Password-2026!" _, user, _ = call_api("POST", "/api/v1/users", { "username": u_name, "display_name": "Track 1 Researcher", "password": pw, }) cred = base64.b64encode(f"{u_name}:{pw}".encode("utf-8")).decode("ascii") _, sess, _ = call_api("POST", "/api/v1/auth/sessions", headers={"Authorization": f"Basic {cred}"}) auth_hdr = {"Authorization": f"Bearer {sess['token']}"} _, chat, _ = call_api("POST", "/api/v1/chats", { "title": "Track 1 Cache Consistency Chat", "member_ids": [user["id"]], }, headers=auth_hdr) chat_id = chat["id"] # Seed 20 messages for i in range(20): call_api("POST", f"/api/v1/chats/{chat_id}/messages", { "text": f"Seed message #{i + 1}", }, headers=auth_hdr) # Experiment 1: Stale Read in naive_ttl vs Strict Read-After-Write in write_through_versioned print("[Track 1 - Step 1] Comparing stale reads (naive_ttl) vs strict read-after-write (write_through_versioned)...") call_api("POST", "/internal/stats?mode=naive_ttl&reset=1") run_cmd("docker exec mtusi-lab2-redis redis-cli FLUSHDB") # Warm up cache in naive_ttl _, page_warm, _ = call_api("GET", f"/api/v1/chats/{chat_id}/messages?limit=50", headers=auth_hdr) # Write a new message _, new_msg_naive, _ = call_api("POST", f"/api/v1/chats/{chat_id}/messages", { "text": "Fresh write during naive_ttl", }, headers=auth_hdr) # Immediate read returns stale cached page without new_msg_naive _, page_after_naive, _ = call_api("GET", f"/api/v1/chats/{chat_id}/messages?limit=50", headers=auth_hdr) naive_saw_new = any(m["id"] == new_msg_naive["id"] for m in page_after_naive["items"]) # Now switch to write_through_versioned and verify 20 consecutive write -> immediate read cycles call_api("POST", "/internal/stats?mode=write_through_versioned&reset=1") run_cmd("docker exec mtusi-lab2-redis redis-cli FLUSHDB") raw_violations = 0 for i in range(20): _, page_before, _ = call_api("GET", f"/api/v1/chats/{chat_id}/messages?limit=100", headers=auth_hdr) _, sent, _ = call_api("POST", f"/api/v1/chats/{chat_id}/messages", { "text": f"Read-after-write verification #{i + 1}", }, headers=auth_hdr) _, page_imm, _ = call_api("GET", f"/api/v1/chats/{chat_id}/messages?limit=100", headers=auth_hdr) if not any(m["id"] == sent["id"] for m in page_imm["items"]): raw_violations += 1 if raw_violations != 0: raise AssertionError(f"Read-after-write violated {raw_violations} times!") # Experiment 2: Cache Stampede on Cold Cache (40 concurrent readers) print("[Track 1 - Step 2] Measuring cache stampede under 40 concurrent readers (naive_ttl vs singleflight)...") def read_worker(_): _, _, ms = call_api("GET", f"/api/v1/chats/{chat_id}/messages?limit=50", headers=auth_hdr) return ms # Warm session & membership first, then delete only message page keys to simulate hot chat page expiration call_api("POST", "/internal/stats?mode=naive_ttl&reset=1") call_api("GET", f"/api/v1/chats/{chat_id}/messages?limit=50", headers=auth_hdr) run_cmd(f'docker exec mtusi-lab2-redis redis-cli DEL "msg_page:{chat_id}:naive:l50:c"') call_api("POST", "/internal/stats?mode=naive_ttl&reset=1") with ThreadPoolExecutor(max_workers=40) as pool: naive_latencies = sorted(list(pool.map(read_worker, range(40)))) _, stats_naive, _ = call_api("GET", "/internal/stats") # Protected mode (write_through_versioned with singleflight) call_api("POST", "/internal/stats?mode=write_through_versioned&reset=1") call_api("GET", f"/api/v1/chats/{chat_id}/messages?limit=50", headers=auth_hdr) # Delete the cached page key so all 40 readers miss simultaneously keys_out = run_cmd(f'docker exec mtusi-lab2-redis redis-cli KEYS "msg_page:{chat_id}:*"') for k in keys_out.splitlines(): if k.strip(): run_cmd(f'docker exec mtusi-lab2-redis redis-cli DEL "{k.strip()}"') call_api("POST", "/internal/stats?mode=write_through_versioned&reset=1") with ThreadPoolExecutor(max_workers=40) as pool: protected_latencies = sorted(list(pool.map(read_worker, range(40)))) _, stats_protected, _ = call_api("GET", "/internal/stats") # Warm cache hit latency (40 requests hitting warm Redis cache -> 0 SQL queries) call_api("POST", "/internal/stats?mode=write_through_versioned&reset=1") warm_latencies = sorted([read_worker(i) for i in range(40)]) _, stats_warm, _ = call_api("GET", "/internal/stats") # Experiment 3: Redis Restart Recovery & Session Preservation print("[Track 1 - Step 3] Testing Redis container restart and cache recovery...") run_cmd("docker restart mtusi-lab2-redis") time.sleep(2) st_code, page_recovered, _ = call_api("GET", f"/api/v1/chats/{chat_id}/messages?limit=100", headers=auth_hdr) if st_code != 200 or len(page_recovered["items"]) < 40: raise AssertionError("Failed to recover history after Redis restart") summary = { "track": "Track 1: Cache Consistency, Stampede Protection, Read-After-Write, and Cache Restart", "read_after_write_experiment": { "naive_ttl_saw_immediate_write": naive_saw_new, "naive_ttl_stale_read_observed": not naive_saw_new, "write_through_versioned_cycles": 20, "write_through_versioned_stale_reads": 0, }, "cache_stampede_40_concurrent_readers": { "unprotected_naive": { "concurrency": 40, "sql_queries_executed": stats_naive["sql_queries"], "singleflight_shared": stats_naive["singleflight_shared"], "latency_p50_ms": percentile(naive_latencies, 50), "latency_p95_ms": percentile(naive_latencies, 95), "latency_p99_ms": percentile(naive_latencies, 99), }, "protected_singleflight": { "concurrency": 40, "sql_queries_executed": stats_protected["sql_queries"], "singleflight_shared": stats_protected["singleflight_shared"], "latency_p50_ms": percentile(protected_latencies, 50), "latency_p95_ms": percentile(protected_latencies, 95), "latency_p99_ms": percentile(protected_latencies, 99), }, "warm_cache_40_reads": { "requests": 40, "sql_queries_executed": stats_warm["sql_queries"], "cache_hits": stats_warm["cache_hits"], "latency_p50_ms": percentile(warm_latencies, 50), "latency_p95_ms": percentile(warm_latencies, 95), "latency_p99_ms": percentile(warm_latencies, 99), }, }, "redis_restart_recovery": { "status_after_restart": st_code, "messages_verified": len(page_recovered["items"]), "session_preserved": True, }, } with open("evidence/track1_cache_consistency.json", "w", encoding="utf-8") as f: json.dump(summary, f, indent=2) print("PASS: Track 1 experiment completed! Saved to evidence/track1_cache_consistency.json") if __name__ == "__main__": main()