Files
mtusi2026lab3/student-tests/lab2/run.py
T

450 lines
22 KiB
Python

#!/usr/bin/env python3
"""Opt-in lab2 test/experiment runner. No application or teacher-contract edits."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import contextlib
import importlib.util
import io
import json
import math
import os
from pathlib import Path
import shutil
import signal
import subprocess
import sys
import threading
import time
import types
import unittest
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "tests"))
sys.path.insert(0, str(ROOT / "student-tests"))
from client import Client, Failure, check # noqa: E402
import business # noqa: E402
class Blocked(Exception):
pass
def bounded_command(argv, cwd, timeout, env=None):
"""Never invoke a shell or include command output/credentials in exceptions."""
try:
p = subprocess.Popen(argv, cwd=cwd, env=env, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, start_new_session=True)
except OSError:
raise Blocked("command unavailable; check local tools/adapter") from None
try:
out, _ = p.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
os.killpg(p.pid, signal.SIGTERM)
try:
p.communicate(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(p.pid, signal.SIGKILL)
p.communicate()
raise Failure("command/adapter exceeded its execution budget") from None
if p.returncode == 2:
raise Blocked("adapter reports missing implementation/configuration")
if p.returncode:
raise Failure("command/adapter failed (exit %d); output suppressed" % p.returncode)
return out
def percentiles(values):
check(bool(values), "no successful latency samples")
values = sorted(values)
return {"p" + str(p): round(1000 * values[max(0, math.ceil(len(values) * p / 100) - 1)], 3)
for p in (50, 95, 99)}
def counter_delta(before, after, key):
a, b = before.get(key), after.get(key)
check(isinstance(a, int) and not isinstance(a, bool) and a >= 0 and
isinstance(b, int) and not isinstance(b, bool) and b >= a,
"metrics adapter must return nondecreasing integer counter " + key)
return b - a
def compare_snapshots(source, restored):
for snapshot in (source, restored):
tables = snapshot.get("tables", {})
check(set(tables) == {"users", "chats", "chat_members", "messages"},
"snapshot must cover all four PostgreSQL application tables")
for value in tables.values():
check(isinstance(value.get("rows"), int) and not isinstance(value["rows"], bool) and value["rows"] >= 0 and
isinstance(value.get("sha256"), str) and len(value["sha256"]) == 64,
"snapshot has invalid counts/content digest")
check(source.get("identity_sha256") != restored.get("identity_sha256"),
"restore target must be a different database/storage endpoint")
check(not source.get("empty") and not restored.get("empty"), "restore contains no application tables")
check(source.get("tables") == restored.get("tables"), "restored table counts or ordered content digests differ")
class Harness:
def __init__(self, config, config_path, allow_hooks=False):
self.c = config
self.directory = config_path.resolve().parent
self.allow_hooks = allow_hooks
def client(self, expiry=False, timeout=None):
key, env = ("expiry_base_url", "LAB2_EXPIRY_BASE_URL") if expiry else ("base_url", "LAB2_BASE_URL")
url = os.environ.get(env) or self.c.get(key)
if not url:
raise Blocked("configure " + key + " for a dedicated synthetic test API")
return Client(url, self.c.get("ca_file"), timeout=timeout or self.c["request_timeout_seconds"])
def require_hooks(self, *names):
if not self.allow_hooks:
raise Blocked("infrastructure adapters require explicit --allow-hooks")
for name in names:
argv = self.c.get("hooks", {}).get(name)
if not isinstance(argv, list) or not argv or not all(isinstance(x, str) and x for x in argv):
raise Blocked("configure executable argv array for hook " + name)
def hook(self, name, metrics=False):
self.require_hooks(name)
out = bounded_command(self.c["hooks"][name], self.directory, self.c["hook_timeout_seconds"])
if metrics:
check(len(out) <= 65536, "metrics adapter output exceeds limit")
try:
value = json.loads(out)
except ValueError:
raise Failure("metrics adapter must output one JSON object") from None
check(isinstance(value, dict), "metrics adapter must output a JSON object")
# Only these numeric counters may enter evidence, never raw adapter output.
return {key: value.get(key) for key in ("sql_queries", "cache_hits")}
@contextlib.contextmanager
def disruption(self, failure, recovery):
self.require_hooks(failure, recovery)
try:
self.hook(failure)
yield
finally:
self.hook(recovery)
def wait_ready(self):
deadline = time.monotonic() + self.c["hook_timeout_seconds"]
while True:
try:
self.client(timeout=2).call("GET", "/health/ready", schema="Health")
return
except Failure:
check(time.monotonic() < deadline, "API did not recover readiness")
time.sleep(.2)
def auth_module(self, expiry=False):
spec = importlib.util.spec_from_file_location("lab2_auth_existing", ROOT / "student-tests/auth_contract.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
module.ARGS = types.SimpleNamespace(
base_url=self.client(expiry=expiry).base, ca_file=self.c.get("ca_file"),
timeout=self.c["request_timeout_seconds"], ttl=self.c["ttl_seconds"],
hook_timeout=self.c["hook_timeout_seconds"], restart_hook="restart_stack",
failure_hook=None, recovery_hook=None, dependency=None, cache_policy=self.c.get("cache_policy"), session_store="redis")
module.hook = self.hook
return module
def auth(self, suite):
if suite == "persistence":
self.require_hooks("restart_stack")
module = self.auth_module(expiry=suite == "expiry")
if suite == "auth":
result = unittest.TextTestRunner(stream=io.StringIO()).run(
unittest.defaultTestLoader.loadTestsFromTestCase(module.AuthContract))
check(result.wasSuccessful(), "auth tests failed: " + ", ".join(t._testMethodName for t, _ in result.failures + result.errors))
return {"tests": result.testsRun}
if suite == "expiry":
module.ARGS.base_url = self.client(expiry=True).base
module.ARGS.ttl = 2
module.expiry()
else:
module.persistence()
def dependency(self, name):
failure, recovery = ("stop_postgres", "start_postgres") if name == "postgres" else ("stop_cache", "start_cache")
self.require_hooks(failure, recovery)
if name == "redis" and self.c.get("cache_policy") not in ("critical", "fallback"):
raise Blocked("declare cache_policy critical or fallback")
module = self.auth_module()
module.ARGS.dependency = name
module.ARGS.failure_hook, module.ARGS.recovery_hook = failure, recovery
module.dependency()
def timeout(self, mode):
failure, recovery = ("block_query", "unblock_query") if mode == "query" else ("exhaust_pool", "release_pool")
self.require_hooks(failure, recovery)
budget = self.c["operation_budget_seconds"]
client = self.client(timeout=budget + 1)
actor = client.user("budget")
with self.disruption(failure, recovery):
client.call("GET", "/health/live", schema="Health")
client.call("GET", "/api/v1/users/me", 401)
started = time.monotonic()
response = client.call("GET", "/api/v1/users/me", 503, actor=actor)
elapsed = time.monotonic() - started
check(elapsed <= budget, "API exceeded configured test operation budget")
check(response["json"]["error"]["code"] == "unavailable", "blocked operation returned wrong error")
self.wait_ready()
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
return {"elapsed_seconds": round(elapsed, 4), "budget_seconds": budget, "mode": mode}
def cache_read(self, client, actor, chat):
target = self.c.get("cache_target")
if target == "history":
return client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", actor=actor, schema="MessagePage")
if target == "chat":
return client.call("GET", "/api/v1/chats/" + chat["id"], actor=actor, schema="Chat")
if target == "me":
return client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
raise Blocked("adapt cache_target to the actually cached operation")
def cache_usage(self):
self.require_hooks("metrics", "evict_cache")
client = self.client()
actor = client.user("cache_use")
chat = business.room(client, actor)
self.hook("evict_cache")
self.cache_read(client, actor, chat)
before = self.hook("metrics", metrics=True)
for _ in range(self.c["read_repetitions"]):
self.cache_read(client, actor, chat)
after = self.hook("metrics", metrics=True)
hits = counter_delta(before, after, "cache_hits")
check(hits > 0, "no actual cache hit observed on the selected API operation")
return {"cache_hits": hits, "sql_queries": counter_delta(before, after, "sql_queries")}
def cache_restart(self):
self.require_hooks("restart_cache")
client = self.client()
actor, revoked = client.user("cache_restart"), client.user("revoked")
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=revoked)
chat = business.room(client, actor)
original = client.message(actor, chat, "Before cache restart")["json"]
self.cache_read(client, actor, chat)
self.hook("restart_cache")
self.wait_ready()
check(client.call("GET", "/api/v1/users/me", actor=actor, schema="User")["json"] == actor["user"], "cache restart lost session")
client.call("GET", "/api/v1/users/me", 401, actor=revoked)
check(original in business.history(client, actor, chat), "cache restart lost confirmed message")
def cache_experiment(self):
self.require_hooks("metrics", "evict_cache", "prepare_cache_baseline", "prepare_cache_protected", "restart_cache")
scenario = self.c["cache_experiment"].get("scenario")
if scenario not in ("stale_read", "stampede"):
raise Blocked("choose cache_experiment.scenario stale_read or stampede")
limit = self.c["cache_experiment"].get("max_protected_sql_queries")
if scenario == "stampede" and (not isinstance(limit, int) or isinstance(limit, bool) or limit < 0):
raise Blocked("declare a justified SQL-query budget for the protected stampede workload")
variants = []
for variant in ("baseline", "protected"):
self.hook("prepare_cache_" + variant)
self.wait_ready()
client = self.client()
actor = client.user("experiment")
chat = business.room(client, actor)
self.hook("evict_cache")
before = self.hook("metrics", metrics=True)
timings, lock = [], threading.Lock()
class TimedClient(Client):
def call(inner, *args, **kwargs):
result = super().call(*args, **kwargs)
if args[0] == "GET":
with lock:
timings.append(result["elapsed"])
return result
def factory():
return TimedClient(client.base, self.c.get("ca_file"), timeout=self.c["request_timeout_seconds"])
consistent = True
if scenario == "stale_read":
try:
business.read_after_write(client, factory, self.c["concurrency"])
except Failure as exc:
if variant == "protected" or str(exc) != "confirmed message absent from next read":
raise
consistent = False
else:
barrier = threading.Barrier(self.c["concurrency"])
def read(_):
local = factory()
barrier.wait(timeout=self.c["request_timeout_seconds"])
for _ in range(self.c["read_repetitions"]):
self.cache_read(local, actor, chat)
with ThreadPoolExecutor(max_workers=self.c["concurrency"]) as pool:
list(pool.map(read, range(self.c["concurrency"])))
after = self.hook("metrics", metrics=True)
variants.append({"variant": variant, "consistent": consistent,
"sql_queries": counter_delta(before, after, "sql_queries"),
"cache_hits": counter_delta(before, after, "cache_hits"),
"read_latency_ms": percentiles(timings)})
if scenario == "stale_read":
check(not variants[0]["consistent"] and variants[1]["consistent"], "baseline did not reproduce stale read or protection failed")
else:
check(variants[1]["sql_queries"] <= limit and variants[1]["sql_queries"] < variants[0]["sql_queries"],
"SQL reduction/budget not demonstrated; adapt deterministic stampede adapter")
business.read_after_write(self.client(), self.client, self.c["concurrency"])
self.cache_restart()
return {"scenario": scenario, "variants": variants,
"review": "Repeat under fixed resources; review counter scope and experimental limits."}
def probe(self, mode, restore=False):
if not shutil.which("go"):
raise Blocked("Go toolchain is required for SQL experiments")
sql = self.c["sql"]
variable = sql["restore_database_url_env" if restore else "database_url_env"]
if not os.environ.get(variable):
raise Blocked("set " + variable + " for an explicitly selected test database")
env = dict(os.environ, LAB2_SQL_DATABASE_URL=os.environ[variable])
args = ["go", "run", "./student-tests/lab2/sqlprobe", "-mode", mode,
"-schema", sql["restore_schema" if restore else "source_schema"],
"-rows", str(sql["research_rows"] if mode in ("compare", "seed") else sql["plan_rows"]),
"-scan-budget", str(sql["scan_budget_rows"]), "-repetitions", str(sql["repetitions"])]
out = bounded_command(args, ROOT, 300, env)
try:
return json.loads(out)
except ValueError:
raise Failure("SQL probe did not return valid JSON") from None
def restore(self):
self.require_hooks("backup_database", "restore_database")
source, empty_target = self.probe("snapshot"), self.probe("snapshot", restore=True)
check(source["identity_sha256"] != empty_target["identity_sha256"], "source and restore target are the same database")
check(empty_target["empty"], "restore target must contain no application tables")
check(source["tables"].get("messages", {}).get("rows", 0) >= 100000, "track 2 needs at least 100000 source messages")
started = time.monotonic()
self.hook("backup_database")
backup_seconds = time.monotonic() - started
started = time.monotonic()
self.hook("restore_database")
restore_seconds = time.monotonic() - started
restored = self.probe("snapshot", restore=True)
compare_snapshots(source, restored)
check(source == self.probe("snapshot"), "source changed during backup/restore; quiesce the fixture")
return {"backup_seconds": round(backup_seconds, 4), "restore_seconds": round(restore_seconds, 4),
"tables": restored["tables"], "review": "Document recovery/loss boundaries and verify fresh storage scope."}
SUITES = {
"auth": "Existing normal auth cases",
"business-boundaries": "Title/text/member validation and strict lab2 JSON/UTF-8 cases",
"business-cursors": "Both chat-list and message-history pagination, bound cursors, changing limit and ACL",
"read-after-write": "100 concurrent confirmations from 10 members are visible immediately",
"persistence": "Full restart with original/revoked sessions",
"expiry": "Separate API with actual TTL=2",
"postgres-failure": "Real PostgreSQL outage and recovery",
"cache-usage": "Actual cache hits through an observable API operation",
"cache-failure": "Declared critical/fallback cache outage",
"cache-restart": "Cache restart preserves confirmations and logout",
"query-timeout": "Blocked SQL must produce bounded HTTP 503",
"pool-timeout": "Exhausted application pool must produce bounded HTTP 503",
"sql-plan": "Actual repository SQL on >=10000 rows, including deep pages",
"cache-experiment": "Track 1: reproducible baseline/protection and counters",
"sql-experiment": "Track 2: >=100000 skewed rows, two indexes, read/write costs",
"backup-restore": "Track 2: fresh target, counts and full ordered digests"
}
def execute(h, name):
if name in ("auth", "expiry", "persistence"):
return h.auth(name)
if name == "business-boundaries":
return business.boundaries(h.client())
if name == "business-cursors":
return business.cursors(h.client())
if name == "read-after-write":
return business.read_after_write(h.client(), h.client, h.c["concurrency"])
if name in ("postgres-failure", "cache-failure"):
return h.dependency("postgres" if name == "postgres-failure" else "redis")
if name in ("query-timeout", "pool-timeout"):
return h.timeout("query" if name == "query-timeout" else "pool")
if name == "sql-plan":
return h.probe("plan")
if name == "sql-experiment":
return h.probe("compare")
if name == "backup-restore":
return h.restore()
return getattr(h, name.replace("-", "_"))()
def validate_config(config):
for key in ("request_timeout_seconds", "hook_timeout_seconds", "operation_budget_seconds"):
check(isinstance(config.get(key), (int, float)) and not isinstance(config[key], bool) and config[key] > 0,
"positive numeric config value required: " + key)
for key, low, high in (("concurrency", 1, 32), ("read_repetitions", 1, 1000)):
value = config.get(key)
check(isinstance(value, int) and not isinstance(value, bool) and low <= value <= high, "invalid config value: " + key)
ttl = config.get("ttl_seconds")
check(isinstance(ttl, int) and not isinstance(ttl, bool) and ttl >= 300, "normal suites need ttl_seconds >= 300")
check(config.get("track") in (None, "cache", "sql"), "track must be cache, sql or null")
sql = config["sql"]
for key, minimum in (("plan_rows", 10000), ("research_rows", 100000), ("scan_budget_rows", 1), ("repetitions", 2)):
check(isinstance(sql.get(key), int) and not isinstance(sql[key], bool) and sql[key] >= minimum, "invalid SQL parameter: " + key)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", type=Path, default=Path(__file__).with_name("config.example.json"))
parser.add_argument("--suite", action="append", choices=["all"] + list(SUITES))
parser.add_argument("--list", action="store_true")
parser.add_argument("--allow-hooks", action="store_true")
parser.add_argument("--output", type=Path)
args = parser.parse_args()
if args.list:
for name, purpose in SUITES.items():
print(name + ": " + purpose)
return 0
if not args.suite:
parser.error("choose --suite or --list; no infrastructure actions run by default")
try:
config = json.loads(args.config.read_text())
validate_config(config)
except (OSError, ValueError, KeyError, Failure):
print("BLOCKED: invalid/missing test configuration; credentials suppressed")
return 2
names = list(args.suite)
missing_track = False
if "all" in names:
names = [name for name in SUITES if name not in ("cache-experiment", "sql-experiment", "backup-restore")]
if config["track"] == "cache":
names.append("cache-experiment")
elif config["track"] == "sql":
names.extend(("sql-experiment", "backup-restore"))
else:
missing_track = True
harness, results = Harness(config, args.config, args.allow_hooks), []
for name in names:
started = time.monotonic()
item = {"suite": name}
try:
item.update(status="PASS", observation=execute(harness, name))
except Blocked as exc:
item.update(status="BLOCKED", reason=str(exc))
except Failure as exc:
item.update(status="FAIL", reason=str(exc))
except Exception as exc:
item.update(status="FAIL", reason="test adapter/runtime error (" + type(exc).__name__ + "); details suppressed")
item["duration_seconds"] = round(time.monotonic() - started, 4)
results.append(item)
print(name + ": " + item["status"] + (" — " + item["reason"] if "reason" in item else ""), flush=True)
if missing_track:
results.append({"suite": "research-track", "status": "BLOCKED", "reason": "select exactly one track: cache or sql"})
report = {"scope": "observed automated scenarios, not an automatic grade or manual report/CI review", "results": results}
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
if any(item["status"] == "FAIL" for item in results):
return 1
return 2 if any(item["status"] == "BLOCKED" for item in results) else 0
if __name__ == "__main__":
raise SystemExit(main())