feat: добавлен сбор метрик: падения запросов к embeded модели; падения запросов к Qdrant, S3; скорости обработки новостей с выделением затраченного времени работы embeded - модели
This commit is contained in:
1 parent
dd0a124e36
commit
a7974404a9
11 files changed
+287
-17
No files matched your search
@@ -249,8 +249,14 @@ scrape-цель — `etl-run:9100`. Поэтому batch-контейнер за
|
|||||||
| `etl_chunks_upserted_total` | Чанки (точки Qdrant), записанные в Qdrant |
|
| `etl_chunks_upserted_total` | Чанки (точки Qdrant), записанные в Qdrant |
|
||||||
| `etl_files_processed_total` | Файлы, обработанные успешно |
|
| `etl_files_processed_total` | Файлы, обработанные успешно |
|
||||||
| `etl_files_failed_total` | Файлы, не обработанные после всех попыток |
|
| `etl_files_failed_total` | Файлы, не обработанные после всех попыток |
|
||||||
|
| `etl_embedding_requests_failed_total` | Упавшие запросы к embedding API (лейбл `error_type`) |
|
||||||
|
| `etl_qdrant_requests_failed_total` | Упавшие запросы к Qdrant (лейблы `operation`, `error_type`) |
|
||||||
|
| `etl_s3_requests_failed_total` | Упавшие запросы к S3 (лейблы `operation`, `error_type`) |
|
||||||
|
| `etl_file_process_duration_seconds` | Гистограмма полного времени обработки файла |
|
||||||
|
| `etl_embedding_request_duration_seconds` | Гистограмма латентности одного запроса к embedding API |
|
||||||
|
|
||||||
Строки за последний час: `increase(etl_rows_processed_total[1h])`.
|
Строки за последний час: `increase(etl_rows_processed_total[1h])`.
|
||||||
|
Скорость обработки (новостей/сек): `rate(etl_rows_processed_total[5m])`.
|
||||||
|
|
||||||
### Чекпоинты
|
### Чекпоинты
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import time
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import structlog
|
import structlog
|
||||||
@@ -12,6 +13,7 @@ from src.embeddings.base import (
|
|||||||
EmbeddingProvider,
|
EmbeddingProvider,
|
||||||
TransientEmbeddingError,
|
TransientEmbeddingError,
|
||||||
)
|
)
|
||||||
|
from src.metrics import EMBEDDING_REQUEST_DURATION, EMBEDDING_REQUESTS_FAILED
|
||||||
|
|
||||||
_RETRYABLE_STATUS = {429, 500, 502, 503, 504}
|
_RETRYABLE_STATUS = {429, 500, 502, 503, 504}
|
||||||
|
|
||||||
@@ -68,13 +70,25 @@ class OpenAIEmbeddingProvider(EmbeddingProvider):
|
|||||||
async def _embed_batch(self, texts: list[str]) -> list[list[float]]:
|
async def _embed_batch(self, texts: list[str]) -> list[list[float]]:
|
||||||
"""Один HTTP-запрос к embedding API (с ограничением конкурентности)."""
|
"""Один HTTP-запрос к embedding API (с ограничением конкурентности)."""
|
||||||
async with self._semaphore:
|
async with self._semaphore:
|
||||||
response = await self._client.post(
|
started = time.perf_counter()
|
||||||
f"{self._api_url}/embeddings",
|
try:
|
||||||
headers={"Authorization": f"Bearer {self._api_key}"},
|
response = await self._client.post(
|
||||||
json={"model": self._model, "input": texts},
|
f"{self._api_url}/embeddings",
|
||||||
)
|
headers={"Authorization": f"Bearer {self._api_key}"},
|
||||||
|
json={"model": self._model, "input": texts},
|
||||||
|
)
|
||||||
|
except httpx.HTTPError as exc:
|
||||||
|
EMBEDDING_REQUESTS_FAILED.labels(
|
||||||
|
error_type=type(exc).__name__
|
||||||
|
).inc()
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
EMBEDDING_REQUEST_DURATION.observe(time.perf_counter() - started)
|
||||||
|
|
||||||
if response.status_code != 200:
|
if response.status_code != 200:
|
||||||
|
EMBEDDING_REQUESTS_FAILED.labels(
|
||||||
|
error_type=f"http_{response.status_code}"
|
||||||
|
).inc()
|
||||||
error_type = (
|
error_type = (
|
||||||
TransientEmbeddingError
|
TransientEmbeddingError
|
||||||
if response.status_code in _RETRYABLE_STATUS
|
if response.status_code in _RETRYABLE_STATUS
|
||||||
|
|||||||
+28
-1
@@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from prometheus_client import Counter, start_http_server
|
from prometheus_client import Counter, Histogram, start_http_server
|
||||||
|
|
||||||
ROWS_PROCESSED = Counter(
|
ROWS_PROCESSED = Counter(
|
||||||
"etl_rows_processed_total",
|
"etl_rows_processed_total",
|
||||||
@@ -28,6 +28,33 @@ FILES_FAILED = Counter(
|
|||||||
"Файлы, не обработанные после всех попыток с момента старта процесса",
|
"Файлы, не обработанные после всех попыток с момента старта процесса",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
EMBEDDING_REQUESTS_FAILED = Counter(
|
||||||
|
"etl_embedding_requests_failed_total",
|
||||||
|
"Запросы к embedding API, завершившиеся ошибкой с момента старта процесса",
|
||||||
|
labelnames=("error_type",),
|
||||||
|
)
|
||||||
|
QDRANT_REQUESTS_FAILED = Counter(
|
||||||
|
"etl_qdrant_requests_failed_total",
|
||||||
|
"Запросы к Qdrant, завершившиеся ошибкой с момента старта процесса",
|
||||||
|
labelnames=("operation", "error_type"),
|
||||||
|
)
|
||||||
|
S3_REQUESTS_FAILED = Counter(
|
||||||
|
"etl_s3_requests_failed_total",
|
||||||
|
"Запросы к S3, завершившиеся ошибкой с момента старта процесса",
|
||||||
|
labelnames=("operation", "error_type"),
|
||||||
|
)
|
||||||
|
|
||||||
|
FILE_PROCESS_DURATION = Histogram(
|
||||||
|
"etl_file_process_duration_seconds",
|
||||||
|
"Полное время обработки одного файла",
|
||||||
|
buckets=(0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0, 300.0, 600.0, 1800.0),
|
||||||
|
)
|
||||||
|
EMBEDDING_REQUEST_DURATION = Histogram(
|
||||||
|
"etl_embedding_request_duration_seconds",
|
||||||
|
"Латентность одного запроса к embedding API",
|
||||||
|
buckets=(0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def start_metrics_server(port: int) -> None:
|
def start_metrics_server(port: int) -> None:
|
||||||
"""Запускает HTTP-сервер с эндпоинтом ``/metrics`` в фоновом потоке.
|
"""Запускает HTTP-сервер с эндпоинтом ``/metrics`` в фоновом потоке.
|
||||||
|
|||||||
+8
-1
@@ -20,7 +20,13 @@ from qdrant_client.models import PointStruct
|
|||||||
from src.config.settings import ChunkingStrategy, PipelineSource, Settings
|
from src.config.settings import ChunkingStrategy, PipelineSource, Settings
|
||||||
from src.embeddings.base import EmbeddingProvider, TransientEmbeddingError
|
from src.embeddings.base import EmbeddingProvider, TransientEmbeddingError
|
||||||
from src.embeddings.factory import create_embedding_provider
|
from src.embeddings.factory import create_embedding_provider
|
||||||
from src.metrics import CHUNKS_UPSERTED, FILES_FAILED, FILES_PROCESSED, ROWS_PROCESSED
|
from src.metrics import (
|
||||||
|
CHUNKS_UPSERTED,
|
||||||
|
FILE_PROCESS_DURATION,
|
||||||
|
FILES_FAILED,
|
||||||
|
FILES_PROCESSED,
|
||||||
|
ROWS_PROCESSED,
|
||||||
|
)
|
||||||
from src.parsers.csv_content import ContentCsvRowParser
|
from src.parsers.csv_content import ContentCsvRowParser
|
||||||
from src.parsers.csv_stream import CsvStreamReader
|
from src.parsers.csv_stream import CsvStreamReader
|
||||||
from src.parsers.documents import (
|
from src.parsers.documents import (
|
||||||
@@ -346,6 +352,7 @@ class ETLPipeline:
|
|||||||
resumed_by_offset=result.resume_by_offset,
|
resumed_by_offset=result.resume_by_offset,
|
||||||
)
|
)
|
||||||
metrics.log_summary()
|
metrics.log_summary()
|
||||||
|
FILE_PROCESS_DURATION.observe(metrics.elapsed)
|
||||||
|
|
||||||
async def _produce_batches(
|
async def _produce_batches(
|
||||||
self,
|
self,
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ from qdrant_client.models import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
from src.config.settings import Settings
|
from src.config.settings import Settings
|
||||||
|
from src.metrics import QDRANT_REQUESTS_FAILED
|
||||||
|
|
||||||
logger = structlog.get_logger(__name__)
|
logger = structlog.get_logger(__name__)
|
||||||
|
|
||||||
@@ -194,12 +195,20 @@ class QdrantRepository:
|
|||||||
await operation()
|
await operation()
|
||||||
return
|
return
|
||||||
except ResourceExhaustedResponse as exc:
|
except ResourceExhaustedResponse as exc:
|
||||||
|
QDRANT_REQUESTS_FAILED.labels(
|
||||||
|
operation=operation_name,
|
||||||
|
error_type="resource_exhausted",
|
||||||
|
).inc()
|
||||||
last_exc = exc
|
last_exc = exc
|
||||||
delay = min(
|
delay = min(
|
||||||
max(float(exc.retry_after_s), 0.0),
|
max(float(exc.retry_after_s), 0.0),
|
||||||
self._settings.retry_max_delay,
|
self._settings.retry_max_delay,
|
||||||
)
|
)
|
||||||
except UnexpectedResponse as exc:
|
except UnexpectedResponse as exc:
|
||||||
|
QDRANT_REQUESTS_FAILED.labels(
|
||||||
|
operation=operation_name,
|
||||||
|
error_type=f"http_{exc.status_code}",
|
||||||
|
).inc()
|
||||||
if exc.status_code not in _RETRYABLE_STATUS:
|
if exc.status_code not in _RETRYABLE_STATUS:
|
||||||
raise
|
raise
|
||||||
last_exc = exc
|
last_exc = exc
|
||||||
@@ -208,6 +217,10 @@ class QdrantRepository:
|
|||||||
self._settings.retry_max_delay,
|
self._settings.retry_max_delay,
|
||||||
)
|
)
|
||||||
except ResponseHandlingException as exc:
|
except ResponseHandlingException as exc:
|
||||||
|
QDRANT_REQUESTS_FAILED.labels(
|
||||||
|
operation=operation_name,
|
||||||
|
error_type=type(exc).__name__,
|
||||||
|
).inc()
|
||||||
last_exc = exc
|
last_exc = exc
|
||||||
delay = min(
|
delay = min(
|
||||||
self._settings.retry_base_delay * (2**attempt),
|
self._settings.retry_base_delay * (2**attempt),
|
||||||
|
|||||||
+20
-7
@@ -16,9 +16,10 @@ import aioboto3
|
|||||||
import structlog
|
import structlog
|
||||||
from aiohttp import ClientError as AiohttpClientError
|
from aiohttp import ClientError as AiohttpClientError
|
||||||
from botocore.config import Config
|
from botocore.config import Config
|
||||||
from botocore.exceptions import ClientError, ResponseStreamingError
|
from botocore.exceptions import BotoCoreError, ClientError, ResponseStreamingError
|
||||||
|
|
||||||
from src.config.settings import Settings
|
from src.config.settings import Settings
|
||||||
|
from src.metrics import S3_REQUESTS_FAILED
|
||||||
|
|
||||||
logger = structlog.get_logger(__name__)
|
logger = structlog.get_logger(__name__)
|
||||||
|
|
||||||
@@ -148,11 +149,17 @@ class S3Client:
|
|||||||
if self._client is None:
|
if self._client is None:
|
||||||
raise RuntimeError("S3-клиент не запущен. Вызовите start() сначала.")
|
raise RuntimeError("S3-клиент не запущен. Вызовите start() сначала.")
|
||||||
|
|
||||||
response = await self._client.get_object(
|
try:
|
||||||
Bucket=self._settings.s3_bucket,
|
response = await self._client.get_object(
|
||||||
Key=key,
|
Bucket=self._settings.s3_bucket,
|
||||||
)
|
Key=key,
|
||||||
data = await response["Body"].read()
|
)
|
||||||
|
data = await response["Body"].read()
|
||||||
|
except (ClientError, BotoCoreError, AiohttpClientError) as exc:
|
||||||
|
S3_REQUESTS_FAILED.labels(
|
||||||
|
operation="read", error_type=type(exc).__name__
|
||||||
|
).inc()
|
||||||
|
raise
|
||||||
return data
|
return data
|
||||||
|
|
||||||
async def put_object(
|
async def put_object(
|
||||||
@@ -287,6 +294,9 @@ class S3Client:
|
|||||||
ResponseStreamingError,
|
ResponseStreamingError,
|
||||||
asyncio.IncompleteReadError,
|
asyncio.IncompleteReadError,
|
||||||
) as exc:
|
) as exc:
|
||||||
|
S3_REQUESTS_FAILED.labels(
|
||||||
|
operation="stream", error_type=type(exc).__name__
|
||||||
|
).inc()
|
||||||
# Соединение с S3 может оборваться на середине объекта.
|
# Соединение с S3 может оборваться на середине объекта.
|
||||||
# Если успели прочитать хотя бы одну строку, переподключаемся
|
# Если успели прочитать хотя бы одну строку, переподключаемся
|
||||||
# с последнего целого смещения и не теряем прогресс.
|
# с последнего целого смещения и не теряем прогресс.
|
||||||
@@ -453,7 +463,10 @@ class S3Client:
|
|||||||
size=size,
|
size=size,
|
||||||
elapsed_s=round(time.perf_counter() - started, 2),
|
elapsed_s=round(time.perf_counter() - started, 2),
|
||||||
)
|
)
|
||||||
except ClientError:
|
except ClientError as exc:
|
||||||
|
S3_REQUESTS_FAILED.labels(
|
||||||
|
operation="move", error_type=type(exc).__name__
|
||||||
|
).inc()
|
||||||
logger.exception("Ошибка перемещения файла", key=key, dest_key=dest_key)
|
logger.exception("Ошибка перемещения файла", key=key, dest_key=dest_key)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,9 @@ from __future__ import annotations
|
|||||||
import asyncio
|
import asyncio
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
from prometheus_client import REGISTRY
|
||||||
|
|
||||||
from src.config.settings import EmbeddingProviderType, Settings
|
from src.config.settings import EmbeddingProviderType, Settings
|
||||||
from src.embeddings.base import (
|
from src.embeddings.base import (
|
||||||
@@ -196,6 +198,74 @@ async def test_openai_embed_limits_concurrency(mock_httpx):
|
|||||||
assert max_active <= 2
|
assert max_active <= 2
|
||||||
|
|
||||||
|
|
||||||
|
async def test_openai_embed_http_error_increments_failed_counter(mock_httpx):
|
||||||
|
"""HTTP-ошибка инкрементит счётчик падений с лейблом error_type=http_500."""
|
||||||
|
mock_httpx.post.return_value = make_mock_response(500, text="Internal Server Error")
|
||||||
|
|
||||||
|
provider = OpenAIEmbeddingProvider(
|
||||||
|
api_url="https://api.openai.com/v1",
|
||||||
|
api_key="key",
|
||||||
|
model="model",
|
||||||
|
)
|
||||||
|
|
||||||
|
before = REGISTRY.get_sample_value(
|
||||||
|
"etl_embedding_requests_failed_total", {"error_type": "http_500"}
|
||||||
|
) or 0.0
|
||||||
|
|
||||||
|
with pytest.raises(EmbeddingAPIError):
|
||||||
|
await provider.embed(["hello"])
|
||||||
|
|
||||||
|
after = REGISTRY.get_sample_value(
|
||||||
|
"etl_embedding_requests_failed_total", {"error_type": "http_500"}
|
||||||
|
)
|
||||||
|
assert after == before + 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_openai_embed_network_error_increments_failed_counter(mock_httpx):
|
||||||
|
"""Сетевая ошибка инкрементит счётчик падений с именем типа исключения."""
|
||||||
|
mock_httpx.post.side_effect = httpx.ConnectError("connection failed")
|
||||||
|
|
||||||
|
provider = OpenAIEmbeddingProvider(
|
||||||
|
api_url="https://api.openai.com/v1",
|
||||||
|
api_key="key",
|
||||||
|
model="model",
|
||||||
|
)
|
||||||
|
|
||||||
|
before = REGISTRY.get_sample_value(
|
||||||
|
"etl_embedding_requests_failed_total", {"error_type": "ConnectError"}
|
||||||
|
) or 0.0
|
||||||
|
|
||||||
|
with pytest.raises(httpx.ConnectError):
|
||||||
|
await provider.embed(["hello"])
|
||||||
|
|
||||||
|
after = REGISTRY.get_sample_value(
|
||||||
|
"etl_embedding_requests_failed_total", {"error_type": "ConnectError"}
|
||||||
|
)
|
||||||
|
assert after == before + 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_openai_embed_observes_latency(mock_httpx):
|
||||||
|
"""Успешный embed увеличивает счётчик наблюдений Histogram латентности."""
|
||||||
|
mock_httpx.post.return_value = make_mock_response(
|
||||||
|
200, {"data": [{"embedding": [0.1], "index": 0}]}
|
||||||
|
)
|
||||||
|
|
||||||
|
provider = OpenAIEmbeddingProvider(
|
||||||
|
api_url="https://api.openai.com/v1",
|
||||||
|
api_key="key",
|
||||||
|
model="model",
|
||||||
|
)
|
||||||
|
|
||||||
|
before = (
|
||||||
|
REGISTRY.get_sample_value("etl_embedding_request_duration_seconds_count") or 0.0
|
||||||
|
)
|
||||||
|
|
||||||
|
await provider.embed(["hello"])
|
||||||
|
|
||||||
|
after = REGISTRY.get_sample_value("etl_embedding_request_duration_seconds_count")
|
||||||
|
assert after == before + 1
|
||||||
|
|
||||||
|
|
||||||
def test_openai_provider_rejects_invalid_batching():
|
def test_openai_provider_rejects_invalid_batching():
|
||||||
with pytest.raises(ValueError, match="batch_size"):
|
with pytest.raises(ValueError, match="batch_size"):
|
||||||
OpenAIEmbeddingProvider(
|
OpenAIEmbeddingProvider(
|
||||||
|
|||||||
@@ -394,6 +394,29 @@ async def test_process_file_single_object(
|
|||||||
assert points[0].payload["object_index"] == 0
|
assert points[0].payload["object_index"] == 0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_process_file_observes_duration_histogram(
|
||||||
|
pipeline, mock_s3_client, mock_csv_reader, mock_chunker, mock_embedding_provider
|
||||||
|
):
|
||||||
|
"""Успешная обработка файла увеличивает Histogram полного времени на 1."""
|
||||||
|
_mock_stream_lines(mock_s3_client, ["text,col", "hello,val"])
|
||||||
|
mock_csv_reader.iter_objects = _make_async_iter(
|
||||||
|
[ParsedObject(text="hello", metadata={"col": "val"})]
|
||||||
|
)
|
||||||
|
|
||||||
|
async def chunk_side_effect(text, metadata):
|
||||||
|
return [Chunk(text=text, index=0, metadata=metadata)]
|
||||||
|
|
||||||
|
mock_chunker.chunk.side_effect = chunk_side_effect
|
||||||
|
mock_embedding_provider.embed.return_value = [[0.1, 0.2, 0.3]]
|
||||||
|
|
||||||
|
before = REGISTRY.get_sample_value("etl_file_process_duration_seconds_count") or 0.0
|
||||||
|
|
||||||
|
await pipeline._process_file("input/data.csv")
|
||||||
|
|
||||||
|
after = REGISTRY.get_sample_value("etl_file_process_duration_seconds_count")
|
||||||
|
assert after == before + 1
|
||||||
|
|
||||||
|
|
||||||
async def test_process_file_adds_title_to_every_chunk_for_non_telegram_news(
|
async def test_process_file_adds_title_to_every_chunk_for_non_telegram_news(
|
||||||
pipeline, mock_s3_client, mock_csv_reader, mock_chunker, mock_embedding_provider, mock_repository
|
pipeline, mock_s3_client, mock_csv_reader, mock_chunker, mock_embedding_provider, mock_repository
|
||||||
):
|
):
|
||||||
|
|||||||
@@ -15,18 +15,27 @@ def test_start_metrics_server_uses_given_port(mocker) -> None:
|
|||||||
|
|
||||||
|
|
||||||
def test_metric_names_exposed_in_registry() -> None:
|
def test_metric_names_exposed_in_registry() -> None:
|
||||||
"""Счётчики зарегистрированы с ожидаемыми именами (с суффиксом _total)."""
|
"""Метрики зарегистрированы с ожидаемыми именами."""
|
||||||
from prometheus_client import REGISTRY
|
from prometheus_client import REGISTRY
|
||||||
|
|
||||||
names = {
|
names = {
|
||||||
sample.name
|
name
|
||||||
for metric in REGISTRY.collect()
|
for metric in REGISTRY.collect()
|
||||||
for sample in metric.samples
|
for name in (
|
||||||
|
metric.name,
|
||||||
|
f"{metric.name}_total",
|
||||||
|
*(sample.name for sample in metric.samples),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
for name in (
|
for name in (
|
||||||
"etl_rows_processed_total",
|
"etl_rows_processed_total",
|
||||||
"etl_chunks_upserted_total",
|
"etl_chunks_upserted_total",
|
||||||
"etl_files_processed_total",
|
"etl_files_processed_total",
|
||||||
"etl_files_failed_total",
|
"etl_files_failed_total",
|
||||||
|
"etl_embedding_requests_failed_total",
|
||||||
|
"etl_qdrant_requests_failed_total",
|
||||||
|
"etl_s3_requests_failed_total",
|
||||||
|
"etl_file_process_duration_seconds",
|
||||||
|
"etl_embedding_request_duration_seconds",
|
||||||
):
|
):
|
||||||
assert name in names
|
assert name in names
|
||||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|||||||
from unittest.mock import AsyncMock, MagicMock
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
from prometheus_client import REGISTRY
|
||||||
from qdrant_client.common.client_exceptions import ResourceExhaustedResponse
|
from qdrant_client.common.client_exceptions import ResourceExhaustedResponse
|
||||||
from qdrant_client.http.exceptions import ResponseHandlingException, UnexpectedResponse
|
from qdrant_client.http.exceptions import ResponseHandlingException, UnexpectedResponse
|
||||||
from qdrant_client.models import Distance, PointStruct
|
from qdrant_client.models import Distance, PointStruct
|
||||||
@@ -300,6 +301,45 @@ async def test_upsert_does_not_retry_http_400(mock_qdrant, settings, mocker):
|
|||||||
assert mock_instance.upsert.await_count == 1
|
assert mock_instance.upsert.await_count == 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_upsert_failure_increments_counter(mock_qdrant, settings, mocker):
|
||||||
|
"""Каждый упавший upsert инкрементит etl_qdrant_requests_failed_total."""
|
||||||
|
_, mock_instance = mock_qdrant
|
||||||
|
mocker.patch("src.qdrant.client.asyncio.sleep", new_callable=AsyncMock)
|
||||||
|
mock_instance.upsert.side_effect = _make_unexpected_response(400)
|
||||||
|
repo = QdrantRepository(settings)
|
||||||
|
await repo.start()
|
||||||
|
|
||||||
|
labels = {"operation": "upsert", "error_type": "http_400"}
|
||||||
|
before = REGISTRY.get_sample_value("etl_qdrant_requests_failed_total", labels) or 0.0
|
||||||
|
|
||||||
|
with pytest.raises(UnexpectedResponse):
|
||||||
|
await repo.upsert([PointStruct(id="p", vector=[0.1], payload={})])
|
||||||
|
|
||||||
|
after = REGISTRY.get_sample_value("etl_qdrant_requests_failed_total", labels)
|
||||||
|
assert after == before + 1
|
||||||
|
|
||||||
|
|
||||||
|
async def test_upsert_counts_each_retry_failure(mock_qdrant, settings, mocker):
|
||||||
|
"""При retry счётчик инкрементится на каждую неудачную попытку."""
|
||||||
|
_, mock_instance = mock_qdrant
|
||||||
|
mocker.patch("src.qdrant.client.asyncio.sleep", new_callable=AsyncMock)
|
||||||
|
mock_instance.upsert.side_effect = [
|
||||||
|
ResponseHandlingException(TimeoutError("timeout")),
|
||||||
|
ResponseHandlingException(TimeoutError("timeout")),
|
||||||
|
None,
|
||||||
|
]
|
||||||
|
repo = QdrantRepository(settings)
|
||||||
|
await repo.start()
|
||||||
|
|
||||||
|
labels = {"operation": "upsert", "error_type": "ResponseHandlingException"}
|
||||||
|
before = REGISTRY.get_sample_value("etl_qdrant_requests_failed_total", labels) or 0.0
|
||||||
|
|
||||||
|
await repo.upsert([PointStruct(id="p", vector=[0.1], payload={})])
|
||||||
|
|
||||||
|
after = REGISTRY.get_sample_value("etl_qdrant_requests_failed_total", labels)
|
||||||
|
assert after == before + 2
|
||||||
|
|
||||||
|
|
||||||
async def test_upsert_honors_retry_after(mock_qdrant, settings, mocker):
|
async def test_upsert_honors_retry_after(mock_qdrant, settings, mocker):
|
||||||
"""429 с Retry-After ждёт указанное сервером время."""
|
"""429 с Retry-After ждёт указанное сервером время."""
|
||||||
_, mock_instance = mock_qdrant
|
_, mock_instance = mock_qdrant
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ from unittest.mock import AsyncMock, MagicMock
|
|||||||
import pytest
|
import pytest
|
||||||
from aiohttp import ClientPayloadError
|
from aiohttp import ClientPayloadError
|
||||||
from botocore.exceptions import ClientError
|
from botocore.exceptions import ClientError
|
||||||
|
from prometheus_client import REGISTRY
|
||||||
|
|
||||||
from src.config.settings import Settings
|
from src.config.settings import Settings
|
||||||
from src.s3.client import S3Client
|
from src.s3.client import S3Client
|
||||||
@@ -201,6 +202,28 @@ async def test_read_file_returns_bytes(mock_s3_client_obj, settings):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_read_file_error_increments_failed_counter(mock_s3_client_obj, settings):
|
||||||
|
"""Ошибка чтения инкрементит etl_s3_requests_failed_total с operation=read."""
|
||||||
|
mock_s3_client_obj.get_object = AsyncMock(
|
||||||
|
side_effect=ClientError(
|
||||||
|
{"Error": {"Code": "NoSuchKey", "Message": "missing"}},
|
||||||
|
"GetObject",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
client = S3Client(settings)
|
||||||
|
await client.start()
|
||||||
|
|
||||||
|
labels = {"operation": "read", "error_type": "ClientError"}
|
||||||
|
before = REGISTRY.get_sample_value("etl_s3_requests_failed_total", labels) or 0.0
|
||||||
|
|
||||||
|
with pytest.raises(ClientError):
|
||||||
|
await client.read_file("input/missing.json")
|
||||||
|
|
||||||
|
after = REGISTRY.get_sample_value("etl_s3_requests_failed_total", labels)
|
||||||
|
assert after == before + 1
|
||||||
|
|
||||||
|
|
||||||
async def test_read_file_raises_when_not_started(settings):
|
async def test_read_file_raises_when_not_started(settings):
|
||||||
client = S3Client(settings)
|
client = S3Client(settings)
|
||||||
|
|
||||||
@@ -756,6 +779,31 @@ async def test_move_file_does_not_delete_on_copy_error(
|
|||||||
mock_s3_client_obj.delete_object.assert_not_awaited()
|
mock_s3_client_obj.delete_object.assert_not_awaited()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_move_file_error_increments_failed_counter(
|
||||||
|
mock_s3_client_obj, settings
|
||||||
|
):
|
||||||
|
"""Ошибка перемещения инкрементит etl_s3_requests_failed_total с operation=move."""
|
||||||
|
mock_s3_client_obj.copy_object = AsyncMock(
|
||||||
|
side_effect=ClientError(
|
||||||
|
{"Error": {"Code": "AccessDenied", "Message": "denied"}},
|
||||||
|
"CopyObject",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
mock_s3_client_obj.delete_object = AsyncMock()
|
||||||
|
|
||||||
|
client = S3Client(settings)
|
||||||
|
await client.start()
|
||||||
|
|
||||||
|
labels = {"operation": "move", "error_type": "ClientError"}
|
||||||
|
before = REGISTRY.get_sample_value("etl_s3_requests_failed_total", labels) or 0.0
|
||||||
|
|
||||||
|
with pytest.raises(ClientError):
|
||||||
|
await client.move_file("input/file.csv")
|
||||||
|
|
||||||
|
after = REGISTRY.get_sample_value("etl_s3_requests_failed_total", labels)
|
||||||
|
assert after == before + 1
|
||||||
|
|
||||||
|
|
||||||
async def test_move_file_raises_when_not_started(settings):
|
async def test_move_file_raises_when_not_started(settings):
|
||||||
client = S3Client(settings)
|
client = S3Client(settings)
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user