perf: идемпотентная отправка сообщения одним вызовом SQL (трек 1)

Гипотеза из профиля (py-spy, 2 x 1.0 CPU, 240 req/s): ~57 % CPU реплики
уходит в psycopg — накладные расходы на каждый оператор; на одно
сообщение ~11 обращений к PostgreSQL в двух транзакциях (проверка
членства, BEGIN, ключ, часы чата, сообщение, COMMIT, проверки пула).

- migrations/0003: функция post_message — та же логика и тот же SQL,
  что в многооператорном пути; вызывается в autocommit, поэтому вызов и
  есть транзакция (ключ, часы чата и сообщение — всё или ничего).
- пул: autocommit-соединения; многооператорная работа по-прежнему в явной
  conn.transaction(); ping — один оператор без транзакции.
- MESSAGE_WRITE_PATH=function (по умолчанию) | multi (прежний путь) — A/B
  на одном образе. Порядок ответов одинаков: постороннему всегда 404,
  даже при неверном ключе/теле.
- Оба режима проходят одни и те же тесты идемпотентности и контракта.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alexey Bodanyuk
2026-10-19 16:03:22 +03:00
co-authored by Claude Opus 5.5
parent 26a0d86431
commit 4830be414e
10 changed files with 141 additions and 15 deletions
+11
View File
@@ -69,6 +69,13 @@ def _bool(name: str, default: bool) -> bool:
return raw in {"true", "1"}
def _choice(name: str, default: str, allowed: set[str]) -> str:
value = os.environ.get(name, "").strip().lower() or default
if value not in allowed:
raise ConfigError(f"{name} must be one of {sorted(allowed)}, got {value!r}")
return value
def _secret(name: str, required: bool) -> str:
"""Value of <NAME>_FILE (preferred, Docker secret) or <NAME> (local runs/tests)."""
path = os.environ.get(f"{name}_FILE", "").strip()
@@ -107,6 +114,7 @@ class Settings:
drain_seconds: float = 0.0
idempotency_ttl_seconds: int = 86400
stats_log_seconds: float = 0.0
message_write_path: str = "function"
@property
def db_statement_timeout_ms(self) -> int:
@@ -154,4 +162,7 @@ class Settings:
idempotency_ttl_seconds=_int("IDEMPOTENCY_TTL_SECONDS", 86400, 86400, 30 * 24 * 3600),
# Experiments (bench/track1): log DB pool counters and process CPU every N s; 0 = off.
stats_log_seconds=_float("STATS_LOG_SECONDS", 0.0, 0.0, 60.0),
# Track 1: `function` = one SQL call per send (migration 0003), `multi` = the previous
# multi-statement transaction; both have identical semantics (A/B on one image).
message_write_path=_choice("MESSAGE_WRITE_PATH", "function", {"function", "multi"}),
)