diff --git a/.claude/conventions/celery.md b/.claude/conventions/celery.md index 27d787daa..0a7094133 100644 --- a/.claude/conventions/celery.md +++ b/.claude/conventions/celery.md @@ -42,7 +42,7 @@ many chunk tasks fired at once) and the TTS evaluation tasks (`run_tts_batch_sub `run_tts_sync_generation` — one long-running task per Sarvam/ElevenLabs model — and `run_tts_result_processing`, which downloads, converts and uploads a whole Gemini batch) use `queue="evaluations"`. -Everything else uses `queue="default"`. Don't move other eval-adjacent tasks (e.g. `run_evaluation_batch_submission`, +Everything else uses `queue="default"`. Don't move other eval-adjacent tasks (e.g. `run_prompt_improvement`, `send_eval_completion_notification`) onto `evaluations` — they're one-shot/fire-and-forget, no burstiness to isolate. diff --git a/backend/app/api/docs/evaluation/create_evaluation.md b/backend/app/api/docs/evaluation/create_evaluation.md deleted file mode 100644 index 3e9d7b636..000000000 --- a/backend/app/api/docs/evaluation/create_evaluation.md +++ /dev/null @@ -1,57 +0,0 @@ -Start an evaluation run against a stored dataset. - -Two execution modes are supported via the optional `run_mode` field: - -* `batch` (default) — submits the work to the OpenAI Batch API. Cost-efficient - for large datasets; turnaround can take up to 24 hours. -* `fast` — runs the evaluation synchronously through the OpenAI Responses API - and returns results within seconds-to-minutes. Restricted to text - evaluations on datasets with at most `EVAL_FAST_MAX_UNIQUE_ROWS` unique rows. - -**Key Features:** -* Fetches dataset items from Langfuse and creates a job (batch or fast) -* Uses a stored config (created via `/configs`) to define the provider parameters -* Same scoring semantics across both modes — cosine similarity, Langfuse traces, - and optional LLM-as-Judge correctness -* Use `GET /evaluations/{evaluation_id}` to monitor progress and retrieve results; - the response carries `run_mode` so clients can tell the two paths apart - -## Example (batch — default) - -```json -{ - "dataset_id": 123, - "experiment_name": "gpt4_file_search_test", - "config_id": "f54f0d67-4817-4103-9fdf-b74b3d46733e", - "config_version": 1 -} -``` - -## Example (fast) - -```json -{ - "dataset_id": 123, - "experiment_name": "may19-temp0.2-gpt4o-fast", - "config_id": "f54f0d67-4817-4103-9fdf-b74b3d46733e", - "config_version": 1, - "run_mode": "fast" -} -``` - -## Fast-mode error responses - -These apply only when `run_mode` is `fast`. - -| Status | Code | When | -| --- | --- | --- | -| 422 | `config_type_unsupported` | Resolved config is not a text-evaluation config | -| 422 | `dataset_too_large_for_fast` | Dataset exceeds `EVAL_FAST_MAX_UNIQUE_ROWS` unique rows | - -## General error responses - -These apply to both `batch` and `fast` modes. - -| Status | Code | When | -| --- | --- | --- | -| 409 | `run_name_already_exists` | A run with the same `experiment_name` already exists for this (organization, project) | diff --git a/backend/app/api/docs/evaluation/examples.py b/backend/app/api/docs/evaluation/examples.py index f5b9b69e0..3c3fab2fe 100644 --- a/backend/app/api/docs/evaluation/examples.py +++ b/backend/app/api/docs/evaluation/examples.py @@ -1,23 +1,7 @@ -"""Request-body examples for the Evaluation routes (v1 and v2). - - -""" +"""Request-body examples for the v2 Evaluation routes.""" from app.api.openapi_docs import Examples -EVALUATION_CREATE_EXAMPLES: Examples = { - "fast": ( - "Start a fast evaluation run", - { - "dataset_id": 42, - "experiment_name": "faq-bot-gpt-4o-baseline", - "config_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", - "config_version": 1, - "run_mode": "fast", - }, - ), -} - EVALUATION_V2_CREATE_EXAMPLES: Examples = { "judged": ( "Start a judged evaluation run", diff --git a/backend/app/api/docs/evaluation/improve_prompt.md b/backend/app/api/docs/evaluation/improve_prompt.md deleted file mode 100644 index 811e58b86..000000000 --- a/backend/app/api/docs/evaluation/improve_prompt.md +++ /dev/null @@ -1,59 +0,0 @@ -Enqueue an AI prompt-improvement job for the configuration that was evaluated by this run. - -The heavy LLM round-trip runs on a background worker, so this endpoint validates preconditions and returns immediately with `202 Accepted` and a `job_id`. The run must have `status = completed` and a `score_trace_url` pointing to the stored trace file. The worker reads the trace file, asks Claude to identify low-performing answers (by scores and divergence from ground truth) and rewrite the system prompt. Only `completion.params.instructions` is changed; model, knowledge base, and all other settings are preserved. - -On success the new prompt is persisted as the next `config_version` for the evaluated configuration, with AI provenance and the source evaluation run id recorded in the version's `commit_message` (prefixed with `[AI Generated]`). - -**Request body (required):** - -```json -{ "callback_url": "https://your-service.example.com/webhooks/prompt-improvement" } -``` - -- `callback_url` — HTTPS webhook that receives the result. Must be `https://` and must not resolve to a private, loopback, or cloud-metadata address. - -**Callback delivery:** - -Once the worker finishes (success or failure), it POSTs a single JSON body to `callback_url`. Delivery is **best-effort, single-attempt** — there is no retry. The `config_version` is persisted regardless of callback outcome and remains recoverable from the configuration's version list, so a failed callback loses the notification, not the work. - -When a webhook signing secret is configured for the project, the request carries `X-Webhook-Signature` (HMAC-SHA256 of the body) and `X-Webhook-Timestamp` headers; verify them before trusting the payload. - -The body is a standard `APIResponse` envelope whose `data` is a `PromptImprovementJobPublic`: - -```json -{ - "success": true, - "data": { - "job_id": "…", - "status": "SUCCESS", - "config_version": { "…": "…" }, - "error_message": null - }, - "error": null, - "metadata": null -} -``` - -```json -{ - "success": false, - "data": { - "job_id": "…", - "status": "FAILED", - "config_version": null, - "error_message": "…" - }, - "error": "…", - "metadata": null -} -``` - -LLM and trace-download failures surface only via the failure callback, not on the `202` response. - -**Validation errors (returned synchronously before the job is created):** -- `404 evaluation_not_found` — no run with this id in the caller's project. -- `409 evaluation_not_completed` — run is not yet completed. -- `409 source_config_unavailable` — the run's config or config_version has been deleted. -- `422 traces_not_available` — the run has no `score_trace_url`; trace file is required. -- `422 invalid_callback_url` — `callback_url` is missing, not `https://`, or resolves to a blocked (private/loopback/metadata) address. -- `500 prompt_improvement_enqueue_failed` — the job could not be queued. diff --git a/backend/app/api/docs/evaluation/list_datasets.md b/backend/app/api/docs/evaluation/list_datasets.md index 36b7cc1c4..3c2bbd7bd 100644 --- a/backend/app/api/docs/evaluation/list_datasets.md +++ b/backend/app/api/docs/evaluation/list_datasets.md @@ -1,6 +1,8 @@ List all datasets for the current organization and project. -Returns a paginated list of datasets ordered by most recent first. Each dataset includes metadata (ID, name, item counts, duplication factor), Langfuse integration details, object store URL, and an `eligible_for_fast` flag that is `true` when the dataset's unique-row count is within `EVAL_FAST_MAX_UNIQUE_ROWS` (and so can be used with `run_mode="fast"` on `POST /evaluations`). +Returns a paginated list of datasets ordered by most recent first. Each dataset includes metadata (ID, name, item counts, duplication factor), Langfuse integration details, object store URL, and an `eligible_for_fast` flag that is `true` when the dataset's unique-row count is within `EVAL_FAST_MAX_UNIQUE_ROWS` (and so can be used with `POST /api/v2/evaluations`). + +Datasets are uploaded via `POST /api/v2/evaluations/datasets`; legacy Langfuse-backed datasets uploaded through the removed v1 route still appear here. ## Query parameters diff --git a/backend/app/api/docs/evaluation/upload_dataset.md b/backend/app/api/docs/evaluation/upload_dataset.md deleted file mode 100644 index f4dcae356..000000000 --- a/backend/app/api/docs/evaluation/upload_dataset.md +++ /dev/null @@ -1,33 +0,0 @@ -Upload a CSV file containing golden Q&A pairs for evaluation. - -Datasets allow you to store reusable question-answer pairs for systematic LLM testing with automatic validation, duplication for statistical significance, and Langfuse integration. Response includes dataset ID, sanitized name, item counts, Langfuse dataset ID, and object store URL (the cloud storage location where your CSV file is stored). - -**Key Features:** -* Validates CSV format and required columns (question, answer) -* Automatic dataset name sanitization for Langfuse compatibility -* Optional item duplication for statistical significance (1-5x, default: 1x) -* Uploads to object store and syncs with Langfuse -* Skips rows with missing values automatically - - -**CSV Format Requirements:** -* Required columns: `question`, `answer` -* Additional columns are allowed (will be ignored) -* Missing values in required columns are automatically skipped - - -**Dataset Name Sanitization:** - -Your dataset name will be automatically sanitized for Langfuse compatibility: -* Spaces → underscores -* Special characters removed -* Converted to lowercase -* Example: `"My Dataset 01!"` → `"my_dataset_01"` - - -**Duplication Factor:** - -Control how many times each Q&A pair is duplicated (1-5x, default: 1x): -* Higher duplication = better statistical significance -* Useful for batch evaluation reliability -* `1` = no duplication (original dataset only) diff --git a/backend/app/api/docs/evaluation/v2/create_evaluation.md b/backend/app/api/docs/evaluation/v2/create_evaluation.md index 066bcbd1c..61b703b53 100644 --- a/backend/app/api/docs/evaluation/v2/create_evaluation.md +++ b/backend/app/api/docs/evaluation/v2/create_evaluation.md @@ -1,8 +1,7 @@ -Start a v2 evaluation run. Replicates the v1 `POST /api/v1/evaluations` request -body with Kaapi's native LLM-as-Judge built in — v1 is left unchanged. +Start a v2 evaluation run, with Kaapi's native LLM-as-Judge built in. This +replaces the removed v1 `POST /api/v1/evaluations`. -v2 runs are **always fast** and always judged (there is no `run_mode`; batch is -deferred to a later phase). Every scoreable row is automatically judged (no opt-in +v2 runs are **always fast** and always judged (there is no `run_mode`). Every scoreable row is automatically judged (no opt-in flag) by one combined LLM-judge call scoring each applicable metric on an integer 0–5 scale with reasoning: **Adherence to Ground Truth** (answer conveys the same correct information as the golden answer), **Adherence to Prompt** (answer obeys the diff --git a/backend/app/api/docs/evaluation/v2/create_evaluation_dataset.md b/backend/app/api/docs/evaluation/v2/create_evaluation_dataset.md index 6750daeab..6c3b90a51 100644 --- a/backend/app/api/docs/evaluation/v2/create_evaluation_dataset.md +++ b/backend/app/api/docs/evaluation/v2/create_evaluation_dataset.md @@ -1,15 +1,15 @@ Upload a CSV of golden Q&A pairs for evaluation, stored natively by Kaapi with no Langfuse dataset (v2). -Same multipart shape as the v1 dataset upload (`file`, `dataset_name`, -`description`, `duplication_factor`), but the dataset is stored in object storage +Multipart fields: `file`, `dataset_name`, `description`, `duplication_factor`. +The dataset is stored in object storage (S3) only: the row is created with `langfuse_dataset_id` null and the CSV holds exactly the **original** rows — no physical duplication. The `duplication_factor` is recorded in `dataset_metadata` (with a run-time-duplication marker) and applied when the run executes, so an 8-row CSV with factor 5 evaluates 40 rows. -**Response:** `APIResponse[DatasetUploadResponse]`, same shape as v1 with -`langfuse_dataset_id` null. `original_items` is the stored row count and +**Response:** `APIResponse[DatasetUploadResponse]` (the shape returned by +`GET /api/v1/evaluations/datasets`) with `langfuse_dataset_id` null. `original_items` is the stored row count and `total_items` is `original_items × duplication_factor` (the count the run will produce, not stored rows). `eligible_for_fast` reflects only the unique-row size cap (`EVAL_FAST_MAX_UNIQUE_ROWS`). diff --git a/backend/app/api/docs/evaluation/v2/improve_prompt.md b/backend/app/api/docs/evaluation/v2/improve_prompt.md index e75bc3592..81f033787 100644 --- a/backend/app/api/docs/evaluation/v2/improve_prompt.md +++ b/backend/app/api/docs/evaluation/v2/improve_prompt.md @@ -1,7 +1,6 @@ Enqueue a v2 prompt-recommendation job for the configuration evaluated by a judged run. -Unlike v1 (which reads cosine similarity + correctness), this consumes the native -three-metric judge results — **Adherence to Ground Truth**, **Adherence to Prompt**, +This consumes the native three-metric judge results — **Adherence to Ground Truth**, **Adherence to Prompt**, and **Adherence to Knowledge Base** — each carrying an integer 0–5 score and the judge's reasoning. The worker reads both the score and the reasoning per metric, focuses the rewrite on rows where Adherence to Prompt / Ground Truth are low, and changes only @@ -10,7 +9,7 @@ preserved. Low Adherence to Knowledge Base is treated as a retrieval/KB gap rath than a prompt fault. The run must be a **judged v2 run** (`is_judge_run = true`), `status = completed`, -and have a `score_trace_url`. The request body is identical to v1 — `callback_url` +and have a `score_trace_url`. The request body is `callback_url` only. The LLM round-trip runs on a background worker, so this returns `202 Accepted` with a `job_id` immediately. diff --git a/backend/app/api/routes/evaluations/dataset.py b/backend/app/api/routes/evaluations/dataset.py index ec85dae30..86ce2b099 100644 --- a/backend/app/api/routes/evaluations/dataset.py +++ b/backend/app/api/routes/evaluations/dataset.py @@ -1,15 +1,12 @@ -"""Evaluation dataset API routes.""" +"""Evaluation dataset read/delete API routes; uploads live in v2.""" import logging from fastapi import ( APIRouter, Depends, - File, - Form, HTTPException, Query, - UploadFile, ) from app.api.deps import AuthContextDep, SessionDep @@ -17,15 +14,13 @@ from app.core.cloud import get_cloud_storage from app.crud.evaluations import ( get_dataset_by_id, +) +from app.crud.evaluations import ( list_datasets as list_evaluation_datasets, ) from app.crud.evaluations.dataset import delete_dataset as delete_dataset_crud from app.models.evaluation import DatasetUploadResponse, EvaluationDataset -from app.services.evaluations import ( - is_dataset_fast_eligible, - upload_dataset as upload_evaluation_dataset, - validate_csv_file, -) +from app.services.evaluations import is_dataset_fast_eligible from app.utils import ( APIResponse, load_description, @@ -55,45 +50,6 @@ def _dataset_to_response( ) -@router.post( - "", - description=load_description("evaluation/upload_dataset.md"), - response_model=APIResponse[DatasetUploadResponse], - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -async def upload_dataset( - session: SessionDep, - auth_context: AuthContextDep, - file: UploadFile = File( - ..., description="CSV file with 'question' and 'answer' columns" - ), - dataset_name: str = Form(..., description="Name for the dataset"), - description: str | None = Form(None, description="Optional dataset description"), - duplication_factor: int = Form( - default=1, - ge=1, - le=5, - description="Number of times to duplicate each item (min: 1, max: 5)", - ), -) -> APIResponse[DatasetUploadResponse]: - """Upload an evaluation dataset.""" - # Validate and read CSV file - csv_content = await validate_csv_file(file) - - # Upload dataset using service - dataset = upload_evaluation_dataset( - session=session, - csv_content=csv_content, - dataset_name=dataset_name, - description=description, - duplication_factor=duplication_factor, - organization_id=auth_context.organization_.id, - project_id=auth_context.project_.id, - ) - - return APIResponse.success_response(data=_dataset_to_response(dataset)) - - @router.get( "", description=load_description("evaluation/list_datasets.md"), @@ -110,7 +66,7 @@ def list_datasets( eligible_for_fast: bool = Query( default=False, description=( - "When true, return only datasets eligible for run_mode='fast' " + "When true, return only datasets eligible for fast (v2) runs " "(unique-row count within EVAL_FAST_MAX_UNIQUE_ROWS)." ), ), diff --git a/backend/app/api/routes/evaluations/evaluation.py b/backend/app/api/routes/evaluations/evaluation.py index 1326aee0c..2ad001a08 100644 --- a/backend/app/api/routes/evaluations/evaluation.py +++ b/backend/app/api/routes/evaluations/evaluation.py @@ -1,44 +1,24 @@ -"""Evaluation run API routes.""" +"""Evaluation run read API routes; run creation and prompt improvement live in v2.""" import logging from typing import Annotated -from uuid import UUID -from asgi_correlation_id import correlation_id from fastapi import ( APIRouter, - Body, Depends, HTTPException, Query, ) from app.api.deps import AuthContextDep, SessionDep -from app.api.docs.evaluation.examples import ( - EVALUATION_CREATE_EXAMPLES, - EVALUATION_IMPROVE_PROMPT_EXAMPLES, -) -from app.api.openapi_docs import request_examples from app.api.permissions import Permission, require_permission -from app.core.rate_monitor import monitor_rate from app.crud.evaluations import list_evaluation_runs as list_evaluation_runs_crud from app.crud.evaluations.core import group_traces_by_question_id -from app.models.evaluation import ( - EvaluationRunPublic, - ImprovePromptRequest, - RunModeEnum, -) -from app.models.llm.response import LLMJobImmediatePublic -from app.services.evaluations import ( - get_evaluation_with_scores, - start_prompt_improvement_job, - validate_and_start_batch_evaluation, - validate_and_start_fast_evaluation, -) +from app.models.evaluation import EvaluationRunPublic +from app.services.evaluations import get_evaluation_with_scores from app.utils import ( APIResponse, load_description, - validate_callback_url, ) logger = logging.getLogger(__name__) @@ -46,70 +26,6 @@ router = APIRouter(prefix="/evaluations", tags=["Evaluation"]) -@router.post( - "", - description=load_description("evaluation/create_evaluation.md"), - openapi_extra=request_examples(EVALUATION_CREATE_EXAMPLES), - response_model=APIResponse[EvaluationRunPublic], - dependencies=[ - Depends(require_permission(Permission.REQUIRE_PROJECT)), - Depends(monitor_rate("evaluations")), - ], -) -def evaluate( - session: SessionDep, - auth_context: AuthContextDep, - dataset_id: int = Body(..., description="ID of the evaluation dataset"), - experiment_name: str = Body( - ..., description="Name for this evaluation experiment/run" - ), - config_id: UUID = Body(..., description="Stored config ID"), - config_version: int = Body(..., ge=1, description="Stored config version"), - run_mode: RunModeEnum = Body( - default=RunModeEnum.FAST, - description="Execution mode: 'batch' or 'fast'. Omit to default to 'fast'.", - ), -) -> APIResponse[EvaluationRunPublic]: - """Start an evaluation run.""" - logger.info( - f"[evaluate] Starting evaluation | run_mode={run_mode.value} | " - f"experiment_name={experiment_name} | dataset_id={dataset_id} | " - f"org_id={auth_context.organization_.id} | " - f"project_id={auth_context.project_.id}" - ) - - if run_mode == RunModeEnum.FAST: - eval_run = validate_and_start_fast_evaluation( - session=session, - dataset_id=dataset_id, - run_name=experiment_name, - config_id=config_id, - config_version=config_version, - organization_id=auth_context.organization_.id, - project_id=auth_context.project_.id, - trace_id=correlation_id.get() or "N/A", - ) - return APIResponse.success_response(data=eval_run) - - eval_run = validate_and_start_batch_evaluation( - session=session, - dataset_id=dataset_id, - experiment_name=experiment_name, - config_id=config_id, - config_version=config_version, - organization_id=auth_context.organization_.id, - project_id=auth_context.project_.id, - ) - - if eval_run.status == "failed": - return APIResponse.failure_response( - error=eval_run.error_message or "Evaluation failed to start", - data=eval_run, - ) - - return APIResponse.success_response(data=eval_run) - - @router.get( "", description=load_description("evaluation/list_evaluations.md"), @@ -212,49 +128,3 @@ def get_evaluation_run_status( if error: return APIResponse.failure_response(error=error, data=eval_run) return APIResponse.success_response(data=eval_run) - - -@router.post( - "/{evaluation_id}/improve-prompt", - description=load_description("evaluation/improve_prompt.md"), - openapi_extra=request_examples(EVALUATION_IMPROVE_PROMPT_EXAMPLES), - response_model=APIResponse[LLMJobImmediatePublic], - status_code=202, - dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))], -) -def improve_evaluation_prompt( - evaluation_id: int, - session: SessionDep, - auth_context: AuthContextDep, - request: ImprovePromptRequest, -) -> APIResponse[LLMJobImmediatePublic]: - """Enqueue an AI prompt-improvement job for a completed evaluation run.""" - logger.info( - f"[improve_evaluation_prompt] Starting | evaluation_id={evaluation_id} " - f"org_id={auth_context.organization_.id} project_id={auth_context.project_.id}" - ) - - # No global ValueError handler exists, so map the SSRF guard's ValueError to - # a 422 here rather than letting it surface as a 500. - try: - validate_callback_url(str(request.callback_url)) - except ValueError as exc: - raise HTTPException(status_code=422, detail=f"invalid_callback_url: {exc}") - - job = start_prompt_improvement_job( - session=session, - evaluation_id=evaluation_id, - organization_id=auth_context.organization_.id, - project_id=auth_context.project_.id, - callback_url=str(request.callback_url), - ) - - return APIResponse.success_response( - data=LLMJobImmediatePublic( - job_id=job.id, - status=job.status.value, - message="Prompt improvement is running; the result will be delivered to your callback_url.", - job_inserted_at=job.inserted_at, - job_updated_at=job.updated_at, - ) - ) diff --git a/backend/app/api/routes/evaluations/v2/dataset.py b/backend/app/api/routes/evaluations/v2/dataset.py index 4d2f4de8c..8e73328c0 100644 --- a/backend/app/api/routes/evaluations/v2/dataset.py +++ b/backend/app/api/routes/evaluations/v2/dataset.py @@ -56,7 +56,6 @@ async def upload_dataset_v2_route( duplication_factor=duplication_factor, organization_id=auth_context.organization_.id, project_id=auth_context.project_.id, - use_langfuse=False, ) return APIResponse.success_response(data=_dataset_to_response(dataset)) diff --git a/backend/app/api/routes/evaluations/v2/evaluation.py b/backend/app/api/routes/evaluations/v2/evaluation.py index 0b30a814a..a7ace1671 100644 --- a/backend/app/api/routes/evaluations/v2/evaluation.py +++ b/backend/app/api/routes/evaluations/v2/evaluation.py @@ -1,4 +1,4 @@ -"""v2 evaluation run trigger — replica of the v1 trigger plus native judging.""" +"""v2 evaluation run trigger: fast, natively judged runs (the v1 trigger was removed).""" import logging from uuid import UUID diff --git a/backend/app/api/routes/evaluations/v2/prompt_improvement.py b/backend/app/api/routes/evaluations/v2/prompt_improvement.py index baea25228..b8e569140 100644 --- a/backend/app/api/routes/evaluations/v2/prompt_improvement.py +++ b/backend/app/api/routes/evaluations/v2/prompt_improvement.py @@ -1,7 +1,7 @@ -"""v2 prompt-improvement trigger — consumes three-metric judge results. +"""Prompt-improvement trigger — consumes three-metric judge results. -Mirrors the v1 improve-prompt route but requires a judged (v2) run and returns a -typed prompt recommendation. The v1 route is left unchanged. +Requires a judged (v2) run and returns a typed prompt recommendation; the v1 +improve-prompt route was removed. """ import logging diff --git a/backend/app/celery/tasks/job_execution.py b/backend/app/celery/tasks/job_execution.py index 4e38ceb84..8c87ea382 100644 --- a/backend/app/celery/tasks/job_execution.py +++ b/backend/app/celery/tasks/job_execution.py @@ -162,23 +162,6 @@ def run_delete_collection_job( ) -@celery_app.task(bind=True, queue="default", priority=2) -@gevent_timeout(settings.CELERY_TASK_SOFT_TIME_LIMIT, "run_evaluation_batch_submission") -def run_evaluation_batch_submission( - self, project_id: int, job_id: str, trace_id: str, **kwargs -): - from app.services.evaluations.batch_job import execute_evaluation_batch_submission - - _set_trace(trace_id) - return execute_evaluation_batch_submission( - project_id=project_id, - job_id=job_id, - task_id=current_task.request.id, - task_instance=self, - **kwargs, - ) - - # Priority 6: user-blocking interactive prompt iteration in the # evaluation domain, above default batch work but below core LLM call/chain jobs. @celery_app.task(bind=True, queue="default", priority=6) diff --git a/backend/app/celery/utils.py b/backend/app/celery/utils.py index 9239d87c3..d92399ab1 100644 --- a/backend/app/celery/utils.py +++ b/backend/app/celery/utils.py @@ -148,25 +148,6 @@ def start_delete_collection_job( return task_id -def start_evaluation_batch_submission( - project_id: int, job_id: str, trace_id: str = "N/A", **kwargs -) -> str: - from app.celery.tasks.job_execution import run_evaluation_batch_submission - - task_id = run_evaluation_batch_submission.apply_async( - kwargs={ - "project_id": project_id, - "job_id": job_id, - "trace_id": trace_id, - **kwargs, - } - ).id - logger.info( - f"[start_evaluation_batch_submission] Started job {job_id} with Celery task {task_id}" - ) - return task_id - - def start_prompt_improvement( project_id: int, job_id: str, trace_id: str = "N/A", **kwargs ) -> str: diff --git a/backend/app/crud/evaluations/__init__.py b/backend/app/crud/evaluations/__init__.py index 6aa187e0c..8f52fcde7 100644 --- a/backend/app/crud/evaluations/__init__.py +++ b/backend/app/crud/evaluations/__init__.py @@ -1,6 +1,5 @@ """Evaluation-related CRUD operations.""" -from app.crud.evaluations.batch import start_evaluation_batch from app.crud.evaluations.core import ( create_evaluation_run, get_evaluation_run_by_id, @@ -20,11 +19,7 @@ list_datasets, upload_csv_to_object_store, ) -from app.crud.evaluations.embeddings import ( - calculate_average_similarity, - calculate_cosine_similarity, - start_embedding_batch, -) +from app.crud.evaluations.embeddings import calculate_cosine_similarity from app.crud.evaluations.fast import run_fast_evaluation, run_response_chunk from app.crud.evaluations.fast_chunks import ( JOB_TYPE_EMBEDDING_FAST, @@ -40,20 +35,14 @@ ) from app.crud.evaluations.langfuse import ( create_langfuse_dataset_run, + fetch_dataset_items, fetch_trace_scores_from_langfuse, update_traces_with_cosine_scores, - upload_dataset_to_langfuse, ) from app.crud.evaluations.merge import ( merge_scores_step_forward, sort_traces_by_question_id, ) -from app.crud.evaluations.processing import ( - check_and_process_evaluation, - poll_all_pending_evaluations, - process_completed_embedding_batch, - process_completed_evaluation, -) from app.crud.evaluations.score import ( CategoricalSummaryScore, EvaluationScore, @@ -79,8 +68,6 @@ "get_dataset_by_id", "list_datasets", "upload_csv_to_object_store", - # Batch - "start_evaluation_batch", # Fast eval "JOB_TYPE_EMBEDDING_FAST", "JOB_TYPE_EVALUATION_FAST", @@ -93,20 +80,13 @@ "get_evaluation_iteration_run_by_id", "list_processing_evaluation_iteration_runs", "update_evaluation_iteration_run", - # Processing - "check_and_process_evaluation", - "poll_all_pending_evaluations", - "process_completed_embedding_batch", - "process_completed_evaluation", # Embeddings - "calculate_average_similarity", "calculate_cosine_similarity", - "start_embedding_batch", # Langfuse "create_langfuse_dataset_run", + "fetch_dataset_items", "fetch_trace_scores_from_langfuse", "update_traces_with_cosine_scores", - "upload_dataset_to_langfuse", # Merge (step-forward resync) "merge_scores_step_forward", "sort_traces_by_question_id", diff --git a/backend/app/crud/evaluations/batch.py b/backend/app/crud/evaluations/batch.py deleted file mode 100644 index 7b8892644..000000000 --- a/backend/app/crud/evaluations/batch.py +++ /dev/null @@ -1,303 +0,0 @@ -""" -Evaluation-specific batch preparation and orchestration. - -This module handles: -1. Fetching dataset items from Langfuse -2. Building evaluation-specific JSONL for batch processing -3. Starting evaluation batches using generic batch infrastructure -""" - -import logging -from typing import Any - -from langfuse import Langfuse -from sqlmodel import Session - -from app.core.batch import ( - BATCH_KEY, - GeminiBatchProvider, - OpenAIBatchProvider, - start_batch_job, -) -from app.core.batch.client import GeminiClient -from app.models import EvaluationRun -from app.models.batch_job import BatchJobType -from app.services.llm.mappers import ( - map_kaapi_to_google_params, - map_kaapi_to_openai_params, -) -from app.services.llm.providers.registry import LLMProvider -from app.utils import get_openai_client - -logger = logging.getLogger(__name__) - - -def fetch_dataset_items(langfuse: Langfuse, dataset_name: str) -> list[dict[str, Any]]: - """ - Fetch all items from a Langfuse dataset. - - Args: - langfuse: Configured Langfuse client - dataset_name: Name of the dataset to fetch - - Returns: - List of dataset items with input and expected_output - - Raises: - ValueError: If dataset not found or empty - """ - try: - dataset = langfuse.get_dataset(dataset_name) - except Exception as e: - logger.warning( - f"[fetch_dataset_items] Failed to fetch dataset | dataset={dataset_name} | {e}" - ) - raise ValueError(f"Dataset '{dataset_name}' not found: {e}") - - if not dataset.items: - raise ValueError(f"Dataset '{dataset_name}' is empty") - - items = [] - for item in dataset.items: - items.append( - { - "id": item.id, - "input": item.input, - "expected_output": item.expected_output, - "metadata": item.metadata if hasattr(item, "metadata") else {}, - } - ) - return items - - -def build_openai_evaluation_jsonl( - dataset_items: list[dict[str, Any]], openai_params: dict[str, Any] -) -> list[dict[str, Any]]: - """Build OpenAI Responses API batch JSONL from Langfuse dataset items. - - Each line: - { - BATCH_KEY: , - "method": "POST", - "url": "/v1/responses", - "body": { ...openai_params, "input": } - } - """ - jsonl_data: list[dict[str, Any]] = [] - for item in dataset_items: - question = item["input"].get("question", "") - if not question: - logger.warning( - f"[build_openai_evaluation_jsonl] Skipping item - no question found | item_id={item['id']}" - ) - continue - - body = dict(openai_params) - body["input"] = question - - jsonl_data.append( - { - BATCH_KEY: item["id"], - "method": "POST", - "url": "/v1/responses", - "body": body, - } - ) - return jsonl_data - - -def build_google_evaluation_jsonl( - dataset_items: list[dict[str, Any]], google_params: dict[str, Any] -) -> list[dict[str, Any]]: - """Build Gemini batch JSONL from Langfuse dataset items. - - Each line: - { - "key": , - "request": { contents, systemInstruction?, generationConfig?, tools? } - } - """ - jsonl_data: list[dict[str, Any]] = [] - system_instruction = google_params.get("instructions") - - generation_config: dict[str, Any] = {} - temperature = google_params.get("temperature") - if temperature is not None: - generation_config["temperature"] = temperature - reasoning = google_params.get("reasoning") - if reasoning: - generation_config["thinkingConfig"] = { - "includeThoughts": False, - "thinkingLevel": reasoning, - } - - tools: list[dict[str, Any]] = [] - knowledge_base_ids = google_params.get("knowledge_base_ids") - if knowledge_base_ids: - tools.append({"fileSearch": {"fileSearchStoreNames": knowledge_base_ids}}) - - for item in dataset_items: - question = item["input"].get("question", "") - if not question: - logger.warning( - f"[build_google_evaluation_jsonl] Skipping item - no question found | item_id={item['id']}" - ) - continue - - request: dict[str, Any] = { - "contents": [{"parts": [{"text": question}], "role": "user"}], - } - if system_instruction: - request["systemInstruction"] = {"parts": [{"text": system_instruction}]} - if generation_config: - request["generationConfig"] = generation_config - if tools: - request["tools"] = tools - - jsonl_data.append({"key": item["id"], "request": request}) - - return jsonl_data - - -def start_evaluation_batch( - langfuse: Langfuse, - session: Session, - eval_run: EvaluationRun, - params: dict[str, Any], - provider: str, -) -> EvaluationRun: - """ - Fetch dataset, build JSONL, submit batch via the appropriate provider. - - Args: - langfuse: Configured Langfuse client - session: Database session - eval_run: EvaluationRun database object - params: Kaapi-standardized completion params (dict) - provider: Completion provider ("openai" or "google-aistudio", with optional "-native" suffix) - - Returns: - Updated EvaluationRun with batch_job_id populated - """ - try: - logger.info( - f"[start_evaluation_batch] Starting evaluation batch | run={eval_run.run_name} | provider={provider}" - ) - dataset_items = fetch_dataset_items( - langfuse=langfuse, dataset_name=eval_run.dataset_name - ) - - base_provider = provider.replace("-native", "") - - if base_provider == LLMProvider.OPENAI: - mapped_params, warnings = map_kaapi_to_openai_params( - session=session, kaapi_params=params - ) - if warnings: - logger.info("[start_evaluation_batch] Mapper warnings: %s", warnings) - - jsonl_data = build_openai_evaluation_jsonl( - dataset_items=dataset_items, openai_params=mapped_params - ) - if not jsonl_data: - raise ValueError( - "Evaluation dataset did not produce any JSONL entries (missing questions?)." - ) - - openai_client = get_openai_client( - session=session, - org_id=eval_run.organization_id, - project_id=eval_run.project_id, - ) - batch_provider = OpenAIBatchProvider(client=openai_client) - - batch_config = { - "endpoint": "/v1/responses", - "description": f"Evaluation: {eval_run.run_name}", - "completion_window": "24h", - "evaluation_config": params, - } - - batch_job = start_batch_job( - session=session, - provider=batch_provider, - provider_name="openai", - job_type=BatchJobType.EVALUATION, - organization_id=eval_run.organization_id, - project_id=eval_run.project_id, - jsonl_data=jsonl_data, - config=batch_config, - ) - - elif base_provider == LLMProvider.GOOGLE_AISTUDIO: - mapped_params, warnings = map_kaapi_to_google_params( - kaapi_params=params, completion_type="text" - ) - if warnings: - logger.info("[start_evaluation_batch] Mapper warnings: %s", warnings) - - jsonl_data = build_google_evaluation_jsonl( - dataset_items=dataset_items, google_params=mapped_params - ) - if not jsonl_data: - raise ValueError( - "Evaluation dataset did not produce any JSONL entries (missing questions?)." - ) - - gemini_client = GeminiClient.from_credentials( - session=session, - org_id=eval_run.organization_id, - project_id=eval_run.project_id, - ) - model_name = mapped_params.get("model", "gemini-2.5-pro") - batch_provider = GeminiBatchProvider( - client=gemini_client.client, model=model_name - ) - - batch_config = { - "display_name": f"evaluation-{eval_run.run_name}", - "model": f"models/{model_name}", - } - - batch_job = start_batch_job( - session=session, - provider=batch_provider, - provider_name="google-aistudio", - job_type=BatchJobType.EVALUATION, - organization_id=eval_run.organization_id, - project_id=eval_run.project_id, - jsonl_data=jsonl_data, - config=batch_config, - ) - - else: - raise ValueError(f"Unsupported provider for evaluation batches: {provider}") - - eval_run.batch_job_id = batch_job.id - eval_run.status = "processing" - eval_run.total_items = batch_job.total_items - - session.add(eval_run) - session.commit() - session.refresh(eval_run) - - logger.info( - f"[start_evaluation_batch] Successfully started evaluation batch | " - f"batch_job_id={batch_job.id} | " - f"provider_batch_id={batch_job.provider_batch_id} | " - f"run={eval_run.run_name} | items={batch_job.total_items} | " - f"provider={base_provider}" - ) - - return eval_run - - except Exception as e: - logger.error( - f"[start_evaluation_batch] Failed to start evaluation batch | {e}", - exc_info=True, - ) - eval_run.status = "failed" - eval_run.error_message = str(e) - session.add(eval_run) - session.commit() - raise diff --git a/backend/app/crud/evaluations/cron.py b/backend/app/crud/evaluations/cron.py index 293056f37..f50ecbd1d 100644 --- a/backend/app/crud/evaluations/cron.py +++ b/backend/app/crud/evaluations/cron.py @@ -1,4 +1,4 @@ -"""Periodic evaluation maintenance: polling, fast-eval barriers, iteration resumes.""" +"""Periodic evaluation maintenance: STT/TTS polling, fast-eval barriers, iteration resumes.""" import asyncio import logging @@ -19,7 +19,6 @@ list_processing_evaluation_iteration_runs, update_evaluation_iteration_run, ) -from app.crud.evaluations.processing import poll_all_pending_evaluations from app.models import EvaluationRun, EvaluationRunUpdate from app.models.evaluation import RunModeEnum from app.models.evaluation_iteration import EvaluationIterationRunUpdate @@ -158,10 +157,8 @@ def dispatch_pending_evaluation_iteration_resumes(session: Session) -> dict[str, async def process_all_pending_evaluations(session: Session) -> dict[str, Any]: - """Poll text/STT/TTS evaluations, then run the fast-eval barrier and iteration resumes.""" + """Poll STT/TTS evaluations, then run the fast-eval barrier and iteration resumes.""" try: - text_summary = await poll_all_pending_evaluations(session=session) - from app.crud.stt_evaluations import poll_all_pending_stt_evaluations from app.crud.tts_evaluations import poll_all_pending_tts_evaluations @@ -172,24 +169,12 @@ async def process_all_pending_evaluations(session: Session) -> dict[str, Any]: session=session ) - total_processed = ( - text_summary["processed"] - + stt_summary["processed"] - + tts_summary["processed"] - ) - total_failed = ( - text_summary["failed"] + stt_summary["failed"] + tts_summary["failed"] - ) + total_processed = stt_summary["processed"] + tts_summary["processed"] + total_failed = stt_summary["failed"] + tts_summary["failed"] total_still_processing = ( - text_summary["still_processing"] - + stt_summary["still_processing"] - + tts_summary["still_processing"] - ) - all_details = ( - text_summary.get("details", []) - + stt_summary.get("details", []) - + tts_summary.get("details", []) + stt_summary["still_processing"] + tts_summary["still_processing"] ) + all_details = stt_summary.get("details", []) + tts_summary.get("details", []) return { "status": "success", diff --git a/backend/app/crud/evaluations/embeddings.py b/backend/app/crud/evaluations/embeddings.py index 5d1458271..df086706f 100644 --- a/backend/app/crud/evaluations/embeddings.py +++ b/backend/app/crud/evaluations/embeddings.py @@ -1,245 +1,9 @@ -""" -Embedding-based similarity scoring for evaluation runs. - -This module handles: -1. Building JSONL for embedding batch requests -2. Parsing embedding results from batch API -3. Calculating cosine similarity between embeddings -4. Orchestrating embedding batch creation and processing -""" - -import logging -from typing import Any +"""Embedding constants and cosine similarity for fast (non-judged) evaluation runs.""" import numpy as np -from openai import OpenAI -from sqlmodel import Session - -from app.core.batch import OpenAIBatchProvider, start_batch_job -from app.core.batch.base import BATCH_KEY -from app.core.util import now -from app.models import EvaluationRun -from app.models.batch_job import BatchJobType -logger = logging.getLogger(__name__) - -# Default embedding model EMBEDDING_MODEL = "text-embedding-3-large" -# Valid embedding models with their dimensions -VALID_EMBEDDING_MODELS = { - "text-embedding-3-small": 1536, - "text-embedding-3-large": 3072, - "text-embedding-ada-002": 1536, -} - - -def validate_embedding_model(model: str) -> None: - """ - Validate that the embedding model is supported. - - Args: - model: The embedding model name - - Raises: - ValueError: If the model is not supported - """ - if model not in VALID_EMBEDDING_MODELS: - valid_models = ", ".join(VALID_EMBEDDING_MODELS.keys()) - raise ValueError( - f"Invalid embedding model '{model}'. Supported models: {valid_models}" - ) - - -def build_embedding_jsonl( - results: list[dict[str, Any]], - trace_id_mapping: dict[str, str], - embedding_model: str = EMBEDDING_MODEL, -) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: - """ - Build JSONL data for embedding batch using OpenAI Embeddings API. - - Each line is a dict with: - - BATCH_KEY: Langfuse trace_id (for direct score updates) - - method: POST - - url: /v1/embeddings - - body: Embedding request with input array [output, ground_truth] - - Args: - results: List of evaluation results from parse_evaluation_output() - Format: [ - { - "item_id": "item_123", - "question": "What is 2+2?", - "generated_output": "The answer is 4", - "ground_truth": "4" - }, - ... - ] - trace_id_mapping: Mapping of item_id to Langfuse trace_id - embedding_model: OpenAI embedding model to use (default: text-embedding-3-large) - - Returns: - Tuple of (jsonl_data, skipped) where: - - jsonl_data is the list of embedding batch requests - - skipped is a list of {item_id, trace_id, reason} for items that - cannot be embedded (reason: empty_output / empty_ground_truth / - missing_trace_id). Used to flag unscoreable items downstream. - """ - # Validate embedding model - validate_embedding_model(embedding_model) - - logger.info( - f"[build_embedding_jsonl] Building JSONL | items={len(results)} | model={embedding_model}" - ) - - jsonl_data: list[dict[str, Any]] = [] - skipped: list[dict[str, Any]] = [] - - for result in results: - item_id = result.get("item_id") - generated_output = result.get("generated_output", "") - ground_truth = result.get("ground_truth", "") - - if not item_id: - logger.warning("Skipping result with no item_id") - continue - - # Get trace_id from mapping - trace_id = trace_id_mapping.get(item_id) - if not trace_id: - logger.warning(f"Skipping item {item_id} - no trace_id found") - skipped.append( - {"item_id": item_id, "trace_id": None, "reason": "missing_trace_id"} - ) - continue - - # Empty output/ground_truth can't be embedded; record the reason. - if not generated_output or not ground_truth: - reason = "empty_output" if not generated_output else "empty_ground_truth" - logger.warning(f"Skipping item {item_id} - {reason}") - skipped.append({"item_id": item_id, "trace_id": trace_id, "reason": reason}) - continue - - # Build the batch request object for Embeddings API - # Use trace_id as BATCH_KEY for direct score updates - batch_request = { - BATCH_KEY: trace_id, - "method": "POST", - "url": "/v1/embeddings", - "body": { - "model": embedding_model, - "input": [ - generated_output, # Index 0 - ground_truth, # Index 1 - ], - "encoding_format": "float", - }, - } - - jsonl_data.append(batch_request) - - logger.info( - f"Built {len(jsonl_data)} embedding JSONL lines | skipped={len(skipped)}" - ) - return jsonl_data, skipped - - -def parse_embedding_results( - raw_results: list[dict[str, Any]], -) -> tuple[list[dict[str, Any]], list[str]]: - """ - Parse embedding batch output into structured embedding pairs. - - Args: - raw_results: Raw results from batch provider (list of JSONL lines) - - Returns: - Tuple of (embedding_pairs, failed_trace_ids): - - embedding_pairs: [{trace_id, output_embedding, ground_truth_embedding}] - - failed_trace_ids: trace_ids whose embedding could not be parsed (flagged - embedding_failed downstream). Lines with no trace_id are dropped silently. - """ - logger.info(f"Parsing embedding results from {len(raw_results)} lines") - - embedding_pairs = [] - failed_trace_ids: list[str] = [] - - for line_num, response in enumerate(raw_results, 1): - trace_id = None - try: - # Extract BATCH_KEY (which is now the Langfuse trace_id) - trace_id = response.get(BATCH_KEY) - if not trace_id: - logger.warning(f"Line {line_num}: No {BATCH_KEY} found, skipping") - continue - - # Handle errors in batch processing - if response.get("error"): - error_msg = response["error"].get("message", "Unknown error") - logger.warning( - f"[parse_embedding_batch_results] Trace {trace_id} had error: {error_msg}" - ) - failed_trace_ids.append(trace_id) - continue - - # Extract the response body - response_body = response.get("response", {}).get("body", {}) - embedding_data = response_body.get("data", []) - - if len(embedding_data) < 2: - logger.warning( - f"Trace {trace_id}: Expected 2 embeddings, got {len(embedding_data)}" - ) - failed_trace_ids.append(trace_id) - continue - - # Extract embeddings by index - # Index 0 = generated_output embedding - # Index 1 = ground_truth embedding - output_embedding = None - ground_truth_embedding = None - - for emb_obj in embedding_data: - index = emb_obj.get("index") - embedding = emb_obj.get("embedding") - - if embedding is None: - continue - - if index == 0: - output_embedding = embedding - elif index == 1: - ground_truth_embedding = embedding - - if output_embedding is None or ground_truth_embedding is None: - logger.warning( - f"Trace {trace_id}: Missing embeddings (output={output_embedding is not None}, " - f"ground_truth={ground_truth_embedding is not None})" - ) - failed_trace_ids.append(trace_id) - continue - - embedding_pairs.append( - { - "trace_id": trace_id, - "output_embedding": output_embedding, - "ground_truth_embedding": ground_truth_embedding, - } - ) - - except Exception as e: - logger.error(f"Line {line_num}: Unexpected error: {e}", exc_info=True) - if trace_id: - failed_trace_ids.append(trace_id) - continue - - logger.info( - f"Parsed {len(embedding_pairs)} embedding pairs from {len(raw_results)} lines " - f"| failed={len(failed_trace_ids)}" - ) - return embedding_pairs, failed_trace_ids - def calculate_cosine_similarity(vec1: list[float], vec2: list[float]) -> float: """ @@ -273,181 +37,3 @@ def calculate_cosine_similarity(vec1: list[float], vec2: list[float]) -> float: similarity = dot_product / (norm_v1 * norm_v2) return float(similarity) - - -def calculate_average_similarity( - embedding_pairs: list[dict[str, Any]], -) -> dict[str, Any]: - """ - Calculate cosine similarity statistics for all embedding pairs. - - Args: - embedding_pairs: List of embedding pairs from parse_embedding_results() - - Returns: - Dictionary with similarity statistics: - { - "cosine_similarity_avg": 0.87, - "cosine_similarity_std": 0.12, - "total_pairs": 50, - "per_item_scores": [...] # Individual scores with trace_ids - } - """ - logger.info(f"Calculating similarity for {len(embedding_pairs)} pairs") - - if not embedding_pairs: - return { - "cosine_similarity_avg": 0.0, - "cosine_similarity_std": 0.0, - "total_pairs": 0, - "per_item_scores": [], - } - - similarities = [] - per_item_scores = [] - - for pair in embedding_pairs: - try: - output_emb = pair["output_embedding"] - ground_truth_emb = pair["ground_truth_embedding"] - - similarity = calculate_cosine_similarity(output_emb, ground_truth_emb) - similarities.append(similarity) - - per_item_scores.append( - { - "trace_id": pair["trace_id"], - "cosine_similarity": similarity, - } - ) - - except Exception as e: - logger.error( - f"Error calculating similarity for trace {pair.get('trace_id')}: {e}" - ) - continue - - if not similarities: - logger.warning("No valid similarities calculated") - return { - "cosine_similarity_avg": 0.0, - "cosine_similarity_std": 0.0, - "total_pairs": 0, - "per_item_scores": [], - } - - # Calculate statistics - similarities_array = np.array(similarities) - - stats = { - "cosine_similarity_avg": float(np.mean(similarities_array)), - "cosine_similarity_std": float(np.std(similarities_array)), - "total_pairs": len(similarities), - "per_item_scores": per_item_scores, - } - - logger.info( - f"Calculated similarity stats: avg={stats['cosine_similarity_avg']:.3f}, " - f"std={stats['cosine_similarity_std']:.3f}" - ) - - return stats - - -def start_embedding_batch( - session: Session, - openai_client: OpenAI, - eval_run: EvaluationRun, - results: list[dict[str, Any]], - trace_id_mapping: dict[str, str], -) -> EvaluationRun: - """ - Start embedding batch for similarity scoring. - - This function orchestrates the embedding batch creation: - 1. Builds embedding JSONL from evaluation results with trace_ids - 2. Creates batch via generic infrastructure (job_type="embedding") - 3. Links embedding_batch_job_id to eval_run - 4. Keeps status as "processing" - - Args: - session: Database session - openai_client: Configured OpenAI client - eval_run: EvaluationRun database object - results: Parsed evaluation results (output + ground_truth pairs) - trace_id_mapping: Mapping of item_id to Langfuse trace_id - - Returns: - Updated EvaluationRun with embedding_batch_job_id populated - - Raises: - Exception: If any step fails - """ - try: - logger.info(f"Starting embedding batch for evaluation run {eval_run.id}") - - # Use default embedding model - embedding_model = EMBEDDING_MODEL - - # Step 1: Build embedding JSONL with trace_ids - jsonl_data, skipped = build_embedding_jsonl( - results=results, - trace_id_mapping=trace_id_mapping, - embedding_model=embedding_model, - ) - - # Record un-embeddable items (keyed by trace_id) so the read path can - # flag them unscoreable with their reason. - unscoreable = { - item["trace_id"]: item["reason"] for item in skipped if item.get("trace_id") - } - if unscoreable: - eval_run.unscoreable = unscoreable - - if not jsonl_data: - raise ValueError("No valid items to create embeddings for") - - # Step 2: Create batch provider - provider = OpenAIBatchProvider(client=openai_client) - - # Step 3: Prepare batch configuration - batch_config = { - "endpoint": "/v1/embeddings", - "description": f"Embeddings for evaluation: {eval_run.run_name}", - "completion_window": "24h", - "embedding_model": embedding_model, - } - - # Step 4: Start batch job using generic infrastructure - batch_job = start_batch_job( - session=session, - provider=provider, - provider_name="openai", - job_type=BatchJobType.EMBEDDING, - organization_id=eval_run.organization_id, - project_id=eval_run.project_id, - jsonl_data=jsonl_data, - config=batch_config, - ) - - # Step 5: Link embedding_batch_job to evaluation_run - eval_run.embedding_batch_job_id = batch_job.id - # Keep status as "processing" - will change to "completed" after embeddings - eval_run.updated_at = now() - - session.add(eval_run) - session.commit() - session.refresh(eval_run) - - logger.info( - f"Successfully started embedding batch: batch_job_id={batch_job.id}, " - f"provider_batch_id={batch_job.provider_batch_id} " - f"for evaluation run {eval_run.id} with {batch_job.total_items} items" - ) - - return eval_run - - except Exception as e: - logger.error(f"Failed to start embedding batch: {e}", exc_info=True) - # Don't update eval_run status here - let caller decide - raise diff --git a/backend/app/crud/evaluations/langfuse.py b/backend/app/crud/evaluations/langfuse.py index 793c89726..5a82298b8 100644 --- a/backend/app/crud/evaluations/langfuse.py +++ b/backend/app/crud/evaluations/langfuse.py @@ -5,7 +5,8 @@ 1. Creating dataset runs in Langfuse 2. Creating traces for each evaluation item 3. Uploading results to Langfuse for visualization -4. Fetching trace scores from Langfuse for results +4. Reading items of legacy Langfuse-backed datasets +5. Fetching trace scores from Langfuse for results """ import logging @@ -20,7 +21,6 @@ from app.crud.evaluations.score import ( COSINE_SCORE_COMMENT, COSINE_SCORE_NAME, - DEFAULT_CATEGORY, EvaluationScore, ) from app.models.evaluation import TraceData, TraceScore @@ -308,105 +308,42 @@ def update_traces_with_cosine_scores( return failed_trace_ids -def upload_dataset_to_langfuse( - langfuse: Langfuse, - items: list[dict[str, str]], - dataset_name: str, - duplication_factor: int, -) -> tuple[str, int]: +def fetch_dataset_items(langfuse: Langfuse, dataset_name: str) -> list[dict[str, Any]]: """ - Upload a dataset to Langfuse from pre-parsed items. + Fetch all items from a Langfuse dataset. Args: langfuse: Configured Langfuse client - items: List of dicts with 'question' and 'answer' keys (already validated) - dataset_name: Name for the dataset in Langfuse - duplication_factor: Number of times to duplicate each item + dataset_name: Name of the dataset to fetch Returns: - Tuple of (langfuse_dataset_id, total_items_uploaded) + List of dataset items with input and expected_output Raises: - Exception: If Langfuse operations fail + ValueError: If dataset not found or empty """ - logger.info( - f"[upload_dataset_to_langfuse] Uploading dataset to Langfuse | " - f"dataset={dataset_name} | items={len(items)} | " - f"duplication_factor={duplication_factor}" - ) - - def upload_item(item: dict[str, str], duplicate_num: int, question_id: str) -> bool: - try: - metadata = { - "original_question": item["question"], - "duplicate_number": duplicate_num + 1, - "duplication_factor": duplication_factor, - "question_id": question_id, - } - if "category" in item: - metadata["category"] = item["category"] or DEFAULT_CATEGORY - langfuse.create_dataset_item( - dataset_name=dataset_name, - input={"question": item["question"]}, - expected_output={"answer": item["answer"]}, - metadata=metadata, - ) - return True - except Exception as e: - logger.warning( - f"[upload_dataset_to_langfuse] Failed to upload item | " - f"duplicate={duplicate_num + 1} | " - f"question={item['question'][:50]}... | {format_langfuse_error(e)}" - ) - return False - try: - # Create or get dataset in Langfuse - dataset = langfuse.create_dataset(name=dataset_name) - - # Generate question_id for each unique question before duplication - # All duplicates of the same question share the same question_id - # Using 1-based integer IDs for easier sorting and grouping - upload_tasks = [] - for idx, item in enumerate(items, start=1): - question_id = idx - for duplicate_num in range(duplication_factor): - upload_tasks.append((item, duplicate_num, question_id)) - - # Upload items concurrently using ThreadPoolExecutor - total_uploaded = 0 - with ThreadPoolExecutor(max_workers=4) as executor: - # Submit all upload tasks and collect the futures - futures = [] - for item, dup_num, question_id in upload_tasks: - future = executor.submit(upload_item, item, dup_num, question_id) - futures.append(future) - - for future in as_completed(futures): - upload_successful = future.result() - if upload_successful: - total_uploaded += 1 - - # Final flush to ensure all items are uploaded - langfuse.flush() - - langfuse_dataset_id = dataset.id - - logger.info( - f"[upload_dataset_to_langfuse] Successfully uploaded to Langfuse | " - f"items={total_uploaded} | dataset={dataset_name} | " - f"id={langfuse_dataset_id}" - ) - - return langfuse_dataset_id, total_uploaded - + dataset = langfuse.get_dataset(dataset_name) except Exception as e: - logger.error( - f"[upload_dataset_to_langfuse] Failed to upload dataset to Langfuse | " - f"dataset={dataset_name} | {format_langfuse_error(e)}", - exc_info=True, + logger.warning( + f"[fetch_dataset_items] Failed to fetch dataset | dataset={dataset_name} | {e}" ) - raise + raise ValueError(f"Dataset '{dataset_name}' not found: {e}") + + if not dataset.items: + raise ValueError(f"Dataset '{dataset_name}' is empty") + + items = [] + for item in dataset.items: + items.append( + { + "id": item.id, + "input": item.input, + "expected_output": item.expected_output, + "metadata": item.metadata if hasattr(item, "metadata") else {}, + } + ) + return items def fetch_trace_scores_from_langfuse( diff --git a/backend/app/crud/evaluations/processing.py b/backend/app/crud/evaluations/processing.py deleted file mode 100644 index a84354989..000000000 --- a/backend/app/crud/evaluations/processing.py +++ /dev/null @@ -1,1322 +0,0 @@ -""" -Evaluation batch processing orchestrator. - -This module coordinates the evaluation-specific workflow: -1. Monitoring batch_job status for evaluations -2. Parsing evaluation results from batch output -3. Creating Langfuse dataset runs with traces -4. Updating evaluation_run with final status and scores -""" - -import ast -import asyncio -import json -import logging -from collections import defaultdict -from typing import Any, cast - -from fastapi import HTTPException -from langfuse import Langfuse -from openai import OpenAI -from sqlmodel import Session, select - -from app.core.batch import ( - GeminiBatchProvider, - OpenAIBatchProvider, - download_batch_results, - poll_batch_status, - upload_batch_results_to_object_store, -) -from app.core.batch.base import BATCH_KEY, BatchProvider -from app.core.batch.client import GeminiClient -from app.core.batch.gemini import BatchJobState, extract_text_from_response_dict -from app.core.cloud.storage import get_cloud_storage -from app.core.storage_utils import load_json_from_object_store -from app.crud.evaluations.batch import fetch_dataset_items -from app.crud.evaluations.core import ( - build_log_prefix, - persist_score_traces, - resolve_model_from_config, - save_score, - update_evaluation_run, -) -from app.services.llm.providers.registry import LLMProvider -from app.crud.evaluations.cost import attach_cost -from app.crud.evaluations.embeddings import ( - EMBEDDING_MODEL, - calculate_average_similarity, - parse_embedding_results, - start_embedding_batch, -) -from app.crud.evaluations.langfuse import ( - create_langfuse_dataset_run, - update_traces_with_cosine_scores, -) -from app.crud.evaluations.merge import apply_cosine_breakdown -from app.crud.evaluations.score import ( - COSINE_SCORE_COMMENT, - COSINE_SCORE_NAME, - EvaluationScore, -) -from app.crud.job import get_batch_job, update_batch_job -from app.models import EvaluationRun, EvaluationRunUpdate -from app.models.batch_job import BatchJob, BatchJobUpdate -from app.models.evaluation import RunModeEnum, TraceData -from app.utils import get_langfuse_client, get_openai_client - -logger = logging.getLogger(__name__) - - -def _get_batch_provider( - session: Session, - provider_name: str, - organization_id: int, - project_id: int, -) -> BatchProvider: - """Get appropriate batch provider instance for the main response batch.""" - if provider_name in (LLMProvider.OPENAI, LLMProvider.OPENAI_NATIVE): - openai_client = get_openai_client( - session=session, - org_id=organization_id, - project_id=project_id, - ) - return OpenAIBatchProvider(client=openai_client) - - if provider_name in ( - LLMProvider.GOOGLE_AISTUDIO, - LLMProvider.GOOGLE_AISTUDIO_NATIVE, - ): - gemini_client = GeminiClient.from_credentials( - session=session, - org_id=organization_id, - project_id=project_id, - ) - return GeminiBatchProvider(client=gemini_client.client) - - raise ValueError(f"Unsupported provider for evaluation polling: {provider_name}") - - -def _extract_batch_error_message( - provider: OpenAIBatchProvider, - error_file_id: str, - batch_job: BatchJob, - session: Session, -) -> str: - """ - Download the error file from OpenAI, parse JSONL entries, and extract - the most common error message. Updates batch_job.error_message. - - Args: - provider: OpenAI batch provider instance - error_file_id: OpenAI error file ID - batch_job: BatchJob to update with error message - session: Database session - - Returns: - Human-readable error message with the top error and counts - """ - try: - error_content = provider.download_file(error_file_id) - lines = error_content.strip().split("\n") - - error_counts: dict[str, int] = {} - for line in lines: - try: - entry = json.loads(line) - message = ( - entry.get("response", {}) - .get("body", {}) - .get("error", {}) - .get("message", "Unknown error") - ) - error_counts[message] = error_counts.get(message, 0) + 1 - except json.JSONDecodeError: - continue - - if error_counts: - top_error = max(error_counts, key=lambda msg: error_counts[msg]) - top_count = error_counts[top_error] - total = sum(error_counts.values()) - error_msg = f"{top_error} ({top_count}/{total} requests)" - else: - error_msg = "Batch completed with errors but could not parse error file" - - except Exception as e: - logger.warning( - f"[_extract_batch_error_message] Failed to extract errors | batch_job_id={batch_job.id} | {e}", - exc_info=True, - ) - error_msg = ( - f"Batch completed with all requests failed (error_file_id: {error_file_id})" - ) - - # Update batch_job with extracted error message (outside try/except - # so persistence failures propagate to the caller) - batch_job_update = BatchJobUpdate(error_message=error_msg) - update_batch_job( - session=session, batch_job=batch_job, batch_job_update=batch_job_update - ) - - logger.info( - f"[_extract_batch_error_message] Extracted error | batch_job_id={batch_job.id} | {error_msg}" - ) - - return error_msg - - -def _extract_gemini_usage(response: dict[str, Any]) -> dict[str, Any] | None: - """Map Gemini usageMetadata to OpenAI-style usage dict for cost tracking.""" - usage_metadata = response.get("usageMetadata") or response.get("usage_metadata") - if not isinstance(usage_metadata, dict): - return None - input_tokens = usage_metadata.get("promptTokenCount") or usage_metadata.get( - "prompt_token_count" - ) - output_tokens = usage_metadata.get("candidatesTokenCount") or usage_metadata.get( - "candidates_token_count" - ) - total_tokens = usage_metadata.get("totalTokenCount") or usage_metadata.get( - "total_token_count" - ) - reasoning_tokens = usage_metadata.get("thoughtsTokenCount") or usage_metadata.get( - "thoughts_token_count" - ) - return { - "input_tokens": input_tokens or 0, - "output_tokens": output_tokens or 0, - "total_tokens": total_tokens or 0, - "reasoning_tokens": reasoning_tokens or 0, - } - - -def parse_evaluation_output( - raw_results: list[dict[str, Any]], - dataset_items: list[dict[str, Any]], - provider_name: str = LLMProvider.OPENAI, -) -> list[dict[str, Any]]: - """ - Parse batch output into evaluation results. - - This function extracts the generated output from the batch results - and matches it with the ground truth from the dataset. - - Args: - raw_results: Raw results from batch provider (list of JSONL lines) - dataset_items: Original dataset items (for matching ground truth) - - Returns: - List of results in format: - [ - { - "item_id": "item_123", - "question": "What is 2+2?", - "generated_output": "4", - "ground_truth": "4", - "response_id": "resp_0b99aadfead1fb62006908e7f540c48197bd110183a347c1d8", - "usage": { - "input_tokens": 69, - "output_tokens": 258, - "total_tokens": 327 - } - }, - ... - ] - """ - # Create lookup map for dataset items by ID - dataset_map = {item["id"]: item for item in dataset_items} - is_google = provider_name in ( - LLMProvider.GOOGLE_AISTUDIO, - LLMProvider.GOOGLE_AISTUDIO_NATIVE, - ) - - results = [] - - for line_num, response in enumerate(raw_results, 1): - try: - item_id = response.get(BATCH_KEY) or response.get("key") - if not item_id: - logger.warning( - f"[parse_evaluation_output] No item_id found, skipping | line={line_num}" - ) - continue - - dataset_item = dataset_map.get(item_id) - if not dataset_item: - logger.warning( - f"[parse_evaluation_output] No dataset item found | line={line_num} | item_id={item_id}" - ) - continue - - generated_output = "" - response_id: str | None = None - usage: dict[str, Any] | None = None - - if is_google: - gemini_response = response.get("response") - error = response.get("error") - if error: - error_msg = str(error) - logger.warning( - f"[parse_evaluation_output] Item had error | item_id={item_id} | {error_msg}" - ) - generated_output = f"ERROR: {error_msg}" - elif isinstance(gemini_response, dict): - text = extract_text_from_response_dict(gemini_response) - generated_output = text or "" - response_id = gemini_response.get( - "responseId" - ) or gemini_response.get("response_id") - usage = _extract_gemini_usage(gemini_response) - else: - response_body = response.get("response", {}).get("body", {}) - response_id = response_body.get("id") - usage = response_body.get("usage") - - if response.get("error"): - error_msg = response["error"].get("message", "Unknown error") - logger.warning( - f"[parse_evaluation_output] Item had error | item_id={item_id} | {error_msg}" - ) - generated_output = f"ERROR: {error_msg}" - else: - output = response_body.get("output", "") - - if isinstance(output, str): - try: - output = json.loads(output) - except (json.JSONDecodeError, ValueError): - try: - output = ast.literal_eval(output) - except (ValueError, SyntaxError): - generated_output = output - output = None - - if isinstance(output, list): - for item in output: - if isinstance(item, dict) and item.get("type") == "message": - for content in item.get("content", []): - if ( - isinstance(content, dict) - and content.get("type") == "output_text" - ): - generated_output = content.get("text", "") - break - if generated_output: - break - elif output is not None: - generated_output = "" - logger.warning( - f"[parse_evaluation_output] Unexpected output type | item_id={item_id} | type={type(output)}" - ) - - question = dataset_item["input"].get("question", "") - ground_truth = dataset_item["expected_output"].get("answer", "") - question_id = dataset_item.get("metadata", {}).get("question_id") - - results.append( - { - "item_id": item_id, - "question": question, - "generated_output": generated_output, - "ground_truth": ground_truth, - "response_id": response_id, - "usage": usage, - "question_id": question_id, - } - ) - - except Exception as e: - logger.error( - f"[parse_evaluation_output] Unexpected error | line={line_num} | {e}" - ) - continue - - logger.info( - f"[parse_evaluation_output] Parsed evaluation results | results={len(results)} | output_lines={len(raw_results)}" - ) - return results - - -def build_trace_skeleton( - results: list[dict[str, Any]], - trace_id_mapping: dict[str, str], -) -> list[TraceData]: - """ - Build per-trace records (Q&A keyed by Langfuse trace_id, no scores yet) from - parsed evaluation results. Persisted at the response stage so the - embedding-completion step can attach cosine scores and write a complete trace - unit, making cosine display independent of Langfuse. Items without a trace_id - are skipped. - """ - traces: list[TraceData] = [] - for result in results: - item_id = result.get("item_id") - if item_id is None: - continue - trace_id = trace_id_mapping.get(item_id) - if not trace_id: - continue - traces.append( - { - "trace_id": trace_id, - "question": result.get("question", ""), - "llm_answer": result.get("generated_output", ""), - "ground_truth_answer": result.get("ground_truth", ""), - "question_id": result.get("question_id"), - "scores": [], - } - ) - return traces - - -async def process_completed_evaluation( - eval_run: EvaluationRun, - session: Session, - openai_client: OpenAI, - langfuse: Langfuse, -) -> EvaluationRun: - """ - Process a completed evaluation batch. - - This function: - 1. Downloads batch output from provider - 2. Parses results into question/output/ground_truth format - 3. Creates Langfuse dataset run with traces - 4. Starts embedding batch for similarity scoring (keeps status as "processing") - - Args: - eval_run: EvaluationRun database object - session: Database session - openai_client: Configured OpenAI client - langfuse: Configured Langfuse client - - Returns: - Updated EvaluationRun object (with embedding_batch_job_id set) - - Raises: - Exception: If processing fails - """ - log_prefix = build_log_prefix(eval_run) - logger.info( - f"[process_completed_evaluation] {log_prefix} Processing completed evaluation" - ) - - try: - # Step 1: Get batch_job - if not eval_run.batch_job_id: - raise ValueError(f"EvaluationRun {eval_run.id} has no batch_job_id") - - batch_job = get_batch_job(session=session, batch_job_id=eval_run.batch_job_id) - if not batch_job: - raise ValueError( - f"BatchJob {eval_run.batch_job_id} not found for evaluation {eval_run.id}" - ) - - # Step 2: Create provider and download results - logger.info( - f"[process_completed_evaluation] {log_prefix} Downloading batch results | batch_job_id={batch_job.id}" - ) - provider = _get_batch_provider( - session=session, - provider_name=batch_job.provider, - organization_id=eval_run.organization_id, - project_id=eval_run.project_id, - ) - raw_results = await asyncio.to_thread( - download_batch_results, provider=provider, batch_job=batch_job - ) - - # Step 2a: Upload raw results to object store for evaluation_run - object_store_url = None - try: - object_store_url = upload_batch_results_to_object_store( - session=session, batch_job=batch_job, results=raw_results - ) - except Exception as store_error: - logger.warning( - f"[process_completed_evaluation] {log_prefix} Object store upload failed | {store_error}" - ) - - # Step 3: Fetch dataset items (needed for matching ground truth) - logger.info( - f"[process_completed_evaluation] {log_prefix} Fetching dataset items | dataset={eval_run.dataset_name}" - ) - dataset_items = await asyncio.to_thread( - fetch_dataset_items, - langfuse=langfuse, - dataset_name=eval_run.dataset_name, - ) - - # Step 4: Parse evaluation results - results = parse_evaluation_output( - raw_results=raw_results, - dataset_items=dataset_items, - provider_name=batch_job.provider, - ) - - if not results: - raise ValueError("No valid results found in batch output") - - # Step 5: Create Langfuse dataset run with traces - # Use model stored at creation time for cost tracking - model = resolve_model_from_config(session=session, eval_run=eval_run) - - # Aggregate response generation cost - attach_cost( - session=session, - eval_run=eval_run, - log_prefix=log_prefix, - response_model=model, - response_results=results, - ) - update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate(cost=eval_run.cost), - ) - - trace_id_mapping = await asyncio.to_thread( - create_langfuse_dataset_run, - langfuse=langfuse, - dataset_name=eval_run.dataset_name, - model=model, - run_name=eval_run.run_name, - results=results, - ) - - # Store object store URL in database - if object_store_url: - eval_run.object_store_url = object_store_url - session.add(eval_run) - session.commit() - - # Step 5b: Persist the trace skeleton now, while results and - # trace_id_mapping are in hand, so the later embedding-completion poll can - # attach cosine scores without depending on Langfuse. persist_score_traces - # records only the pointer (not `score`), keeping the run score-less until - # cosine completes. Best-effort: the read path can backfill from - # per_item_scores if the skeleton is missing. - skeleton = build_trace_skeleton( - results=results, trace_id_mapping=trace_id_mapping - ) - if skeleton: - persist_score_traces( - eval_run_id=eval_run.id, - organization_id=eval_run.organization_id, - project_id=eval_run.project_id, - traces=skeleton, - ) - logger.info( - f"[process_completed_evaluation] {log_prefix} Persisted trace " - f"skeleton | traces={len(skeleton)}" - ) - - # Step 6: Start embedding batch for similarity scoring - # Pass trace_id_mapping directly without storing in DB - try: - eval_run = await asyncio.to_thread( - start_embedding_batch, - session=session, - openai_client=openai_client, - eval_run=eval_run, - results=results, - trace_id_mapping=trace_id_mapping, - ) - # Note: Status remains "processing" until embeddings complete - - except Exception as e: - logger.error( - f"[process_completed_evaluation] {log_prefix} Failed to start embedding batch | {e}", - exc_info=True, - ) - # Don't fail the entire evaluation, just mark as completed without embeddings - eval_run = update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate( - status="completed", - error_message=f"Embeddings failed: {str(e)}", - ), - ) - - logger.info( - f"[process_completed_evaluation] {log_prefix} Processed evaluation | items={len(results)}" - ) - - return eval_run - - except Exception as e: - logger.error( - f"[process_completed_evaluation] {log_prefix} Failed to process completed evaluation | {e}", - exc_info=True, - ) - # Mark as failed - return update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate( - status="failed", - error_message=f"Processing failed: {str(e)}", - ), - ) - - -def _load_score_traces( - session: Session, - project_id: int, - eval_run: EvaluationRun, -) -> list[TraceData] | None: - """ - Load the trace skeleton persisted to ``score_trace_url`` at the response - stage. Returns None when there is no pointer or it can't be read, so the - caller falls back to a summary-only score. Never raises. - """ - if not eval_run.score_trace_url: - return None - try: - storage = get_cloud_storage(session=session, project_id=project_id) - traces = load_json_from_object_store( - storage=storage, url=eval_run.score_trace_url - ) - if isinstance(traces, list) and traces: - return traces - except Exception as e: - logger.warning( - f"[_load_score_traces] Could not load trace skeleton | " - f"evaluation_id={eval_run.id} | url={eval_run.score_trace_url} | {e}", - exc_info=True, - ) - return None - - -def _attach_cosine_scores( - traces: list[TraceData], - cosine_by_trace: dict[str, float], - unscoreable: dict[str, str], -) -> list[TraceData]: - """ - Attach computed cosine scores (and 0-score placeholders for unscoreable - items) onto the trace skeleton, in place. Traces already carrying a computed - cosine are left untouched; unscoreable placeholders are flagged to stay out - of the summary stats. - """ - for trace in traces: - trace_id = trace.get("trace_id") - scores = trace.setdefault("scores", []) - has_cosine = any( - s.get("name") == COSINE_SCORE_NAME and not s.get("unscoreable") - for s in scores - ) - if has_cosine: - continue - if trace_id in cosine_by_trace: - scores.append( - { - "name": COSINE_SCORE_NAME, - "value": round(float(cosine_by_trace[trace_id]), 2), - "data_type": "NUMERIC", - "comment": COSINE_SCORE_COMMENT, - } - ) - elif trace_id in unscoreable: - scores.append( - { - "name": COSINE_SCORE_NAME, - "value": 0, - "data_type": "NUMERIC", - "comment": f"Cannot compute: {unscoreable[trace_id]}", - "unscoreable": True, - } - ) - return traces - - -async def process_completed_embedding_batch( - eval_run: EvaluationRun, - session: Session, - openai_client: OpenAI, - langfuse: Langfuse, -) -> EvaluationRun: - """ - Process a completed embedding batch and calculate similarity scores. - - This function: - 1. Downloads embedding batch results - 2. Parses embeddings (output + ground_truth pairs) - 3. Calculates cosine similarity for each pair - 4. Calculates average and statistics - 5. Updates eval_run.score with results - 6. Updates Langfuse traces with per-item cosine similarity scores - 7. Marks evaluation as completed - - Args: - eval_run: EvaluationRun database object - session: Database session - openai_client: Configured OpenAI client - langfuse: Configured Langfuse client - - Returns: - Updated EvaluationRun object with similarity scores - - Raises: - Exception: If processing fails - """ - log_prefix = build_log_prefix(eval_run) - logger.info( - f"[process_completed_embedding_batch] {log_prefix} Processing completed embedding batch" - ) - - try: - # Step 1: Get embedding_batch_job - if not eval_run.embedding_batch_job_id: - raise ValueError( - f"EvaluationRun {eval_run.id} has no embedding_batch_job_id" - ) - - embedding_batch_job = get_batch_job( - session=session, batch_job_id=eval_run.embedding_batch_job_id - ) - if not embedding_batch_job: - raise ValueError( - f"Embedding BatchJob {eval_run.embedding_batch_job_id} not found for evaluation {eval_run.id}" - ) - - # Step 2: Create provider and download results - provider = OpenAIBatchProvider(client=openai_client) - raw_results = await asyncio.to_thread( - download_batch_results, - provider=provider, - batch_job=embedding_batch_job, - ) - - # Step 3: Parse embedding results - embedding_pairs, failed_trace_ids = parse_embedding_results( - raw_results=raw_results - ) - - if not embedding_pairs: - raise ValueError("No valid embedding pairs found in batch output") - - # Flag failed embeddings before Step 5/6 so the gap is counted and written. - # setdefault keeps any reason already set at start_embedding_batch. - if failed_trace_ids: - unscoreable = dict(eval_run.unscoreable or {}) - for trace_id in failed_trace_ids: - unscoreable.setdefault(trace_id, "embedding_failed") - eval_run.unscoreable = unscoreable or None - - # Step 4: Calculate similarity scores - similarity_stats = calculate_average_similarity(embedding_pairs=embedding_pairs) - - # Step 5: Update evaluation_run with scores in summary_scores format - # This format is consistent with what Langfuse returns when fetching traces - per_item_scores = similarity_stats.get("per_item_scores", []) - - summary_scores = apply_cosine_breakdown( - [ - { - "name": COSINE_SCORE_NAME, - "avg": round(float(similarity_stats["cosine_similarity_avg"]), 2), - "std": round(float(similarity_stats["cosine_similarity_std"]), 2), - "total_pairs": similarity_stats["total_pairs"], - "data_type": "NUMERIC", - } - ], - total_items=eval_run.total_items, - unscoreable=eval_run.unscoreable, - ) - eval_run.score = {"summary_scores": summary_scores} - - # Durable per-item cosine scores (source of truth), so a failed Langfuse - # write can be backfilled on resync. - eval_run.per_item_scores = { - item["trace_id"]: round(float(item["cosine_similarity"]), 6) - for item in per_item_scores - if item.get("trace_id") is not None - } - - # Step 6: Accumulate embedding cost onto existing response cost. Mutates - # eval_run.cost in memory; persisted in the completion commit below. - attach_cost( - session=session, - eval_run=eval_run, - log_prefix=log_prefix, - embedding_model=EMBEDDING_MODEL, - embedding_raw_results=raw_results, - ) - - # Step 7: Mark completed WITH the score now that cosine is done; this also - # persists the per_item_scores / unscoreable set above. Trace-writing - # happens afterwards (Steps 8-9) so completion isn't gated on Langfuse. - eval_run = update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate( - status="completed", - score=eval_run.score, - cost=eval_run.cost, - ), - ) - - # Step 8: With the run completed, update Langfuse traces with cosine - # similarity scores. Also write explicit 0-scores for unscoreable items so - # the gap is visible in the UI. - logger.info( - f"[process_completed_embedding_batch] {log_prefix} Updating Langfuse traces with cosine similarity scores" - ) - unscoreable_writes = [ - {"trace_id": trace_id, "unscoreable": True, "reason": reason} - for trace_id, reason in (eval_run.unscoreable or {}).items() - ] - write_items = per_item_scores + unscoreable_writes - # False if any write fails, so a cron can retry the gap from per_item_scores. - is_score_updated = True - if write_items: - try: - failed_trace_ids = update_traces_with_cosine_scores( - langfuse=langfuse, - per_item_scores=write_items, - ) - if failed_trace_ids: - is_score_updated = False - logger.warning( - f"[process_completed_embedding_batch] {log_prefix} " - f"{len(failed_trace_ids)} Langfuse score writes failed; " - f"recoverable from durable per_item_scores on resync" - ) - except Exception as e: - # Log error but don't fail the evaluation - is_score_updated = False - logger.warning( - f"[process_completed_embedding_batch] {log_prefix} Failed to update Langfuse traces with scores | {e}", - exc_info=True, - ) - - # Persist the Langfuse write outcome so a cron can retry the gap later. - eval_run = update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate(is_score_updated=is_score_updated), - ) - - # Step 9: Upgrade the score to a complete trace unit. Load the skeleton, - # attach cosine scores (and 0-score placeholders), and persist via - # save_score so the read path serves cosine without a Langfuse dependency. - skeleton = _load_score_traces( - session=session, project_id=eval_run.project_id, eval_run=eval_run - ) - if skeleton: - traces = _attach_cosine_scores( - traces=skeleton, - cosine_by_trace={ - item["trace_id"]: item["cosine_similarity"] - for item in per_item_scores - if item.get("trace_id") is not None - }, - unscoreable=eval_run.unscoreable or {}, - ) - full_score: EvaluationScore = { - "summary_scores": summary_scores, - "traces": traces, - } - saved = save_score( - eval_run_id=eval_run.id, - organization_id=eval_run.organization_id, - project_id=eval_run.project_id, - score=full_score, - ) - if saved is not None: - eval_run = saved - eval_run.score = cast(dict[str, Any], full_score) - logger.info( - f"[process_completed_embedding_batch] {log_prefix} Persisted " - f"durable trace unit | traces={len(traces)}" - ) - else: - logger.info( - f"[process_completed_embedding_batch] {log_prefix} No trace " - f"skeleton found; cosine recoverable via per_item_scores backfill " - f"on read" - ) - - logger.info( - f"[process_completed_embedding_batch] {log_prefix} Completed evaluation | avg_similarity={similarity_stats['cosine_similarity_avg']:.3f}" - ) - - return eval_run - - except Exception as e: - logger.error( - f"[process_completed_embedding_batch] {log_prefix} Failed to process completed embedding batch | {e}", - exc_info=True, - ) - # Mark as completed anyway, but with error message - return update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate( - status="completed", - error_message=f"Embedding processing failed: {str(e)}", - ), - ) - - -async def check_and_process_evaluation( - eval_run: EvaluationRun, - session: Session, - openai_client: OpenAI, - langfuse: Langfuse, -) -> dict[str, Any]: - """ - Check evaluation batch status and process if completed. - - This function handles both the response batch and embedding batch: - 1. If embedding_batch_job_id exists, checks and processes embedding batch first - 2. Otherwise, checks and processes the main response batch - 3. Triggers appropriate processing based on batch completion status - - Args: - eval_run: EvaluationRun database object - session: Database session - openai_client: Configured OpenAI client - langfuse: Configured Langfuse client - - Returns: - Dict with status information: - { - "run_id": 123, - "run_name": "test_run", - "previous_status": "processing", - "current_status": "completed", - "batch_status": "completed", - "action": "processed" | "embeddings_completed" | "embeddings_failed" | "failed" | "no_change" - } - """ - log_prefix = build_log_prefix(eval_run) - previous_status = eval_run.status - - try: - # Check if we need to process embedding batch first - if eval_run.embedding_batch_job_id and eval_run.status == "processing": - embedding_batch_job = get_batch_job( - session=session, batch_job_id=eval_run.embedding_batch_job_id - ) - - if embedding_batch_job: - # Poll embedding batch status - provider = OpenAIBatchProvider(client=openai_client) - await asyncio.to_thread( - poll_batch_status, - session=session, - provider=provider, - batch_job=embedding_batch_job, - ) - session.refresh(embedding_batch_job) - - embedding_status = embedding_batch_job.provider_status - - if embedding_status == "completed": - logger.info( - f"[check_and_process_evaluation] {log_prefix} Processing embedding batch | provider_batch_id={embedding_batch_job.provider_batch_id}" - ) - - await process_completed_embedding_batch( - eval_run=eval_run, - session=session, - openai_client=openai_client, - langfuse=langfuse, - ) - - return { - "run_id": eval_run.id, - "run_name": eval_run.run_name, - "previous_status": previous_status, - "current_status": eval_run.status, - "provider_status": embedding_status, - "action": "embeddings_completed", - } - - elif embedding_status in ["failed", "expired", "cancelled"]: - logger.warning( - f"[check_and_process_evaluation] {log_prefix} Embedding batch failed | provider_batch_id={embedding_batch_job.provider_batch_id} | {embedding_batch_job.error_message}" - ) - # Mark as completed without embeddings - eval_run = update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate( - status="completed", - error_message=f"Embedding batch failed: {embedding_batch_job.error_message}", - ), - ) - - return { - "run_id": eval_run.id, - "run_name": eval_run.run_name, - "previous_status": previous_status, - "current_status": "completed", - "provider_status": embedding_status, - "action": "embeddings_failed", - } - - else: - # Embedding batch still processing - return { - "run_id": eval_run.id, - "run_name": eval_run.run_name, - "previous_status": previous_status, - "current_status": eval_run.status, - "provider_status": embedding_status, - "action": "no_change", - } - - # Get batch_job (main response batch) - if not eval_run.batch_job_id: - raise ValueError(f"EvaluationRun {eval_run.id} has no batch_job_id") - - batch_job = get_batch_job(session=session, batch_job_id=eval_run.batch_job_id) - if not batch_job: - raise ValueError( - f"BatchJob {eval_run.batch_job_id} not found for evaluation {eval_run.id}" - ) - - # Build batch provider from batch_job.provider (OpenAI or Gemini) - provider = _get_batch_provider( - session=session, - provider_name=batch_job.provider, - organization_id=eval_run.organization_id, - project_id=eval_run.project_id, - ) - status_result = await asyncio.to_thread( - poll_batch_status, - session=session, - provider=provider, - batch_job=batch_job, - ) - - # Refresh batch_job to get the updated provider_status - session.refresh(batch_job) - provider_status = batch_job.provider_status - is_openai = batch_job.provider in ( - LLMProvider.OPENAI, - LLMProvider.OPENAI_NATIVE, - ) - - # Handle different provider statuses - if ( - provider_status == "completed" - or provider_status == BatchJobState.SUCCEEDED.value - ): - # OpenAI-only: batch completed but all requests failed (error file present, output file absent) - if ( - is_openai - and not status_result.get( - "provider_output_file_id", batch_job.provider_output_file_id - ) - and status_result.get("error_file_id") - ): - error_msg = _extract_batch_error_message( - provider=cast(OpenAIBatchProvider, provider), - error_file_id=status_result["error_file_id"], - batch_job=batch_job, - session=session, - ) - - eval_run = update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate( - status="failed", - error_message=error_msg, - ), - ) - - logger.error( - f"[check_and_process_evaluation] {log_prefix} Batch completed with all requests failed | {error_msg}" - ) - - return { - "run_id": eval_run.id, - "run_name": eval_run.run_name, - "previous_status": previous_status, - "current_status": "failed", - "provider_status": provider_status, - "action": "failed", - "error": error_msg, - } - - # Process the completed evaluation - await process_completed_evaluation( - eval_run=eval_run, - session=session, - openai_client=openai_client, - langfuse=langfuse, - ) - - return { - "run_id": eval_run.id, - "run_name": eval_run.run_name, - "previous_status": previous_status, - "current_status": eval_run.status, - "provider_status": provider_status, - "action": "processed", - } - - elif provider_status in ( - "failed", - "expired", - "cancelled", - BatchJobState.FAILED.value, - BatchJobState.CANCELLED.value, - BatchJobState.EXPIRED.value, - ): - # Mark evaluation as failed based on provider status - error_msg = batch_job.error_message or f"Provider batch {provider_status}" - - eval_run = update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate( - status="failed", - error_message=error_msg, - ), - ) - - logger.error( - f"[check_and_process_evaluation] {log_prefix} Batch failed | provider_batch_id={batch_job.provider_batch_id} | {error_msg}" - ) - - return { - "run_id": eval_run.id, - "run_name": eval_run.run_name, - "previous_status": previous_status, - "current_status": "failed", - "provider_status": provider_status, - "action": "failed", - "error": error_msg, - } - - else: - # Still in progress (validating, in_progress, finalizing) - return { - "run_id": eval_run.id, - "run_name": eval_run.run_name, - "previous_status": previous_status, - "current_status": eval_run.status, - "provider_status": provider_status, - "action": "no_change", - } - - except Exception as e: - logger.error( - f"[check_and_process_evaluation] {log_prefix} Error checking evaluation | {e}", - exc_info=True, - ) - - # Mark as failed - update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate( - status="failed", - error_message=f"Checking failed: {str(e)}", - ), - ) - - return { - "run_id": eval_run.id, - "run_name": eval_run.run_name, - "previous_status": previous_status, - "current_status": "failed", - "provider_status": "unknown", - "action": "failed", - "error": str(e), - } - - -async def poll_all_pending_evaluations(session: Session) -> dict[str, Any]: - """ - Poll all pending evaluations across all organizations. - - Fetches all evaluation runs with status='processing' in a single query, - groups them by project_id, and processes each project with its own - OpenAI/Langfuse clients. - - Args: - session: Database session - - Returns: - Summary dict: - { - "total": 5, - "processed": 2, - "failed": 1, - "still_processing": 2, - "details": [...] - } - """ - # Only batch-mode text runs are polled here; fast-mode runs complete - # synchronously and have no batch_job_id, and STT/TTS poll separately. - statement = select(EvaluationRun).where( - EvaluationRun.status == "processing", - EvaluationRun.type == "text", - EvaluationRun.run_mode == RunModeEnum.BATCH.value, - ) - pending_runs = session.exec(statement).all() - - if not pending_runs: - return { - "total": 0, - "processed": 0, - "failed": 0, - "still_processing": 0, - "details": [], - } - - logger.info( - f"[poll_all_pending_evaluations] Found {len(pending_runs)} pending evaluation runs" - ) - - # Group evaluations by project_id since credentials are per project - evaluations_by_project: dict[int, list[EvaluationRun]] = defaultdict(list) - for run in pending_runs: - evaluations_by_project[run.project_id].append(run) - - # Process each project separately - all_results = [] - total_processed_count = 0 - total_failed_count = 0 - total_still_processing_count = 0 - - for project_id, project_runs in evaluations_by_project.items(): - # All runs in a project share the same org_id - org_id = project_runs[0].organization_id - try: - # Get API clients for this project - try: - openai_client = get_openai_client( - session=session, - org_id=org_id, - project_id=project_id, - ) - langfuse = get_langfuse_client( - session=session, - org_id=org_id, - project_id=project_id, - ) - except HTTPException as http_exc: - logger.error( - f"[poll_all_pending_evaluations] Failed to get API clients | org_id={org_id} | project_id={project_id} | error={http_exc.detail}" - ) - # Mark all runs in this project as failed due to client configuration error - for eval_run in project_runs: - update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate( - status="failed", - error_message=http_exc.detail, - ), - ) - - all_results.append( - { - "run_id": eval_run.id, - "run_name": eval_run.run_name, - "action": "failed", - "error": http_exc.detail, - } - ) - total_failed_count += 1 - continue - - # Process each evaluation in this project - for eval_run in project_runs: - try: - result = await check_and_process_evaluation( - eval_run=eval_run, - session=session, - openai_client=openai_client, - langfuse=langfuse, - ) - all_results.append(result) - - if result["action"] == "processed": - total_processed_count += 1 - elif result["action"] == "failed": - total_failed_count += 1 - else: - total_still_processing_count += 1 - - except Exception as e: - logger.error( - f"[poll_all_pending_evaluations] Failed to check evaluation run | run_id={eval_run.id} | {e}", - exc_info=True, - ) - update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate( - status="failed", - error_message=f"Check failed: {str(e)}", - ), - ) - - all_results.append( - { - "run_id": eval_run.id, - "run_name": eval_run.run_name, - "action": "failed", - "error": str(e), - } - ) - total_failed_count += 1 - - # Flush background ingestion threads before discarding this client. - # Each Langfuse() instance spawns TaskManager threads; without flush, - # they accumulate across cron runs and pile up concurrent API calls. - try: - langfuse.flush() - except Exception as flush_err: - logger.warning( - f"[poll_all_pending_evaluations] Langfuse flush failed | project_id={project_id} | {flush_err}" - ) - - except Exception as e: - logger.error( - f"[poll_all_pending_evaluations] Failed to process project | project_id={project_id} | {e}", - exc_info=True, - ) - for eval_run in project_runs: - update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate( - status="failed", - error_message=f"Project processing failed: {str(e)}", - ), - ) - - all_results.append( - { - "run_id": eval_run.id, - "run_name": eval_run.run_name, - "action": "failed", - "error": f"Project processing failed: {str(e)}", - } - ) - total_failed_count += 1 - - summary = { - "total": len(pending_runs), - "processed": total_processed_count, - "failed": total_failed_count, - "still_processing": total_still_processing_count, - "details": all_results, - } - - logger.info( - f"[poll_all_pending_evaluations] Polling summary | processed={total_processed_count} | failed={total_failed_count} | still_processing={total_still_processing_count}" - ) - - return summary diff --git a/backend/app/crud/evaluations/score.py b/backend/app/crud/evaluations/score.py index 207447808..26fad1d33 100644 --- a/backend/app/crud/evaluations/score.py +++ b/backend/app/crud/evaluations/score.py @@ -44,8 +44,8 @@ def verdict_from_score(score: float) -> VerdictEnum: PROMPT_SCORE_NAME: str = "Adherence to Prompt" KNOWLEDGE_BASE_SCORE_NAME: str = "Adherence to Knowledge Base" # Reasons an item cannot be scored, recorded in EvaluationRun.unscoreable. -# MISSING_TRACE_ID appears only in build_embedding_jsonl's internal skipped list; -# EMBEDDING_FAILED is v1-only (cosine), since v2 judged runs never embed. +# MISSING_TRACE_ID was only produced by the removed text-batch pipeline and +# EMBEDDING_FAILED is v1-only (cosine); both are kept to read historical runs. UNSCOREABLE_EMPTY_OUTPUT: str = "empty_output" UNSCOREABLE_EMPTY_GROUND_TRUTH: str = "empty_ground_truth" UNSCOREABLE_EMBEDDING_FAILED: str = "embedding_failed" diff --git a/backend/app/services/evaluations/__init__.py b/backend/app/services/evaluations/__init__.py index 5a06cb7dc..beb91da1d 100644 --- a/backend/app/services/evaluations/__init__.py +++ b/backend/app/services/evaluations/__init__.py @@ -1,10 +1,7 @@ """Evaluation services.""" from app.services.evaluations.dataset import upload_dataset -from app.services.evaluations.evaluation import ( - get_evaluation_with_scores, - validate_and_start_batch_evaluation, -) +from app.services.evaluations.evaluation import get_evaluation_with_scores from app.services.evaluations.fast import ( execute_fast_evaluation_aggregate, execute_fast_evaluation_chunk, diff --git a/backend/app/services/evaluations/batch_job.py b/backend/app/services/evaluations/batch_job.py deleted file mode 100644 index 99a6da0e0..000000000 --- a/backend/app/services/evaluations/batch_job.py +++ /dev/null @@ -1,102 +0,0 @@ -import logging -from uuid import UUID - -from celery.exceptions import SoftTimeLimitExceeded -from gevent import Timeout -from sqlmodel import Session - -from app.core.db import engine -from app.crud.evaluations import ( - get_evaluation_run_by_id, - resolve_evaluation_config, - start_evaluation_batch, -) -from app.crud.evaluations.core import update_evaluation_run -from app.models.evaluation import EvaluationRunUpdate -from app.services.llm.mappers import kaapi_params_as_dict -from app.utils import get_langfuse_client - -logger = logging.getLogger(__name__) - - -def execute_evaluation_batch_submission( - project_id: int, - job_id: str, - task_id: str, - task_instance, - organization_id: int, - config_id: str, - config_version: int, - **kwargs, -) -> dict: - run_id = int(job_id) - logger.info( - f"[execute_evaluation_batch_submission] Starting | run_id={run_id} | task={task_id}" - ) - with Session(engine) as session: - run = get_evaluation_run_by_id( - session=session, - evaluation_id=run_id, - organization_id=organization_id, - project_id=project_id, - ) - if not run: - return {"success": False, "error": "Run not found"} - confirmed_run = run - try: - config, error = resolve_evaluation_config( - session=session, - config_id=UUID(str(config_id)), - config_version=config_version, - project_id=project_id, - ) - - def _fail(msg: str) -> dict: - update_evaluation_run( - session=session, - eval_run=confirmed_run, - update=EvaluationRunUpdate(status="failed", error_message=msg), - ) - return {"success": False, "error": msg} - - if error or config is None: - return _fail(error or "Config could not be resolved") - - provider = config.completion.provider - if provider is None: - return _fail("Config has no resolvable provider") - - langfuse = get_langfuse_client( - session=session, org_id=organization_id, project_id=project_id - ) - run = start_evaluation_batch( - langfuse=langfuse, - session=session, - eval_run=run, - params=kaapi_params_as_dict(config.completion.params), - provider=config.completion.provider, - ) - return {"success": True, "batch_job_id": run.batch_job_id} - except (Timeout, SoftTimeLimitExceeded): - logger.warning( - f"[execute_evaluation_batch_submission] Timeout | run_id={run_id}" - ) - update_evaluation_run( - session=session, - eval_run=run, - update=EvaluationRunUpdate( - status="failed", error_message="Task exceeded soft time limit" - ), - ) - raise - except Exception as e: - logger.error( - f"[execute_evaluation_batch_submission] Failed | run_id={run_id} | {e}", - exc_info=True, - ) - update_evaluation_run( - session=session, - eval_run=run, - update=EvaluationRunUpdate(status="failed", error_message=str(e)), - ) - raise diff --git a/backend/app/services/evaluations/dataset.py b/backend/app/services/evaluations/dataset.py index 0872b39b7..f670a1028 100644 --- a/backend/app/services/evaluations/dataset.py +++ b/backend/app/services/evaluations/dataset.py @@ -9,7 +9,6 @@ from app.crud.evaluations import ( create_evaluation_dataset, upload_csv_to_object_store, - upload_dataset_to_langfuse, ) from app.crud.evaluations.dataset import ( DATASET_META_DUPLICATION_FACTOR, @@ -21,7 +20,6 @@ parse_csv_items, sanitize_dataset_name, ) -from app.utils import get_langfuse_client logger = logging.getLogger(__name__) @@ -34,7 +32,6 @@ def upload_dataset( duplication_factor: int, organization_id: int, project_id: int, - use_langfuse: bool = True, ) -> EvaluationDataset: """ Orchestrate dataset upload workflow. @@ -43,8 +40,7 @@ def upload_dataset( 1. Sanitize dataset name 2. Parse and validate CSV 3. Upload to object store - 4. Upload to Langfuse - 5. Store metadata in database + 4. Store metadata in database Args: session: Database session @@ -54,10 +50,6 @@ def upload_dataset( duplication_factor: Number of times to duplicate each item organization_id: Organization ID project_id: Project ID - use_langfuse: v1 default. False is the v2 Langfuse-free upload: the items - are duplicated at run time rather than physically, so only the original - CSV is stored and the object-store upload becomes mandatory (it is the - only copy of the data, with no Langfuse fallback). Returns: Created EvaluationDataset record @@ -65,7 +57,7 @@ def upload_dataset( Raises: HTTPException: If upload fails at any step """ - # Step 1: Sanitize dataset name for Langfuse compatibility + # Step 1: Sanitize dataset name original_name = dataset_name try: dataset_name = sanitize_dataset_name(dataset_name) @@ -93,69 +85,31 @@ def upload_dataset( f"total_with_duplication={total_items_count}" ) - # Step 3: Upload to object store. Best-effort when Langfuse also holds the items - # (v1); the sole copy, so mandatory, when it doesn't (v2). - object_store_url = None + # Step 3: Upload to object store. Mandatory: the CSV is the only copy of the + # items, which are duplicated at run time rather than physically. try: storage = get_cloud_storage(session=session, project_id=project_id) object_store_url = upload_csv_to_object_store( storage=storage, csv_content=csv_content, dataset_name=dataset_name ) - if object_store_url: - logger.info( - f"[upload_dataset] Successfully uploaded CSV to object store | {object_store_url}" - ) - else: - logger.info( - "[upload_dataset] Object store upload returned None | " - "continuing without object store storage" - ) except Exception as e: - logger.warning( - f"[upload_dataset] Failed to upload CSV to object store " - f"(continuing without object store) | {e}", + logger.error( + f"[upload_dataset] Failed to upload CSV to object store | {e}", exc_info=True, ) object_store_url = None - if not use_langfuse and not object_store_url: + if not object_store_url: raise HTTPException( status_code=500, detail="Failed to store dataset CSV in object store", ) - # Step 4: Upload to Langfuse - langfuse_dataset_id = None - if use_langfuse: - try: - langfuse = get_langfuse_client( - session=session, - org_id=organization_id, - project_id=project_id, - ) - - langfuse_dataset_id, _ = upload_dataset_to_langfuse( - langfuse=langfuse, - items=original_items, - dataset_name=dataset_name, - duplication_factor=duplication_factor, - ) - - logger.info( - f"[upload_dataset] Successfully uploaded dataset to Langfuse | " - f"dataset={dataset_name} | id={langfuse_dataset_id}" - ) - - except Exception as e: - logger.error( - f"[upload_dataset] Failed to upload dataset to Langfuse | {e}", - exc_info=True, - ) - raise HTTPException( - status_code=500, detail=f"Failed to upload dataset to Langfuse: {e}" - ) - - # Step 5: Store metadata in database + logger.info( + f"[upload_dataset] Successfully uploaded CSV to object store | {object_store_url}" + ) + + # Step 4: Store metadata in database metadata = { DATASET_META_ORIGINAL_ITEMS: original_items_count, DATASET_META_TOTAL_ITEMS: total_items_count, @@ -168,7 +122,6 @@ def upload_dataset( description=description, dataset_metadata=metadata, object_store_url=object_store_url, - langfuse_dataset_id=langfuse_dataset_id, organization_id=organization_id, project_id=project_id, ) diff --git a/backend/app/services/evaluations/evaluation.py b/backend/app/services/evaluations/evaluation.py index 02d13a324..45decf8a5 100644 --- a/backend/app/services/evaluations/evaluation.py +++ b/backend/app/services/evaluations/evaluation.py @@ -4,47 +4,37 @@ from typing import cast from uuid import UUID -from asgi_correlation_id import correlation_id from fastapi import HTTPException from sqlalchemy.exc import IntegrityError from sqlmodel import Session -from app.celery.utils import start_evaluation_batch_submission from app.core.cloud.storage import get_cloud_storage from app.core.storage_utils import load_json_from_object_store from app.crud.evaluations import ( EvaluationScore, fetch_trace_scores_from_langfuse, - get_dataset_by_id, get_evaluation_run_by_id, merge_scores_step_forward, - resolve_evaluation_config, save_score, - sort_traces_by_question_id, ) from app.crud.evaluations import ( create_evaluation_run as _create_evaluation_run, ) -from app.crud.evaluations.core import update_evaluation_run from app.crud.evaluations.merge import apply_cosine_breakdown from app.crud.evaluations.score import ( CategoryMetrics, ) from app.models.evaluation import ( EvaluationRun, - EvaluationRunUpdate, RunModeEnum, TraceData, ) -from app.models.llm.constants import CompletionType -from app.services.llm.providers import LLMProvider from app.utils import get_langfuse_client logger = logging.getLogger(__name__) # Error code surfaced in HTTPException.detail when a run_name collides with the -# (organization_id, project_id, run_name) unique constraint. Shared by the batch -# and fast paths so both return an identical 409 contract. +# (organization_id, project_id, run_name) unique constraint. ERR_RUN_NAME_ALREADY_EXISTS = "run_name_already_exists" # Name of the (organization_id, project_id, run_name) unique constraint on @@ -52,16 +42,6 @@ # other IntegrityError (e.g. FK violations), which must not be masked. _RUN_NAME_UNIQUE_CONSTRAINT = "uq_evaluation_run_org_project_run_name" -# Providers whose configs can run through the async batch evaluation path. -# Mirrors app.services.assessment.service._SUPPORTED_BATCH_PROVIDERS — the -# native variants forward raw params but still submit via the same batch API. -_SUPPORTED_BATCH_PROVIDERS = { - LLMProvider.OPENAI, - LLMProvider.OPENAI_NATIVE, - LLMProvider.GOOGLE_AISTUDIO, - LLMProvider.GOOGLE_AISTUDIO_NATIVE, -} - def _is_run_name_conflict(error: IntegrityError) -> bool: """True only when the IntegrityError is the run_name uniqueness violation.""" @@ -85,7 +65,7 @@ def create_evaluation_run( config_version: int, organization_id: int, project_id: int, - run_mode: RunModeEnum = RunModeEnum.BATCH, + run_mode: RunModeEnum = RunModeEnum.FAST, is_judge_run: bool = False, callback_url: str | None = None, duplication_factor: int | None = None, @@ -98,10 +78,6 @@ def create_evaluation_run( The (organization_id, project_id, run_name) unique constraint guards against double-click / client-retry races; on collision we roll back and raise 409 if the run_name already exists for this organization and project. - - The v2-only params (is_judge_run, callback_url, duplication_factor, total_items, - status) are passed straight through and default to the v1 no-op values, so - existing batch callers need no change. """ try: return _create_evaluation_run( @@ -224,157 +200,6 @@ def _attach_category_metrics( return score -def validate_and_start_batch_evaluation( - session: Session, - dataset_id: int, - experiment_name: str, - config_id: UUID, - config_version: int, - organization_id: int, - project_id: int, -) -> EvaluationRun: - """ - Start an evaluation run. - - Steps: - 1. Validate dataset exists and has Langfuse ID - 2. Resolve config from stored config management - 3. Check the config provider is supported for batch evaluation - 4. Check the config type is 'text' - 5. Create evaluation run record - 6. Start batch processing - - Args: - session: Database session - dataset_id: ID of the evaluation dataset - experiment_name: Name for this evaluation experiment/run - config_id: UUID of the stored config - config_version: Version number of the config - organization_id: Organization ID - project_id: Project ID - - Returns: - EvaluationRun instance - - Raises: - HTTPException: If dataset not found, config invalid, or evaluation fails to start - """ - logger.info( - f"[validate_and_start_batch_evaluation] Starting evaluation | experiment_name={experiment_name} | " - f"dataset_id={dataset_id} | " - f"org_id={organization_id} | " - f"config_id={config_id} | " - f"config_version={config_version}" - ) - - # Step 1: Fetch dataset from database - dataset = get_dataset_by_id( - session=session, - dataset_id=dataset_id, - organization_id=organization_id, - project_id=project_id, - ) - - if not dataset: - raise HTTPException( - status_code=404, - detail=f"Dataset {dataset_id} not found or not accessible to this " - f"organization/project", - ) - - logger.info( - f"[validate_and_start_batch_evaluation] Found dataset | id={dataset.id} | name={dataset.name} | " - f"object_store_url={'present' if dataset.object_store_url else 'None'} | " - f"langfuse_id={dataset.langfuse_dataset_id}" - ) - - if not dataset.langfuse_dataset_id: - raise HTTPException( - status_code=400, - detail=f"Dataset {dataset_id} does not have a Langfuse dataset ID. " - "Please ensure Langfuse credentials were configured when the dataset was created.", - ) - - # Step 2: Resolve config from stored config management - config, error = resolve_evaluation_config( - session=session, - config_id=config_id, - config_version=config_version, - project_id=project_id, - ) - if error or config is None: - raise HTTPException( - status_code=400, - detail=f"Failed to resolve config from stored config: {error}", - ) - elif config.completion.provider not in _SUPPORTED_BATCH_PROVIDERS: - raise HTTPException( - status_code=422, - detail=( - f"Provider '{config.completion.provider}' is not supported for " - f"evaluation configs. Supported providers: " - f"{sorted(_SUPPORTED_BATCH_PROVIDERS)}" - ), - ) - - if config.completion.type != CompletionType.TEXT: - raise HTTPException( - status_code=422, - detail=( - f"Config type '{config.completion.type}' is not supported for " - f"evaluation configs. Only '{CompletionType.TEXT.value}' type is supported." - ), - ) - - logger.info( - "[validate_and_start_batch_evaluation] Successfully resolved config from config management" - ) - - # Step 3: Create EvaluationRun record with config references - eval_run = create_evaluation_run( - session=session, - run_name=experiment_name, - dataset_name=dataset.name, - dataset_id=dataset_id, - config_id=config_id, - config_version=config_version, - organization_id=organization_id, - project_id=project_id, - log_context="validate_and_start_batch_evaluation", - ) - - # Step 4: Queue the batch submission for asynchronous processing - trace_id = correlation_id.get() or "N/A" - try: - celery_task_id = start_evaluation_batch_submission( - project_id=project_id, - job_id=str(eval_run.id), - trace_id=trace_id, - organization_id=organization_id, - config_id=str(config_id), - config_version=config_version, - ) - logger.info( - f"[validate_and_start_batch_evaluation] Batch submission queued | " - f"run_id={eval_run.id} | celery_task_id={celery_task_id}" - ) - return eval_run - except Exception as e: - logger.error( - f"[validate_and_start_batch_evaluation] Failed to queue batch submission | run_id={eval_run.id} | {e}", - exc_info=True, - ) - eval_run = update_evaluation_run( - session=session, - eval_run=eval_run, - update=EvaluationRunUpdate( - status="failed", - error_message=f"Failed to queue batch submission: {e}", - ), - ) - return eval_run - - def _load_cached_traces( session: Session, project_id: int, diff --git a/backend/app/services/evaluations/fast.py b/backend/app/services/evaluations/fast.py index 57ed337f3..266e6063c 100644 --- a/backend/app/services/evaluations/fast.py +++ b/backend/app/services/evaluations/fast.py @@ -25,7 +25,6 @@ resolve_evaluation_config, run_fast_evaluation, ) -from app.crud.evaluations.batch import fetch_dataset_items from app.crud.evaluations.core import update_evaluation_run from app.crud.evaluations.dataset import ( DATASET_META_DUPLICATION_FACTOR, @@ -33,6 +32,7 @@ download_csv_from_object_store, ) from app.crud.evaluations.fast import run_response_chunk +from app.crud.evaluations.langfuse import fetch_dataset_items from app.crud.evaluations.score import DEFAULT_CATEGORY from app.models.evaluation import ( EvaluationDataset, diff --git a/backend/app/tests/api/routes/test_evaluation.py b/backend/app/tests/api/routes/test_evaluation.py index 51e3c4686..0abf125a5 100644 --- a/backend/app/tests/api/routes/test_evaluation.py +++ b/backend/app/tests/api/routes/test_evaluation.py @@ -1,1175 +1,18 @@ -import io -from typing import Any -from unittest.mock import MagicMock, Mock, patch -from uuid import uuid4 +from unittest.mock import patch import pytest from fastapi.testclient import TestClient -from sqlmodel import Session, select +from sqlmodel import Session -from app.core.util import now -from app.crud.evaluations.batch import ( - build_google_evaluation_jsonl, - build_openai_evaluation_jsonl, - start_evaluation_batch, -) from app.crud.evaluations.core import create_evaluation_run from app.models import ( - BatchJob, EvaluationDataset, EvaluationRun, - Organization, - Project, ) -from app.models.batch_job import BatchJobType from app.tests.utils.auth import TestAuthContext from app.tests.utils.test_data import create_test_config, create_test_evaluation_dataset -# Helper function to create CSV file-like object -def create_csv_file(content: str) -> tuple[str, io.BytesIO]: - """Create a CSV file-like object for testing.""" - file_obj = io.BytesIO(content.encode("utf-8")) - return ("test.csv", file_obj) - - -@pytest.fixture -def valid_csv_content() -> str: - """Valid CSV content with question and answer columns.""" - return """question,answer -"Who is known as the strongest jujutsu sorcerer?","Satoru Gojo" -"What is the name of Gojo's Domain Expansion?","Infinite Void" -"Who is known as the King of Curses?","Ryomen Sukuna" -""" - - -@pytest.fixture -def invalid_csv_missing_columns() -> str: - """CSV content missing required columns.""" - return """query,response -"Who is known as the strongest jujutsu sorcerer?","Satoru Gojo" -""" - - -@pytest.fixture -def csv_with_empty_rows() -> str: - """CSV content with some empty rows.""" - return """question,answer -"Who is known as the strongest jujutsu sorcerer?","Satoru Gojo" -"","4" -"Who wrote Romeo and Juliet?","" -"Valid question","Valid answer" -""" - - -class TestDatasetUploadValidation: - """Test CSV validation and parsing.""" - - def test_upload_dataset_valid_csv( - self, - client: TestClient, - user_api_key_header: dict[str, str], - valid_csv_content: str, - db: Session, - ) -> None: - """Test uploading a valid CSV file.""" - with ( - patch("app.core.cloud.get_cloud_storage") as _mock_storage, - patch( - "app.services.evaluations.dataset.upload_csv_to_object_store" - ) as mock_store_upload, - patch( - "app.services.evaluations.dataset.get_langfuse_client" - ) as mock_get_langfuse_client, - patch( - "app.services.evaluations.dataset.upload_dataset_to_langfuse" - ) as mock_langfuse_upload, - ): - mock_store_upload.return_value = "s3://bucket/datasets/test_dataset.csv" - - mock_get_langfuse_client.return_value = Mock() - - mock_langfuse_upload.return_value = ("test_dataset_id", 9) - - filename, file_obj = create_csv_file(valid_csv_content) - - response = client.post( - "/api/v1/evaluations/datasets", - files={"file": (filename, file_obj, "text/csv")}, - data={ - "dataset_name": "test_dataset", - "description": "Test dataset description", - "duplication_factor": 3, - }, - headers=user_api_key_header, - ) - - assert response.status_code == 200, response.text - response_data = response.json() - assert response_data["success"] is True - data = response_data["data"] - - assert data["dataset_name"] == "test_dataset" - assert data["original_items"] == 3 - assert data["total_items"] == 9 # 3 items * 3 duplication - assert data["duplication_factor"] == 3 - assert data["langfuse_dataset_id"] == "test_dataset_id" - assert data["object_store_url"] == "s3://bucket/datasets/test_dataset.csv" - assert "dataset_id" in data - - # Verify object store upload was called - mock_store_upload.assert_called_once() - - mock_langfuse_upload.assert_called_once() - - def test_upload_dataset_missing_columns( - self, - client: TestClient, - user_api_key_header: dict[str, str], - invalid_csv_missing_columns: str, - ) -> None: - """Test uploading CSV with missing required columns.""" - filename, file_obj = create_csv_file(invalid_csv_missing_columns) - - # The CSV validation happens before any mocked functions are called - # so this test checks the actual validation logic - response = client.post( - "/api/v1/evaluations/datasets", - files={"file": (filename, file_obj, "text/csv")}, - data={ - "dataset_name": "test_dataset", - "duplication_factor": 5, - }, - headers=user_api_key_header, - ) - - assert response.status_code == 422 - response_data = response.json() - error_str = response_data.get( - "detail", response_data.get("message", str(response_data)) - ) - assert "question" in error_str.lower() or "answer" in error_str.lower() - - def test_upload_dataset_empty_rows( - self, - client: TestClient, - user_api_key_header: dict[str, str], - csv_with_empty_rows: str, - ) -> None: - """Test uploading CSV with empty rows (should skip them).""" - with ( - patch("app.core.cloud.get_cloud_storage") as _mock_storage, - patch( - "app.services.evaluations.dataset.upload_csv_to_object_store" - ) as mock_store_upload, - patch( - "app.services.evaluations.dataset.get_langfuse_client" - ) as mock_get_langfuse_client, - patch( - "app.services.evaluations.dataset.upload_dataset_to_langfuse" - ) as mock_langfuse_upload, - ): - mock_store_upload.return_value = "s3://bucket/datasets/test_dataset.csv" - mock_get_langfuse_client.return_value = Mock() - mock_langfuse_upload.return_value = ("test_dataset_id", 4) - - filename, file_obj = create_csv_file(csv_with_empty_rows) - - response = client.post( - "/api/v1/evaluations/datasets", - files={"file": (filename, file_obj, "text/csv")}, - data={ - "dataset_name": "test_dataset", - "duplication_factor": 2, - }, - headers=user_api_key_header, - ) - - assert response.status_code == 200, response.text - response_data = response.json() - assert response_data["success"] is True - data = response_data["data"] - - # Should only have 2 valid items (first and last rows) - assert data["original_items"] == 2 - assert data["total_items"] == 4 # 2 items * 2 duplication - - -class TestDatasetUploadDuplication: - """Test duplication logic.""" - - def test_upload_with_default_duplication( - self, - client: TestClient, - user_api_key_header: dict[str, str], - valid_csv_content: str, - ) -> None: - """Test uploading with default duplication factor (1).""" - with ( - patch("app.core.cloud.get_cloud_storage") as _mock_storage, - patch( - "app.services.evaluations.dataset.upload_csv_to_object_store" - ) as mock_store_upload, - patch( - "app.services.evaluations.dataset.get_langfuse_client" - ) as mock_get_langfuse_client, - patch( - "app.services.evaluations.dataset.upload_dataset_to_langfuse" - ) as mock_langfuse_upload, - ): - mock_store_upload.return_value = "s3://bucket/datasets/test_dataset.csv" - mock_get_langfuse_client.return_value = Mock() - mock_langfuse_upload.return_value = ("test_dataset_id", 3) - - filename, file_obj = create_csv_file(valid_csv_content) - - response = client.post( - "/api/v1/evaluations/datasets", - files={"file": (filename, file_obj, "text/csv")}, - data={ - "dataset_name": "test_dataset", - # duplication_factor not provided, would default to 1 - }, - headers=user_api_key_header, - ) - - assert response.status_code == 200, response.text - response_data = response.json() - assert response_data["success"] is True - data = response_data["data"] - - assert data["duplication_factor"] == 1 - assert data["original_items"] == 3 - assert data["total_items"] == 3 - - def test_upload_with_custom_duplication( - self, - client: TestClient, - user_api_key_header: dict[str, str], - valid_csv_content: str, - ) -> None: - """Test uploading with custom duplication factor.""" - with ( - patch("app.core.cloud.get_cloud_storage") as _mock_storage, - patch( - "app.services.evaluations.dataset.upload_csv_to_object_store" - ) as mock_store_upload, - patch( - "app.services.evaluations.dataset.get_langfuse_client" - ) as mock_get_langfuse_client, - patch( - "app.services.evaluations.dataset.upload_dataset_to_langfuse" - ) as mock_langfuse_upload, - ): - mock_store_upload.return_value = "s3://bucket/datasets/test_dataset.csv" - mock_get_langfuse_client.return_value = Mock() - mock_langfuse_upload.return_value = ("test_dataset_id", 12) - - filename, file_obj = create_csv_file(valid_csv_content) - - response = client.post( - "/api/v1/evaluations/datasets", - files={"file": (filename, file_obj, "text/csv")}, - data={ - "dataset_name": "test_dataset", - "duplication_factor": 4, - }, - headers=user_api_key_header, - ) - - assert response.status_code == 200, response.text - response_data = response.json() - assert response_data["success"] is True - data = response_data["data"] - - assert data["duplication_factor"] == 4 - assert data["original_items"] == 3 - assert data["total_items"] == 12 # 3 items * 4 duplication - - def test_upload_with_description( - self, - client: TestClient, - user_api_key_header: dict[str, str], - valid_csv_content: str, - db: Session, - ) -> None: - """Test uploading with a description.""" - with ( - patch("app.core.cloud.get_cloud_storage") as _mock_storage, - patch( - "app.services.evaluations.dataset.upload_csv_to_object_store" - ) as mock_store_upload, - patch( - "app.services.evaluations.dataset.get_langfuse_client" - ) as mock_get_langfuse_client, - patch( - "app.services.evaluations.dataset.upload_dataset_to_langfuse" - ) as mock_langfuse_upload, - ): - mock_store_upload.return_value = "s3://bucket/datasets/test_dataset.csv" - mock_get_langfuse_client.return_value = Mock() - mock_langfuse_upload.return_value = ("test_dataset_id", 9) - - filename, file_obj = create_csv_file(valid_csv_content) - - response = client.post( - "/api/v1/evaluations/datasets", - files={"file": (filename, file_obj, "text/csv")}, - data={ - "dataset_name": "test_dataset_with_description", - "description": "This is a test dataset for evaluation", - "duplication_factor": 3, - }, - headers=user_api_key_header, - ) - - assert response.status_code == 200, response.text - response_data = response.json() - assert response_data["success"] is True - data = response_data["data"] - - # Verify the description is stored - dataset = db.exec( - select(EvaluationDataset).where( - EvaluationDataset.id == data["dataset_id"] - ) - ).first() - - assert dataset is not None - assert dataset.description == "This is a test dataset for evaluation" - - def test_upload_with_duplication_factor_below_minimum( - self, - client: TestClient, - user_api_key_header: dict[str, str], - valid_csv_content: str, - ) -> None: - """Test uploading with duplication factor below minimum (0).""" - filename, file_obj = create_csv_file(valid_csv_content) - - response = client.post( - "/api/v1/evaluations/datasets", - files={"file": (filename, file_obj, "text/csv")}, - data={ - "dataset_name": "test_dataset", - "duplication_factor": 0, - }, - headers=user_api_key_header, - ) - - assert response.status_code == 422 - response_data = response.json() - assert response_data["errors"] - assert any( - "greater than or equal to 1" in e["message"] - for e in response_data["errors"] - ) - - def test_upload_with_duplication_factor_above_maximum( - self, - client: TestClient, - user_api_key_header: dict[str, str], - valid_csv_content: str, - ) -> None: - """Test uploading with duplication factor above maximum (6).""" - filename, file_obj = create_csv_file(valid_csv_content) - - response = client.post( - "/api/v1/evaluations/datasets", - files={"file": (filename, file_obj, "text/csv")}, - data={ - "dataset_name": "test_dataset", - "duplication_factor": 6, - }, - headers=user_api_key_header, - ) - - assert response.status_code == 422 - response_data = response.json() - assert response_data["errors"] - assert any( - "less than or equal to 5" in e["message"] for e in response_data["errors"] - ) - - def test_upload_with_duplication_factor_boundary_minimum( - self, - client: TestClient, - user_api_key_header: dict[str, str], - valid_csv_content: str, - ) -> None: - """Test uploading with duplication factor at minimum boundary (1).""" - with ( - patch("app.core.cloud.get_cloud_storage") as _mock_storage, - patch( - "app.services.evaluations.dataset.upload_csv_to_object_store" - ) as mock_store_upload, - patch( - "app.services.evaluations.dataset.get_langfuse_client" - ) as mock_get_langfuse_client, - patch( - "app.services.evaluations.dataset.upload_dataset_to_langfuse" - ) as mock_langfuse_upload, - ): - mock_store_upload.return_value = "s3://bucket/datasets/test_dataset.csv" - mock_get_langfuse_client.return_value = Mock() - mock_langfuse_upload.return_value = ("test_dataset_id", 3) - - filename, file_obj = create_csv_file(valid_csv_content) - - response = client.post( - "/api/v1/evaluations/datasets", - files={"file": (filename, file_obj, "text/csv")}, - data={ - "dataset_name": "test_dataset", - "duplication_factor": 1, - }, - headers=user_api_key_header, - ) - - assert response.status_code == 200, response.text - response_data = response.json() - assert response_data["success"] is True - data = response_data["data"] - - assert data["duplication_factor"] == 1 - assert data["original_items"] == 3 - assert data["total_items"] == 3 - - -class TestDatasetUploadErrors: - """Test error handling.""" - - def test_upload_returns_500_when_langfuse_upload_raises( - self, - client: TestClient, - user_api_key_header: dict[str, str], - valid_csv_content: str, - ) -> None: - """Tracing enabled but the Langfuse upload fails → 500.""" - with ( - patch("app.core.cloud.get_cloud_storage") as _mock_storage, - patch( - "app.services.evaluations.dataset.upload_csv_to_object_store" - ) as mock_store_upload, - patch( - "app.services.evaluations.dataset.get_langfuse_client" - ) as mock_get_langfuse_client, - patch( - "app.services.evaluations.dataset.upload_dataset_to_langfuse" - ) as mock_langfuse_upload, - ): - mock_store_upload.return_value = "s3://bucket/datasets/test_dataset.csv" - mock_get_langfuse_client.return_value = Mock() - mock_langfuse_upload.side_effect = Exception("Langfuse down") - - filename, file_obj = create_csv_file(valid_csv_content) - - response = client.post( - "/api/v1/evaluations/datasets", - files={"file": (filename, file_obj, "text/csv")}, - data={ - "dataset_name": "test_dataset", - "duplication_factor": 3, - }, - headers=user_api_key_header, - ) - - assert response.status_code == 500, response.text - response_data = response.json() - error_str = response_data.get( - "detail", response_data.get("error", str(response_data)) - ) - assert "Failed to upload dataset to Langfuse" in str(error_str) - - def test_upload_invalid_csv_format( - self, client: TestClient, user_api_key_header: dict[str, str] - ) -> None: - """Test uploading invalid CSV format.""" - invalid_csv = "not,a,valid\ncsv format here!!!" - filename, file_obj = create_csv_file(invalid_csv) - - response = client.post( - "/api/v1/evaluations/datasets", - files={"file": (filename, file_obj, "text/csv")}, - data={ - "dataset_name": "test_dataset", - "duplication_factor": 5, - }, - headers=user_api_key_header, - ) - - # Should fail validation - check error contains expected message - assert response.status_code == 422 - response_data = response.json() - error_str = response_data.get( - "detail", response_data.get("message", str(response_data)) - ) - assert ( - "question" in error_str.lower() - or "answer" in error_str.lower() - or "invalid" in error_str.lower() - ) - - def test_upload_without_authentication(self, client, valid_csv_content): - """Test uploading without authentication.""" - filename, file_obj = create_csv_file(valid_csv_content) - - response = client.post( - "/api/v1/evaluations/datasets", - files={"file": (filename, file_obj, "text/csv")}, - data={ - "dataset_name": "test_dataset", - "duplication_factor": 5, - }, - ) - - assert response.status_code == 401 # Unauthorized - - -class TestBatchEvaluation: - """Test batch evaluation endpoint using OpenAI Batch API.""" - - @pytest.fixture - def sample_evaluation_config(self) -> dict[str, Any]: - """Sample evaluation configuration.""" - return { - "model": "gpt-4o", - "temperature": 0.2, - "instructions": "You are a helpful assistant", - } - - def test_start_batch_evaluation_invalid_dataset_id( - self, - client: TestClient, - user_api_key_header: dict[str, str], - db: Session, - user_api_key: TestAuthContext, - ) -> None: - """Test batch evaluation fails with invalid dataset_id.""" - # Create a valid config to use - config = create_test_config(db, project_id=user_api_key.project_id) - - # Try to start evaluation with non-existent dataset_id - response = client.post( - "/api/v1/evaluations", - json={ - "experiment_name": "test_evaluation_run", - "dataset_id": 99999, # Non-existent - "config_id": str(config.id), - "config_version": 1, - }, - headers=user_api_key_header, - ) - - assert response.status_code == 404 - response_data = response.json() - error_str = response_data.get( - "detail", response_data.get("message", str(response_data)) - ) - assert "not found" in error_str.lower() or "not accessible" in error_str.lower() - - def test_start_batch_evaluation_invalid_config_id( - self, client: TestClient, user_api_key_header: dict[str, str] - ) -> None: - """Test batch evaluation fails with invalid config_id.""" - # Test with a non-existent config_id (random UUID) - response = client.post( - "/api/v1/evaluations", - json={ - "experiment_name": "test_no_config", - "dataset_id": 1, # Dummy ID, config validation happens first - "config_id": str(uuid4()), # Non-existent config - "config_version": 1, - }, - headers=user_api_key_header, - ) - - # Should fail with either 400 (config not found) or 404 (dataset/config not found) - assert response.status_code in [400, 404] - response_data = response.json() - error_str = response_data.get( - "detail", response_data.get("message", str(response_data)) - ) - # Should mention config or not found - assert "config" in error_str.lower() or "not found" in error_str.lower() - - def test_start_batch_evaluation_without_authentication( - self, client, sample_evaluation_config - ): - """Test batch evaluation requires authentication.""" - response = client.post( - "/api/v1/evaluations", - json={ - "experiment_name": "test_evaluation_run", - "dataset_id": 1, - "config": sample_evaluation_config, - }, - ) - - assert response.status_code == 401 # Unauthorized - - -class TestBatchEvaluationJSONLBuilding: - """Test JSONL building logic for batch evaluation. - - ``build_openai_evaluation_jsonl`` wraps an already-mapped ``openai_params`` - dict (the output of ``map_kaapi_to_openai_params``) into Responses API batch - lines: ``body`` is the params dict plus the per-item ``input``. Param shaping - (temperature inclusion, knowledge_base_ids -> tools) is the mapper's job and - is covered in tests/services/llm/test_mappers.py, so these tests pass plain - pre-mapped dicts and assert faithful pass-through. - """ - - def test_build_batch_jsonl_basic(self) -> None: - """Test basic JSONL building with a fully populated params dict.""" - dataset_items = [ - { - "id": "item1", - "input": {"question": "What is 2+2?"}, - "expected_output": {"answer": "4"}, - "metadata": {}, - } - ] - - openai_params = { - "model": "gpt-4o", - "temperature": 0.2, - "instructions": "You are a helpful assistant", - } - - jsonl_data = build_openai_evaluation_jsonl(dataset_items, openai_params) - - assert len(jsonl_data) == 1 - assert isinstance(jsonl_data[0], dict) - - request = jsonl_data[0] - assert request["custom_id"] == "item1" - assert request["method"] == "POST" - assert request["url"] == "/v1/responses" - assert request["body"]["model"] == "gpt-4o" - assert request["body"]["temperature"] == 0.2 - assert request["body"]["instructions"] == "You are a helpful assistant" - assert request["body"]["input"] == "What is 2+2?" - - def test_build_batch_jsonl_with_tools(self) -> None: - """Tools present in the params dict are passed through to the body.""" - dataset_items = [ - { - "id": "item1", - "input": {"question": "Search the docs"}, - "expected_output": {"answer": "Answer from docs"}, - "metadata": {}, - } - ] - - openai_params = { - "model": "gpt-4o-mini", - "instructions": "Search documents", - "tools": [ - { - "type": "file_search", - "vector_store_ids": ["vs_abc123"], - "max_num_results": 20, - } - ], - } - - jsonl_data = build_openai_evaluation_jsonl(dataset_items, openai_params) - - assert len(jsonl_data) == 1 - request = jsonl_data[0] - assert request["body"]["tools"][0]["type"] == "file_search" - assert "vs_abc123" in request["body"]["tools"][0]["vector_store_ids"] - - def test_build_batch_jsonl_minimal_config(self) -> None: - """Test JSONL building with minimal params (only model).""" - dataset_items = [ - { - "id": "item1", - "input": {"question": "Test question"}, - "expected_output": {"answer": "Test answer"}, - "metadata": {}, - } - ] - - openai_params = {"model": "gpt-4o"} - - jsonl_data = build_openai_evaluation_jsonl(dataset_items, openai_params) - - assert len(jsonl_data) == 1 - request = jsonl_data[0] - assert request["body"]["model"] == "gpt-4o" - assert request["body"]["input"] == "Test question" - - def test_build_batch_jsonl_skips_empty_questions(self) -> None: - """Test that items with empty questions are skipped.""" - dataset_items = [ - { - "id": "item1", - "input": {"question": "Valid question"}, - "expected_output": {"answer": "Answer"}, - "metadata": {}, - }, - { - "id": "item2", - "input": {"question": ""}, # Empty question - "expected_output": {"answer": "Answer"}, - "metadata": {}, - }, - { - "id": "item3", - "input": {}, # Missing question key - "expected_output": {"answer": "Answer"}, - "metadata": {}, - }, - ] - - openai_params = {"model": "gpt-4o", "instructions": "Test"} - - jsonl_data = build_openai_evaluation_jsonl(dataset_items, openai_params) - - # Should only have 1 valid item - assert len(jsonl_data) == 1 - assert jsonl_data[0]["custom_id"] == "item1" - - def test_build_batch_jsonl_multiple_items(self) -> None: - """Test JSONL building with multiple items.""" - dataset_items = [ - { - "id": f"item{i}", - "input": {"question": f"Question {i}"}, - "expected_output": {"answer": f"Answer {i}"}, - "metadata": {}, - } - for i in range(5) - ] - - openai_params = { - "model": "gpt-4o", - "instructions": "Answer questions", - } - - jsonl_data = build_openai_evaluation_jsonl(dataset_items, openai_params) - - assert len(jsonl_data) == 5 - - for i, request_dict in enumerate(jsonl_data): - assert request_dict["custom_id"] == f"item{i}" - assert request_dict["body"]["input"] == f"Question {i}" - assert request_dict["body"]["model"] == "gpt-4o" - - def test_build_batch_jsonl_temperature_included_when_explicitly_set(self) -> None: - """A temperature present in the params dict appears in the JSONL body.""" - dataset_items = [ - { - "id": "item1", - "input": {"question": "Test question"}, - "expected_output": {"answer": "Test answer"}, - "metadata": {}, - } - ] - - openai_params = {"model": "gpt-4o", "temperature": 0.5} - - jsonl_data = build_openai_evaluation_jsonl(dataset_items, openai_params) - - assert len(jsonl_data) == 1 - assert "temperature" in jsonl_data[0]["body"] - assert jsonl_data[0]["body"]["temperature"] == 0.5 - - def test_build_batch_jsonl_temperature_excluded_when_not_set(self) -> None: - """A temperature absent from the params dict stays absent from the body.""" - dataset_items = [ - { - "id": "item1", - "input": {"question": "Test question"}, - "expected_output": {"answer": "Test answer"}, - "metadata": {}, - } - ] - - # Mapper omits temperature when it was never set, so it isn't in the dict. - openai_params = {"model": "gpt-4o"} - - jsonl_data = build_openai_evaluation_jsonl(dataset_items, openai_params) - - assert len(jsonl_data) == 1 - assert "temperature" not in jsonl_data[0]["body"] - - def test_build_batch_jsonl_temperature_zero_included_when_explicitly_set( - self, - ) -> None: - """A temperature of 0.0 in the params dict is preserved in the body.""" - dataset_items = [ - { - "id": "item1", - "input": {"question": "Test question"}, - "expected_output": {"answer": "Test answer"}, - "metadata": {}, - } - ] - - openai_params = {"model": "gpt-4o", "temperature": 0.0} - - jsonl_data = build_openai_evaluation_jsonl(dataset_items, openai_params) - - assert len(jsonl_data) == 1 - assert "temperature" in jsonl_data[0]["body"] - assert jsonl_data[0]["body"]["temperature"] == 0.0 - - -class TestBuildGoogleEvaluationJSONL: - """Test JSONL building for Gemini batch evaluation. - - ``build_google_evaluation_jsonl`` wraps an already-mapped ``google_params`` - dict (output of ``map_kaapi_to_google_params``) into Gemini batch lines: - ``{"key": , "request": {...}}``. The request always carries the - per-item question in ``contents``; ``instructions``/``temperature``/ - ``reasoning`` are folded into ``systemInstruction``/``generationConfig`` only - when present, so these tests pass pre-mapped dicts and assert that shaping. - """ - - def _items(self, *questions: str) -> list[dict[str, Any]]: - return [ - { - "id": f"item{i}", - "input": {"question": q}, - "expected_output": {"answer": "a"}, - "metadata": {}, - } - for i, q in enumerate(questions) - ] - - def test_basic_question_only(self) -> None: - """A bare params dict produces contents but no system/generation config.""" - jsonl_data = build_google_evaluation_jsonl( - self._items("What is 2+2?"), {"model": "gemini-2.5-pro"} - ) - - assert len(jsonl_data) == 1 - line = jsonl_data[0] - assert line["key"] == "item0" - request = line["request"] - assert request["contents"] == [ - {"parts": [{"text": "What is 2+2?"}], "role": "user"} - ] - assert "systemInstruction" not in request - assert "generationConfig" not in request - - def test_instructions_become_system_instruction(self) -> None: - """``instructions`` are mapped into ``systemInstruction``.""" - jsonl_data = build_google_evaluation_jsonl( - self._items("Q"), - {"model": "gemini-2.5-pro", "instructions": "Be concise"}, - ) - - request = jsonl_data[0]["request"] - assert request["systemInstruction"] == {"parts": [{"text": "Be concise"}]} - - def test_temperature_in_generation_config(self) -> None: - """``temperature`` goes into ``generationConfig``.""" - jsonl_data = build_google_evaluation_jsonl( - self._items("Q"), {"model": "gemini-2.5-pro", "temperature": 0.3} - ) - - assert jsonl_data[0]["request"]["generationConfig"]["temperature"] == 0.3 - - def test_temperature_zero_included(self) -> None: - """A temperature of 0.0 is preserved (not treated as absent).""" - jsonl_data = build_google_evaluation_jsonl( - self._items("Q"), {"model": "gemini-2.5-pro", "temperature": 0.0} - ) - - assert jsonl_data[0]["request"]["generationConfig"]["temperature"] == 0.0 - - def test_reasoning_becomes_thinking_config(self) -> None: - """``reasoning`` is mapped into ``thinkingConfig``.""" - jsonl_data = build_google_evaluation_jsonl( - self._items("Q"), {"model": "gemini-2.5-pro", "reasoning": "high"} - ) - - thinking = jsonl_data[0]["request"]["generationConfig"]["thinkingConfig"] - assert thinking == {"includeThoughts": False, "thinkingLevel": "high"} - - def test_knowledge_base_ids_become_file_search_tool(self) -> None: - """``knowledge_base_ids`` are mapped into the FileSearch tool on every line.""" - jsonl_data = build_google_evaluation_jsonl( - self._items("Q1", "Q2"), - { - "model": "gemini-2.5-pro", - "knowledge_base_ids": ["fileSearchStores/abc123"], - }, - ) - - assert len(jsonl_data) == 2 - for line in jsonl_data: - assert line["request"]["tools"] == [ - {"fileSearch": {"fileSearchStoreNames": ["fileSearchStores/abc123"]}} - ] - - def test_no_knowledge_base_ids_no_tools(self) -> None: - """Without ``knowledge_base_ids`` the request carries no ``tools`` key.""" - jsonl_data = build_google_evaluation_jsonl( - self._items("Q"), {"model": "gemini-2.5-pro"} - ) - - assert "tools" not in jsonl_data[0]["request"] - - def test_full_params(self) -> None: - """All optional fields together populate both config blocks.""" - jsonl_data = build_google_evaluation_jsonl( - self._items("Q"), - { - "model": "gemini-2.5-pro", - "instructions": "sys", - "temperature": 0.7, - "reasoning": "low", - }, - ) - - request = jsonl_data[0]["request"] - assert request["systemInstruction"] == {"parts": [{"text": "sys"}]} - assert request["generationConfig"]["temperature"] == 0.7 - assert request["generationConfig"]["thinkingConfig"]["thinkingLevel"] == "low" - - def test_skips_empty_and_missing_questions(self) -> None: - """Items with empty or missing questions are dropped.""" - dataset_items = [ - { - "id": "ok", - "input": {"question": "Real"}, - "expected_output": {}, - "metadata": {}, - }, - { - "id": "empty", - "input": {"question": ""}, - "expected_output": {}, - "metadata": {}, - }, - {"id": "missing", "input": {}, "expected_output": {}, "metadata": {}}, - ] - - jsonl_data = build_google_evaluation_jsonl( - dataset_items, {"model": "gemini-2.5-pro"} - ) - - assert len(jsonl_data) == 1 - assert jsonl_data[0]["key"] == "ok" - - def test_multiple_items(self) -> None: - """Each item yields one line keyed by its id.""" - jsonl_data = build_google_evaluation_jsonl( - self._items("Q0", "Q1", "Q2"), {"model": "gemini-2.5-pro"} - ) - - assert [line["key"] for line in jsonl_data] == ["item0", "item1", "item2"] - assert jsonl_data[1]["request"]["contents"][0]["parts"][0]["text"] == "Q1" - - -_BATCH_DATASET_ITEMS = [ - { - "id": "item1", - "input": {"question": "What is 2+2?"}, - "expected_output": {"answer": "4"}, - "metadata": {}, - } -] - - -class TestStartEvaluationBatch: - """Test start_evaluation_batch, the provider-dispatching orchestrator.""" - - @pytest.fixture - def eval_run(self, db: Session) -> EvaluationRun: - """A persisted EvaluationRun in the default (pending) state.""" - org = db.exec(select(Organization)).first() - project = db.exec( - select(Project).where(Project.organization_id == org.id) - ).first() - dataset = create_test_evaluation_dataset( - db=db, - organization_id=org.id, - project_id=project.id, - name="test_dataset_start_batch", - description="Test dataset", - original_items_count=1, - duplication_factor=1, - ) - config = create_test_config(db, project_id=project.id, use_kaapi_schema=True) - return create_evaluation_run( - session=db, - run_name="start_batch_run", - dataset_name=dataset.name, - dataset_id=dataset.id, - config_id=config.id, - config_version=1, - organization_id=org.id, - project_id=project.id, - ) - - def _make_batch_job( - self, db: Session, eval_run: EvaluationRun, provider: str - ) -> BatchJob: - """Persist a BatchJob to stand in for start_batch_job's return value.""" - batch_job = BatchJob( - provider=provider, - provider_batch_id="batch_xyz", - provider_status="submitted", - job_type=BatchJobType.EVALUATION, - total_items=1, - status="submitted", - organization_id=eval_run.organization_id, - project_id=eval_run.project_id, - inserted_at=now(), - updated_at=now(), - ) - db.add(batch_job) - db.commit() - db.refresh(batch_job) - return batch_job - - @patch("app.crud.evaluations.batch.start_batch_job") - @patch("app.crud.evaluations.batch.OpenAIBatchProvider") - @patch("app.crud.evaluations.batch.get_openai_client") - @patch("app.crud.evaluations.batch.map_kaapi_to_openai_params") - @patch("app.crud.evaluations.batch.fetch_dataset_items") - def test_openai_branch( - self, - mock_fetch, - mock_map, - mock_get_client, - mock_provider_cls, - mock_start_batch, - db: Session, - eval_run: EvaluationRun, - ) -> None: - mock_fetch.return_value = _BATCH_DATASET_ITEMS - mock_map.return_value = ({"model": "gpt-4o"}, []) - batch_job = self._make_batch_job(db, eval_run, "openai") - mock_start_batch.return_value = batch_job - - result = start_evaluation_batch( - langfuse=MagicMock(), - session=db, - eval_run=eval_run, - params={"model": "gpt-4o"}, - provider="openai", - ) - - assert result.status == "processing" - assert result.batch_job_id == batch_job.id - assert result.total_items == 1 - assert mock_start_batch.call_args.kwargs["provider_name"] == "openai" - mock_get_client.assert_called_once() - - @patch("app.crud.evaluations.batch.start_batch_job") - @patch("app.crud.evaluations.batch.OpenAIBatchProvider") - @patch("app.crud.evaluations.batch.get_openai_client") - @patch("app.crud.evaluations.batch.map_kaapi_to_openai_params") - @patch("app.crud.evaluations.batch.fetch_dataset_items") - def test_native_suffix_resolves_to_base_provider( - self, - mock_fetch, - mock_map, - mock_get_client, - mock_provider_cls, - mock_start_batch, - db: Session, - eval_run: EvaluationRun, - ) -> None: - """An 'openai-native' provider runs through the OpenAI branch.""" - mock_fetch.return_value = _BATCH_DATASET_ITEMS - mock_map.return_value = ({"model": "gpt-4o"}, ["warn"]) - mock_start_batch.return_value = self._make_batch_job(db, eval_run, "openai") - - result = start_evaluation_batch( - langfuse=MagicMock(), - session=db, - eval_run=eval_run, - params={"model": "gpt-4o"}, - provider="openai-native", - ) - - assert result.status == "processing" - assert mock_start_batch.call_args.kwargs["provider_name"] == "openai" - - @patch("app.crud.evaluations.batch.start_batch_job") - @patch("app.crud.evaluations.batch.GeminiBatchProvider") - @patch("app.crud.evaluations.batch.GeminiClient") - @patch("app.crud.evaluations.batch.map_kaapi_to_google_params") - @patch("app.crud.evaluations.batch.fetch_dataset_items") - def test_google_branch( - self, - mock_fetch, - mock_map, - mock_gemini_client, - mock_provider_cls, - mock_start_batch, - db: Session, - eval_run: EvaluationRun, - ) -> None: - mock_fetch.return_value = _BATCH_DATASET_ITEMS - mock_map.return_value = ({"model": "gemini-2.5-pro"}, []) - batch_job = self._make_batch_job(db, eval_run, "google-aistudio") - mock_start_batch.return_value = batch_job - - result = start_evaluation_batch( - langfuse=MagicMock(), - session=db, - eval_run=eval_run, - params={"model": "gemini-2.5-pro"}, - provider="google-aistudio", - ) - - assert result.status == "processing" - assert result.batch_job_id == batch_job.id - assert mock_start_batch.call_args.kwargs["provider_name"] == "google-aistudio" - mock_gemini_client.from_credentials.assert_called_once() - - @patch("app.crud.evaluations.batch.fetch_dataset_items") - def test_unsupported_provider_marks_failed( - self, mock_fetch, db: Session, eval_run: EvaluationRun - ) -> None: - mock_fetch.return_value = _BATCH_DATASET_ITEMS - - with pytest.raises(ValueError, match="Unsupported provider"): - start_evaluation_batch( - langfuse=MagicMock(), - session=db, - eval_run=eval_run, - params={"model": "claude"}, - provider="anthropic", - ) - - db.refresh(eval_run) - assert eval_run.status == "failed" - assert eval_run.error_message - - @patch("app.crud.evaluations.batch.map_kaapi_to_openai_params") - @patch("app.crud.evaluations.batch.fetch_dataset_items") - def test_empty_jsonl_marks_failed( - self, mock_fetch, mock_map, db: Session, eval_run: EvaluationRun - ) -> None: - """No questions in the dataset -> empty JSONL -> failure.""" - mock_fetch.return_value = [ - {"id": "x", "input": {}, "expected_output": {}, "metadata": {}} - ] - mock_map.return_value = ({"model": "gpt-4o"}, []) - - with pytest.raises(ValueError, match="did not produce any JSONL"): - start_evaluation_batch( - langfuse=MagicMock(), - session=db, - eval_run=eval_run, - params={"model": "gpt-4o"}, - provider="openai", - ) - - db.refresh(eval_run) - assert eval_run.status == "failed" - - class TestGetEvaluationRunStatus: """Test GET /evaluations/{evaluation_id} endpoint.""" diff --git a/backend/app/tests/api/routes/test_evaluation_dataset_v2.py b/backend/app/tests/api/routes/test_evaluation_dataset_v2.py index f4e9727a8..61bcddbfa 100644 --- a/backend/app/tests/api/routes/test_evaluation_dataset_v2.py +++ b/backend/app/tests/api/routes/test_evaluation_dataset_v2.py @@ -3,13 +3,12 @@ `POST {API_V2_STR}/evaluations/datasets` — the three-metric SRD's Langfuse-free upload (docs/srd-three-metric-evaluation-verdict.md, FR-19/FR-20): -- FR-19: 200, row created with null langfuse id, CSV stored in S3, Langfuse never - called. +- FR-19: 200, row created with null langfuse id, CSV stored in S3. - FR-20: response + persisted metadata carry the original/total item counts and the stored duplication factor. -Object storage and Langfuse are the external boundaries and are mocked; the -dataset row lands in the real (transactional) DB. +Object storage is the external boundary and is mocked; the dataset row lands in +the real (transactional) DB. """ import io @@ -52,8 +51,6 @@ def test_upload_creates_langfuse_free_dataset( f"{_DATASET}.upload_csv_to_object_store", return_value="s3://bucket/datasets/v2.csv", ) as mock_upload, - patch(f"{_DATASET}.get_langfuse_client") as mock_langfuse_client, - patch(f"{_DATASET}.upload_dataset_to_langfuse") as mock_langfuse_upload, ): resp = client.post( V2_DATASETS, @@ -71,8 +68,6 @@ def test_upload_creates_langfuse_free_dataset( assert body["object_store_url"] == "s3://bucket/datasets/v2.csv" mock_upload.assert_called_once() - mock_langfuse_client.assert_not_called() - mock_langfuse_upload.assert_not_called() persisted = db.get(EvaluationDataset, body["dataset_id"]) assert persisted is not None @@ -96,8 +91,6 @@ def test_upload_defaults_duplication_factor_to_one( f"{_DATASET}.upload_csv_to_object_store", return_value="s3://bucket/datasets/v2.csv", ), - patch(f"{_DATASET}.get_langfuse_client"), - patch(f"{_DATASET}.upload_dataset_to_langfuse"), ): resp = client.post( V2_DATASETS, @@ -117,11 +110,10 @@ def test_object_store_no_url_returns_500( client: TestClient, user_api_key_header: dict[str, str], ) -> None: - """FR-19: with no Langfuse fallback, a failed S3 store is a 500.""" + """FR-19: S3 is the only copy of the items, so a failed store is a 500.""" with ( patch(f"{_DATASET}.get_cloud_storage", return_value=MagicMock()), patch(f"{_DATASET}.upload_csv_to_object_store", return_value=None), - patch(f"{_DATASET}.get_langfuse_client"), ): resp = client.post( V2_DATASETS, @@ -170,3 +162,96 @@ def test_duplication_factor_below_min_rejected( ) assert resp.status_code == 422 + + def test_upload_persists_description( + self, + client: TestClient, + user_api_key_header: dict[str, str], + db: Session, + ) -> None: + with ( + patch(f"{_DATASET}.get_cloud_storage", return_value=MagicMock()), + patch( + f"{_DATASET}.upload_csv_to_object_store", + return_value="s3://bucket/datasets/v2.csv", + ), + ): + resp = client.post( + V2_DATASETS, + files={"file": _csv_upload()}, + data={ + "dataset_name": f"v2-desc-{random_lower_string()}", + "description": "Golden FAQ set", + }, + headers=user_api_key_header, + ) + + assert resp.status_code == 200, resp.text + body = resp.json()["data"] + assert body["description"] == "Golden FAQ set" + persisted = db.get(EvaluationDataset, body["dataset_id"]) + assert persisted is not None + assert persisted.description == "Golden FAQ set" + + def test_upload_skips_rows_missing_question_or_answer( + self, + client: TestClient, + user_api_key_header: dict[str, str], + ) -> None: + csv_text = ( + "question,answer\n" + '"Who is the strongest sorcerer?","Satoru Gojo"\n' + '"","4"\n' + '"Who wrote Romeo and Juliet?",""\n' + '"Valid question","Valid answer"\n' + ) + with ( + patch(f"{_DATASET}.get_cloud_storage", return_value=MagicMock()), + patch( + f"{_DATASET}.upload_csv_to_object_store", + return_value="s3://bucket/datasets/v2.csv", + ), + ): + resp = client.post( + V2_DATASETS, + files={ + "file": ( + "dataset.csv", + io.BytesIO(csv_text.encode("utf-8")), + "text/csv", + ) + }, + data={ + "dataset_name": f"v2-empty-rows-{random_lower_string()}", + "duplication_factor": 2, + }, + headers=user_api_key_header, + ) + + assert resp.status_code == 200, resp.text + body = resp.json()["data"] + assert body["original_items"] == 2 + assert body["total_items"] == 4 + + def test_upload_missing_required_columns_rejected( + self, + client: TestClient, + user_api_key_header: dict[str, str], + ) -> None: + csv_text = 'query,response\n"Who is the strongest sorcerer?","Satoru Gojo"\n' + resp = client.post( + V2_DATASETS, + files={ + "file": ( + "dataset.csv", + io.BytesIO(csv_text.encode("utf-8")), + "text/csv", + ) + }, + data={"dataset_name": f"v2-badcols-{random_lower_string()}"}, + headers=user_api_key_header, + ) + + assert resp.status_code == 422 + error = str(resp.json()).lower() + assert "question" in error or "answer" in error diff --git a/backend/app/tests/api/routes/test_evaluation_fast.py b/backend/app/tests/api/routes/test_evaluation_fast.py index f3f444f31..b05aa3cab 100644 --- a/backend/app/tests/api/routes/test_evaluation_fast.py +++ b/backend/app/tests/api/routes/test_evaluation_fast.py @@ -283,7 +283,7 @@ def __exit__(self, *exc: object) -> bool: return False -# Route validation: POST /evaluations with run_mode=fast (FR-1..FR-5, FR-15) +# Route validation: POST /api/v2/evaluations (FR-1..FR-5, FR-15) @pytest.fixture @@ -309,7 +309,7 @@ def _patch_dispatch() -> Iterator[MagicMock]: class TestFastEvaluationRoute: - """End-to-end validation on POST /evaluations with run_mode='fast'.""" + """End-to-end validation on POST /api/v2/evaluations (always fast).""" def test_fr4_accepts_eligible_request_and_dispatches( self, @@ -324,13 +324,12 @@ def test_fr4_accepts_eligible_request_and_dispatches( config = _make_text_openai_config(db, user_api_key.project_id) resp = client.post( - "/api/v1/evaluations", + f"{settings.API_V2_STR}/evaluations", json={ "experiment_name": "fr4-fast-run", "dataset_id": dataset.id, "config_id": str(config.id), "config_version": 1, - "run_mode": "fast", }, headers=user_api_key_header, ) @@ -363,13 +362,12 @@ def test_fr2_rejects_dataset_with_too_many_unique_rows( config = _make_text_openai_config(db, user_api_key.project_id) resp = client.post( - "/api/v1/evaluations", + f"{settings.API_V2_STR}/evaluations", json={ "experiment_name": "fr2-fast-run", "dataset_id": dataset.id, "config_id": str(config.id), "config_version": 1, - "run_mode": "fast", }, headers=user_api_key_header, ) @@ -396,16 +394,19 @@ def test_fr3_rejects_duplicate_run_name( "dataset_id": dataset.id, "config_id": str(config.id), "config_version": 1, - "run_mode": "fast", } first = client.post( - "/api/v1/evaluations", json=payload, headers=user_api_key_header + f"{settings.API_V2_STR}/evaluations", + json=payload, + headers=user_api_key_header, ) assert first.status_code == 200, first.text second = client.post( - "/api/v1/evaluations", json=payload, headers=user_api_key_header + f"{settings.API_V2_STR}/evaluations", + json=payload, + headers=user_api_key_header, ) assert second.status_code == 409 assert "run_name_already_exists" in _api_error(second.json()) diff --git a/backend/app/tests/api/routes/test_evaluation_v2.py b/backend/app/tests/api/routes/test_evaluation_v2.py index 14930d27f..46f06c777 100644 --- a/backend/app/tests/api/routes/test_evaluation_v2.py +++ b/backend/app/tests/api/routes/test_evaluation_v2.py @@ -357,34 +357,27 @@ def test_omitting_override_leaves_run_factor_null( assert run.total_items == 15 -class TestV1TriggerUnchanged: - def test_v1_fast_run_is_not_a_judge_run( - self, - client: TestClient, - user_api_key_header: dict[str, str], - db: Session, - user_api_key: TestAuthContext, - _patch_dispatch, - ): - """FR-18: the v1 trigger produces a cosine-only run — never a judged one.""" - dataset = _make_dataset(db=db, user_api_key=user_api_key) - config = _make_text_config(db, user_api_key.project_id) +class TestV1WriteRoutesRemoved: + """v2 superseded the v1 write routes; only v1 reads/deletes remain.""" + @pytest.mark.parametrize( + "path", + ["/evaluations", "/evaluations/datasets"], + ) + def test_v1_post_is_not_allowed( + self, client: TestClient, user_api_key_header: dict[str, str], path: str + ) -> None: resp = client.post( - f"{settings.API_V1_STR}/evaluations", - json={ - "experiment_name": f"v1-plain-{random_lower_string()}", - "dataset_id": dataset.id, - "config_id": str(config.id), - "config_version": 1, - "run_mode": "fast", - }, - headers=user_api_key_header, + f"{settings.API_V1_STR}{path}", json={}, headers=user_api_key_header ) + assert resp.status_code == 405 - assert resp.status_code == 200, resp.text - body = resp.json()["data"] - assert not body["is_judge_run"] - run = db.get(EvaluationRun, body["id"]) - assert not run.is_judge_run - assert run.run_mode == "fast" + def test_v1_improve_prompt_is_gone( + self, client: TestClient, user_api_key_header: dict[str, str] + ) -> None: + resp = client.post( + f"{settings.API_V1_STR}/evaluations/1/improve-prompt", + json={"callback_url": "https://example.com/hook"}, + headers=user_api_key_header, + ) + assert resp.status_code == 404 diff --git a/backend/app/tests/api/routes/test_improve_prompt.py b/backend/app/tests/api/routes/test_improve_prompt.py index 17027b399..6e7593be8 100644 --- a/backend/app/tests/api/routes/test_improve_prompt.py +++ b/backend/app/tests/api/routes/test_improve_prompt.py @@ -1,10 +1,8 @@ """Tests for the async prompt-improvement feature (callback-URL / webhook flow). -The endpoint is: - - POST /evaluations/{id}/improve-prompt → 202 + a job handle - (LLMJobImmediatePublic). Requires a JSON body {"callback_url": "https://..."}. - The result is delivered to callback_url once the worker finishes — there is - no GET poll route anymore. +The endpoint (POST /api/v2/evaluations/{id}/improve-prompt) is covered in +test_improve_prompt_v2.py; the v1 route was removed. This module covers: + - start_prompt_improvement_job → creates the Job and enqueues the worker. - execute_prompt_improvement → the Celery worker entrypoint that does the Anthropic round-trip, mints the new config_version, and fires send_callback on every exit (SUCCESS, timeout, generic failure, redelivery no-op). @@ -14,11 +12,8 @@ - get_cloud_storage / load_json_from_object_store (traces) - start_prompt_improvement (the Celery enqueue helper) — never touch a broker - send_callback + get_webhook_secret — never make real outbound HTTP -- validate_callback_url at the route call site — real DNS is avoided for the - happy/domain paths; the SSRF-rejection tests use the real validator with - literal hosts that resolve without network. - Session (the worker opens its own Session(engine); we redirect it at the - transactional db fixture, matching the doctransformer worker tests) + transactional db fixture) DB is real (transactional db fixture; rolls back after each test). """ @@ -62,8 +57,6 @@ from app.tests.utils.utils import random_lower_string _SERVICE = "app.services.evaluations.prompt_improvement" -_ROUTE_VALIDATE = "app.api.routes.evaluations.evaluation.validate_callback_url" -POST_URL = "/api/v1/evaluations/{evaluation_id}/improve-prompt" # The deleted GET poll route — any method here must now miss all routes. OLD_POLL_URL = "/api/v1/evaluations/{evaluation_id}/improve-prompt/{job_id}" @@ -424,83 +417,8 @@ def test_unresolvable_config_version_raises_409( assert "source_config_unavailable" in exc.value.detail -class TestStartJobRoute: - """POST → 202 + job handle; enqueue behavior and fast-fail without enqueue.""" - - def test_returns_202_with_job_handle_and_persists_job( - self, - client: Any, - headers: dict[str, str], - db: Session, - auth: TestAuthContext, - completed_run: EvaluationRun, - ) -> None: - with patch(_ROUTE_VALIDATE), patch( - f"{_SERVICE}.start_prompt_improvement", return_value="task-1" - ) as enqueue: - resp = client.post( - POST_URL.format(evaluation_id=completed_run.id), - headers=headers, - json={"callback_url": _CALLBACK_URL}, - ) - - assert resp.status_code == 202, resp.text - body = resp.json()["data"] - assert body["status"] == JobStatus.PENDING.value - job_id = body["job_id"] - - job = JobCrud(session=db).get(job_id=job_id, project_id=auth.project_id) - assert job is not None - assert job.job_type == JobType.PROMPT_IMPROVEMENT - - enqueue.assert_called_once() - kwargs = enqueue.call_args.kwargs - assert kwargs["project_id"] == auth.project_id - assert kwargs["job_id"] == job_id - assert kwargs["organization_id"] == auth.organization_id - assert kwargs["evaluation_id"] == completed_run.id - assert kwargs["callback_url"] == _CALLBACK_URL - - def test_missing_callback_url_returns_422( - self, - client: Any, - headers: dict[str, str], - completed_run: EvaluationRun, - ) -> None: - with patch(f"{_SERVICE}.start_prompt_improvement") as enqueue: - resp = client.post( - POST_URL.format(evaluation_id=completed_run.id), - headers=headers, - json={}, - ) - assert resp.status_code == 422, resp.text - enqueue.assert_not_called() - - @pytest.mark.parametrize( - "callback_url", - [ - "http://example.com/callback", # non-HTTPS scheme - "https://10.0.0.1/callback", # RFC 1918 private IP - "https://127.0.0.1/callback", # loopback - ], - ) - def test_invalid_callback_url_rejected_by_ssrf_guard( - self, - callback_url: str, - client: Any, - headers: dict[str, str], - completed_run: EvaluationRun, - ) -> None: - # Real validate_callback_url runs; literal hosts resolve without DNS. - with patch(f"{_SERVICE}.start_prompt_improvement") as enqueue: - resp = client.post( - POST_URL.format(evaluation_id=completed_run.id), - headers=headers, - json={"callback_url": callback_url}, - ) - assert resp.status_code == 422, resp.text - assert "invalid_callback_url" in resp.json()["error"], resp.text - enqueue.assert_not_called() +class TestStartJob: + """Service-level enqueue behavior; the route is covered in test_improve_prompt_v2.""" def test_enqueue_failure_marks_job_failed_and_raises_500( self, @@ -531,61 +449,6 @@ def test_enqueue_failure_marks_job_failed_and_raises_500( assert job.status == JobStatus.FAILED assert job.error_message is not None - @pytest.mark.parametrize( - "make_run_kwargs,expected_status,error_token", - [ - (None, 404, "evaluation_not_found"), - ({"status": "pending"}, 409, "evaluation_not_completed"), - ({"score_trace_url": None}, 422, "traces_not_available"), - ], - ) - def test_fast_validation_error_does_not_enqueue( - self, - make_run_kwargs: dict | None, - expected_status: int, - error_token: str, - client: Any, - headers: dict[str, str], - db: Session, - auth: TestAuthContext, - dataset: EvaluationDataset, - config_with_instructions: Any, - anthropic_creds: None, - ) -> None: - if make_run_kwargs is None: - evaluation_id = 9999999 - else: - run = _make_completed_run( - db=db, - config_id=config_with_instructions.id, - config_version=1, - organization_id=auth.organization_id, - project_id=auth.project_id, - dataset_id=dataset.id, - **make_run_kwargs, - ) - evaluation_id = run.id - - with patch(_ROUTE_VALIDATE), patch( - f"{_SERVICE}.start_prompt_improvement" - ) as enqueue: - resp = client.post( - POST_URL.format(evaluation_id=evaluation_id), - headers=headers, - json={"callback_url": _CALLBACK_URL}, - ) - - assert resp.status_code == expected_status, resp.text - assert error_token in resp.json()["error"], resp.text - enqueue.assert_not_called() - - no_job = db.exec( - select(Job) - .where(Job.project_id == auth.project_id) - .where(Job.job_type == JobType.PROMPT_IMPROVEMENT) - ).first() - assert no_job is None - class TestExecuteWorker: """Worker entrypoint: PROCESSING → SUCCESS/FAILED, callback delivery, redelivery.""" diff --git a/backend/app/tests/api/routes/test_improve_prompt_v2.py b/backend/app/tests/api/routes/test_improve_prompt_v2.py index a4fc3f08b..f06a1acdc 100644 --- a/backend/app/tests/api/routes/test_improve_prompt_v2.py +++ b/backend/app/tests/api/routes/test_improve_prompt_v2.py @@ -482,10 +482,26 @@ def test_missing_trace_url_returns_422( assert "traces_not_available" in resp.json()["error"], resp.text enqueue.assert_not_called() + def test_missing_callback_url_returns_422( + self, + client: Any, + headers: dict[str, str], + judge_run: EvaluationRun, + ) -> None: + with patch(f"{_SERVICE}.start_prompt_improvement") as enqueue: + resp = client.post( + POST_URL.format(evaluation_id=judge_run.id), + headers=headers, + json={}, + ) + assert resp.status_code == 422, resp.text + enqueue.assert_not_called() + @pytest.mark.parametrize( "callback_url", [ "http://example.com/callback", # non-HTTPS scheme + "https://10.0.0.1/callback", # RFC 1918 private IP "https://127.0.0.1/callback", # loopback (SSRF) ], ) diff --git a/backend/app/tests/api/test_auth_failures.py b/backend/app/tests/api/test_auth_failures.py index d49deb9bd..bc3017de1 100644 --- a/backend/app/tests/api/test_auth_failures.py +++ b/backend/app/tests/api/test_auth_failures.py @@ -21,13 +21,13 @@ (f"{settings.API_V1_STR}/documents/12345678-1234-5678-1234-567812345678", "DELETE"), (f"{settings.API_V1_STR}/cron/evaluations", "GET"), (f"{settings.API_V1_STR}/cron/pending-jobs", "GET"), - (f"{settings.API_V1_STR}/evaluations/datasets", "POST"), + (f"{settings.API_V2_STR}/evaluations/datasets", "POST"), (f"{settings.API_V1_STR}/evaluations/datasets", "GET"), ( f"{settings.API_V1_STR}/evaluations/datasets/12345678-1234-5678-1234-567812345678", "GET", ), - (f"{settings.API_V1_STR}/evaluations", "POST"), + (f"{settings.API_V2_STR}/evaluations", "POST"), (f"{settings.API_V1_STR}/evaluations", "GET"), (f"{settings.API_V1_STR}/evaluations/12345678-1234-5678-1234-567812345678", "GET"), (f"{settings.API_V1_STR}/llm/call", "POST"), diff --git a/backend/app/tests/celery/test_job_execution.py b/backend/app/tests/celery/test_job_execution.py index dec4be87d..bad59001b 100644 --- a/backend/app/tests/celery/test_job_execution.py +++ b/backend/app/tests/celery/test_job_execution.py @@ -26,10 +26,6 @@ "run_delete_collection_job", "app.services.collections.delete_collection.execute_job", ), - ( - "run_evaluation_batch_submission", - "app.services.evaluations.batch_job.execute_evaluation_batch_submission", - ), ( "run_prompt_improvement", "app.services.evaluations.prompt_improvement.execute_prompt_improvement", diff --git a/backend/app/tests/celery/test_utils.py b/backend/app/tests/celery/test_utils.py index 6af8b2faa..2930bc41b 100644 --- a/backend/app/tests/celery/test_utils.py +++ b/backend/app/tests/celery/test_utils.py @@ -32,12 +32,6 @@ JOB_KWARGS, JOB_KWARGS, ), - ( - "start_evaluation_batch_submission", - "run_evaluation_batch_submission", - JOB_KWARGS, - JOB_KWARGS, - ), ( "start_prompt_improvement", "run_prompt_improvement", diff --git a/backend/app/tests/core/test_rate_limit.py b/backend/app/tests/core/test_rate_limit.py index bec8cfe14..6d7576d41 100644 --- a/backend/app/tests/core/test_rate_limit.py +++ b/backend/app/tests/core/test_rate_limit.py @@ -238,11 +238,3 @@ def test_v2_iteration_is_not_rate_limited( for _ in range(settings.EVAL_RATE_LIMIT_PER_MINUTE + 1): resp = client.post(V2_ITERATIONS_URL, headers=user_api_key_header, json={}) assert resp.status_code == 422 - - def test_v1_evaluation_is_not_rate_limited( - self, client: TestClient, user_api_key_header: dict[str, str] - ) -> None: - url = f"{settings.API_V1_STR}/evaluations" - for _ in range(settings.EVAL_RATE_LIMIT_PER_MINUTE + 1): - resp = client.post(url, headers=user_api_key_header, json={}) - assert resp.status_code == 422 diff --git a/backend/app/tests/crud/evaluations/test_embeddings.py b/backend/app/tests/crud/evaluations/test_embeddings.py index 675abd2dd..118230f49 100644 --- a/backend/app/tests/crud/evaluations/test_embeddings.py +++ b/backend/app/tests/crud/evaluations/test_embeddings.py @@ -1,283 +1,6 @@ import pytest -from app.crud.evaluations.embeddings import ( - build_embedding_jsonl, - calculate_average_similarity, - calculate_cosine_similarity, - parse_embedding_results, -) - - -class TestBuildEmbeddingJsonl: - """Tests for build_embedding_jsonl function.""" - - def test_build_embedding_jsonl_basic(self) -> None: - """Test building JSONL for basic evaluation results.""" - results = [ - { - "item_id": "item_1", - "question": "What is 2+2?", - "generated_output": "The answer is 4", - "ground_truth": "4", - }, - { - "item_id": "item_2", - "question": "What is the capital of France?", - "generated_output": "Paris", - "ground_truth": "Paris", - }, - ] - - trace_id_mapping = { - "item_1": "trace_1", - "item_2": "trace_2", - } - - jsonl_data, skipped = build_embedding_jsonl(results, trace_id_mapping) - - assert len(jsonl_data) == 2 - assert skipped == [] - - assert jsonl_data[0]["custom_id"] == "trace_1" - assert jsonl_data[0]["method"] == "POST" - assert jsonl_data[0]["url"] == "/v1/embeddings" - assert jsonl_data[0]["body"]["model"] == "text-embedding-3-large" - assert jsonl_data[0]["body"]["input"] == ["The answer is 4", "4"] - assert jsonl_data[0]["body"]["encoding_format"] == "float" - - def test_build_embedding_jsonl_custom_model(self) -> None: - """Test building JSONL with custom embedding model.""" - results = [ - { - "item_id": "item_1", - "question": "Test?", - "generated_output": "Output", - "ground_truth": "Truth", - } - ] - - trace_id_mapping = {"item_1": "trace_1"} - - jsonl_data, skipped = build_embedding_jsonl( - results, trace_id_mapping, embedding_model="text-embedding-3-small" - ) - - assert len(jsonl_data) == 1 - assert skipped == [] - assert jsonl_data[0]["body"]["model"] == "text-embedding-3-small" - - def test_build_embedding_jsonl_skips_empty(self) -> None: - """Test that items with empty output or ground_truth are skipped.""" - results = [ - { - "item_id": "item_1", - "question": "Test?", - "generated_output": "", - "ground_truth": "Truth", - }, - { - "item_id": "item_2", - "question": "Test?", - "generated_output": "Output", - "ground_truth": "", - }, - { - "item_id": "item_3", - "question": "Test?", - "generated_output": "Output", - "ground_truth": "Truth", - }, - ] - - trace_id_mapping = { - "item_1": "trace_1", - "item_2": "trace_2", - "item_3": "trace_3", - } - - jsonl_data, skipped = build_embedding_jsonl(results, trace_id_mapping) - - assert len(jsonl_data) == 1 - assert jsonl_data[0]["custom_id"] == "trace_3" - - # Empty output/ground_truth are reported with a per-item reason + trace_id. - skipped_by_trace = {s["trace_id"]: s["reason"] for s in skipped} - assert skipped_by_trace == { - "trace_1": "empty_output", - "trace_2": "empty_ground_truth", - } - - def test_build_embedding_jsonl_missing_item_id(self) -> None: - """Test that items without item_id or trace_id are skipped.""" - results = [ - { - "question": "Test?", - "generated_output": "Output", - "ground_truth": "Truth", - }, - { - "item_id": "item_2", - "question": "Test?", - "generated_output": "Output", - "ground_truth": "Truth", - }, - ] - - trace_id_mapping = {"item_2": "trace_2"} - - jsonl_data, skipped = build_embedding_jsonl(results, trace_id_mapping) - - assert len(jsonl_data) == 1 - assert jsonl_data[0]["custom_id"] == "trace_2" - # Item with no item_id is dropped silently (cannot be keyed at all). - assert skipped == [] - - -class TestParseEmbeddingResults: - """Tests for parse_embedding_results function.""" - - def test_parse_embedding_results_basic(self) -> None: - """Test parsing basic embedding results.""" - raw_results = [ - { - "custom_id": "trace_1", - "response": { - "body": { - "data": [ - {"index": 0, "embedding": [0.1, 0.2, 0.3]}, - {"index": 1, "embedding": [0.15, 0.22, 0.32]}, - ] - } - }, - }, - { - "custom_id": "trace_2", - "response": { - "body": { - "data": [ - {"index": 0, "embedding": [0.5, 0.6, 0.7]}, - {"index": 1, "embedding": [0.55, 0.65, 0.75]}, - ] - } - }, - }, - ] - - embedding_pairs, failed_trace_ids = parse_embedding_results(raw_results) - - assert len(embedding_pairs) == 2 - assert failed_trace_ids == [] - - assert embedding_pairs[0]["trace_id"] == "trace_1" - assert embedding_pairs[0]["output_embedding"] == [0.1, 0.2, 0.3] - assert embedding_pairs[0]["ground_truth_embedding"] == [0.15, 0.22, 0.32] - - assert embedding_pairs[1]["trace_id"] == "trace_2" - assert embedding_pairs[1]["output_embedding"] == [0.5, 0.6, 0.7] - assert embedding_pairs[1]["ground_truth_embedding"] == [0.55, 0.65, 0.75] - - def test_parse_embedding_results_with_error(self) -> None: - """Test parsing results with errors.""" - raw_results = [ - { - "custom_id": "trace_1", - "error": {"message": "Rate limit exceeded"}, - }, - { - "custom_id": "trace_2", - "response": { - "body": { - "data": [ - {"index": 0, "embedding": [0.1, 0.2]}, - {"index": 1, "embedding": [0.15, 0.22]}, - ] - } - }, - }, - ] - - embedding_pairs, failed_trace_ids = parse_embedding_results(raw_results) - - assert len(embedding_pairs) == 1 - assert embedding_pairs[0]["trace_id"] == "trace_2" - # The errored line is reported so it can be flagged embedding_failed. - assert failed_trace_ids == ["trace_1"] - - def test_parse_embedding_results_missing_embedding(self) -> None: - """Test parsing results with missing embeddings.""" - raw_results = [ - { - "custom_id": "trace_1", - "response": { - "body": { - "data": [ - {"index": 0, "embedding": [0.1, 0.2]}, - # Missing index 1 - ] - } - }, - }, - { - "custom_id": "trace_2", - "response": { - "body": { - "data": [ - {"index": 0, "embedding": [0.1, 0.2]}, - {"index": 1, "embedding": [0.15, 0.22]}, - ] - } - }, - }, - ] - - embedding_pairs, failed_trace_ids = parse_embedding_results(raw_results) - - assert len(embedding_pairs) == 1 - assert embedding_pairs[0]["trace_id"] == "trace_2" - # The partial-result line (only index 0) is reported as failed. - assert failed_trace_ids == ["trace_1"] - - def test_parse_embedding_results_missing_trace_id_not_reported(self) -> None: - """A line with no trace_id is dropped silently, not reported as failed.""" - raw_results = [ - { - # No custom_id / BATCH_KEY: cannot be keyed, so not reportable. - "response": { - "body": { - "data": [ - {"index": 0, "embedding": [0.1, 0.2]}, - {"index": 1, "embedding": [0.15, 0.22]}, - ] - } - }, - }, - ] - - embedding_pairs, failed_trace_ids = parse_embedding_results(raw_results) - - assert embedding_pairs == [] - assert failed_trace_ids == [] - - def test_parse_embedding_results_null_ground_truth_embedding(self) -> None: - """Both indices present but one embedding is None -> reported as failed.""" - raw_results = [ - { - "custom_id": "trace_1", - "response": { - "body": { - "data": [ - {"index": 0, "embedding": [0.1, 0.2]}, - {"index": 1, "embedding": None}, - ] - } - }, - }, - ] - - embedding_pairs, failed_trace_ids = parse_embedding_results(raw_results) - - assert embedding_pairs == [] - assert failed_trace_ids == ["trace_1"] +from app.crud.evaluations.embeddings import calculate_cosine_similarity class TestCalculateCosineSimilarity: @@ -327,102 +50,3 @@ def test_calculate_cosine_similarity_zero_vector(self) -> None: similarity = calculate_cosine_similarity(vec1, vec2) assert similarity == 0.0 - - -class TestCalculateAverageSimilarity: - """Tests for calculate_average_similarity function.""" - - def test_calculate_average_similarity_basic(self) -> None: - """Test calculating average similarity for basic embedding pairs.""" - embedding_pairs = [ - { - "trace_id": "trace_1", - "output_embedding": [1.0, 0.0, 0.0], - "ground_truth_embedding": [1.0, 0.0, 0.0], - }, - { - "trace_id": "trace_2", - "output_embedding": [1.0, 0.0, 0.0], - "ground_truth_embedding": [0.0, 1.0, 0.0], - }, - { - "trace_id": "trace_3", - "output_embedding": [1.0, 1.0, 0.0], - "ground_truth_embedding": [1.0, 0.0, 0.0], - }, - ] - - stats = calculate_average_similarity(embedding_pairs) - - assert stats["total_pairs"] == 3 - # Average of [1.0, 0.0, 0.707] ≈ 0.569 - assert stats["cosine_similarity_avg"] == pytest.approx(0.569, abs=0.01) - assert "cosine_similarity_std" in stats - assert len(stats["per_item_scores"]) == 3 - - def test_calculate_average_similarity_empty(self) -> None: - """Test calculating average similarity for empty list.""" - embedding_pairs = [] - - stats = calculate_average_similarity(embedding_pairs) - - assert stats["total_pairs"] == 0 - assert stats["cosine_similarity_avg"] == 0.0 - assert stats["cosine_similarity_std"] == 0.0 - assert stats["per_item_scores"] == [] - - def test_calculate_average_similarity_per_item_scores(self) -> None: - """Test that per-item scores are correctly calculated.""" - embedding_pairs = [ - { - "trace_id": "trace_1", - "output_embedding": [1.0, 0.0], - "ground_truth_embedding": [1.0, 0.0], - }, - { - "trace_id": "trace_2", - "output_embedding": [0.0, 1.0], - "ground_truth_embedding": [0.0, 1.0], - }, - ] - - stats = calculate_average_similarity(embedding_pairs) - - assert len(stats["per_item_scores"]) == 2 - assert stats["per_item_scores"][0]["trace_id"] == "trace_1" - assert stats["per_item_scores"][0]["cosine_similarity"] == pytest.approx(1.0) - assert stats["per_item_scores"][1]["trace_id"] == "trace_2" - assert stats["per_item_scores"][1]["cosine_similarity"] == pytest.approx(1.0) - - def test_calculate_average_similarity_statistics(self) -> None: - """Test that all statistics are calculated correctly.""" - embedding_pairs = [ - { - "trace_id": "trace_1", - "output_embedding": [1.0, 0.0], - "ground_truth_embedding": [1.0, 0.0], - }, - { - "trace_id": "trace_2", - "output_embedding": [1.0, 0.0], - "ground_truth_embedding": [0.0, 1.0], - }, - { - "trace_id": "trace_3", - "output_embedding": [1.0, 0.0], - "ground_truth_embedding": [1.0, 0.0], - }, - { - "trace_id": "trace_4", - "output_embedding": [1.0, 0.0], - "ground_truth_embedding": [0.0, 1.0], - }, - ] - - stats = calculate_average_similarity(embedding_pairs) - - # Similarities = [1.0, 0.0, 1.0, 0.0] - assert stats["cosine_similarity_avg"] == pytest.approx(0.5) - # Standard deviation of [1, 0, 1, 0] = 0.5 - assert stats["cosine_similarity_std"] == pytest.approx(0.5) - assert stats["total_pairs"] == 4 diff --git a/backend/app/tests/crud/evaluations/test_langfuse.py b/backend/app/tests/crud/evaluations/test_langfuse.py index 9e62c1f54..e2e45108d 100644 --- a/backend/app/tests/crud/evaluations/test_langfuse.py +++ b/backend/app/tests/crud/evaluations/test_langfuse.py @@ -5,9 +5,9 @@ from app.crud.evaluations.langfuse import ( create_langfuse_dataset_run, + fetch_dataset_items, fetch_trace_scores_from_langfuse, update_traces_with_cosine_scores, - upload_dataset_to_langfuse, ) @@ -510,233 +510,6 @@ def test_update_traces_with_cosine_scores_empty_list(self) -> None: mock_langfuse.flush.assert_called_once() -class TestUploadDatasetToLangfuse: - """Test uploading datasets to Langfuse from pre-parsed items.""" - - @pytest.fixture - def valid_items(self) -> Any: - """Valid parsed items.""" - return [ - {"question": "What is 2+2?", "answer": "4"}, - {"question": "What is the capital of France?", "answer": "Paris"}, - {"question": "Who wrote Romeo and Juliet?", "answer": "Shakespeare"}, - ] - - def test_upload_dataset_to_langfuse_success(self, valid_items): - """Test successful upload with duplication.""" - mock_langfuse = MagicMock() - mock_dataset = MagicMock() - mock_dataset.id = "dataset_123" - mock_langfuse.create_dataset.return_value = mock_dataset - - langfuse_id, total_items = upload_dataset_to_langfuse( - langfuse=mock_langfuse, - items=valid_items, - dataset_name="test_dataset", - duplication_factor=5, - ) - - assert langfuse_id == "dataset_123" - assert total_items == 15 - - mock_langfuse.create_dataset.assert_called_once_with(name="test_dataset") - - assert mock_langfuse.create_dataset_item.call_count == 15 - - assert mock_langfuse.flush.call_count == 1 - - def test_upload_dataset_to_langfuse_duplication_metadata(self, valid_items): - """Test that duplication metadata is included.""" - mock_langfuse = MagicMock() - mock_dataset = MagicMock() - mock_dataset.id = "dataset_123" - mock_langfuse.create_dataset.return_value = mock_dataset - - upload_dataset_to_langfuse( - langfuse=mock_langfuse, - items=valid_items, - dataset_name="test_dataset", - duplication_factor=3, - ) - - calls = mock_langfuse.create_dataset_item.call_args_list - - duplicate_numbers = [] - for call_args in calls: - metadata = call_args.kwargs.get("metadata", {}) - duplicate_numbers.append(metadata.get("duplicate_number")) - assert metadata.get("duplication_factor") == 3 - - assert duplicate_numbers.count(1) == 3 - assert duplicate_numbers.count(2) == 3 - assert duplicate_numbers.count(3) == 3 - - def test_upload_dataset_to_langfuse_question_id_in_metadata(self, valid_items): - """Test that question_id is included in metadata as integer.""" - mock_langfuse = MagicMock() - mock_dataset = MagicMock() - mock_dataset.id = "dataset_123" - mock_langfuse.create_dataset.return_value = mock_dataset - - upload_dataset_to_langfuse( - langfuse=mock_langfuse, - items=valid_items, - dataset_name="test_dataset", - duplication_factor=1, - ) - - calls = mock_langfuse.create_dataset_item.call_args_list - assert len(calls) == 3 - - question_ids = [] - for call_args in calls: - metadata = call_args.kwargs.get("metadata", {}) - assert "question_id" in metadata - assert metadata["question_id"] is not None - # Verify it's an integer (1-based index) - assert isinstance(metadata["question_id"], int) - question_ids.append(metadata["question_id"]) - - # Verify sequential IDs starting from 1 - assert sorted(question_ids) == [1, 2, 3] - - def test_upload_dataset_to_langfuse_same_question_id_for_duplicates( - self, valid_items - ): - """Test that all duplicates of the same question share the same question_id.""" - mock_langfuse = MagicMock() - mock_dataset = MagicMock() - mock_dataset.id = "dataset_123" - mock_langfuse.create_dataset.return_value = mock_dataset - - upload_dataset_to_langfuse( - langfuse=mock_langfuse, - items=valid_items, - dataset_name="test_dataset", - duplication_factor=3, - ) - - calls = mock_langfuse.create_dataset_item.call_args_list - assert len(calls) == 9 # 3 items * 3 duplicates - - # Group calls by original_question - question_ids_by_question: dict[str, set[int]] = {} - for call_args in calls: - metadata = call_args.kwargs.get("metadata", {}) - original_question = metadata.get("original_question") - question_id = metadata.get("question_id") - - # Verify question_id is an integer - assert isinstance(question_id, int) - - if original_question not in question_ids_by_question: - question_ids_by_question[original_question] = set() - question_ids_by_question[original_question].add(question_id) - - # Verify each question has exactly one unique question_id across all duplicates - for question, question_ids in question_ids_by_question.items(): - assert ( - len(question_ids) == 1 - ), f"Question '{question}' has multiple question_ids: {question_ids}" - - # Verify different questions have different question_ids (1, 2, 3) - all_unique_ids: set[int] = set() - for qid_set in question_ids_by_question.values(): - all_unique_ids.update(qid_set) - assert all_unique_ids == {1, 2, 3} # 3 unique questions = IDs 1, 2, 3 - - def test_upload_dataset_to_langfuse_empty_items(self) -> None: - """Test with empty items list.""" - mock_langfuse = MagicMock() - mock_dataset = MagicMock() - mock_dataset.id = "dataset_123" - mock_langfuse.create_dataset.return_value = mock_dataset - - langfuse_id, total_items = upload_dataset_to_langfuse( - langfuse=mock_langfuse, - items=[], - dataset_name="test_dataset", - duplication_factor=1, - ) - - assert langfuse_id == "dataset_123" - assert total_items == 0 - mock_langfuse.create_dataset_item.assert_not_called() - assert mock_langfuse.flush.call_count == 1 - - def test_upload_dataset_to_langfuse_single_duplication(self, valid_items): - """Test upload with duplication factor of 1.""" - mock_langfuse = MagicMock() - mock_dataset = MagicMock() - mock_dataset.id = "dataset_123" - mock_langfuse.create_dataset.return_value = mock_dataset - - langfuse_id, total_items = upload_dataset_to_langfuse( - langfuse=mock_langfuse, - items=valid_items, - dataset_name="test_dataset", - duplication_factor=1, - ) - - assert total_items == 3 - assert mock_langfuse.create_dataset_item.call_count == 3 - assert mock_langfuse.flush.call_count == 1 - - def test_upload_dataset_to_langfuse_item_creation_error(self, valid_items): - """Test that item creation errors are logged but don't stop processing.""" - mock_langfuse = MagicMock() - mock_dataset = MagicMock() - mock_dataset.id = "dataset_123" - mock_langfuse.create_dataset.return_value = mock_dataset - - mock_langfuse.create_dataset_item.side_effect = [ - None, - Exception("API error"), - None, - ] - - langfuse_id, total_items = upload_dataset_to_langfuse( - langfuse=mock_langfuse, - items=valid_items, - dataset_name="test_dataset", - duplication_factor=1, - ) - - assert total_items == 2 - assert mock_langfuse.create_dataset_item.call_count == 3 - - def test_upload_dataset_writes_category_only_when_item_has_it(self) -> None: - """`category` is optional: items without it must not produce a Langfuse - metadata `category` field, while items that have it must. - - This is what keeps the no-category-column upload path clean end-to-end. - """ - items = [ - {"question": "q1", "answer": "a1"}, # no category - {"question": "q2", "answer": "a2", "category": "Health"}, - ] - mock_langfuse = MagicMock() - mock_dataset = MagicMock() - mock_dataset.id = "dataset_123" - mock_langfuse.create_dataset.return_value = mock_dataset - - upload_dataset_to_langfuse( - langfuse=mock_langfuse, - items=items, - dataset_name="test_dataset", - duplication_factor=1, - ) - - calls = mock_langfuse.create_dataset_item.call_args_list - assert len(calls) == 2 - - metadatas_by_question = { - call.kwargs["input"]["question"]: call.kwargs["metadata"] for call in calls - } - assert "category" not in metadatas_by_question["q1"] - assert metadatas_by_question["q2"]["category"] == "Health" - - class TestFetchTraceScoresFromLangfuse: """Test fetching trace scores from Langfuse.""" @@ -1188,3 +961,42 @@ def test_fetch_trace_scores_mixed_question_id_types(self) -> None: assert len(result["traces"]) == 2 assert result["traces"][0]["question_id"] == 123 assert result["traces"][1]["question_id"] == "abc-456" + + +class TestFetchDatasetItems: + """Reads items of legacy Langfuse-backed datasets for fast runs.""" + + def test_fetch_dataset_items_maps_fields(self) -> None: + item = MagicMock() + item.id = "item_1" + item.input = {"question": "Q?"} + item.expected_output = {"answer": "A"} + item.metadata = {"question_id": 1} + langfuse = MagicMock() + langfuse.get_dataset.return_value = MagicMock(items=[item]) + + items = fetch_dataset_items(langfuse=langfuse, dataset_name="ds") + + langfuse.get_dataset.assert_called_once_with("ds") + assert items == [ + { + "id": "item_1", + "input": {"question": "Q?"}, + "expected_output": {"answer": "A"}, + "metadata": {"question_id": 1}, + } + ] + + def test_fetch_dataset_items_missing_dataset_raises(self) -> None: + langfuse = MagicMock() + langfuse.get_dataset.side_effect = Exception("404") + + with pytest.raises(ValueError, match="not found"): + fetch_dataset_items(langfuse=langfuse, dataset_name="ds") + + def test_fetch_dataset_items_empty_dataset_raises(self) -> None: + langfuse = MagicMock() + langfuse.get_dataset.return_value = MagicMock(items=[]) + + with pytest.raises(ValueError, match="is empty"): + fetch_dataset_items(langfuse=langfuse, dataset_name="ds") diff --git a/backend/app/tests/crud/evaluations/test_processing.py b/backend/app/tests/crud/evaluations/test_processing.py deleted file mode 100644 index 13555a7dc..000000000 --- a/backend/app/tests/crud/evaluations/test_processing.py +++ /dev/null @@ -1,1783 +0,0 @@ -import json -from typing import Any -from unittest.mock import MagicMock, patch - -import pytest -from sqlmodel import Session, select - -from app.core.util import now -from app.crud.evaluations.core import create_evaluation_run -from app.crud.evaluations.processing import ( - _extract_batch_error_message, - _extract_gemini_usage, - _get_batch_provider, - check_and_process_evaluation, - parse_evaluation_output, - poll_all_pending_evaluations, - process_completed_embedding_batch, - process_completed_evaluation, -) -from app.models import BatchJob, EvaluationDataset, EvaluationRun, Organization, Project -from app.models.batch_job import BatchJobType -from app.models.evaluation import RunModeEnum -from app.tests.utils.test_data import create_test_config, create_test_evaluation_dataset - - -class TestParseEvaluationOutput: - """Test parsing evaluation batch output.""" - - def test_parse_evaluation_output_basic(self) -> None: - """Test basic parsing with valid data.""" - raw_results = [ - { - "custom_id": "item1", - "response": { - "body": { - "id": "resp_123", - "output": [ - { - "type": "message", - "content": [ - {"type": "output_text", "text": "The answer is 4"} - ], - } - ], - "usage": { - "input_tokens": 10, - "output_tokens": 5, - "total_tokens": 15, - }, - } - }, - } - ] - - dataset_items = [ - { - "id": "item1", - "input": {"question": "What is 2+2?"}, - "expected_output": {"answer": "4"}, - "metadata": {"question_id": 1}, - } - ] - - results = parse_evaluation_output(raw_results, dataset_items) - - assert len(results) == 1 - assert results[0]["item_id"] == "item1" - assert results[0]["question"] == "What is 2+2?" - assert results[0]["generated_output"] == "The answer is 4" - assert results[0]["ground_truth"] == "4" - assert results[0]["response_id"] == "resp_123" - assert results[0]["usage"]["total_tokens"] == 15 - assert results[0]["question_id"] == 1 - - def test_parse_evaluation_output_without_question_id(self) -> None: - """Test parsing dataset items without question_id (backwards compatibility).""" - raw_results = [ - { - "custom_id": "item1", - "response": { - "body": { - "id": "resp_123", - "output": "Answer text", - "usage": {"total_tokens": 10}, - } - }, - } - ] - - dataset_items = [ - { - "id": "item1", - "input": {"question": "Test question?"}, - "expected_output": {"answer": "Test answer"}, - # No metadata / question_id - } - ] - - results = parse_evaluation_output(raw_results, dataset_items) - - assert len(results) == 1 - assert results[0]["question_id"] is None - - def test_parse_evaluation_output_simple_string(self) -> None: - """Test parsing with simple string output.""" - raw_results = [ - { - "custom_id": "item1", - "response": { - "body": { - "id": "resp_123", - "output": "Simple text response", - "usage": { - "input_tokens": 10, - "output_tokens": 5, - "total_tokens": 15, - }, - } - }, - } - ] - - dataset_items = [ - { - "id": "item1", - "input": {"question": "Test?"}, - "expected_output": {"answer": "Test"}, - } - ] - - results = parse_evaluation_output(raw_results, dataset_items) - - assert len(results) == 1 - assert results[0]["generated_output"] == "Simple text response" - - def test_parse_evaluation_output_with_error(self) -> None: - """Test parsing item with error.""" - raw_results = [ - { - "custom_id": "item1", - "error": {"message": "Rate limit exceeded"}, - "response": {"body": {}}, - } - ] - - dataset_items = [ - { - "id": "item1", - "input": {"question": "Test?"}, - "expected_output": {"answer": "Test"}, - } - ] - - results = parse_evaluation_output(raw_results, dataset_items) - - assert len(results) == 1 - assert "ERROR: Rate limit exceeded" in results[0]["generated_output"] - - def test_parse_evaluation_output_missing_custom_id(self) -> None: - """Test parsing skips items without custom_id.""" - raw_results = [ - { - "response": { - "body": { - "output": "Test", - "usage": {"total_tokens": 10}, - } - } - } - ] - - dataset_items = [ - { - "id": "item1", - "input": {"question": "Test?"}, - "expected_output": {"answer": "Test"}, - } - ] - - results = parse_evaluation_output(raw_results, dataset_items) - - assert len(results) == 0 - - def test_parse_evaluation_output_missing_dataset_item(self) -> None: - """Test parsing skips items not in dataset.""" - raw_results = [ - { - "custom_id": "item999", - "response": {"body": {"output": "Test", "usage": {"total_tokens": 10}}}, - } - ] - - dataset_items = [ - { - "id": "item1", - "input": {"question": "Test?"}, - "expected_output": {"answer": "Test"}, - } - ] - - results = parse_evaluation_output(raw_results, dataset_items) - - assert len(results) == 0 - - def test_parse_evaluation_output_json_string(self) -> None: - """Test parsing JSON string output.""" - raw_results = [ - { - "custom_id": "item1", - "response": { - "body": { - "output": json.dumps( - [ - { - "type": "message", - "content": [ - {"type": "output_text", "text": "Parsed JSON"} - ], - } - ] - ), - "usage": {"total_tokens": 10}, - } - }, - } - ] - - dataset_items = [ - { - "id": "item1", - "input": {"question": "Test?"}, - "expected_output": {"answer": "Test"}, - } - ] - - results = parse_evaluation_output(raw_results, dataset_items) - - assert len(results) == 1 - assert results[0]["generated_output"] == "Parsed JSON" - - def test_parse_evaluation_output_multiple_items(self) -> None: - """Test parsing multiple items.""" - raw_results = [ - { - "custom_id": f"item{i}", - "response": { - "body": { - "output": f"Output {i}", - "usage": {"total_tokens": 10}, - } - }, - } - for i in range(3) - ] - - dataset_items = [ - { - "id": f"item{i}", - "input": {"question": f"Q{i}"}, - "expected_output": {"answer": f"A{i}"}, - } - for i in range(3) - ] - - results = parse_evaluation_output(raw_results, dataset_items) - - assert len(results) == 3 - for i, result in enumerate(results): - assert result["item_id"] == f"item{i}" - assert result["generated_output"] == f"Output {i}" - assert result["ground_truth"] == f"A{i}" - - -class TestParseEvaluationOutputGoogle: - """Test parsing Gemini batch output (provider_name=google-aistudio). - - Gemini lines are keyed by ``key`` (not ``custom_id``) and carry a nested - ``response`` dict with ``candidates``/``usageMetadata`` rather than the - OpenAI ``response.body`` shape. - """ - - def _dataset_items(self) -> list[dict[str, Any]]: - return [ - { - "id": "item1", - "input": {"question": "What is 2+2?"}, - "expected_output": {"answer": "4"}, - "metadata": {"question_id": 7}, - } - ] - - def test_parse_gemini_success(self) -> None: - """Text is pulled from candidates and usage from usageMetadata.""" - raw_results = [ - { - "key": "item1", - "response": { - "responseId": "resp_g1", - "candidates": [ - {"content": {"parts": [{"text": "The answer is 4"}]}} - ], - "usageMetadata": { - "promptTokenCount": 10, - "candidatesTokenCount": 5, - "totalTokenCount": 15, - "thoughtsTokenCount": 2, - }, - }, - } - ] - - results = parse_evaluation_output( - raw_results, self._dataset_items(), provider_name="google-aistudio" - ) - - assert len(results) == 1 - result = results[0] - assert result["item_id"] == "item1" - assert result["generated_output"] == "The answer is 4" - assert result["response_id"] == "resp_g1" - assert result["question_id"] == 7 - assert result["usage"] == { - "input_tokens": 10, - "output_tokens": 5, - "total_tokens": 15, - "reasoning_tokens": 2, - } - - def test_parse_gemini_error(self) -> None: - """An ``error`` on the line yields an ERROR: generated_output.""" - raw_results = [{"key": "item1", "error": {"message": "quota exceeded"}}] - - results = parse_evaluation_output( - raw_results, self._dataset_items(), provider_name="google-aistudio" - ) - - assert len(results) == 1 - assert results[0]["generated_output"].startswith("ERROR:") - assert "quota exceeded" in results[0]["generated_output"] - - def test_parse_gemini_native_provider(self) -> None: - """The -native provider variant is treated as Google too.""" - raw_results = [ - { - "key": "item1", - "response": { - "candidates": [{"content": {"parts": [{"text": "ok"}]}}], - }, - } - ] - - results = parse_evaluation_output( - raw_results, - self._dataset_items(), - provider_name="google-aistudio-native", - ) - - assert results[0]["generated_output"] == "ok" - assert results[0]["usage"] is None - - -class TestExtractGeminiUsage: - """Test ``_extract_gemini_usage`` mapping of Gemini usage to OpenAI shape.""" - - def test_camel_case(self) -> None: - usage = _extract_gemini_usage( - { - "usageMetadata": { - "promptTokenCount": 10, - "candidatesTokenCount": 5, - "totalTokenCount": 15, - "thoughtsTokenCount": 3, - } - } - ) - assert usage == { - "input_tokens": 10, - "output_tokens": 5, - "total_tokens": 15, - "reasoning_tokens": 3, - } - - def test_snake_case(self) -> None: - usage = _extract_gemini_usage( - { - "usage_metadata": { - "prompt_token_count": 1, - "candidates_token_count": 2, - "total_token_count": 3, - "thoughts_token_count": 4, - } - } - ) - assert usage == { - "input_tokens": 1, - "output_tokens": 2, - "total_tokens": 3, - "reasoning_tokens": 4, - } - - def test_missing_metadata_returns_none(self) -> None: - assert _extract_gemini_usage({}) is None - assert _extract_gemini_usage({"usageMetadata": None}) is None - - def test_partial_metadata_defaults_to_zero(self) -> None: - usage = _extract_gemini_usage({"usageMetadata": {"promptTokenCount": 9}}) - assert usage == { - "input_tokens": 9, - "output_tokens": 0, - "total_tokens": 0, - "reasoning_tokens": 0, - } - - -class TestGetBatchProvider: - """Test _get_batch_provider dispatch by provider name.""" - - @patch("app.crud.evaluations.processing.OpenAIBatchProvider") - @patch("app.crud.evaluations.processing.get_openai_client") - def test_openai(self, mock_get_client, mock_provider_cls) -> None: - provider = _get_batch_provider( - session=MagicMock(), - provider_name="openai", - organization_id=1, - project_id=2, - ) - mock_get_client.assert_called_once() - assert provider is mock_provider_cls.return_value - - @patch("app.crud.evaluations.processing.GeminiBatchProvider") - @patch("app.crud.evaluations.processing.GeminiClient") - def test_google(self, mock_gemini_client, mock_provider_cls) -> None: - provider = _get_batch_provider( - session=MagicMock(), - provider_name="google-aistudio", - organization_id=1, - project_id=2, - ) - mock_gemini_client.from_credentials.assert_called_once() - assert provider is mock_provider_cls.return_value - - def test_unsupported_raises(self) -> None: - with pytest.raises(ValueError, match="Unsupported provider"): - _get_batch_provider( - session=MagicMock(), - provider_name="anthropic", - organization_id=1, - project_id=2, - ) - - -class TestProcessCompletedEvaluation: - """Test processing completed evaluation batch.""" - - @pytest.fixture - def test_dataset(self, db: Session) -> EvaluationDataset: - """Create a test dataset for evaluation runs.""" - org = db.exec(select(Organization)).first() - project = db.exec( - select(Project).where(Project.organization_id == org.id) - ).first() - - return create_test_evaluation_dataset( - db=db, - organization_id=org.id, - project_id=project.id, - name="test_dataset_processing", - description="Test dataset", - original_items_count=3, - duplication_factor=1, - ) - - @pytest.fixture - def eval_run_with_batch(self, db: Session, test_dataset) -> EvaluationRun: - """Create evaluation run with batch job.""" - # Create a config for the evaluation run - config = create_test_config( - db, project_id=test_dataset.project_id, use_kaapi_schema=True - ) - - # Create batch job - batch_job = BatchJob( - provider="openai", - provider_batch_id="batch_abc123", - provider_status="completed", - job_type=BatchJobType.EVALUATION, - total_items=2, - status="submitted", - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - inserted_at=now(), - updated_at=now(), - ) - db.add(batch_job) - db.commit() - db.refresh(batch_job) - - eval_run = create_evaluation_run( - session=db, - run_name="test_run", - dataset_name=test_dataset.name, - dataset_id=test_dataset.id, - config_id=config.id, - config_version=1, - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - ) - eval_run.batch_job_id = batch_job.id - eval_run.status = "processing" - db.add(eval_run) - db.commit() - db.refresh(eval_run) - - return eval_run - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.download_batch_results") - @patch("app.crud.evaluations.processing.fetch_dataset_items") - @patch("app.crud.evaluations.processing.create_langfuse_dataset_run") - @patch("app.crud.evaluations.processing.start_embedding_batch") - @patch("app.crud.evaluations.processing.upload_batch_results_to_object_store") - async def test_process_completed_evaluation_success( - self, - mock_upload, - mock_start_embedding, - mock_create_langfuse, - mock_fetch_dataset, - mock_download, - db: Session, - eval_run_with_batch, - ): - """Test successfully processing completed evaluation.""" - # Mock batch results - mock_download.return_value = [ - { - "custom_id": "item1", - "response": { - "body": { - "id": "resp_123", - "output": "Answer 1", - "usage": { - "input_tokens": 100, - "output_tokens": 50, - "total_tokens": 150, - }, - } - }, - } - ] - - # Mock dataset items - mock_fetch_dataset.return_value = [ - { - "id": "item1", - "input": {"question": "Q1"}, - "expected_output": {"answer": "A1"}, - } - ] - - # Mock Langfuse - mock_create_langfuse.return_value = {"item1": "trace_123"} - - # Mock embedding batch - mock_start_embedding.return_value = eval_run_with_batch - - # Mock upload - mock_upload.return_value = "s3://bucket/results.jsonl" - - mock_openai = MagicMock() - mock_langfuse = MagicMock() - - result = await process_completed_evaluation( - eval_run=eval_run_with_batch, - session=db, - openai_client=mock_openai, - langfuse=mock_langfuse, - ) - - assert result is not None - mock_download.assert_called_once() - mock_fetch_dataset.assert_called_once() - mock_create_langfuse.assert_called_once() - mock_start_embedding.assert_called_once() - - # Cost tracking: response cost should be aggregated and persisted. - db.refresh(result) - assert result.cost is not None - assert "response" in result.cost - response_cost = result.cost["response"] - assert response_cost["model"] == "gpt-4o" - assert response_cost["input_tokens"] == 100 - assert response_cost["output_tokens"] == 50 - assert response_cost["total_tokens"] == 150 - assert response_cost["cost_usd"] > 0 - assert result.cost["total_cost_usd"] == response_cost["cost_usd"] - # Embedding cost is added later by process_completed_embedding_batch. - assert "embedding" not in result.cost - # Batch has no per-call timing; no stand-in latency is ever written. - assert result.latency is None - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.persist_score_traces") - @patch("app.crud.evaluations.processing.download_batch_results") - @patch("app.crud.evaluations.processing.fetch_dataset_items") - @patch("app.crud.evaluations.processing.create_langfuse_dataset_run") - @patch("app.crud.evaluations.processing.start_embedding_batch") - @patch("app.crud.evaluations.processing.upload_batch_results_to_object_store") - async def test_process_completed_evaluation_persists_trace_skeleton( - self, - mock_upload, - mock_start_embedding, - mock_create_langfuse, - mock_fetch_dataset, - mock_download, - mock_persist_traces, - db: Session, - eval_run_with_batch, - ): - """Q&A trace skeleton is persisted durably before embeddings complete.""" - mock_download.return_value = [ - { - "custom_id": "item1", - "response": { - "body": { - "id": "resp_123", - "output": "Answer 1", - "usage": { - "input_tokens": 100, - "output_tokens": 50, - "total_tokens": 150, - }, - } - }, - } - ] - mock_fetch_dataset.return_value = [ - { - "id": "item1", - "input": {"question": "Q1"}, - "expected_output": {"answer": "A1"}, - "metadata": {"question_id": 7}, - } - ] - mock_create_langfuse.return_value = {"item1": "trace_123"} - mock_start_embedding.return_value = eval_run_with_batch - mock_upload.return_value = "s3://bucket/results.jsonl" - mock_persist_traces.return_value = eval_run_with_batch - - await process_completed_evaluation( - eval_run=eval_run_with_batch, - session=db, - openai_client=MagicMock(), - langfuse=MagicMock(), - ) - - # The Q&A-only skeleton is persisted via persist_score_traces (trace - # pointer only — it never writes the `score` column, so the run stays - # score-less / "processing" until cosine is computed), keyed by the - # Langfuse trace_id so the embedding stage can attach cosine later. - mock_persist_traces.assert_called_once() - traces = mock_persist_traces.call_args.kwargs["traces"] - assert len(traces) == 1 - assert traces[0]["trace_id"] == "trace_123" - assert traces[0]["question"] == "Q1" - assert traces[0]["llm_answer"] == "Answer 1" - assert traces[0]["ground_truth_answer"] == "A1" - assert traces[0]["question_id"] == 7 - assert traces[0]["scores"] == [] - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.download_batch_results") - @patch("app.crud.evaluations.processing.fetch_dataset_items") - async def test_process_completed_evaluation_no_results( - self, - mock_fetch_dataset, - mock_download, - db: Session, - eval_run_with_batch, - ): - """Test processing with no valid results.""" - mock_download.return_value = [] - mock_fetch_dataset.return_value = [ - { - "id": "item1", - "input": {"question": "Q1"}, - "expected_output": {"answer": "A1"}, - } - ] - - mock_openai = MagicMock() - mock_langfuse = MagicMock() - - result = await process_completed_evaluation( - eval_run=eval_run_with_batch, - session=db, - openai_client=mock_openai, - langfuse=mock_langfuse, - ) - - db.refresh(result) - assert result.status == "failed" - assert "No valid results" in result.error_message - - @pytest.mark.asyncio - async def test_process_completed_evaluation_no_batch_job_id( - self, db: Session, test_dataset - ): - """Test processing without batch_job_id.""" - # Create a config for the evaluation run - config = create_test_config( - db, project_id=test_dataset.project_id, use_kaapi_schema=True - ) - - eval_run = create_evaluation_run( - session=db, - run_name="test_run", - dataset_name=test_dataset.name, - dataset_id=test_dataset.id, - config_id=config.id, - config_version=1, - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - ) - - mock_openai = MagicMock() - mock_langfuse = MagicMock() - - result = await process_completed_evaluation( - eval_run=eval_run, - session=db, - openai_client=mock_openai, - langfuse=mock_langfuse, - ) - - db.refresh(result) - assert result.status == "failed" - assert "no batch_job_id" in result.error_message - - -class TestProcessCompletedEmbeddingBatch: - """Test processing completed embedding batch.""" - - @pytest.fixture - def test_dataset(self, db: Session) -> EvaluationDataset: - """Create a test dataset.""" - org = db.exec(select(Organization)).first() - project = db.exec( - select(Project).where(Project.organization_id == org.id) - ).first() - - return create_test_evaluation_dataset( - db=db, - organization_id=org.id, - project_id=project.id, - name="test_dataset_embedding", - description="Test dataset", - original_items_count=2, - duplication_factor=1, - ) - - @pytest.fixture - def eval_run_with_embedding_batch(self, db: Session, test_dataset) -> EvaluationRun: - """Create evaluation run with embedding batch job.""" - # Create a config for the evaluation run - config = create_test_config( - db, project_id=test_dataset.project_id, use_kaapi_schema=True - ) - - # Create embedding batch job - embedding_batch = BatchJob( - provider="openai", - provider_batch_id="batch_embed_123", - provider_status="completed", - job_type=BatchJobType.EMBEDDING, - total_items=4, - status="submitted", - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - inserted_at=now(), - updated_at=now(), - ) - db.add(embedding_batch) - db.commit() - db.refresh(embedding_batch) - - # Create evaluation run - eval_run = create_evaluation_run( - session=db, - run_name="test_run_embedding", - dataset_name=test_dataset.name, - dataset_id=test_dataset.id, - config_id=config.id, - config_version=1, - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - ) - eval_run.embedding_batch_job_id = embedding_batch.id - eval_run.status = "processing" - db.add(eval_run) - db.commit() - db.refresh(eval_run) - - return eval_run - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.download_batch_results") - @patch("app.crud.evaluations.processing.parse_embedding_results") - @patch("app.crud.evaluations.processing.calculate_average_similarity") - @patch("app.crud.evaluations.processing.update_traces_with_cosine_scores") - async def test_process_completed_embedding_batch_success( - self, - mock_update_traces, - mock_calculate, - mock_parse, - mock_download, - db: Session, - eval_run_with_embedding_batch, - ): - """Test successfully processing completed embedding batch.""" - # Pre-populate eval_run.cost with a response entry to verify that the - # embedding stage merges (not overwrites) existing cost data. - eval_run_with_embedding_batch.cost = { - "response": { - "model": "gpt-4o", - "input_tokens": 100, - "output_tokens": 50, - "total_tokens": 150, - "cost_usd": 0.000375, - }, - "total_cost_usd": 0.000375, - } - db.add(eval_run_with_embedding_batch) - db.commit() - db.refresh(eval_run_with_embedding_batch) - - # Raw results carry the usage payload that _build_embedding_cost_entry reads. - mock_download.return_value = [ - { - "custom_id": "trace_123", - "response": { - "body": {"usage": {"prompt_tokens": 200, "total_tokens": 200}} - }, - } - ] - mock_parse.return_value = ( - [ - { - "item_id": "item1", - "trace_id": "trace_123", - "output_embedding": [1.0, 0.0], - "ground_truth_embedding": [1.0, 0.0], - } - ], - [], - ) - mock_calculate.return_value = { - "cosine_similarity_avg": 0.95, - "cosine_similarity_std": 0.02, - "total_pairs": 1, - "per_item_scores": [ - {"item_id": "item1", "trace_id": "trace_123", "cosine_similarity": 0.95} - ], - } - - mock_openai = MagicMock() - mock_langfuse = MagicMock() - - result = await process_completed_embedding_batch( - eval_run=eval_run_with_embedding_batch, - session=db, - openai_client=mock_openai, - langfuse=mock_langfuse, - ) - - db.refresh(result) - assert result.status == "completed" - assert result.score is not None - assert "summary_scores" in result.score - summary_scores = result.score["summary_scores"] - cosine_score = next( - (s for s in summary_scores if s["name"] == "Cosine Similarity"), None - ) - assert cosine_score is not None - assert cosine_score["avg"] == 0.95 - # Denominator is surfaced for the UI alongside the scored pair count. - assert cosine_score["total_items"] == result.total_items - - # Durable per-item scores are persisted as the resync source of truth, - # so a lost/failed Langfuse write can always be backfilled later. - assert result.per_item_scores == {"trace_123": pytest.approx(0.95)} - - # Cost tracking: embedding entry is added, response entry is preserved, - # and total_cost_usd is the sum of both. - assert result.cost is not None - assert "response" in result.cost - assert "embedding" in result.cost - assert result.cost["response"]["cost_usd"] == 0.000375 - embedding_cost = result.cost["embedding"] - assert embedding_cost["model"] == "text-embedding-3-large" - assert embedding_cost["input_tokens"] == 200 - assert embedding_cost["output_tokens"] == 0 - assert embedding_cost["total_tokens"] == 200 - assert embedding_cost["cost_usd"] > 0 - assert result.cost["total_cost_usd"] == pytest.approx( - 0.000375 + embedding_cost["cost_usd"] - ) - assert result.latency is None - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.save_score") - @patch("app.crud.evaluations.processing._load_score_traces") - @patch("app.crud.evaluations.processing.download_batch_results") - @patch("app.crud.evaluations.processing.parse_embedding_results") - @patch("app.crud.evaluations.processing.calculate_average_similarity") - @patch("app.crud.evaluations.processing.update_traces_with_cosine_scores") - async def test_process_completed_embedding_batch_persists_durable_traces( - self, - mock_update_traces, - mock_calculate, - mock_parse, - mock_download, - mock_load_traces, - mock_save_score, - db: Session, - eval_run_with_embedding_batch, - ): - """When a Q&A skeleton exists, cosine is attached and full traces saved. - - Cosine display then comes straight from score_trace_url (no Langfuse). - """ - mock_download.return_value = [ - { - "custom_id": "trace_123", - "response": { - "body": {"usage": {"prompt_tokens": 200, "total_tokens": 200}} - }, - } - ] - mock_parse.return_value = ( - [ - { - "item_id": "item1", - "trace_id": "trace_123", - "output_embedding": [1.0, 0.0], - "ground_truth_embedding": [1.0, 0.0], - } - ], - [], - ) - mock_calculate.return_value = { - "cosine_similarity_avg": 0.95, - "cosine_similarity_std": 0.0, - "total_pairs": 1, - "per_item_scores": [ - {"item_id": "item1", "trace_id": "trace_123", "cosine_similarity": 0.95} - ], - } - # A durable Q&A skeleton (no scores yet) persisted at the response stage. - mock_load_traces.return_value = [ - { - "trace_id": "trace_123", - "question": "Q1", - "llm_answer": "A1", - "ground_truth_answer": "GT1", - "question_id": 1, - "scores": [], - } - ] - mock_save_score.return_value = eval_run_with_embedding_batch - - result = await process_completed_embedding_batch( - eval_run=eval_run_with_embedding_batch, - session=db, - openai_client=MagicMock(), - langfuse=MagicMock(), - ) - - # The full trace unit is persisted with cosine attached to the skeleton. - mock_save_score.assert_called_once() - saved_score = mock_save_score.call_args.kwargs["score"] - traces = saved_score["traces"] - assert len(traces) == 1 - cosine = next( - s for s in traces[0]["scores"] if s["name"] == "Cosine Similarity" - ) - assert cosine["value"] == 0.95 - assert not cosine.get("unscoreable") - assert saved_score["summary_scores"][0]["name"] == "Cosine Similarity" - - # The in-memory score carries the traces for the response. - assert result.score["traces"][0]["trace_id"] == "trace_123" - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.save_score") - @patch("app.crud.evaluations.processing._load_score_traces") - @patch("app.crud.evaluations.processing.download_batch_results") - @patch("app.crud.evaluations.processing.parse_embedding_results") - @patch("app.crud.evaluations.processing.calculate_average_similarity") - @patch("app.crud.evaluations.processing.update_traces_with_cosine_scores") - async def test_process_completed_embedding_batch_unscoreable_placeholder( - self, - mock_update_traces, - mock_calculate, - mock_parse, - mock_download, - mock_load_traces, - mock_save_score, - db: Session, - eval_run_with_embedding_batch, - ): - """Unscoreable items get a flagged 0-score placeholder on the durable trace.""" - # Flag trace_empty as unscoreable (empty model output). - eval_run_with_embedding_batch.unscoreable = {"trace_empty": "empty_output"} - db.add(eval_run_with_embedding_batch) - db.commit() - db.refresh(eval_run_with_embedding_batch) - - mock_download.return_value = [] - mock_parse.return_value = ( - [ - { - "item_id": "item1", - "trace_id": "trace_123", - "output_embedding": [1.0, 0.0], - "ground_truth_embedding": [1.0, 0.0], - } - ], - [], - ) - mock_calculate.return_value = { - "cosine_similarity_avg": 0.95, - "cosine_similarity_std": 0.0, - "total_pairs": 1, - "per_item_scores": [ - {"item_id": "item1", "trace_id": "trace_123", "cosine_similarity": 0.95} - ], - } - mock_load_traces.return_value = [ - { - "trace_id": "trace_123", - "question": "Q1", - "llm_answer": "A1", - "ground_truth_answer": "GT1", - "question_id": 1, - "scores": [], - }, - { - "trace_id": "trace_empty", - "question": "Q2", - "llm_answer": "", - "ground_truth_answer": "GT2", - "question_id": 2, - "scores": [], - }, - ] - mock_save_score.return_value = eval_run_with_embedding_batch - - await process_completed_embedding_batch( - eval_run=eval_run_with_embedding_batch, - session=db, - openai_client=MagicMock(), - langfuse=MagicMock(), - ) - - saved_score = mock_save_score.call_args.kwargs["score"] - by_id = {t["trace_id"]: t for t in saved_score["traces"]} - placeholder = by_id["trace_empty"]["scores"][0] - assert placeholder["value"] == 0 - assert placeholder["unscoreable"] is True - assert "empty_output" in placeholder["comment"] - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.save_score") - @patch("app.crud.evaluations.processing._load_score_traces") - @patch("app.crud.evaluations.processing.download_batch_results") - @patch("app.crud.evaluations.processing.parse_embedding_results") - @patch("app.crud.evaluations.processing.calculate_average_similarity") - @patch("app.crud.evaluations.processing.update_traces_with_cosine_scores") - async def test_process_completed_embedding_batch_flags_embedding_failed( - self, - mock_update_traces, - mock_calculate, - mock_parse, - mock_download, - mock_load_traces, - mock_save_score, - db: Session, - eval_run_with_embedding_batch, - ): - """A failed embedding is flagged embedding_failed across all outputs.""" - mock_download.return_value = [] - # trace_ok scored normally; trace_fail dropped by parse_embedding_results. - mock_parse.return_value = ( - [ - { - "item_id": "item1", - "trace_id": "trace_ok", - "output_embedding": [1.0, 0.0], - "ground_truth_embedding": [1.0, 0.0], - } - ], - ["trace_fail"], - ) - mock_calculate.return_value = { - "cosine_similarity_avg": 0.95, - "cosine_similarity_std": 0.0, - "total_pairs": 1, - "per_item_scores": [ - {"item_id": "item1", "trace_id": "trace_ok", "cosine_similarity": 0.95} - ], - } - mock_update_traces.return_value = [] - mock_load_traces.return_value = [ - { - "trace_id": "trace_ok", - "question": "Q1", - "llm_answer": "A1", - "ground_truth_answer": "GT1", - "question_id": 1, - "scores": [], - }, - { - "trace_id": "trace_fail", - "question": "Q2", - "llm_answer": "A2", - "ground_truth_answer": "GT2", - "question_id": 2, - "scores": [], - }, - ] - mock_save_score.return_value = eval_run_with_embedding_batch - - result = await process_completed_embedding_batch( - eval_run=eval_run_with_embedding_batch, - session=db, - openai_client=MagicMock(), - langfuse=MagicMock(), - ) - - # Flagged embedding_failed in the durable unscoreable map. - assert result.unscoreable["trace_fail"] == "embedding_failed" - - # Counted in the cosine summary's unscoreable breakdown. - cosine_summary = result.score["summary_scores"][0] - assert cosine_summary["unscoreable"] == {"embedding_failed": 1} - - # Written to Langfuse as a 0-placeholder with the reason. - write_items = mock_update_traces.call_args.kwargs["per_item_scores"] - assert { - "trace_id": "trace_fail", - "unscoreable": True, - "reason": "embedding_failed", - } in write_items - - # Rendered as a flagged 0-score on the durable trace. - saved_traces = { - t["trace_id"]: t - for t in mock_save_score.call_args.kwargs["score"]["traces"] - } - placeholder = saved_traces["trace_fail"]["scores"][0] - assert placeholder["value"] == 0 - assert placeholder["unscoreable"] is True - assert placeholder["comment"] == "Cannot compute: embedding_failed" - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.save_score") - @patch("app.crud.evaluations.processing._load_score_traces") - @patch("app.crud.evaluations.processing.download_batch_results") - @patch("app.crud.evaluations.processing.parse_embedding_results") - @patch("app.crud.evaluations.processing.calculate_average_similarity") - @patch("app.crud.evaluations.processing.update_traces_with_cosine_scores") - async def test_process_completed_embedding_batch_failed_does_not_override_empty( - self, - mock_update_traces, - mock_calculate, - mock_parse, - mock_download, - mock_load_traces, - mock_save_score, - db: Session, - eval_run_with_embedding_batch, - ): - """A trace already flagged empty_* keeps its reason (no embedding_failed).""" - eval_run_with_embedding_batch.unscoreable = {"trace_x": "empty_output"} - db.add(eval_run_with_embedding_batch) - db.commit() - db.refresh(eval_run_with_embedding_batch) - - mock_download.return_value = [] - mock_parse.return_value = ( - [ - { - "item_id": "item1", - "trace_id": "trace_ok", - "output_embedding": [1.0, 0.0], - "ground_truth_embedding": [1.0, 0.0], - } - ], - ["trace_x"], - ) - mock_calculate.return_value = { - "cosine_similarity_avg": 0.95, - "cosine_similarity_std": 0.0, - "total_pairs": 1, - "per_item_scores": [ - {"item_id": "item1", "trace_id": "trace_ok", "cosine_similarity": 0.95} - ], - } - mock_update_traces.return_value = [] - mock_load_traces.return_value = None - mock_save_score.return_value = eval_run_with_embedding_batch - - result = await process_completed_embedding_batch( - eval_run=eval_run_with_embedding_batch, - session=db, - openai_client=MagicMock(), - langfuse=MagicMock(), - ) - - # setdefault preserves the original empty_output reason. - assert result.unscoreable["trace_x"] == "empty_output" - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.download_batch_results") - @patch("app.crud.evaluations.processing.parse_embedding_results") - async def test_process_completed_embedding_batch_no_results( - self, - mock_parse, - mock_download, - db: Session, - eval_run_with_embedding_batch, - ): - """Test processing with no valid embedding results.""" - mock_download.return_value = [] - mock_parse.return_value = ([], []) - - mock_openai = MagicMock() - mock_langfuse = MagicMock() - - result = await process_completed_embedding_batch( - eval_run=eval_run_with_embedding_batch, - session=db, - openai_client=mock_openai, - langfuse=mock_langfuse, - ) - - db.refresh(result) - assert result.status == "completed" - assert "failed" in result.error_message.lower() - - -class TestCheckAndProcessEvaluation: - """Test check and process evaluation function.""" - - @pytest.fixture - def test_dataset(self, db: Session) -> EvaluationDataset: - """Create a test dataset.""" - org = db.exec(select(Organization)).first() - project = db.exec( - select(Project).where(Project.organization_id == org.id) - ).first() - - return create_test_evaluation_dataset( - db=db, - organization_id=org.id, - project_id=project.id, - name="test_dataset_check", - description="Test dataset", - original_items_count=2, - duplication_factor=1, - ) - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.get_batch_job") - @patch("app.crud.evaluations.processing.poll_batch_status") - @patch("app.crud.evaluations.processing.process_completed_evaluation") - async def test_check_and_process_evaluation_completed( - self, - mock_process, - mock_poll, - mock_get_batch, - db: Session, - test_dataset, - ): - """Test checking evaluation with completed batch.""" - # Create a config for the evaluation run - config = create_test_config( - db, project_id=test_dataset.project_id, use_kaapi_schema=True - ) - - # Create batch job with output file (successful completion) - batch_job = BatchJob( - provider="openai", - provider_batch_id="batch_abc", - provider_status="completed", - provider_output_file_id="output-file-123", - job_type=BatchJobType.EVALUATION, - total_items=2, - status="submitted", - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - inserted_at=now(), - updated_at=now(), - ) - db.add(batch_job) - db.commit() - db.refresh(batch_job) - - # Create evaluation run - eval_run = create_evaluation_run( - session=db, - run_name="test_run", - dataset_name=test_dataset.name, - dataset_id=test_dataset.id, - config_id=config.id, - config_version=1, - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - ) - eval_run.batch_job_id = batch_job.id - eval_run.status = "processing" - db.add(eval_run) - db.commit() - db.refresh(eval_run) - - mock_get_batch.return_value = batch_job - mock_poll.return_value = { - "provider_status": "completed", - "provider_output_file_id": "output-file-123", - "error_file_id": None, - "request_counts": {"total": 2, "completed": 2, "failed": 0}, - } - mock_process.return_value = eval_run - - mock_openai = MagicMock() - mock_langfuse = MagicMock() - - result = await check_and_process_evaluation( - eval_run=eval_run, - session=db, - openai_client=mock_openai, - langfuse=mock_langfuse, - ) - - assert result["action"] == "processed" - assert result["run_id"] == eval_run.id - mock_process.assert_called_once() - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.get_batch_job") - @patch("app.crud.evaluations.processing.poll_batch_status") - async def test_check_and_process_evaluation_failed( - self, - mock_poll, - mock_get_batch, - db: Session, - test_dataset, - ): - """Test checking evaluation with failed batch.""" - # Create a config for the evaluation run - config = create_test_config( - db, project_id=test_dataset.project_id, use_kaapi_schema=True - ) - - # Create failed batch job - batch_job = BatchJob( - provider="openai", - provider_batch_id="batch_fail", - provider_status="failed", - job_type=BatchJobType.EVALUATION, - total_items=2, - status="submitted", - error_message="Provider error", - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - inserted_at=now(), - updated_at=now(), - ) - db.add(batch_job) - db.commit() - db.refresh(batch_job) - - # Create evaluation run - eval_run = create_evaluation_run( - session=db, - run_name="test_run_fail", - dataset_name=test_dataset.name, - dataset_id=test_dataset.id, - config_id=config.id, - config_version=1, - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - ) - eval_run.batch_job_id = batch_job.id - eval_run.status = "processing" - db.add(eval_run) - db.commit() - db.refresh(eval_run) - - mock_get_batch.return_value = batch_job - mock_poll.return_value = { - "provider_status": "failed", - "provider_output_file_id": None, - "error_file_id": None, - "error_message": "Provider error", - "request_counts": {"total": 2, "completed": 0, "failed": 2}, - } - - mock_openai = MagicMock() - mock_langfuse = MagicMock() - - result = await check_and_process_evaluation( - eval_run=eval_run, - session=db, - openai_client=mock_openai, - langfuse=mock_langfuse, - ) - - assert result["action"] == "failed" - assert result["current_status"] == "failed" - db.refresh(eval_run) - assert eval_run.status == "failed" - - @pytest.fixture - def all_requests_failed_setup( - self, db: Session, test_dataset - ) -> tuple[BatchJob, EvaluationRun]: - """Create a BatchJob (completed, no output file) and a processing EvaluationRun for the all-requests-failed scenario.""" - config = create_test_config( - db, project_id=test_dataset.project_id, use_kaapi_schema=True - ) - - batch_job = BatchJob( - provider="openai", - provider_batch_id="batch_all_fail", - provider_status="completed", - job_type=BatchJobType.EVALUATION, - total_items=9, - status="submitted", - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - inserted_at=now(), - updated_at=now(), - ) - db.add(batch_job) - db.commit() - db.refresh(batch_job) - - eval_run = create_evaluation_run( - session=db, - run_name="test_run_all_fail", - dataset_name=test_dataset.name, - dataset_id=test_dataset.id, - config_id=config.id, - config_version=1, - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - ) - eval_run.batch_job_id = batch_job.id - eval_run.status = "processing" - db.add(eval_run) - db.commit() - db.refresh(eval_run) - - return batch_job, eval_run - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.get_batch_job") - @patch("app.crud.evaluations.processing.poll_batch_status") - @patch("app.crud.evaluations.processing.OpenAIBatchProvider") - async def test_check_and_process_evaluation_completed_all_requests_failed( - self, - mock_provider_cls, - mock_poll, - mock_get_batch, - db: Session, - all_requests_failed_setup: tuple[BatchJob, EvaluationRun], - ): - """Test batch completed but all requests failed — both batch_job and eval_run get error_message.""" - batch_job, eval_run = all_requests_failed_setup - - mock_get_batch.return_value = batch_job - mock_poll.return_value = { - "provider_status": "completed", - "provider_output_file_id": None, - "error_file_id": "error-file-abc", - "request_counts": {"total": 9, "completed": 0, "failed": 9}, - } - - # Mock the provider instance returned by OpenAIBatchProvider(client=...) - # to return realistic error file content - error_lines = "\n".join( - [ - json.dumps( - { - "id": f"batch_req_{i}", - "custom_id": f"id-{i}", - "response": { - "status_code": 400, - "body": { - "error": { - "message": "Unsupported parameter: 'temperature' is not supported with this model.", - } - }, - }, - "error": None, - } - ) - for i in range(9) - ] - ) - mock_provider_instance = mock_provider_cls.return_value - mock_provider_instance.download_file.return_value = error_lines - - mock_openai = MagicMock() - mock_langfuse = MagicMock() - - result = await check_and_process_evaluation( - eval_run=eval_run, - session=db, - openai_client=mock_openai, - langfuse=mock_langfuse, - ) - - assert result["action"] == "failed" - assert result["current_status"] == "failed" - assert "temperature" in result["error"] - assert "(9/9 requests)" in result["error"] - - # Verify eval_run updated with error - db.refresh(eval_run) - assert eval_run.status == "failed" - assert "temperature" in eval_run.error_message - - # Verify batch_job updated with error - db.refresh(batch_job) - assert "temperature" in batch_job.error_message - assert "(9/9 requests)" in batch_job.error_message - - -class TestExtractBatchErrorMessage: - """Test extracting error messages from OpenAI error files.""" - - def test_single_unique_error(self) -> None: - """Test error file where all requests have the same error.""" - error_lines = [] - for i in range(5): - error_lines.append( - json.dumps( - { - "id": f"batch_req_{i}", - "custom_id": f"id-{i}", - "response": { - "status_code": 400, - "body": { - "error": { - "message": "Unsupported parameter: 'temperature' is not supported with this model.", - "type": "invalid_request_error", - } - }, - }, - "error": None, - } - ) - ) - error_content = "\n".join(error_lines) - - mock_provider = MagicMock() - mock_provider.download_file.return_value = error_content - - mock_session = MagicMock() - mock_batch_job = MagicMock() - mock_batch_job.id = 1 - - result = _extract_batch_error_message( - provider=mock_provider, - error_file_id="error-file-123", - batch_job=mock_batch_job, - session=mock_session, - ) - - assert "Unsupported parameter" in result - assert "(5/5 requests)" in result - mock_provider.download_file.assert_called_once_with("error-file-123") - - def test_multiple_unique_errors_picks_most_common(self) -> None: - """Test error file with mixed errors; picks the most frequent one.""" - error_lines = [] - # 3 requests with temperature error - for i in range(3): - error_lines.append( - json.dumps( - { - "id": f"batch_req_{i}", - "custom_id": f"id-{i}", - "response": { - "status_code": 400, - "body": { - "error": { - "message": "Unsupported parameter: 'temperature'", - } - }, - }, - "error": None, - } - ) - ) - # 1 request with rate limit error - error_lines.append( - json.dumps( - { - "id": "batch_req_3", - "custom_id": "id-3", - "response": { - "status_code": 429, - "body": { - "error": { - "message": "Rate limit exceeded", - } - }, - }, - "error": None, - } - ) - ) - error_content = "\n".join(error_lines) - - mock_provider = MagicMock() - mock_provider.download_file.return_value = error_content - - mock_session = MagicMock() - mock_batch_job = MagicMock() - mock_batch_job.id = 1 - - result = _extract_batch_error_message( - provider=mock_provider, - error_file_id="error-file-123", - batch_job=mock_batch_job, - session=mock_session, - ) - - assert "Unsupported parameter: 'temperature'" in result - assert "(3/4 requests)" in result - - -class TestPollAllPendingEvaluations: - """Test polling all pending evaluations.""" - - @pytest.fixture - def test_dataset(self, db: Session) -> EvaluationDataset: - """Create a test dataset.""" - org = db.exec(select(Organization)).first() - project = db.exec( - select(Project).where(Project.organization_id == org.id) - ).first() - - return create_test_evaluation_dataset( - db=db, - organization_id=org.id, - project_id=project.id, - name="test_dataset_poll", - description="Test dataset", - original_items_count=2, - duplication_factor=1, - ) - - @pytest.mark.asyncio - async def test_poll_all_pending_evaluations_no_pending( - self, db: Session, test_dataset - ): - """Test polling with no pending evaluations.""" - result = await poll_all_pending_evaluations(session=db) - - assert result["total"] == 0 - assert result["processed"] == 0 - assert result["failed"] == 0 - assert result["still_processing"] == 0 - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.check_and_process_evaluation") - @patch("app.crud.evaluations.processing.get_openai_client") - @patch("app.crud.evaluations.processing.get_langfuse_client") - async def test_poll_all_pending_evaluations_with_runs( - self, - mock_langfuse_client, - mock_openai_client, - mock_check, - db: Session, - test_dataset, - ): - """Test polling with pending evaluations.""" - # Create a config for the evaluation run - config = create_test_config( - db, project_id=test_dataset.project_id, use_kaapi_schema=True - ) - - # Create batch job - batch_job = BatchJob( - provider="openai", - provider_batch_id="batch_test", - provider_status="in_progress", - job_type=BatchJobType.EVALUATION, - total_items=2, - status="submitted", - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - inserted_at=now(), - updated_at=now(), - ) - db.add(batch_job) - db.commit() - db.refresh(batch_job) - - # Create pending evaluation run - eval_run = create_evaluation_run( - session=db, - run_name="test_pending_run", - dataset_name=test_dataset.name, - dataset_id=test_dataset.id, - config_id=config.id, - config_version=1, - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - ) - eval_run.batch_job_id = batch_job.id - eval_run.status = "processing" - db.add(eval_run) - db.commit() - db.refresh(eval_run) - - mock_openai_client.return_value = MagicMock() - mock_langfuse_client.return_value = MagicMock() - mock_check.return_value = { - "run_id": eval_run.id, - "run_name": eval_run.run_name, - "action": "no_change", - } - - result = await poll_all_pending_evaluations(session=db) - - assert result["total"] == 1 - assert result["still_processing"] == 1 - mock_check.assert_called_once() - - @pytest.mark.asyncio - @patch("app.crud.evaluations.processing.check_and_process_evaluation") - async def test_poll_all_pending_evaluations_excludes_fast_runs( - self, - mock_check, - db: Session, - test_dataset, - ): - """Fast-mode runs are handled synchronously and have no provider batch - job, so the batch poller must skip them. Otherwise it picks up an - in-flight fast run (status='processing', no batch_job_id yet) and wrongly - marks it 'Checking failed: ... has no batch_job_id'.""" - config = create_test_config( - db, project_id=test_dataset.project_id, use_kaapi_schema=True - ) - - eval_run = create_evaluation_run( - session=db, - run_name="test_fast_run", - dataset_name=test_dataset.name, - dataset_id=test_dataset.id, - config_id=config.id, - config_version=1, - organization_id=test_dataset.organization_id, - project_id=test_dataset.project_id, - run_mode=RunModeEnum.FAST, - ) - eval_run.status = "processing" - db.add(eval_run) - db.commit() - db.refresh(eval_run) - - result = await poll_all_pending_evaluations(session=db) - - assert result["total"] == 0 - mock_check.assert_not_called() - db.refresh(eval_run) - assert eval_run.status == "processing" - assert eval_run.error_message is None diff --git a/backend/app/tests/services/evaluations/test_dataset_v2.py b/backend/app/tests/services/evaluations/test_dataset_v2.py index 8b4ecc92d..0fcb8d8ff 100644 --- a/backend/app/tests/services/evaluations/test_dataset_v2.py +++ b/backend/app/tests/services/evaluations/test_dataset_v2.py @@ -1,10 +1,9 @@ -"""Tests for the Langfuse-free dataset upload service (`upload_dataset(use_langfuse=False)`). +"""Tests for the Langfuse-free dataset upload service (`upload_dataset`). Covers the v2 upload slice of the three-metric SRD (docs/srd-three-metric-evaluation-verdict.md, FR-19/FR-20): -- FR-19: creates the `evaluation_dataset` row with `langfuse_dataset_id` null and - never touches the Langfuse client. +- FR-19: creates the `evaluation_dataset` row with `langfuse_dataset_id` null. - FR-20: stores only the original rows (no physical duplication) and records the original/total counts and stored duplication factor. @@ -34,10 +33,10 @@ class TestUploadDatasetV2: - def test_creates_langfuse_free_row_without_calling_langfuse( + def test_creates_langfuse_free_row( self, db: Session, user_api_key: TestAuthContext ) -> None: - """FR-19: row has null langfuse id; no Langfuse client/upload is called.""" + """FR-19: row has null langfuse id and points at the stored CSV.""" name = f"v2-upload-{random_lower_string()}" with ( patch(f"{_DATASET}.get_cloud_storage", return_value=MagicMock()), @@ -45,8 +44,6 @@ def test_creates_langfuse_free_row_without_calling_langfuse( f"{_DATASET}.upload_csv_to_object_store", return_value="s3://bucket/datasets/v2.csv", ), - patch(f"{_DATASET}.get_langfuse_client") as mock_langfuse_client, - patch(f"{_DATASET}.upload_dataset_to_langfuse") as mock_langfuse_upload, ): dataset = upload_dataset( session=db, @@ -56,12 +53,8 @@ def test_creates_langfuse_free_row_without_calling_langfuse( duplication_factor=5, organization_id=user_api_key.organization_id, project_id=user_api_key.project_id, - use_langfuse=False, ) - mock_langfuse_client.assert_not_called() - mock_langfuse_upload.assert_not_called() - persisted = db.get(EvaluationDataset, dataset.id) assert persisted is not None assert persisted.langfuse_dataset_id is None @@ -78,8 +71,6 @@ def test_stores_original_rows_and_factor_metadata( f"{_DATASET}.upload_csv_to_object_store", return_value="s3://bucket/datasets/v2.csv", ) as mock_upload, - patch(f"{_DATASET}.get_langfuse_client"), - patch(f"{_DATASET}.upload_dataset_to_langfuse"), ): dataset = upload_dataset( session=db, @@ -89,7 +80,6 @@ def test_stores_original_rows_and_factor_metadata( duplication_factor=5, organization_id=user_api_key.organization_id, project_id=user_api_key.project_id, - use_langfuse=False, ) # The bytes handed to S3 are the original rows, not a duplicated payload. @@ -105,11 +95,10 @@ def test_stores_original_rows_and_factor_metadata( def test_object_store_returns_no_url_raises_500( self, db: Session, user_api_key: TestAuthContext ) -> None: - """S3 is the sole source in v2, so a missing url is fatal (no Langfuse fallback).""" + """S3 is the sole copy of the items, so a missing url is fatal.""" with ( patch(f"{_DATASET}.get_cloud_storage", return_value=MagicMock()), patch(f"{_DATASET}.upload_csv_to_object_store", return_value=None), - patch(f"{_DATASET}.get_langfuse_client"), ): with pytest.raises(HTTPException) as exc: upload_dataset( @@ -120,7 +109,30 @@ def test_object_store_returns_no_url_raises_500( duplication_factor=2, organization_id=user_api_key.organization_id, project_id=user_api_key.project_id, - use_langfuse=False, + ) + + assert exc.value.status_code == 500 + + def test_object_store_exception_raises_500( + self, db: Session, user_api_key: TestAuthContext + ) -> None: + """A storage error is surfaced as a 500, never a dataset row without a CSV.""" + with ( + patch(f"{_DATASET}.get_cloud_storage", return_value=MagicMock()), + patch( + f"{_DATASET}.upload_csv_to_object_store", + side_effect=RuntimeError("s3 down"), + ), + ): + with pytest.raises(HTTPException) as exc: + upload_dataset( + session=db, + csv_content=_CSV, + dataset_name=f"v2-s3err-{random_lower_string()}", + description=None, + duplication_factor=1, + organization_id=user_api_key.organization_id, + project_id=user_api_key.project_id, ) assert exc.value.status_code == 500 diff --git a/backend/app/tests/services/evaluations/test_evaluation_service_s3.py b/backend/app/tests/services/evaluations/test_evaluation_service_s3.py index b6ac76d4c..172f40a77 100644 --- a/backend/app/tests/services/evaluations/test_evaluation_service_s3.py +++ b/backend/app/tests/services/evaluations/test_evaluation_service_s3.py @@ -3,17 +3,11 @@ from collections.abc import Callable from typing import Optional from unittest.mock import MagicMock, patch -from uuid import uuid4 import pytest -from fastapi import HTTPException from app.models import EvaluationRun -from app.services.evaluations.evaluation import ( - get_evaluation_with_scores, - validate_and_start_batch_evaluation, -) - +from app.services.evaluations.evaluation import get_evaluation_with_scores # A v2 judge run's deterministic run-level overall — not trace-derived, so the # trace-merge reconstructions must preserve it rather than rebuild it away. @@ -320,113 +314,3 @@ def test_resync_skipped_when_cache_unreadable( assert error is not None mock_fetch_langfuse.assert_not_called() # did not re-fetch mock_save_score.assert_not_called() # did not overwrite the cache - - -_MODULE = "app.services.evaluations.evaluation" - - -def _dataset() -> MagicMock: - dataset = MagicMock() - dataset.id = 1 - dataset.name = "ds" - dataset.langfuse_dataset_id = "lf_ds_1" - dataset.object_store_url = None - return dataset - - -def _config(provider: str) -> MagicMock: - config = MagicMock() - config.completion.provider = provider - config.completion.type = "text" - config.completion.params = {"model": "m"} - return config - - -class TestValidateAndStartBatchEvaluation: - """Test validate_and_start_batch_evaluation provider gating and queueing.""" - - @patch(f"{_MODULE}.resolve_evaluation_config") - @patch(f"{_MODULE}.get_dataset_by_id") - def test_unsupported_provider_raises_422( - self, mock_get_dataset, mock_resolve - ) -> None: - mock_get_dataset.return_value = _dataset() - mock_resolve.return_value = (_config("anthropic"), None) - - with pytest.raises(HTTPException) as exc: - validate_and_start_batch_evaluation( - session=MagicMock(), - dataset_id=1, - experiment_name="exp", - config_id=uuid4(), - config_version=1, - organization_id=1, - project_id=2, - ) - - assert exc.value.status_code == 422 - assert "not supported" in exc.value.detail - - @patch(f"{_MODULE}.update_evaluation_run") - @patch(f"{_MODULE}.start_evaluation_batch_submission") - @patch(f"{_MODULE}.create_evaluation_run") - @patch(f"{_MODULE}.resolve_evaluation_config") - @patch(f"{_MODULE}.get_dataset_by_id") - def test_queue_failure_marks_run_failed( - self, - mock_get_dataset, - mock_resolve, - mock_create_run, - mock_submit, - mock_update, - ) -> None: - """A failure enqueueing the celery task flips the run to failed (no raise).""" - mock_get_dataset.return_value = _dataset() - mock_resolve.return_value = (_config("openai"), None) - - eval_run = MagicMock() - eval_run.id = 99 - mock_create_run.return_value = eval_run - mock_submit.side_effect = Exception("broker down") - mock_update.return_value = eval_run - - result = validate_and_start_batch_evaluation( - session=MagicMock(), - dataset_id=1, - experiment_name="exp", - config_id=uuid4(), - config_version=1, - organization_id=1, - project_id=2, - ) - - assert result is eval_run - update_arg = mock_update.call_args.kwargs["update"] - assert update_arg.status == "failed" - assert "Failed to queue batch submission" in update_arg.error_message - - @patch(f"{_MODULE}.start_evaluation_batch_submission") - @patch(f"{_MODULE}.create_evaluation_run") - @patch(f"{_MODULE}.resolve_evaluation_config") - @patch(f"{_MODULE}.get_dataset_by_id") - def test_success_returns_run( - self, mock_get_dataset, mock_resolve, mock_create_run, mock_submit - ) -> None: - mock_get_dataset.return_value = _dataset() - mock_resolve.return_value = (_config("google-aistudio"), None) - eval_run = MagicMock() - mock_create_run.return_value = eval_run - mock_submit.return_value = "task-1" - - result = validate_and_start_batch_evaluation( - session=MagicMock(), - dataset_id=1, - experiment_name="exp", - config_id=uuid4(), - config_version=1, - organization_id=1, - project_id=2, - ) - - assert result is eval_run - mock_submit.assert_called_once() diff --git a/docs/architecture/kaapi-evaluations-ARCHITECTURE.md b/docs/architecture/kaapi-evaluations-ARCHITECTURE.md index 280b2010b..c9efec060 100644 --- a/docs/architecture/kaapi-evaluations-ARCHITECTURE.md +++ b/docs/architecture/kaapi-evaluations-ARCHITECTURE.md @@ -1,5 +1,7 @@ # Kaapi Evaluations — Architecture Overview +> **Note:** the v1 text write routes (`POST /api/v1/evaluations`, `POST /api/v1/evaluations/datasets`, `POST /api/v1/evaluations/{id}/improve-prompt`) and the text **batch** pipeline (`crud/evaluations/batch.py`, `processing.py`, embedding batches, text-batch cron polling) have been removed; text runs are v2 fast/judged only. Sections describing them are historical — see `docs/wiki/modules/evaluations.md` for the current surface. + ## Purpose The **Evaluations** module lets a one measure _how good_ an LLM diff --git a/docs/wiki/modules/evaluations.md b/docs/wiki/modules/evaluations.md index 7956d75c0..9249cd9ce 100644 --- a/docs/wiki/modules/evaluations.md +++ b/docs/wiki/modules/evaluations.md @@ -1,18 +1,18 @@ # Module: Evaluations -Measures LLM config quality on golden datasets. Three families sharing one dataset/run schema: `text` (cosine + LLM-judge, OpenAI), `stt` (WER/CER, Gemini), `tts` (human annotation; Gemini batch + Sarvam/ElevenLabs sync). Batch-first (provider Batch APIs, not `/llm/call`), plus a synchronous `fast` text mode capped at `EVAL_FAST_MAX_UNIQUE_ROWS`. +Measures LLM config quality on golden datasets. Three families sharing one dataset/run schema: `text` (cosine + LLM-judge, OpenAI), `stt` (WER/CER, Gemini), `tts` (human annotation; Gemini batch + Sarvam/ElevenLabs sync). STT/TTS are batch-first (provider Batch APIs, not `/llm/call`); text runs are `fast`-only (chunked Celery fan-out, capped at `EVAL_FAST_MAX_UNIQUE_ROWS`) — the v1 text-batch pipeline was removed, though historical `run_mode=batch` rows stay readable. Deep dive: `docs/architecture/kaapi-evaluations-ARCHITECTURE.md` (§3 data model, §5 text pipeline, §6 STT, §7 TTS, §8 batch infra, §9 cron, §12 design decisions). All paths relative to `backend/app/`. ## Routes -- `api/routes/evaluations/dataset.py`, `api/routes/evaluations/evaluation.py` — text datasets + runs (v1, `/api/v1`) -- `api/routes/evaluations/v2/evaluation.py` — `POST /api/v2/evaluations`, replica of v1 run trigger + native ground-truth LLM judge (Langfuse-free); mounted under `settings.API_V2_STR`; rate limited per org (`evaluations` bucket, see `cross-cutting/rate-limiting.md`) +- `api/routes/evaluations/dataset.py`, `api/routes/evaluations/evaluation.py` — v1 (`/api/v1`) **read/delete only**: `GET /evaluations`, `GET /evaluations/{id}` (incl. `get_trace_info`/`resync_score` Langfuse score fetch for historical runs), `GET /evaluations/datasets`, `GET`/`DELETE /evaluations/datasets/{id}`. The v1 writes (`POST /evaluations`, `POST /evaluations/datasets`, `POST /evaluations/{id}/improve-prompt`) were removed in favour of v2. `v2/dataset.py` reuses `_dataset_to_response` from the v1 dataset module. +- `api/routes/evaluations/v2/evaluation.py` — `POST /api/v2/evaluations`, the only text run trigger: always fast + native LLM judge (Langfuse-free); mounted under `settings.API_V2_STR`; rate limited per org (`evaluations` bucket, see `cross-cutting/rate-limiting.md`) - `api/routes/evaluations/v2/dataset.py` — `POST /api/v2/evaluations/datasets`, Langfuse-free dataset upload; stores only the original CSV in S3 and records `duplication_factor` as metadata (rows expanded ×factor at run time, not physically duplicated) -- `api/routes/evaluations/v2/prompt_improvement.py` — `POST /api/v2/evaluations/{evaluation_id}/improve-prompt`, prompt iteration off the three-metric judge results (requires an `is_judge_run` run); same body as v1, returns a recommendation of type `prompt`; rate limited per org (`prompt_improvement` bucket, see `cross-cutting/rate-limiting.md`) +- `api/routes/evaluations/v2/prompt_improvement.py` — `POST /api/v2/evaluations/{evaluation_id}/improve-prompt`, prompt iteration off the three-metric judge results (requires an `is_judge_run` run); body is `{callback_url}`, returns a recommendation of type `prompt`; rate limited per org (`prompt_improvement` bucket, see `cross-cutting/rate-limiting.md`) - `api/routes/evaluations/v2/iteration.py` — `POST /api/v2/evaluations/iterations`, kicks off the automated eval → improve-prompt → eval loop (see Async); returns `202` with an `EvaluationIterationRunImmediatePublic` handle, final round-by-round report delivered to `callback_url` - `api/routes/stt_evaluations/`, `api/routes/tts_evaluations/` — STT/TTS -- `api/routes/cron.py` — batch polling trigger +- `api/routes/cron.py` — cron trigger: STT/TTS batch polling, fast-eval barrier, iteration resumes ## Tables (SQLModel) | Table | Model | @@ -33,34 +33,34 @@ Key `TTSResult` JSONB fields (migration 092; `JSONB(none_as_null=True)` on `scor `EvaluationIterationRun` is a thin bookkeeping row only (`status`, `stop_reason`, `dataset_id`, `config_id`, `initial_config_version`, `callback_url`, `error_message`) — round-by-round state (`round_number`, `current_eval_run_id`, `current_improvement_job_id`, `history`, `best_*`, `consecutive_low_delta_rounds`) lives entirely in the LangGraph checkpoint keyed by `thread_id = str(id)`, not on this table. No FK to `EvaluationRun`/`Job`; those are referenced only inside the checkpoint state. ## Services / CRUD -- `services/evaluations/` — `evaluation.py`, `dataset.py` (`upload_dataset`; `use_langfuse=False` is the v2 Langfuse-free upload), `fast.py` (`validate_fast_evaluation_inputs` extracted for reuse by both the direct eval-start path and the iteration loop), `batch_job.py`, `validators.py`, `prompt_improvement.py`, `iteration.py` (`validate_and_start_evaluation_iteration`, `compute_round_scores`), `iteration_graph.py` (the LangGraph `StateGraph`: nodes + graph wiring only), `iteration_state.py` (`EvaluationIterationState`, `advance_round_state` — the pure per-round bookkeeping/stop arithmetic, `build_iteration_report`), `iteration_checkpointer.py` (`get_evaluation_iteration_checkpointer`, psycopg pool) +- `services/evaluations/` — `evaluation.py`, `dataset.py` (`upload_dataset` — S3-only, the CSV upload is mandatory), `fast.py` (`validate_fast_evaluation_inputs` extracted for reuse by both the direct eval-start path and the iteration loop), `validators.py`, `prompt_improvement.py`, `iteration.py` (`validate_and_start_evaluation_iteration`, `compute_round_scores`), `iteration_graph.py` (the LangGraph `StateGraph`: nodes + graph wiring only), `iteration_state.py` (`EvaluationIterationState`, `advance_round_state` — the pure per-round bookkeeping/stop arithmetic, `build_iteration_report`), `iteration_checkpointer.py` (`get_evaluation_iteration_checkpointer`, psycopg pool) - `services/stt_evaluations/`, `services/tts_evaluations/` - TTS (`services/tts_evaluations/`): `constants.py` is flat module-level constants: `GEMINI_TTS_MODELS` (`gemini-3.8-flash-tts`, `gemini-3.8-flash-lite-tts`; Gemini Batch), `DEPRECATED_GEMINI_TTS_MODELS` (`gemini-2.5-pro-preview-tts`, `gemini-3.1-flash-tts-preview` — not accepted for new runs, but kept in `GEMINI_BATCH_TTS_MODELS`, which submission and the cron use for routing, so in-flight runs finish), `SARVAM_TTS_MODELS` (`bulbul:v3`) and `ELEVENLABS_TTS_MODELS` (`eleven_v4`, `eleven_v3`) — the latter two synthesized directly; `SUPPORTED_TTS_MODELS` (the request validator's allow-list) is their concatenation. Voices: `TTSEvaluationRunCreate.models` items are a model string or `TTSModelVoice` `{model, voice?}` (`extra="forbid"`; strings normalised to the object form, duplicate models rejected since result rows are keyed by model). `services/tts_evaluations/voices.py` (`voices_for_model`, `default_voice_for_model`, `resolve_voice`) is the one source for allowed/default voices — a separate module because the ElevenLabs names are the keys of `models/llm/constants.py::ELEVENLABS_VOICE_TO_ID`, which `constants.py` cannot import. Sets: Gemini `GEMINI_TTS_VOICES` (30 prebuilt, case-sensitive, default `DEFAULT_VOICE_NAME` `Kore`), Sarvam `SARVAM_TTS_VOICES` (37 bulbul:v3 speakers, client casing lowered, default `SARVAM_SPEAKER` `shubh`), ElevenLabs names mapped to voice IDs at synthesis via `mappers.voice_to_id` (default `DEFAULT_ELEVENLABS_VOICE` `Rahul`). The resolved voice is stamped on `tts_result.voice` (migration 092); NULL rows (pre-092 runs) fall back to `default_voice_for_model`. `run.providers` stays a list of model names; the create response's `run_metadata.voices` is the per-model resolved voice (legacy `voice_name` kept). Language: submission maps the dataset's `language_id` → `Language.locale` → BCP-47 via `LOCALE_TO_BCP47` (`hi` → `hi-IN`, `or` → `od-IN`), defaulting to `DEFAULT_TTS_LANGUAGE` (`en-IN`); Sarvam gets the BCP-47 tag, ElevenLabs the ISO code via `BCP47_TO_ELEVENLABS_LANG` (unmapped → auto-detect). `sync_generation.py` holds `synthesize_sarvam` / `synthesize_elevenlabs` (keyword `voice`, per row from `tts_result.voice`; an ElevenLabs name without an ID fails only that row; raw 24 kHz/16-bit/mono PCM; Sarvam's multi-chunk WAVs are header-stripped per chunk) — retries are the SDKs' built-in ones; a failed sample is marked FAILED with `" synthesis failed: "`. `crud/tts_evaluations/run.py::finalize_tts_run_status` is the single run-status rule (locks the run row `FOR UPDATE`, counts results: `processing` while any row is PENDING or PROCESSING, `failed` when no row succeeded, else `completed` with `"N synthesis(es) failed"` if some failed) and is called only by the TTS cron; workers only write `tts_result` rows, so one model failing never fails the run and the final status lags by up to one `CRON_INTERVAL_MINUTES`. -- `crud/evaluations/` — `core.py`, `batch.py`, `fast.py` (orchestration + S3/OpenAI IO only; the pieces below carry the rest), `fast_results.py` (pure per-item S3 unit shapes, usage sums, failure threshold), `fast_chunks.py` (`batch_job` bookkeeping + chunk queries/cleanup), `fast_cosine.py` (pure v1 cosine scoring), `fast_traces.py` (pure `TraceData` building), `judge_stage.py` (run-level v2 judge: `resolve_config_prompt`, `judge_rows` pool, per-metric summary rollup), `judge_prompts.py` (rubric text, moved out of `score.py`), `retry.py` (shared OpenAI retry policy), `judge.py` (`METRIC_REGISTRY` + combined judge call; `ground_truth`, `prompt`, and `knowledge_base` metrics, applied per-row by which required inputs the row carries, each spec carrying a `weight` for the overall rollup), `score.py` (`VerdictEnum`/`verdict_from_score`, `OverallSummary`/`compute_overall_summary`), `summary.py` (`generate_run_ai_summary` — one-shot Anthropic `messages.create` call via `ClaudeProvider`, plain-text output — deliberately NOT a `json_schema` `output_config`, since a quotation mark in the prose reads as the JSON string terminator and silently truncates the note; `stop_reason != STOP_REASON_COMPLETE` (the shared `end_turn` constant in `services/llm/providers/claude.py`) is logged as a truncation warning; prompt carries every trace's raw per-question scores + judge rationale, golden/generated answers, and the evaluated config, each trace keyed on `question_id` (the 1-based dataset row number from `merge.py`, cited back as "Question N") rather than the Langfuse `trace_id`, and returns a severity-ranked diagnostic note, not just a qualitative band summary), `embeddings.py`, `cost.py`, `langfuse.py`, `merge.py`, `processing.py`, `cron.py`, `iteration.py` (thin-row CRUD for the iteration loop) -- `crud/evaluations/` — `core.py`, `batch.py`, `fast.py` (orchestration + S3/OpenAI IO only; the pieces below carry the rest), `fast_results.py` (pure per-item S3 unit shapes incl. fast-only `latency_ms`, usage sums, failure threshold), `fast_chunks.py` (`batch_job` bookkeeping + chunk queries/cleanup), `fast_cosine.py` (pure v1 cosine scoring), `fast_traces.py` (pure `TraceData` building), `judge_stage.py` (run-level v2 judge: `resolve_config_prompt`, `judge_rows` pool, per-metric summary rollup), `judge_prompts.py` (rubric text, moved out of `score.py`), `retry.py` (shared OpenAI retry policy), `judge.py` (`METRIC_REGISTRY` + combined judge call; `ground_truth`, `prompt`, and `knowledge_base` metrics, applied per-row by which required inputs the row carries, each spec carrying a `weight` for the overall rollup), `score.py` (`VerdictEnum`/`verdict_from_score`, `OverallSummary`/`compute_overall_summary`), `summary.py` (`generate_run_ai_summary` — one-shot Anthropic `messages.create` call via `ClaudeProvider`, plain-text output — deliberately NOT a `json_schema` `output_config`, since a quotation mark in the prose reads as the JSON string terminator and silently truncates the note; `stop_reason != STOP_REASON_COMPLETE` (the shared `end_turn` constant in `services/llm/providers/claude.py`) is logged as a truncation warning; prompt carries every trace's raw per-question scores + judge rationale, golden/generated answers, and the evaluated config, each trace keyed on `question_id` (the 1-based dataset row number from `merge.py`, cited back as "Question N") rather than the Langfuse `trace_id`, and returns a severity-ranked diagnostic note, not just a qualitative band summary), `embeddings.py`, `cost.py`, `latency.py` (`attach_latency` — per-stage avg OpenAI call latency onto `evaluation_run.latency`, never raises), `langfuse.py`, `merge.py`, `processing.py`, `cron.py`, `iteration.py` (thin-row CRUD for the iteration loop) +- `crud/evaluations/` — `core.py`, `fast.py` (orchestration + S3/OpenAI IO only; the pieces below carry the rest), `fast_results.py` (pure per-item S3 unit shapes, usage sums, failure threshold), `fast_chunks.py` (`batch_job` bookkeeping + chunk queries/cleanup), `fast_cosine.py` (pure v1 cosine scoring), `fast_traces.py` (pure `TraceData` building), `judge_stage.py` (run-level v2 judge: `resolve_config_prompt`, `judge_rows` pool, per-metric summary rollup), `judge_prompts.py` (rubric text, moved out of `score.py`), `retry.py` (shared OpenAI retry policy), `judge.py` (`METRIC_REGISTRY` + combined judge call; `ground_truth`, `prompt`, and `knowledge_base` metrics, applied per-row by which required inputs the row carries, each spec carrying a `weight` for the overall rollup), `score.py` (`VerdictEnum`/`verdict_from_score`, `OverallSummary`/`compute_overall_summary`), `summary.py` (`generate_run_ai_summary` — one-shot Anthropic `messages.create` call via `ClaudeProvider`, plain-text output — deliberately NOT a `json_schema` `output_config`, since a quotation mark in the prose reads as the JSON string terminator and silently truncates the note; `stop_reason != STOP_REASON_COMPLETE` (the shared `end_turn` constant in `services/llm/providers/claude.py`) is logged as a truncation warning; prompt carries every trace's raw per-question scores + judge rationale, golden/generated answers, and the evaluated config, each trace keyed on `question_id` (the 1-based dataset row number from `merge.py`, cited back as "Question N") rather than the Langfuse `trace_id`, and returns a severity-ranked diagnostic note, not just a qualitative band summary), `embeddings.py` (`EMBEDDING_MODEL` + `calculate_cosine_similarity` only), `cost.py`, `langfuse.py` (v1 dataset-run traces + cosine score sync, legacy dataset item reads, trace-score fetch for `GET /evaluations/{id}`), `merge.py`, `cron.py`, `iteration.py` (thin-row CRUD for the iteration loop) +- `crud/evaluations/` — `core.py`, `fast.py` (orchestration + S3/OpenAI IO only; the pieces below carry the rest), `fast_results.py` (pure per-item S3 unit shapes incl. fast-only `latency_ms`, usage sums, failure threshold), `fast_chunks.py` (`batch_job` bookkeeping + chunk queries/cleanup), `fast_cosine.py` (pure v1 cosine scoring), `fast_traces.py` (pure `TraceData` building), `judge_stage.py` (run-level v2 judge: `resolve_config_prompt`, `judge_rows` pool, per-metric summary rollup), `judge_prompts.py` (rubric text, moved out of `score.py`), `retry.py` (shared OpenAI retry policy), `judge.py` (`METRIC_REGISTRY` + combined judge call; `ground_truth`, `prompt`, and `knowledge_base` metrics, applied per-row by which required inputs the row carries, each spec carrying a `weight` for the overall rollup), `score.py` (`VerdictEnum`/`verdict_from_score`, `OverallSummary`/`compute_overall_summary`), `summary.py` (`generate_run_ai_summary` — one-shot Anthropic `messages.create` call via `ClaudeProvider`, plain-text output — deliberately NOT a `json_schema` `output_config`, since a quotation mark in the prose reads as the JSON string terminator and silently truncates the note; `stop_reason != STOP_REASON_COMPLETE` (the shared `end_turn` constant in `services/llm/providers/claude.py`) is logged as a truncation warning; prompt carries every trace's raw per-question scores + judge rationale, golden/generated answers, and the evaluated config, each trace keyed on `question_id` (the 1-based dataset row number from `merge.py`, cited back as "Question N") rather than the Langfuse `trace_id`, and returns a severity-ranked diagnostic note, not just a qualitative band summary), `embeddings.py` (`EMBEDDING_MODEL` + `calculate_cosine_similarity` only), `cost.py`, `latency.py` (`attach_latency` — per-stage avg OpenAI call latency onto `evaluation_run.latency`, never raises), `langfuse.py` (v1 dataset-run traces + cosine score sync, legacy dataset item reads, trace-score fetch for `GET /evaluations/{id}`), `merge.py`, `cron.py`, `iteration.py` (thin-row CRUD for the iteration loop) - `core/batch/` — shared provider batch clients: `openai.py`, `gemini.py`, `anthropic.py`, `polling.py`, `operations.py` ## Async -- Provider batches polled by cron (`crud/evaluations/cron.py`); no long-lived Celery task per run. +- STT/TTS provider batches polled by cron (`crud/evaluations/cron.py`); no long-lived Celery task per run. Text runs are never batch-polled (text-batch pipeline removed). - Gemini TTS batch requests (`core/batch/gemini.py::create_tts_batch_requests`): 3.8+ models get the style in `speechMetadata.style` (they speak `text` verbatim) and `responseFormat.audio.mimeType=AUDIO_L16`; deprecated preview models keep `legacy_prompting` (style prefixed to the text, default raw PCM, since they reject L16). Result processing still unwraps a WAV payload via `core/audio_utils.py::strip_wav_header`. - STT (`run_stt_batch_submission`, `run_stt_metric_computation`) and TTS (`run_tts_batch_submission`, `run_tts_sync_generation`, `run_tts_result_processing`) Celery tasks run on the `evaluations` queue at priority 2, below fast eval. - TTS submission (`run_tts_batch_submission` → `services/tts_evaluations/batch_job.py::execute_batch_submission`, kwargs `models: list[str]` + `voices: dict[str, str]`; a missing `voices` entry, e.g. a task queued before 092, gets the model default) creates one `tts_result` per text×model carrying its voice and sets the run `processing` before any model work; Gemini rows go to `start_tts_evaluation_batch` (Gemini Batch; one batch per model, using that model's row voice for `voice_name` in the requests and the BatchJob config), and each Sarvam/ElevenLabs model gets one `run_tts_sync_generation` task (`celery/utils.py::start_tts_sync_generation`, priority 2, global Celery time limits like every other task) → `services/tts_evaluations/sync_generation.py::execute_tts_sync_generation`, which claims that model's PENDING rows (`crud/tts_evaluations/result.py::claim_pending_tts_results`, one atomic `UPDATE … SET status='PROCESSING', updated_at=now() WHERE status='PENDING' RETURNING id`; 0 claimed → return without work, so a duplicate/redelivered task is a no-op and a redelivery after a worker death leaves its rows to the cron's dead-worker sweep) and synthesizes them `settings.TTS_SYNC_MAX_WORKERS` (2) at a time in a thread pool, with clients from `SarvamAIProvider.create_client` / `ElevenlabsAIProvider.create_client`, and writes each outcome in its own short session (`update_tts_result` only writes rows still PROCESSING); on timeout/crash it marks the model's PENDING and PROCESSING rows FAILED (`fail_pending_tts_results(statuses=UNFINISHED_TTS_STATUSES)`). Row lifecycle: PENDING (created/queued) → PROCESSING (claimed by a worker; `updated_at` = claim time) → SUCCESS/FAILED. `status` is varchar, so PROCESSING needed no migration. A Gemini submission failure or a sync task that can't be queued marks only that model's rows FAILED; the other models carry on. - TTS cron (`crud/tts_evaluations/cron.py::poll_all_pending_tts_evaluations`) has its own loop (not `cron_utils.poll_all_pending_evaluations_by_type`): it picks up every `processing` TTS run, including sync-only runs with NULL `batch_job_id`, and per run (`poll_tts_run`) builds the Gemini client only when the run has `batch_job` rows (a client failure fails only that run's Gemini rows), polls batches and dispatches `run_tts_result_processing` on SUCCEEDED (re-dispatching an already-SUCCEEDED batch only while the model still has PENDING rows, so claimed rows stop re-dispatch), fails a model's PENDING rows when its batch ends FAILED/CANCELLED/EXPIRED, and sweeps: (1) every tick, PROCESSING rows whose `updated_at` (claim time) is older than `CELERY_TASK_TIME_LIMIT` + `settings.TTS_SYNC_STALE_GRACE_SECONDS` — the worker died — fail with `"Synthesis did not complete"` (sync models) or `"Result processing did not complete"` (Gemini models); (2) once the run is older than `CELERY_TASK_TIME_LIMIT` + `TTS_SYNC_STALE_GRACE_SECONDS`, PENDING rows of Gemini models with no batch job (`"No batch jobs found"`); (3) once the run is older than `settings.TTS_QUEUED_STALE_SECONDS` (24 h), PENDING rows of sync models — a task lost before it started (`"Synthesis never started"`); a PENDING sync row younger than that is just queued behind other `evaluations` tasks and is left alone. It then calls `finalize_tts_run_status`. A poll exception leaves the run `processing` for the next tick. Gemini result processing does not finalize; it claims its model's rows before downloading (0 claimed → returns `processed: 0` without downloading), and on failure fails its model's PENDING and PROCESSING rows. The three TTS tuning knobs (`TTS_SYNC_MAX_WORKERS`, `TTS_SYNC_STALE_GRACE_SECONDS`, `TTS_QUEUED_STALE_SECONDS`) are env-overridable `Settings` in `core/config.py`. - TTS DB-connection discipline: submission, sync generation and Gemini result processing (`batch_result_processing.py`) never hold a session across network I/O — short sessions for the claim, session-free CSV read/download/convert/upload (Gemini rows are modified detached and written back in one short session via `crud/tts_evaluations/result.py::save_processed_tts_results`, which only updates rows still PROCESSING so a row the cron's dead-worker sweep already failed isn't revived; on a soft-limit timeout the already-finished rows are saved before the rest are failed), fresh session for failure marking. `core/batch/operations.py::start_batch_job` commits (ending the read transaction opened by `create_batch_job`'s refresh) before `provider.create_batch` for every caller. The cron's `poll_batch_status` loop still runs inside the cron session's open transaction. - Fast text runs (v1 cosine + v2 judge) fan out `ceil(total_items / EVAL_FAST_CHUNK_SIZE)` `run_evaluation_fast_chunk` tasks (responses only), then a cron barrier (`dispatch_fast_evaluation_barriers`) enqueues one `run_evaluation_fast_aggregate` once every chunk has a `raw_output_url`. The aggregate merges chunks, then (v2) judges **every** row in that single task — so the judge pool is sized by its own `EVAL_JUDGE_CONCURRENCY` (not the response stage's `EVAL_FAST_API_CONCURRENCY`) to clear the max dataset (`EVAL_FAST_MAX_UNIQUE_ROWS` × `duplication_factor`) under the aggregate's `CELERY_TASK_SOFT_TIME_LIMIT`. No judge fan-out / second barrier. The aggregate persists the score unit (`save_score` → traces to S3 behind `score_trace_url`, summary + overall to the DB) **before** flipping the run to `completed`: on v2 that unit is the only copy of the per-row judge scores, so a crash between the two must leave the run `processing`, never `completed` with its scores gone. Chunk-artifact cleanup and the v1 Langfuse score sync run after completion as a best-effort tail that may never fail the run. -- Prompt improvement is job-based with callback delivery: `POST /evaluations/{id}/improve-prompt` validates preconditions, enqueues a `Job` (`JobType.PROMPT_IMPROVEMENT`, `models/job.py`) run by Celery task `run_prompt_improvement` (`celery/tasks/job_execution.py`), and returns `202` with an `LLMJobImmediatePublic` handle. On finish the worker POSTs a single best-effort callback to the caller-supplied `callback_url` (SSRF-guarded via `validate_callback_url`): an `APIResponse[PromptImprovementJobPublic]` (`models/evaluation.py`) carrying the new `ConfigVersion` on success or `error_message` on failure (for an Anthropic fault `error_message` carries the provider's own response body, appended by `_anthropic_error_detail` in `services/evaluations/prompt_improvement.py`). The `ConfigVersion` is persisted regardless of callback outcome. `_call_prompt_drafting_llm` keeps `json_schema` structured output (two fields, `rationale` length-capped) but raises `prompt_generation_failed` when `stop_reason != STOP_REASON_COMPLETE`, so a `max_tokens`-truncated draft fails the job instead of minting a half-written system prompt. Before the call, `_format_traces_for_brief` projects the score traces to what the brief actually reads (`TraceQuestion` / `TraceAttempt` / `TraceScoreSummary` TypedDicts in `models/evaluation.py`, alongside `TraceData` / `TraceScore`) — one entry per question (`question_id`, `question`, `ground_truth_answer`) with repeated runs nested as `attempts[{llm_answer, scores[{name, value, comment, unscoreable}]}]`, dropping `trace_id`/`data_type`/`verdict`/`category`/guardrail bookkeeping; a guardrail-rewritten row substitutes `input_to_llm`/`output_from_llm` for `question`/`llm_answer` — and the JSON is dumped with `ensure_ascii=False` (escaping Devanagari inflates its token count several-fold; a 500-row Hindi run previously exceeded Claude's 1M-token context). Celery redelivery of a `SUCCESS` job re-sends the callback without re-running the LLM. -- v2 prompt iteration reuses the same job/Celery/config-version machinery (`services/evaluations/prompt_improvement.py`) and branches on `run.is_judge_run`: the v2 route calls `start_prompt_improvement_job(..., require_judge_run=True)` (a non-judge run → `422 not_a_judge_run`), and the worker drafts from the three-metric judge trace (`_draft_improved_prompt(is_judge_run=True)`, using each metric's score + reasoning) and delivers a `PromptRecommendationJobPublic` callback carrying `recommendation_type` (`Literal["prompt"]`, `models/evaluation.py`; widens to a union when knowledge-base / model recommendations land). Non-judge (v1) runs keep the default `_draft_improved_prompt` brief + `PromptImprovementJobPublic` path unchanged. +- Prompt improvement is job-based with callback delivery: `POST /api/v2/evaluations/{id}/improve-prompt` validates preconditions, enqueues a `Job` (`JobType.PROMPT_IMPROVEMENT`, `models/job.py`) run by Celery task `run_prompt_improvement` (`celery/tasks/job_execution.py`), and returns `202` with an `LLMJobImmediatePublic` handle. On finish the worker POSTs a single best-effort callback to the caller-supplied `callback_url` (SSRF-guarded via `validate_callback_url`): an `APIResponse[PromptImprovementJobPublic]` (`models/evaluation.py`) carrying the new `ConfigVersion` on success or `error_message` on failure (for an Anthropic fault `error_message` carries the provider's own response body, appended by `_anthropic_error_detail` in `services/evaluations/prompt_improvement.py`). The `ConfigVersion` is persisted regardless of callback outcome. `_call_prompt_drafting_llm` keeps `json_schema` structured output (two fields, `rationale` length-capped) but raises `prompt_generation_failed` when `stop_reason != STOP_REASON_COMPLETE`, so a `max_tokens`-truncated draft fails the job instead of minting a half-written system prompt. Before the call, `_format_traces_for_brief` projects the score traces to what the brief actually reads (`TraceQuestion` / `TraceAttempt` / `TraceScoreSummary` TypedDicts in `models/evaluation.py`, alongside `TraceData` / `TraceScore`) — one entry per question (`question_id`, `question`, `ground_truth_answer`) with repeated runs nested as `attempts[{llm_answer, scores[{name, value, comment, unscoreable}]}]`, dropping `trace_id`/`data_type`/`verdict`/`category`/guardrail bookkeeping; a guardrail-rewritten row substitutes `input_to_llm`/`output_from_llm` for `question`/`llm_answer` — and the JSON is dumped with `ensure_ascii=False` (escaping Devanagari inflates its token count several-fold; a 500-row Hindi run previously exceeded Claude's 1M-token context). Celery redelivery of a `SUCCESS` job re-sends the callback without re-running the LLM. +- v2 prompt iteration reuses the same job/Celery/config-version machinery (`services/evaluations/prompt_improvement.py`) and branches on `run.is_judge_run`: the v2 route calls `start_prompt_improvement_job(..., require_judge_run=True)` (a non-judge run → `422 not_a_judge_run`), and the worker drafts from the three-metric judge trace (`_draft_improved_prompt(is_judge_run=True)`, using each metric's score + reasoning) and delivers a `PromptRecommendationJobPublic` callback carrying `recommendation_type` (`Literal["prompt"]`, `models/evaluation.py`; widens to a union when knowledge-base / model recommendations land). The non-judge (v1) `_draft_improved_prompt` brief + `PromptImprovementJobPublic` path is no longer reachable from any route (every caller passes `require_judge_run=True`); it is kept only so jobs queued before the v1 route's removal still complete. - Evaluation iteration loop (`POST /evaluations/iterations`) chains fast-eval + v2 prompt improvement into a self-driving cycle via LangGraph (`services/evaluations/iteration_graph.py`): `start_eval_node` → `wait_eval_node` → (conditional) `start_improve_node` → `wait_improve_node` → loops back to `start_eval_node`, or → `finalize_node`. Stop-score = mean(`Adherence to Ground Truth`, `Adherence to Prompt`) from `EvaluationRun.score["summary_scores"]` (`compute_round_scores`); `Adherence to Knowledge Base` is recorded per round for visibility only, never gates stopping. Stops on 3 consecutive rounds with `