feat: add reconcile strategies, deep check, rate limit and cost profile

- reconcile --strategy head, --deep (checksum_mismatch), restore needs the same SHA-256
- [reconciler] max_objects_per_second (2000), pause interrupted by signal
- --apply stops rechecks once the limit is exceeded (unchecked)
- pass cost in the summary: S3 objects and requests, bytes, DB sessions, phases
- S3 client counters, cleaner exits with os._exit after main()
- fault tests, hook args, driver reconcile-signal --pace
- bench profile reconcile / reconcile_quick: fill outside the API, gateway metrics, background load
- sync spec deltas, rules, AGENTS.md, PLAN.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-23 04:52:56 +03:00
co-authored by Claude Opus 5.5
parent dcdfe5f2e4
commit 8d4cf7eebf
41 changed files with 5344 additions and 441 deletions
+11 -1
View File
@@ -30,4 +30,14 @@ if __name__ == "__main__":
)
sys.exit(2)
sys.exit(main())
code = main()
# engine и клиент S3 закрыты, «Stopped cleaner» записан: выход без
# финализации интерпретатора. При 0,25 CPU она длится 0,8–1,5 с (модули
# botocore, SQLAlchemy), и остановка по сигналу во время паузы предела
# скорости не укладывалась бы в секунду (design change
# track2-reconcile-cost, «Уточнения apply», п. 14)
import os
sys.stdout.flush()
sys.stderr.flush()
os._exit(code)
+72 -9
View File
@@ -1,8 +1,10 @@
"""Уборщик незавершённых загрузок и сверка bucket и БД.
`python -m src.cleaner [--once]` — сервис уборки; `python -m src.cleaner
reconcile [--apply] [--max-changes N]` — разовая сверка, по умолчанию
dry-run (design change `track2-reconciler`, решение 1).
reconcile [--apply] [--max-changes N] [--strategy batch|head] [--deep]
[--max-objects-per-second R]` — разовая сверка, по умолчанию dry-run
(design change `track2-reconciler`, решение 1; стратегия, глубина и
предел скорости — design change `track2-reconcile-cost`, решения 4–6).
Отдельный процесс стенда, а не задача реплик API (design change
`upload-consistency`, решения 2, 4, 5). Свои engine (пул из
@@ -23,6 +25,7 @@ dry-run (design change `track2-reconciler`, решение 1).
import argparse
import asyncio
import math
import signal
from contextlib import AbstractAsyncContextManager, suppress
from datetime import timedelta
@@ -42,6 +45,7 @@ from src.infra.db.scope import session_scope
from src.infra.logger import AbstractLogger, get_logger
from src.infra.s3 import create_object_storage
from src.schemas import dataclasses
from src.schemas.enums import ReconcileStrategy
from src.utils.utc import utcnow
logger: AbstractLogger = get_logger().bind(module="cleaner")
@@ -77,6 +81,16 @@ def _positive_int(value: str) -> int:
return number
def _non_negative_float(value: str) -> float:
try:
number = float(value)
except ValueError:
raise argparse.ArgumentTypeError("must be a number") from None
if not math.isfinite(number) or number < 0:
raise argparse.ArgumentTypeError("must be a non-negative number")
return number
def _parse_args(argv: list[str] | None) -> argparse.Namespace:
parser = argparse.ArgumentParser(
prog="python -m src.cleaner",
@@ -105,6 +119,25 @@ def _parse_args(argv: list[str] | None) -> argparse.Namespace:
default=None,
help="change limit of the pass (default: [reconciler] max_changes)",
)
reconcile.add_argument(
"--strategy",
choices=[item.value for item in ReconcileStrategy],
default=ReconcileStrategy.BATCH.value,
help="batch: list pages and one database query per page; head: a "
"database query per object and HEAD per ready row",
)
reconcile.add_argument(
"--deep",
action="store_true",
help="read objects and compare their SHA-256 with the metadata",
)
reconcile.add_argument(
"--max-objects-per-second",
type=_non_negative_float,
default=None,
help="S3 objects per second, 0 - no limit "
"(default: [reconciler] max_objects_per_second)",
)
return parser.parse_args(argv)
@@ -115,11 +148,10 @@ def main(argv: list[str] | None = None) -> int:
run(
mode=MODE_RECONCILE,
apply=args.apply,
max_changes=(
settings.reconciler.max_changes
if args.max_changes is None
else args.max_changes
),
max_changes=args.max_changes,
strategy=ReconcileStrategy(args.strategy),
deep=args.deep,
max_objects_per_second=args.max_objects_per_second,
),
)
return asyncio.run(run(mode=MODE_ONCE if args.once else MODE_SERVICE))
@@ -130,12 +162,24 @@ async def run(
mode: str,
apply: bool = True,
max_changes: int | None = None,
strategy: ReconcileStrategy = ReconcileStrategy.BATCH,
deep: bool = False,
max_objects_per_second: float | None = None,
) -> int:
"""Проверка grace, затем проходы уборки до сигнала (или один с
`--once`) с плановой сверкой — или одна разовая сверка."""
`--once`) с плановой сверкой — или одна разовая сверка. Стратегия и
глубина — только у разовой сверки; плановая — `batch`, поверхностная,
предел скорости из настроек (design change `track2-reconcile-cost`,
решения 4–6)."""
cleaner = settings.cleaner
reconciler = settings.reconciler
limit = reconciler.max_changes if max_changes is None else max_changes
rate = (
reconciler.max_objects_per_second
if max_objects_per_second is None
else max_objects_per_second
)
once_pass = mode == MODE_RECONCILE
bound = live_upload_bound_seconds(settings)
if cleaner.pending_grace_seconds <= bound:
# до engine и клиента S3: ни одного обращения к хранилищам
@@ -193,7 +237,10 @@ async def run(
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,
reconcile_max_objects_per_second=rate,
reconcile_apply=apply if once_pass else None,
reconcile_strategy=strategy.value if once_pass else None,
reconcile_deep=deep if once_pass else None,
database_host=settings.database.host,
database_port=settings.database.port,
database_name=settings.database.name,
@@ -207,6 +254,9 @@ async def run(
reconcile,
apply=apply,
max_changes=limit,
strategy=strategy,
deep=deep,
max_objects_per_second=rate,
stop=stop,
)
exit_code = _reconcile_exit_code(result)
@@ -255,10 +305,17 @@ async def _serve(
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,
strategy=ReconcileStrategy.BATCH,
deep=False,
max_objects_per_second=(
settings.reconciler.max_objects_per_second
),
stop=stop,
)
next_reconcile = loop.time() + interval
@@ -296,6 +353,9 @@ async def _reconcile_once(
*,
apply: bool,
max_changes: int,
strategy: ReconcileStrategy,
deep: bool,
max_objects_per_second: float,
stop: asyncio.Event,
) -> dataclasses.ReconcilePassDTO | None:
"""Проход сверки; `None` — непредвиденная ошибка: `error` с
@@ -310,6 +370,9 @@ async def _reconcile_once(
max_changes=max_changes,
page_size=settings.reconciler.page_size,
batch_size=settings.cleaner.batch_size,
strategy=strategy,
deep=deep,
max_objects_per_second=max_objects_per_second,
stop_requested=stop.is_set,
)
except Exception as e: