feat: reconcile the bucket against attachment rows in the cleaner

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 19:32:08 +03:00
co-authored by Claude Opus 5.5
parent c13df14f36
commit c1648d9b83
53 changed files with 4207 additions and 205 deletions
+179 -34
View File
@@ -1,15 +1,24 @@
"""Уборщик незавершённых загрузок: `python -m src.cleaner [--once]`.
"""Уборщик незавершённых загрузок и сверка bucket и БД.
`python -m src.cleaner [--once]` — сервис уборки; `python -m src.cleaner
reconcile [--apply] [--max-changes N]` — разовая сверка, по умолчанию
dry-run (design change `track2-reconciler`, решение 1).
Отдельный процесс стенда, а не задача реплик API (design change
`upload-consistency`, решения 2, 4, 5). Свои engine (пул из
`DATABASE__POOL_SIZE`, на стенде 1) и клиент S3 с ключами пользователя
уборщика; глобалы процесса API (`src/infra/db/session.py`,
`src/infra/s3/instance.py`) не импортируются.
`src/infra/s3/instance.py`) не импортируются. Сервис после прохода уборки
выполняет плановую сверку с исправлением: при старте и раз в
`[reconciler] interval_seconds` (0 — без неё; решение 9).
Коды выхода: 0 — остановлен сигналом или `--once` дошёл до конца
прохода; 1 — `--once` прерван отказом хранилища или ошибкой; 2 —
неверная конфигурация (grace не больше границы живой загрузки, ошибка
настроек — `src/cleaner/__main__.py`).
Коды выхода сервиса и `--once`: 0 — остановлен сигналом или `--once`
дошёл до конца прохода; 1 — `--once` прерван отказом хранилища или
ошибкой; 2 — неверная конфигурация (grace не больше границы живой
загрузки, ошибка настроек — `src/cleaner/__main__.py`, неверный
аргумент — argparse). Разовая сверка: 0 — расхождений нет, 3 — остались
(в том числе чужие объекты и отказ по пределу), 1 — прервана отказом,
ошибкой или сигналом, 2 — конфигурация (решение 8).
"""
import argparse
@@ -22,7 +31,10 @@ from sqlalchemy.ext.asyncio import AsyncSession
from src.config import settings
from src.config.settings import Settings
from src.core.services import AttachmentCleanupService
from src.core.services import (
AttachmentCleanupService,
AttachmentReconcileService,
)
from src.core.services.attachment_cleanup import INTERRUPTED_BY_STOP
from src.infra import early_stop
from src.infra.db import create_engine, create_session_factory
@@ -37,6 +49,12 @@ logger: AbstractLogger = get_logger().bind(module="cleaner")
EXIT_OK = 0
EXIT_PASS_FAILED = 1
EXIT_CONFIG = 2
# разовая сверка: расхождения остались
EXIT_DISCREPANCIES = 3
MODE_SERVICE = "service"
MODE_ONCE = "once"
MODE_RECONCILE = "reconcile"
def live_upload_bound_seconds(config: Settings) -> float:
@@ -52,27 +70,72 @@ def live_upload_bound_seconds(config: Settings) -> float:
)
def _positive_int(value: str) -> int:
number = int(value)
if number < 1:
raise argparse.ArgumentTypeError("must be at least 1")
return number
def _parse_args(argv: list[str] | None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
prog="python -m src.cleaner",
description="Remove stale pending attachments and their objects.",
description="Remove stale pending attachments and their objects; "
"reconcile the bucket with the database.",
)
parser.add_argument(
"--once",
action="store_true",
help="one pass and exit: 0 done, 1 interrupted, 2 bad config",
help="one cleanup pass and exit: 0 done, 1 interrupted, 2 bad config",
)
commands = parser.add_subparsers(dest="command")
reconcile = commands.add_parser(
MODE_RECONCILE,
help="one reconcile pass, dry-run by default: 0 no discrepancies, "
"3 discrepancies left, 1 interrupted, 2 bad config",
)
reconcile.add_argument(
"--apply",
action="store_true",
help="fix what is safe to fix",
)
reconcile.add_argument(
"--max-changes",
type=_positive_int,
default=None,
help="change limit of the pass (default: [reconciler] max_changes)",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
args = _parse_args(argv)
return asyncio.run(run(once=args.once))
if args.command == MODE_RECONCILE:
return asyncio.run(
run(
mode=MODE_RECONCILE,
apply=args.apply,
max_changes=(
settings.reconciler.max_changes
if args.max_changes is None
else args.max_changes
),
),
)
return asyncio.run(run(mode=MODE_ONCE if args.once else MODE_SERVICE))
async def run(*, once: bool) -> int:
"""Проверка grace, затем проходы до сигнала (или один с `--once`)."""
async def run(
*,
mode: str,
apply: bool = True,
max_changes: int | None = None,
) -> int:
"""Проверка grace, затем проходы уборки до сигнала (или один с
`--once`) с плановой сверкой — или одна разовая сверка."""
cleaner = settings.cleaner
reconciler = settings.reconciler
limit = reconciler.max_changes if max_changes is None else max_changes
bound = live_upload_bound_seconds(settings)
if cleaner.pending_grace_seconds <= bound:
# до engine и клиента S3: ни одного обращения к хранилищам
@@ -91,8 +154,8 @@ async def run(*, once: bool) -> int:
loop = asyncio.get_running_loop()
for signum in (signal.SIGTERM, signal.SIGINT):
loop.add_signal_handler(signum, stop.set)
# дальше сигналы обрабатывает цикл: текущий шаг уборки доводится до
# commit или отката, новые не начинаются
# дальше сигналы обрабатывает цикл: текущий шаг уборки или сверки
# доводится до commit или отката, новые не начинаются
early_stop.disarm()
engine = create_engine(settings.database)
@@ -108,7 +171,8 @@ async def run(*, once: bool) -> int:
timeout_seconds=settings.database.request_timeout_seconds,
)
service = AttachmentCleanupService(db_scope=db_scope, storage=storage)
cleanup = AttachmentCleanupService(db_scope=db_scope, storage=storage)
reconcile = AttachmentReconcileService(db_scope=db_scope, storage=storage)
exit_code = EXIT_OK
try:
if not (
@@ -120,11 +184,16 @@ async def run(*, once: bool) -> int:
await storage.start()
logger.info(
"Started cleaner",
mode=mode,
interval_seconds=cleaner.interval_seconds,
pending_grace_seconds=cleaner.pending_grace_seconds,
batch_size=cleaner.batch_size,
live_upload_bound_seconds=bound,
once=once,
once=mode == MODE_ONCE,
reconcile_interval_seconds=reconciler.interval_seconds,
reconcile_page_size=reconciler.page_size,
reconcile_max_changes=limit,
reconcile_apply=apply if mode == MODE_RECONCILE else None,
database_host=settings.database.host,
database_port=settings.database.port,
database_name=settings.database.name,
@@ -133,26 +202,21 @@ async def run(*, once: bool) -> int:
s3_port=settings.s3.port,
s3_bucket=settings.s3.bucket,
)
while not stop.is_set():
result = await _clean_once(
service,
grace_seconds=cleaner.pending_grace_seconds,
batch_size=cleaner.batch_size,
if mode == MODE_RECONCILE:
result = await _reconcile_once(
reconcile,
apply=apply,
max_changes=limit,
stop=stop,
)
exit_code = _reconcile_exit_code(result)
else:
exit_code = await _serve(
cleanup,
reconcile,
once=mode == MODE_ONCE,
stop=stop,
)
if once:
if result is None or result.interrupted_by not in (
None,
INTERRUPTED_BY_STOP,
):
exit_code = EXIT_PASS_FAILED
break
# пауза до следующего прохода или до сигнала
with suppress(TimeoutError):
await asyncio.wait_for(
stop.wait(),
timeout=cleaner.interval_seconds,
)
finally:
await engine.dispose()
await storage.aclose()
@@ -160,6 +224,51 @@ async def run(*, once: bool) -> int:
return exit_code
async def _serve(
cleanup: AttachmentCleanupService,
reconcile: AttachmentReconcileService,
*,
once: bool,
stop: asyncio.Event,
) -> int:
"""Проходы уборки до сигнала; после прохода — плановая сверка, если
подошёл её срок: первая — при старте, следующая — через
`[reconciler] interval_seconds` после конца предыдущей."""
cleaner = settings.cleaner
interval = settings.reconciler.interval_seconds
loop = asyncio.get_running_loop()
next_reconcile = loop.time() if interval > 0 and not once else None
while not stop.is_set():
result = await _clean_once(
cleanup,
grace_seconds=cleaner.pending_grace_seconds,
batch_size=cleaner.batch_size,
stop=stop,
)
if once:
if result is None or result.interrupted_by not in (
None,
INTERRUPTED_BY_STOP,
):
return EXIT_PASS_FAILED
return EXIT_OK
pause = cleaner.interval_seconds
if next_reconcile is not None and not stop.is_set():
if loop.time() >= next_reconcile:
await _reconcile_once(
reconcile,
apply=True,
max_changes=settings.reconciler.max_changes,
stop=stop,
)
next_reconcile = loop.time() + interval
pause = min(pause, max(0.0, next_reconcile - loop.time()))
# пауза до следующего прохода или до сигнала
with suppress(TimeoutError):
await asyncio.wait_for(stop.wait(), timeout=pause)
return EXIT_OK
async def _clean_once(
service: AttachmentCleanupService,
*,
@@ -180,3 +289,39 @@ async def _clean_once(
except Exception as e:
logger.error("Cleanup pass failed", exc_info=e)
return None
async def _reconcile_once(
service: AttachmentReconcileService,
*,
apply: bool,
max_changes: int,
stop: asyncio.Event,
) -> dataclasses.ReconcilePassDTO | None:
"""Проход сверки; `None` — непредвиденная ошибка: `error` с
traceback, сервис живёт до следующей плановой сверки."""
older_than = utcnow() - timedelta(
seconds=settings.cleaner.pending_grace_seconds,
)
try:
return await service.reconcile(
older_than=older_than,
apply=apply,
max_changes=max_changes,
page_size=settings.reconciler.page_size,
batch_size=settings.cleaner.batch_size,
stop_requested=stop.is_set,
)
except Exception as e:
logger.error("Reconcile pass failed", exc_info=e)
return None
def _reconcile_exit_code(result: dataclasses.ReconcilePassDTO | None) -> int:
"""Код разового прохода сверки: прерван (в том числе сигналом) — 1,
остались расхождения или отказ по пределу — 3, иначе 0."""
if result is None or result.interrupted_by is not None:
return EXIT_PASS_FAILED
if result.remaining or result.refused:
return EXIT_DISCREPANCIES
return EXIT_OK