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
View File
@@ -471,6 +471,8 @@ async def _statements(engine, action) -> list[str]:
[
("lock_due_jobs", "'queued'"),
("count_published", "'queued'"),
("count_unfinished", "'processing'"),
("count_unfinished", "'queued'"),
("lock_stale_pending", "'pending'"),
("get_staging_candidates", "'ready'"),
],
@@ -487,6 +489,8 @@ async def test_status_is_a_constant_in_statement(
await uow.jobs.lock_due_jobs(now=NOW, limit=1)
elif method == "count_published":
await uow.jobs.count_published()
elif method == "count_unfinished":
await uow.jobs.count_unfinished(limit=1)
elif method == "lock_stale_pending":
await uow.attachments.lock_stale_pending(
attachment_id=user_dto().id,
+17
View File
@@ -683,6 +683,23 @@ class FakeAttachmentJobRepository(
) -> dataclasses.AttachmentJobDTO | None:
return self._db.jobs.get(job_id)
async def count_unfinished(self, *, limit: int) -> int:
groups = (
[
job
for job in self._db.jobs.values()
if job.state == AttachmentJobState.QUEUED
and job.published_at is None
],
self._published(),
[
job
for job in self._db.jobs.values()
if job.state == AttachmentJobState.PROCESSING
],
)
return sum(min(len(group), limit) for group in groups)
async def get_attachment_job(
self,
*,
+58
View File
@@ -880,6 +880,64 @@ async def check_count_and_mark_published(new_uow: NewUow) -> None:
assert other.published_at is None
async def check_count_unfinished(new_uow: NewUow) -> None:
world = await _world(new_uow)
async def count(limit: int) -> int:
async with new_uow() as uow:
return await uow.jobs.count_unfinished(limit=limit)
assert await count(1) == 0
# завершённые не считаются
await _failed_job(new_uow, world)
succeeded = await _started_job(new_uow, world)
async with new_uow() as uow:
await uow.jobs.finish_job(
job_id=succeeded.id,
state=AttachmentJobState.SUCCEEDED,
reason=None,
now=at(1),
)
await uow.commit()
assert await count(10) == 0
# queued без отметки
outbox = await _job(new_uow, world)
assert await count(10) == 1
# queued с отметкой
published = await _job(new_uow, world)
async with new_uow() as uow:
await uow.jobs.mark_published(job_ids=[published.id], now=at(1))
await uow.commit()
assert await count(10) == 2
# processing
await _started_job(new_uow, world, lease_expires_at=at(100))
assert await count(10) == 3
# queued со сроком следующей попытки: ждёт, но считается
retrying = await _started_job(new_uow, world, lease_expires_at=at(100))
async with new_uow() as uow:
assert await uow.jobs.return_to_queued(
job_id=retrying.id,
attempt=retrying.attempt,
reason=AttachmentJobReason.STORAGE_UNAVAILABLE,
next_attempt_at=at(1000),
now=at(1),
)
await uow.commit()
assert await count(10) == 4
# решение «не меньше предела»: ниже, на пределе и выше
assert await count(5) < 5
assert await count(4) >= 4
assert await count(3) >= 3
# одна группа больше предела: счёт обрывается, решение то же
assert outbox is not None
extra = [await _job(new_uow, world) for _ in range(3)]
assert len(extra) == 3
assert await count(2) >= 2
# в outbox теперь 5 строк (retrying с outbox), две другие группы по одной
assert await count(3) == 3 + 1 + 1
assert await count(1) == 3
async def check_recover_expired_leases(new_uow: NewUow) -> None:
world = await _world(new_uow)
expired = await _started_job(new_uow, world, lease_expires_at=at(-5))
+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,