forked from mtusi2026/mtusi2026lab7
lab7: тесты безопасности и перевод своих тестов на HTTPS, документы (trust-matrix, THREAT_MODEL, OPERATOR, DEFENSE, WINDOWS, PR), сборщик доказательств, чистка legacy bench
This commit is contained in:
@@ -1,141 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 4: stop EACH API replica in turn under load (restoring the previous one first) and
|
||||
measure RPS, errors and recovery. Modes: graceful `stop` (SIGTERM + drain), `kill` (SIGKILL)
|
||||
and `pause` (frozen process: the kernel still accepts TCP, nothing answers - the worst case
|
||||
for detection, only the active health check can find it).
|
||||
|
||||
python bench/failover_series.py --output evidence/failover # ~5 min for 2 replicas x 3 modes
|
||||
|
||||
Timeline of one round (all times from the moment the stop command is issued):
|
||||
warm-up 6 s -> stop replica -> 12 s with it down -> start it again -> wait until HAProxy
|
||||
has every replica UP (rejoin time) -> 6 s steady state.
|
||||
Measured per round: requests/ok/failed and ok-RPS before / during / after, the last failed
|
||||
request (+s), the first moment after which the stopped replica never answered again
|
||||
(= removal from rotation), time until the restarted replica is UP in HAProxy and serves
|
||||
traffic again, plus the history check (no confirmed message lost, no duplicate).
|
||||
Output: <output>/series.json (summary), <output>/timeline-<mode>-<replica>.csv (per second),
|
||||
<output>/series.md (table for REPORT.md). No tokens are written.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import datetime as dt
|
||||
import json
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
sys.path.insert(0, str(ROOT / "bench"))
|
||||
import lbctl # noqa: E402
|
||||
from loadgen import Load # noqa: E402
|
||||
|
||||
|
||||
def docker(*args: str) -> str:
|
||||
return subprocess.run(["docker", *args], capture_output=True, text=True, check=True, timeout=120).stdout
|
||||
|
||||
|
||||
def one_round(replica: dict, mode: str, replicas: int, workers: int, out: Path) -> dict:
|
||||
load = Load(workers).start()
|
||||
time.sleep(6)
|
||||
t_stop = load.now()
|
||||
if mode == "pause":
|
||||
docker("pause", replica["id"])
|
||||
else:
|
||||
docker("stop", "--time", "15" if mode == "stop" else "0", replica["id"])
|
||||
t_stopped = load.now()
|
||||
time.sleep(12)
|
||||
t_start = load.now()
|
||||
docker("unpause" if mode == "pause" else "start", replica["id"])
|
||||
lbctl.wait_up(replicas, timeout=90)
|
||||
t_up = load.now()
|
||||
# The restarted container keeps its hostname: wait until it serves requests again.
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
if any(e[3] == replica["hostname"] and e[0] > t_up for e in load.events):
|
||||
break
|
||||
time.sleep(0.1)
|
||||
t_serves = load.now()
|
||||
time.sleep(6)
|
||||
load.stop()
|
||||
t_end = load.now()
|
||||
|
||||
failed_after_stop = [e for e in load.events if e[0] >= t_stop and e[2] not in (200, 201)]
|
||||
served_by_target = [e[0] for e in load.events if e[3] == replica["hostname"] and t_stop <= e[0] < t_start]
|
||||
out_of_rotation = (max(served_by_target) - t_stop) if served_by_target else 0.0
|
||||
rows = load.per_second()
|
||||
with (out / f"timeline-{mode}-{replica['name']}.csv").open("w", newline="", encoding="utf-8") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=["second", "ok", "failed", "instances"])
|
||||
writer.writeheader()
|
||||
for row in rows:
|
||||
row = dict(row)
|
||||
row["instances"] = row["instances"].replace(replica["hostname"], "TARGET")
|
||||
writer.writerow(row)
|
||||
state = json.loads(docker("inspect", replica["id"]))[0]["State"]
|
||||
return {
|
||||
"mode": mode, "replica": replica["name"], "instance_id": replica["hostname"],
|
||||
"stop_command_seconds": round(t_stopped - t_stop, 2),
|
||||
"before": load.window(0.5, t_stop), "during": load.window(t_stop, t_start), "after": load.window(t_serves, t_end),
|
||||
"failed_after_stop": len(failed_after_stop),
|
||||
"failed_statuses": sorted({e[2] for e in failed_after_stop}),
|
||||
"last_failure_after_stop_s": round(max((e[0] for e in failed_after_stop), default=t_stop) - t_stop, 3),
|
||||
"target_last_served_after_stop_s": round(out_of_rotation, 3),
|
||||
"rejoin_up_in_lb_s": round(t_up - t_start, 2), "rejoin_serving_s": round(t_serves - t_start, 2),
|
||||
"client_retries_same_key": load.retries,
|
||||
"history": load.verify_history(),
|
||||
"restarted_state": f"{state['Status']} health={(state.get('Health') or {}).get('Status')}",
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
parser.add_argument("--output", default="evidence/failover")
|
||||
parser.add_argument("--modes", default="stop,kill,pause")
|
||||
parser.add_argument("--workers", type=int, default=4)
|
||||
args = parser.parse_args()
|
||||
out = ROOT / args.output
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
replicas = sorted((r for r in lbctl.replicas() if r["state"] == "running"), key=lambda r: r["name"])
|
||||
assert len(replicas) >= 2, "need at least two running replicas"
|
||||
lbctl.wait_up(len(replicas))
|
||||
results = []
|
||||
for mode in args.modes.split(","):
|
||||
for replica in replicas: # each replica in turn; the previous one is already restored
|
||||
print(f"== {mode} {replica['name']} ...", flush=True)
|
||||
result = one_round(replica, mode, len(replicas), args.workers, out)
|
||||
results.append(result)
|
||||
print(json.dumps({k: result[k] for k in ("failed_after_stop", "last_failure_after_stop_s",
|
||||
"target_last_served_after_stop_s", "rejoin_serving_s")}), flush=True)
|
||||
meta = {"date": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
|
||||
"commit": subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True,
|
||||
text=True).stdout.strip(),
|
||||
"host": f"{platform.system()} {platform.release()}, docker {docker('version', '--format', '{{.Server.Version}}').strip()}",
|
||||
"workload": f"{args.workers} closed-loop workers from the host via 127.0.0.1:8080: POST message "
|
||||
"(Idempotency-Key, uncertain -> same key) + GET last page; client timeout 3 s",
|
||||
"lb": "HAProxy: check GET /health/ready inter 1s fastinter 500ms fall 2 rise 2, timeout check 1s; "
|
||||
"retry-on conn-failure + redispatch",
|
||||
"api": "DRAIN_SECONDS=3, SHUTDOWN_TIMEOUT_SECONDS=8, stop_grace_period 15s"}
|
||||
(out / "series.json").write_text(json.dumps({"meta": meta, "rounds": results}, ensure_ascii=False, indent=2) + "\n",
|
||||
encoding="utf-8")
|
||||
lines = ["| Режим | Реплика | Запросов во время отказа | Ошибок после stop | ok-RPS до / во время / после | "
|
||||
"Последняя ошибка, с | Цель ушла из ротации, с | Возврат в LB / обслуживает, с | Потери / дубли |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |"]
|
||||
for r in results:
|
||||
h = r["history"]
|
||||
lines.append(f"| {r['mode']} | {r['replica']} | {r['during']['requests']} | {r['failed_after_stop']} "
|
||||
f"{r['failed_statuses'] or ''} | {r['before']['ok_rps']} / {r['during']['ok_rps']} / {r['after']['ok_rps']} | "
|
||||
f"{r['last_failure_after_stop_s']} | {r['target_last_served_after_stop_s']} | "
|
||||
f"{r['rejoin_up_in_lb_s']} / {r['rejoin_serving_s']} | "
|
||||
f"{h['lost_confirmed']} / {h['duplicate_ids'] + h['duplicate_texts']} |")
|
||||
(out / "series.md").write_text("\n".join([f"Дата {meta['date']}, commit {meta['commit']}. {meta['workload']}.", "",
|
||||
*lines, ""]), encoding="utf-8")
|
||||
print("\n".join(lines))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,424 +0,0 @@
|
||||
#!/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/<name>.json (timeline, alert times, metric snapshots, client counts)
|
||||
and <name>.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())
|
||||
@@ -1,212 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Background HTTP traffic through the LB for failover / rolling-update experiments (level 4).
|
||||
|
||||
Closed loop, N worker threads, each: POST a message (Idempotency-Key) + GET the last page.
|
||||
An uncertain POST (timeout, connection error, 5xx) is retried with the SAME key and body,
|
||||
exactly as a correct client must do; the history is checked afterwards for losses and
|
||||
duplicates. Every request is recorded as (t, kind, status, instance, latency).
|
||||
This is a correctness/availability probe, not a capacity benchmark (see bench/track1 for that).
|
||||
|
||||
python bench/loadgen.py --duration 30 --workers 4 # prints a summary JSON
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from collections import Counter, defaultdict
|
||||
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
|
||||
|
||||
|
||||
class Http:
|
||||
"""Minimal stdlib client with keep-alive per thread (http.client under urllib is not)."""
|
||||
|
||||
def __init__(self, base_url: str, timeout: float):
|
||||
import http.client
|
||||
from urllib.parse import urlsplit
|
||||
parts = urlsplit(base_url)
|
||||
self.host, self.port = parts.hostname, parts.port or 80
|
||||
self.timeout = timeout
|
||||
self.factory = lambda: http.client.HTTPConnection(self.host, self.port, timeout=self.timeout)
|
||||
self.conn = self.factory()
|
||||
|
||||
def request(self, method: str, path: str, body: bytes | None = None, headers: dict | None = None):
|
||||
try:
|
||||
self.conn.request(method, path, body=body, headers=headers or {})
|
||||
response = self.conn.getresponse()
|
||||
data = response.read()
|
||||
if response.getheader("connection", "").lower() == "close":
|
||||
self.conn.close()
|
||||
self.conn = self.factory()
|
||||
return response.status, dict(response.getheaders()), data
|
||||
except Exception:
|
||||
self.conn.close()
|
||||
self.conn = self.factory()
|
||||
raise
|
||||
|
||||
|
||||
def call(method: str, path: str, body=None, headers=None, timeout=10.0):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
h = {"Content-Type": "application/json", **(headers or {})}
|
||||
req = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.status, json.loads(r.read() or b"null")
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, json.loads(e.read() or b"null")
|
||||
|
||||
|
||||
def make_user(label: str) -> dict:
|
||||
username = f"{label}_{uuid.uuid4().hex[:12]}"
|
||||
password = "Load-password-" + uuid.uuid4().hex
|
||||
status, user = call("POST", "/api/v1/users", {"username": username, "display_name": label, "password": password})
|
||||
assert status == 201, (status, user)
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
status, session = call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
|
||||
assert status == 201, (status, session)
|
||||
return {"id": user["id"], "token": session["token"]}
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, workers: int = 4, timeout: float = 3.0, pause: float = 0.0):
|
||||
self.workers = workers
|
||||
self.timeout = timeout
|
||||
self.pause = pause
|
||||
self.alice, self.bob = make_user("load"), make_user("load")
|
||||
status, chat = call("POST", "/api/v1/chats", {"title": "load", "member_ids": [self.alice["id"], self.bob["id"]]},
|
||||
headers={"Authorization": "Bearer " + self.alice["token"]})
|
||||
assert status == 201, chat
|
||||
self.chat = chat
|
||||
self.stop_event = threading.Event()
|
||||
self.lock = threading.Lock()
|
||||
self.events: list[tuple[float, str, int, str, float]] = []
|
||||
self.confirmed: dict[str, dict] = {}
|
||||
self.retries = 0
|
||||
self.t0 = time.monotonic()
|
||||
self.threads = [threading.Thread(target=self._worker, args=(i,), daemon=True) for i in range(workers)]
|
||||
|
||||
def now(self) -> float:
|
||||
return time.monotonic() - self.t0
|
||||
|
||||
def _record(self, kind: str, status: int, instance: str, latency: float) -> None:
|
||||
with self.lock:
|
||||
self.events.append((round(self.now(), 4), kind, status, instance, round(latency * 1000, 2)))
|
||||
|
||||
def _worker(self, index: int) -> None:
|
||||
http = Http(BASE_URL, self.timeout)
|
||||
auth = {"Authorization": "Bearer " + self.alice["token"]}
|
||||
path = f"/api/v1/chats/{self.chat['id']}/messages"
|
||||
n, key = 0, uuid.uuid4().hex
|
||||
text = f"w{index}-0-{key[:6]}"
|
||||
while not self.stop_event.is_set():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
status, headers, data = http.request("POST", path, json.dumps({"text": text}).encode(),
|
||||
{**auth, "Idempotency-Key": key, "Content-Type": "application/json"})
|
||||
instance = headers.get("x-instance-id") or headers.get("X-Instance-Id") or "-"
|
||||
except Exception:
|
||||
status, instance, data = 0, "-", b""
|
||||
self._record("POST", status, instance, time.monotonic() - started)
|
||||
if status == 201:
|
||||
msg = json.loads(data)
|
||||
with self.lock:
|
||||
self.confirmed[msg["id"]] = msg
|
||||
n += 1
|
||||
key = uuid.uuid4().hex
|
||||
text = f"w{index}-{n}-{key[:6]}"
|
||||
elif status in (0, 502, 503, 504, 500):
|
||||
with self.lock:
|
||||
self.retries += 1 # same key + same text on the next iteration
|
||||
started = time.monotonic()
|
||||
try:
|
||||
status, headers, _ = http.request("GET", path + "?limit=5", None, auth)
|
||||
instance = headers.get("x-instance-id") or headers.get("X-Instance-Id") or "-"
|
||||
except Exception:
|
||||
status, instance = 0, "-"
|
||||
self._record("GET", status, instance, time.monotonic() - started)
|
||||
if self.pause:
|
||||
time.sleep(self.pause)
|
||||
|
||||
def start(self) -> "Load":
|
||||
self.t0 = time.monotonic()
|
||||
for t in self.threads:
|
||||
t.start()
|
||||
return self
|
||||
|
||||
def stop(self) -> None:
|
||||
self.stop_event.set()
|
||||
for t in self.threads:
|
||||
t.join(timeout=15)
|
||||
|
||||
def verify_history(self) -> dict:
|
||||
"""Walk the whole history with the second user: no confirmed message lost, no duplicate."""
|
||||
items, cursor = [], None
|
||||
while True:
|
||||
q = "?limit=100" + (f"&cursor={cursor}" if cursor else "")
|
||||
status, page = call("GET", f"/api/v1/chats/{self.chat['id']}/messages{q}",
|
||||
headers={"Authorization": "Bearer " + self.bob["token"]}, timeout=30)
|
||||
assert status == 200, page
|
||||
items += page["items"]
|
||||
cursor = page["next_cursor"]
|
||||
if not cursor:
|
||||
break
|
||||
ids = [m["id"] for m in items]
|
||||
texts = [m["text"] for m in items]
|
||||
lost = [i for i in self.confirmed if i not in set(ids)]
|
||||
changed = [m for m in items if m["id"] in self.confirmed and self.confirmed[m["id"]] != m]
|
||||
return {"history_messages": len(items), "confirmed_messages": len(self.confirmed),
|
||||
"lost_confirmed": len(lost), "altered_confirmed": len(changed),
|
||||
"duplicate_ids": len(ids) - len(set(ids)), "duplicate_texts": len(texts) - len(set(texts)),
|
||||
"unconfirmed_but_stored": len(set(ids) - set(self.confirmed))}
|
||||
|
||||
# ------------------------------------------------------------------ summaries
|
||||
def window(self, start: float, end: float) -> dict:
|
||||
ev = [e for e in self.events if start <= e[0] < end]
|
||||
ok = [e for e in ev if e[2] in (200, 201)]
|
||||
lat = sorted(e[4] for e in ok)
|
||||
|
||||
def pct(p: float):
|
||||
return lat[max(0, math.ceil(p * len(lat)) - 1)] if lat else None
|
||||
span = max(end - start, 1e-9)
|
||||
return {"seconds": round(span, 2), "requests": len(ev), "ok": len(ok), "failed": len(ev) - len(ok),
|
||||
"ok_rps": round(len(ok) / span, 1), "error_ratio": round((len(ev) - len(ok)) / len(ev), 5) if ev else None,
|
||||
"statuses": dict(Counter(e[2] for e in ev)), "instances": dict(Counter(e[3] for e in ok)),
|
||||
"p50_ms": pct(.5), "p95_ms": pct(.95), "p99_ms": pct(.99)}
|
||||
|
||||
def per_second(self) -> list[dict]:
|
||||
buckets: dict[int, list] = defaultdict(list)
|
||||
for e in self.events:
|
||||
buckets[int(e[0])].append(e)
|
||||
rows = []
|
||||
for second in sorted(buckets):
|
||||
ev = buckets[second]
|
||||
rows.append({"second": second, "ok": sum(1 for e in ev if e[2] in (200, 201)),
|
||||
"failed": sum(1 for e in ev if e[2] not in (200, 201)),
|
||||
"instances": "|".join(f"{k}:{v}" for k, v in sorted(Counter(e[3] for e in ev).items()))})
|
||||
return rows
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
parser.add_argument("--duration", type=float, default=20)
|
||||
parser.add_argument("--workers", type=int, default=4)
|
||||
args = parser.parse_args()
|
||||
load = Load(args.workers).start()
|
||||
time.sleep(args.duration)
|
||||
load.stop()
|
||||
print(json.dumps({"total": load.window(0, load.now()), "history": load.verify_history(),
|
||||
"client_retries_same_key": load.retries}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,309 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 2 experiment: proven idempotency of the versioned pipeline under injected faults.
|
||||
|
||||
Hypothesis. With at-least-once delivery, duplicated and reordered messages, crashes of the worker
|
||||
before/after its side effects and stale jobs of an older pipeline version:
|
||||
H1 no accepted (202) work is lost - every upload ends ready (or failed with a code, never stuck);
|
||||
H2 every effect (attachment, pipeline_version, variant) is published exactly once - one set of
|
||||
variant rows written by ONE successful attempt, one set of objects in the bucket;
|
||||
H3 the published version only grows - an older job never overwrites a newer result, `ready`
|
||||
never goes back to queued/processing;
|
||||
H4 objects of interrupted attempts are garbage that the cleanup removes; nothing published is
|
||||
ever deleted.
|
||||
|
||||
Method. For every scenario the affected service (relay/worker) is recreated with FAULT_POINTS of
|
||||
the scenario (the real code paths, real crashes = os._exit of the process, real `docker pause`),
|
||||
N uploads go through the LB, then the scenario-specific facts are read from PostgreSQL and S3 and
|
||||
the read-only invariant audit (messenger.audit, I1-I7, with SHA-256 of every published object)
|
||||
runs over the WHOLE stand. The normal configuration is restored after each scenario.
|
||||
|
||||
python bench/pipeline_faults.py --output evidence/track2 [--uploads 5]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import platform
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
import imagegen # noqa: E402
|
||||
from conftest import (Api, attachment_row, compose, events_of, jobctl, psql, s3_keys, service_with_env, # noqa: E402
|
||||
wait_healthy)
|
||||
|
||||
FAST = {"JOB_LEASE_SECONDS": "6", "ORPHAN_GRACE_SECONDS": "3", "CLEANUP_INTERVAL_SECONDS": "1"}
|
||||
|
||||
|
||||
def now() -> str:
|
||||
return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
|
||||
|
||||
def wait(condition, timeout: float, what: str):
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
value = condition()
|
||||
if value:
|
||||
return value
|
||||
if time.monotonic() > deadline:
|
||||
raise AssertionError(what)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def facts(attachment_id: str, objects: set[str]) -> dict:
|
||||
row = attachment_row(attachment_id)
|
||||
out = psql("SELECT json_build_object("
|
||||
"'claims', (SELECT count(*) FROM job_attempts a JOIN jobs j ON j.id = a.job_id WHERE j.attachment_id = '{0}'), "
|
||||
"'succeeded_attempts', (SELECT count(*) FROM job_attempts a JOIN jobs j ON j.id = a.job_id "
|
||||
" WHERE j.attachment_id = '{0}' AND a.outcome = 'succeeded'), "
|
||||
"'variant_rows', (SELECT count(*) FROM attachment_variants WHERE attachment_id = '{0}'), "
|
||||
"'versions', (SELECT coalesce(json_agg(DISTINCT pipeline_version), '[]') FROM attachment_variants "
|
||||
" WHERE attachment_id = '{0}'), "
|
||||
"'job_states', (SELECT coalesce(json_agg(state || ':v' || pipeline_version ORDER BY created_at), '[]') "
|
||||
" FROM jobs WHERE attachment_id = '{0}'), "
|
||||
"'uncleaned_failed_attempts', (SELECT count(*) FROM job_attempts a JOIN jobs j ON j.id = a.job_id "
|
||||
" WHERE j.attachment_id = '{0}' AND a.outcome <> 'succeeded' AND a.objects_cleaned_at IS NULL))"
|
||||
.format(attachment_id))
|
||||
f = json.loads(out)
|
||||
f.update(status=row["status"], published_version=row["published_version"], staging_state=row["staging_state"],
|
||||
objects=len([k for k in objects if k.startswith(f"a/{attachment_id}/")]))
|
||||
f["events"] = [e["event"] for e in events_of(attachment_id)]
|
||||
return f
|
||||
|
||||
|
||||
def audit() -> dict:
|
||||
r = compose("run", "--rm", "--no-deps", "-T", "auditor", "--verify-checksums", check=False, timeout=600)
|
||||
report = json.loads(r.stdout)
|
||||
return {"ok": report["ok"], "violations": report["violations"], "notes": len(report["notes"]),
|
||||
"objects": report["objects"]}
|
||||
|
||||
|
||||
class Run:
|
||||
def __init__(self, api: Api, uploads: int):
|
||||
self.api = api
|
||||
self.n = uploads
|
||||
self.alice, self.bob = api.user("t2a"), api.user("t2b")
|
||||
self.chat = api.chat(self.alice, self.bob)
|
||||
|
||||
def upload_many(self, n: int | None = None) -> list[dict]:
|
||||
return [self.api.upload(self.alice, self.chat, imagegen.png(60 + i, 40, noise=True)).json()
|
||||
for i in range(n or self.n)]
|
||||
|
||||
def finish(self, atts: list[dict], timeout: float = 180) -> tuple[list[dict], list[float]]:
|
||||
started = time.monotonic()
|
||||
took = []
|
||||
for a in atts:
|
||||
self.api.wait_status(self.bob, a["id"], timeout=timeout)
|
||||
took.append(round(time.monotonic() - started, 2))
|
||||
return atts, took
|
||||
|
||||
|
||||
def expect_one_effect(f: dict, version: int = 1) -> list[str]:
|
||||
"""H1 + H2 for a plain upload of pipeline `version`."""
|
||||
problems = []
|
||||
if f["status"] != "ready":
|
||||
problems.append(f"status {f['status']}")
|
||||
if f["succeeded_attempts"] != 1 or f["variant_rows"] != 3 or f["published_version"] != version:
|
||||
problems.append(f"effect {f['succeeded_attempts']} attempts/{f['variant_rows']} rows/v{f['published_version']}")
|
||||
if f["objects"] != 4: # original + thumbnail + crop + optimized, cleanup done
|
||||
problems.append(f"{f['objects']} objects in the bucket")
|
||||
return problems
|
||||
|
||||
|
||||
def plain_scenario(run: Run, name: str, service: str, env: dict, *, scale: int | None = None,
|
||||
cleanup_wait: bool = True) -> dict:
|
||||
with service_with_env(service, scale=scale, **env):
|
||||
atts, took = run.finish(run.upload_many())
|
||||
if cleanup_wait: # garbage of interrupted attempts: cleaned after ORPHAN_GRACE_SECONDS
|
||||
try:
|
||||
wait(lambda: all(json.loads(psql(
|
||||
"SELECT json_build_object('n', count(*)) FROM job_attempts a JOIN jobs j ON j.id = a.job_id "
|
||||
f"WHERE j.attachment_id = '{a['id']}' AND a.outcome <> 'succeeded' "
|
||||
"AND a.objects_cleaned_at IS NULL"))["n"] == 0 for a in atts), 60, "cleanup")
|
||||
except AssertionError:
|
||||
pass # reported below as uncleaned attempts
|
||||
objects = s3_keys("a/")
|
||||
per = [facts(a["id"], objects) for a in atts]
|
||||
problems = {a["id"]: p for a, f in zip(atts, per) if (p := expect_one_effect(f))}
|
||||
return {"scenario": name, "faults": {service: env}, "uploads": len(atts),
|
||||
"ready": sum(f["status"] == "ready" for f in per), "claims_total": sum(f["claims"] for f in per),
|
||||
"max_claims": max(f["claims"] for f in per), "time_to_ready_s": {"p50": statistics.median(took),
|
||||
"max": max(took)},
|
||||
"event_sequences": sorted({" > ".join(f["events"]) for f in per}), "problems": problems}
|
||||
|
||||
|
||||
def versions_scenario(run: Run) -> dict:
|
||||
"""Stale job after a newer version: v2 (slow) and v3 run at the same time; v3 publishes first,
|
||||
v2 finishes later and must end superseded without touching the published v3 result."""
|
||||
att = run.upload_many(1)[0]
|
||||
run.api.wait_status(run.bob, att["id"], "ready")
|
||||
observed = set()
|
||||
with service_with_env("worker", WORKER_FAULT_POINTS="slow=10,slow_pipeline=2"):
|
||||
jobctl("reprocess", att["id"], "--pipeline", "2", "--operator", "track2", "--reason", "new encoder")
|
||||
wait(lambda: "processing:v2" in facts(att["id"], set())["job_states"], 60, "v2 not claimed")
|
||||
jobctl("reprocess", att["id"], "--pipeline", "3", "--operator", "track2", "--reason", "newer encoder")
|
||||
deadline = time.monotonic() + 120
|
||||
while time.monotonic() < deadline:
|
||||
meta = run.api.attachment(run.bob, att["id"])
|
||||
observed.add(meta["status"])
|
||||
states = facts(att["id"], set())["job_states"]
|
||||
if not any(s.startswith(("queued", "processing")) for s in states):
|
||||
break
|
||||
time.sleep(0.3)
|
||||
final = run.api.attachment(run.bob, att["id"])
|
||||
f = facts(att["id"], s3_keys("a/"))
|
||||
thumb_v3 = psql(f"SELECT encode(sha256, 'hex') FROM attachment_variants WHERE attachment_id = '{att['id']}' "
|
||||
"AND pipeline_version = 3 AND name = 'thumbnail'")
|
||||
problems = []
|
||||
if f["job_states"] != ["succeeded:v1", "superseded:v2", "succeeded:v3"]:
|
||||
problems.append(f"job states {f['job_states']}")
|
||||
if f["published_version"] != 3 or observed != {"ready"}:
|
||||
problems.append(f"published v{f['published_version']}, statuses seen {sorted(observed)}")
|
||||
if next(v["sha256"] for v in final["variants"] if v["name"] == "thumbnail") != thumb_v3:
|
||||
problems.append("published thumbnail is not the v3 one")
|
||||
# Stale duplicate of the FIRST job, published by hand with the relay's broker user: a no-op.
|
||||
job_v1 = psql(f"SELECT id FROM jobs WHERE attachment_id = '{att['id']}' AND pipeline_version = 1")
|
||||
script = ("import asyncio, aio_pika, datetime as d\n"
|
||||
"from messenger import broker\n"
|
||||
"async def m():\n"
|
||||
" c = await aio_pika.connect(open('/run/secrets/broker_url').read().strip())\n"
|
||||
" ch = await c.channel(publisher_confirms=True)\n"
|
||||
" ex = await ch.get_exchange(broker.EXCHANGE, ensure=False)\n"
|
||||
f" body = broker.encode('{job_v1}', '{att['id']}', 1, 1, d.datetime.now(d.timezone.utc))\n"
|
||||
" await ex.publish(aio_pika.Message(body), routing_key=broker.ROUTING_KEY)\n"
|
||||
" await c.close()\n"
|
||||
"asyncio.run(m())\n")
|
||||
compose("exec", "-T", "relay", "python", "-c", script)
|
||||
time.sleep(3)
|
||||
after = run.api.attachment(run.bob, att["id"])
|
||||
if after != final:
|
||||
problems.append("stale v1 message changed the attachment")
|
||||
return {"scenario": "stale_version_and_reorder", "uploads": 1, "statuses_seen_during_reprocess": sorted(observed),
|
||||
"job_states": f["job_states"], "published_version": f["published_version"],
|
||||
"variant_rows_by_version": f["variant_rows"], "objects": f["objects"],
|
||||
"events": f["events"], "problems": problems}
|
||||
|
||||
|
||||
def queued_reorder_scenario(run: Run) -> dict:
|
||||
"""Both newer versions wait in the outbox; the relay publishes them in REVERSE order and one worker
|
||||
takes them one by one: v3 is published first, v2 is then superseded at its claim (no work)."""
|
||||
att = run.upload_many(1)[0]
|
||||
run.api.wait_status(run.bob, att["id"], "ready")
|
||||
# The worker stays stopped until it is recreated with concurrency 1 (no normal start in between).
|
||||
# Worker and relay stay stopped until each is recreated with the scenario's settings: no normal
|
||||
# start in between that would consume/publish the jobs in the ordinary order.
|
||||
compose("stop", "worker", "relay")
|
||||
try:
|
||||
jobctl("reprocess", att["id"], "--pipeline", "2", "--operator", "track2", "--reason", "v2")
|
||||
jobctl("reprocess", att["id"], "--pipeline", "3", "--operator", "track2", "--reason", "v3")
|
||||
with service_with_env("relay", RELAY_FAULT_POINTS="reverse_order"):
|
||||
wait(lambda: psql("SELECT count(*) FROM outbox o JOIN jobs j ON j.id = o.job_id WHERE j.attachment_id = "
|
||||
f"'{att['id']}' AND j.pipeline_version > 1 AND o.published_at IS NOT NULL") == "2",
|
||||
30, "both reprocess jobs not published") # in one relay batch: v3 first, then v2
|
||||
with service_with_env("worker", WORKER_CONCURRENCY="1"):
|
||||
wait(lambda: not any(s.startswith(("queued", "processing"))
|
||||
for s in facts(att["id"], set())["job_states"]), 120, "reprocess jobs did not finish")
|
||||
finally:
|
||||
compose("start", "worker", "relay")
|
||||
wait_healthy("worker", "relay")
|
||||
f = facts(att["id"], s3_keys("a/"))
|
||||
problems = []
|
||||
if f["job_states"] != ["succeeded:v1", "superseded:v2", "succeeded:v3"] or f["published_version"] != 3:
|
||||
problems.append(f"{f['job_states']} published v{f['published_version']}")
|
||||
if f["claims"] != 2: # v1 and v3 only: v2 was superseded before any work
|
||||
problems.append(f"{f['claims']} claims")
|
||||
return {"scenario": "reordered_versions_in_queue", "job_states": f["job_states"], "claims": f["claims"],
|
||||
"published_version": f["published_version"], "events": f["events"], "problems": problems}
|
||||
|
||||
|
||||
def hung_worker_scenario(run: Run) -> dict:
|
||||
with service_with_env("worker", scale=2, WORKER_FAULT_POINTS="slow=8", **FAST):
|
||||
att = run.upload_many(1)[0]
|
||||
owner = wait(lambda: psql(f"SELECT lease_owner FROM jobs WHERE attachment_id = '{att['id']}' "
|
||||
"AND state = 'processing'"), 30, "not claimed")
|
||||
ids = compose("ps", "-q", "worker").stdout.split()
|
||||
names = dict(line.split() for line in subprocess.run(
|
||||
["docker", "inspect", "-f", "{{.Config.Hostname}} {{.Id}}", *ids], capture_output=True, text=True,
|
||||
check=True).stdout.splitlines())
|
||||
subprocess.run(["docker", "pause", names[owner]], check=True)
|
||||
try:
|
||||
run.api.wait_status(run.bob, att["id"], "ready", timeout=150)
|
||||
published = psql(f"SELECT string_agg(object_key, ',' ORDER BY object_key) FROM attachment_variants "
|
||||
f"WHERE attachment_id = '{att['id']}'")
|
||||
finally:
|
||||
subprocess.run(["docker", "unpause", names[owner]], check=True)
|
||||
time.sleep(15)
|
||||
again = psql(f"SELECT string_agg(object_key, ',' ORDER BY object_key) FROM attachment_variants "
|
||||
f"WHERE attachment_id = '{att['id']}'")
|
||||
wait(lambda: json.loads(psql("SELECT json_build_object('n', count(*)) FROM job_attempts a JOIN jobs j "
|
||||
f"ON j.id = a.job_id WHERE j.attachment_id = '{att['id']}' AND a.outcome <> "
|
||||
"'succeeded' AND a.objects_cleaned_at IS NULL"))["n"] == 0, 60, "cleanup")
|
||||
f = facts(att["id"], s3_keys("a/"))
|
||||
problems = expect_one_effect(f)
|
||||
if published != again:
|
||||
problems.append("the resumed (fenced) attempt changed the published result")
|
||||
return {"scenario": "hung_worker_docker_pause", "frozen": owner, "claims": f["claims"], "events": f["events"],
|
||||
"problems": problems}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--output", default="evidence/track2")
|
||||
p.add_argument("--uploads", type=int, default=5)
|
||||
args = p.parse_args()
|
||||
out = ROOT / args.output
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
api = Api()
|
||||
run = Run(api, args.uploads)
|
||||
started = now()
|
||||
results = []
|
||||
plan = [
|
||||
("baseline_no_faults", "worker", {}),
|
||||
("duplicate_publish", "relay", {"RELAY_FAULT_POINTS": "duplicate_publish"}),
|
||||
("duplicate_and_reverse_order", "relay", {"RELAY_FAULT_POINTS": "duplicate_publish,reverse_order"}),
|
||||
("relay_crash_after_confirm_before_mark", "relay", {"RELAY_FAULT_POINTS": "crash_after_publish"}),
|
||||
("worker_crash_before_side_effect", "worker", {"WORKER_FAULT_POINTS": "crash_after_claim", **FAST}),
|
||||
("worker_crash_after_s3_before_commit", "worker", {"WORKER_FAULT_POINTS": "crash_after_s3_write", **FAST}),
|
||||
("worker_crash_after_commit_before_ack", "worker", {"WORKER_FAULT_POINTS": "crash_after_commit", **FAST}),
|
||||
("transient_errors_then_success", "worker", {"WORKER_FAULT_POINTS": "transient_error=2",
|
||||
"JOB_RETRY_BASE_SECONDS": "0.5", **FAST}),
|
||||
]
|
||||
for name, service, env in plan:
|
||||
print(f"[{now()}] {name}", flush=True)
|
||||
results.append(plain_scenario(run, name, service, env))
|
||||
print(f"[{now()}] two_workers_duplicate_publish", flush=True)
|
||||
with service_with_env("relay", RELAY_FAULT_POINTS="duplicate_publish"):
|
||||
results.append(plain_scenario(run, "two_workers_duplicate_publish", "worker", {}, scale=2))
|
||||
for scenario in (versions_scenario, queued_reorder_scenario, hung_worker_scenario):
|
||||
print(f"[{now()}] {scenario.__name__}", flush=True)
|
||||
results.append(scenario(run))
|
||||
wait_healthy("worker", "relay")
|
||||
report = audit()
|
||||
summary = {
|
||||
"experiment": "track 2: idempotency of the versioned pipeline under injected faults",
|
||||
"started": started, "finished": now(),
|
||||
"host": {"os": platform.platform(), "python": platform.python_version()},
|
||||
"uploads_per_plain_scenario": args.uploads,
|
||||
"scenarios": results,
|
||||
"audit_after_all": report,
|
||||
"violations": sum(len(r["problems"]) for r in results) + len(report["violations"]),
|
||||
}
|
||||
(out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
lines = [f"{'scenario':45} {'uploads':>7} {'ready':>5} {'claims':>6} problems"]
|
||||
for r in results:
|
||||
lines.append(f"{r['scenario']:45} {r.get('uploads', 1):>7} {r.get('ready', '-'):>5} "
|
||||
f"{r.get('claims_total', r.get('claims', '-')):>6} {len(r['problems'])}")
|
||||
lines.append(f"audit after all scenarios: ok={report['ok']} violations={len(report['violations'])} "
|
||||
f"objects={report['objects']}")
|
||||
(out / "summary.txt").write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
print("\n".join(lines))
|
||||
return 0 if summary["violations"] == 0 else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,75 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 4: scripts/rolling-update.sh while bench/loadgen.py traffic runs through the LB.
|
||||
|
||||
python bench/rolling_under_load.py --output evidence/rolling-update
|
||||
|
||||
Writes <output>/summary.json (errors, RPS, history check, revisions before/after),
|
||||
<output>/timeline.csv (per second ok/failed/instances) and <output>/script-output.txt.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
sys.path.insert(0, str(ROOT / "bench"))
|
||||
import lbctl # noqa: E402
|
||||
from loadgen import Load # noqa: E402
|
||||
|
||||
|
||||
def revisions() -> dict[str, str]:
|
||||
result = {}
|
||||
for r in lbctl.replicas():
|
||||
if r["state"] == "running":
|
||||
label = subprocess.run(["docker", "inspect", "-f", '{{index .Config.Labels "org.opencontainers.image.revision"}}',
|
||||
r["id"]], capture_output=True, text=True).stdout.strip()
|
||||
result[r["name"]] = f"{r['hostname']} revision={label}"
|
||||
return result
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
||||
parser.add_argument("--output", default="evidence/rolling-update")
|
||||
parser.add_argument("--workers", type=int, default=4)
|
||||
args = parser.parse_args()
|
||||
out = ROOT / args.output
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
before = revisions()
|
||||
load = Load(args.workers).start()
|
||||
time.sleep(5)
|
||||
t_begin = load.now()
|
||||
bash = (os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Git", "bin", "bash.exe")
|
||||
if os.name == "nt" else "sh")
|
||||
env = {**os.environ, "PYTHON": sys.executable}
|
||||
script = subprocess.run([bash, str(ROOT / "scripts" / "rolling-update.sh")], cwd=ROOT, env=env,
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=900)
|
||||
t_end = load.now()
|
||||
time.sleep(5)
|
||||
load.stop()
|
||||
(out / "script-output.txt").write_text(f"$ sh scripts/rolling-update.sh (exit {script.returncode})\n"
|
||||
+ script.stdout + script.stderr, encoding="utf-8")
|
||||
with (out / "timeline.csv").open("w", newline="", encoding="utf-8") as f:
|
||||
writer = csv.DictWriter(f, fieldnames=["second", "ok", "failed", "instances"])
|
||||
writer.writeheader()
|
||||
writer.writerows(load.per_second())
|
||||
summary = {"script_exit_code": script.returncode, "update_seconds": round(t_end - t_begin, 1),
|
||||
"before": before, "after": revisions(),
|
||||
"during_update": load.window(t_begin, t_end), "whole_run": load.window(0, load.now()),
|
||||
"client_retries_same_key": load.retries, "history": load.verify_history(),
|
||||
"workload": f"{args.workers} closed-loop workers: POST (Idempotency-Key) + GET page via 127.0.0.1:8080"}
|
||||
(out / "summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps({k: summary[k] for k in ("script_exit_code", "update_seconds", "before", "after", "history")},
|
||||
ensure_ascii=False, indent=2))
|
||||
print(json.dumps(summary["during_update"], ensure_ascii=False))
|
||||
return 0 if script.returncode == 0 else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
-361
@@ -1,361 +0,0 @@
|
||||
#!/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())
|
||||
@@ -1,146 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Summarise evidence/track1/run*-<config>.json into evidence/track1/summary.md (+ summary.json).
|
||||
|
||||
python bench/track1_summary.py [evidence/track1]
|
||||
|
||||
Per configuration: median over the runs (in brackets min..max), so one noisy run cannot decide.
|
||||
CPU: application containers from cgroup usage_usec (exact, per window), the telemetry stack from
|
||||
its own process CPU counters; RAM: docker stats average. Kept rare events = traces found in Tempo /
|
||||
events the client saw (5xx answers, POSTs > 450 ms).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import statistics
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ORDER = ["off", "full", "head10", "tail"]
|
||||
|
||||
|
||||
def med(values):
|
||||
values = [v for v in values if v is not None]
|
||||
if not values:
|
||||
return None, None, None
|
||||
return statistics.median(values), min(values), max(values)
|
||||
|
||||
|
||||
def fmt(triple, digits=1, unit=""):
|
||||
m, lo, hi = triple
|
||||
if m is None:
|
||||
return "—"
|
||||
if lo == hi:
|
||||
return f"{m:.{digits}f}{unit}"
|
||||
return f"{m:.{digits}f}{unit} ({lo:.{digits}f}–{hi:.{digits}f})"
|
||||
|
||||
|
||||
def kept(found, seen):
|
||||
if found is None or found < 0 or not seen:
|
||||
return None
|
||||
return 100.0 * found / seen
|
||||
|
||||
|
||||
def summarise(rs: list[dict]) -> dict:
|
||||
post = [r["client"]["post"] for r in rs]
|
||||
get = [r["client"]["get"] for r in rs]
|
||||
cpu = [r["client"].get("cpu_pct", {}) for r in rs]
|
||||
res = [r["resources"] for r in rs]
|
||||
tel = [r["telemetry"] for r in rs]
|
||||
windows = [r["client"]["window"][1] - r["client"]["window"][0] + 25 for r in rs]
|
||||
|
||||
def tele_cpu(t, w):
|
||||
values = (t.get("telemetry_cpu_s") or {}).values()
|
||||
return None if not values or any(v is None for v in values) else 100 * sum(values) / w
|
||||
|
||||
return {
|
||||
"runs": len(rs),
|
||||
"post_ok_rps": med([p["ok_rps"] for p in post]),
|
||||
"post_p50_ms": med([p["p50_ms"] for p in post]), "post_p95_ms": med([p["p95_ms"] for p in post]),
|
||||
"post_p99_ms": med([p["p99_ms"] for p in post]),
|
||||
"get_p50_ms": med([g["p50_ms"] for g in get]), "get_p95_ms": med([g["p95_ms"] for g in get]),
|
||||
"get_p99_ms": med([g["p99_ms"] for g in get]),
|
||||
"api_cpu_pct": med([sum(v for k, v in c.items() if k.startswith("api")) or None for c in cpu]),
|
||||
"worker_cpu_pct": med([c.get("worker") for c in cpu]),
|
||||
"relay_cpu_pct": med([c.get("relay") for c in cpu]),
|
||||
"postgres_cpu_pct": med([c.get("postgres") for c in cpu]),
|
||||
"api_mem_mib": med([sum(v["mem_mib_avg"] for k, v in x.items() if k.startswith("api")) or None for x in res]),
|
||||
"telemetry_cpu_pct": med([tele_cpu(t, w) for t, w in zip(tel, windows)]),
|
||||
"telemetry_mem_mib": med([sum(x.get(k, {}).get("mem_mib_avg", 0) for k in ("otel-collector", "tempo", "loki",
|
||||
"prometheus")) for x in res]),
|
||||
"collector_mem_mib": med([x.get("otel-collector", {}).get("mem_mib_avg") for x in res]),
|
||||
"spans_recorded": med([t.get("sdk_spans_recorded") for t in tel]),
|
||||
"spans_accepted": med([t.get("collector_spans_accepted") for t in tel]),
|
||||
"spans_to_tempo": med([t.get("collector_spans_sent") for t in tel]),
|
||||
"spans_refused_or_failed": med([None if t.get("collector_spans_refused") is None else
|
||||
t["collector_spans_refused"] + (t.get("collector_spans_send_failed") or 0)
|
||||
+ (t.get("sdk_spans_export_failed") or 0) for t in tel]),
|
||||
"tempo_kib": med([None if t.get("tempo_bytes_received") is None else t["tempo_bytes_received"] / 1024 for t in tel]),
|
||||
"loki_kib": med([None if t.get("loki_bytes_received") is None else t["loki_bytes_received"] / 1024 for t in tel]),
|
||||
"logs": med([t.get("collector_logs_accepted") for t in tel]),
|
||||
"metric_points": med([t.get("collector_metric_points_accepted") for t in tel]),
|
||||
"errors_injected": med([p["5xx"] for p in post]),
|
||||
"errors_in_tempo": med([t.get("error_traces_in_tempo") for t in tel]),
|
||||
"errors_kept_pct": med([kept(t.get("error_traces_in_tempo"), p["5xx"]) for t, p in zip(tel, post)]),
|
||||
"slow_seen": med([p["slow_over_450ms"] for p in post]),
|
||||
"slow_in_tempo": med([t.get("slow_traces_in_tempo") for t in tel]),
|
||||
"slow_kept_pct": med([kept(t.get("slow_traces_in_tempo"), p["slow_over_450ms"]) for t, p in zip(tel, post)]),
|
||||
"post_traces_in_tempo": med([t.get("server_traces_in_tempo") for t in tel]),
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
folder = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / "evidence" / "track1"
|
||||
runs: dict[str, list[dict]] = {}
|
||||
for f in sorted(folder.glob("run*-*.json")):
|
||||
data = json.loads(f.read_text(encoding="utf-8"))
|
||||
runs.setdefault(data["config"], []).append(data)
|
||||
meta = json.loads((folder / "meta.json").read_text(encoding="utf-8"))
|
||||
summary = {c: summarise(runs[c]) for c in ORDER if c in runs}
|
||||
rows = list(summary.items())
|
||||
L = [f"# Трек 1: цена наблюдаемости — сводка (серия от {meta['started']})", "",
|
||||
f"Нагрузка: open loop {meta['rate']:.0f} req/s (70 % POST message, 30 % GET history) + 1 upload/s, "
|
||||
f"прогрев {meta['warmup']:.0f} с, замер {meta['duration']:.0f} с; редкие события `{meta['faults']}` "
|
||||
"(~1 % POST → 503, ~1 % POST +500 мс). Медиана по повторам, в скобках min–max.", "",
|
||||
"## Задержка (клиент, от запланированного момента запроса)", "",
|
||||
"| Конфигурация | POST ok RPS | POST p50, мс | POST p95, мс | POST p99, мс* | GET p50, мс | GET p95, мс | GET p99, мс |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- |"]
|
||||
for c, s in rows:
|
||||
L.append(f"| {c} ({s['runs']}) | {fmt(s['post_ok_rps'], 2)} | {fmt(s['post_p50_ms'])} | {fmt(s['post_p95_ms'])} | "
|
||||
f"{fmt(s['post_p99_ms'])} | {fmt(s['get_p50_ms'])} | {fmt(s['get_p95_ms'])} | {fmt(s['get_p99_ms'])} |")
|
||||
L += ["", "\\* p99 POST определяется внедрёнными медленными запросами (1 % × +500 мс), поэтому ≈ 500 мс во всех "
|
||||
"конфигурациях; чистая цена телеметрии видна по GET (там отказы не внедряются) и по p50/p95.", "",
|
||||
"## Ресурсы", "",
|
||||
"| Конфигурация | CPU api×2, % | CPU worker, % | CPU relay, % | CPU postgres, % | CPU телеметрии**, % | RAM api×2, MiB | RAM телеметрии**, MiB | RAM Collector, MiB |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |"]
|
||||
for c, s in rows:
|
||||
L.append(f"| {c} | {fmt(s['api_cpu_pct'])} | {fmt(s['worker_cpu_pct'])} | {fmt(s['relay_cpu_pct'])} | "
|
||||
f"{fmt(s['postgres_cpu_pct'])} | {fmt(s['telemetry_cpu_pct'])} | {fmt(s['api_mem_mib'])} | "
|
||||
f"{fmt(s['telemetry_mem_mib'])} | {fmt(s['collector_mem_mib'])} |")
|
||||
L += ["", "100 % = одно ядро. CPU приложения — точный счётчик cgroup (`cpu.stat usage_usec`) за окно замера; "
|
||||
"\\*\\* телеметрия = Collector + Tempo + Loki + Prometheus (их собственные счётчики CPU; RAM — docker stats).", "",
|
||||
"## Объём телеметрии и потери (окно замера + 25 с на доставку)", "",
|
||||
"| Конфигурация | spans записано SDK | принято Collector | ушло в Tempo | отказ/сбой отправки | Tempo, KiB | Loki, KiB | log records | metric points |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |"]
|
||||
for c, s in rows:
|
||||
L.append(f"| {c} | {fmt(s['spans_recorded'], 0)} | {fmt(s['spans_accepted'], 0)} | {fmt(s['spans_to_tempo'], 0)} | "
|
||||
f"{fmt(s['spans_refused_or_failed'], 0)} | {fmt(s['tempo_kib'], 0)} | {fmt(s['loki_kib'], 0)} | "
|
||||
f"{fmt(s['logs'], 0)} | {fmt(s['metric_points'], 0)} |")
|
||||
L += ["", "«Отказ/сбой» = отказано memory_limiter-ом + не отправлено Collector-ом + не отправлено SDK. "
|
||||
"Отброшенное политикой sampling (head в SDK, tail в Collector) потерей не считается: это решение.", "",
|
||||
"## Что осталось найти: редкие ошибки и медленные запросы", "",
|
||||
"| Конфигурация | 5xx у клиента | 5xx-трасс в Tempo | найдено ошибок | медленных (> 450 мс) у клиента | медленных трасс в Tempo | найдено медленных | трасс POST в Tempo |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- |"]
|
||||
for c, s in rows:
|
||||
L.append(f"| {c} | {fmt(s['errors_injected'], 0)} | {fmt(s['errors_in_tempo'], 0)} | {fmt(s['errors_kept_pct'], 0, ' %')} | "
|
||||
f"{fmt(s['slow_seen'], 0)} | {fmt(s['slow_in_tempo'], 0)} | {fmt(s['slow_kept_pct'], 0, ' %')} | "
|
||||
f"{fmt(s['post_traces_in_tempo'], 0)} |")
|
||||
out = "\n".join(L) + "\n"
|
||||
(folder / "summary.md").write_text(out, encoding="utf-8", newline="\n")
|
||||
(folder / "summary.json").write_text(json.dumps(summary, indent=1) + "\n", encoding="utf-8", newline="\n")
|
||||
print(out)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,244 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 4 experiment: peak memory of the API replicas under >= 10 simultaneous uploads.
|
||||
|
||||
Hypothesis: the memory of one replica is bounded by UPLOAD_CONCURRENCY x MAX_UPLOAD_BYTES (bodies
|
||||
waiting for a slot stay in TCP buffers, not in the process) + one image check at a time
|
||||
(IMAGE_VERIFY_CONCURRENCY), independent of how many clients upload at once.
|
||||
|
||||
Method (repeatable, the stand must be up):
|
||||
* for every scenario the api replicas are RECREATED with the scenario's settings, so the cgroup
|
||||
counter memory.peak starts from an idle process (it never decreases during a container's life);
|
||||
* idle memory.current of each replica is read; then N clients upload at the same moment through
|
||||
the LB (a barrier releases them together), each a different file;
|
||||
* during the run memory.current of every replica is sampled every 50 ms inside the container;
|
||||
afterwards memory.peak (cgroup v2: all processes of the container incl. djpeg) and VmHWM of
|
||||
PID 1 (the Python server alone) are read;
|
||||
* the normal configuration is restored at the end.
|
||||
|
||||
python bench/upload_memory.py --output evidence/memory
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import httpx2 as httpx
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
import imagegen # noqa: E402
|
||||
|
||||
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
||||
PASSWORD = "Bench-password-Ω-12345"
|
||||
MiB = 1024 * 1024
|
||||
|
||||
|
||||
def sh(*args: str, env: dict | None = None, timeout: float = 300) -> str:
|
||||
return subprocess.run(args, cwd=ROOT, capture_output=True, text=True, check=True, timeout=timeout,
|
||||
env={**os.environ, **(env or {})}).stdout
|
||||
|
||||
|
||||
def replicas() -> list[str]:
|
||||
return sh("docker", "compose", "ps", "-q", "api").split()
|
||||
|
||||
|
||||
def cg(cid: str, name: str) -> int:
|
||||
return int(sh("docker", "exec", cid, "cat", f"/sys/fs/cgroup/{name}").split()[0])
|
||||
|
||||
|
||||
def memory_stat(cid: str, key: str) -> int:
|
||||
for line in sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.stat").splitlines():
|
||||
name, value = line.split()
|
||||
if name == key:
|
||||
return int(value)
|
||||
return 0
|
||||
|
||||
|
||||
def vmhwm(cid: str) -> int:
|
||||
for line in sh("docker", "exec", cid, "cat", "/proc/1/status").splitlines():
|
||||
if line.startswith("VmHWM:"):
|
||||
return int(line.split()[1]) * 1024
|
||||
return 0
|
||||
|
||||
|
||||
def container_events() -> dict[str, str]:
|
||||
"""restart count + OOM-kill events per container (cgroup memory.events oom_kill counter)."""
|
||||
out = {}
|
||||
for cid in sh("docker", "compose", "ps", "-q").split():
|
||||
name, restarts = sh("docker", "inspect", "-f", "{{.Name}} {{.RestartCount}}", cid).split()
|
||||
events = dict(line.split() for line in sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.events").splitlines())
|
||||
out[name.lstrip("/")] = f"restarts={restarts} oom_kill={events.get('oom_kill', '?')}"
|
||||
return out
|
||||
|
||||
|
||||
def recreate(env: dict) -> None:
|
||||
sh("docker", "compose", "up", "-d", "--force-recreate", "--no-deps", "--wait", "api", env=env, timeout=300)
|
||||
sh(sys.executable, "scripts/lbctl.py", "wait-up", str(len(replicas())), "--timeout", "90") # LB sees them UP
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
class Sampler(threading.Thread):
|
||||
"""memory.current of one container every 50 ms, read by a shell loop inside it."""
|
||||
|
||||
def __init__(self, cid: str):
|
||||
super().__init__(daemon=True)
|
||||
self.cid = cid
|
||||
self.values: list[int] = []
|
||||
self.proc = subprocess.Popen(["docker", "exec", cid, "sh", "-c",
|
||||
"while :; do cat /sys/fs/cgroup/memory.current; sleep 0.05; done"],
|
||||
stdout=subprocess.PIPE, text=True)
|
||||
|
||||
def run(self) -> None:
|
||||
for line in self.proc.stdout:
|
||||
if line.strip().isdigit():
|
||||
self.values.append(int(line))
|
||||
|
||||
def stop(self) -> None:
|
||||
self.proc.kill()
|
||||
|
||||
|
||||
def actor(client: httpx.Client) -> tuple[str, str]:
|
||||
name = "mem_" + uuid.uuid4().hex[:10]
|
||||
client.post("/api/v1/users", json={"username": name, "display_name": "bench", "password": PASSWORD}).raise_for_status()
|
||||
import base64
|
||||
basic = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode()
|
||||
token = client.post("/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic}).json()["token"]
|
||||
me = client.get("/api/v1/users/me", headers={"Authorization": "Bearer " + token}).json()
|
||||
chat = client.post("/api/v1/chats", headers={"Authorization": "Bearer " + token},
|
||||
json={"title": "mem", "member_ids": [me["id"]]}).json()
|
||||
return token, chat["id"]
|
||||
|
||||
|
||||
def big_jpeg(width: int, height: int, seed: int) -> bytes:
|
||||
"""Large progressive JPEG (smooth content keeps it < 10 MiB): the costliest file to check."""
|
||||
image = Image.linear_gradient("L").resize((width, height)).convert("RGB")
|
||||
image.putpixel((seed % width, 0), (seed % 255, 0, 0))
|
||||
out = io.BytesIO()
|
||||
image.save(out, "JPEG", quality=90, progressive=True, subsampling=0)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def run_scenario(name: str, env: dict, files: list[tuple[bytes, str]]) -> dict:
|
||||
recreate(env)
|
||||
ids = replicas()
|
||||
idle = {cid: cg(cid, "memory.current") for cid in ids}
|
||||
client = httpx.Client(base_url=BASE, timeout=120)
|
||||
token, chat_id = actor(client)
|
||||
barrier = threading.Barrier(len(files))
|
||||
results: list[tuple[int, float, str]] = [None] * len(files) # type: ignore[list-item]
|
||||
|
||||
def upload(i: int, data: bytes, ctype: str) -> None:
|
||||
c = httpx.Client(base_url=BASE, timeout=120)
|
||||
barrier.wait()
|
||||
started = time.perf_counter()
|
||||
r = c.post(f"/api/v1/chats/{chat_id}/attachments?filename=f{i}", content=data,
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": ctype})
|
||||
reason = r.json()["error"]["message"] if r.status_code != 201 else ""
|
||||
results[i] = (r.status_code, time.perf_counter() - started, r.headers.get("x-instance-id", "-"), reason)
|
||||
c.close()
|
||||
|
||||
s3_id = sh("docker", "compose", "ps", "-q", "s3").strip()
|
||||
restarts_before = container_events()
|
||||
samplers = [Sampler(cid) for cid in ids] + [Sampler(s3_id)]
|
||||
for s in samplers:
|
||||
s.start()
|
||||
time.sleep(0.5)
|
||||
threads = [threading.Thread(target=upload, args=(i, d, t)) for i, (d, t) in enumerate(files)]
|
||||
wall = time.perf_counter()
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
wall = time.perf_counter() - wall
|
||||
time.sleep(0.5)
|
||||
for s in samplers:
|
||||
s.stop()
|
||||
per_replica = {}
|
||||
for cid, s in zip(ids, samplers[:-1]):
|
||||
hostname = sh("docker", "inspect", "-f", "{{.Config.Hostname}}", cid).strip()
|
||||
per_replica[hostname] = {
|
||||
"idle_mib": round(idle[cid] / MiB, 1),
|
||||
"peak_mib": round(cg(cid, "memory.peak") / MiB, 1),
|
||||
"sampled_max_mib": round(max(s.values or [0]) / MiB, 1),
|
||||
"python_vmhwm_mib": round(vmhwm(cid) / MiB, 1),
|
||||
"uploads_served": sum(1 for r in results if r[2] == hostname),
|
||||
"limit_mib": round(cg(cid, "memory.max") / MiB, 1),
|
||||
}
|
||||
per_replica[hostname]["peak_minus_idle_mib"] = round(per_replica[hostname]["peak_mib"]
|
||||
- per_replica[hostname]["idle_mib"], 1)
|
||||
lat = sorted(r[1] for r in results if r[0] == 201)
|
||||
codes: dict[str, int] = {}
|
||||
reasons: dict[str, int] = {}
|
||||
for r in results:
|
||||
codes[str(r[0])] = codes.get(str(r[0]), 0) + 1
|
||||
if r[3]:
|
||||
reasons[r[3]] = reasons.get(r[3], 0) + 1
|
||||
summary = {
|
||||
"scenario": name, "settings": env, "clients": len(files),
|
||||
"s3_sampled_max_mib": round(max(samplers[-1].values or [0]) / MiB, 1),
|
||||
"s3_anon_after_mib": round(memory_stat(s3_id, "anon") / MiB, 1),
|
||||
"s3_limit_mib": round(cg(s3_id, "memory.max") / MiB, 1),
|
||||
# OOM kills / restarts DURING the scenario (any container of the stand): must be empty
|
||||
"incidents": {k: v for k, v in container_events().items() if v != restarts_before.get(k)},
|
||||
"file_mib_each": round(statistics.mean(len(d) for d, _ in files) / MiB, 2),
|
||||
"types": sorted({t for _, t in files}), "status_codes": codes, "error_reasons": reasons, "wall_seconds": round(wall, 2),
|
||||
"latency_s": {"p50": round(lat[len(lat) // 2], 2), "max": round(lat[-1], 2)} if lat else None,
|
||||
"replicas": per_replica,
|
||||
}
|
||||
print(json.dumps(summary, ensure_ascii=False), flush=True)
|
||||
return summary
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--clients", type=int, default=16)
|
||||
p.add_argument("--output", default="evidence/memory")
|
||||
args = p.parse_args()
|
||||
out = ROOT / args.output
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
print("generating files ...", flush=True)
|
||||
pngs = [(imagegen.png_of_size(int(9.5 * MiB)), "image/png") for _ in range(2 * args.clients)]
|
||||
jpegs = [(big_jpeg(8000, 5000, i), "image/jpeg") for i in range(args.clients)]
|
||||
base = {"UPLOAD_CONCURRENCY": "4", "IMAGE_VERIFY_CONCURRENCY": "1"}
|
||||
n, n2 = args.clients, 2 * args.clients
|
||||
scenarios = [
|
||||
(f"png-9.4MiB x{n}, slots=4 (default)", base, pngs[:n]),
|
||||
(f"png-9.4MiB x{n2}, slots=4 (default)", base, pngs),
|
||||
(f"png-9.4MiB x{n2}, slots=16 (bound raised)", {"UPLOAD_CONCURRENCY": "16", "IMAGE_VERIFY_CONCURRENCY": "1"}, pngs),
|
||||
(f"jpeg-40Mpx-progressive-4:4:4 x{n}, verify=1 (default)", base, jpegs),
|
||||
(f"jpeg-40Mpx-progressive-4:4:4 x{n}, verify=4", {"UPLOAD_CONCURRENCY": "4", "IMAGE_VERIFY_CONCURRENCY": "4"}, jpegs),
|
||||
]
|
||||
results = []
|
||||
sh("docker", "compose", "restart", "s3") # S3 memory counters start from an idle process
|
||||
sh("docker", "compose", "up", "-d", "--wait", "s3")
|
||||
try:
|
||||
for name, env, files in scenarios:
|
||||
results.append(run_scenario(name, env, files))
|
||||
finally:
|
||||
recreate({}) # back to the compose defaults
|
||||
meta = {
|
||||
"date": time.strftime("%Y-%m-%d %H:%M:%S"), "host": platform.platform(), "cpus": os.cpu_count(),
|
||||
"commit": sh("git", "rev-parse", "--short", "HEAD").strip(),
|
||||
"api_limits": sh("docker", "inspect", "-f", "{{.HostConfig.NanoCpus}} {{.HostConfig.Memory}}",
|
||||
replicas()[0]).strip(),
|
||||
"jpeg_file_mib": round(len(jpegs[0][0]) / MiB, 2), "png_file_mib": round(len(pngs[0][0]) / MiB, 2),
|
||||
}
|
||||
(out / "summary.json").write_text(json.dumps({"meta": meta, "scenarios": results}, ensure_ascii=False, indent=1),
|
||||
encoding="utf-8")
|
||||
print(json.dumps(meta, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user