add metrics
This commit is contained in:
1 parent
fde869fd35
commit
b1d34fc10c
8 files changed
+342
-4
No files matched your search
+54
-4
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from types import TracebackType
|
||||
@@ -16,6 +17,7 @@ from src.embeddings.factory import create_embedding_provider
|
||||
from src.parsers.csv_content import ContentCsvRowParser
|
||||
from src.parsers.csv_stream import CsvStreamReader
|
||||
from src.pipeline.checkpoint import CheckpointStore, S3CheckpointStore
|
||||
from src.pipeline.metrics import PipelineMetrics
|
||||
from src.pipeline.retry import retry_async
|
||||
from src.processors.base import Chunk, Chunker
|
||||
from src.processors.noop import NoOpChunker
|
||||
@@ -185,14 +187,32 @@ class ETLPipeline:
|
||||
batch_chunks: list[Chunk] = []
|
||||
object_count = 0
|
||||
saved_rows = rows_done
|
||||
metrics = PipelineMetrics(
|
||||
key=key,
|
||||
log_interval=self._settings.metrics_log_interval,
|
||||
)
|
||||
|
||||
lines = self._s3_client.stream_file_lines(key)
|
||||
async for parsed in self._csv_reader.iter_objects(lines):
|
||||
objects = self._csv_reader.iter_objects(lines).__aiter__()
|
||||
|
||||
while True:
|
||||
# Отдельно замеряем ожидание/парсинг строки: сюда входит чтение из S3
|
||||
# и разбор CSV, но не чанкинг и не сетевые стадии.
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
parsed = await objects.__anext__()
|
||||
except StopAsyncIteration:
|
||||
break
|
||||
metrics.add("read_parse", time.perf_counter() - started, items=1)
|
||||
|
||||
object_index = object_count
|
||||
object_count += 1
|
||||
|
||||
if object_index < rows_done:
|
||||
# Эта строка уже записана в Qdrant в прошлом запуске
|
||||
metrics.add_skipped_rows()
|
||||
if metrics.due():
|
||||
metrics.log_progress()
|
||||
continue
|
||||
|
||||
metadata = {**base_metadata, **parsed.metadata}
|
||||
@@ -200,21 +220,32 @@ class ETLPipeline:
|
||||
metadata["document_id"] = str(uuid.uuid4())
|
||||
metadata["object_index"] = object_index
|
||||
|
||||
started = time.perf_counter()
|
||||
chunks = await self._chunker.chunk(parsed.text, metadata)
|
||||
metrics.add("chunk", time.perf_counter() - started, items=len(chunks))
|
||||
|
||||
metrics.add_rows(1)
|
||||
metrics.add_chunks(len(chunks))
|
||||
batch_chunks.extend(chunks)
|
||||
|
||||
if len(batch_chunks) >= batch_limit:
|
||||
await self._embed_and_upsert(batch_chunks, key)
|
||||
await self._embed_and_upsert(batch_chunks, key, metrics)
|
||||
batch_chunks.clear()
|
||||
started = time.perf_counter()
|
||||
await self._save_checkpoint(key, object_count)
|
||||
metrics.add("checkpoint", time.perf_counter() - started, items=1)
|
||||
saved_rows = object_count
|
||||
if metrics.due():
|
||||
metrics.log_progress()
|
||||
|
||||
if batch_chunks:
|
||||
await self._embed_and_upsert(batch_chunks, key)
|
||||
await self._embed_and_upsert(batch_chunks, key, metrics)
|
||||
batch_chunks.clear()
|
||||
|
||||
if object_count > saved_rows:
|
||||
started = time.perf_counter()
|
||||
await self._save_checkpoint(key, object_count)
|
||||
metrics.add("checkpoint", time.perf_counter() - started, items=1)
|
||||
|
||||
logger.info(
|
||||
"Файл обработан",
|
||||
@@ -222,6 +253,7 @@ class ETLPipeline:
|
||||
objects=object_count,
|
||||
resumed_from=rows_done,
|
||||
)
|
||||
metrics.log_summary()
|
||||
|
||||
def _point_id(self, key: str, object_index: int, chunk_index: int) -> str:
|
||||
"""Детерминированный ID точки: повторная обработка перезаписывает точку."""
|
||||
@@ -256,12 +288,24 @@ class ETLPipeline:
|
||||
except Exception:
|
||||
logger.exception("Не удалось удалить чекпоинт", key=key)
|
||||
|
||||
async def _embed_and_upsert(self, chunks: list[Chunk], key: str) -> None:
|
||||
async def _embed_and_upsert(
|
||||
self,
|
||||
chunks: list[Chunk],
|
||||
key: str,
|
||||
metrics: PipelineMetrics | None = None,
|
||||
) -> None:
|
||||
"""Векторизация и сохранение списка чанков."""
|
||||
if not chunks:
|
||||
return
|
||||
texts = [chunk.text for chunk in chunks]
|
||||
|
||||
started = time.perf_counter()
|
||||
vectors = await self._embedding_provider.embed(texts)
|
||||
if metrics is not None:
|
||||
metrics.add("embed", time.perf_counter() - started, items=len(texts))
|
||||
|
||||
# Сборка PointStruct — заметная CPU-стадия: pydantic + uuid5 на каждую точку
|
||||
started = time.perf_counter()
|
||||
points = [
|
||||
PointStruct(
|
||||
id=self._point_id(
|
||||
@@ -279,7 +323,13 @@ class ETLPipeline:
|
||||
)
|
||||
for chunk, vector in zip(chunks, vectors, strict=True)
|
||||
]
|
||||
if metrics is not None:
|
||||
metrics.add("build_points", time.perf_counter() - started, items=len(points))
|
||||
|
||||
started = time.perf_counter()
|
||||
await self._repository.upsert(points)
|
||||
if metrics is not None:
|
||||
metrics.add("upsert", time.perf_counter() - started, items=len(points))
|
||||
|
||||
|
||||
async def run_pipeline(settings: Settings) -> None:
|
||||
|
||||
Reference in new issue
Block a user