forked from mtusi2026/mtusi2026lab6
75 lines
3.1 KiB
Python
75 lines
3.1 KiB
Python
"""Пересчёт четырёх равномерно дискретизированных контрольных рядов из slo.test.yml."""
|
||
import json
|
||
from pathlib import Path
|
||
|
||
import yaml
|
||
|
||
ROOT = Path(__file__).resolve().parents[2]
|
||
STEP = 15
|
||
|
||
|
||
def rate(values, i, window):
|
||
# Фикстуры имеют равный шаг и не содержат сбросов. На левом краю
|
||
# экстраполяция ограничена нулём монотонного счётчика.
|
||
first = max(0, i - window // STEP + 1)
|
||
duration = (i - first) * STEP
|
||
delta = values[i] - values[first]
|
||
if not duration or not delta:
|
||
return 0.0
|
||
left = min(window - duration, duration * values[first] / delta)
|
||
if i * STEP < window:
|
||
left = min(left, STEP / 2)
|
||
return delta / duration * (duration + left) / window
|
||
|
||
|
||
def replay(case):
|
||
profile = case["name"].split()[0]
|
||
api = profile == "api"
|
||
budget, hold = (0.01, 60) if api else (0.05, 30)
|
||
a, b = [list(map(int, item["values"].split())) for item in case["input_series"]]
|
||
bad = b if api else [total - fast for total, fast in zip(a, b)]
|
||
changes = [i for i in range(1, len(bad)) if bad[i] > bad[i-1]]
|
||
onset = (changes[0] - 1) * STEP
|
||
recovery = changes[-1] * STEP
|
||
active = first_firing = first_clear = None
|
||
firing_points = set()
|
||
episodes = 0
|
||
for i in range(1, len(a)):
|
||
burns = []
|
||
for window in (60, 300):
|
||
x, y = rate(a, i, window), rate(b, i, window)
|
||
bad_rate, total = (y, x+y) if api else (max(0, x-y), x)
|
||
burns.append(bad_rate / total / budget if total else 0)
|
||
ts = i * STEP
|
||
if min(burns) > 6:
|
||
if active is None:
|
||
active = ts
|
||
if ts - active >= hold:
|
||
firing_points.add(ts)
|
||
if ts - STEP not in firing_points:
|
||
episodes += 1
|
||
if first_firing is None:
|
||
first_firing = ts
|
||
else:
|
||
if ts - STEP in firing_points and first_clear is None:
|
||
first_clear = ts
|
||
active = None
|
||
for test in case["alert_rule_test"]:
|
||
minutes, seconds = test["eval_time"].split("m")
|
||
ts = 60 * int(minutes) + int(seconds.rstrip("s") or 0)
|
||
if (ts in firing_points) != bool(test["exp_alerts"]):
|
||
raise ValueError(f"Расхождение в {case['name']} на {ts} с")
|
||
return dict(scenario=case["name"], signal_duration_seconds=recovery-onset,
|
||
firing_episodes=episodes,
|
||
detection_seconds=first_firing-onset if first_firing is not None else None,
|
||
recovery_seconds=first_clear-recovery if first_clear is not None else None)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
fixture = ROOT / "infra/prometheus/tests/slo.test.yml"
|
||
cases = yaml.safe_load(fixture.read_text(encoding="utf-8"))["tests"]
|
||
results = [replay(case) for case in cases]
|
||
path = Path(__file__).with_name("synthetic-results.json")
|
||
path.write_text(json.dumps(results, ensure_ascii=False, indent=2)+"\n", encoding="utf-8")
|
||
print(path)
|