forked from mtusi2026/mtusi2026lab3
fix: реплика не «замерзает» при потере сети к PostgreSQL; сети edge/data
Найдено тестом сценария рецензента (docker network disconnect одной API от сети хранилищ): по дедлайну задача psycopg отменялась, psycopg слал cancel-запрос, а libpq PQcancelStart синхронно резолвит имя хоста в потоке event loop — вся реплика, включая /health/live, висела ~1 минуту и не возвращалась в ротацию сама. Теперь задача по дедлайну не отменяется (запрос сразу получает 503, задача доживает сама), а мёртвые соединения рвёт TCP keepalive + tcp_user_timeout = DB_TIMEOUT_SECONDS. - compose: сеть edge (lb, api) и internal-сеть data (api, migrate, postgres, valkey) — LB не видит хранилища. - тесты: неготовая реплика (pg_hba и network disconnect) выводится из ротации, процесс отвечает на live, после восстановления сам UP за <= 15 с; пробельные Unicode-строки, 1e1000, байт FF в пароле, 101 участник, курсор одного списка в другом. - bench/track1: CPU реплик суммируется по каждому замеру, в raw и CSV — фактические лимиты контейнеров из docker inspect. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
2033440cdb
commit
3f45eb1b51
@@ -21,6 +21,7 @@ services:
|
||||
image: grafana/k6:2.3.0@sha256:9c2dee7f8ed74d317e4027c06a10f169b625638189de8d4555d0b3486a5aeb34
|
||||
profiles: ["bench"]
|
||||
cpuset: "${K6_CPUSET:-0-1}"
|
||||
networks: [edge] # reaches the LB only, like an external client
|
||||
environment:
|
||||
BASE_URL: http://lb:8080
|
||||
volumes:
|
||||
|
||||
+26
-1
@@ -123,6 +123,19 @@ def start_stand(cfg: dict) -> None:
|
||||
raise RuntimeError("not all replicas UP in HAProxy")
|
||||
|
||||
|
||||
def actual_limits() -> dict:
|
||||
"""What Docker really applied (not what the config intended): CPU quota, memory, cpuset."""
|
||||
ids = compose("ps", "-q").split()
|
||||
result = {}
|
||||
for item in json.loads(subprocess.run(["docker", "inspect", *ids], capture_output=True, text=True,
|
||||
check=True).stdout):
|
||||
host = item["HostConfig"]
|
||||
result[item["Name"].lstrip("/")[len(PROJECT) + 1:]] = {
|
||||
"cpus": host["NanoCpus"] / 1e9, "memory_mib": host["Memory"] // (1024 * 1024),
|
||||
"cpuset": host["CpusetCpus"], "image": item["Config"]["Image"]}
|
||||
return result
|
||||
|
||||
|
||||
def make_chats(users: int) -> list[dict]:
|
||||
created = []
|
||||
stamp = uuid.uuid4().hex[:8]
|
||||
@@ -171,6 +184,11 @@ class Sampler(threading.Thread):
|
||||
def window(self, start: float, end: float) -> dict:
|
||||
rows = [r for t, r in self.samples if start <= t <= end]
|
||||
result = {}
|
||||
# All API replicas summed PER SAMPLE first, then the median over time (not a sum of medians).
|
||||
totals = [sum(v["cpu"] for k, v in r.items() if k.startswith("api-")) for r in rows]
|
||||
if totals:
|
||||
result["api_total"] = {"cpu_median": round(statistics.median(totals), 1), "cpu_max": round(max(totals), 1),
|
||||
"samples": len(totals)}
|
||||
for name in sorted({n for r in rows for n in r}):
|
||||
values = [r[name]["cpu"] for r in rows if name in r]
|
||||
result[name] = {"cpu_median": round(statistics.median(values), 1), "cpu_max": round(max(values), 1),
|
||||
@@ -281,8 +299,13 @@ def run_step(cfg: dict, rate: int, args, chats_dir: str, sampler: Sampler) -> di
|
||||
|
||||
def flat(r: dict) -> dict:
|
||||
cpu = r["cpu"]
|
||||
api_cpu = sum(v["cpu_median"] for k, v in cpu.items() if k.startswith("api-"))
|
||||
api_cpu = cpu.get("api_total", {}).get("cpu_median", 0.0)
|
||||
limits = r.get("limits", {})
|
||||
api_limits = [v for k, v in limits.items() if k.startswith("api-")]
|
||||
return {"config": r["config"], "repeat": r["repeat"], "rate": r["rate"], "ok_rps": r["ok_rps"],
|
||||
"replicas_running": len(api_limits), "api_cpus_limit_total": round(sum(v["cpus"] for v in api_limits), 2),
|
||||
"api_mem_mib_each": api_limits[0]["memory_mib"] if api_limits else None,
|
||||
"pg_cpus_limit": limits.get("postgres-1", {}).get("cpus"),
|
||||
"requests": r["requests"], "ok": r["ok"], "dropped": r["dropped"], "error_ratio": r["error_ratio"],
|
||||
"p50_ms": r["ok_p50_ms"], "p95_ms": r["ok_p95_ms"], "p99_ms": r["ok_p99_ms"],
|
||||
"api_cpu_pct_total": round(api_cpu, 1), "pg_cpu_pct": cpu.get("postgres-1", {}).get("cpu_median"),
|
||||
@@ -333,6 +356,7 @@ def main() -> int:
|
||||
name = config_name(cfg)
|
||||
print(f"== {args.series}/{args.label} {name} repeat {repeat}: fresh stand", flush=True)
|
||||
start_stand(cfg)
|
||||
limits = actual_limits()
|
||||
chats_dir = tempfile.mkdtemp(prefix="track1-")
|
||||
try:
|
||||
Path(chats_dir, "chats.json").write_text(json.dumps(make_chats(args.users)), encoding="utf-8")
|
||||
@@ -341,6 +365,7 @@ def main() -> int:
|
||||
for rate in rates:
|
||||
result = run_step(cfg, rate, args, chats_dir, sampler)
|
||||
result["repeat"] = repeat
|
||||
result["limits"] = limits
|
||||
(out / "raw" / f"{name}-r{repeat}-{rate}.json").write_text(
|
||||
json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
row = flat(result)
|
||||
|
||||
Reference in New Issue
Block a user