Files
mtusi2026lab6/student-tests/lab6/observability.py

648 lines
36 KiB
Python

"""Executable evidence for the Lab 6 grade 4 contract."""
import base64
from collections import defaultdict
import hashlib
import json
import math
from pathlib import Path
import re
import secrets
import time
import uuid
from runtime import Pending
from signals import (
Client, Endpoint, Failure, Privacy, Prometheus, ROOT, Unavailable, ancestors,
check, child_of, log_rows, log_streams, norm_key, received_error, trace_nodes, wait,
)
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
PREFIX = "messenger_"
HTTP = PREFIX + "http_requests_total"
JOBS = PREFIX + "jobs_total"
HISTOGRAMS = tuple(PREFIX + suffix for suffix in (
"http_request_duration_seconds", "job_duration_seconds", "attachment_time_to_ready_seconds",
))
GAUGES = tuple(PREFIX + suffix for suffix in (
"queue_depth", "queue_oldest_age_seconds", "worker_busy", "worker_capacity",
"db_pool_connections", "db_pool_waiting",
))
DYNAMIC_LABELS = {
"user_id", "chat_id", "message_id", "attachment_id", "request_id", "trace_id", "span_id",
"url", "raw_url", "http_target", "url_path", "filename", "text", "username", "token", "password",
}
UUID_PATTERN = re.compile(r"(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
def trace_context():
trace_id, parent = secrets.token_hex(16), secrets.token_hex(8)
return trace_id, parent, {"traceparent": f"00-{trace_id}-{parent}-01", "tracestate": "lab6=synthetic"}
class Checks:
def __init__(self, args, stand):
self.a, self.stand, self.e = args, stand, stand.e
self.api = Client(args.base_url, timeout=4)
self.prom = Prometheus(Endpoint("Prometheus", args.prometheus))
self.tempo = Endpoint("Tempo", args.tempo)
self.loki = Endpoint("Loki", args.loki)
grafana_headers = {}
if args.grafana_password_file:
raw = Path(args.grafana_password_file).read_text().strip()
grafana_headers["Authorization"] = "Basic " + base64.b64encode(("admin:" + raw).encode()).decode()
self.grafana = Endpoint("Grafana", args.grafana, grafana_headers)
self.privacy = Privacy()
self.privacy_traces = {}
self.start_ns = time.time_ns()
def canary_header(self, name):
trace, parent, headers = trace_context()
self.privacy_traces[name] = (trace, parent)
return headers
def actor(self, *, canaries=False):
nonce = uuid.uuid4().hex
name, password = "lab6_" + nonce[:20], "Lab6Secret-" + nonce + "-end"
payload = {"username": name, "password": password, "display_name": "Lab 6 fixture"}
credential = base64.b64encode(f"{name}:{password}".encode()).decode()
registration = self.canary_header("registration_password") if canaries else {}
login = self.canary_header("successful_login") if canaries else {}
user = self.api.call("POST", "/api/v1/users", 201, body=payload, schema="User", headers=registration)["json"]
sess = self.api.call("POST", "/api/v1/auth/sessions", 201,
headers={**login, "Authorization": "Basic " + credential}, schema="Session")["json"]
check(sess["user"] == user, "session identity changed")
if canaries:
self.privacy.add("registration_password", password)
self.privacy.add("basic_credentials", credential)
self.privacy.add("bearer_token", sess["token"])
bad = base64.b64encode(f"{name}:{password}-bad".encode()).decode()
self.privacy.add("rejected_basic_credentials", bad)
self.api.call("POST", "/api/v1/auth/sessions", 401,
headers={**self.canary_header("rejected_login"), "Authorization": "Basic " + bad})
return {"id": user["id"], "token": sess["token"], "user": user}
def chat(self, actor):
return self.api.call("POST", "/api/v1/chats", 201, actor=actor, schema="Chat",
body={"title": "Lab 6 synthetic chat", "member_ids": [actor["id"]]})["json"]
def upload(self, actor, chat, headers=None, filename="sample.png"):
path = f"/api/v1/chats/{chat['id']}/attachments?filename={filename}"
r = self.api.call("POST", path, 202, actor=actor, raw=SAMPLE, schema="Attachment",
headers={"Content-Type": "image/png", **(headers or {})})
check(r["json"]["status"] == "queued" and r["json"]["sha256"] == hashlib.sha256(SAMPLE).hexdigest(),
"upload was not a valid durable acceptance")
return r
def ready(self, actor, attachment):
path = "/api/v1/attachments/" + attachment["id"]
def completed():
r = self.api.call("GET", path, actor=actor, schema="Attachment")["json"]
check(r["status"] != "failed", "a confirmed attachment failed")
return r if r["status"] == "ready" else None
current = wait(completed, self.a.timeout, "a confirmed upload never became ready")
original = self.api.call("GET", path + "/content", actor=actor)
check(original["bytes"] == SAMPLE and current["sha256"] == attachment["sha256"],
"original changed during fault recovery")
self.e.event("attachment_ready", attachment=attachment["id"], sha256=current["sha256"])
return current
def backend_readiness(self):
for endpoint in (self.tempo, self.loki):
wait(lambda: endpoint.get("/ready", raw=True), self.a.timeout, f"{endpoint.name} not ready")
wait(lambda: self.prom.http.get("/-/ready", raw=True), self.a.timeout, "Prometheus not ready")
wait(lambda: self.grafana.get("/api/health").get("database") == "ok",
self.a.timeout, "Grafana not healthy")
def provisioning(self):
sources = self.grafana.get("/api/datasources")
check({"prometheus", "loki", "tempo"} <= {s["type"] for s in sources}, "Grafana datasources not provisioned")
dashboards = self.grafana.get("/api/search", {"type": "dash-db"})
titles, expressions, panels_checked = [], [], []
for item in dashboards:
dash = self.grafana.get("/api/dashboards/uid/" + item["uid"])
if not dash.get("meta", {}).get("provisioned"):
continue
titles.append(dash["dashboard"]["title"])
def panels(node):
for panel in node:
for target in panel.get("targets", []):
datasource = target.get("datasource", panel.get("datasource", {}))
if datasource.get("type") == "prometheus" and "expr" in target:
yield panel["title"], target["expr"]
yield from panels(panel.get("panels", []))
for title, expr in panels(dash["dashboard"].get("panels", [])):
# Parse/evaluate exactly the displayed query. An empty series
# is normal before a fault or the second scrape for rate().
self.prom.query(expr)
expressions.append(expr)
panels_checked.append(title)
check(titles and expressions, "no provisioned Grafana dashboard expressions")
flat = " ".join(expressions)
required = [HTTP, PREFIX + "queue_depth", PREFIX + "queue_oldest_age_seconds",
PREFIX + "db_pool_connections", PREFIX + "db_pool_waiting",
PREFIX + "worker_busy", PREFIX + "worker_capacity", JOBS, HISTOGRAMS[1]]
check(all(name in flat for name in required), "dashboard omits required signals")
check(re.search(r"(?i)cpu", flat) and re.search(r"(?i)(?:memory|_rss)", flat),
"dashboard omits process or container CPU/RAM")
for quantile in (50, 95, 99):
filtered = [e for e in expressions if re.search(
rf"histogram_quantile\s*\(\s*0\.{quantile}0*\s*,", e.replace("0.5,", "0.50,"))]
check(any(HISTOGRAMS[0] + "_bucket" in e and re.search(r"\b(?:sum|rate)\b", e)
for e in filtered), f"dashboard does not derive p{quantile} from HTTP histogram")
check(any(HTTP in e and "5xx" in e and "/" in e for e in expressions),
"dashboard has no explicit HTTP error ratio")
rules = [wait(lambda: self.prom.alert(name), self.a.timeout, f"no evaluation of {name}")
for name in (self.a.error_alert, self.a.lag_alert)]
for rule in rules:
check(rule["expr"] and rule["for_s"] > 0 and rule["interval_s"] > 0
and rule["annotations"], "incomplete alert rule")
self.e.event("provisioning", datasources=[s["type"] for s in sources],
dashboards=titles, panels=panels_checked, expressions=expressions, rules=rules)
def metric(self, expression, predicate, reason):
def observe():
val = self.prom.scalar(expression, allow_empty=True)
return {"value": val} if val is not None and predicate(val) else None
result = wait(observe, self.a.timeout, reason)
self.e.event("prometheus_value", expr=expression, **result)
return result["value"]
def metrics(self):
actor = self.actor()
self.ready(actor, self.upload(actor, self.chat(actor))["json"])
tracked_before = self.prom.query("{__name__=~\"messenger_http_.*\"}")
send_count = f'sum({HTTP}{{method="POST",route="/api/v1/chats/{{chat_id}}/messages",status_class="2xx"}})'
previous_sends = self.prom.scalar(send_count, allow_empty=True) or 0
for _ in range(8):
chat = self.chat(actor)
self.api.message(actor, chat, "Lab6 metric fixture")
self.metric(f"sum({HTTP}{{method=\"POST\",status_class=\"2xx\"}})",
lambda n: n > 0, "no successful HTTP request counters")
route_set = set(json.loads((ROOT / "contracts/openapi.json").read_text())["paths"])
# Wait for the high-cardinality fixture routes to reach the collector.
self.metric(send_count, lambda n: n >= previous_sends + 8,
"eight new synthetic chats did not use the same route label")
series = self.prom.read("series", {"match[]": '{__name__=~"messenger_.*"}',
"start": str(self.start_ns / 1e9)})
check(bool(series), "no business metric series")
self.privacy.check(series, "Prometheus labels")
for row in series:
for field, value in row.items():
normalized = norm_key(field)
check(normalized not in DYNAMIC_LABELS, "forbidden high-cardinality metric label")
check(not UUID_PATTERN.search(value) or normalized in ("instance", "service_instance_id"),
"unexpected dynamic identifier in metric labels")
if "route" in row:
check(row["route"] in route_set | {"unmatched", "unknown", "<unmatched>"},
"HTTP route is not an OpenAPI template")
if "status_class" in row:
check(re.fullmatch(r"[1-5]xx", row["status_class"]) is not None,
"HTTP status label is not a status class")
http_rows = self.prom.query(HTTP)
job_rows = wait(lambda: self.prom.query(JOBS), self.a.timeout, "no observed job counters")
check(http_rows and all({"method", "route", "status_class"} <= r["labels"].keys() for r in http_rows),
"HTTP counter lacks required labels")
check(job_rows and all({"job_type", "outcome"} <= r["labels"].keys() for r in job_rows)
and any(r["value"] and r["value"] > 0 for r in job_rows), "jobs counter lacks observations or dimensions")
self.e.event("metric_cardinality", http_before=len(tracked_before), current_series=len(series),
series=series, http=http_rows, jobs=job_rows, previous_sends=previous_sends)
for histogram in HISTOGRAMS:
self.metric(f"sum({histogram}_count)", lambda n: n > 0, f"{histogram} has no observations")
self.histogram(histogram)
for gauge in GAUGES:
rows = wait(lambda: self.prom.query(gauge), self.a.timeout, f"missing gauge {gauge}")
check(all(r["value"] is not None and r["value"] >= 0 for r in rows), f"invalid gauge values for {gauge}")
if gauge == PREFIX + "db_pool_connections":
check({r["labels"].get("state") for r in rows} & {"used", "acquired", "in_use"},
"DB pool has no used/acquired state")
self.e.event("prometheus_gauge", metric=gauge, samples=rows)
for suffix in ("process_cpu_time_seconds_total", "process_memory_bytes"):
self.metric(f"max({PREFIX}{suffix})", lambda n: n > 0, f"missing live process metric {suffix}")
self.metric(f"max({PREFIX}worker_capacity)", lambda n: n > 0, "worker capacity is not positive")
def histogram(self, name):
at = time.time()
buckets = self.prom.query(name + "_bucket", at)
count = self.prom.query(name + "_count", at)
sums = self.prom.query(name + "_sum", at)
groups = defaultdict(list)
def signature(labels):
return tuple(sorted((k, v) for k, v in labels.items() if k not in ("__name__", "le")))
for row in buckets:
groups[signature(row["labels"])].append((float(row["labels"]["le"]), row["value"]))
counts = {signature(r["labels"]): r["value"] for r in count}
check(bool(groups) and set(counts) == set(groups), "histogram has inconsistent count labels")
for labels, ranges in groups.items():
ordered = sorted(ranges)
check(len(ordered) >= 3 and ordered[-1] == (math.inf, counts[labels]),
"histogram lacks real finite boundaries or +Inf/count agreement")
check(all(v is not None and v >= 0 for _, v in ordered)
and [v for _, v in ordered] == sorted(v for _, v in ordered), "non-cumulative histogram buckets")
check({signature(r["labels"]) for r in sums} == set(counts) and
all(r["value"] is not None and r["value"] >= 0 for r in sums), "invalid histogram sums")
quantiles = {}
route_filter = '{route!~"/health/(live|ready)"}' if name == HISTOGRAMS[0] else ""
for p in (0.50, 0.95, 0.99):
expr = f"histogram_quantile({p}, sum by (le) ({name}_bucket{route_filter}))"
quantiles[str(p)] = self.prom.scalar(expr, at=at)
check(0 <= quantiles["0.5"] <= quantiles["0.95"] <= quantiles["0.99"], "invalid histogram quantiles")
self.e.event("histogram", metric=name, buckets=buckets, count=count, sums=sums, quantiles_seconds=quantiles)
def retry_trace(self):
if not any(Path(f).name == "compose.storage-fault.test.yaml" for f in self.a.compose_file):
raise Pending("retry trace requires the worker-only S3 network test override")
actor = self.actor(canaries=True)
chat = self.chat(actor)
message = "Lab6Body-" + uuid.uuid4().hex
self.privacy.add("message_text", message)
self.api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, actor=actor,
body={"text": message}, schema="Message",
headers={**self.canary_header("message_body"), "Idempotency-Key": uuid.uuid4().hex})
filename = "Lab6Filename-" + uuid.uuid4().hex + ".png"
self.privacy.add("filename", filename)
self.privacy.add("image_body", base64.b64encode(SAMPLE).decode()[:192])
trace, caller, headers = trace_context()
cid = self.stand.one(self.a.worker_service)
try:
with self.stand.stopped(self.a.relay_service):
response = self.upload(actor, chat, headers, filename)
att = response["json"]
self.stand.storage_network(cid, False)
attempts = wait(lambda: self.retry_attempts(att), self.a.timeout,
"worker did not persist a transient retry", interval=0.2)
self.e.event("trace_retry_injected", attachment=att["id"], attempts=attempts)
finally:
self.stand.storage_network(cid, True)
self.ready(actor, att)
attempts = self.stand.attachment_attempts(att["id"])
check(attempts[-1]["outcome"] == "ready" and any(a["outcome"] == "retry" for a in attempts),
"restored job did not recover from the observed retry")
carrier = self.stand.outbox_carrier(att["id"])
check(len(carrier) >= 2 and all(
re.fullmatch(rf"00-{trace}-[0-9a-f]{{16}}-01", row["traceparent"] or "") is not None
and "lab6=synthetic" in (row["tracestate"] or "").split(",")
for row in carrier), "initial or retry outbox lost the W3C trace context")
self.e.event("trace_retry_recovered", attempts=attempts, carrier=carrier)
rid = response["headers"]["X-Request-Id"]
try:
nodes, roles = wait(lambda: self.upload_chain(trace, caller), self.a.timeout,
"Tempo did not expose the causal upload/relay/worker/S3/DB chain")
except Failure:
# Capture permissible fields of a partial graph if the failure is
# missing edges. Privacy errors still prohibit artifact writes.
incomplete = self.fetch_trace(trace)
if incomplete:
self.save_trace(trace, incomplete, {})
raise
self.save_trace(trace, nodes, roles)
self.correlate_logs(trace, rid, nodes, roles)
for label, (canary_trace, upstream) in self.privacy_traces.items():
observed = wait(lambda: self.canary_trace(canary_trace, upstream), self.a.timeout,
f"canary trace {label} was not exported")
self.e.event("tempo_privacy_canary", label=label, trace_id=canary_trace,
observed_span_count=len(observed))
def retry_attempts(self, att):
rows = self.stand.attachment_attempts(att["id"])
check(not any(r["outcome"] == "failed" for r in rows), "S3 fault exhausted all attempts")
return rows if any(r["outcome"] == "retry" for r in rows) else None
def fetch_trace(self, trace):
payload = self.tempo.get("/api/traces/" + trace, absent=404)
if payload is None:
return {}
self.privacy.check(payload, "Tempo trace")
return trace_nodes(payload, trace)
def canary_trace(self, trace, caller):
nodes = self.fetch_trace(trace)
return nodes if any(s["parent"] == caller and s["kind"] == "2" for s in nodes.values()) else None
def upload_chain(self, trace, caller):
nodes = self.fetch_trace(trace)
server = [s for s in nodes.values() if s["kind"] == "2" and s["parent"] == caller
and s["resource"].get("service.name") == self.a.api_name]
if not server:
return None
check(len(server) == 1, "upload trace has multiple entry spans")
root = server[0]
route = root["attrs"].get("http.route") or root["name"]
check("/attachments" in route, "incoming trace parent belongs to another endpoint")
producers = [s for s in nodes.values() if s["kind"] == "4" and child_of(s, root, nodes)
and s["resource"].get("service.name") == self.a.relay_name]
consumers = [s for s in nodes.values() if s["kind"] == "5"
and s["resource"].get("service.name") == self.a.worker_name
and any(child_of(s, p, nodes) for p in producers)]
failed = [s for s in consumers if received_error(s)]
successful = [s for s in consumers if not received_error(s)]
if len(producers) < 2 or not failed or not successful:
return None
publisher_ids = {p["id"] for p in producers}
def nearest_publisher(consumer):
return next(p["id"] for p in ancestors(consumer, nodes) if p["id"] in publisher_ids)
if not any(nearest_publisher(f) != nearest_publisher(s) for f in failed for s in successful):
return None
s3 = [s for s in nodes.values() if self.dependency(s, "s3")
and any(child_of(s, c, nodes) for c in successful)]
pg = [s for s in nodes.values() if self.dependency(s, "postgres")
and any(child_of(s, c, nodes) for c in successful)]
failed_s3 = [s for s in nodes.values() if self.dependency(s, "s3") and received_error(s)
and any(child_of(s, c, nodes) for c in failed)]
if not (s3 and pg and failed_s3):
return None
# W3C tracestate may be absent from OTLP output despite being
# carried internally. When it is exported, preserve the actual value.
return nodes, {"server": [root["id"]], "producer": [p["id"] for p in producers],
"consumer_error": [s["id"] for s in failed],
"consumer_success": [s["id"] for s in successful],
"s3": [s["id"] for s in s3], "postgres": [s["id"] for s in pg],
"failed_s3": [s["id"] for s in failed_s3]}
@staticmethod
def dependency(span, name):
attrs = span["attrs"]
attrs = [attrs.get(k, "") for k in ("db.system", "db.system.name", "rpc.service",
"aws.service", "messenger.dependency", "server.address")]
search = " ".join([span["name"], *map(str, attrs)]).lower()
return name in search or (name == "postgres" and
re.search(r"\b(?:pgx|sql|db)[./ :]", search) is not None)
def save_trace(self, trace, nodes, roles):
for role, ids in roles.items():
for sid in ids:
resource = nodes[sid]["resource"]
check(all(resource.get(k) for k in ("service.name", "service.version", "service.instance.id",
"deployment.environment.name")),
f"missing resource attributes for {role}")
attrs = ("http.route", "http.request.method", "http.response.status_code", "db.system.name",
"db.system", "messaging.system", "messaging.operation.type", "request_id", "job_id")
self.e.event("tempo_trace", trace_id=trace, roles=roles,
nodes=[{**{k: s[k] for k in ("id", "parent", "kind", "name", "status", "duration_ms",
"trace_state")},
"resource": {k: s["resource"].get(k) for k in ("service.name", "service.version",
"service.instance.id", "deployment.environment.name")},
"attributes": {k: s["attrs"][k] for k in attrs if k in s["attrs"]}}
for s in nodes.values()])
def correlate_logs(self, trace, rid, nodes, roles):
def collect():
# Query by real stream labels. Inspect the whole returned sample,
# including unrelated signup/login canaries in the same interval.
streams = log_streams(self.loki, self.a.log_selector, self.start_ns)
self.privacy.check(streams, "Loki logs")
targets = {self.a.api_name: roles["server"]}
consumers = roles.get("consumer_success", []) + roles.get("consumer_error", [])
if consumers:
targets[self.a.worker_name] = consumers
matched = {}
rows = list(log_rows(streams))
for fields, ts in rows:
self.privacy.check(fields, "decoded Loki log")
if fields.get("trace_id", fields.get("traceid")) != trace:
continue
service = fields.get("service_name", fields.get("service"))
sid = fields.get("span_id", fields.get("spanid"))
if service not in targets or sid not in nodes or not any(
sid == root or child_of(nodes[sid], nodes[root], nodes) for root in targets[service]
):
continue
request_id = fields.get("request_id", fields.get("requestid"))
if service == self.a.api_name and request_id != rid:
continue
severity = fields.get("severity_text", fields.get("severity", fields.get("level")))
event = fields.get("event", fields.get("msg", fields.get("message")))
if severity and isinstance(event, str) and event and int(ts) > 0:
matched[service] = {"timestamp_ns": ts, "trace_id": trace, "span_id": sid,
"request_id": request_id, "severity": severity, "event": event[:180]}
return (matched, len(rows)) if set(matched) == set(targets) else None
correlated, count = wait(collect, self.a.timeout, "Loki lacked logs with valid trace/span/request correlation")
self.e.event("loki_correlation", matched=correlated, examined=count, privacy_canaries=sorted(self.privacy.markers))
def transition(self, name, desired, started, seconds, tick=None):
last = None
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
row = self.prom.alert(name)
except Unavailable:
time.sleep(0.5)
continue
if row["state"] != last:
self.e.event("alert_observed", **row)
last = row["state"]
if last == desired:
elapsed = time.monotonic() - started
self.e.event("alert_transition", name=name,
state="resolved" if desired == "inactive" else desired, seconds=elapsed)
return
if tick:
tick()
time.sleep(0.4)
raise Failure(f"alert {name} did not reach {desired}; last state {last}")
def require_inactive(self, name):
last = None
def clean_baseline():
nonlocal last
rule = self.prom.alert(name)
if rule["state"] != last:
self.e.event("alert_baseline_observed", **rule)
last = rule["state"]
return rule if rule["state"] == "inactive" else None
rule = wait(clean_baseline, self.a.alert_timeout, f"{name} stayed active before fault")
self.e.event("alert_baseline", **rule)
def lag_incident(self):
alert = self.a.lag_alert
self.require_inactive(alert)
actor = self.actor()
room = self.chat(actor)
with self.stand.stopped(self.a.worker_service):
start = time.monotonic()
pending = [self.upload(actor, room)["json"] for _ in range(3)]
self.metric(f'max({PREFIX}queue_depth{{queue="{self.a.queue}"}})', lambda n: n >= 1,
"paused worker did not leave durable backlog")
self.metric(f'max({PREFIX}queue_oldest_age_seconds{{queue="{self.a.queue}"}})',
lambda n: n > self.a.lag_threshold, "oldest job did not grow past the lag threshold")
self.transition(alert, "firing", start, self.a.alert_timeout)
for att in pending:
response = self.api.call("GET", f"/api/v1/attachments/{att['id']}", actor=actor, schema="Attachment")
check(response["json"]["status"] == "queued", "work advanced with the only worker stopped")
self.api.call("GET", "/api/v1/users/me", actor=actor, schema="User")
recovered = time.monotonic()
for att in pending:
self.ready(actor, att)
self.metric(f'max({PREFIX}queue_depth{{queue="{self.a.queue}"}})', lambda n: n == 0,
"worker restoration did not drain the backlog")
self.transition(alert, "inactive", recovered, self.a.alert_timeout)
def db_incident(self):
alert = self.a.error_alert
self.require_inactive(alert)
actor = self.actor()
samples = []
timings = []
started = time.monotonic()
def one(expect_error):
trace, caller, headers = trace_context()
response = self.api.call("GET", "/api/v1/users/me", 503 if expect_error else 200,
actor=actor, headers=headers, schema="User")
if expect_error:
check(response["json"]["error"]["code"] == "unavailable", "DB blockage did not produce API unavailable")
samples.append((trace, caller, response["headers"]["X-Request-Id"]))
timings.append(response["elapsed"])
else:
check(response["json"] == actor["user"], "session identity changed after DB restoration")
return response
with self.stand.blocked_database_read():
started = time.monotonic()
self.prom.alert(alert)
self.api.call("GET", "/health/ready", schema="Health")
one(True)
self.transition(alert, "firing", started, self.a.alert_timeout, lambda: one(True))
self.metric(f"sum({HTTP}{{status_class=\"5xx\",route=\"/api/v1/users/me\"}})",
lambda n: n >= 5, "DB blockage did not produce HTTP 5xx telemetry")
self.e.event("db_errors", count=len(samples), elapsed_s=timings,
kind="users-table exclusive lock with healthy SQL connectivity")
recovered = time.monotonic()
one(False)
self.transition(alert, "inactive", recovered, self.a.alert_timeout, lambda: one(False))
def affected():
for trace, caller, rid in samples[:3]:
nodes = self.fetch_trace(trace)
server = [s for s in nodes.values() if s["parent"] == caller and s["kind"] == "2"
and s["resource"].get("service.name") == self.a.api_name]
if not server:
continue
root = server[0]
db = [s for s in nodes.values() if self.dependency(s, "postgres") and received_error(s)
and child_of(s, root, nodes)]
status = root["attrs"].get("http.response.status_code", root["attrs"].get("http.status_code"))
if str(status) == "503" and db:
return (trace, rid, nodes, {"server": [root["id"]], "failed_postgres": [s["id"] for s in db]})
return None
trace, rid, nodes, roles = wait(affected, self.a.timeout, "DB outage trace lacked a failed PostgreSQL child")
self.save_trace(trace, nodes, roles)
self.correlate_logs(trace, rid, nodes, roles)
def collector_policy(self):
config = Path(self.a.collector_config).read_text()
def section(key, level, value=config):
indent = " " * level
match = re.search(rf"(?m)^{indent}{re.escape(key)}:\s*\n"
rf"((?:{indent} +[^\n]*\n|\n)*)", value)
return match.group(1) if match else ""
processors = section("processors", 0)
memory = section("memory_limiter", 2, processors)
batch = section("batch", 2, processors)
pipeline = section("logs", 4, section("pipelines", 2, section("service", 0)))
exporter = section("otlphttp/loki", 2, section("exporters", 0))
check(re.search(r"limit_mib:\s*[1-9][0-9]*", memory)
and re.search(r"send_batch_max_size:\s*[1-9][0-9]*", batch)
and re.search(r"processors:\s*\[\s*memory_limiter\s*,\s*batch\s*\]", pipeline)
and re.search(r"exporters:\s*\[\s*otlphttp/loki\s*\]", pipeline),
"configured log pipeline lacks memory limiter/batch or Loki exporter binding")
queue = re.search(r"queue_size:\s*([1-9][0-9]*)", exporter)
retry = re.search(r"max_elapsed_time:\s*([1-9][0-9]*(?:ms|s|m))\b", exporter)
check(queue and retry, "Loki queue or retry has no explicit finite bound")
self.e.event("collector_policy", loki_queue_capacity_config=int(queue.group(1)), retry_window=retry.group(1),
processors=["memory_limiter", "batch"])
return int(queue.group(1))
def observed_http_telemetry(self, actor):
trace, caller, headers = trace_context()
response = self.api.call("GET", "/api/v1/users/me", actor=actor, schema="User", headers=headers)
def fresh_trace():
nodes = self.fetch_trace(trace)
server = [s["id"] for s in nodes.values()
if s["parent"] == caller and s["kind"] == "2"
and s["resource"].get("service.name") == self.a.api_name]
return (nodes, {"server": server}) if server else None
nodes, roles = wait(fresh_trace, self.a.timeout, "new control trace did not reach Tempo")
self.correlate_logs(trace, response["headers"]["X-Request-Id"], nodes, roles)
return trace
def loki_outage(self):
capacity_config = self.collector_policy()
collector = self.stand.one(self.a.collector_service)
before = self.stand.state(collector)
check(before["status"] == "running" and before["memory"] > 0, "Collector has no hard RAM limit")
for expr in (self.a.queue_capacity_query, self.a.queue_size_query, self.a.rss_query):
self.metric(expr, lambda n: n >= 0, f"missing bounded-buffer metric {expr}")
actor = self.actor()
chat = self.chat(actor)
warm_trace = self.observed_http_telemetry(actor)
self.e.event("collector_primed", trace_id=warm_trace, rss_bytes=self.prom.scalar(self.a.rss_query))
previous = self.prom.scalar(self.a.dropped_query, allow_empty=True)
previous = 0 if previous is None else previous
confirmed = {}
max_rss = max_queue = reads = 0
maximum_dropped = previous
lag_start = None
with self.stand.stopped(self.a.loki_service):
started = time.monotonic()
try:
self.loki.get("/ready", raw=True)
except Unavailable:
self.e.event("logs_backend_unreachable")
else:
raise Failure("Loki responded while supposedly stopped")
next_sample = 0
while time.monotonic() - started < self.a.loki_window:
self.api.call("GET", "/api/v1/users/me", actor=actor, schema="User")
reads += 1
if len(confirmed) < 8:
response = self.api.message(actor, chat, "While Loki is offline " + uuid.uuid4().hex)
confirmed[response["json"]["id"]] = response["json"]
if time.monotonic() >= next_sample:
dropped = self.prom.scalar(self.a.dropped_query, allow_empty=True)
queue = self.prom.scalar(self.a.queue_size_query)
capacity = self.prom.scalar(self.a.queue_capacity_query)
rss = self.prom.scalar(self.a.rss_query)
self.e.event("loki_outage_sample", dropped=dropped, queue=queue, capacity=capacity, rss_bytes=rss,
hard_limit_bytes=before["memory"], seconds_offline=time.monotonic()-started)
check(0 < capacity <= capacity_config and 0 <= queue <= capacity,
"collector exceeded the configured queue capacity")
check(0 < rss < before["memory"], "collector RSS reached the configured container RAM limit")
max_rss, max_queue = max(max_rss, rss), max(max_queue, queue)
maximum_dropped = max(maximum_dropped, dropped if dropped is not None else previous)
if dropped is not None and dropped > previous and lag_start is None:
lag_start = time.monotonic()-started
next_sample = time.monotonic() + 2
time.sleep(0.10)
check(lag_start is not None, "no increasing loss counter observed while Loki was stopped")
after = self.stand.state(collector)
check((before["id"], before["started_at"], before["restarts"]) ==
(after["id"], after["started_at"], after["restarts"]) and not after["oom"]
and after["status"] == "running", "collector restarted/OOMed during Loki outage")
observed = self.api.call("GET", f"/api/v1/chats/{chat['id']}/messages", actor=actor,
schema="MessagePage")["json"]
check(len(observed["items"]) == len(confirmed) == 8 and
{m["id"]:m for m in observed["items"]} == confirmed, "confirmed writes changed during logging outage")
wait(lambda: self.loki.get("/ready", raw=True), self.a.timeout, "Loki did not recover")
recovered_trace = self.observed_http_telemetry(actor)
self.e.event("loki_outage_verified", phase_seconds=self.a.loki_window, time_to_loss_s=lag_start,
initial_dropped=previous, dropped_delta=maximum_dropped-previous,
peak_rss_bytes=max_rss, peak_queue_size=max_queue, hard_limit_bytes=before["memory"],
successful_reads=reads, preserved_messages=len(confirmed), recovered_trace_id=recovered_trace,
collector=after)