тесты и healthcheck устойчивее к медленному хосту: время пробы внутри контейнера, healthcheck timeout 5 с, дочитывание TLS-ответа, grace уборщика 15 с

This commit is contained in:
Alexey Bodanyuk
2026-11-28 16:22:52 +03:00
parent c5c9b5c9ab
commit 783aa35456
5 changed files with 77 additions and 21 deletions
+33 -2
View File
@@ -133,9 +133,40 @@ RESULTS_TABLE
### Argon2id: выбор параметров замером
Замер на стенде: `bench/argon2_bench.py` внутри реплики API, с её лимитами (cgroup `cpu.max = 100000 100000` = 1 CPU, 512 MiB), argon2-cffi 25.1.0, p = 1. Сырые данные — [evidence/argon2/bench.json](evidence/argon2/bench.json).
Замер на стенде: `bench/argon2_bench.py` внутри реплики API, с её лимитами (cgroup `cpu.max = 100000 100000` = 1 CPU, 512 MiB), argon2-cffi 25.1.0, p = 1. Сырые данные — [evidence/argon2/bench-run1-dev.json](evidence/argon2/bench-run1-dev.json) и [evidence/argon2/bench.json](evidence/argon2/bench.json).
ARGON2_TABLE
Последовательно, по одному хешу (N = 15 на точку; мс):
| m, KiB (MiB) | t | замер 1 (dev): медиана / p95 | замер 2 (чистый clone): медиана / p95 | CPU на хеш, мс (1 / 2) |
| --- | --- | --- | --- | --- |
| 19456 (19) | 2 **выбрано** | 30.6 / 47.4 | 154.0 / 270.1 | 30.4 / 87.9 |
| 19456 (19) | 3 | 47.4 / 54.7 | 210.4 / 391.7 | 45.1 / 143.6 |
| 19456 (19) | 4 | 102.3 / 175.4 | 265.5 / 486.4 | 62.3 / 195.0 |
| 32768 (32) | 2 | 72.9 / 82.4 | 245.6 / 601.1 | 69.8 / 205.4 |
| 32768 (32) | 3 | 144.5 / 284.0 | 461.3 / 732.6 | 116.3 / 292.8 |
| 32768 (32) | 4 | 144.6 / 378.7 | 431.4 / 942.8 | 135.4 / 356.6 |
| 47104 (46) | 2 | 119.1 / 291.2 | 496.6 / 778.5 | 114.6 / 335.1 |
| 47104 (46) | 3 | 144.3 / 384.1 | 598.8 / 937.3 | 141.7 / 433.5 |
| 47104 (46) | 4 | 246.7 / 485.3 | 915.5 / 2236.4 | 215.5 / 635.7 |
| 65536 (64) | 2 | 162.8 / 368.5 | 699.4 / 1298.1 | 157.4 / 474.5 |
| 65536 (64) | 3 | 233.3 / 669.8 | 703.0 / 1489.6 | 222.1 / 580.9 |
| 65536 (64) | 4 | 319.5 / 711.3 | 1199.7 / 1682.2 | 261.4 / 731.5 |
Параллельно (K потоков хешируют одновременно; 6 хешей на поток) — пропускная способность одной реплики = сколько входов в секунду она может проверить:
| m, KiB | t | K | хешей/с (1 / 2) | медиана, мс (1 / 2) | p95, мс (1 / 2) | RAM на хеши, MiB |
| --- | --- | --- | --- | --- | --- | --- |
| 19456 | 2 | 1 | 26.8 / 12.1 | 33.6 / 75.2 | 61.0 / 105.4 | 19.0 |
| 19456 | 2 | 2 | 30.6 / 7.8 | 74.3 / 212.3 | 89.3 / 373.0 | 38.0 |
| 19456 | 2 | 4 | 17.4 / 7.5 | 204.1 / 480.6 | 289.0 / 972.2 | 76.0 |
| 47104 | 2 | 1 | 4.3 / 1.8 | 206.5 / 501.0 | 369.1 / 807.2 | 46.0 |
| 47104 | 2 | 2 | 7.4 / 2.4 | 286.2 / 805.2 | 295.9 / 1043.5 | 92.0 |
| 47104 | 2 | 4 | 5.4 / 2.5 | 703.6 / 1496.4 | 988.7 / 1900.7 | 184.0 |
| 19456 | 3 | 1 | 8.8 / 3.6 | 101.2 / 278.5 | 165.8 / 374.2 | 19.0 |
| 19456 | 3 | 2 | 14.3 / 5.6 | 114.2 / 345.8 | 201.5 / 516.2 | 38.0 |
| 19456 | 3 | 4 | 12.2 / 5.8 | 304.6 / 650.2 | 409.3 / 881.8 | 76.0 |
Замер 1: 2026-11-27T13:50:01Z, dev-стенд; замер 2: 2026-11-28T12:21:11Z, чистый стенд. Оба — в контейнере API, cgroup `cpu.max` 100000 100000, `memory.max` 536870912; argon2-cffi 25.1.0, Python 3.13.16. Абсолютные числа различаются в 2–5 раз (Docker Desktop, разная фоновая нагрузка хоста), **соотношения между точками сохраняются**.
**Вывод.** Реплика имеет 1 CPU и разрешает 2 хеша одновременно (`PASSWORD_HASH_CONCURRENCY=2`, это 2 × m RAM). Цель — вход не дольше ~100 мс при двух параллельных хешах. Её выполняет только базовая конфигурация OWASP m=19 MiB, t=2, p=1.
+5 -3
View File
@@ -408,7 +408,9 @@ services:
healthcheck:
test: ["CMD", "python", "-m", "messenger.healthcheck"]
interval: 2s
timeout: 2s
# 5 s: starting the Python probe alone took > 2 s on a loaded Windows host (lab 7 clean run),
# which kept a healthy replica "unhealthy". The probe's own HTTP timeout stays 2 s.
timeout: 5s
retries: 3
# Lab 7: the start includes the OpenBao login and the first TLS connections; after a cold
# Docker start this took > 11 s once and `up --wait` gave up. Failures inside start_period do
@@ -496,7 +498,7 @@ services:
healthcheck:
test: ["CMD", "python", "-m", "messenger.healthcheck", "--file", "/tmp/heartbeat", "--max-age", "30"]
interval: 5s
timeout: 3s
timeout: 5s
retries: 3
start_period: 10s
depends_on:
@@ -543,7 +545,7 @@ services:
healthcheck:
test: ["CMD", "python", "-m", "messenger.healthcheck", "--file", "/tmp/heartbeat", "--max-age", "30"]
interval: 5s
timeout: 3s
timeout: 5s
retries: 3
start_period: 10s
depends_on:
+17 -8
View File
@@ -456,12 +456,21 @@ def attachment_row(attachment_id: str) -> dict | None:
return json.loads(out) if out else None
def probe_inside(replica: dict, path: str) -> int:
"""HTTP status of `path` asked inside the replica container itself (bypassing the LB) - lab 7: on
the loopback health listener (127.0.0.1:8081), the mTLS port needs the LB's client certificate."""
code = ("import urllib.request as u, urllib.error as e\n"
"try: print(u.urlopen('http://127.0.0.1:8081%s', timeout=3).status)\n"
"except e.HTTPError as x: print(x.code)") % path
def probe_inside_timed(replica: dict, path: str) -> tuple[int, float]:
"""(HTTP status, seconds) of `path` asked inside the replica container itself (bypassing the LB) -
lab 7: on the loopback health listener (127.0.0.1:8081), the mTLS port needs the LB's client
certificate. The time is measured INSIDE the container around the request only: `docker exec`
and the Python start-up (seconds on a loaded Windows host) are the test tool's cost, not the
replica's responsiveness."""
code = ("import time, urllib.request as u, urllib.error as e\n"
"t = time.perf_counter()\n"
"try: s = u.urlopen('http://127.0.0.1:8081%s', timeout=5).status\n"
"except e.HTTPError as x: s = x.code\n"
"print(s, round(time.perf_counter() - t, 3))") % path
out = subprocess.run(["docker", "exec", replica["id"], "python", "-c", code], capture_output=True, text=True,
timeout=30).stdout.strip()
return int(out or 0)
timeout=60).stdout.split()
return (int(out[0]), float(out[1])) if len(out) == 2 else (0, 99.0)
def probe_inside(replica: dict, path: str) -> int:
return probe_inside_timed(replica, path)[0]
+5 -5
View File
@@ -15,7 +15,7 @@ import uuid
import httpx2 as httpx
import pytest
from conftest import BASE_URL, REPLICAS, Api, compose, lbctl, probe_inside, psql, replica_stopped, run_hook, \
from conftest import BASE_URL, REPLICAS, Api, compose, lbctl, probe_inside_timed, psql, replica_stopped, run_hook, \
running_replicas, wait_healthy, wait_stand
pytestmark = pytest.mark.stack
@@ -109,10 +109,10 @@ def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position
time.sleep(0.1)
detected = time.monotonic() - started
for _ in range(3): # the process stays responsive (event loop never blocked) ...
started_probe = time.monotonic()
assert probe_inside(replica, "/health/live") == 200
assert probe_inside(replica, "/health/ready") == 503 # ... but not ready
assert time.monotonic() - started_probe < 4.5, "replica froze while its dependencies were unreachable"
live, live_s = probe_inside_timed(replica, "/health/live")
ready, ready_s = probe_inside_timed(replica, "/health/ready")
assert live == 200 and ready == 503 # ... but not ready
assert live_s + ready_s < 4.5, ("replica froze while its dependencies were unreachable", live_s, ready_s)
seen = instances_seen(api, actor["token"], 40)
assert replica["instance"] not in seen and len(seen) == 40
for i in range(20): # writes keep working, only through the ready replicas
+17 -3
View File
@@ -60,7 +60,19 @@ def raw_upload(token: str, chat_id: str, declared: int, body: bytes, *, wait_ans
sock.close()
return b""
time.sleep(wait_answer)
answer = sock.recv(65536)
answer = b""
sock.settimeout(5)
try:
while chunk := sock.recv(65536): # lab 7: TLS delivers headers and body in separate records
answer += chunk
if b"\r\n\r\n" in answer:
head, _, body = answer.partition(b"\r\n\r\n")
length = next((int(line.split(b":", 1)[1]) for line in head.split(b"\r\n")
if line.lower().startswith(b"content-length:")), None)
if length is not None and len(body) >= length:
break
except (TimeoutError, OSError):
pass
sock.close()
return answer
@@ -84,14 +96,16 @@ def test_crash_after_staging_before_job_is_cleaned_by_janitor(api):
(object first) and then the intent row; no job, no message ever existed."""
alice = api.user("alice")
chat = api.chat(alice)
with api_with_env(API_FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="3", JANITOR_INTERVAL_SECONDS="1"):
# grace 15 s: the checks below go through docker exec (seconds each on a loaded host) and must
# see the orphan BEFORE the janitor may remove it.
with api_with_env(API_FAULT_POINTS="after_s3_put", PENDING_GRACE_SECONDS="15", JANITOR_INTERVAL_SECONDS="1"):
assert api.upload(alice, chat, SAMPLE, 503).json()["error"]["code"] == "unavailable"
[(attachment_id, status, key)] = rows_of_chat(chat["id"])
assert status == "pending" and s3_size(key, "staging") == len(SAMPLE) # the orphan-to-be exists
assert jobs_of(attachment_id) == (0, 0) # no job, no outbox row
api.call("GET", f"/api/v1/attachments/{attachment_id}", 404, token=alice["token"]) # invisible
api.post_message(alice, chat, {"text": "", "attachment_ids": [attachment_id]}, 404) # not attachable
wait_for(lambda: rows_of_chat(chat["id"]) == [], 30, "janitor did not remove the stale intent")
wait_for(lambda: rows_of_chat(chat["id"]) == [], 60, "janitor did not remove the stale intent")
assert s3_size(key, "staging") is None # object removed first
# Normal configuration again: an upload in the same chat works and is not touched.
att = api.upload(alice, chat, SAMPLE).json()