Files
mtusi2026lab7/bench/track1.py
T

362 lines
18 KiB
Python

#!/usr/bin/env python3
"""Track 1 "the price of observability": the same load under four telemetry configurations.
python bench/track1.py --runs 3 --rate 40 --duration 90 --output evidence/track1
python bench/track1.py --configs full,tail --runs 1 # subset, quick check
Configurations (only the telemetry differs; image, limits, load and data are the same):
off OTEL_SDK_DISABLED=true in api/relay/worker (stdout JSON logs only) - baseline
full SDK on, every trace kept (parentbased_always_on, Collector traces-all)
head10 SDK head sampling 10 % (parentbased_traceidratio 0.1), Collector traces-all
tail SDK on 100 %, Collector TAIL sampling: all errors + all traces >= 250 ms + 10 % of the
rest (infra/otel/traces-tail.yaml) - proposed balance
Metrics and logs are NOT sampled in any configuration: the dashboards/alerts stay exact.
Load (open loop, fixed arrival rate, latency measured from the SCHEDULED start of each request,
so a slow server cannot slow down the generator - no coordinated omission): `rate` req/s,
70 % POST message / 30 % GET history page, + 1 upload/s for the worker. Rare events on purpose:
API_FAULT_POINTS=random_5xx=10,random_slow=10 -> ~1 % of POSTs answer 503, ~1 % take +500 ms.
The client counts them exactly; then Tempo is asked how many of them are still findable.
Per run: recreate the services for the configuration, warm up `warmup` s, measure `duration` s,
wait for ingestion, read: client RPS/latency/errors; CPU of api/worker/relay/postgres EXACTLY from
the cgroup counter (`/sys/fs/cgroup/cpu.stat` usage_usec at the start and the end of the window),
CPU of the telemetry stack from its own counters (increase of process_cpu_seconds_total), RAM from
docker stats (sampled every 5 s); GET latency (no faults injected there) as the clean overhead;
Collector counters (accepted / sent / dropped spans, log records, metric points); Tempo/Loki bytes
received; SDK spans recorded/exported; error and slow traces found in Tempo vs injected.
Order of runs: off, full, head10, tail repeated `runs` times (drift spreads over all configs).
"""
from __future__ import annotations
import argparse
import base64
import json
import os
import random
import secrets
import statistics
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import uuid
from concurrent.futures import ThreadPoolExecutor
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"
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
FAULTS = "random_5xx=10,random_slow=10"
CONFIGS = {
"off": {"OTEL_SDK_DISABLED": "true", "OTEL_COLLECTOR_TRACES": "traces-all"},
"full": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER": "parentbased_always_on",
"OTEL_COLLECTOR_TRACES": "traces-all"},
"head10": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER": "parentbased_traceidratio",
"OTEL_TRACES_SAMPLER_ARG": "0.1", "OTEL_COLLECTOR_TRACES": "traces-all"},
"tail": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER": "parentbased_always_on",
"OTEL_COLLECTOR_TRACES": "traces-tail"},
}
WATCHED = ["api", "worker", "relay", "otel-collector", "tempo", "loki", "prometheus", "postgres"]
# ----------------------------------------------------------------------------- stand
def compose_up(env: dict) -> None:
"""`docker compose up` of the telemetry-dependent services; retried: on Windows the CLI itself
sometimes fails to start (exit 0xC0000142) when the desktop session is busy."""
for attempt in range(3):
result = subprocess.run(["docker", "compose", "up", "-d", "--no-deps", "--wait", "otel-collector", "api",
"relay", "worker"], cwd=ROOT, env=env, capture_output=True, timeout=300)
if result.returncode == 0:
return
print(f" compose up failed (exit {result.returncode}), retry {attempt + 1}", flush=True)
time.sleep(10)
raise RuntimeError("docker compose up failed 3 times")
def apply_config(name: str) -> None:
env = {k: v for k, v in os.environ.items() if not k.startswith("OTEL_")}
env.update(CONFIGS[name])
env["API_FAULT_POINTS"] = FAULTS
compose_up(env)
deadline = time.time() + 90
while time.time() < deadline: # LB sees both replicas again
try:
with urllib.request.urlopen(BASE.rsplit("/api/v1", 1)[0] + "/health/ready", timeout=2) as r:
if r.status == 200:
break
except Exception: # noqa: BLE001
pass
time.sleep(1)
time.sleep(5)
def restore() -> None:
env = {k: v for k, v in os.environ.items() if not k.startswith("OTEL_") and k != "API_FAULT_POINTS"}
compose_up(env)
def container_ids() -> dict[str, str]:
out = {}
for service in WATCHED:
ids = subprocess.run(["docker", "compose", "ps", "-q", service], cwd=ROOT, capture_output=True,
text=True).stdout.split()
for i, cid in enumerate(ids):
out[f"{service}-{i + 1}" if len(ids) > 1 else service] = cid
return out
CGROUP_SERVICES = ("api", "worker", "relay", "postgres") # images with a shell (`cat`)
def cgroup_cpu(ids: dict[str, str]) -> dict[str, float]:
"""usage_usec of every application container's cgroup, read in parallel (seconds)."""
out: dict[str, float] = {}
def one(name: str, cid: str) -> None:
raw = subprocess.run(["docker", "exec", cid, "cat", "/sys/fs/cgroup/cpu.stat"], capture_output=True,
text=True, timeout=30).stdout
for line in raw.splitlines():
if line.startswith("usage_usec "):
out[name] = int(line.split()[1]) / 1e6
threads = [threading.Thread(target=one, args=(n, c)) for n, c in ids.items() if n.split("-")[0] in CGROUP_SERVICES]
for t in threads:
t.start()
for t in threads:
t.join(40)
return out
class Stats(threading.Thread):
"""docker stats every 5 s: CPU % (100 = one core) and memory (MiB) per container."""
def __init__(self, ids: dict[str, str]):
super().__init__(daemon=True)
self.ids = ids
self.samples: dict[str, list[tuple[float, float]]] = {k: [] for k in ids}
self.stop = threading.Event()
def run(self) -> None:
names = {v[:12]: k for k, v in self.ids.items()}
while not self.stop.is_set():
raw = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.ID}};{{.CPUPerc}};{{.MemUsage}}",
*self.ids.values()], capture_output=True, text=True).stdout
for line in raw.splitlines():
cid, cpu, mem = line.split(";")
if cid[:12] in names:
self.samples[names[cid[:12]]].append((float(cpu.rstrip("%")), _mib(mem.split("/")[0].strip())))
self.stop.wait(5)
def summary(self) -> dict:
out = {}
for name, rows in self.samples.items():
if rows:
out[name] = {"cpu_pct_avg": round(statistics.mean(r[0] for r in rows), 1),
"mem_mib_avg": round(statistics.mean(r[1] for r in rows), 1),
"mem_mib_max": round(max(r[1] for r in rows), 1)}
return out
def _mib(text: str) -> float:
num = float("".join(c for c in text if c.isdigit() or c == "."))
return num / 1024 if text.endswith("KiB") else num * 1024 if text.endswith("GiB") else num
# ----------------------------------------------------------------------------- load
def http(method, path, body=None, headers=None, raw=None, timeout=10.0):
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, json.loads(r.read() or b"null")
except urllib.error.HTTPError as exc:
exc.read()
return exc.code, None
except Exception: # noqa: BLE001
return 0, None
def actor() -> dict:
username = "t1_" + uuid.uuid4().hex[:12]
password = "Track1-" + secrets.token_hex(8)
_, user = http("POST", "/users", {"username": username, "display_name": "track1", "password": password})
_, session = http("POST", "/auth/sessions",
headers={"Authorization": "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()})
headers = {"Authorization": "Bearer " + session["token"]}
_, chat = http("POST", "/chats", {"title": "track1", "member_ids": [user["id"]]}, headers)
return {"headers": headers, "chat": chat["id"]}
def load(rate: float, seconds: float, warmup: float, ids: dict[str, str]) -> dict:
actors = [actor() for _ in range(8)]
for a in actors: # same history size in every run
for _ in range(20):
http("POST", f"/chats/{a['chat']}/messages", {"text": "seed"}, {**a["headers"], "Idempotency-Key": uuid.uuid4().hex})
results: list[tuple[float, str, int, float]] = []
lock = threading.Lock()
rnd = random.Random(42) # the same request mix in every run
def one(scheduled: float, kind: str, a: dict) -> None:
if kind == "post":
status, _ = http("POST", f"/chats/{a['chat']}/messages", {"text": "load"},
{**a["headers"], "Idempotency-Key": uuid.uuid4().hex})
elif kind == "get":
status, _ = http("GET", f"/chats/{a['chat']}/messages?limit=20", headers=a["headers"])
else:
status, _ = http("POST", f"/chats/{a['chat']}/attachments?filename=t1.png", raw=SAMPLE,
headers={**a["headers"], "Content-Type": "image/png"}, timeout=20)
with lock:
results.append((scheduled, kind, status, time.perf_counter() - scheduled))
total = warmup + seconds
plan = []
for i in range(int(total * rate)):
plan.append((i / rate, "post" if rnd.random() < 0.7 else "get", rnd.randrange(len(actors))))
for i in range(int(total)):
plan.append((i + 0.5, "upload", rnd.randrange(len(actors))))
plan.sort()
start = time.perf_counter()
snap: dict = {}
def snapshot_start() -> None:
snap["t0"], snap["cpu0"] = time.time(), cgroup_cpu(ids)
starter = None
with ThreadPoolExecutor(max_workers=96) as pool:
for offset, kind, idx in plan:
if starter is None and offset >= warmup:
starter = threading.Thread(target=snapshot_start)
starter.start()
delay = start + offset - time.perf_counter()
if delay > 0:
time.sleep(delay)
pool.submit(one, start + offset, kind, actors[idx])
t1, cpu1 = time.time(), cgroup_cpu(ids)
starter.join(60)
measured = [r for r in results if r[0] - start >= warmup]
window_s = t1 - snap["t0"]
out = {"window": [snap["t0"], t1],
"cpu_pct": {name: round(100 * (cpu1[name] - snap["cpu0"][name]) / window_s, 1)
for name in cpu1 if name in snap["cpu0"]}}
for kind in ("post", "get", "upload"):
rows = [r for r in measured if r[1] == kind]
ok = sorted(r[3] for r in rows if 200 <= r[2] < 300)
out[kind] = {"sent": len(rows), "ok": len(ok), "5xx": sum(r[2] >= 500 for r in rows),
"no_response": sum(r[2] == 0 for r in rows),
"ok_rps": round(len(ok) / seconds, 2),
"p50_ms": _pct(ok, .5), "p95_ms": _pct(ok, .95), "p99_ms": _pct(ok, .99),
"slow_over_450ms": sum(1 for r in rows if 200 <= r[2] < 300 and r[3] > 0.45)}
return out
def _pct(values, q):
return round(values[min(len(values) - 1, int(q * len(values)))] * 1000, 1) if values else None
# ----------------------------------------------------------------------------- telemetry side
def increase(expr: str, start: float, end: float) -> float | None:
"""Counter growth inside [start, end]: sum(increase(expr[window])) evaluated at `end`. increase()
handles counter resets (services are recreated for every configuration) and series of old
processes (they do not grow); subtracting two raw sums did not, and gave negative numbers."""
window = max(15, int(round(end - start)))
try:
result = obs.promql(f"sum(increase({expr}[{window}s]))", at=end)
except Exception: # noqa: BLE001
return None
return round(float(result[0]["value"][1]), 1) if result else 0.0
def tempo_count(traceql: str, start: float, end: float) -> int:
end_i, start_i = int(end) + 1, int(start)
try:
found = obs.get("tempo", "api/search", {"q": traceql, "start": start_i, "end": end_i, "limit": 5000},
timeout=60).get("traces", [])
except Exception: # noqa: BLE001
return -1
return len(found)
def telemetry_side(window: list[float], config: str) -> dict:
start, end = window
end_q = end + 25 # counters pushed every 5 s, batch 2 s
return {
"sdk_spans_recorded": increase("messenger_telemetry_spans_ended_total", start, end_q),
"sdk_spans_export_failed": increase('messenger_telemetry_spans_exported_total{result="failure"}', start, end_q),
"collector_spans_accepted": increase("otelcol_receiver_accepted_spans", start, end_q),
"collector_spans_refused": increase("otelcol_receiver_refused_spans", start, end_q),
"collector_spans_sent": increase('otelcol_exporter_sent_spans{exporter="otlp_http/tempo"}', start, end_q),
"collector_spans_send_failed": increase("otelcol_exporter_send_failed_spans", start, end_q),
"collector_logs_accepted": increase("otelcol_receiver_accepted_log_records", start, end_q),
"collector_metric_points_accepted": increase("otelcol_receiver_accepted_metric_points", start, end_q),
"tempo_bytes_received": increase("tempo_distributor_bytes_received_total", start, end_q),
"loki_bytes_received": increase("loki_distributor_bytes_received_total", start, end_q),
# the Collector names its own CPU counter otelcol_process_cpu_seconds (no _total suffix)
"telemetry_cpu_s": {"otel-collector": increase('otelcol_process_cpu_seconds{job="otel-collector"}', start, end_q),
**{job: increase(f'process_cpu_seconds_total{{job="{job}"}}', start, end_q)
for job in ("tempo", "loki", "prometheus")}},
"error_traces_in_tempo": tempo_count('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && span.http.response.status_code = 503 }',
start, end),
"slow_traces_in_tempo": tempo_count('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && kind = server && duration > 450ms }',
start, end),
"server_traces_in_tempo": tempo_count('{ span.http.route = "/api/v1/chats/{chat_id}/messages" && kind = server }', start, end),
}
# ----------------------------------------------------------------------------- main
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--configs", default="off,full,head10,tail")
parser.add_argument("--runs", type=int, default=3)
parser.add_argument("--first-run", type=int, default=1, help="continue an interrupted series (keeps earlier files)")
parser.add_argument("--rate", type=float, default=40)
parser.add_argument("--duration", type=float, default=90)
parser.add_argument("--warmup", type=float, default=20)
parser.add_argument("--output", default="evidence/track1")
args = parser.parse_args()
out_dir = ROOT / args.output
out_dir.mkdir(parents=True, exist_ok=True)
configs = args.configs.split(",")
meta = {"started": time.strftime("%Y-%m-%d %H:%M:%S"), "rate": args.rate, "duration": args.duration,
"warmup": args.warmup, "faults": FAULTS, "configs": {c: CONFIGS[c] for c in configs}}
if args.first_run == 1 or not (out_dir / "meta.json").exists():
(out_dir / "meta.json").write_text(json.dumps(meta, indent=1) + "\n", encoding="utf-8")
try:
for run in range(args.first_run, args.runs + 1):
for config in configs:
print(f"--- run {run} config {config}", flush=True)
apply_config(config)
ids = container_ids()
stats = Stats(ids)
stats.start()
client = load(args.rate, args.duration, args.warmup, ids)
stats.stop.set()
stats.join(15)
time.sleep(30) # ingestion + tail decision_wait + metric push
result = {"config": config, "run": run, "client": client, "resources": stats.summary(),
"telemetry": telemetry_side(client["window"], config)}
(out_dir / f"run{run}-{config}.json").write_text(json.dumps(result, indent=1) + "\n", encoding="utf-8")
c, t = client["post"], result["telemetry"]
print(f" post ok_rps={c['ok_rps']} p50={c['p50_ms']} p95={c['p95_ms']} p99={c['p99_ms']} "
f"5xx={c['5xx']} slow={c['slow_over_450ms']} | get p99={client['get']['p99_ms']} | cpu "
f"{client['cpu_pct']} | "
f"errors in tempo={t.get('error_traces_in_tempo')} slow in tempo={t.get('slow_traces_in_tempo')}",
flush=True)
finally:
restore()
return 0
if __name__ == "__main__":
sys.exit(main())