fix: correct replicas-lb details found in verify

- stop-one.sh: an empty TARGET_INSTANCE_ID now exits 2 in any shell,
  as the design states (${VAR:?} gave 1 under bash).
- driver.py kill-inflight: reproducible "aborted response is not
  retried" scenario (logins in flight, replica killed via stop-one.sh).
- Detection time of a hung replica is fall x (inter + timeout check) =
  8 s, not inter x fall + timeout check = 5 s (docker pause: 7.3 s);
  fixed in haproxy.cfg, balancer.md and the design.
- The 1 CPU replica limit is kept on purpose; the compose comment and
  the design now say that Argon2id uses more and logins are slower.
- load-balancing spec: API_REPLICAS is read by compose and Makefile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-10 18:44:57 +03:00
co-authored by Claude Opus 5.5
parent de93056eab
commit a4ca9ef3a7
10 changed files with 287 additions and 29 deletions
@@ -21,6 +21,12 @@
instances [--count N] распределение одной сессии по репликам: вход
одним синтетическим пользователем, N × GET /users/me с одним
токеном, X-Instance-Id каждого ответа и итог по репликам
kill-inflight [--threads N] [--seconds S] [--after A] только стенд
с LB: N потоков S секунд входят по Basic (Argon2id — запросы
в полёте есть всегда), через A секунд scripts/stop-one.sh в
режиме kill убивает реплику пробного запроса; статусы по
репликам и ответы LB. Реплика остаётся остановленной
(make replicas)
stop остановить свой экземпляр на порту
all start → flow → smoke → student (если есть student-tests/) → stop
@@ -40,6 +46,7 @@ import os
import signal
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
@@ -595,6 +602,108 @@ def cmd_instances(port: int, count: int) -> int:
return 1 if failures else 0
def cmd_kill_inflight(
port: int,
*,
threads: int,
seconds: float,
after: float,
) -> int:
"""Сценарий «Оборванный ответ не повторяется» (спек `load-balancing`).
`threads` потоков `seconds` секунд подряд входят по Basic одним
синтетическим пользователем: Argon2id на реплике с лимитом 1 CPU
занимает сотни миллисекунд, поэтому в момент kill запросы в полёте
есть. Через `after` секунд `scripts/stop-one.sh` в режиме kill
убивает реплику, ответившую на пробный запрос. Пароль и токены не
печатаются, тела успешных ответов не сохраняются.
"""
_, pid_path = paths(port)
if pid_path.exists():
print(f"port {port}: console process of the driver, no LB to test")
return 1
tag = uuid.uuid4().hex[:8]
username, password = f"kill_{tag}", f"Pw-kill-{uuid.uuid4().hex}"
body = {
"username": username,
"display_name": "Kill demo",
"password": password,
}
status, _, _ = call(port, "POST", USERS, body=body)
if status != 201:
print(f"register: {status}")
return 1
authorization = basic(username, password)
_, probe, _ = call(port, "GET", "/health/live")
target = probe.get("x-instance-id", "")
print(f"target replica (X-Instance-Id of a probe): {target}")
# (статус, реплика, тело ошибки LB, совпал ли request_id с заголовком)
results: list[tuple[int, str, object, bool]] = []
lock = threading.Lock()
deadline = time.monotonic() + seconds
def login() -> None:
while time.monotonic() < deadline:
try:
status, hdrs, payload = call(
port,
"POST",
SESSIONS,
authorization=authorization,
)
except OSError as error:
status, hdrs, payload = 0, {}, type(error).__name__
error = None
same_id = False
if status >= 500 or status == 0:
error = payload
if isinstance(payload, dict) and "error" in payload:
error = payload["error"]
same_id = error.get("request_id") == hdrs.get(
"x-request-id",
)
with lock:
results.append(
(status, hdrs.get("x-instance-id", "LB"), error, same_id),
)
workers = [threading.Thread(target=login) for _ in range(threads)]
for worker in workers:
worker.start()
time.sleep(after)
hook = subprocess.run(
[str(ROOT / "scripts" / "stop-one.sh")],
cwd=ROOT,
env=os.environ | {"TARGET_INSTANCE_ID": target, "STOP_MODE": "kill"},
capture_output=True,
text=True,
check=False,
)
print(f"stop-one.sh (kill): exit {hook.returncode}; {hook.stderr.strip()}")
for worker in workers:
worker.join()
print(f"{len(results)} logins in {seconds:g} s by {threads} threads")
counts = Counter((status, instance) for status, instance, _, _ in results)
for (status, instance), served in sorted(counts.items()):
print(f" {status} via {instance}: {served}")
cut = [(s, e, same) for s, _, e, same in results if e is not None]
for status, error, same_id in cut:
print(
f" LB error {status}: {json.dumps(error, ensure_ascii=False)}"
f" request_id == X-Request-Id: {same_id}",
)
print(f"replica {target} is left stopped; restore: make replicas")
if hook.returncode != 0:
return 1
if not cut:
print("no request was in flight on the killed replica: repeat")
return 1
unexpected = {status for status, _, _, _ in results} - {201, 502}
return 1 if unexpected else 0
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
@@ -603,6 +712,10 @@ def main() -> int:
sub.add_parser(name)
instances = sub.add_parser("instances")
instances.add_argument("--count", type=int, default=12)
inflight = sub.add_parser("kill-inflight")
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)
req = sub.add_parser("req")
req.add_argument("method")
req.add_argument("path")
@@ -636,6 +749,13 @@ def main() -> int:
return cmd_req(port, args)
if args.cmd == "instances":
return cmd_instances(port, args.count)
if args.cmd == "kill-inflight":
return cmd_kill_inflight(
port,
threads=args.threads,
seconds=args.seconds,
after=args.after,
)
handlers = {
"start": cmd_start,
"stop": cmd_stop,