fix: address unit-of-work verify findings

Abort the transport when a bounded close ends, so a frozen server leaves
no sessions over the pool once the ping has no transaction. Under the
shared request deadline a block sets no timer of its own, so a single
cancel closes the connection and the log has one record. Add a test that
concurrent worker deliveries get separate units of work, and state the
cost of the pattern against both baselines in the report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-01 01:58:51 +03:00
co-authored by Claude Opus 5.5
parent 952c16350e
commit d8fe2e87f1
17 changed files with 588 additions and 60 deletions
+124 -21
View File
@@ -10,6 +10,7 @@ from sqlalchemy import event, exc, text
from builders import NOW, PASSWORD_HASH, attachment_dto, user_dto
from conftest import (
DatabaseWarnings,
TcpProxy,
admin,
make_engine,
@@ -23,28 +24,16 @@ from src.infra.db import scope
from src.infra.db.engine import _ping_once
from src.infra.db.uow import SqlAlchemyUnitOfWork
from src.schemas.enums import AttachmentStatus
from src.utils.constants import DB_CLOSE_TIMEOUT_SECONDS
from src.utils.constants import (
DB_APPLICATION_NAME,
DB_CLOSE_TIMEOUT_SECONDS,
)
pytestmark = pytest.mark.anyio
SECONDS_MARGIN = 0.7
class _Warnings:
"""Записи логгера `database`: сколько раз назван отказ."""
def __init__(self) -> None:
self.events: list[str] = []
def warning(self, event_name: str, **_: object) -> None:
self.events.append(event_name)
@pytest.fixture
def warnings(monkeypatch: pytest.MonkeyPatch) -> _Warnings:
recorder = _Warnings()
monkeypatch.setattr(scope, "logger", recorder)
return recorder
# сервер замечает закрытый сокет не сразу
SESSIONS_SETTLE_SECONDS = 3.0
@pytest.fixture
@@ -157,7 +146,7 @@ async def test_commit_returns_connection_after_exit(uow, engine) -> None:
async def test_statement_longer_than_block(
engine,
warnings: _Warnings,
warnings: DatabaseWarnings,
) -> None:
"""Сценарий «Запрос дольше срока»."""
uow = make_uow(make_factory(engine), timeout_seconds=0.3)
@@ -177,7 +166,10 @@ async def test_statement_longer_than_block(
assert await _pid(uow) != first_pid
async def test_frozen_on_rollback(proxy_target, warnings: _Warnings) -> None:
async def test_frozen_on_rollback(
proxy_target,
warnings: DatabaseWarnings,
) -> None:
"""Сценарий «PostgreSQL заморожен при откате»."""
async with TcpProxy(*proxy_target) as proxy:
engine = make_engine(host="127.0.0.1", port=proxy.port, pool_size=1)
@@ -247,7 +239,118 @@ async def test_cancel_with_open_transaction(proxy_target) -> None:
await engine.dispose()
async def test_constraint_violation(uow, engine, warnings: _Warnings) -> None:
async def test_child_task_under_deadline_keeps_block_timer(engine) -> None:
"""Общий срок снимает таймер только у своей задачи: дочернюю его отмена не
достанет, а копия контекста у неё та же."""
uow = make_uow(make_factory(engine), timeout_seconds=0.3)
async def slow_block() -> None:
async with uow:
await uow._current_session().execute(text("SELECT pg_sleep(4)"))
started = time.monotonic()
async with scope.deadline_scope(timeout_seconds=30):
with pytest.raises(exceptions.ServiceUnavailable):
await asyncio.create_task(slow_block())
assert time.monotonic() - started < 0.3 + DB_CLOSE_TIMEOUT_SECONDS
async def _app_sessions(connection) -> int:
"""Сессии приложения во временной базе; соединение теста — без его имени."""
return await connection.fetchval(
"SELECT count(*) FROM pg_stat_activity "
"WHERE datname = current_database() AND application_name = $1",
DB_APPLICATION_NAME,
)
async def _settled_sessions(connection, *, limit: int) -> int:
"""Сессии, когда их стало не больше `limit` или вышел срок ожидания."""
deadline = time.monotonic() + SESSIONS_SETTLE_SECONDS
while True:
sessions = await _app_sessions(connection)
if sessions <= limit or time.monotonic() > deadline:
return sessions
await asyncio.sleep(0.1)
async def test_no_sessions_over_pool_after_freeze(proxy_target) -> None:
"""Сценарий «После заморозки PostgreSQL сессий сверх пула нет»: заморозка на
проверке соединения при выдаче (транзакции нет, и срок простоя транзакции
сессию не снимет), три раза подряд."""
pool_size = 2
connection = await admin()
try:
baseline = await _app_sessions(connection)
async with TcpProxy(*proxy_target) as proxy:
engine = make_engine(
host="127.0.0.1",
port=proxy.port,
pool_size=pool_size,
)
factory = make_factory(engine)
async def step() -> None:
uow = make_uow(factory, timeout_seconds=0.3)
async with uow:
await uow._current_session().execute(
text("SELECT pg_sleep(0.05)"),
)
for _ in range(3):
# прогрев: открыты все соединения пула, запросы идут вместе
await asyncio.gather(*(step() for _ in range(pool_size)))
proxy.freeze()
results = await asyncio.gather(
*(step() for _ in range(pool_size)),
return_exceptions=True,
)
assert all(
isinstance(result, exceptions.ServiceUnavailable)
for result in results
), results
proxy.thaw()
# соединения этой пачки сброшены, в пуле их нет
assert engine.pool.checkedout() == 0
sessions = await _settled_sessions(connection, limit=baseline)
assert sessions <= baseline, f"{sessions} > {baseline}"
# пул рабочий: новые соединения вместо сброшенных
await step()
await engine.dispose()
finally:
await connection.close()
async def test_soft_close_is_graceful(proxy_target) -> None:
"""Мягкое закрытие без отказа: сервер получил Terminate и закрыл сессию сам,
обрыв транспорта после него ничего не меняет."""
connection = await admin()
try:
baseline = await _app_sessions(connection)
async with TcpProxy(*proxy_target) as proxy:
engine = make_engine(
host="127.0.0.1",
port=proxy.port,
pool_size=1,
)
async with engine.connect():
pass
assert await _app_sessions(connection) == baseline + 1
before = proxy.client_writes
await engine.dispose()
sessions = await _settled_sessions(connection, limit=baseline)
assert sessions == baseline
# единственная порция клиента после проверки — Terminate
assert proxy.client_writes == before + 1
finally:
await connection.close()
async def test_constraint_violation(
uow,
engine,
warnings: DatabaseWarnings,
) -> None:
"""Сценарий «Нарушение ограничения»."""
async with uow:
first_pid = await _pid(uow)