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:
Alexey Bodanyuk
2026-10-19 14:01:11 +03:00
co-authored by Claude Opus 5.5
parent 2033440cdb
commit 3f45eb1b51
7 changed files with 139 additions and 17 deletions
+23 -8
View File
@@ -8,12 +8,21 @@ Three independent limits keep a request from hanging when the database misbehave
* client deadline — covers what the server cannot report, e.g. a
paused/frozen PostgreSQL container or a dead network.
The client deadline needs care: when a psycopg query is cancelled, psycopg sends a
cancel request to the server and waits for it (up to 5 s + 5 s) before giving up.
With a frozen server that would stretch a 3 s deadline to 13 s. Therefore every unit
of work runs as its own task: at the deadline the request stops waiting and gets 503
at once, while the task finishes its cleanup (cancel, close, return to the pool) in
the background. Any failure becomes 503 `unavailable` — never 401, never a hang.
The client deadline needs care. Every unit of work runs as its own task; at the deadline
the REQUEST stops waiting and gets 503 at once, but the task is NOT cancelled: cancelling a
psycopg query makes psycopg send a cancel request, and libpq starts that connection
(PQcancelStart) synchronously in the event-loop thread, resolving the host name first.
When the API has lost its network to PostgreSQL (lab 3 review scenario: `docker network
disconnect`), that blocked the WHOLE replica, /health/live included, for ~1 minute.
The abandoned task instead ends by itself, bounded by:
* TCP keepalives + `tcp_user_timeout` (= the deadline): a dead peer or a vanished network
breaks the socket within seconds, the connection is discarded by the pool;
* `statement_timeout` / `lock_timeout` on a live but slow server;
* a frozen (paused) server keeps the connection until it resumes; meanwhile new work waits
at most the pool timeout and gets 503.
Any failure becomes 503 `unavailable` — never 401, never a hang.
"""
from __future__ import annotations
@@ -65,6 +74,12 @@ class Database:
"options": options,
"connect_timeout": max(1, int(settings.db_timeout_seconds)),
"application_name": "messenger-api",
# Detect a dead peer / lost network without any cancel request (see module doc).
"keepalives": 1,
"keepalives_idle": 5,
"keepalives_interval": 1,
"keepalives_count": 3,
"tcp_user_timeout": int(settings.db_timeout_seconds * 1000),
},
)
@@ -95,8 +110,8 @@ class Database:
raise Unavailable("База данных временно недоступна") from None
finally:
if not task.done():
# Deadline or cancelled request: stop waiting now, let psycopg clean up later.
task.cancel()
# Deadline or cancelled request: stop waiting now. The task is left to finish
# on its own (no task.cancel(): that would trigger psycopg's blocking cancel).
task.add_done_callback(_forget)
async def ping(self, timeout: float = 1.0) -> bool: