forked from mtusi2026/mtusi2026lab7
fix: record replica death and OOM in the login bench profile
The first baseline attempt on 13fdd18 lost CPU and peak memory of the
"before" variant: its replicas died inside the window and the profile
did not notice. Poll memory.peak during the window, inspect replicas
after it (OOMKilled, exit code, time of death), add oom / replica_died
marks and base H4 on them. The attempt is kept out of git and recorded
in QUESTIONS.md; the label is retaken as baseline2.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+232
-9
@@ -66,6 +66,14 @@ RUN_FIELDS = [
|
||||
"db_cpu_cores",
|
||||
"cache_cpu_cores",
|
||||
"flags",
|
||||
# с метки baseline2: судьба реплик за прогон (`docker inspect` после
|
||||
# окна) — последний прочитанный пик до гибели, сколько реплик умерло и
|
||||
# сколько из них OOMKilled, состояние каждой, гибель от начала окна, с
|
||||
"api_last_peak_mib",
|
||||
"api_died",
|
||||
"api_oom",
|
||||
"api_fate",
|
||||
"api_died_at_s",
|
||||
]
|
||||
|
||||
|
||||
@@ -231,6 +239,14 @@ def run_row(
|
||||
flags.append("light_errors")
|
||||
if stats["flood_s502"] + stats["flood_s503"] + stats["flood_s504"]:
|
||||
flags.append("flood_5xx")
|
||||
fate = replica_fates(
|
||||
usage.get("fates", []),
|
||||
usage.get("window_begin_ms"),
|
||||
)
|
||||
if fate["api_oom"]:
|
||||
flags.append("oom")
|
||||
if fate["api_died"]:
|
||||
flags.append("replica_died")
|
||||
row = {
|
||||
**{key: run[key] for key in ("run", "variant", "rate", "repeat")},
|
||||
"order": run["order"],
|
||||
@@ -243,12 +259,56 @@ def run_row(
|
||||
"db_cpu_cores": usage.get("db_cpu_cores"),
|
||||
"cache_cpu_cores": usage.get("cache_cpu_cores"),
|
||||
"flags": " ".join(flags),
|
||||
"api_last_peak_mib": usage.get("api_last_peak_mib"),
|
||||
**fate,
|
||||
}
|
||||
if window_s <= 0:
|
||||
raise ValueError("window must be positive")
|
||||
return row
|
||||
|
||||
|
||||
def replica_fates(
|
||||
fates: list[dict[str, Any]],
|
||||
begin_ms: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""Итог `Stand.replica_fate` реплик прогона: умершие (не работает или
|
||||
перезапускалась), из них OOMKilled, состояние каждой строкой и самая
|
||||
ранняя гибель от начала окна замера, с (меньше 0 — на прогреве)."""
|
||||
died = [
|
||||
item
|
||||
for item in fates
|
||||
if item.get("status") != "running" or item.get("restarts")
|
||||
]
|
||||
parts = []
|
||||
for item in fates:
|
||||
if item not in died:
|
||||
parts.append("running")
|
||||
continue
|
||||
text = [str(item.get("status"))]
|
||||
if item.get("oom"):
|
||||
text.append("OOMKilled")
|
||||
if item.get("exit_code") is not None:
|
||||
text.append(f"exit={item['exit_code']}")
|
||||
if item.get("restarts"):
|
||||
text.append(f"restarts={item['restarts']}")
|
||||
parts.append(" ".join(text))
|
||||
moments = [
|
||||
item["finished_ms"]
|
||||
for item in died
|
||||
if item.get("finished_ms") is not None
|
||||
]
|
||||
return {
|
||||
"api_died": len(died),
|
||||
"api_oom": sum(1 for item in died if item.get("oom")),
|
||||
"api_fate": "; ".join(parts),
|
||||
"api_died_at_s": (
|
||||
round((min(moments) - begin_ms) / 1000, 1)
|
||||
if moments and begin_ms is not None
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def num(value: Any) -> float | None:
|
||||
if value in (None, ""):
|
||||
return None
|
||||
@@ -296,6 +356,7 @@ def share(part: Any, whole: Any) -> float | None:
|
||||
def hypotheses(
|
||||
rows: list[dict[str, Any]],
|
||||
top: int,
|
||||
limit_mib: float | None = None,
|
||||
) -> dict[str, dict[str, str]]:
|
||||
"""Вердикты H1–H4 на уровне `top` (выше ёмкости) по медианам повторов;
|
||||
формулировки — `REPORT.md`, раздел защиты входа."""
|
||||
@@ -361,17 +422,79 @@ def hypotheses(
|
||||
)
|
||||
else:
|
||||
result["H3"] = verdict(None, "нет прогона без потока или «полная»")
|
||||
result["H4"] = memory_verdict(before, [*budget, *full], limit_mib, verdict)
|
||||
return result
|
||||
|
||||
|
||||
def memory_verdict(
|
||||
before: list[dict[str, Any]],
|
||||
after: list[dict[str, Any]],
|
||||
limit_mib: float | None,
|
||||
verdict: Any,
|
||||
) -> dict[str, str]:
|
||||
"""H4: пик реплики с бюджетом ниже, чем «до». OOMKilled «до» — признак,
|
||||
что память без бюджета упирается в лимит (пик ≥ лимита): число в пик не
|
||||
подставляется, вердикт опирается на пометку `oom`."""
|
||||
limit = f" {limit_mib:.0f} МБ" if limit_mib else ""
|
||||
oom_before = sum(1 for row in before if num(row.get("api_oom")))
|
||||
oom_after = sum(1 for row in after if num(row.get("api_oom")))
|
||||
died_before = sum(1 for row in before if num(row.get("api_died")))
|
||||
peak_before = median(row["api_peak_mib"] for row in before)
|
||||
peak_after = median(row["api_peak_mib"] for row in [*budget, *full])
|
||||
peak_after = median(row["api_peak_mib"] for row in after)
|
||||
if oom_after:
|
||||
return verdict(
|
||||
False,
|
||||
f"с бюджетом OOMKilled в {oom_after} из {len(after)} прогонов "
|
||||
f"(пик ≥ лимита{limit})",
|
||||
)
|
||||
if oom_before and peak_after is not None:
|
||||
last = median(
|
||||
row.get("api_last_peak_mib")
|
||||
for row in before
|
||||
if num(row.get("api_oom"))
|
||||
)
|
||||
tail = (
|
||||
f"; последний замер до гибели {last:.1f} MiB"
|
||||
if last is not None
|
||||
else ""
|
||||
)
|
||||
return verdict(
|
||||
True,
|
||||
f"«до» — OOMKilled в {oom_before} из {len(before)} прогонов (пик ≥ "
|
||||
f"лимита{limit}: память без бюджета упирается в лимит{tail}), с "
|
||||
f"бюджетом пик {peak_after:.1f} MiB без OOM",
|
||||
)
|
||||
if peak_before is not None and peak_after is not None:
|
||||
result["H4"] = verdict(
|
||||
return verdict(
|
||||
peak_after < peak_before,
|
||||
f"пик памяти реплики: «до» {peak_before:.1f} MiB, с бюджетом "
|
||||
f"{peak_after:.1f} MiB",
|
||||
)
|
||||
else:
|
||||
result["H4"] = verdict(None, "нет пиков памяти")
|
||||
return result
|
||||
if died_before:
|
||||
return verdict(
|
||||
None,
|
||||
f"нет пиков памяти: реплики «до» умерли в {died_before} из "
|
||||
f"{len(before)} прогонов без OOMKilled",
|
||||
)
|
||||
return verdict(None, "нет пиков памяти")
|
||||
|
||||
|
||||
def deaths_cell(group: list[dict[str, Any]], limit_mib: float | None) -> str:
|
||||
"""Гибель реплик ячейки: OOMKilled (пик ≥ лимита — числом в пик не
|
||||
подставляется) и прочая гибель, прогонов из всех."""
|
||||
oom = sum(1 for row in group if num(row.get("api_oom")))
|
||||
died = sum(1 for row in group if num(row.get("api_died")))
|
||||
if not died:
|
||||
return "—"
|
||||
parts = []
|
||||
if oom:
|
||||
limit = f" {limit_mib:.0f} МБ" if limit_mib else ""
|
||||
parts.append(
|
||||
f"OOMKilled в {oom} из {len(group)} (пик ≥ лимита{limit})",
|
||||
)
|
||||
if died > oom:
|
||||
parts.append(f"умерла без OOM в {died - oom} из {len(group)}")
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
def fmt_share(value: float | None) -> str:
|
||||
@@ -382,6 +505,8 @@ def render_summary(meta: dict[str, Any], rows: list[dict[str, Any]]) -> str:
|
||||
info = meta.get("login", {})
|
||||
rates = info.get("rates", [])
|
||||
top = max(rates) if rates else 0
|
||||
memory = meta.get("limits", {}).get("api", {}).get("memory")
|
||||
limit_mib = memory / 2**20 if memory else None
|
||||
lines = [
|
||||
f"# Профиль входа — {meta.get('label', '')}",
|
||||
"",
|
||||
@@ -398,8 +523,9 @@ def render_summary(meta: dict[str, Any], rows: list[dict[str, Any]]) -> str:
|
||||
"",
|
||||
"| вариант | L/с | p95 лёгких мс | p99 лёгких мс | поток 401 | "
|
||||
"поток 429 | поток 5xx | Retry-After | верные 201 / 429 | p95 "
|
||||
"верных мс | хэшей за окно | CPU реплик | пик реплики MiB |",
|
||||
"|---|---|---|---|---|---|---|---|---|---|---|---|---|",
|
||||
"верных мс | хэшей за окно | CPU реплик | пик реплики MiB | гибель "
|
||||
"реплик |",
|
||||
"|---|---|---|---|---|---|---|---|---|---|---|---|---|---|",
|
||||
]
|
||||
groups = [("baseline", 0)] + [
|
||||
(variant, rate) for variant in VARIANTS for rate in rates
|
||||
@@ -452,13 +578,33 @@ def render_summary(meta: dict[str, Any], rows: list[dict[str, Any]]) -> str:
|
||||
spread((row["hashes"] for row in group), 0),
|
||||
spread((row["api_cpu_cores"] for row in group), 2),
|
||||
spread(row["api_peak_mib"] for row in group),
|
||||
deaths_cell(group, limit_mib),
|
||||
],
|
||||
)
|
||||
+ " |",
|
||||
)
|
||||
lines += ["", f"## Гипотезы (уровень L={top}/с)", ""]
|
||||
for name, item in hypotheses(rows, top).items():
|
||||
for name, item in hypotheses(rows, top, limit_mib).items():
|
||||
lines.append(f"- **{name}** — {item['verdict']}: {item['detail']}")
|
||||
dead = [row for row in rows if num(row.get("api_died"))]
|
||||
if dead:
|
||||
lines += [
|
||||
"",
|
||||
"## Гибель реплик",
|
||||
"",
|
||||
"Состояние реплик после окна (`docker inspect`); момент — самая "
|
||||
"ранняя гибель от начала окна замера (меньше 0 — на прогреве).",
|
||||
"",
|
||||
"| прогон | реплики | гибель, с | последний пик до гибели MiB |",
|
||||
"|---|---|---|---|",
|
||||
]
|
||||
for row in dead:
|
||||
moment = num(row.get("api_died_at_s"))
|
||||
lines.append(
|
||||
f"| {row['run']} | {row['api_fate']} | "
|
||||
f"{'—' if moment is None else f'{moment:.1f}'} | "
|
||||
f"{spread([row.get('api_last_peak_mib')])} |",
|
||||
)
|
||||
lines += [
|
||||
"",
|
||||
"Ограничение: поток со многих адресов предел адреса не остановит — "
|
||||
@@ -519,7 +665,20 @@ def selftest() -> int:
|
||||
],
|
||||
)
|
||||
assert count_hashes(log, 16000, 76000) == 2
|
||||
usage = {"api_cpu_cores": 0.5, "api_peak_mib": 150}
|
||||
alive = {
|
||||
"status": "running",
|
||||
"oom": False,
|
||||
"exit_code": None,
|
||||
"restarts": 0,
|
||||
"finished_ms": None,
|
||||
}
|
||||
usage = {
|
||||
"api_cpu_cores": 0.5,
|
||||
"api_peak_mib": 150,
|
||||
"api_last_peak_mib": 150,
|
||||
"fates": [alive, alive],
|
||||
"window_begin_ms": 16000,
|
||||
}
|
||||
rows = []
|
||||
for item in plan:
|
||||
row = run_row(item, stats, [3, 4], usage, 60)
|
||||
@@ -529,15 +688,79 @@ def selftest() -> int:
|
||||
if item["run"] == BASELINE:
|
||||
row["light_p95_ms"] = 20
|
||||
rows.append(row)
|
||||
assert rows[0]["flags"] == "" and rows[0]["api_died"] == 0
|
||||
assert rows[0]["api_fate"] == "running; running"
|
||||
verdicts = hypotheses(rows, 40)
|
||||
assert verdicts["H1"]["verdict"] == "подтверждена", verdicts
|
||||
assert verdicts["H4"]["verdict"] == "подтверждена", verdicts
|
||||
assert "OOM" not in verdicts["H4"]["detail"], verdicts
|
||||
summary = render_summary(
|
||||
{"label": "self", "login": {"rates": [10, 40]}},
|
||||
rows,
|
||||
)
|
||||
assert "## Гипотезы" in summary
|
||||
assert "## Гибель реплик" not in summary
|
||||
assert set(RUN_FIELDS) <= set(rows[0])
|
||||
# «до» — реплика убита ядром за 4 с окна: пик не прочитать, пометки
|
||||
# oom и replica_died, H4 — по пометке, а не по числу пика
|
||||
killed = {
|
||||
"status": "exited",
|
||||
"oom": True,
|
||||
"exit_code": 137,
|
||||
"restarts": 0,
|
||||
"finished_ms": 20000,
|
||||
}
|
||||
dead_usage = {
|
||||
**usage,
|
||||
"api_cpu_cores": None,
|
||||
"api_peak_mib": None,
|
||||
"api_last_peak_mib": 430.0,
|
||||
"fates": [killed, alive],
|
||||
}
|
||||
rows = [
|
||||
run_row(item, stats, [3, 4], dead_usage, 60)
|
||||
if item["variant"] == "before"
|
||||
else row
|
||||
for item, row in zip(plan, rows, strict=True)
|
||||
]
|
||||
dead = next(row for row in rows if row["variant"] == "before")
|
||||
assert dead["flags"] == "oom replica_died", dead["flags"]
|
||||
assert (dead["api_died"], dead["api_oom"]) == (1, 1)
|
||||
assert dead["api_died_at_s"] == 4.0
|
||||
assert dead["api_fate"] == "exited OOMKilled exit=137; running"
|
||||
assert dead["api_peak_mib"] is None
|
||||
verdicts = hypotheses(rows, 40, 512)
|
||||
assert verdicts["H4"]["verdict"] == "подтверждена", verdicts
|
||||
assert "OOMKilled в 3 из 3" in verdicts["H4"]["detail"], verdicts
|
||||
assert "430.0 MiB" in verdicts["H4"]["detail"], verdicts
|
||||
summary = render_summary(
|
||||
{
|
||||
"label": "self",
|
||||
"login": {"rates": [10, 40]},
|
||||
"limits": {"api": {"memory": 512 * 2**20}},
|
||||
},
|
||||
rows,
|
||||
)
|
||||
assert "OOMKilled в 3 из 3 (пик ≥ лимита 512 МБ)" in summary, summary
|
||||
assert "## Гибель реплик" in summary
|
||||
# OOM с бюджетом — H4 не подтверждена; гибель «до» без OOM — нет данных
|
||||
oom_after = [
|
||||
run_row(item, stats, [3, 4], dead_usage, 60)
|
||||
if item["variant"] == "full"
|
||||
else row
|
||||
for item, row in zip(plan, rows, strict=True)
|
||||
]
|
||||
assert hypotheses(oom_after, 40)["H4"]["verdict"] == "не подтверждена"
|
||||
exited = {**killed, "oom": False, "exit_code": 1}
|
||||
no_oom = [
|
||||
run_row(item, stats, [3, 4], {**dead_usage, "fates": [exited]}, 60)
|
||||
if item["variant"] == "before"
|
||||
else row
|
||||
for item, row in zip(plan, rows, strict=True)
|
||||
]
|
||||
verdicts = hypotheses(no_oom, 40)
|
||||
assert verdicts["H4"]["verdict"] == "нет данных", verdicts
|
||||
assert "без OOMKilled" in verdicts["H4"]["detail"], verdicts
|
||||
print("login.py selftest: ok")
|
||||
return 0
|
||||
|
||||
|
||||
+65
-3
@@ -486,6 +486,9 @@ class Profile:
|
||||
login_light_rate: int = 50
|
||||
login_good_rate: int = 1
|
||||
login_users: int = 20
|
||||
# опрос `memory.peak` реплик в окне: последний пик до гибели реплики
|
||||
# (после OOM cgroup контейнера уже не прочитать)
|
||||
login_poll_s: int = 5
|
||||
login_budget_env: tuple[tuple[str, str], ...] = (
|
||||
("AUTH__LOGIN_MAX_FAILURES_PER_ACCOUNT", "0"),
|
||||
("AUTH__LOGIN_MAX_FAILURES_PER_ADDRESS", "0"),
|
||||
@@ -3865,6 +3868,39 @@ class Stand:
|
||||
"exit_code": state.get("ExitCode"),
|
||||
}
|
||||
|
||||
def replica_fate(self, name: str) -> dict[str, Any]:
|
||||
"""Судьба реплики за прогон профиля входа: состояние, OOM, код
|
||||
выхода, перезапуски и время завершения (часы ВМ, мс) — у
|
||||
неработающей; контейнера нет — `status` `missing`."""
|
||||
text = sh(
|
||||
"docker",
|
||||
"inspect",
|
||||
"-f",
|
||||
"{{json .State}}|{{.RestartCount}}",
|
||||
name,
|
||||
check=False,
|
||||
)
|
||||
state_json, _, restarts = text.rpartition("|")
|
||||
if not state_json:
|
||||
return {
|
||||
"status": "missing",
|
||||
"oom": False,
|
||||
"exit_code": None,
|
||||
"restarts": 0,
|
||||
"finished_ms": None,
|
||||
}
|
||||
state = json.loads(state_json)
|
||||
running = bool(state.get("Running"))
|
||||
return {
|
||||
"status": state.get("Status") or "",
|
||||
"oom": bool(state.get("OOMKilled")),
|
||||
"exit_code": None if running else state.get("ExitCode"),
|
||||
"restarts": int(restarts or 0),
|
||||
"finished_ms": (
|
||||
None if running else login.iso_ms(state.get("FinishedAt", ""))
|
||||
),
|
||||
}
|
||||
|
||||
def down_storages(self) -> list[str]:
|
||||
"""Хранилища, которые за прогон умирали, убивались или рестартовали."""
|
||||
down = []
|
||||
@@ -7494,7 +7530,10 @@ class Bench:
|
||||
"""Прогон: реплики варианта, сверка «Started API», генератор потока
|
||||
и лёгких запросов, затем верные входы со второго генератора; CPU — по
|
||||
`cpu.stat` контейнеров на границах окна, пик памяти реплик — их
|
||||
`memory.peak` (контейнеры нового прогона), хэши — по журналу."""
|
||||
`memory.peak` (контейнеры нового прогона; в окне — опрос раз в
|
||||
`login_poll_s`, последний пик до гибели), хэши — по журналу; после
|
||||
окна — `docker inspect` реплик (состояние, OOM, код выхода,
|
||||
перезапуски, время завершения): пометки `oom` и `replica_died`."""
|
||||
p = self.profile
|
||||
stand = self.stand
|
||||
name = run["run"]
|
||||
@@ -7555,7 +7594,18 @@ class Bench:
|
||||
key: stand.cgroup_value(c, "cpu.stat", "usage_usec")
|
||||
for key, c in containers.items()
|
||||
}
|
||||
time.sleep(max(0.0, end - time.time()))
|
||||
# последний прочитанный пик каждой реплики: после гибели
|
||||
# (OOM) её cgroup уже не прочитать
|
||||
last_peaks: dict[str, int] = {}
|
||||
while True:
|
||||
for replica in replicas:
|
||||
value = stand.cgroup_value(replica, "memory.peak")
|
||||
if value is not None:
|
||||
last_peaks[replica] = value
|
||||
left = end - time.time()
|
||||
if left <= 0:
|
||||
break
|
||||
time.sleep(min(p.login_poll_s, left))
|
||||
cpu_after = {
|
||||
key: stand.cgroup_value(c, "cpu.stat", "usage_usec")
|
||||
for key, c in containers.items()
|
||||
@@ -7589,6 +7639,10 @@ class Bench:
|
||||
peaks = [
|
||||
stand.cgroup_value(replica, "memory.peak") for replica in replicas
|
||||
]
|
||||
for replica, value in zip(replicas, peaks, strict=True):
|
||||
if value is not None:
|
||||
last_peaks[replica] = value
|
||||
fates = [stand.replica_fate(replica) for replica in replicas]
|
||||
usage = {
|
||||
"api_cpu_cores": (
|
||||
round(sum(c for c in api_cores if c is not None), 3)
|
||||
@@ -7603,6 +7657,13 @@ class Bench:
|
||||
"lb_cpu_cores": cores("lb"),
|
||||
"db_cpu_cores": cores("db"),
|
||||
"cache_cpu_cores": cores("cache"),
|
||||
"api_last_peak_mib": (
|
||||
round(max(last_peaks.values()) / 2**20, 1)
|
||||
if last_peaks
|
||||
else None
|
||||
),
|
||||
"fates": fates,
|
||||
"window_begin_ms": round(begin * 1000),
|
||||
}
|
||||
hashes = [
|
||||
login.count_hashes(
|
||||
@@ -7633,7 +7694,8 @@ class Bench:
|
||||
f"{row['light_p95_ms']} ms, flood 401 {row['flood_s401']} 429 "
|
||||
f"{row['flood_s429']}, good 201 {row['good_s201']}/"
|
||||
f"{row['good_count']}, hashes {row['hashes']}, api CPU "
|
||||
f"{row['api_cpu_cores']}, peak {row['api_peak_mib']} MiB",
|
||||
f"{row['api_cpu_cores']}, peak {row['api_peak_mib']} MiB"
|
||||
+ (f", replicas: {row['api_fate']}" if row["api_died"] else ""),
|
||||
)
|
||||
self.progress(last={"run": name, "flags": row["flags"]})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user