Files
mtusi2026lab6/src/core/repos/attachment_job.py
T
ricoromaandClaude Opus 5.5 9cc6c0c7a6 chore: port lab 5 solution into the lab 6 skeleton
Source: mtusi2026lab5-safronov, solution/bvt2301-safronov, 046ec9e.
Contracts, public tests and evidence of lab 5 are not carried over.
The compose project, image and CI prefix are renamed to lab6; the first
broker start defect is recorded in KNOWN_ISSUES.md; PLAN.md outlines the
OpenSpec changes of lab 6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 04:46:56 +03:00

456 lines
17 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Задание обработки вложения в PostgreSQL (design change `async-attachments`,
решения 1, 3, 7; `pipeline-reliability`, решения 2–5).
Логическая работа одна на вложение и версию; `id` — `job_id` контракта, при
повторах и replay не меняется. Строки `queued` без `published_at` — outbox:
намерения, которые публикует relay. Порядок блокировок везде один: сначала
строка задания, затем вложения. `updated_at` — через `greatest`: часы процессов
расходятся. Состояние в выборках relay — константой (`literal_execute`): условие
частичного индекса планировщик доказывает только по константе, а общий план с
параметром — Seq Scan (проба, решение 2).
"""
from collections.abc import Collection
from datetime import datetime
from uuid import UUID
from sqlalchemy import (
BindParameter,
ColumnElement,
Row,
Uuid,
any_,
bindparam,
exists,
func,
insert,
literal,
literal_column,
select,
update,
)
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy.ext.asyncio import AsyncSession
from src.core.ports.attachment_job import AbstractAttachmentJobRepository
from src.infra.db.models import Attachment, AttachmentJob
from src.schemas import dataclasses
from src.schemas.enums import (
AttachmentErrorCode,
AttachmentJobReason,
AttachmentJobState,
)
_JOB_COLUMNS = (
AttachmentJob.id,
AttachmentJob.attachment_id,
AttachmentJob.pipeline_version,
AttachmentJob.state,
AttachmentJob.attempt,
AttachmentJob.attempt_base,
AttachmentJob.created_at,
AttachmentJob.updated_at,
AttachmentJob.last_error_code,
AttachmentJob.next_attempt_at,
AttachmentJob.lease_expires_at,
AttachmentJob.published_at,
AttachmentJob.finished_at,
)
# срок задания: то же выражение, что в индексе ix_attachment_jobs_outbox
_DUE_AT = func.coalesce(
AttachmentJob.next_attempt_at,
AttachmentJob.created_at,
)
def _queued() -> ColumnElement[bool]:
return AttachmentJob.state == literal(
AttachmentJobState.QUEUED.value,
literal_execute=True,
)
def _outbox_condition() -> tuple[ColumnElement[bool], ...]:
return (_queued(), AttachmentJob.published_at.is_(None))
def _uuid_array(values: Collection[UUID]) -> BindParameter:
return bindparam(None, list(values), type_=ARRAY(Uuid()))
def _to_dto(row: Row) -> dataclasses.AttachmentJobDTO:
fields = dict(row._mapping)
fields["state"] = AttachmentJobState(fields["state"])
return dataclasses.AttachmentJobDTO(**fields)
def _later_of_now(now: datetime) -> ColumnElement[datetime]:
return func.greatest(now, AttachmentJob.updated_at)
class SqlAlchemyAttachmentJobRepository(AbstractAttachmentJobRepository):
def __init__(self, session: AsyncSession) -> None:
self._session = session
async def insert_job(
self,
*,
job: dataclasses.AttachmentJobDTO,
) -> dataclasses.AttachmentJobDTO:
"""Новая работа; вложение становится `queued` в той же транзакции."""
await self._session.execute(
insert(AttachmentJob).values(
id=job.id,
attachment_id=job.attachment_id,
pipeline_version=job.pipeline_version,
state=job.state.value,
attempt=job.attempt,
created_at=job.created_at,
updated_at=job.updated_at,
),
)
return job
async def lock_job(
self,
*,
job_id: UUID,
) -> dataclasses.AttachmentJobDTO | None:
"""Задание под `FOR UPDATE` до конца транзакции."""
statement = (
select(*_JOB_COLUMNS)
.where(AttachmentJob.id == job_id)
.with_for_update()
)
row = (await self._session.execute(statement)).one_or_none()
return None if row is None else _to_dto(row)
async def get_job(
self,
*,
job_id: UUID,
) -> dataclasses.AttachmentJobDTO | None:
statement = select(*_JOB_COLUMNS).where(AttachmentJob.id == job_id)
row = (await self._session.execute(statement)).one_or_none()
return None if row is None else _to_dto(row)
async def get_attachment_job(
self,
*,
attachment_id: UUID,
pipeline_version: int,
) -> dataclasses.AttachmentJobDTO | None:
statement = select(*_JOB_COLUMNS).where(
AttachmentJob.attachment_id == attachment_id,
AttachmentJob.pipeline_version == pipeline_version,
)
row = (await self._session.execute(statement)).one_or_none()
return None if row is None else _to_dto(row)
async def start_attempt(
self,
*,
job_id: UUID,
lease_expires_at: datetime,
now: datetime,
) -> dataclasses.AttachmentJobDTO | None:
"""Начать попытку под блокировкой `lock_job`: счётчик +1, срок аренды,
`processing`. Вызывающий проверил, что итога и живой аренды нет."""
statement = (
update(AttachmentJob)
.where(AttachmentJob.id == job_id)
.values(
state=AttachmentJobState.PROCESSING.value,
attempt=AttachmentJob.attempt + 1,
lease_expires_at=lease_expires_at,
next_attempt_at=None,
updated_at=_later_of_now(now),
)
.returning(*_JOB_COLUMNS)
)
row = (await self._session.execute(statement)).one_or_none()
return None if row is None else _to_dto(row)
async def return_to_queued(
self,
*,
job_id: UUID,
attempt: int,
reason: AttachmentJobReason,
next_attempt_at: datetime,
now: datetime,
) -> bool:
"""Временная ошибка: `processing` → `queued`, только своя попытка (номер
совпал), со сроком следующей. Сообщение ещё не передано, его опубликует
relay: `published_at` — NULL. `False` — задание уже ведёт другая попытка
или есть итог."""
statement = (
update(AttachmentJob)
.where(
AttachmentJob.id == job_id,
AttachmentJob.state == AttachmentJobState.PROCESSING.value,
AttachmentJob.attempt == attempt,
)
.values(
state=AttachmentJobState.QUEUED.value,
last_error_code=reason.value,
next_attempt_at=next_attempt_at,
lease_expires_at=None,
published_at=None,
updated_at=_later_of_now(now),
)
.returning(AttachmentJob.id)
)
return (
await self._session.execute(statement)
).one_or_none() is not None
async def finish_job(
self,
*,
job_id: UUID,
state: AttachmentJobState,
reason: AttachmentJobReason | None,
now: datetime,
) -> bool:
"""Итог задания: `succeeded` или `failed`, под блокировкой
`lock_job`."""
values: dict[str, object] = {
"state": state.value,
"lease_expires_at": None,
"next_attempt_at": None,
"finished_at": now,
"updated_at": _later_of_now(now),
}
if reason is not None:
values["last_error_code"] = reason.value
statement = (
update(AttachmentJob)
.where(AttachmentJob.id == job_id)
.values(**values)
.returning(AttachmentJob.id)
)
return (
await self._session.execute(statement)
).one_or_none() is not None
async def lock_due_jobs(
self,
*,
now: datetime,
limit: int,
) -> list[dataclasses.AttachmentJobDTO]:
"""Намерения, срок которых наступил, в порядке срока, под `FOR UPDATE
SKIP LOCKED`: задание, которое публикует другой relay, пропускается.
Блокировка держится до отметки: worker, получивший сообщение раньше
COMMIT, ждёт её в `lock_job`."""
statement = (
select(*_JOB_COLUMNS)
.where(*_outbox_condition(), now >= _DUE_AT)
.order_by(_DUE_AT, AttachmentJob.id)
.limit(limit)
.with_for_update(skip_locked=True)
)
rows = (await self._session.execute(statement)).all()
return [_to_dto(row) for row in rows]
async def count_published(self) -> int:
"""Опубликованные и не взятые задания: то, что считает предел."""
statement = (
select(func.count())
.select_from(AttachmentJob)
.where(_queued(), AttachmentJob.published_at.is_not(None))
)
return (await self._session.execute(statement)).scalar_one()
async def count_unfinished(self, *, limit: int) -> int:
"""Сумма трёх счётов, каждый оборван на `limit`, по условиям частичных
индексов outbox, опубликованных и аренды: Index Only Scan, один запрос
(design change `track1-queue-overload`, решение 3). Без `LIMIT` цена
росла бы с бэклогом; новый индекс не быстрее, а запись дороже (проба)."""
groups = (
_outbox_condition(),
(_queued(), AttachmentJob.published_at.is_not(None)),
(
AttachmentJob.state
== literal(
AttachmentJobState.PROCESSING.value,
literal_execute=True,
),
),
)
counts = [
select(func.count())
.select_from(
select(literal_column("1").label("one"))
.select_from(AttachmentJob)
.where(*condition)
.limit(limit)
.subquery(),
)
.scalar_subquery()
for condition in groups
]
statement = select(counts[0] + counts[1] + counts[2])
return (await self._session.execute(statement)).scalar_one()
async def mark_published(
self,
*,
job_ids: Collection[UUID],
now: datetime,
) -> int:
"""Брокер подтвердил сообщения пакета: время — отметка, а не условие.
Вызывается под блокировкой `lock_due_jobs`."""
statement = (
update(AttachmentJob)
.where(AttachmentJob.id == any_(_uuid_array(job_ids)))
.values(published_at=now, updated_at=_later_of_now(now))
.returning(AttachmentJob.id)
)
return len((await self._session.execute(statement)).all())
async def recover_expired_leases(
self,
*,
now: datetime,
limit: int,
) -> list[dataclasses.AttachmentJobDTO]:
"""Истёкшие аренды: `processing` → `queued` без паузы, причина «истёк
срок аренды» (design change `pipeline-reliability`, решения 2 и 3).
Вложения тех же `id` переводит вызывающий в той же транзакции: порядок
блокировок — задание, затем вложение."""
expired = (
select(AttachmentJob.id)
.where(
AttachmentJob.state
== literal(
AttachmentJobState.PROCESSING.value,
literal_execute=True,
),
AttachmentJob.lease_expires_at < now,
)
.order_by(AttachmentJob.lease_expires_at)
.limit(limit)
.with_for_update(skip_locked=True)
)
statement = (
update(AttachmentJob)
.where(AttachmentJob.id.in_(expired))
.values(
state=AttachmentJobState.QUEUED.value,
last_error_code=AttachmentJobReason.LEASE_EXPIRED.value,
lease_expires_at=None,
next_attempt_at=None,
published_at=None,
updated_at=_later_of_now(now),
)
.returning(*_JOB_COLUMNS)
)
rows = (await self._session.execute(statement)).all()
return [_to_dto(row) for row in rows]
async def has_published_before(self, *, older_than: datetime) -> bool:
"""Есть ли отмеченные задания старше порога: кандидаты в потерянные."""
# IS NOT NULL явно: условие индекса ix_attachment_jobs_published (проба)
statement = select(
exists().where(
_queued(),
AttachmentJob.published_at.is_not(None),
AttachmentJob.published_at < older_than,
),
)
return bool((await self._session.execute(statement)).scalar_one())
async def reset_published_before(
self,
*,
older_than: datetime,
now: datetime,
) -> int:
"""Потерянные сообщения: отметка снимается, задание снова намерение."""
statement = (
update(AttachmentJob)
.where(
_queued(),
AttachmentJob.published_at.is_not(None),
AttachmentJob.published_at < older_than,
)
.values(published_at=None, updated_at=_later_of_now(now))
.returning(AttachmentJob.id)
)
return len((await self._session.execute(statement)).all())
async def replay_job(self, *, job_id: UUID, now: datetime) -> bool:
"""`failed` → `queued` с новым бюджетом (design change
`pipeline-reliability`, решение 5): `attempt` монотонен, это
fencing-токен, поэтому бюджет считается от `attempt_base`. Сообщение
публикует relay."""
statement = (
update(AttachmentJob)
.where(
AttachmentJob.id == job_id,
AttachmentJob.state == AttachmentJobState.FAILED.value,
)
.values(
state=AttachmentJobState.QUEUED.value,
attempt_base=AttachmentJob.attempt,
last_error_code=None,
next_attempt_at=None,
lease_expires_at=None,
published_at=None,
finished_at=None,
updated_at=_later_of_now(now),
)
.returning(AttachmentJob.id)
)
return (
await self._session.execute(statement)
).one_or_none() is not None
async def list_failed(
self,
*,
error_code: str | None,
reason: str | None,
limit: int,
) -> list[dataclasses.FailedJobDTO]:
"""Реестр `failed`, новые раньше. Индекса нет: выбор оператора редок, а
строк `failed` мало (решение 10)."""
statement = (
select(
AttachmentJob.id.label("job_id"),
AttachmentJob.attachment_id,
Attachment.error_code,
AttachmentJob.last_error_code.label("reason"),
AttachmentJob.attempt,
AttachmentJob.attempt_base,
AttachmentJob.finished_at,
)
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
.where(AttachmentJob.state == AttachmentJobState.FAILED.value)
.order_by(AttachmentJob.finished_at.desc(), AttachmentJob.id)
.limit(limit)
)
if error_code is not None:
statement = statement.where(Attachment.error_code == error_code)
if reason is not None:
statement = statement.where(
AttachmentJob.last_error_code == reason,
)
rows = (await self._session.execute(statement)).all()
return [
dataclasses.FailedJobDTO(
**{
**row._mapping,
"error_code": (
None
if row.error_code is None
else AttachmentErrorCode(row.error_code)
),
},
)
for row in rows
]