feat: limit accepted attachment work and add queue overload bench

Reject uploads with 429 at [uploads] max_unfinished_jobs, counted by the existing partial indexes in the membership block. Add the bench_queue profile, hypotheses H1-H9 and the fifth failure-stand API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-01 07:30:08 +03:00
co-authored by Claude Opus 5.5
parent 5b5f59aa3b
commit d667fa3c57
53 changed files with 5043 additions and 122 deletions
+4 -1
View File
@@ -39,7 +39,10 @@ def fixed_settings(monkeypatch: pytest.MonkeyPatch) -> None:
(settings.auth, {"session_ttl_seconds": 3600}),
(settings.idempotency, {"ttl_seconds": 86400}),
(settings.cache, {"chat_ttl_seconds": 600}),
(settings.uploads, {"body_timeout_seconds": 1}),
(
settings.uploads,
{"body_timeout_seconds": 1, "max_unfinished_jobs": 0},
),
(settings.app, {"instance_id": "test-instance"}),
)
for section, fields in fixed:
+132 -1
View File
@@ -8,8 +8,18 @@ from uuid import UUID, uuid4
import pytest
from builders import NOW, attachment_dto, chat_dto, user_dto, variant_dto
from builders import (
NOW,
attachment_dto,
chat_dto,
job_dto,
user_dto,
variant_dto,
)
from fakes import FakeCache, FakeDatabase, FakeObjectStorage, FakeUnitOfWork
from src.api.errors import DOMAIN_ERRORS, RETRY_AFTER
from src.api.schemas import ErrorCode
from src.config import settings
from src.core import exceptions
from src.core.services import AttachmentService
from src.infra.upload_slots import UploadSlots
@@ -130,6 +140,127 @@ async def test_upload_order_and_events(
assert not database.inside_block("storage.put")
def _fill_backlog(database: FakeDatabase, count: int) -> None:
"""`count` незавершённых заданий: `queued` и `processing` поровну."""
for number in range(count):
state = (
AttachmentJobState.QUEUED
if number % 2 == 0
else AttachmentJobState.PROCESSING
)
job = job_dto(attachment_id=uuid4())
database.jobs[job.id] = replace(job, state=state)
async def test_backlog_full_rejects_without_body_or_slot(
uow: FakeUnitOfWork,
cache: FakeCache,
storage: FakeObjectStorage,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(settings.uploads, "max_unfinished_jobs", 3)
_fill_backlog(database, 3)
slots = _slots()
service = AttachmentService(uow, cache, storage, slots)
# все места заняты: 429 предела приходит раньше очереди мест
async with slots.slot():
with pytest.raises(exceptions.UploadBacklogFull):
await _upload(service, world, body=_Untouched())
assert database.attachments == {}
assert storage.objects == {}
assert "jobs.count_unfinished" in database.events
# отказ не занял места: занятое выше освобождено, новая берётся
async with slots.slot():
pass
async def test_backlog_below_limit_accepts(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(settings.uploads, "max_unfinished_jobs", 3)
_fill_backlog(database, 2)
attachment = await _upload(service, world)
assert attachment.status == AttachmentStatus.QUEUED
assert database.events.index("jobs.count_unfinished") < (
database.events.index("attachments.insert_attachment")
)
# счёт — в первом блоке, рядом с членством: шаг с БД до тела один
first_block = database.events[
database.events.index("enter") : database.events.index("exit")
]
assert "jobs.count_unfinished" in first_block
async def test_backlog_finished_jobs_not_counted(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(settings.uploads, "max_unfinished_jobs", 2)
for state in (AttachmentJobState.SUCCEEDED, AttachmentJobState.FAILED):
for _ in range(3):
job = job_dto(attachment_id=uuid4())
database.jobs[job.id] = replace(job, state=state)
attachment = await _upload(service, world)
assert attachment.status == AttachmentStatus.QUEUED
async def test_backlog_off_makes_no_query(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(settings.uploads, "max_unfinished_jobs", 0)
_fill_backlog(database, 5)
attachment = await _upload(service, world)
assert attachment.status == AttachmentStatus.QUEUED
assert "jobs.count_unfinished" not in database.events
@pytest.mark.parametrize(
("kind", "error"),
[
("stranger", exceptions.ChatNotFound),
("type", exceptions.UnsupportedMediaType),
("size", exceptions.PayloadTooLarge),
],
)
async def test_backlog_checked_after_cheap_checks(
service: AttachmentService,
database: FakeDatabase,
world: tuple[UUID, UUID, UUID],
monkeypatch: pytest.MonkeyPatch,
kind: str,
error: type[Exception],
) -> None:
monkeypatch.setattr(settings.uploads, "max_unfinished_jobs", 1)
_fill_backlog(database, 1)
_, bob, _ = world
arguments = {
"stranger": {"owner": bob},
"type": {"media_type": "text/plain"},
"size": {"content_length": ATTACHMENT_MAX_BYTES + 1},
}[kind]
with pytest.raises(error):
await _upload(service, world, body=_Untouched(), **arguments)
assert "jobs.count_unfinished" not in database.events
async def test_backlog_error_maps_to_429_with_retry_after() -> None:
assert DOMAIN_ERRORS[exceptions.UploadBacklogFull] == (
429,
ErrorCode.RATE_LIMITED,
)
assert RETRY_AFTER[exceptions.UploadBacklogFull] == 5
async def test_not_member_404_before_everything(
service: AttachmentService,
database: FakeDatabase,