diff --git a/src/app/storage/s3_cleanup.py b/src/app/storage/s3_cleanup.py index 61e3c2e4..3d0d4cb8 100644 --- a/src/app/storage/s3_cleanup.py +++ b/src/app/storage/s3_cleanup.py @@ -60,11 +60,21 @@ def _known_keys() -> set[str]: return keys +def _active_attachment_ids() -> set[str]: + """ID вложений в статусах queued/processing — их staging трогать нельзя.""" + with connection() as conn, conn.cursor() as cur: + cur.execute( + "SELECT id FROM attachments WHERE status IN ('queued', 'processing')" + ) + return {str(r[0]) for r in cur.fetchall()} + + def _run_once() -> dict: now = datetime.now(timezone.utc) grace_cutoff = now - timedelta(seconds=_grace()) known = _known_keys() + active_ids = _active_attachment_ids() orphan_deleted = 0 missing = 0 scanned = 0 @@ -93,8 +103,18 @@ def _run_once() -> dict: log.error("event=orphan_delete_failed key=%s type=%s", key, type(exc).__name__) - # staging/ — удаляем только старое (не in-flight). + # staging/ — удаляем только старое И не принадлежащее активной задаче. + # Ключ: staging///original for obj in s3.list_objects("staging/"): + key = obj["Key"] + parts = key.split("/") + # Ожидаем минимум 4 части: staging / chat_id / attachment_id / original + if len(parts) < 4 or parts[0] != "staging": + continue + attachment_id = parts[2] + if attachment_id in active_ids: + # Задача ещё в queued/processing — staging нужен worker'у. + continue lm = obj.get("LastModified") if lm is None: continue @@ -103,7 +123,7 @@ def _run_once() -> dict: if lm > grace_cutoff: continue try: - s3.delete_object(obj["Key"]) + s3.delete_object(key) staging_deleted += 1 except Exception: pass