feat: coordinate timeout chain and add failover load profile

HAProxy checks get fastinter 500ms and timeout check 2.5s (hung replica
detected within 6.5 s), http-reuse never with uvicorn keep-alive 60 s so
the LB closes idle replica connections, and app connections set
idle_in_transaction_session_timeout so a frozen replica releases its
idempotency key. The bench stand runs behind HAProxy with N replicas and
gains the failover profile (make bench_failover / bench_failover_quick):
constant-rate writes with a key and reads while each replica is stopped,
killed or paused, with per-second timeline, detection and recovery time
and write reconciliation. Driver commands idle-conns and hang-key check
the keep-alive and hung-transaction decisions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-10 23:21:12 +03:00
co-authored by Claude Opus 5.5
parent b76a666621
commit 459f84c75c
25 changed files with 2400 additions and 269 deletions
+9 -2
View File
@@ -13,8 +13,10 @@ FastAPI/uvicorn, данные в PostgreSQL из compose, карточки ча
останавливает сервер. Против стенда compose (`make run_docker`:
HAProxy на `APP_OUT_PORT` перед репликами API) работают те же команды
драйвера, кроме `start`/`stop`, плюс `instances` — распределение одной
сессии по репликам и `kill-inflight` — kill реплики с запросами в
полёте. Только стандартная библиотека Python.
сессии по репликам, `kill-inflight` — kill реплики с запросами в
полёте, `idle-conns` — кто закрывает простаивающие соединения LB →
реплика и `hang-key` — повтор ключа после зависшей реплики. Только
стандартная библиотека Python.
Все пути — от корня репозитория. Проверено на macOS (arm64), uv 0.12,
Python 3.12 из `.python-version`, Docker Desktop 29.8.
@@ -88,6 +90,8 @@ python3 $D stop
| `student` | `make student_test BASE_URL=http://localhost:<port>` (pytest по `student-tests/`); против своего процесса (есть pid-файл) — с `EXPECT_REPLICAS=1`, тесты реплик пропускаются с причиной; код 1, если каталога нет |
| `instances [--count N]` | вход одним синтетическим пользователем, N (12) × `GET /api/v1/users/me` с одним токеном: `X-Instance-Id` каждого ответа и число ответов каждой реплики; токен не печатается. Его зовёт `make instances` |
| `kill-inflight [--threads 8] [--seconds 4] [--after 1.5]` | только стенд с LB (`--port 8080`): потоки входят по Basic, через `--after` с `scripts/stop-one.sh` в режиме kill убивает реплику пробного запроса. Печатает статусы по репликам и ответы LB: оборванные входы — 502 в формате контракта без повтора, начатые после kill — 201 от другой реплики. Код 1, если оборванных нет. Реплика остаётся остановленной — `make replicas` |
| `idle-conns [--threads 20] [--requests 50] [--keep-alive 60]` | только стенд с LB: всплеск `GET /health/live` через LB с keep-alive соединениями, клиенты остаются подключены и молчат; раз в секунду — установленные соединения на порт API внутри каждой реплики (`/proc/net/tcp`) и пул LB (`idle_conn_cur` + `safe_conn_cur`). Код 0, если реплики остались без соединений раньше `--keep-alive` (`[app] keep_alive_seconds`): закрыл LB по своему `timeout http-keep-alive`, а не реплика |
| `hang-key` | только стенд с LB: временный триггер задерживает вставку пробного сообщения на 2 с, реплика с этой транзакцией замораживается `docker pause`, повторы того же `Idempotency-Key` через LB до 201 (сначала 504 от LB или 503 по ожиданию блокировки), разморозка; печатает `idle_in_transaction_session_timeout` соединения приложения и строку журнала PostgreSQL о прерывании. Код 0 — повтор получил 201, в чате одно сообщение, обе реплики снова `UP`. Триггер удаляется при любом исходе |
| `stop` | SIGTERM всей группе; ждёт, пока порт освободится. Чужой сервер и контейнер не трогает |
| `all` | всё подряд (`student` — если есть `student-tests/`), `stop` в `finally` |
@@ -124,6 +128,9 @@ STOP_MODE=kill STOP_ONE_LOG=/tmp/stop-one.log make test-failover ACTION_SCRIPT=s
# kill вместо graceful; журнал: какой TARGET_INSTANCE_ID и контейнер
TARGET_INSTANCE_ID=<x-instance-id> scripts/stop-one.sh # остановить одну реплику руками
python3 $D --port 8080 kill-inflight # kill реплики во время входов: 502 от LB без повтора
python3 $D --port 8080 idle-conns # простаивающие соединения с репликами закрывает LB (~10 с), а не реплика (60 с)
python3 $D --port 8080 hang-key # зависшая реплика держит ключ: повтор получает 201 после прерывания транзакции
make bench_failover_quick # отказ каждой реплики под нагрузкой на своём стенде mtusi-bench, ~2 мин
make replicas # вернуть остановленные реплики (те же ID), ждать healthy
make replicas API_REPLICAS=3 # разово 3 реплики; LB видит новую за 1–3 с без правки конфига
make down # удалить контейнеры, volume с данными остаётся
+441 -1
View File
@@ -27,6 +27,17 @@
режиме kill убивает реплику пробного запроса; статусы по
репликам и ответы LB. Реплика остаётся остановленной
(make replicas)
idle-conns [--threads N] [--requests M] [--keep-alive S] только
стенд с LB: всплеск запросов через LB, клиенты остаются
подключены; раз в секунду — соединения на порт API внутри
каждой реплики и пул LB; код 1, если реплики держат
соединения дольше S секунд — срока keep-alive реплики
hang-key только стенд с LB: сценарий «Повтор ключа после зависшей
реплики» — временный триггер задерживает вставку пробного
сообщения, реплика с этой транзакцией замораживается
(docker pause), повторы того же ключа через LB до 201,
разморозка, одно сообщение в чате, строка журнала PostgreSQL;
триггер удаляется при любом исходе
stop остановить свой экземпляр на порту
all start → flow → smoke → student (если есть student-tests/) → stop
@@ -41,6 +52,9 @@
import argparse
import base64
import contextlib
import csv
import http.client
import io
import json
import os
import signal
@@ -52,6 +66,7 @@ import urllib.error
import urllib.request
import uuid
from collections import Counter
from datetime import UTC, datetime
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
@@ -97,6 +112,7 @@ def call(
extra: dict[str, str] | None = None,
body: object = None,
raw: bytes | None = None,
timeout: float = 5,
) -> tuple[int, dict[str, str], object]:
data = raw
headers = {"Accept": "application/json"}
@@ -116,7 +132,7 @@ def call(
headers=headers,
)
try:
with urllib.request.urlopen(request, timeout=5) as response:
with urllib.request.urlopen(request, timeout=timeout) as response:
status = response.status
hdrs = dict(response.headers)
payload = response.read()
@@ -704,6 +720,415 @@ def cmd_kill_inflight(
return 1 if unexpected else 0
# статистика HAProxy изнутри контейнера LB, как make lb_stats
LB_STATS = (
"exec 3<>/dev/tcp/127.0.0.1/8404 && "
'printf "GET /stats;csv HTTP/1.0\\r\\n\\r\\n" >&3 && cat <&3'
)
# psql в контейнере PostgreSQL рабочего стенда от пользователя образа
PSQL = (
'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -XAtq -v ON_ERROR_STOP=1'
)
def compose(*args: str, stdin: str | None = None) -> str:
"""docker compose рабочего стенда (проект из docker-compose.yml)."""
proc = subprocess.run(
["docker", "compose", *args],
cwd=ROOT,
input=stdin,
capture_output=True,
text=True,
check=False,
)
if proc.returncode != 0:
raise RuntimeError(f"docker compose {args[0]}: {proc.stderr[-500:]}")
return proc.stdout
def lb_slots() -> list[dict[str, str]]:
"""Занятые слоты backend `api`: адрес, состояние, соединения."""
text = compose("exec", "-T", "haproxy", "bash", "-c", LB_STATS)
lines = [ln for ln in text.splitlines() if ln.startswith(("# ", "api,"))]
if not lines:
return []
rows = csv.DictReader(io.StringIO("\n".join(lines).removeprefix("# ")))
return [
row
for row in rows
if row["svname"] not in ("BACKEND", "FRONTEND") and row.get("addr")
]
def no_lb(port: int) -> bool:
_, pid_path = paths(port)
if pid_path.exists():
print(f"port {port}: console process of the driver, no LB to test")
return True
return False
def replica_connections(container: str, port: int) -> int:
"""Установленные TCP-соединения на порт API внутри контейнера
реплики (`/proc/net/tcp`): то, что реплика держит открытым."""
out = subprocess.run(
[
"docker",
"exec",
container,
"cat",
"/proc/net/tcp",
"/proc/net/tcp6",
],
capture_output=True,
text=True,
check=False,
).stdout
suffix = f":{port:04X}"
return sum(
1
for parts in (line.split() for line in out.splitlines())
if len(parts) > 3
and parts[0] != "sl"
and parts[1].endswith(suffix)
and parts[3] == "01"
)
def cmd_idle_conns(
port: int,
*,
threads: int,
requests: int,
keep_alive: float,
) -> int:
"""Простаивающие соединения LB → реплика (решение 3 design change
`graceful-failover`): их должен закрыть LB раньше, чем реплика по
своему сроку keep-alive.
Клиенты после всплеска остаются подключены и молчат, как браузер
между запросами. Каждую секунду — соединения на порт API внутри
каждой реплики и пул LB. Реплика закрыла бы их через `keep_alive`
секунд, LB — через свой `timeout http-keep-alive` (10 с): по тому,
когда они исчезли, видно, кто закрыл.
"""
if no_lb(port):
return 1
statuses: Counter[int] = Counter()
lock = threading.Lock()
clients: list[http.client.HTTPConnection] = []
def burst() -> None:
# одно keep-alive соединение клиента на поток, после всплеска
# остаётся открытым
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
with lock:
clients.append(conn)
for _ in range(requests):
conn.request("GET", "/health/live")
response = conn.getresponse()
response.read()
with lock:
statuses[response.status] += 1
replicas = {}
for container in compose("ps", "-q", "api").split():
address = subprocess.run(
[
"docker",
"inspect",
"-f",
"{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}",
container,
],
capture_output=True,
text=True,
check=False,
).stdout.strip()
replicas[container] = address
slots = {row["addr"].rsplit(":", 1)[0]: row for row in lb_slots()}
api_port = int(next(iter(slots.values()))["addr"].rsplit(":", 1)[1])
workers = [threading.Thread(target=burst) for _ in range(threads)]
for worker in workers:
worker.start()
for worker in workers:
worker.join()
last = time.monotonic()
print(
f"burst: {threads} keep-alive clients × {requests} GET /health/live "
f"through LB: {dict(statuses)}; clients stay connected and idle",
)
print("t, s replica: connections on its API port | LB pool idle+safe")
zero_since: float | None = None
try:
while True:
elapsed = time.monotonic() - last
held = {
container: replica_connections(container, api_port)
for container in replicas
}
pools = {
container: sum(
int(slots_now.get(field) or 0)
for field in ("idle_conn_cur", "safe_conn_cur")
)
for container, address in replicas.items()
for slots_now in [
{
row["addr"].rsplit(":", 1)[0]: row
for row in lb_slots()
}.get(address, {}),
]
}
print(
f"{elapsed:5.1f} "
+ " ".join(
f"{container[:12]}: {held[container]} | {pools[container]}"
for container in replicas
),
flush=True,
)
# проверка LB открывает соединение на миг: ноль — дважды подряд
if any(held.values()):
zero_since = None
elif zero_since is None:
zero_since = elapsed
else:
print(
f"replicas hold no connections {zero_since:.1f} s after "
f"the last request (replica keep-alive {keep_alive:g} "
"s): closed by LB",
)
return 0 if zero_since < keep_alive else 1
if elapsed > keep_alive + 10:
print(f"replicas still hold connections after {elapsed:.0f} s")
return 1
time.sleep(max(0.0, last + elapsed + 1 - time.monotonic()))
finally:
for conn in clients:
conn.close()
def cmd_hang_key(port: int) -> int:
"""Сценарий «Повтор ключа после зависшей реплики» (спек
`load-balancing`, решение 4 design change `graceful-failover`).
Пробный текст уникален: триггер задерживает вставку только этого
сообщения (`pg_sleep`), другие запросы стенда он не трогает и
удаляется в `finally`. Пароль, токен и ключ не печатаются.
"""
if no_lb(port):
return 1
tag = uuid.uuid4().hex[:8]
username, password = f"hang_{tag}", f"Pw-hang-{uuid.uuid4().hex}"
status, _, user = call(
port,
"POST",
USERS,
body={
"username": username,
"display_name": "Hang demo",
"password": password,
},
)
if status != 201 or not isinstance(user, dict):
print(f"register: {status}")
return 1
status, _, session = call(
port,
"POST",
SESSIONS,
authorization=basic(username, password),
)
if status != 201 or not isinstance(session, dict):
print(f"login: {status}")
return 1
token = session["token"]
status, _, chat = call(
port,
"POST",
CHATS,
token=token,
body={"title": "Hang demo", "member_ids": [user["id"]]},
)
if status != 201 or not isinstance(chat, dict):
print(f"create chat: {status}")
return 1
text = f"hang-probe-{tag}"
path = f"{CHATS}/{chat['id']}/messages"
key = key_header()
trigger = (
"CREATE OR REPLACE FUNCTION hang_probe() RETURNS trigger "
"LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_sleep(2); RETURN NEW; "
"END $$;\n"
"CREATE TRIGGER hang_probe BEFORE INSERT ON messages FOR EACH ROW "
f"WHEN (NEW.text = '{text}') EXECUTE FUNCTION hang_probe();\n"
)
cleanup = (
"DROP TRIGGER IF EXISTS hang_probe ON messages;\n"
"DROP FUNCTION IF EXISTS hang_probe();\n"
)
started = time.time()
t0 = time.monotonic()
paused: str | None = None
first: list[tuple[int, str, float]] = []
def send(timeout: float) -> tuple[int, str]:
try:
status, hdrs, _ = call(
port,
"POST",
path,
token=token,
extra=key,
body={"text": text},
timeout=timeout,
)
except OSError as error:
return 0, type(error).__name__
return status, hdrs.get("x-instance-id", "LB")
def original() -> None:
status, instance = send(30)
first.append((status, instance, time.monotonic() - t0))
try:
compose("exec", "-T", "postgres", "sh", "-c", PSQL, stdin=trigger)
print("trigger: INSERT of the probe message sleeps 2 s")
sender = threading.Thread(target=original)
sender.start()
address = ""
deadline = time.monotonic() + 3
while not address and time.monotonic() < deadline:
address = compose(
"exec",
"-T",
"postgres",
"sh",
"-c",
PSQL,
stdin="SELECT host(client_addr) FROM pg_stat_activity "
"WHERE wait_event = 'PgSleep' "
"AND application_name = 'mtusi-messenger';\n",
).strip()
ids = compose("ps", "-q", "api").split()
for container in ids:
ip = subprocess.run(
[
"docker",
"inspect",
"-f",
"{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}",
container,
],
capture_output=True,
text=True,
check=False,
).stdout.strip()
if address and ip == address.splitlines()[0]:
paused = container
if paused is None:
print(f"replica of the probe INSERT not found ({address!r})")
return 1
timeout_setting = subprocess.run(
[
"docker",
"exec",
paused,
"python",
"-c",
"import asyncio\n"
"from sqlalchemy import text\n"
"from src.infra.db.session import engine\n"
"async def main():\n"
" async with engine.connect() as c:\n"
" r = await c.execute(text("
"'SHOW idle_in_transaction_session_timeout'))\n"
" print(r.scalar())\n"
" await engine.dispose()\n"
"asyncio.run(main())\n",
],
capture_output=True,
text=True,
check=False,
).stdout.strip()
subprocess.run(
["docker", "pause", paused],
check=True,
capture_output=True,
)
mark = time.monotonic() - t0
print(
f"{mark:5.2f} s paused replica {paused[:12]} inside the "
"transaction with the key (INSERT of the probe message); its "
f"connections: idle_in_transaction_session_timeout = "
f"{timeout_setting or '?'}",
)
done = False
while not done and time.monotonic() - t0 < 60:
start = time.monotonic() - t0
status, instance = send(15)
spent = time.monotonic() - t0 - start
print(
f"{start:5.2f} s retry with the same key: {status} via "
f"{instance} in {spent:.2f} s",
flush=True,
)
done = status == 201
if not done:
time.sleep(0.5)
sender.join()
for status, instance, at in first:
print(
f"{at:5.2f} s original request answered: {status} via {instance}",
)
logs = compose(
"logs",
"--no-log-prefix",
"--since",
f"{started:.0f}",
"postgres",
)
terminated = [
ln for ln in logs.splitlines() if "idle-in-transaction" in ln
]
for line in terminated:
# отметка журнала PostgreSQL — часы ВМ, близкие к часам хоста
stamp = datetime.strptime(line[:23], "%Y-%m-%d %H:%M:%S.%f")
at = stamp.replace(tzinfo=UTC).timestamp() - started
print(f"{at:5.2f} s postgres: {line.strip()}")
subprocess.run(
["docker", "unpause", paused],
check=True,
capture_output=True,
)
print(f"{time.monotonic() - t0:5.2f} s unpaused {paused[:12]}")
paused = None
deadline = time.monotonic() + 15
up = False
while not up and time.monotonic() < deadline:
up = all(row["status"] == "UP" for row in lb_slots())
if not up:
time.sleep(0.5)
status, _, page = call(port, "GET", f"{path}?limit=100", token=token)
items = page.get("items", []) if isinstance(page, dict) else []
count = sum(1 for item in items if item.get("text") == text)
print(
f"chat history: {status}, {count} message(s) with the probe text; "
f"all replicas UP in LB: {up}",
)
return 0 if done and count == 1 and terminated and up else 1
finally:
if paused is not None:
subprocess.run(
["docker", "unpause", paused],
check=False,
capture_output=True,
)
compose("exec", "-T", "postgres", "sh", "-c", PSQL, stdin=cleanup)
print("trigger removed")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
@@ -716,6 +1141,12 @@ def main() -> int:
inflight.add_argument("--threads", type=int, default=8)
inflight.add_argument("--seconds", type=float, default=4)
inflight.add_argument("--after", type=float, default=1.5)
idle = sub.add_parser("idle-conns")
idle.add_argument("--threads", type=int, default=20)
idle.add_argument("--requests", type=int, default=50)
# [app] keep_alive_seconds реплики
idle.add_argument("--keep-alive", type=float, default=60)
sub.add_parser("hang-key")
req = sub.add_parser("req")
req.add_argument("method")
req.add_argument("path")
@@ -756,6 +1187,15 @@ def main() -> int:
seconds=args.seconds,
after=args.after,
)
if args.cmd == "idle-conns":
return cmd_idle_conns(
port,
threads=args.threads,
requests=args.requests,
keep_alive=args.keep_alive,
)
if args.cmd == "hang-key":
return cmd_hang_key(port)
handlers = {
"start": cmd_start,
"stop": cmd_stop,