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
+22 -1
View File
@@ -59,13 +59,34 @@ from sqlalchemy.ext.asyncio import ( # noqa: E402
)
from src.config import settings # noqa: E402
from src.infra.db import create_engine, create_session_factory # noqa: E402
from src.infra.db import ( # noqa: E402
create_engine,
create_session_factory,
scope,
)
from src.infra.db.models.base import Base # noqa: E402
from src.infra.db.uow import SqlAlchemyUnitOfWork # noqa: E402
_created = False
class DatabaseWarnings:
"""Записи логгера `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) -> DatabaseWarnings:
recorder = DatabaseWarnings()
monkeypatch.setattr(scope, "logger", recorder)
return recorder
async def _admin_connection(database: str = "postgres") -> asyncpg.Connection:
source = settings.database
return await asyncpg.connect(
+69 -1
View File
@@ -3,6 +3,7 @@ JSON-запроса (спек `unit-of-work`). S3 и кэш — фейки: ра
PostgreSQL как сервера, не затрагивается."""
import asyncio
import logging
import time
from collections.abc import AsyncIterator
from pathlib import Path
@@ -13,10 +14,17 @@ import pytest
from sqlalchemy import event
from builders import attachment_dto
from conftest import BLOCK_SECONDS, admin, truncate_all
from conftest import (
BLOCK_SECONDS,
DatabaseWarnings,
TcpProxy,
admin,
truncate_all,
)
from fakes import FakeCache, FakeDatabase, FakeObjectStorage
from src.api import dependencies
from src.core.repos import chat_cache
from src.core.services import ChatService
from src.core.services import session as session_module
from src.infra.db import create_engine, create_session_factory
from src.infra.db.session import engine, session_factory
@@ -24,6 +32,7 @@ from src.infra.db.uow import SqlAlchemyUnitOfWork
from src.main import app
from src.schemas.dataclasses import ChatFullDTO
from src.schemas.enums import AttachmentStatus
from src.utils.constants import DB_CLOSE_TIMEOUT_SECONDS
from src.utils.utc import utcnow
pytestmark = pytest.mark.anyio
@@ -268,6 +277,65 @@ async def test_hash_queue_gets_deadline(client: httpx.AsyncClient) -> None:
assert max(elapsed for _, elapsed in results) < BLOCK_SECONDS + MARGIN
class _PoolRecords(logging.Handler):
"""Записи пула: только текст, `exc_info` с кадрами не хранится."""
def __init__(self) -> None:
super().__init__(level=logging.WARNING)
self.messages: list[str] = []
def emit(self, record: logging.LogRecord) -> None:
self.messages.append(record.getMessage())
async def test_deadline_in_second_block_single_record(
client: httpx.AsyncClient,
monkeypatch: pytest.MonkeyPatch,
proxy_target: tuple[str, int],
warnings: DatabaseWarnings,
) -> None:
"""Сценарий «Срок запроса истёк во втором блоке: одна запись, без ERROR
пула»: заморозка между входом и операцией, зазор сроков — настоящая
длительность блока входа."""
headers, _ = await _register_login(client)
records = _PoolRecords()
pool_logger = logging.getLogger("sqlalchemy.pool")
pool_logger.addHandler(records)
async with TcpProxy(*proxy_target) as proxy:
proxied = create_engine(
dependencies.settings.database.model_copy(
update={"host": "127.0.0.1", "port": proxy.port},
),
)
monkeypatch.setattr(
dependencies,
"session_factory",
create_session_factory(proxied),
)
real_list = ChatService.list_user_chats
async def frozen_list(self, **kwargs):
proxy.freeze()
return await real_list(self, **kwargs)
monkeypatch.setattr(ChatService, "list_user_chats", frozen_list)
try:
started = time.monotonic()
response = await client.get("/chats", headers=headers)
elapsed = time.monotonic() - started
checked_out = proxied.pool.checkedout()
finally:
pool_logger.removeHandler(records)
proxy.thaw()
await proxied.dispose()
assert response.status_code == 503
assert response.json()["error"]["code"] == "unavailable"
assert elapsed < BLOCK_SECONDS + DB_CLOSE_TIMEOUT_SECONDS + MARGIN
assert warnings.events == ["Database is unavailable"]
assert records.messages == []
assert checked_out == 0
async def test_upload_longer_than_block(
client: httpx.AsyncClient,
fake_clients,
+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)