"""`AttachmentReconcileService`: находки обеих стратегий, действия, счёт блоков.""" from dataclasses import replace from datetime import timedelta from hashlib import sha256 from uuid import uuid4 import pytest from builders import attachment_dto from fakes import FakeDatabase, FakeObjectStorage, FakeUnitOfWork from src.core import exceptions from src.core.services.attachment_cleanup import ( INTERRUPTED_BY_DATABASE, INTERRUPTED_BY_OBJECT_STORAGE, INTERRUPTED_BY_STOP, ) from src.core.services.attachment_reconcile import AttachmentReconcileService from src.schemas import dataclasses from src.schemas.enums import ( AttachmentStatus, ReconcileFinding, ReconcileStrategy, ) from src.utils.utc import utcnow pytestmark = pytest.mark.anyio STRATEGIES = list(ReconcileStrategy) def _long_ago(): return utcnow() - timedelta(hours=2) @pytest.fixture def service( uow: FakeUnitOfWork, storage: FakeObjectStorage, ) -> AttachmentReconcileService: return AttachmentReconcileService(uow, storage) async def _ready( uow: FakeUnitOfWork, storage: FakeObjectStorage, *, with_object: bool = True, data: bytes = b"content", object_key: str | None = None, updated_at=None, ) -> dataclasses.AttachmentFullDTO: moment = updated_at or _long_ago() row = attachment_dto( chat_id=uuid4(), owner_id=uuid4(), status=AttachmentStatus.READY, created_at=moment, staging=False, data=data, object_key=object_key, ) async with uow: await uow.attachments.insert_attachment(attachment=row) await uow.commit() if with_object: storage.seed(row.object_key, data, last_modified=_long_ago()) return row def _key(storage: FakeObjectStorage, name: str) -> str: return f"{storage.namespace}/attachments/{name}" async def _pass( service: AttachmentReconcileService, *, apply: bool = False, strategy: ReconcileStrategy = ReconcileStrategy.BATCH, deep: bool = False, max_changes: int = 100, stop_requested=None, page_size: int = 2, ) -> dataclasses.ReconcilePassDTO: now = utcnow() kwargs = ( {} if stop_requested is None else {"stop_requested": stop_requested} ) return await service.reconcile( older_than=now - timedelta(minutes=15), staging_older_than=now - timedelta(minutes=15), apply=apply, max_changes=max_changes, page_size=page_size, batch_size=2, strategy=strategy, deep=deep, **kwargs, ) async def _all_classes( uow: FakeUnitOfWork, storage: FakeObjectStorage, ) -> dict[str, object]: """По одному расхождению каждого класса без чтения содержимого.""" await _ready(uow, storage) orphan_id = uuid4() orphan = _key(storage, f"{orphan_id}/original") storage.seed(orphan, last_modified=_long_ago()) variant_orphan = _key(storage, f"{uuid4()}/v1-thumbnail") storage.seed(variant_orphan, last_modified=_long_ago()) unknown = _key(storage, "weird-object") storage.seed(unknown, last_modified=_long_ago()) staging_orphan = f"{storage.namespace}/staging/{uuid4()}/original" storage.seed(staging_orphan, last_modified=_long_ago()) staging_unknown = f"{storage.namespace}/staging/weird" storage.seed(staging_unknown, last_modified=_long_ago()) missing = await _ready(uow, storage, with_object=False) size = await _ready(uow, storage, with_object=False) storage.seed(size.object_key, b"other size!", last_modified=_long_ago()) foreign = await _ready( uow, storage, with_object=False, object_key="other-db/attachments/x/original", ) pending = attachment_dto( chat_id=uuid4(), owner_id=uuid4(), created_at=_long_ago(), ) async with uow: await uow.attachments.insert_attachment(attachment=pending) await uow.commit() storage.seed(pending.staging_key, last_modified=_long_ago()) return { "orphan": orphan, "variant_orphan": variant_orphan, "unknown": unknown, "staging_orphan": staging_orphan, "staging_unknown": staging_unknown, "missing": missing, "size": size, "foreign": foreign, "pending": pending, } EXPECTED = { ReconcileFinding.ORPHAN_OBJECT: 2, ReconcileFinding.UNKNOWN_OBJECT: 3, ReconcileFinding.ORPHAN_STAGING: 1, ReconcileFinding.MISSING_OBJECT: 1, ReconcileFinding.SIZE_MISMATCH: 1, ReconcileFinding.STALE_PENDING: 1, } @pytest.mark.parametrize("strategy", STRATEGIES) async def test_dry_run_finds_all_and_changes_nothing( service: AttachmentReconcileService, uow: FakeUnitOfWork, storage: FakeObjectStorage, database: FakeDatabase, strategy: ReconcileStrategy, ) -> None: await _all_classes(uow, storage) rows = database.snapshot()["attachments"] objects = dict(storage.objects) result = await _pass(service, strategy=strategy) assert dict(result.found) == EXPECTED assert result.fixed == {} assert result.remaining == sum(EXPECTED.values()) assert result.interrupted_by is None assert database.attachments == rows assert storage.objects == objects async def test_apply_order_and_effects( service: AttachmentReconcileService, uow: FakeUnitOfWork, storage: FakeObjectStorage, database: FakeDatabase, ) -> None: seeded = await _all_classes(uow, storage) database.events.clear() result = await _pass(service, apply=True) assert result.fixed[ReconcileFinding.ORPHAN_OBJECT] == 2 assert result.fixed[ReconcileFinding.ORPHAN_STAGING] == 1 assert result.fixed[ReconcileFinding.MISSING_OBJECT] == 1 assert result.fixed[ReconcileFinding.SIZE_MISMATCH] == 1 assert result.fixed[ReconcileFinding.STALE_PENDING] == 1 # чужое не исправляется assert ReconcileFinding.UNKNOWN_OBJECT not in result.fixed assert result.remaining == 3 assert seeded["orphan"] not in storage.objects assert seeded["unknown"] in storage.objects assert seeded["staging_unknown"] in storage.objects assert database.attachments[seeded["missing"].id].lost_at is not None assert database.attachments[seeded["size"].id].lost_at is not None assert database.attachments[seeded["foreign"].id].lost_at is None assert seeded["pending"].id not in database.attachments # порядок решения 7: зависшие → объекты → пометки events = database.events removed = events.index("attachments.delete_attachment") first_lost = events.index("attachments.mark_lost") deletes = [ index for index, name in enumerate(events) if name == "storage.delete" ] assert removed < first_lost assert deletes[-1] < first_lost async def test_change_limit_refuses_and_stops_rechecks( service: AttachmentReconcileService, uow: FakeUnitOfWork, storage: FakeObjectStorage, database: FakeDatabase, ) -> None: for _ in range(5): storage.seed( _key(storage, f"{uuid4()}/original"), last_modified=_long_ago(), ) objects = dict(storage.objects) result = await _pass(service, apply=True, max_changes=2) assert result.refused assert result.unchecked == 2 assert storage.objects == objects assert "storage.delete" not in database.events async def test_dry_run_rechecks_everything_over_limit( service: AttachmentReconcileService, storage: FakeObjectStorage, ) -> None: for _ in range(4): storage.seed( _key(storage, f"{uuid4()}/original"), last_modified=_long_ago(), ) result = await _pass(service, apply=False, max_changes=1) assert result.unchecked == 0 assert dict(result.found) == {ReconcileFinding.ORPHAN_OBJECT: 4} async def test_recheck_drops_candidate_that_got_a_row( uow: FakeUnitOfWork, database: FakeDatabase, storage: FakeObjectStorage, ) -> None: """Перед перепроверкой появилась строка: кандидат выбывает.""" attachment_id = uuid4() key = _key(storage, f"{attachment_id}/original") storage.seed(key, last_modified=_long_ago()) service = AttachmentReconcileService(uow, storage) original = service._recheck_all async def recheck_all(state, *, max_changes): row = attachment_dto( chat_id=uuid4(), owner_id=uuid4(), status=AttachmentStatus.READY, created_at=_long_ago(), staging=False, object_key=key, ) database.attachments[attachment_id] = replace(row, id=attachment_id) await original(state, max_changes=max_changes) service._recheck_all = recheck_all result = await _pass(service, apply=True) assert result.found == {} assert key in storage.objects async def test_fresh_object_is_not_a_finding( service: AttachmentReconcileService, storage: FakeObjectStorage, ) -> None: storage.seed( _key(storage, f"{uuid4()}/original"), last_modified=utcnow(), ) result = await _pass(service) assert result.found == {} assert result.fresh_objects == 1 async def test_fresh_row_is_not_a_finding( service: AttachmentReconcileService, uow: FakeUnitOfWork, storage: FakeObjectStorage, ) -> None: await _ready(uow, storage, with_object=False, updated_at=utcnow()) result = await _pass(service) assert result.found == {} assert result.fresh_rows == 1 @pytest.mark.parametrize("strategy", STRATEGIES) async def test_deep_finds_checksum_mismatch( service: AttachmentReconcileService, uow: FakeUnitOfWork, storage: FakeObjectStorage, database: FakeDatabase, strategy: ReconcileStrategy, ) -> None: row = await _ready(uow, storage) storage.seed(row.object_key, b"CONTENT", last_modified=_long_ago()) assert (await _pass(service, strategy=strategy)).found == {} result = await _pass(service, strategy=strategy, deep=True, apply=True) assert result.found == {ReconcileFinding.CHECKSUM_MISMATCH: 1} assert database.attachments[row.id].lost_at is not None assert result.read_bytes > 0 async def test_restored_object_same_sha_clears_mark( service: AttachmentReconcileService, uow: FakeUnitOfWork, storage: FakeObjectStorage, database: FakeDatabase, ) -> None: row = await _ready(uow, storage) async with uow: await uow.attachments.mark_lost( attachment_id=row.id, object_key=row.object_key, lost_at=_long_ago(), ) await uow.commit() result = await _pass(service, apply=True) assert result.fixed == {ReconcileFinding.RESTORED_OBJECT: 1} assert database.attachments[row.id].lost_at is None async def test_restored_object_other_sha_keeps_mark( service: AttachmentReconcileService, uow: FakeUnitOfWork, storage: FakeObjectStorage, database: FakeDatabase, ) -> None: row = await _ready(uow, storage) storage.seed(row.object_key, b"CONTENT", last_modified=_long_ago()) async with uow: await uow.attachments.mark_lost( attachment_id=row.id, object_key=row.object_key, lost_at=_long_ago(), ) await uow.commit() result = await _pass(service, apply=True) assert result.fixed == {} assert result.lost_known == 1 assert database.attachments[row.id].lost_at is not None assert row.sha256 == sha256(b"content").digest() async def test_stop_before_call_and_failures( service: AttachmentReconcileService, uow: FakeUnitOfWork, storage: FakeObjectStorage, database: FakeDatabase, ) -> None: await _ready(uow, storage) result = await _pass(service, stop_requested=lambda: True) assert result.interrupted_by == INTERRUPTED_BY_STOP assert "storage.list" not in database.events database.fail_on["storage.list"] = exceptions.ObjectStorageUnavailable() result = await _pass(service) assert result.interrupted_by == INTERRUPTED_BY_OBJECT_STORAGE database.fail_on.clear() database.fail_on["attachments.get_ready_page"] = ( exceptions.ServiceUnavailable() ) result = await _pass(service) assert result.interrupted_by == INTERRUPTED_BY_DATABASE # отказ после сигнала считается остановкой calls = 0 def stopping() -> bool: nonlocal calls calls += 1 return calls > 3 result = await _pass(service, stop_requested=stopping) assert result.interrupted_by == INTERRUPTED_BY_STOP async def test_interrupted_recheck_changes_nothing( service: AttachmentReconcileService, storage: FakeObjectStorage, database: FakeDatabase, ) -> None: storage.seed( _key(storage, f"{uuid4()}/original"), last_modified=_long_ago(), ) objects = dict(storage.objects) database.fail_on["attachments.find_attachment_reference"] = ( exceptions.ServiceUnavailable() ) result = await _pass(service, apply=True) assert result.interrupted_by == INTERRUPTED_BY_DATABASE assert storage.objects == objects @pytest.mark.parametrize("strategy", STRATEGIES) async def test_db_sessions_equal_blocks_with_cleanup( service: AttachmentReconcileService, uow: FakeUnitOfWork, storage: FakeObjectStorage, database: FakeDatabase, strategy: ReconcileStrategy, ) -> None: """Сценарий «Счёт блоков сверки»: и блоки уборки зависших загрузок.""" await _all_classes(uow, storage) database.events.clear() result = await _pass(service, apply=True, strategy=strategy) assert result.db_sessions == database.events.count("enter") # уборка одной зависшей — два блока сверх остальных assert result.fixed[ReconcileFinding.STALE_PENDING] == 1 locks = database.events.count("attachments.lock_stale_pending") assert locks == 2 async def test_db_sessions_is_per_pass( service: AttachmentReconcileService, storage: FakeObjectStorage, database: FakeDatabase, ) -> None: storage.seed( _key(storage, f"{uuid4()}/original"), last_modified=_long_ago(), ) await _pass(service) database.events.clear() result = await _pass(service) assert result.db_sessions == database.events.count("enter") async def test_cost_counters( service: AttachmentReconcileService, uow: FakeUnitOfWork, storage: FakeObjectStorage, ) -> None: await _ready(uow, storage) result = await _pass(service, strategy=ReconcileStrategy.HEAD) assert result.s3_requests["head"] == 1 assert result.storage_objects == result.listed_objects + 1 assert set(result.phase_ms) == {"list", "rows", "stale", "recheck", "act"} async def test_object_of_other_row_key_compared_by_rows_step( service: AttachmentReconcileService, uow: FakeUnitOfWork, storage: FakeObjectStorage, database: FakeDatabase, ) -> None: """Строка с ключом `/original` другого вложения — HEAD её объекта.""" other = uuid4() key = _key(storage, f"{other}/original") await _ready(uow, storage, with_object=False, object_key=key) storage.seed(key, b"different", last_modified=_long_ago()) database.events.clear() result = await _pass(service) assert result.found.get(ReconcileFinding.SIZE_MISMATCH) == 1 assert "storage.head" in database.events