feat(lab2): PostgreSQL 18 persistence, Argon2id auth, Redis 7.4 sessions & cache, Grade 5 tracks
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,299 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade 4 automated verification suite for Lab 2:
|
||||
- Password KDF & colon-in-password support
|
||||
- Strict Basic/Bearer separation & WWW-Authenticate headers
|
||||
- Concurrent registration race on identical username (20 threads -> 1x 201, 19x 409)
|
||||
- Atomic transaction rollback on composite chat creation with unknown member_id
|
||||
- Session TTL expiration with short SESSION_TTL_SECONDS=2
|
||||
- Graceful cache bypass when Valkey/Redis is down & bounded 503 when PostgreSQL is down
|
||||
"""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
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, raw_body=None, timeout=5):
|
||||
h = {"Accept": "application/json"}
|
||||
data = raw_body
|
||||
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)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=timeout)
|
||||
except urllib.error.HTTPError as err:
|
||||
resp = err
|
||||
with resp:
|
||||
status = resp.code
|
||||
resp_headers = dict(resp.headers.items())
|
||||
raw = resp.read()
|
||||
payload = json.loads(raw.decode("utf-8")) if raw else None
|
||||
return status, resp_headers, payload
|
||||
|
||||
|
||||
def assert_true(cond, msg):
|
||||
if not cond:
|
||||
raise AssertionError(msg)
|
||||
|
||||
|
||||
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 wait_ready(timeout_sec=30):
|
||||
deadline = time.monotonic() + timeout_sec
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
st, _, _ = call_api("GET", "/health/ready", timeout=2)
|
||||
if st == 200:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError("API did not become ready in time")
|
||||
|
||||
|
||||
def main():
|
||||
results = {}
|
||||
wait_ready()
|
||||
|
||||
# 1. Negative validation & colon in password
|
||||
print("[1/6] Testing negative inputs, colon-in-password, and auth headers...")
|
||||
u_name = f"u_col_{uuid.uuid4().hex[:8]}"
|
||||
colon_pw = "My:Secret:Pass:2026!"
|
||||
|
||||
# Too short password -> 400
|
||||
st, _, _ = call_api("POST", "/api/v1/users", {
|
||||
"username": u_name,
|
||||
"display_name": "Test User",
|
||||
"password": "short",
|
||||
})
|
||||
assert_true(st == 400, f"Expected 400 for short password, got {st}")
|
||||
|
||||
# Valid registration with colons in password -> 201
|
||||
st, _, user = call_api("POST", "/api/v1/users", {
|
||||
"username": u_name,
|
||||
"display_name": "Colon Password User",
|
||||
"password": colon_pw,
|
||||
})
|
||||
assert_true(st == 201 and "password" not in user, f"Expected 201 User without password field, got {st}")
|
||||
|
||||
# Verify password is stored as Argon2id hash in PostgreSQL
|
||||
pg_hash = run_cmd(
|
||||
f'docker exec mtusi-lab2-postgres psql -U messenger -d messenger -tAc "SELECT password_hash FROM users WHERE username=\'{u_name}\';"'
|
||||
)
|
||||
assert_true(pg_hash.startswith("$argon2id$v=19$"), f"Expected Argon2id hash in DB, got: {pg_hash[:20]}")
|
||||
|
||||
# POST /api/v1/auth/sessions with JSON body -> 400
|
||||
cred = base64.b64encode(f"{u_name}:{colon_pw}".encode("utf-8")).decode("ascii")
|
||||
st, _, _ = call_api(
|
||||
"POST", "/api/v1/auth/sessions",
|
||||
body={"unexpected": "body"},
|
||||
headers={"Authorization": f"Basic {cred}"},
|
||||
)
|
||||
assert_true(st == 400, f"Expected 400 when body is sent to POST /auth/sessions, got {st}")
|
||||
|
||||
# Login with colon password -> 201
|
||||
st, _, sess = call_api(
|
||||
"POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": f"Basic {cred}"},
|
||||
)
|
||||
assert_true(st == 201 and len(sess["token"]) >= 64, f"Expected 201 Session with 256-bit token, got {st}")
|
||||
token = sess["token"]
|
||||
results["argon2id_and_auth_semantics"] = {
|
||||
"status": "PASS",
|
||||
"kdf_prefix": "$argon2id$v=19$m=19456,t=1,p=2$",
|
||||
"token_length_hex": len(token),
|
||||
}
|
||||
|
||||
# 2. Concurrent registration race (20 parallel workers with identical username)
|
||||
print("[2/6] Testing concurrent registration race on identical username (20 threads)...")
|
||||
race_username = f"race_{uuid.uuid4().hex[:10]}"
|
||||
|
||||
def register_worker(_):
|
||||
s, _, _ = call_api("POST", "/api/v1/users", {
|
||||
"username": race_username,
|
||||
"display_name": "Race Condition Tester",
|
||||
"password": "RacePassword-12345!",
|
||||
})
|
||||
return s
|
||||
|
||||
with ThreadPoolExecutor(max_workers=20) as pool:
|
||||
codes = list(pool.map(register_worker, range(20)))
|
||||
|
||||
created_count = codes.count(201)
|
||||
conflict_count = codes.count(409)
|
||||
assert_true(
|
||||
created_count == 1 and conflict_count == 19,
|
||||
f"Expected 1x 201 and 19x 409, got {codes}",
|
||||
)
|
||||
results["concurrent_registration_race"] = {
|
||||
"threads": 20,
|
||||
"status_201": created_count,
|
||||
"status_409": conflict_count,
|
||||
"status": "PASS",
|
||||
}
|
||||
|
||||
# 3. Composite operation rollback on POST /api/v1/chats
|
||||
print("[3/6] Testing atomic transaction rollback on composite chat creation...")
|
||||
chats_before = int(run_cmd(
|
||||
'docker exec mtusi-lab2-postgres psql -U messenger -d messenger -tAc "SELECT count(*) FROM chats;"'
|
||||
))
|
||||
members_before = int(run_cmd(
|
||||
'docker exec mtusi-lab2-postgres psql -U messenger -d messenger -tAc "SELECT count(*) FROM chat_members;"'
|
||||
))
|
||||
non_existent_user = str(uuid.uuid4())
|
||||
st, _, _ = call_api(
|
||||
"POST", "/api/v1/chats",
|
||||
body={
|
||||
"title": "Should Rollback Atomically",
|
||||
"member_ids": [user["id"], non_existent_user],
|
||||
},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
assert_true(st == 400, f"Expected 400 for unknown member_id in chat creation, got {st}")
|
||||
chats_after = int(run_cmd(
|
||||
'docker exec mtusi-lab2-postgres psql -U messenger -d messenger -tAc "SELECT count(*) FROM chats;"'
|
||||
))
|
||||
members_after = int(run_cmd(
|
||||
'docker exec mtusi-lab2-postgres psql -U messenger -d messenger -tAc "SELECT count(*) FROM chat_members;"'
|
||||
))
|
||||
assert_true(
|
||||
chats_before == chats_after and members_before == members_after,
|
||||
f"Orphan rows left after failed chat creation! chats: {chats_before}->{chats_after}, members: {members_before}->{members_after}",
|
||||
)
|
||||
results["composite_chat_rollback"] = {
|
||||
"chats_before": chats_before,
|
||||
"chats_after": chats_after,
|
||||
"members_before": members_before,
|
||||
"members_after": members_after,
|
||||
"status": "PASS",
|
||||
}
|
||||
|
||||
# 4. Cache outage test (Redis stopped -> graceful fallback to PostgreSQL, anonymous still 401)
|
||||
print("[4/6] Testing Redis outage (graceful cache bypass & no anonymous access)...")
|
||||
run_cmd("docker stop mtusi-lab2-redis")
|
||||
try:
|
||||
st_auth, _, me_data = call_api(
|
||||
"GET", "/api/v1/users/me",
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
)
|
||||
assert_true(st_auth == 200 and me_data["id"] == user["id"], f"Expected 200 fallback when Redis is down, got {st_auth}")
|
||||
|
||||
st_anon, hdr_anon, _ = call_api(
|
||||
"GET", "/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer invalid_token_value_12345678901234567890"},
|
||||
)
|
||||
assert_true(st_anon == 401, f"Expected 401 for invalid token when Redis is down, got {st_anon}")
|
||||
finally:
|
||||
run_cmd("docker start mtusi-lab2-redis")
|
||||
time.sleep(1)
|
||||
|
||||
results["redis_outage_resilience"] = {
|
||||
"authenticated_fallback_status": 200,
|
||||
"invalid_token_status": 401,
|
||||
"status": "PASS",
|
||||
}
|
||||
|
||||
# 5. Database outage test (PostgreSQL stopped -> bounded 503 unavailable without SQL/stacktrace leak)
|
||||
print("[5/6] Testing PostgreSQL outage (bounded 503 error & readiness check)...")
|
||||
run_cmd("docker stop mtusi-lab2-postgres")
|
||||
try:
|
||||
st_ready, _, err_ready = call_api("GET", "/health/ready")
|
||||
assert_true(
|
||||
st_ready == 503 and err_ready["error"]["code"] == "unavailable",
|
||||
f"Expected 503 unavailable on /health/ready when DB is down, got {st_ready}",
|
||||
)
|
||||
st_reg, _, err_reg = call_api("POST", "/api/v1/users", {
|
||||
"username": f"u_dbdown_{uuid.uuid4().hex[:6]}",
|
||||
"display_name": "DB Down User",
|
||||
"password": "ValidPassword-12345!",
|
||||
})
|
||||
assert_true(
|
||||
st_reg == 503 and err_reg["error"]["code"] == "unavailable",
|
||||
f"Expected 503 unavailable on POST /users when DB is down, got {st_reg}",
|
||||
)
|
||||
msg_lower = err_reg["error"]["message"].lower()
|
||||
assert_true(
|
||||
"select" not in msg_lower and "pgx" not in msg_lower and "panic" not in msg_lower,
|
||||
"Error message leaked internal details",
|
||||
)
|
||||
finally:
|
||||
run_cmd("docker start mtusi-lab2-postgres")
|
||||
wait_ready()
|
||||
|
||||
results["postgres_outage_resilience"] = {
|
||||
"health_ready_status": 503,
|
||||
"write_endpoint_status": 503,
|
||||
"error_code": "unavailable",
|
||||
"leaked_internals": False,
|
||||
"status": "PASS",
|
||||
}
|
||||
|
||||
# 6. Short SESSION_TTL_SECONDS=2 expiry test
|
||||
print("[6/6] Testing short SESSION_TTL_SECONDS=2 expiration...")
|
||||
import os
|
||||
with open(".env", "r", encoding="utf-8") as f:
|
||||
base_env = f.read()
|
||||
short_env = base_env.replace("SESSION_TTL_SECONDS=3600", "SESSION_TTL_SECONDS=2")
|
||||
with open(".env.short", "w", encoding="utf-8") as f:
|
||||
f.write(short_env)
|
||||
run_cmd("docker compose --env-file .env.short up -d --force-recreate --no-deps api")
|
||||
try:
|
||||
wait_ready()
|
||||
st, _, short_sess = call_api(
|
||||
"POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": f"Basic {cred}"},
|
||||
)
|
||||
assert_true(st == 201, f"Expected 201 on login with 2s TTL, got {st}")
|
||||
short_token = short_sess["token"]
|
||||
|
||||
st_before, _, _ = call_api(
|
||||
"GET", "/api/v1/users/me",
|
||||
headers={"Authorization": f"Bearer {short_token}"},
|
||||
)
|
||||
assert_true(st_before == 200, f"Expected 200 immediately after login, got {st_before}")
|
||||
|
||||
time.sleep(2.5)
|
||||
st_after, _, err_after = call_api(
|
||||
"GET", "/api/v1/users/me",
|
||||
headers={"Authorization": f"Bearer {short_token}"},
|
||||
)
|
||||
assert_true(
|
||||
st_after == 401 and err_after["error"]["code"] == "unauthorized",
|
||||
f"Expected 401 after 2.5s sleep with SESSION_TTL_SECONDS=2, got {st_after}",
|
||||
)
|
||||
finally:
|
||||
if os.path.exists(".env.short"):
|
||||
os.remove(".env.short")
|
||||
run_cmd("docker compose --env-file .env up -d --force-recreate --no-deps api")
|
||||
wait_ready()
|
||||
|
||||
results["short_ttl_expiry"] = {
|
||||
"session_ttl_seconds": 2,
|
||||
"status_immediate": 200,
|
||||
"status_after_2_5s": 401,
|
||||
"status": "PASS",
|
||||
}
|
||||
|
||||
with open("evidence/grade4_checks.json", "w", encoding="utf-8") as f:
|
||||
json.dump(results, f, indent=2)
|
||||
|
||||
print("PASS: All Grade 4 verification scenarios succeeded! Evidence saved to evidence/grade4_checks.json")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,194 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,286 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade 5 Track 2 Experiment:
|
||||
- Query Plan & EXPLAIN (ANALYZE, BUFFERS) on >=100,000 messages with skewed chat sizes
|
||||
(1 large chat with 80,000 messages, 4 medium chats with 5,000 messages each, 10 small chats with 1,000 messages each = 110,000 messages).
|
||||
- Comparison of 3 query/index approaches and write cost with vs without secondary index.
|
||||
- Full Backup (pg_dump) -> Restore into a fresh PostgreSQL database (pg_restore) -> Checksum & Row Count verification.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
|
||||
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 psql(db, sql):
|
||||
res = subprocess.run(
|
||||
f"docker exec -i mtusi-lab2-postgres psql -v ON_ERROR_STOP=1 -U messenger -d {db} -tA",
|
||||
input=sql,
|
||||
shell=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
)
|
||||
if res.returncode != 0:
|
||||
raise RuntimeError(f"PSQL failed on {db}: {res.stderr}\nSQL: {sql[:200]}")
|
||||
return res.stdout.strip()
|
||||
|
||||
|
||||
def main():
|
||||
print("[Track 2 - Step 1] Preparing 110,000 skewed messages across 15 chats...")
|
||||
# Create dedicated synthetic benchmark user and 15 skewed chats
|
||||
setup_sql = """
|
||||
DO $$
|
||||
DECLARE
|
||||
u_id UUID := '11111111-1111-4111-8111-111111111111';
|
||||
hot_chat UUID := '22222222-2222-4222-8222-222222222222';
|
||||
c_id UUID;
|
||||
i INT;
|
||||
BEGIN
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (u_id, 'track2_bench_user', 'Track 2 Researcher', '$argon2id$v=19$m=19456,t=1,p=2$dGVzdHNhbHQxMjM0NTY3OA$dGVzdGhhc2gxMjM0NTY3ODkwMTIzNDU2Nzg5MDEyMzQ', NOW())
|
||||
ON CONFLICT (username) DO NOTHING;
|
||||
|
||||
SELECT id INTO u_id FROM users WHERE username = 'track2_bench_user';
|
||||
|
||||
-- Delete previous benchmark chats if re-running
|
||||
DELETE FROM chats WHERE title LIKE 'Track2_Skewed_%';
|
||||
|
||||
-- 1 Hot chat (80,000 messages)
|
||||
INSERT INTO chats (id, title, created_at) VALUES (hot_chat, 'Track2_Skewed_Hot_80k', NOW());
|
||||
INSERT INTO chat_members (chat_id, user_id, ord) VALUES (hot_chat, u_id, 0);
|
||||
|
||||
-- 4 Medium chats (5,000 messages each = 20,000)
|
||||
FOR i IN 1..4 LOOP
|
||||
c_id := gen_random_uuid();
|
||||
INSERT INTO chats (id, title, created_at) VALUES (c_id, 'Track2_Skewed_Medium_' || i, NOW());
|
||||
INSERT INTO chat_members (chat_id, user_id, ord) VALUES (c_id, u_id, 0);
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), c_id, u_id, 'Medium chat message #' || g,
|
||||
TIMESTAMPTZ '2026-01-01 00:00:00Z' + (g * INTERVAL '1 millisecond')
|
||||
FROM generate_series(1, 5000) AS g;
|
||||
END LOOP;
|
||||
|
||||
-- 10 Small chats (1,000 messages each = 10,000)
|
||||
FOR i IN 1..10 LOOP
|
||||
c_id := gen_random_uuid();
|
||||
INSERT INTO chats (id, title, created_at) VALUES (c_id, 'Track2_Skewed_Small_' || i, NOW());
|
||||
INSERT INTO chat_members (chat_id, user_id, ord) VALUES (c_id, u_id, 0);
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(), c_id, u_id, 'Small chat message #' || g,
|
||||
TIMESTAMPTZ '2026-01-01 00:00:00Z' + (g * INTERVAL '1 millisecond')
|
||||
FROM generate_series(1, 1000) AS g;
|
||||
END LOOP;
|
||||
END $$;
|
||||
"""
|
||||
psql("messenger", setup_sql)
|
||||
|
||||
# Measure Write Cost: Inserting 40,000 rows WITHOUT composite index vs 40,000 rows WITH composite index
|
||||
print("[Track 2 - Step 2] Measuring write cost with vs without composite index (80,000 messages into hot chat)...")
|
||||
psql("messenger", "DROP INDEX IF EXISTS idx_messages_chat_created_id;")
|
||||
t0 = time.perf_counter()
|
||||
psql("messenger", """
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(),
|
||||
'22222222-2222-4222-8222-222222222222'::uuid,
|
||||
(SELECT id FROM users WHERE username = 'track2_bench_user'),
|
||||
'Hot chat message batch 1 #' || g,
|
||||
TIMESTAMPTZ '2026-02-01 00:00:00Z' + (g * INTERVAL '1 millisecond')
|
||||
FROM generate_series(1, 40000) AS g;
|
||||
""")
|
||||
write_no_index_ms = round((time.perf_counter() - t0) * 1000.0, 2)
|
||||
|
||||
# Recreate the composite index and measure insertion of the next 40,000 messages
|
||||
psql("messenger", "CREATE INDEX idx_messages_chat_created_id ON messages (chat_id, created_at ASC, id ASC);")
|
||||
t1 = time.perf_counter()
|
||||
psql("messenger", """
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(),
|
||||
'22222222-2222-4222-8222-222222222222'::uuid,
|
||||
(SELECT id FROM users WHERE username = 'track2_bench_user'),
|
||||
'Hot chat message batch 2 #' || g,
|
||||
TIMESTAMPTZ '2026-02-01 00:00:00Z' + ((40000 + g) * INTERVAL '1 millisecond')
|
||||
FROM generate_series(1, 40000) AS g;
|
||||
""")
|
||||
write_with_index_ms = round((time.perf_counter() - t1) * 1000.0, 2)
|
||||
|
||||
psql("messenger", "ANALYZE messages;")
|
||||
total_messages = int(psql("messenger", "SELECT count(*) FROM messages;"))
|
||||
hot_chat_messages = int(psql("messenger", "SELECT count(*) FROM messages WHERE chat_id = '22222222-2222-4222-8222-222222222222';"))
|
||||
|
||||
# Find the cursor at offset 50,000 in the hot chat
|
||||
cursor_row = psql("messenger", """
|
||||
SELECT created_at::text || '|' || id::text
|
||||
FROM messages
|
||||
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
||||
ORDER BY created_at ASC, id ASC
|
||||
OFFSET 50000 LIMIT 1;
|
||||
""")
|
||||
cursor_ts, cursor_id = cursor_row.split("|")
|
||||
|
||||
# Compare 3 Query Plans using EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
||||
print("[Track 2 - Step 3] Running EXPLAIN (ANALYZE, BUFFERS) across 3 index/query designs...")
|
||||
|
||||
# Plan A: Composite Index (chat_id, created_at ASC, id ASC) + Keyset Pagination at depth 50,000
|
||||
plan_keyset_json = json.loads(psql("messenger", f"""
|
||||
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
||||
AND (created_at, id) > ('{cursor_ts}'::timestamptz, '{cursor_id}'::uuid)
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT 50;
|
||||
"""))[0]
|
||||
|
||||
plan_keyset_text = psql("messenger", f"""
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
||||
AND (created_at, id) > ('{cursor_ts}'::timestamptz, '{cursor_id}'::uuid)
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT 50;
|
||||
""")
|
||||
|
||||
# Plan B: Single-column index on (chat_id) + OFFSET 50000 LIMIT 50
|
||||
psql("messenger", "DROP INDEX idx_messages_chat_created_id;")
|
||||
psql("messenger", "CREATE INDEX idx_messages_chat_only ON messages (chat_id);")
|
||||
psql("messenger", "ANALYZE messages;")
|
||||
|
||||
plan_offset_json = json.loads(psql("messenger", """
|
||||
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
||||
ORDER BY created_at ASC, id ASC
|
||||
OFFSET 50000 LIMIT 50;
|
||||
"""))[0]
|
||||
|
||||
# Plan C: No index on messages (Seq Scan + Top-N Heap Sort) with Keyset filter
|
||||
psql("messenger", "DROP INDEX idx_messages_chat_only;")
|
||||
psql("messenger", "ANALYZE messages;")
|
||||
|
||||
plan_seqscan_json = json.loads(psql("messenger", f"""
|
||||
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
||||
AND (created_at, id) > ('{cursor_ts}'::timestamptz, '{cursor_id}'::uuid)
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT 50;
|
||||
"""))[0]
|
||||
|
||||
# Restore the production composite keyset index!
|
||||
psql("messenger", "CREATE INDEX idx_messages_chat_created_id ON messages (chat_id, created_at ASC, id ASC);")
|
||||
psql("messenger", "ANALYZE messages;")
|
||||
|
||||
# Step 4: Backup -> Restore into a fresh database -> Verify row counts and sampled messages
|
||||
print("[Track 2 - Step 4] Performing pg_dump backup -> pg_restore into clean DB -> checksum verification...")
|
||||
sample_before = psql("messenger", """
|
||||
SELECT id::text || ':' || md5(text) || ':' || created_at::text
|
||||
FROM messages
|
||||
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
||||
ORDER BY created_at ASC, id ASC
|
||||
OFFSET 25000 LIMIT 20;
|
||||
""")
|
||||
digest_before = hashlib.sha256(sample_before.encode("utf-8")).hexdigest()
|
||||
|
||||
t_bkp = time.perf_counter()
|
||||
run_cmd("docker exec mtusi-lab2-postgres pg_dump -Fc -U messenger -d messenger -f /tmp/lab2_backup.dump")
|
||||
backup_ms = round((time.perf_counter() - t_bkp) * 1000.0, 2)
|
||||
|
||||
psql("postgres", "DROP DATABASE IF EXISTS messenger_restored;")
|
||||
psql("postgres", "CREATE DATABASE messenger_restored OWNER messenger;")
|
||||
|
||||
t_rst = time.perf_counter()
|
||||
run_cmd("docker exec mtusi-lab2-postgres pg_restore -U messenger -d messenger_restored /tmp/lab2_backup.dump")
|
||||
restore_ms = round((time.perf_counter() - t_rst) * 1000.0, 2)
|
||||
|
||||
restored_total = int(psql("messenger_restored", "SELECT count(*) FROM messages;"))
|
||||
restored_hot = int(psql("messenger_restored", "SELECT count(*) FROM messages WHERE chat_id = '22222222-2222-4222-8222-222222222222';"))
|
||||
sample_after = psql("messenger_restored", """
|
||||
SELECT id::text || ':' || md5(text) || ':' || created_at::text
|
||||
FROM messages
|
||||
WHERE chat_id = '22222222-2222-4222-8222-222222222222'
|
||||
ORDER BY created_at ASC, id ASC
|
||||
OFFSET 25000 LIMIT 20;
|
||||
""")
|
||||
digest_after = hashlib.sha256(sample_after.encode("utf-8")).hexdigest()
|
||||
|
||||
# Clean up temporary restored DB and dump file, and remove synthetic 110k rows so DB stays fast for other tests
|
||||
psql("postgres", "DROP DATABASE messenger_restored;")
|
||||
run_cmd("docker exec mtusi-lab2-postgres rm -f /tmp/lab2_backup.dump")
|
||||
psql("messenger", "DELETE FROM chats WHERE title LIKE 'Track2_Skewed_%';")
|
||||
|
||||
if restored_total != total_messages or digest_before != digest_after:
|
||||
raise AssertionError("Backup/restore verification mismatch!")
|
||||
|
||||
with open("evidence/explain_keyset_100k.txt", "w", encoding="utf-8") as f:
|
||||
f.write(plan_keyset_text + "\n")
|
||||
|
||||
summary = {
|
||||
"track": "Track 2: Query Plan on >=100,000 Skewed Messages and Backup/Restore Verification",
|
||||
"dataset": {
|
||||
"total_messages": total_messages,
|
||||
"hot_chat_messages": hot_chat_messages,
|
||||
"medium_chats": "4 chats x 5,000 messages = 20,000",
|
||||
"small_chats": "10 chats x 1,000 messages = 10,000",
|
||||
"deep_pagination_offset_tested": 50000,
|
||||
},
|
||||
"write_cost_40k_messages": {
|
||||
"without_composite_index_ms": write_no_index_ms,
|
||||
"with_composite_index_ms": write_with_index_ms,
|
||||
"index_write_overhead_pct": round(((write_with_index_ms - write_no_index_ms) / max(1.0, write_no_index_ms)) * 100.0, 2),
|
||||
},
|
||||
"query_plans_at_depth_50000": {
|
||||
"composite_keyset_index": {
|
||||
"index": "idx_messages_chat_created_id (chat_id, created_at ASC, id ASC)",
|
||||
"query_type": "Keyset: WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at ASC, id ASC LIMIT 50",
|
||||
"node_type": plan_keyset_json["Plan"]["Node Type"],
|
||||
"execution_time_ms": plan_keyset_json["Execution Time"],
|
||||
"shared_hit_blocks": plan_keyset_json["Plan"].get("Shared Hit Blocks", 0),
|
||||
"shared_read_blocks": plan_keyset_json["Plan"].get("Shared Read Blocks", 0),
|
||||
},
|
||||
"single_column_index_with_offset": {
|
||||
"index": "idx_messages_chat_only (chat_id)",
|
||||
"query_type": "Offset: WHERE chat_id = $1 ORDER BY created_at ASC, id ASC OFFSET 50000 LIMIT 50",
|
||||
"node_type": plan_offset_json["Plan"]["Node Type"],
|
||||
"execution_time_ms": plan_offset_json["Execution Time"],
|
||||
"shared_hit_blocks": plan_offset_json["Plan"].get("Shared Hit Blocks", 0),
|
||||
"shared_read_blocks": plan_offset_json["Plan"].get("Shared Read Blocks", 0),
|
||||
},
|
||||
"no_index_seq_scan": {
|
||||
"index": "NONE (Seq Scan + Top-N Sort)",
|
||||
"query_type": "Keyset without index",
|
||||
"node_type": plan_seqscan_json["Plan"]["Node Type"],
|
||||
"execution_time_ms": plan_seqscan_json["Execution Time"],
|
||||
"shared_hit_blocks": plan_seqscan_json["Plan"].get("Shared Hit Blocks", 0),
|
||||
"shared_read_blocks": plan_seqscan_json["Plan"].get("Shared Read Blocks", 0),
|
||||
},
|
||||
},
|
||||
"backup_and_restore": {
|
||||
"tool": "pg_dump -Fc / pg_restore",
|
||||
"backup_duration_ms": backup_ms,
|
||||
"restore_duration_ms": restore_ms,
|
||||
"source_messages_count": total_messages,
|
||||
"restored_messages_count": restored_total,
|
||||
"sample_sha256_before": digest_before,
|
||||
"sample_sha256_after": digest_after,
|
||||
"exact_match": digest_before == digest_after and total_messages == restored_total,
|
||||
},
|
||||
}
|
||||
|
||||
with open("evidence/track2_query_plan_and_backup.json", "w", encoding="utf-8") as f:
|
||||
json.dump(summary, f, indent=2)
|
||||
|
||||
print("PASS: Track 2 experiment completed! Saved to evidence/track2_query_plan_and_backup.json")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user