chore(lint): ruff-гейт в CI + фиксы (0 находок) — блокирует кривой деплой
Второй CI-гейт после тестов: ruff как статический анализатор всего Python-кода (services + scripts). Раньше ни линта, ни проверки типов в CI не было вовсе. Конфиг ruff.toml: правила E/F/W/I/UP/B/SIM/C4, line-length 100. Осознанно выключены E501 (длину держит форматтер; длинные RU-комментарии — норма), B008 (Depends()/Query() в дефолтах — идиома FastAPI, не баг) и UP042 ((str, Enum)→StrEnum меняет __str__/сериализацию — не трогаем). Починено под ноль находок: - B904 (11): raise ... from exc / from None — читаемые цепочки исключений в Celery-ретраях и HTTPException, ошибки обработки не маскируют исходные. - SIM105 (5): try/except/pass → contextlib.suppress (faiss remove_ids, lsh.remove, сброс кэша, ws-disconnect, парс года). - C416/SIM108/B905/F841/UP035/UP017/F401/I001: dict(rows), тернарник, zip strict, мёртвая переменная, устаревшие импорты, timezone.utc→UTC, чистка/сортировка. Обвязка: scripts/run_lint.sh (ruff в изолированном python:3.11-slim), шаг «Линт» в job test перед юнит-тестами (падаем раньше). make lint / make lint-fix. Все 41 юнит-тест по-прежнему зелёные, изменённые файлы компилируются. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
"""Синхронное подключение к PostgreSQL для Celery воркеров."""
|
||||
|
||||
import logging
|
||||
from collections.abc import Generator
|
||||
from contextlib import contextmanager
|
||||
from typing import Generator
|
||||
|
||||
import redis as redis_lib
|
||||
from sqlalchemy import create_engine
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from elasticsearch import Elasticsearch, exceptions as es_exceptions
|
||||
from elasticsearch import Elasticsearch
|
||||
from elasticsearch import exceptions as es_exceptions
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
миллионов документов) полный перебор по FlatIP по скорости приемлем.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -88,7 +89,7 @@ class FAISSManager:
|
||||
distances, ids = cls._index.search(query, min(k, cls._index.ntotal))
|
||||
|
||||
results = []
|
||||
for idx, dist in zip(ids[0], distances[0]):
|
||||
for idx, dist in zip(ids[0], distances[0], strict=False):
|
||||
if idx == -1:
|
||||
continue
|
||||
# Для IDMap2 idx — это уже doc_id из PostgreSQL
|
||||
@@ -120,10 +121,8 @@ class FAISSManager:
|
||||
ids = np.asarray(doc_ids, dtype=np.int64)
|
||||
|
||||
# Удалить существующие id, чтобы повторный эмбеддинг не создавал дубли
|
||||
try:
|
||||
with contextlib.suppress(Exception):
|
||||
cls._index.remove_ids(ids)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
cls._index.add_with_ids(vectors, ids)
|
||||
logger.info(f"Добавлено {len(doc_ids)} векторов в FAISS. Всего: {cls._index.ntotal}")
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
"""Базовые модели данных для GPU воркера (минимальный набор для работы с БД)."""
|
||||
|
||||
from datetime import datetime
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import JSON, BigInteger, ForeignKey, Integer, String, Text, func
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
||||
from sqlalchemy import JSON, ForeignKey, Integer, String, Text, func
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
"""Celery задачи проверки плагиата (уровни 3 и 4) и построения эмбеддингов."""
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from celery.utils.log import get_task_logger
|
||||
@@ -209,7 +208,7 @@ def check_plagiarism(
|
||||
except Exception as db_exc:
|
||||
logger.error(f"Не удалось обновить статус задачи: {db_exc}")
|
||||
|
||||
raise self.retry(exc=exc, countdown=120)
|
||||
raise self.retry(exc=exc, countdown=120) from exc
|
||||
|
||||
|
||||
@celery_app.task(name="gpu.embed_documents")
|
||||
@@ -225,10 +224,9 @@ def embed_documents(doc_ids: list[int]) -> dict[str, Any]:
|
||||
if not doc_ids:
|
||||
return {"status": "ok", "embedded": 0}
|
||||
|
||||
from app.models import Document
|
||||
from app.faiss_manager import FAISSManager
|
||||
from app.model_manager import ModelManager
|
||||
from sqlalchemy import select
|
||||
from app.models import Document
|
||||
|
||||
logger.info(f"Построение эмбеддингов для {len(doc_ids)} документов...")
|
||||
|
||||
@@ -248,7 +246,6 @@ def embed_documents(doc_ids: list[int]) -> dict[str, Any]:
|
||||
]
|
||||
ids = [d.id for d in docs]
|
||||
|
||||
import numpy as np
|
||||
vectors = ModelManager.encode(texts)
|
||||
|
||||
FAISSManager.add_vectors(vectors, ids)
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from celery.utils.log import get_task_logger
|
||||
@@ -278,4 +277,4 @@ def search_semantic(
|
||||
logger.error(f"Не удалось обновить статус задачи: {db_exc}")
|
||||
|
||||
# Повторить попытку
|
||||
raise self.retry(exc=exc, countdown=60)
|
||||
raise self.retry(exc=exc, countdown=60) from exc
|
||||
|
||||
Reference in New Issue
Block a user