test(observability): await measured recovery and verify store persistence

This commit is contained in:
2026-11-20 16:36:18 +03:00
parent ba1c658bd7
commit e11ee51e90
8 changed files with 11917 additions and 9 deletions
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -15,7 +15,7 @@ processors:
exporters:
prometheus:
endpoint: 0.0.0.0:8889
metric_expiration: 5m
metric_expiration: 15s
resource_constant_labels:
included:
- service.name
+249
View File
@@ -0,0 +1,249 @@
"""Derive tables and a figure from completed observations, never simulated data."""
import argparse
import csv
import json
import math
from collections import Counter
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def quantile(values, fraction):
ordered = sorted(values)
return (
ordered[max(0, math.ceil(len(ordered) * fraction) - 1)]
if ordered
else None
)
def main():
parser = argparse.ArgumentParser()
parser.add_argument("input", type=Path)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
report = json.loads(args.input.read_text())
assert report["complete"] and report["scope"] == "full30m"
assert report["elapsed_seconds"] >= 1800
with (args.input.parent / report["requests_csv"]).open() as stream:
requests = list(csv.DictReader(stream))
samples = report["samples"]
origin = samples[0]["at"]
summaries = []
for phase in report["phases"]:
rows = [r for r in requests if r["phase"] == phase["name"]]
successful = [
float(r["seconds"]) for r in rows if r["status"] == "201"
]
elapsed = phase["end"] - phase["start"]
summaries.append(
{
"phase": phase["name"],
"seconds": round(elapsed, 3),
"started_requests": len(rows),
"statuses": dict(Counter(r["status"] for r in rows)),
"successful_rps": round(len(successful) / elapsed, 3),
"success_p50_ms": round(quantile(successful, 0.5) * 1000, 3)
if successful
else None,
"success_p95_ms": round(quantile(successful, 0.95) * 1000, 3)
if successful
else None,
"success_p99_ms": round(quantile(successful, 0.99) * 1000, 3)
if successful
else None,
"critical_firing_names": sorted(
n
for n in phase["firing"]
if n
in {
"ApiFastBurn",
"ApiSlowBurn",
"ReadyFastBurn",
"ReadySlowBurn",
}
),
"warning_firing_names": sorted(
n
for n in phase["firing"]
if n
not in {
"ApiFastBurn",
"ApiSlowBurn",
"ReadyFastBurn",
"ReadySlowBurn",
}
),
}
)
intervals = {}
for name in sorted({a["name"] for s in samples for a in s["alerts"]}):
segments, start = [], None
for sample in samples:
active = any(
a["name"] == name and a["state"] == "firing"
for a in sample["alerts"]
)
if active and start is None:
start = sample["at"]
elif not active and start is not None:
segments.append([start, sample["at"]])
start = None
if start is not None:
segments.append([start, samples[-1]["at"]])
intervals[name] = segments
gap = [
b["at"] - a["at"] for a, b in zip(samples, samples[1:], strict=False)
]
memory = [
s["signals"]["collector_memory"] / 1024**2
for s in samples
if s["signals"]["collector_memory"] is not None
]
summary = {
"source_commit": report["source_commit"],
"runtime_versions": report["runtime_versions"],
"elapsed_seconds": report["elapsed_seconds"],
"sample_count": len(samples),
"sample_gap_seconds": {
"min": min(gap),
"median": quantile(gap, 0.5),
"max": max(gap),
},
"client_quantile_method": "nearest rank of successful end-to-end writes; not histogram interpolation",
"phases": summaries,
"incidents": report["incidents"],
"firing_intervals_unix_seconds": intervals,
"short_spikes": report["short_spikes"],
"collector_rss_mib": {"min": min(memory), "max": max(memory)},
"collector_max_queued_packets_sum": max(
s["signals"]["collector_queue"] or 0 for s in samples
),
"collector_queue_capacity_sum": max(
s["signals"]["collector_queue_capacity"] or 0 for s in samples
),
"backend_outage": report["backend_outage"],
"preservation": report["preservation"],
"final_30m_sli": report["final_30m_sli"],
}
args.output.mkdir(parents=True, exist_ok=True)
(args.output / "summary.json").write_text(
json.dumps(summary, ensure_ascii=False, indent=2) + "\n"
)
with (args.output / "phases.csv").open("w") as stream:
writer = csv.DictWriter(stream, fieldnames=list(summaries[0]))
writer.writeheader()
writer.writerows(summaries)
x = [(s["at"] - origin) / 60 for s in samples]
fig, axes = plt.subplots(
4, 1, figsize=(12, 12), sharex=True, layout="constrained"
)
for axis in axes:
axis.grid(alpha=0.2)
for phase in report["phases"]:
if (
phase["name"].endswith("_sustained")
or phase["name"] == "backend_unavailable"
):
color = (
"#cf704e"
if phase["name"].startswith("api")
else "#8b79b5"
if phase["name"].startswith("ready")
else "#85919d"
)
axis.axvspan(
(phase["start"] - origin) / 60,
(phase["end"] - origin) / 60,
color=color,
alpha=0.15,
)
axes[0].plot(
x,
[(s["signals"]["api_error_ratio_1m"] or 0) * 100 for s in samples],
color="#b04a32",
label="API 5xx ratio, rolling 1 min",
)
axes[0].axhline(1, color="black", ls=":", label="1% error budget")
axes[0].set_ylabel("5xx, %")
axes[0].legend(loc="upper right")
axes[0].set_title(
"Actual 30-minute SLO experiment: DB delay, stopped worker, unavailable telemetry stores"
)
axes[1].plot(
x,
[s["signals"]["queue_depth"] for s in samples],
color="#386a9b",
label="Queued jobs",
)
axes[1].set_ylabel("Jobs")
other = axes[1].twinx()
other.plot(
x,
[s["signals"]["oldest_job_age"] for s in samples],
color="#8b579d",
label="Oldest unfinished job",
)
other.axhline(20, ls=":", color="#8b579d")
other.set_ylabel("Age, seconds")
axes[1].legend(loc="upper left")
other.legend(loc="upper right")
alert_names = [
"ApiFastBurn",
"ApiSlowBurn",
"ReadyFastBurn",
"ReadySlowBurn",
]
for index, name in enumerate(alert_names):
axes[2].broken_barh(
[
((start - origin) / 60, (end - start) / 60)
for start, end in intervals.get(name, [])
],
(index - 0.3, 0.6),
facecolors="#bd523c",
)
axes[2].set_yticks(range(4), alert_names)
axes[2].set_ylim(-0.6, 3.6)
axes[2].set_ylabel("Critical alert firing")
axes[3].plot(
x,
[
s["signals"]["collector_memory"] / 1024**2
if s["signals"]["collector_memory"] is not None
else None
for s in samples
],
color="#347465",
label="Collector RSS",
)
axes[3].axhline(
report["container_limits"]["otel"]["mem_limit"] / 1024**2,
ls=":",
color="black",
label="Container memory limit",
)
axes[3].set_ylabel("MiB")
axes[3].set_xlabel("Minutes from first observation")
other = axes[3].twinx()
other.plot(
x,
[s["signals"]["collector_queue"] for s in samples],
color="#9c6e2e",
label="Queued telemetry packets, sum",
)
other.set_ylabel("Packets")
axes[3].legend(loc="upper left")
other.legend(loc="upper right")
fig.savefig(args.output / "slo-timeline.png", dpi=150)
plt.close(fig)
print("PASS: measured phase statistics, alert intervals and timeline")
if __name__ == "__main__":
main()
+18 -6
View File
@@ -268,19 +268,28 @@ def main():
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
)
def hold(name, seconds):
def hold(name, seconds, *, until_clear=None, max_seconds=None):
load.phase = name
phase = {
"name": name,
"start": time.time(),
"planned_seconds": seconds,
"maximum_seconds": max_seconds or seconds,
}
report["phases"].append(phase)
deadline = time.monotonic() + seconds
minimum_end = time.monotonic() + seconds
deadline = time.monotonic() + (max_seconds or seconds)
start_index = len(report["samples"])
while time.monotonic() < deadline:
report["samples"].append(snapshot(name))
sample = snapshot(name)
report["samples"].append(sample)
save()
if (
until_clear is not None
and time.monotonic() >= minimum_end
and not until_clear.intersection(firing([sample]))
):
break
time.sleep(min(5, max(0, deadline - time.monotonic())))
phase["end"] = time.time()
phase["firing"] = sorted(firing(report["samples"][start_index:]))
@@ -352,14 +361,17 @@ def main():
restore_started = time.time()
restore()
restore_finished = time.time()
recovered = hold(
signal + "_recovery", 150 if signal == "api" else 240
)
expected = (
{"ApiFastBurn", "ApiSlowBurn", "ApiHighErrorRate"}
if signal == "api"
else {"ReadyFastBurn", "ReadySlowBurn", "QueueLagGrowing"}
)
recovered = hold(
signal + "_recovery",
150 if signal == "api" else 240,
until_clear=expected,
max_seconds=600,
)
assert expected <= set(degraded["firing"]), (
signal,
degraded["firing"],
+34 -2
View File
@@ -74,11 +74,15 @@ def main():
with socket.socket() as reservation:
reservation.bind(("127.0.0.1", 0))
public_port = str(reservation.getsockname()[1])
with socket.socket() as grafana_reservation:
grafana_reservation.bind(("127.0.0.1", 0))
grafana_port = str(grafana_reservation.getsockname()[1])
env = {
**os.environ,
"COMPOSE_PROJECT_NAME": project,
"API_IMAGE": "mtusi-messenger:lab6-clean-" + identity,
"PUBLIC_PORT": public_port,
"GRAFANA_PORT": grafana_port,
"VCS_REF": sha,
"COMPOSE_FILE": "compose.yaml:compose.test.yaml",
"NO_PROXY": "localhost,127.0.0.1",
@@ -132,6 +136,33 @@ def main():
receipt["http_tests"] = run(
[".venv/bin/pytest", "student-tests", "-q"], cwd=clone, env=env
)
for module, extra in [
("verify_telemetry", []),
(
"verify_observability_persistence",
["--causal-evidence", "evidence/clean-telemetry.json"],
),
]:
name = (
"telemetry"
if module == "verify_telemetry"
else "observability-persistence"
)
run(
[
".venv/bin/python",
"-m",
"scripts." + module,
"--output",
"evidence/clean-" + name + ".json",
*extra,
],
cwd=clone,
env=env,
)
receipt[name] = json.loads(
(clone / ("evidence/clean-" + name + ".json")).read_text()
)
run(
[
".venv/bin/python",
@@ -204,11 +235,12 @@ def main():
"relay",
"reconciler",
"controller",
"observer",
],
cwd=clone,
env=env,
).split()
assert len(ids) == 6
assert len(ids) == 7
for cid in ids:
actual = json.loads(
run(
@@ -229,7 +261,7 @@ def main():
)
assert not info["HostConfig"]["PortBindings"]
receipt[
"api_worker_relay_reconciler_runtime_hashes_and_revision_match"
"all_seven_application_roles_runtime_hashes_and_revision_match"
] = True
receipt["fsck"] = run(
["git", "fsck", "--full"], cwd=clone, env=env
+145
View File
@@ -0,0 +1,145 @@
"""Restart actual stores and compare data accepted before the restart."""
import argparse
import json
import os
import time
from datetime import UTC, datetime
import httpx
os.environ.setdefault("COMPOSE_FILE", "compose.yaml:compose.test.yaml")
from scripts.observe import fetch, logs, query, spans, wait
from scripts.stand import ROOT, command, compose
def instances():
result = {}
for role in ["prometheus", "loki", "tempo", "grafana"]:
cid = compose("ps", "-q", role)
data = json.loads(command(["docker", "inspect", cid]))[0]
result[role] = {
"started_at": data["State"]["StartedAt"],
"volumes": sorted(
m["Name"] for m in data["Mounts"] if m["Type"] == "volume"
),
"read_only": data["HostConfig"]["ReadonlyRootfs"],
"cap_drop": data["HostConfig"]["CapDrop"],
"user": data["Config"]["User"],
}
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--causal-evidence", default="evidence/telemetry-first.json"
)
parser.add_argument(
"--output", default="evidence/observability-persistence-first.json"
)
args = parser.parse_args()
output = ROOT / args.output
assert not output.exists()
causal = json.loads((ROOT / args.causal_evidence).read_text())
assert causal["complete"]
identity = causal["causal_uploads"][0]["trace_id"]
timestamp = time.time() - 20
historical = query("sum(messenger_http_requests_total)", at=timestamp)
assert historical and spans(identity) and logs(identity)["data"]["result"]
report = {
"date": datetime.now(UTC).isoformat(),
"source_commit": command(["git", "rev-parse", "HEAD"]),
"trace_id": identity,
"historical_query_at": timestamp,
"historical_before": historical,
"before": instances(),
"complete": False,
}
password = (ROOT / "secrets/grafana_password").read_text().strip()
base = "http://127.0.0.1:" + os.getenv("GRAFANA_PORT", "3006")
with httpx.Client(
base_url=base, auth=("admin", password), timeout=10, trust_env=False
) as grafana:
preferences = grafana.get("/api/user/preferences")
preferences.raise_for_status()
previous = preferences.json()
temporary = {
**previous,
"theme": "light" if previous.get("theme") != "light" else "dark",
}
try:
changed = grafana.put("/api/user/preferences", json=temporary)
changed.raise_for_status()
compose("restart", "prometheus", "loki", "tempo", "grafana")
for role, path in [
("prometheus", "/-/ready"),
("loki", "/ready"),
("tempo", "/ready"),
]:
wait(
lambda role=role, path=path: fetch(
role, path, json_result=False
),
timeout=120,
)
def grafana_ready():
try:
response = grafana.get("/api/health")
return (
response.status_code == 200
and response.json()["database"] == "ok"
)
except httpx.HTTPError:
return False
wait(grafana_ready, timeout=120)
wait(lambda: spans(identity), timeout=120)
wait(lambda: logs(identity)["data"]["result"], timeout=120)
report["historical_after"] = query(
"sum(messenger_http_requests_total)", at=timestamp
)
assert report["historical_after"] == historical
assert (
grafana.get("/api/user/preferences").json()["theme"]
== temporary["theme"]
)
report["after"] = instances()
for role, before in report["before"].items():
after = report["after"][role]
assert before["started_at"] != after["started_at"]
assert (
before["volumes"] == after["volumes"] and before["volumes"]
)
assert after["read_only"] and after["user"] not in {
"",
"0",
"0:0",
"root",
}
assert "ALL" in after["cap_drop"]
report.update(
stored_trace_survives=True,
stored_logs_survive=True,
historical_metric_survives=True,
grafana_sqlite_preference_survives=True,
complete=True,
)
finally:
try:
grafana.put(
"/api/user/preferences", json=previous
).raise_for_status()
finally:
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(
json.dumps(report, ensure_ascii=False, indent=2) + "\n"
)
print(
"PASS: metrics, traces, logs and Grafana state survive real store restarts"
)
if __name__ == "__main__":
main()
+30
View File
@@ -115,3 +115,33 @@ def test_http_metrics_use_route_template_and_bounded_method(
assert sensitive not in json.dumps(logs, default=str)
assert sensitive not in str(exporter.get_finished_spans()[0].attributes)
assert sensitive not in capsys.readouterr().out
def test_large_tracestate_cannot_break_durable_job_contract(signals):
from datetime import UTC, datetime
from uuid import uuid4
from src.pipeline import validate_job
trace_id = uuid4().hex
incoming = {
"traceparent": "00-" + trace_id + "-" + uuid4().hex[:16] + "-01",
"tracestate": ",".join(
"vendor" + str(i) + "=" + "x" * 200 for i in range(3)
),
}
with telemetry.span("upload", parent=incoming):
retained = telemetry.carrier()
message = {
"schema_version": 1,
"job_id": str(uuid4()),
"type": "attachment.process.v1",
"attachment_id": str(uuid4()),
"pipeline_version": 1,
"attempt": 1,
"created_at": datetime.now(UTC).isoformat(),
**retained,
}
assert validate_job(message) == message
assert retained["traceparent"].split("-")[1] == trace_id
assert "tracestate" not in retained