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
@@ -302,3 +302,43 @@ def test_every_api_response_carries_instance_and_request_id(api):
|
||||
api.call("GET", "/api/v1/users/me", 401)
|
||||
response = api.call("GET", "/api/v1/users/me", 401, headers={"X-Request-Id": "client-supplied.id-1"})
|
||||
assert response.headers["x-request-id"] == "client-supplied.id-1" # one id from LB log to API log
|
||||
|
||||
|
||||
@pytest.mark.parametrize("blank", [" ", " ", " \t "])
|
||||
def test_unicode_whitespace_only_strings_are_400(api, blank):
|
||||
alice = api.user("blank")
|
||||
chat = api.chat(alice)
|
||||
api.call("POST", "/api/v1/users", 400, json_body={"username": "bl_" + uuid.uuid4().hex[:10], "display_name": blank,
|
||||
"password": PASSWORD})
|
||||
api.call("POST", "/api/v1/chats", 400, token=alice["token"], json_body={"title": blank, "member_ids": [alice["id"]]})
|
||||
api.post_message(alice, chat, {"text": blank}, 400)
|
||||
assert api.history(alice, chat, 100)[0] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", [b'{"username":"num_probe","display_name":"x","password":1e1000}',
|
||||
'{"username":"ff_probe","display_name":"x","password":"12345678901'.encode() + b'\xff"}',
|
||||
b'{"username":"num_probe","display_name":1,"password":"Twelve-chars-ok"}'])
|
||||
def test_odd_registration_bodies_are_400_and_the_api_survives(api, raw):
|
||||
api.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"})
|
||||
api.call("GET", "/health/ready", 200)
|
||||
|
||||
|
||||
def test_more_than_100_members_is_400(api):
|
||||
owner = api.user("big")
|
||||
others = [api.register(f"m{i}")["id"] for i in range(100)]
|
||||
api.call("POST", "/api/v1/chats", 400, token=owner["token"], json_body={"title": "x", "member_ids": [owner["id"], *others]})
|
||||
chat = api.call("POST", "/api/v1/chats", 201, token=owner["token"],
|
||||
json_body={"title": "x", "member_ids": [owner["id"], *others[:99]]}, schema="Chat").json()
|
||||
assert len(chat["member_ids"]) == 100
|
||||
|
||||
|
||||
def test_cursor_of_one_list_is_rejected_by_the_other(api):
|
||||
alice = api.user("cross")
|
||||
chats = [api.chat(alice, title=f"c{i}") for i in range(2)]
|
||||
for _ in range(2):
|
||||
api.send(alice, chats[0], "m")
|
||||
message_cursor = api.call("GET", f"/api/v1/chats/{chats[0]['id']}/messages?limit=1", 200,
|
||||
token=alice["token"]).json()["next_cursor"]
|
||||
chat_cursor = api.call("GET", "/api/v1/chats?limit=1", 200, token=alice["token"]).json()["next_cursor"]
|
||||
api.call("GET", f"/api/v1/chats?cursor={message_cursor}", 400, token=alice["token"])
|
||||
api.call("GET", f"/api/v1/chats/{chats[0]['id']}/messages?cursor={chat_cursor}", 400, token=alice["token"])
|
||||
|
||||
@@ -62,7 +62,7 @@ def hba_file() -> str:
|
||||
def isolated_from_postgres(replica: dict):
|
||||
"""Make ONE replica unable to reach PostgreSQL (pg_hba reject for its IP + terminate its
|
||||
connections), while it keeps running and answering /health/live. Always undone."""
|
||||
ip = replica["ips"][0]
|
||||
ip = replica["networks"]["data"] # PostgreSQL sees the replica's address on the data network
|
||||
path = hba_file()
|
||||
marker = "lab3-test-isolate"
|
||||
compose("exec", "-T", "postgres", "sh", "-c", f"sed -i '1i host all all {ip}/32 reject # {marker}' {path}")
|
||||
@@ -73,28 +73,51 @@ def isolated_from_postgres(replica: dict):
|
||||
finally:
|
||||
compose("exec", "-T", "postgres", "sh", "-c", f"sed -i '/{marker}/d' {path}")
|
||||
psql("SELECT pg_reload_conf()")
|
||||
lbctl.wait_up(REPLICAS, timeout=15) # self-heals: no restart of the replica needed
|
||||
wait_stand()
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def disconnected_from_data_network(replica: dict):
|
||||
"""`docker network disconnect <project>_data <api>`: the replica keeps its edge link to the
|
||||
LB but loses PostgreSQL AND Valkey. Always reconnected."""
|
||||
network = next(n for n in json.loads(subprocess.run(
|
||||
["docker", "inspect", "-f", "{{json .NetworkSettings.Networks}}", replica["id"]],
|
||||
capture_output=True, text=True, check=True).stdout) if n.endswith("_data"))
|
||||
subprocess.run(["docker", "network", "disconnect", network, replica["id"]], check=True, capture_output=True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
subprocess.run(["docker", "network", "connect", network, replica["id"]], check=True, capture_output=True)
|
||||
lbctl.wait_up(REPLICAS, timeout=15) # self-heals: dead sockets are dropped (tcp_user_timeout)
|
||||
wait_stand()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("how", ["pg_hba", "network"])
|
||||
@pytest.mark.parametrize("position", range(REPLICAS))
|
||||
def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position):
|
||||
"""The reviewer's scenario: one API loses PostgreSQL but keeps running. Its /health/live is
|
||||
200, /health/ready 503 -> HAProxy must take it out; no business request may reach it."""
|
||||
def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position, how):
|
||||
"""The reviewers' scenarios: one API loses PostgreSQL (pg_hba reject) or its whole data
|
||||
network (docker network disconnect) but keeps running. /health/live 200, /health/ready
|
||||
503 -> HAProxy must take it out; no business request may reach it."""
|
||||
replica = sorted(running_replicas(), key=lambda r: r["name"])[position]
|
||||
actor = api.user("ready")
|
||||
with isolated_from_postgres(replica):
|
||||
isolate = isolated_from_postgres if how == "pg_hba" else disconnected_from_data_network
|
||||
with isolate(replica):
|
||||
started = time.monotonic()
|
||||
while replica["hostname"] in lbctl.up_instances():
|
||||
assert time.monotonic() - started < 5, "HAProxy did not mark the unready replica DOWN within 5 s"
|
||||
time.sleep(0.1)
|
||||
detected = time.monotonic() - started
|
||||
assert probe_inside(replica, "/health/live") == 200 # the process is alive ...
|
||||
assert probe_inside(replica, "/health/ready") == 503 # ... but not ready
|
||||
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"
|
||||
seen = instances_seen(api, actor["token"], 40)
|
||||
assert replica["hostname"] not in seen and len(seen) == 40
|
||||
for i in range(20): # writes keep working, only through the ready replicas
|
||||
assert api.register(f"r{i}")["id"]
|
||||
print(f"{replica['name']}: unready replica out of rotation after {detected:.2f} s")
|
||||
print(f"{replica['name']} ({how}): unready replica out of rotation after {detected:.2f} s")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ stopping replicas under traffic
|
||||
@@ -273,6 +296,10 @@ def test_compose_policy_limits_ports_secrets_images():
|
||||
volumes = {name: [v["source"] for v in svc.get("volumes", []) if v["type"] == "volume"]
|
||||
for name, svc in services.items()}
|
||||
assert volumes == {"postgres": ["pgdata"], "valkey": ["valkeydata"], "migrate": [], "api": [], "lb": []}
|
||||
networks = {name: sorted(svc.get("networks", {})) for name, svc in services.items()}
|
||||
assert networks == {"postgres": ["data"], "valkey": ["data"], "migrate": ["data"], "api": ["data", "edge"],
|
||||
"lb": ["edge"]}, networks # the LB cannot reach the stores at all
|
||||
assert config["networks"]["data"].get("internal") is True
|
||||
|
||||
|
||||
def test_running_containers_have_limits_and_no_bypass_ports():
|
||||
|
||||
Reference in New Issue
Block a user