#!/usr/bin/env python3 """Lab 6 level 4: controlled incidents under load, found and timed with the STORED observations. python bench/incidents.py worker-stop # (1) worker stopped -> queue lag alert -> resolved python bench/incidents.py db-lock # (2a) slow/blocked database (table lock held 90 s) python bench/incidents.py slow-handler # (2b) contrast: slow handler code, healthy database python bench/incidents.py backend-down # (3a) Tempo + Loki stopped: API unaffected, Collector bounded python bench/incidents.py collector-down # (3b) Collector stopped: SDK queues bounded, API unaffected python bench/incidents.py all Results: evidence/incidents/.json (timeline, alert times, metric snapshots, client counts) and .txt (human-readable). Every incident restores the stand in `finally`. Load during every incident (own threads, fixed pacing): 4 writers posting messages (~8 req/s in total) and 1 uploader (one PNG every 2 s). Client-side counts are kept separately from the telemetry, so the effect of an incident on users is measured independently of it. """ from __future__ import annotations import argparse import base64 import json import os import secrets import subprocess import sys import threading import time import urllib.error import urllib.request import uuid from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "scripts")) import obs # noqa: E402 BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/") + "/api/v1" OUT = ROOT / "evidence" / "incidents" SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() # ----------------------------------------------------------------------------- HTTP + load def http(method: str, path: str, body=None, headers=None, raw: bytes | None = None, timeout: float = 15): h = dict(headers or {}) data = raw if body is not None: data = json.dumps(body).encode() h["Content-Type"] = "application/json" request = urllib.request.Request(BASE + path, data=data, method=method, headers=h) try: with urllib.request.urlopen(request, timeout=timeout) as r: return r.status, r.headers, json.loads(r.read() or b"null") except urllib.error.HTTPError as exc: return exc.code, exc.headers, None def new_actor() -> dict: username = "inc_" + uuid.uuid4().hex[:12] password = "Incident-" + secrets.token_hex(8) _, _, user = http("POST", "/users", {"username": username, "display_name": "load", "password": password}) auth = "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode() _, _, session = http("POST", "/auth/sessions", headers={"Authorization": auth}) headers = {"Authorization": "Bearer " + session["token"]} _, _, chat = http("POST", "/chats", {"title": "incident load", "member_ids": [user["id"]]}, headers) return {"headers": headers, "chat": chat["id"]} class Load: """Background traffic; per-second client-side outcome counts (status classes, timeouts).""" def __init__(self, writers: int = 4, write_interval: float = 0.5, upload_interval: float = 2.0): self.actors = [new_actor() for _ in range(writers + 1)] self.write_interval, self.upload_interval = write_interval, upload_interval self.stop = threading.Event() self.lock = threading.Lock() self.events: list[tuple[float, str, int, float]] = [] # (time, kind, status, latency) self.uploads: list[tuple[float, str]] = [] # (accepted at, attachment id) self.threads = [threading.Thread(target=self.writer, args=(a,), daemon=True) for a in self.actors[:-1]] self.threads.append(threading.Thread(target=self.uploader, args=(self.actors[-1],), daemon=True)) def record(self, kind: str, status: int, began: float) -> None: with self.lock: self.events.append((time.time(), kind, status, time.perf_counter() - began)) def writer(self, actor: dict) -> None: while not self.stop.is_set(): began = time.perf_counter() try: status, _, _ = http("POST", f"/chats/{actor['chat']}/messages", {"text": "load"}, {**actor["headers"], "Idempotency-Key": uuid.uuid4().hex}, timeout=10) except Exception: # noqa: BLE001 - timeout / connection error status = 0 self.record("message", status, began) self.stop.wait(max(0.0, self.write_interval - (time.perf_counter() - began))) def uploader(self, actor: dict) -> None: while not self.stop.is_set(): began = time.perf_counter() try: status, _, body = http("POST", f"/chats/{actor['chat']}/attachments?filename=load.png", raw=SAMPLE, headers={**actor["headers"], "Content-Type": "image/png"}, timeout=15) if status == 202: with self.lock: self.uploads.append((time.time(), body["id"])) except Exception: # noqa: BLE001 status = 0 self.record("upload", status, began) self.stop.wait(max(0.0, self.upload_interval - (time.perf_counter() - began))) def __enter__(self): for t in self.threads: t.start() return self def __exit__(self, *exc): self.stop.set() for t in self.threads: t.join(20) def summary(self, start: float, end: float) -> dict: with self.lock: ev = [e for e in self.events if start <= e[0] < end] out = {} for kind in ("message", "upload"): rows = [e for e in ev if e[1] == kind] lat = sorted(e[3] for e in rows if 200 <= e[2] < 300) out[kind] = {"total": len(rows), "2xx": sum(200 <= e[2] < 300 for e in rows), "4xx": sum(400 <= e[2] < 500 for e in rows), "5xx": sum(e[2] >= 500 for e in rows), "no_response": sum(e[2] == 0 for e in rows), "p50_ms": _pct(lat, 0.50), "p95_ms": _pct(lat, 0.95), "p99_ms": _pct(lat, 0.99)} return out def _pct(values: list[float], q: float): if not values: return None return round(values[min(len(values) - 1, int(q * len(values)))] * 1000, 1) # ----------------------------------------------------------------------------- stand control def compose(*args: str, timeout: float = 180) -> str: return subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True, encoding="utf-8", timeout=timeout, check=True).stdout def docker_mem(service: str) -> float | None: """Current memory (MiB) of a compose service's first container, from `docker stats`.""" ids = compose("ps", "-q", service).split() if not ids: return None raw = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", ids[0]], capture_output=True, text=True).stdout.split("/")[0].strip() num = float("".join(c for c in raw if c.isdigit() or c == ".")) return round(num / 1024 if raw.endswith("KiB") else num * 1024 if raw.endswith("GiB") else num, 1) class Timeline: def __init__(self, name: str): self.name = name self.t0 = time.time() self.rows: list[dict] = [] self.lines: list[str] = [] def mark(self, what: str, **data) -> float: now = time.time() self.rows.append({"t": round(now - self.t0, 1), "event": what, **data}) line = f"+{now - self.t0:7.1f} s {what}" + (f" {json.dumps(data, ensure_ascii=False)}" if data else "") print(line, flush=True) self.lines.append(line) return now def wait_alert(tl: Timeline, alert: str, state: str, since: float, timeout: float) -> float | None: """Poll Prometheus every 2 s; returns seconds from `since` to the alert reaching `state`.""" deadline = time.time() + timeout last = None while time.time() < deadline: current = obs.alert_state(alert) if current != last: tl.mark(f"alert {alert}: {current}") last = current if (state == "resolved" and current == "inactive") or current == state: return round(time.time() - since, 1) time.sleep(2) tl.mark(f"alert {alert}: still {last} after {timeout} s") return None def wait_quiet(tl: Timeline, timeout: float = 420) -> None: """Start every incident from a calm stand: no alert pending/firing (a previous incident's alert would otherwise make the detection time look like 0 s).""" deadline = time.time() + timeout while time.time() < deadline: active = [a["name"] for a in obs.alerts()] if not active: tl.mark("stand quiet: no pending/firing alerts") return time.sleep(5) raise SystemExit(f"alerts still active after {timeout} s: {active}") def snapshot(queries: dict[str, str]) -> dict: out = {} for name, expr in queries.items(): try: value = obs.scalar(expr) out[name] = None if value is None else round(value, 4) except Exception as exc: # noqa: BLE001 out[name] = f"error: {type(exc).__name__}" return out Q_API = { "rps": "messenger:http_requests:rate1m", "error_ratio_5xx": "messenger:http_error_ratio:rate1m", "p99_s": "messenger:http_latency:p99_2m", "db_p95_s_api": 'histogram_quantile(0.95, sum by (le) (rate(db_client_operation_duration_seconds_bucket{job="messenger-api"}[1m])))', "db_pool_waiting_api": 'sum(db_client_connection_pending_requests{job="messenger-api"})', "db_pool_used_api": 'sum(db_client_connection_count{job="messenger-api", db_client_connection_state="used"})', } Q_QUEUE = { "queued": 'max(messenger_queue_depth{state="queued"})', "oldest_age_s": "max(messenger_queue_oldest_age_seconds)", "jobs_succeeded_per_s": 'sum(rate(messenger_jobs_processed_total{outcome="succeeded"}[1m]))', "worker_busy": "sum(messenger_worker_busy)", "time_to_ready_p95_s": 'histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[2m])))', } Q_COLLECTOR = { "collector_rss_mib": "otelcol_process_memory_rss / 1048576", "spans_accepted_per_s": "sum(rate(otelcol_receiver_accepted_spans[1m]))", "spans_failed_total": "sum(otelcol_exporter_send_failed_spans) or vector(0)", "logs_failed_total": "sum(otelcol_exporter_send_failed_log_records) or vector(0)", "queue_size_tempo": 'max(otelcol_exporter_queue_size{exporter="otlp_http/tempo"})', "queue_capacity_tempo": 'max(otelcol_exporter_queue_capacity{exporter="otlp_http/tempo"})', "sdk_export_failures_total": 'sum(messenger_telemetry_spans_exported_total{result="failure"}) or vector(0)', } # ----------------------------------------------------------------------------- incidents def worker_stop(tl: Timeline, load: Load) -> dict: """(1) The worker is stopped: uploads still get 202, nothing is processed. Expected: queue depth and the oldest job age grow -> MessengerQueueLagGrowing firing; after the start the backlog drains -> resolved. HTTP SLIs stay green (the API does not depend on the worker).""" time.sleep(30) result = {"before": {**snapshot(Q_API), **snapshot(Q_QUEUE)}} start = tl.mark("FAULT: docker compose stop worker") compose("stop", "worker") try: result["detect_s"] = wait_alert(tl, "MessengerQueueLagGrowing", "firing", start, 240) result["during"] = {**snapshot(Q_API), **snapshot(Q_QUEUE)} result["during_client"] = load.summary(start, time.time()) tl.mark("observed during", **result["during"]) finally: fixed = tl.mark("FIX: docker compose start worker") compose("start", "worker") result["resolve_s"] = wait_alert(tl, "MessengerQueueLagGrowing", "resolved", fixed, 300) result["after"] = {**snapshot(Q_API), **snapshot(Q_QUEUE)} tl.mark("observed after", **result["after"]) result["client_total"] = load.summary(tl.t0, time.time()) return result def db_lock(tl: Timeline, load: Load) -> dict: """(2a) A long transaction holds an EXCLUSIVE lock on `messages` for 150 s (an "ALTER TABLE"/ migration-like incident). Message writes wait for the lock until lock_timeout and answer 503; reads keep working. Expected: 5xx ratio and p99 grow, DB pool waits; the trace of a failed POST shows the time inside the `db ...` span (error LockNotAvailable), not in handler code.""" time.sleep(30) result = {"before": snapshot(Q_API)} sql = "BEGIN; LOCK TABLE messages IN EXCLUSIVE MODE; SELECT pg_sleep(150); COMMIT;" start = tl.mark("FAULT: psql holds LOCK TABLE messages IN EXCLUSIVE MODE for 150 s") locker = subprocess.Popen(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c", sql], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) try: result["detect_error_s"] = wait_alert(tl, "MessengerApiHighErrorRate", "firing", start, 140) result["during"] = snapshot(Q_API) tl.mark("observed during", **result["during"]) result["during_client"] = load.summary(start, time.time()) result["example_trace"] = example_trace('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && status = error }') result["pg_locks"] = subprocess.run( ["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", "SELECT state, wait_event_type, wait_event, count(*), max(now() - xact_start)::text " "FROM pg_stat_activity WHERE datname = 'messenger' AND state <> 'idle' GROUP BY 1, 2, 3"], cwd=ROOT, capture_output=True, text=True, encoding="utf-8").stdout.strip().splitlines() tl.mark("pg_stat_activity lock waits", waits=result["pg_locks"]) finally: locker.wait(200) fixed = tl.mark("FIX: lock released (transaction ended)") result["resolve_s"] = wait_alert(tl, "MessengerApiHighErrorRate", "resolved", fixed, 240) result["after"] = snapshot(Q_API) result["client_total"] = load.summary(tl.t0, time.time()) return result def slow_handler(tl: Timeline, load: Load) -> dict: """(2b) Contrast to (2a): API_FAULT_POINTS=slow_handler=1500 - 1.5 s of handler code before the database call in POST messages, database healthy. Expected: p99 > 1 s -> MessengerApiLatencyHigh, NO 5xx, DB p95 unchanged; the trace shows a 1.5 s server span whose `db` child is a few ms.""" time.sleep(30) result = {"before": snapshot(Q_API)} env = {**os.environ, "API_FAULT_POINTS": "slow_handler=1500"} start = tl.mark("FAULT: api recreated with API_FAULT_POINTS=slow_handler=1500") subprocess.run(["docker", "compose", "up", "-d", "--no-deps", "--wait", "api"], cwd=ROOT, env=env, capture_output=True, check=True, timeout=180) try: result["detect_s"] = wait_alert(tl, "MessengerApiLatencyHigh", "firing", start, 300) result["during"] = snapshot(Q_API) tl.mark("observed during", **result["during"]) result["during_client"] = load.summary(start, time.time()) result["example_trace"] = example_trace('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && duration > 1s }') finally: fixed = tl.mark("FIX: api recreated without fault points") clean = {k: v for k, v in os.environ.items() if k != "API_FAULT_POINTS"} subprocess.run(["docker", "compose", "up", "-d", "--no-deps", "--wait", "api"], cwd=ROOT, env=clean, capture_output=True, check=True, timeout=180) result["resolve_s"] = wait_alert(tl, "MessengerApiLatencyHigh", "resolved", fixed, 300) result["after"] = snapshot(Q_API) result["client_total"] = load.summary(tl.t0, time.time()) return result def backend_down(tl: Timeline, load: Load) -> dict: """(3a) Tempo and Loki stopped for ~4 min. Expected: API/worker unaffected (client counts), the Collector retries into a BOUNDED queue (size <= capacity), then drops and counts (send_failed), its RSS stays under the memory_limiter; TelemetryExportFailing fires.""" time.sleep(20) result = {"before": {**snapshot(Q_API), **snapshot(Q_COLLECTOR)}, "collector_mem_mib": []} start = tl.mark("FAULT: docker compose stop tempo loki") compose("stop", "tempo", "loki") try: # failures appear only after the exporter gave up (retry max_elapsed_time 60 s), then the # 2 min rate window and `for: 30s`: 120-190 s were measured, so wait up to 240 s. result["detect_s"] = wait_alert(tl, "TelemetryExportFailing", "firing", start, 240) while time.time() - start < 250: result["collector_mem_mib"].append(docker_mem("otel-collector")) time.sleep(10) result["during"] = {**snapshot(Q_API), **snapshot(Q_COLLECTOR)} tl.mark("observed during", **result["during"], collector_mem_mib=result["collector_mem_mib"]) result["during_client"] = load.summary(start, time.time()) finally: fixed = tl.mark("FIX: docker compose start tempo loki") compose("start", "tempo", "loki") result["resolve_s"] = wait_alert(tl, "TelemetryExportFailing", "resolved", fixed, 300) result["after"] = {**snapshot(Q_API), **snapshot(Q_COLLECTOR)} result["client_total"] = load.summary(tl.t0, time.time()) return result def collector_down(tl: Timeline, load: Load) -> dict: """(3b) The Collector itself stopped for 2 min. Expected: API unaffected; the SDK exporters fail fast (3 s timeout) in their background threads, BatchSpanProcessor drops beyond 2048 queued spans, API memory flat. Counted afterwards: messenger_telemetry_spans_exported_total{result=failure} (cumulative, delivered once the Collector is back). Metrics of the outage window are missing: a gap in the graphs, not a lie.""" time.sleep(20) api_mem = [] result = {"before": {**snapshot(Q_API), **snapshot(Q_COLLECTOR)}} start = tl.mark("FAULT: docker compose stop otel-collector") compose("stop", "otel-collector") try: while time.time() - start < 120: api_mem.append(docker_mem("api")) time.sleep(10) result["api_mem_mib"] = api_mem result["during_client"] = load.summary(start, time.time()) tl.mark("client during outage", **result["during_client"]["message"], api_mem_mib=api_mem) finally: tl.mark("FIX: docker compose start otel-collector") compose("start", "otel-collector") time.sleep(45) result["after"] = {**snapshot(Q_API), **snapshot(Q_COLLECTOR)} tl.mark("observed after", **result["after"]) result["client_total"] = load.summary(tl.t0, time.time()) return result def example_trace(traceql: str) -> dict | None: """First matching trace: its span tree as text (the diagnosis evidence).""" time.sleep(8) found = obs.search(traceql, minutes=5, limit=5) if not found: return None trace_id = found[0]["traceID"] return {"traceql": traceql, "trace_id": trace_id, "tree": obs.tree(obs.trace_spans(trace_id)).splitlines()} INCIDENTS = {"worker-stop": worker_stop, "db-lock": db_lock, "slow-handler": slow_handler, "backend-down": backend_down, "collector-down": collector_down} def run(name: str) -> dict: print(f"\n=== incident {name}") tl = Timeline(name) wait_quiet(tl) with Load() as load: tl.mark("load started (4 writers x 2 req/s, 1 upload / 2 s)") result = INCIDENTS[name](tl, load) result.update({"incident": name, "timeline": tl.rows, "doc": INCIDENTS[name].__doc__.strip()}) OUT.mkdir(parents=True, exist_ok=True) (OUT / f"{name}.json").write_text(json.dumps(result, indent=1, ensure_ascii=False) + "\n", encoding="utf-8") text = [f"incident {name}: {time.strftime('%Y-%m-%d %H:%M:%S')}", INCIDENTS[name].__doc__.strip(), "", *tl.lines, ""] for key in ("detect_s", "detect_error_s", "resolve_s"): if key in result: text.append(f"{key}: {result[key]}") for key in ("before", "during", "after", "during_client", "client_total"): if key in result: text.append(f"{key}: {json.dumps(result[key], ensure_ascii=False)}") if result.get("example_trace"): text += ["", f"example trace ({result['example_trace']['traceql']}):", *result["example_trace"]["tree"]] (OUT / f"{name}.txt").write_text("\n".join(text) + "\n", encoding="utf-8", newline="\n") return result def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("incident", choices=[*INCIDENTS, "all"]) args = parser.parse_args() for name in (INCIDENTS if args.incident == "all" else [args.incident]): run(name) return 0 if __name__ == "__main__": sys.exit(main())