From fcf3e0227baa10153c1fedb5d67fc2a7347e5da0 Mon Sep 17 00:00:00 2001 From: skl Date: Thu, 15 Oct 2026 14:27:09 +0200 Subject: [PATCH 01/48] portfolio item 3 --- tests/conftest.py | 75 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/tests/conftest.py b/tests/conftest.py index 8264fc5..715c07f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -26,6 +26,81 @@ ] +def _install_shared_embedding_model() -> None: + """Make repeated sentence-transformers loads share one model instance. + + ``EmbeddingClient`` falls back to ``SentenceTransformer("all-MiniLM-L6-v2")`` + once per instance (app/services/rag/embeddings.py), and sentence-transformers + 6.x keeps no class-level cache, so every RAGService construction re-reads the + model from disk (~3-6 s each; ~14 s cold including the torch import). The + tests never assert on vector values or on how often a model is loaded — only + that an embedding backend exists and works — so sharing one real instance + preserves behaviour while removing the suite's dominant cost. Ollama itself + stays genuinely unreachable: every client still attempts (and fails) its HTTP + probe before falling back. + """ + try: + import sentence_transformers as st + except ImportError: # pragma: no cover - ST is required for the fallback path + return + + cls = st.SentenceTransformer + if getattr(cls, "_apollo_shared_model", False): + return + + original_init = cls.__init__ + shared: dict[str, object] = {} + + def cached_init(self, model_name_or_path=None, *args, **kwargs) -> None: + key = ( + model_name_or_path + if isinstance(model_name_or_path, str) and not args and not kwargs + else None + ) + if key is not None and key in shared: + self.__dict__.update(shared[key].__dict__) + return + original_init(self, model_name_or_path, *args, **kwargs) + if key is not None: + shared[key] = self + + cls._apollo_shared_model = True # type: ignore[attr-defined] + cls.__init__ = cached_init # type: ignore[method-assign] + + +_install_shared_embedding_model() + + +@pytest.fixture(autouse=True) +def fast_external_timeouts(): + """Fail fast against the absent Ollama/ComfyUI during tests. + + On this machine a connect to a closed localhost port is refused only after + ~2-4 s (delayed RST), so every real-client probe in the suite pays that delay + on top of its work. The tests assert on outcomes — unreachable services + surface as errors, 503s or fallbacks — not on how long an attempt took, and + none of them read these settings directly (the one test that needs specific + values sets them itself via ``set_setting``). Originals are restored after + each test. + """ + from app.core import config + + overrides = { + "request_timeout": 0.2, + "vision_timeout": 0.2, + "comfyui_timeout": 0.2, + "comfyui_generation_timeout": 0.5, + "comfyui_poll_interval": 0.05, + } + originals = {name: getattr(config.settings, name) for name in overrides} + + for name, value in overrides.items(): + object.__setattr__(config.settings, name, value) + yield + for name, value in originals.items(): + object.__setattr__(config.settings, name, value) + + @pytest.fixture def tmp_settings(tmp_path): """Point every writable storage root at a temp dir for the duration of a test. From 7e1fdc7b64352562b6b60c248cdc2b8d008fc098 Mon Sep 17 00:00:00 2001 From: skl Date: Thu, 15 Oct 2026 14:32:51 +0200 Subject: [PATCH 02/48] portfolio item 4 --- requirements-dev.txt | 4 ++++ ruff.toml | 15 +++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 requirements-dev.txt create mode 100644 ruff.toml diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..49d3cb8 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,4 @@ +-r requirements.txt +ruff==0.17.0 +mypy==2.4.0 +pytest-cov==7.1.0 diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..b194bae --- /dev/null +++ b/ruff.toml @@ -0,0 +1,15 @@ +line-length = 100 +target-version = "py312" +extend-exclude = [ + "tests/debug_chat_route.py", + "tests/test_chat_error.py", + "tests/test_endpoints.py", + "tests/test_ollama_detailed.py", + "tests/test_ollama_endpoints.py", + "tests/test_routes_debug.py", + "tests/test_routes_detailed.py", +] + +[lint] +select = ["E", "F", "W", "I", "B", "UP"] +ignore = ["E501", "B008", "UP042"] From e42b36e235ce1c0d9b58c4a7a9bc0fb83c510b5e Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 14:56:27 +0200 Subject: [PATCH 03/48] portfolio item 5: safe automatic lint fixes ruff --fix with the safe rules only (F401, W293, I001, UP017, UP035, UP015): no logic changes. pytest: 261 passed in 79.58s. Co-Authored-By: Claude Opus 5.5 --- app/api/lora_routes.py | 1 - app/clients/ollama_client.py | 2 +- app/core/jobs.py | 7 ++++--- app/main.py | 12 ++++++------ app/models/schemas.py | 1 - app/services/llm_service.py | 16 ++++++++-------- app/services/lora_dataset_service.py | 6 +++--- app/services/lora_training_service.py | 4 ++-- app/services/memory_service.py | 4 ++-- app/services/prompt_service.py | 4 ++-- app/services/rag/service.py | 2 +- app/services/training_preflight.py | 2 +- tests/test_api_app.py | 2 +- tests/test_comfyui.py | 1 - tests/test_integration_pass.py | 8 +++----- tests/test_launcher.py | 1 - tests/test_lora.py | 2 +- tests/test_main_entrypoint.py | 1 - tests/test_production_hardening.py | 4 +--- tests/test_runner.py | 4 ++-- tests/test_stress.py | 4 +--- 21 files changed, 39 insertions(+), 49 deletions(-) diff --git a/app/api/lora_routes.py b/app/api/lora_routes.py index d5745b4..0a39b48 100644 --- a/app/api/lora_routes.py +++ b/app/api/lora_routes.py @@ -122,7 +122,6 @@ def hardware_info( ) -> dict: """What this machine can run: GPU, VRAM, RAM, disk.""" from app.core.config import settings as app_settings - from app.services.hardware import detect_hardware return detect_hardware( diff --git a/app/clients/ollama_client.py b/app/clients/ollama_client.py index 2e2cd5e..19c1e61 100644 --- a/app/clients/ollama_client.py +++ b/app/clients/ollama_client.py @@ -73,7 +73,7 @@ def generate(self, *, model: str, prompt: str) -> dict: # Use chat completion with system role for simple prompt completion messages = [{"role": "user", "content": prompt}] response = self.chat_completion(model=model, messages=messages) - + # Convert OpenAI response format to Ollama generate format for compatibility if "choices" in response and response["choices"]: return { diff --git a/app/core/jobs.py b/app/core/jobs.py index cb194e9..aa73bf2 100644 --- a/app/core/jobs.py +++ b/app/core/jobs.py @@ -10,11 +10,12 @@ import logging import threading import uuid +from collections.abc import Callable from concurrent.futures import ThreadPoolExecutor from dataclasses import asdict, dataclass, field -from datetime import datetime, timezone +from datetime import UTC, datetime from enum import Enum -from typing import Any, Callable +from typing import Any from app.core.paths import read_json, write_json_atomic @@ -33,7 +34,7 @@ class JobStatus(str, Enum): def _now() -> str: - return datetime.now(timezone.utc).isoformat() + return datetime.now(UTC).isoformat() @dataclass diff --git a/app/main.py b/app/main.py index e7c0bfc..69b8918 100644 --- a/app/main.py +++ b/app/main.py @@ -159,7 +159,7 @@ async def log_routes(): print("=" * 70) print("\nREGISTERED ENDPOINTS:") print("-" * 70) - + # Collect all routes (including nested included routers) routes = {} for route in _iter_api_routes(app.routes): @@ -169,13 +169,13 @@ async def log_routes(): if path not in routes: routes[path] = [] routes[path].append(methods) - + # Print routes organized by path for path in sorted(routes.keys()): methods_list = routes[path] for methods in methods_list: print(f" {methods:10} {path}") - + print("-" * 70) print("\nCRITICAL ROUTES:") print(" POST /chat <- Frontend calls this") @@ -184,18 +184,18 @@ async def log_routes(): print(" GET /documents <- Load documents") print(" GET /health <- Health check") print("-" * 70) - + # Verify /chat endpoint exists chat_route_found = any( r.path == "/chat" and "POST" in r.methods for r in _iter_api_routes(app.routes) ) - + if chat_route_found: print("\n[OK] /chat endpoint is REGISTERED") else: print("\n[WARN] /chat endpoint NOT FOUND!") - + print("\nFrontend API base:") print(" Same origin as this server (localhost, LAN, or Cloudflare tunnel)") print(" POST /chat with JSON: {\"prompt\": \"...\", \"session_id\": \"...\", \"model\": \"...\"}") diff --git a/app/models/schemas.py b/app/models/schemas.py index 13f0b0a..9492f89 100644 --- a/app/models/schemas.py +++ b/app/models/schemas.py @@ -4,7 +4,6 @@ from pydantic import BaseModel, Field - # ============================================ # CHAT SCHEMAS # ============================================ diff --git a/app/services/llm_service.py b/app/services/llm_service.py index d473640..4fd9cb9 100644 --- a/app/services/llm_service.py +++ b/app/services/llm_service.py @@ -25,35 +25,35 @@ def health_check(self) -> dict: def chat(self, prompt: str, model: str | None = None) -> str: """Send a prompt to Ollama and get a response. - + Uses the OpenAI-compatible /v1/chat/completions endpoint to get a text completion for the provided prompt. """ selected_model = model or settings.default_model - + # Format prompt as a chat message for the /v1/chat/completions endpoint messages = [{"role": "user", "content": prompt}] - + response = self.client.chat_completion(model=selected_model, messages=messages) - + # Extract content from OpenAI-compatible response format if isinstance(response.get("choices"), list) and response["choices"]: content = response["choices"][0].get("message", {}).get("content") if isinstance(content, str): return content - + raise OllamaServiceError("Ollama returned an invalid chat response", status_code=502) def list_models(self) -> list[str]: """List available models from Ollama.""" payload = self.client.list_models() - + # Handle OpenAI-compatible response format: {"data": [{"id": "model:tag"}, ...]} if "data" in payload and isinstance(payload["data"], list): return [model.get("id", "") for model in payload["data"] if isinstance(model, dict) and model.get("id")] - + # Fallback for legacy /api/tags format: {"models": [{"name": "model:tag"}, ...]} if "models" in payload and isinstance(payload["models"], list): return [model.get("name", "") for model in payload["models"] if isinstance(model, dict) and model.get("name")] - + raise OllamaServiceError("Ollama returned an invalid model list", status_code=502) diff --git a/app/services/lora_dataset_service.py b/app/services/lora_dataset_service.py index 7732f50..daad006 100644 --- a/app/services/lora_dataset_service.py +++ b/app/services/lora_dataset_service.py @@ -16,7 +16,7 @@ import re import uuid from dataclasses import asdict, dataclass, field -from datetime import datetime, timezone +from datetime import UTC, datetime from pathlib import Path from typing import Any @@ -43,7 +43,7 @@ def _now() -> str: - return datetime.now(timezone.utc).isoformat() + return datetime.now(UTC).isoformat() @dataclass @@ -499,7 +499,7 @@ def _library_entry( "training_status": project.training_status if project else "external", "size_bytes": path.stat().st_size, "created_at": datetime.fromtimestamp( - path.stat().st_mtime, tz=timezone.utc + path.stat().st_mtime, tz=UTC ).isoformat(), } diff --git a/app/services/lora_training_service.py b/app/services/lora_training_service.py index 4947121..c31eab3 100644 --- a/app/services/lora_training_service.py +++ b/app/services/lora_training_service.py @@ -24,7 +24,7 @@ from app.core.config import settings from app.core.exceptions import AIToolkitError, LoRAProjectError -from app.core.jobs import Job, JobStatus, JobStore +from app.core.jobs import Job, JobStore from app.core.paths import is_safetensors, safe_join from app.services.lora_dataset_service import LoRAProjectService from app.services.run_history import RunHistory @@ -605,7 +605,7 @@ def start_training(self, project_id: str, options: dict[str, Any]) -> Job: # Record the run with full provenance before anything can fail. try: - from app.services.hardware import HardwareInfo, detect_hardware + from app.services.hardware import detect_hardware from app.services.training_preflight import advise images = self.projects.list_images(project_id) diff --git a/app/services/memory_service.py b/app/services/memory_service.py index 6aac91c..bcb6975 100644 --- a/app/services/memory_service.py +++ b/app/services/memory_service.py @@ -1,6 +1,6 @@ """Memory service for managing chat history per session.""" -from datetime import datetime, timezone +from datetime import UTC, datetime from typing import TypedDict from app.core.persistence import JsonPersist @@ -19,7 +19,7 @@ class Message(TypedDict): def _utc_now() -> str: - return datetime.now(timezone.utc).isoformat() + return datetime.now(UTC).isoformat() class MemoryService: diff --git a/app/services/prompt_service.py b/app/services/prompt_service.py index a49fb5b..a7eab78 100644 --- a/app/services/prompt_service.py +++ b/app/services/prompt_service.py @@ -1,6 +1,6 @@ """Prompt service for managing prompt templates.""" -from datetime import datetime, timezone +from datetime import UTC, datetime from typing import TypedDict @@ -15,7 +15,7 @@ class Prompt(TypedDict): def _utc_now() -> str: - return datetime.now(timezone.utc).isoformat() + return datetime.now(UTC).isoformat() class PromptService: diff --git a/app/services/rag/service.py b/app/services/rag/service.py index 2298c9e..7153300 100644 --- a/app/services/rag/service.py +++ b/app/services/rag/service.py @@ -262,8 +262,8 @@ def _load_store(self) -> None: self._rebuild_version_map() def _quarantine_files(self) -> None: - from pathlib import Path import shutil + from pathlib import Path root = Path(self.persist_dir) quarantine = root / "quarantined" diff --git a/app/services/training_preflight.py b/app/services/training_preflight.py index 41a8417..e0853d9 100644 --- a/app/services/training_preflight.py +++ b/app/services/training_preflight.py @@ -20,7 +20,7 @@ from dataclasses import dataclass, field from typing import Any -from app.services.hardware import HardwareInfo, detect_hardware, detect_disk_free_gb +from app.services.hardware import HardwareInfo, detect_disk_free_gb, detect_hardware logger = logging.getLogger(__name__) diff --git a/tests/test_api_app.py b/tests/test_api_app.py index f625424..8f25c57 100644 --- a/tests/test_api_app.py +++ b/tests/test_api_app.py @@ -1,7 +1,7 @@ from fastapi.testclient import TestClient -from app.main import create_app from app.core.exceptions import OllamaServiceError +from app.main import create_app class StubService: diff --git a/tests/test_comfyui.py b/tests/test_comfyui.py index 5f6b9e5..5a052de 100644 --- a/tests/test_comfyui.py +++ b/tests/test_comfyui.py @@ -350,7 +350,6 @@ def test_successful_run_saves_outputs(self, tmp_settings): service.save_workflow("flow", sample_graph()) graph, _ = service.build_graph("flow", {"prompt": "x"}) - from app.core.jobs import Job job = service.jobs.create("comfyui_generation") service._run_generation(job, graph) diff --git a/tests/test_integration_pass.py b/tests/test_integration_pass.py index 4bd0846..13e0601 100644 --- a/tests/test_integration_pass.py +++ b/tests/test_integration_pass.py @@ -7,9 +7,8 @@ import pytest -from app.services.run_history import RunHistory from app.services.dashboard import build_dashboard - +from app.services.run_history import RunHistory # ============================================ # TRAINING RUN HISTORY @@ -350,7 +349,6 @@ def test_dashboard_survives_a_broken_subsystem(self, tmp_settings): """One failing subsystem must not blank the whole dashboard.""" from app.core.jobs import JobStore from app.services.comfyui_service import ComfyUIService - from app.services.document_service import DocumentService from app.services.lora_dataset_service import LoRAProjectService from app.services.lora_training_service import LoRATrainingService from app.services.rag.service import RAGService @@ -378,8 +376,8 @@ def get_all_documents(self): class TestRagDebug: def test_debug_query_shows_full_pipeline(self, tmp_path): - from tests.test_production_hardening import FakeEmbeddingClient from app.services.rag.service import RAGService + from tests.test_production_hardening import FakeEmbeddingClient service = RAGService(FakeEmbeddingClient(), persist_dir=str(tmp_path / "rag")) service.add_document("Debug target content. " * 10, @@ -392,8 +390,8 @@ def test_debug_query_shows_full_pipeline(self, tmp_path): assert "debug target" in view["context"].lower() or view["context"] def test_debug_query_on_empty_index_is_honest(self, tmp_path): - from tests.test_production_hardening import FakeEmbeddingClient from app.services.rag.service import RAGService + from tests.test_production_hardening import FakeEmbeddingClient service = RAGService(FakeEmbeddingClient(), persist_dir=str(tmp_path / "rag")) view = service.query_debug("anything") diff --git a/tests/test_launcher.py b/tests/test_launcher.py index 5b77ef4..27a1ef8 100644 --- a/tests/test_launcher.py +++ b/tests/test_launcher.py @@ -8,7 +8,6 @@ import importlib.util import socket -import sys import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer diff --git a/tests/test_lora.py b/tests/test_lora.py index be9b180..75005c9 100644 --- a/tests/test_lora.py +++ b/tests/test_lora.py @@ -16,7 +16,7 @@ import yaml from app.core.exceptions import AIToolkitError, LoRAProjectError, OllamaServiceError -from app.services.lora_dataset_service import LoRAProjectService, _clean_caption +from app.services.lora_dataset_service import _clean_caption from app.services.lora_training_service import ( AIToolkitProcess, LoRATrainingService, diff --git a/tests/test_main_entrypoint.py b/tests/test_main_entrypoint.py index e7a8964..cd87e7e 100644 --- a/tests/test_main_entrypoint.py +++ b/tests/test_main_entrypoint.py @@ -1,4 +1,3 @@ -import importlib def test_main_defaults_to_interactive_agent(monkeypatch) -> None: diff --git a/tests/test_production_hardening.py b/tests/test_production_hardening.py index 5869580..87d0b4c 100644 --- a/tests/test_production_hardening.py +++ b/tests/test_production_hardening.py @@ -14,11 +14,10 @@ from PIL import Image from app.services.dataset_validation import classify_pair, validate_dataset -from app.services.hardware import HardwareInfo, GPUInfo +from app.services.hardware import GPUInfo, HardwareInfo from app.services.rag.service import RAGService, content_hash from app.services.training_preflight import advise, diagnose_failure, estimate_vram_mb - # ============================================ # Deterministic embedding provider # ============================================ @@ -180,7 +179,6 @@ class DifferentModel(FakeEmbeddingClient): assert second.query("fresh under new") def test_corrupted_index_recovers_with_quarantine(self, tmp_path): - import json from pathlib import Path persist_dir = Path(tmp_path / "rag") diff --git a/tests/test_runner.py b/tests/test_runner.py index 561ff7e..ecf6b0d 100644 --- a/tests/test_runner.py +++ b/tests/test_runner.py @@ -1,9 +1,9 @@ -from ai_agent.tools import summarize, find_keywords, answer_questions +from ai_agent.tools import answer_questions, find_keywords, summarize def main(): try: - with open('data/company_document.txt', 'r', encoding='utf-8') as f: + with open('data/company_document.txt', encoding='utf-8') as f: doc = f.read() except FileNotFoundError: print('data/company_document.txt not found in project/data/') diff --git a/tests/test_stress.py b/tests/test_stress.py index 2f7910f..259da36 100644 --- a/tests/test_stress.py +++ b/tests/test_stress.py @@ -9,10 +9,8 @@ from __future__ import annotations import io -import json import random import time -from pathlib import Path import numpy as np import pytest @@ -90,8 +88,8 @@ def test_upload_and_list_60_images_via_service(self, project_service, project): class TestLargeDocument: def test_large_document_chunk_index_persist_retrieve(self, tmp_path): - from tests.test_production_hardening import FakeEmbeddingClient from app.services.rag.service import RAGService + from tests.test_production_hardening import FakeEmbeddingClient # ~200 KB of text -> roughly 250+ chunks at default settings. paragraph = ( From 396fc6a5eaa9e81dad42a9e2412495eed425c897 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 15:12:25 +0200 Subject: [PATCH 04/48] portfolio item 6: fix F findings by hand (F821 undefined config in start_training silently broke run history) --- app/services/dataset_validation.py | 85 --------------------------- app/services/lora_training_service.py | 3 + tests/test_lora.py | 23 ++++++++ tests/test_stress.py | 2 - 4 files changed, 26 insertions(+), 87 deletions(-) diff --git a/app/services/dataset_validation.py b/app/services/dataset_validation.py index 0419615..fa5be30 100644 --- a/app/services/dataset_validation.py +++ b/app/services/dataset_validation.py @@ -246,91 +246,6 @@ def classify_pair( return "near_duplicate_high" -def _mean_color(image: Any) -> tuple[float, float, float]: - """Average RGB color, used to corroborate matches on flat images.""" - small = image.convert("RGB").resize((1, 1)) - return small.getpixel((0, 0)) - - -def _color_distance(a: tuple[float, float, float], b: tuple[float, float, float]) -> float: - return max(abs(x - y) for x, y in zip(a, b)) - - -def _is_low_entropy(hash_hex: str) -> bool: - """True when an aHash is nearly all-0 or all-1 (flat/gradient images). - - Such hashes carry no structure, so hash similarity alone is meaningless - for them — two unrelated solid-color photos would "match". - """ - bits = int(hash_hex, 16) - ones = bin(bits).count("1") - return ones <= LOW_ENTROPY_BITS or ones >= 64 - LOW_ENTROPY_BITS - - -def _same_aspect_ratio(w_a: int, h_a: int, w_b: int, h_b: int) -> bool: - ratio_a = w_a / max(h_a, 1) - ratio_b = w_b / max(h_b, 1) - if ratio_a == 0 or ratio_b == 0: - return False - return abs(ratio_a - ratio_b) / max(ratio_a, ratio_b) <= ASPECT_RATIO_TOLERANCE - - -def classify_pair( - hash_a: str, - hash_b: str, - *, - dims_a: tuple[int, int] | None = None, - dims_b: tuple[int, int] | None = None, - color_a: tuple[float, float, float] | None = None, - color_b: tuple[float, float, float] | None = None, -) -> str: - """Classify how similar two images are, using every available signal. - - Returns one of: - - * ``"exact_duplicate"`` — identical perceptual hash AND identical - mean color (pixel-identical copies are caught earlier by SHA-256) - * ``"near_duplicate_high"`` — hash distance <= NEAR_HASH_CLOSE with - corroborating signals (same aspect ratio; flat images also need the - same mean color) - * ``"near_duplicate_possible"`` — hash-similar but signals disagree - (e.g. a crop or a reframe); surfaced for human review, never auto-merged - * ``"unique"`` - """ - distance = _hamming(hash_a, hash_b) - - if distance == 0: - # Identical structure. For flat images the hash is trivially equal for - # any same-brightness pair, so require the mean color to agree too. - if _is_low_entropy(hash_a) and color_a is not None and color_b is not None: - if _color_distance(color_a, color_b) > FLAT_COLOR_DISTANCE: - return "unique" - return "near_duplicate_high" - - if distance > NEAR_HASH_CLOSE: - return "unique" - - # Hash says "close". Corroborate with structure signals when available. - corroboration = 0 - required = 0 - - if dims_a and dims_b: - required += 1 - if _same_aspect_ratio(*dims_a, *dims_b): - corroboration += 1 - - if _is_low_entropy(hash_a) or _is_low_entropy(hash_b): - # Flat images: hash distance is noise, color must match. - if color_a is not None and color_b is not None: - required += 1 - if _color_distance(color_a, color_b) <= FLAT_COLOR_DISTANCE: - corroboration += 1 - - if required and corroboration < required: - return "near_duplicate_possible" - return "near_duplicate_high" - - def validate_dataset( images: list[dict[str, Any]], read_bytes, diff --git a/app/services/lora_training_service.py b/app/services/lora_training_service.py index c31eab3..cd94159 100644 --- a/app/services/lora_training_service.py +++ b/app/services/lora_training_service.py @@ -610,6 +610,9 @@ def start_training(self, project_id: str, options: dict[str, Any]) -> Job: images = self.projects.list_images(project_id) project = self.projects.get_project(project_id) + # Read back what was actually written, so the recorded run matches + # the config file on disk (there is no local ``config`` here). + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) process_config = config["config"]["process"][0] hardware_info = detect_hardware(comfyui_base_url=settings.comfyui_base_url) hardware = hardware_info.to_dict() diff --git a/tests/test_lora.py b/tests/test_lora.py index 75005c9..7555e8f 100644 --- a/tests/test_lora.py +++ b/tests/test_lora.py @@ -446,6 +446,29 @@ def test_start_without_configuration_raises(self, tmp_path, tmp_settings): with pytest.raises(AIToolkitError, match="not configured"): trainer.start() + def test_start_training_records_a_run_in_history( + self, project_service, project, tmp_path, set_setting + ): + """Regression for an F821 bug: run-history recording referenced an + undefined ``config`` (NameError) that the broad except swallowed, so + runs were silently never recorded.""" + write_fake_trainer(tmp_path, "print('done')\n") + set_setting("ai_toolkit_path", str(tmp_path)) + set_setting("ai_toolkit_python", sys.executable) + + project_service.add_image(project.id, "a.png", png_bytes()) + project_service.set_caption(project.id, "a", "p3r5on, portrait") + + service = LoRATrainingService(projects=project_service) + job = service.start_training(project.id, {}) + + runs = service.history.list_runs(project.id) + assert len(runs) == 1 + assert runs[0]["job_id"] == job.id + # The recorded config is the one actually written to disk. + assert runs[0]["config"]["train"]["steps"] > 0 + assert runs[0]["base_model"].startswith("stabilityai/") + # ============================================ # LORA LIBRARY DISCOVERY diff --git a/tests/test_stress.py b/tests/test_stress.py index 259da36..c2dc01d 100644 --- a/tests/test_stress.py +++ b/tests/test_stress.py @@ -9,7 +9,6 @@ from __future__ import annotations import io -import random import time import numpy as np @@ -33,7 +32,6 @@ class TestLargeDataset: def test_120_image_dataset_validation_under_30s(self, project_service, project): from app.services.dataset_validation import validate_dataset - rng = random.Random(42) images_meta = [] store: dict[str, bytes] = {} From e8bdd281d6c7cb0fe2086eb0e15d4fa3a7efe291 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 15:24:18 +0200 Subject: [PATCH 05/48] portfolio item 7: fix B and E findings by hand (B904 exception chaining, strict zips, unused loop vars, E402) --- app/api/routes.py | 8 ++++---- app/services/comfyui_service.py | 2 +- app/services/dataset_validation.py | 6 +++--- scripts/smoke_preflight.py | 4 ++-- scripts/verify_system.py | 2 +- tests/test_production_hardening.py | 2 +- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/app/api/routes.py b/app/api/routes.py index c2bb2cc..adfa59b 100644 --- a/app/api/routes.py +++ b/app/api/routes.py @@ -346,14 +346,14 @@ async def upload_document( return DocumentResponse(id=doc_id, source=file.filename) - except UnicodeDecodeError: - raise HTTPException(status_code=400, detail="File must be valid UTF-8 text") + except UnicodeDecodeError as err: + raise HTTPException(status_code=400, detail="File must be valid UTF-8 text") from err except ValueError as exc: - raise HTTPException(status_code=400, detail=str(exc)) + raise HTTPException(status_code=400, detail=str(exc)) from exc except OllamaServiceError as exc: raise exc.to_http_exception() from exc except Exception as e: - raise HTTPException(status_code=500, detail=f"Error uploading document: {str(e)}") + raise HTTPException(status_code=500, detail=f"Error uploading document: {str(e)}") from e finally: if temp_path and os.path.exists(temp_path): os.unlink(temp_path) diff --git a/app/services/comfyui_service.py b/app/services/comfyui_service.py index 2f89a9b..c008bb8 100644 --- a/app/services/comfyui_service.py +++ b/app/services/comfyui_service.py @@ -406,7 +406,7 @@ def _save_outputs(self, job_id: str, outputs: dict) -> list[str]: """ saved: list[str] = [] for node_output in outputs.values(): - for index, image in enumerate(node_output.get("images", [])): + for _index, image in enumerate(node_output.get("images", [])): filename = image.get("filename") if not filename: continue diff --git a/app/services/dataset_validation.py b/app/services/dataset_validation.py index fa5be30..6f982f4 100644 --- a/app/services/dataset_validation.py +++ b/app/services/dataset_validation.py @@ -167,7 +167,7 @@ def _mean_color(image: Any) -> tuple[float, float, float]: def _color_distance(a: tuple[float, float, float], b: tuple[float, float, float]) -> float: - return max(abs(x - y) for x, y in zip(a, b)) + return max(abs(x - y) for x, y in zip(a, b, strict=True)) def _is_low_entropy(hash_hex: str) -> bool: @@ -368,8 +368,8 @@ def validate_dataset( ) # ---- dimension consistency (informational) ---- - if widths and len(set(zip(widths, heights))) > 1: - distinct = len(set(zip(widths, heights))) + if widths and len(set(zip(widths, heights, strict=True))) > 1: + distinct = len(set(zip(widths, heights, strict=True))) report.findings.append( ImageFinding("*", "(dataset)", "dimension_inconsistency", f"{distinct} distinct dimensions; AI Toolkit will " diff --git a/scripts/smoke_preflight.py b/scripts/smoke_preflight.py index e2325b4..ff88ea7 100644 --- a/scripts/smoke_preflight.py +++ b/scripts/smoke_preflight.py @@ -4,10 +4,10 @@ import sys import urllib.request -BASE = "http://127.0.0.1:8765" - from PIL import Image +BASE = "http://127.0.0.1:8765" + def main() -> None: # create project diff --git a/scripts/verify_system.py b/scripts/verify_system.py index 39b92ed..acb8065 100644 --- a/scripts/verify_system.py +++ b/scripts/verify_system.py @@ -10,7 +10,7 @@ if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) -from app.main import app +from app.main import app # noqa: E402 - must come after the sys.path setup above def main() -> None: diff --git a/tests/test_production_hardening.py b/tests/test_production_hardening.py index 87d0b4c..ab000fc 100644 --- a/tests/test_production_hardening.py +++ b/tests/test_production_hardening.py @@ -477,7 +477,7 @@ def test_hardware_presets_structure(self, project_service): service = LoRATrainingService(projects=project_service) result = service.hardware_presets() assert "hardware" in result and "presets" in result - for preset_id, variants in result["presets"].items(): + for _preset_id, variants in result["presets"].items(): assert set(variants) >= {"label", "conservative", "balanced", "quality"} # Conservative is always at least as light as quality. cons = variants["conservative"] From e1909c285bfb75a6f806deab77b8ce827c3a5898 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 15:27:02 +0200 Subject: [PATCH 06/48] portfolio item 8: zero lint findings (auto-fix I001/UP/W292/F401 in ai_agent and scripts) --- ai_agent/__init__.py | 2 +- ai_agent/agent.py | 2 +- ai_agent/cli.py | 3 ++- ai_agent/config.py | 7 +++---- ai_agent/io.py | 2 +- ai_agent/llm_client.py | 6 +++--- scripts/smoke_preflight.py | 1 - scripts/smoke_rag_persistence.py | 1 - 8 files changed, 11 insertions(+), 13 deletions(-) diff --git a/ai_agent/__init__.py b/ai_agent/__init__.py index c4255fa..7151626 100644 --- a/ai_agent/__init__.py +++ b/ai_agent/__init__.py @@ -1,5 +1,5 @@ from .agent import run_agent from .llm import ask_llm, list_models -from .tools import summarize, find_keywords, answer_questions +from .tools import answer_questions, find_keywords, summarize __all__ = ["run_agent", "ask_llm", "list_models", "summarize", "find_keywords", "answer_questions"] diff --git a/ai_agent/agent.py b/ai_agent/agent.py index ba16fde..b704b2a 100644 --- a/ai_agent/agent.py +++ b/ai_agent/agent.py @@ -1,4 +1,4 @@ -from .tools import summarize, find_keywords, answer_questions +from .tools import answer_questions, find_keywords, summarize def run_agent(question: str, document: str) -> str: diff --git a/ai_agent/cli.py b/ai_agent/cli.py index 7ee7a3e..0190486 100644 --- a/ai_agent/cli.py +++ b/ai_agent/cli.py @@ -1,6 +1,7 @@ +import os + from .core import run_agent from .io import import_document, list_supported_files -import os def main(): diff --git a/ai_agent/config.py b/ai_agent/config.py index 348f22a..77a3874 100644 --- a/ai_agent/config.py +++ b/ai_agent/config.py @@ -1,12 +1,11 @@ import os from pathlib import Path -from typing import Dict DEFAULT_OLLAMA_BASE_URL = "http://localhost:11434" -def _load_dotenv(path: Path) -> Dict[str, str]: - values: Dict[str, str] = {} +def _load_dotenv(path: Path) -> dict[str, str]: + values: dict[str, str] = {} try: with path.open("r", encoding="utf-8") as handle: @@ -56,4 +55,4 @@ def get_ollama_base_url() -> str: return DEFAULT_OLLAMA_BASE_URL -OLLAMA_BASE_URL = get_ollama_base_url() \ No newline at end of file +OLLAMA_BASE_URL = get_ollama_base_url() diff --git a/ai_agent/io.py b/ai_agent/io.py index 19a2c2b..2e4e951 100644 --- a/ai_agent/io.py +++ b/ai_agent/io.py @@ -2,7 +2,7 @@ def import_document(file_path): - with open(file_path, 'r', encoding='utf-8') as f: + with open(file_path, encoding='utf-8') as f: return f.read() diff --git a/ai_agent/llm_client.py b/ai_agent/llm_client.py index a7e1ab3..f6f113c 100644 --- a/ai_agent/llm_client.py +++ b/ai_agent/llm_client.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Any, Dict, Optional +from typing import Any try: import requests @@ -16,7 +16,7 @@ def _format_url(base_url: str, endpoint: str) -> str: return f"{base_url.rstrip('/')}{endpoint}" -def _build_payload(prompt: str, model: str) -> Dict[str, Any]: +def _build_payload(prompt: str, model: str) -> dict[str, Any]: return { "model": model, "prompt": prompt, @@ -89,4 +89,4 @@ def list_models(base_url: str | None = None) -> dict: results[url] = resp.text except Exception as exc: results[url] = str(exc) - return results \ No newline at end of file + return results diff --git a/scripts/smoke_preflight.py b/scripts/smoke_preflight.py index ff88ea7..f7e7486 100644 --- a/scripts/smoke_preflight.py +++ b/scripts/smoke_preflight.py @@ -1,7 +1,6 @@ """Live preflight smoke test against a running server (temp project).""" import io import json -import sys import urllib.request from PIL import Image diff --git a/scripts/smoke_rag_persistence.py b/scripts/smoke_rag_persistence.py index 925c96c..5a5fb4c 100644 --- a/scripts/smoke_rag_persistence.py +++ b/scripts/smoke_rag_persistence.py @@ -6,7 +6,6 @@ """ import json import sys -import time import urllib.request BASE = "http://127.0.0.1:8765" From 3e4e2a1238ef9b52537b362277e27ff9aa395a27 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 15:28:12 +0200 Subject: [PATCH 07/48] portfolio item 9: lint in CI (ruff job) --- .github/workflows/ci.yml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6889a0d..f6f43ee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,19 @@ on: pull_request: jobs: + lint: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install ruff + run: pip install "ruff==0.17.0" + - name: Lint (ruff) + run: ruff check . + test: runs-on: ubuntu-latest timeout-minutes: 30 From 315f8d54973112a46d1495fd2505a82963e449c2 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 15:35:39 +0200 Subject: [PATCH 08/48] portfolio item 10: type-check configuration (mypy.ini) --- mypy.ini | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 mypy.ini diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 0000000..cb3cd63 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,25 @@ +# Type-checking configuration (portfolio item 10). +# Run from the repo root: python -m mypy +# Scope mirrors ruff.toml: app, ai_agent, scripts, tests + entry points; +# the same debug test files excluded from lint are excluded here. + +[mypy] +python_version = 3.12 +files = app, ai_agent, scripts, tests, launcher.py, main.py +explicit_package_bases = True +mypy_path = . +warn_unused_configs = True +no_implicit_optional = True +disallow_untyped_defs = False +check_untyped_defs = False +exclude = (debug_chat_route|test_chat_error|test_endpoints|test_ollama_detailed|test_ollama_endpoints|test_routes_debug|test_routes_detailed)\.py + +# Third-party libraries without bundled type stubs +[mypy-psutil] +ignore_missing_imports = True + +[mypy-yaml] +ignore_missing_imports = True + +[mypy-pyperclip] +ignore_missing_imports = True From d08d0a9516e884d363fc97397b45a0caa2861b10 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 15:49:50 +0200 Subject: [PATCH 09/48] portfolio item 11: types in lora_routes.py (pydantic mypy plugin, strict module section, Request param fix) --- app/api/lora_routes.py | 2 +- mypy.ini | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/app/api/lora_routes.py b/app/api/lora_routes.py index 0a39b48..2e76774 100644 --- a/app/api/lora_routes.py +++ b/app/api/lora_routes.py @@ -371,8 +371,8 @@ def generate_captions( @router.post("/projects/{project_id}/caption-jobs", response_model=JobResponse) def start_caption_job( project_id: str, + request: Request, payload: CaptionGenerateRequest | None = None, - request: Request = None, service: LoRAProjectService = Depends(get_project_service), ) -> JobResponse: """Queue dataset captioning as a background job (for large datasets). diff --git a/mypy.ini b/mypy.ini index cb3cd63..aff81af 100644 --- a/mypy.ini +++ b/mypy.ini @@ -5,6 +5,7 @@ [mypy] python_version = 3.12 +plugins = pydantic.mypy files = app, ai_agent, scripts, tests, launcher.py, main.py explicit_package_bases = True mypy_path = . @@ -14,6 +15,12 @@ disallow_untyped_defs = False check_untyped_defs = False exclude = (debug_chat_route|test_chat_error|test_endpoints|test_ollama_detailed|test_ollama_endpoints|test_routes_debug|test_routes_detailed)\.py +# Fully typed modules: every function must carry complete annotations. +# Item 11 starts with lora_routes; later items extend this list module by +# module until the whole codebase can flip disallow_untyped_defs globally. +[mypy-app.api.lora_routes] +disallow_untyped_defs = True + # Third-party libraries without bundled type stubs [mypy-psutil] ignore_missing_imports = True From c6edeae18132dfde152121649e403261f5f8d126 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 16:12:18 +0200 Subject: [PATCH 10/48] portfolio item 12: types in routes.py (strict module section, no code changes needed) --- mypy.ini | 3 +++ 1 file changed, 3 insertions(+) diff --git a/mypy.ini b/mypy.ini index aff81af..2d199a4 100644 --- a/mypy.ini +++ b/mypy.ini @@ -21,6 +21,9 @@ exclude = (debug_chat_route|test_chat_error|test_endpoints|test_ollama_detailed| [mypy-app.api.lora_routes] disallow_untyped_defs = True +[mypy-app.api.routes] +disallow_untyped_defs = True + # Third-party libraries without bundled type stubs [mypy-psutil] ignore_missing_imports = True From f48ba87f93846e04585a2673493551b7fdfbfc86 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 16:20:38 +0200 Subject: [PATCH 11/48] portfolio item 13: types in dataset + ComfyUI services (strict sections, dict-invariance fix, isinstance guards) --- app/services/comfyui_service.py | 8 ++++++-- app/services/lora_dataset_service.py | 3 ++- mypy.ini | 6 ++++++ 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/app/services/comfyui_service.py b/app/services/comfyui_service.py index c008bb8..5b5a372 100644 --- a/app/services/comfyui_service.py +++ b/app/services/comfyui_service.py @@ -257,7 +257,9 @@ def _load_info(self, workflow_id: str) -> WorkflowInfo: graph = read_json(self._graph_path(workflow_id)) if not isinstance(graph, dict): raise WorkflowError(f"Workflow '{workflow_id}' could not be read") - meta = read_json(self._map_path(workflow_id), default={}) or {} + meta = read_json(self._map_path(workflow_id), default={}) + if not isinstance(meta, dict): + meta = {} return WorkflowInfo( id=workflow_id, name=meta.get("name", workflow_id.replace("_", " ").title()), @@ -278,7 +280,9 @@ def load_workflow(self, workflow_id: str) -> tuple[dict, dict]: raise WorkflowError(f"Workflow '{workflow_id}' is not valid JSON") validate_graph(graph) - meta = read_json(self._map_path(workflow_id), default={}) or {} + meta = read_json(self._map_path(workflow_id), default={}) + if not isinstance(meta, dict): + meta = {} return graph, meta.get("inputs", {}) def save_workflow( diff --git a/app/services/lora_dataset_service.py b/app/services/lora_dataset_service.py index daad006..32fc2e6 100644 --- a/app/services/lora_dataset_service.py +++ b/app/services/lora_dataset_service.py @@ -121,13 +121,14 @@ def create_project( slug = re.sub(r"[^a-z0-9_-]", "_", name.strip().lower()).strip("_")[:40] or "lora" project_id = f"{slug}_{uuid.uuid4().hex[:6]}" + overrides: dict[str, Any] = {"base_model": base_model} if base_model else {} project = LoRAProject( id=project_id, name=name.strip(), description=description, arch=arch, trigger_word=trigger_word.strip(), - **({"base_model": base_model} if base_model else {}), + **overrides, ) root = safe_join(self.data_dir, project_id) diff --git a/mypy.ini b/mypy.ini index 2d199a4..90fc3a5 100644 --- a/mypy.ini +++ b/mypy.ini @@ -24,6 +24,12 @@ disallow_untyped_defs = True [mypy-app.api.routes] disallow_untyped_defs = True +[mypy-app.services.lora_dataset_service] +disallow_untyped_defs = True + +[mypy-app.services.comfyui_service] +disallow_untyped_defs = True + # Third-party libraries without bundled type stubs [mypy-psutil] ignore_missing_imports = True From f2c9489f69a7b117cfe6e93b24b00365595e5672 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 16:25:38 +0200 Subject: [PATCH 12/48] portfolio item 14: zero type errors (6 fixes across launcher, diagnostics, llm_client, memory, vector store, entrypoint test) --- ai_agent/llm_client.py | 2 +- app/services/memory_service.py | 4 ++-- app/services/rag/vector_store.py | 4 +++- launcher.py | 3 ++- scripts/diagnostics_ollama.py | 3 ++- tests/test_main_entrypoint.py | 5 ++++- 6 files changed, 14 insertions(+), 7 deletions(-) diff --git a/ai_agent/llm_client.py b/ai_agent/llm_client.py index f6f113c..6529685 100644 --- a/ai_agent/llm_client.py +++ b/ai_agent/llm_client.py @@ -5,7 +5,7 @@ try: import requests except ImportError: # pragma: no cover - exercised in minimal environments - requests = None + requests = None # type: ignore[assignment] from .config import OLLAMA_BASE_URL diff --git a/app/services/memory_service.py b/app/services/memory_service.py index bcb6975..812e03f 100644 --- a/app/services/memory_service.py +++ b/app/services/memory_service.py @@ -1,7 +1,7 @@ """Memory service for managing chat history per session.""" from datetime import UTC, datetime -from typing import TypedDict +from typing import TypedDict, cast from app.core.persistence import JsonPersist @@ -44,7 +44,7 @@ def _load(self) -> None: for session_id, messages in sessions.items(): if isinstance(messages, list): self._storage[str(session_id)] = [ - message for message in messages + cast(Message, message) for message in messages if isinstance(message, dict) and "role" in message ] settings_map = stored.get("settings") diff --git a/app/services/rag/vector_store.py b/app/services/rag/vector_store.py index 040009e..53307ce 100644 --- a/app/services/rag/vector_store.py +++ b/app/services/rag/vector_store.py @@ -106,7 +106,9 @@ def __init__( self.persist_dir = Path(persist_dir) if persist_dir else None self._chunks: list[StoredChunk] = [] self._embeddings: list[np.ndarray] = [] - self._index = faiss.IndexFlatIP(dimension) + # Declared as the base Index type: faiss.read_index() may return any + # index class, and only add/search/ntotal are ever used on it. + self._index: faiss.Index = faiss.IndexFlatIP(dimension) self._dirty = False if self.persist_dir is not None: diff --git a/launcher.py b/launcher.py index 7d6146f..5d6b4a8 100644 --- a/launcher.py +++ b/launcher.py @@ -166,7 +166,8 @@ def _http_probe(url: str, timeout: float = 3.0) -> tuple[int | None, str | None, body = None return exc.code, body, None except (urllib.error.URLError, TimeoutError, OSError) as exc: - return None, None, str(exc.reason or exc) + # Only URLError carries .reason; plain OSError/TimeoutError do not. + return None, None, str(getattr(exc, "reason", None) or exc) def _wait_for_backend(timeout: float = 45.0) -> StartupResult: diff --git a/scripts/diagnostics_ollama.py b/scripts/diagnostics_ollama.py index 2e46cd0..74ec720 100644 --- a/scripts/diagnostics_ollama.py +++ b/scripts/diagnostics_ollama.py @@ -2,6 +2,7 @@ """Probe local Ollama connectivity and available HTTP endpoints.""" import socket +from typing import Any import requests @@ -20,7 +21,7 @@ "/completion", ] -payload = {"model": "ggml-small", "prompt": "Hello diagnostics", "stream": False} +payload: dict[str, Any] = {"model": "ggml-small", "prompt": "Hello diagnostics", "stream": False} def check_socket(hostname: str, port: int = 11434, timeout: float = 3.0): diff --git a/tests/test_main_entrypoint.py b/tests/test_main_entrypoint.py index cd87e7e..fdeda21 100644 --- a/tests/test_main_entrypoint.py +++ b/tests/test_main_entrypoint.py @@ -1,5 +1,8 @@ +from typing import Any + + def test_main_defaults_to_interactive_agent(monkeypatch) -> None: import main as main_module @@ -20,7 +23,7 @@ def fake_main() -> None: def test_main_can_start_api_server(monkeypatch) -> None: import main as main_module - called = {} + called: dict[str, Any] = {} monkeypatch.setattr(main_module, "run_cli", lambda: called.setdefault("interactive", True)) From d9466051e67eee31cfe4051370d02f4ee862d43b Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 16:26:25 +0200 Subject: [PATCH 13/48] portfolio item 15: type check in CI (typecheck job, mypy via requirements-dev.txt) --- .github/workflows/ci.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f6f43ee..0b0d4b7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,6 +19,24 @@ jobs: - name: Lint (ruff) run: ruff check . + typecheck: + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + - name: Install dependencies + # Full install (CPU-only torch first) so mypy resolves the same imports as locally; + # mypy.ini's pydantic plugin also needs pydantic present. + run: | + pip install torch --index-url https://download.pytorch.org/whl/cpu + pip install -r requirements-dev.txt + - name: Type check (mypy) + run: python -m mypy + test: runs-on: ubuntu-latest timeout-minutes: 30 From 4707fe8e7d27edb04579d79c23b74c5022007bf8 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 16:40:36 +0200 Subject: [PATCH 14/48] portfolio item 16: coverage in CI (pytest --cov=app, dev requirements) --- .github/workflows/ci.yml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0b0d4b7..875d2e2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,6 +50,8 @@ jobs: # CPU-only torch first, so sentence-transformers does not pull the multi-GB CUDA build run: | pip install torch --index-url https://download.pytorch.org/whl/cpu - pip install -r requirements.txt - - name: Run tests - run: python -m pytest + pip install -r requirements-dev.txt + - name: Run tests (with coverage) + # Coverage is reported for now; a minimum threshold will be added once the + # eval work has established what the number should protect. + run: python -m pytest --cov=app --cov-report=term-missing From de90a7ea1c5fba4f053de7525aad59e0efbb97db Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 16:40:38 +0200 Subject: [PATCH 15/48] portfolio item 17: RAG eval corpus and question set (12 docs, 48 questions with ground truth) --- evals/corpus/apollo-lora-pipeline.md | 19 + evals/corpus/apollo-rag-knowledge-base.md | 19 + evals/corpus/comfyui-workflows.md | 15 + evals/corpus/diffusion-basics.md | 23 ++ evals/corpus/lora-concepts.md | 17 + evals/corpus/lora-dataset-curation.md | 19 + evals/corpus/prompt-engineering.md | 23 ++ evals/corpus/sampling-and-cfg.md | 22 ++ evals/corpus/sdxl.md | 17 + evals/corpus/training-failure-modes.md | 19 + evals/corpus/upscaling-and-resolution.md | 19 + evals/corpus/vector-search-basics.md | 19 + evals/questions.json | 409 ++++++++++++++++++++++ 13 files changed, 640 insertions(+) create mode 100644 evals/corpus/apollo-lora-pipeline.md create mode 100644 evals/corpus/apollo-rag-knowledge-base.md create mode 100644 evals/corpus/comfyui-workflows.md create mode 100644 evals/corpus/diffusion-basics.md create mode 100644 evals/corpus/lora-concepts.md create mode 100644 evals/corpus/lora-dataset-curation.md create mode 100644 evals/corpus/prompt-engineering.md create mode 100644 evals/corpus/sampling-and-cfg.md create mode 100644 evals/corpus/sdxl.md create mode 100644 evals/corpus/training-failure-modes.md create mode 100644 evals/corpus/upscaling-and-resolution.md create mode 100644 evals/corpus/vector-search-basics.md create mode 100644 evals/questions.json diff --git a/evals/corpus/apollo-lora-pipeline.md b/evals/corpus/apollo-lora-pipeline.md new file mode 100644 index 0000000..680ab93 --- /dev/null +++ b/evals/corpus/apollo-lora-pipeline.md @@ -0,0 +1,19 @@ +# Apollo's LoRA Training Pipeline + +Apollo automates the path from a folder of images to a trained LoRA adapter. The pipeline has four stages: dataset quality control, captioning, training configuration generation, and execution through an external trainer. + +## Dataset quality control + +Before anything is trained on, every image in the project folder passes automated checks. Images are decoded to verify they are not corrupt, near-duplicates are detected by perceptual hash and flagged for removal, and resolution is checked against a minimum threshold so tiny thumbnails do not silently degrade the dataset. The result is a quality report listing how many images passed, which were dropped, and why — the user reviews this before training starts. + +## Captioning + +Each surviving image receives a caption. If Ollama with a vision model is available locally, Apollo uses it to generate descriptive captions automatically; otherwise captions can be supplied manually as sidecar text files named after each image. Captions follow the curation guidance: describe the scene and context, keep the subject's identity out of the text so the adapter learns it from pixels alone. + +## Configuration generation + +Apollo writes a training configuration file in the YAML format expected by the Ostris AI Toolkit, an external local process that performs the actual GPU training. The generated YAML encodes the chosen base model, dataset path, trigger word, rank and alpha, learning rate, epochs, and batch size. Users can edit the generated file before launching; Apollo re-reads it at launch time so manual tweaks are respected. + +## Execution and results + +Training runs as a supervised background job: Apollo starts the toolkit process, polls its progress output, and records status transitions (queued, running, completed, failed) in its local job store. When training finishes, the resulting adapter file is copied into the LoRA library where it becomes selectable in generation workflows with an adjustable strength slider. Failed jobs keep their log files so the cause — usually out-of-memory or a path error — can be inspected without rerunning. diff --git a/evals/corpus/apollo-rag-knowledge-base.md b/evals/corpus/apollo-rag-knowledge-base.md new file mode 100644 index 0000000..640118b --- /dev/null +++ b/evals/corpus/apollo-rag-knowledge-base.md @@ -0,0 +1,19 @@ +# Apollo's Knowledge Base (RAG) + +Apollo includes a local knowledge base so the chat assistant can answer questions about your own documents. The feature is built as a retrieval-augmented generation pipeline: uploaded files are chunked, embedded into vectors, and stored in an index that the chat service queries before composing an answer. + +## Ingestion + +When a document is added, its text is split into overlapping chunks of 800 characters with 150 characters of overlap between neighbors, splitting on sentence boundaries so no sentence is cut in half. Each chunk is embedded by the configured embedding model and appended to the index. Documents are tracked by content hash: re-uploading an unchanged file skips re-embedding entirely, while a changed file has its old chunks removed before the new ones are added, so stale text never lingers in results. + +## The index + +Vectors live in a FAISS flat inner-product index on disk under the application data directory. Embeddings are L2-normalized before storage, which makes the inner product equivalent to cosine similarity — higher score means more similar. The index file is written atomically (temp file plus rename) so a crash mid-save cannot corrupt the previous good state, and a small metadata file records the embedding model name and vector dimension; loading an index built with a different model is refused rather than silently mixing incompatible vectors. + +## Retrieval at query time + +When you ask a question in chat, the question is embedded with the same model and the top four most similar chunks are retrieved by default (configurable via `RAG_TOP_K`). Those chunks are formatted into a context block that is injected into the assistant's prompt, so the answer can cite your documents instead of relying on general knowledge. A developer view shows exactly which chunks were retrieved with their scores, which makes it easy to trace a bad answer back to weak retrieval or to a missing document. + +## Limits + +The knowledge base is local and single-user: there is no multi-tenant isolation because there is only one tenant. Very large corpora are supported but embedding time grows linearly with chunk count, and the flat index searches every vector on each query, which stays fast up to roughly a hundred thousand chunks before approximate methods become worthwhile. diff --git a/evals/corpus/comfyui-workflows.md b/evals/corpus/comfyui-workflows.md new file mode 100644 index 0000000..ed7b7d4 --- /dev/null +++ b/evals/corpus/comfyui-workflows.md @@ -0,0 +1,15 @@ +# ComfyUI Workflows + +ComfyUI is a node-based interface for running diffusion models. Instead of fixed forms, you build a directed graph where each node performs one operation and passes tensors to its neighbors. The same graph can generate text-to-image, image-to-image, inpainting, or upscaling pipelines by rewiring nodes. + +## Core nodes + +Every workflow contains the same skeleton: a **CheckpointLoader** that loads the base model (and exposes its CLIP text encoder, VAE, and UNet as separate outputs), one or two **CLIPTextEncode** nodes for the positive and negative prompts, a **KSampler** that runs the denoising loop, and a **VAEDecode** plus **SaveImage** pair to turn latents into pixels. The KSampler's inputs — model, positive prompt, negative prompt, latent image, seed, steps, CFG, sampler name, and denoise strength — are the same settings described in the sampling documentation. + +## Latent space plumbing + +Nodes exchange latents rather than images wherever possible: an **EmptyLatentImage** node creates a blank canvas of chosen width and height for text-to-image work, while **VAEEncode** converts an uploaded image into latents for image-to-image or inpainting. The denoise strength on the KSampler controls how much of the source survives: 1.0 ignores it entirely (pure generation), values around 0.5 to 0.75 restyle while keeping composition, and low values near 0.3 only refine detail. + +## Managing workflows + +Workflows are saved as JSON files describing nodes and their connections, which makes them easy to version-control and share. Apollo stores its built-in workflow templates in a `workflows` directory and can load any compatible file from there; custom workflows added by the user appear in the picker automatically. Because the graph is data rather than code, swapping one node — for example replacing a plain upscaler with a tiled variant — changes behavior without touching anything else. diff --git a/evals/corpus/diffusion-basics.md b/evals/corpus/diffusion-basics.md new file mode 100644 index 0000000..3779d12 --- /dev/null +++ b/evals/corpus/diffusion-basics.md @@ -0,0 +1,23 @@ +# How Diffusion Models Work + +A diffusion model is a generative model that learns to produce images by reversing a gradual noising process. Instead of predicting an entire image in one step, the model learns to remove a little noise at a time until a coherent picture emerges from random static. + +## The forward process + +Training starts with real images. The model is shown an image and then asked to predict the noise that was added to it. Concretely, a copy of the training image is corrupted by adding Gaussian noise in many small steps: first almost no noise, then slightly more, until the image is indistinguishable from pure random noise. This sequence of increasingly noisy versions is called the diffusion schedule. + +## The reverse process + +The network itself is usually a U-Net that takes a noisy image and a step counter as input and outputs an estimate of the noise present in that image. Subtracting the predicted noise from the noisy image yields a slightly cleaner version. Repeating this denoising loop from pure noise produces the final generated image. Each individual pass through the network is called one sampling step, and typical generations use between 20 and 50 steps. + +## Latent diffusion + +Running the full noising process on raw pixels is expensive, so modern systems such as Stable Diffusion work in a compressed latent space instead. An autoencoder first compresses an image into a small tensor of latent values, roughly eight times smaller in each spatial dimension. The diffusion process then runs entirely on these latents, and only at the very end does the decoder turn the final clean latent back into pixels. This is why the same model can generate images at different resolutions without retraining. + +## Conditioning with text + +To make generation follow a prompt, the noise prediction network is conditioned on an embedding of the text prompt produced by a language encoder such as CLIP. The encoder turns the prompt into a sequence of vector tokens, and cross-attention layers let every part of the image attend to those tokens. This conditioning is what makes the model produce "a red fox in snow" rather than random texture: the text embedding steers which denoising path the latent follows at every step. + +## Why steps matter + +Fewer sampling steps are faster but give the model less opportunity to refine structure, so very short runs can look blurry or contain artifacts. More steps cost more compute and usually improve fine detail up to a point of diminishing returns. The exact trade-off depends on the sampler used, which is covered in the sampling documentation. diff --git a/evals/corpus/lora-concepts.md b/evals/corpus/lora-concepts.md new file mode 100644 index 0000000..d4d36d6 --- /dev/null +++ b/evals/corpus/lora-concepts.md @@ -0,0 +1,17 @@ +# LoRA: Low-Rank Adaptation + +LoRA (Low-Rank Adaptation) is a technique for fine-tuning a large model cheaply. Instead of updating all the weights of a diffusion UNet, which would require copying hundreds of gigabytes and days of GPU time, LoRA learns a small set of additional matrices that are added to the original weights at inference time. + +## How it works + +For a weight matrix W in the network, LoRA freezes W and learns two smaller matrices A and B such that the update is approximated as W + A·B. The product A·B has the same shape as W but far fewer parameters, because A and B are "low rank": their inner dimension, called the rank, is much smaller than the matrix width. During training only A and B are updated; during generation the combined weights are applied on the fly with negligible overhead. + +## Rank and alpha + +The **rank** controls how much information the adapter can carry. Low ranks (4 to 8) capture a single strong concept such as one person's face or one art style, and they resist overfitting. Higher ranks (32 and up) can encode more complex behavior but need more data and are easier to over-train. + +**Alpha** is a scaling factor applied to the learned update; the effective strength of the adapter at inference time is alpha divided by rank. Keeping alpha equal to rank gives a neutral starting point, and most training tools expose both values so users can tune relative strength without retraining. + +## Why LoRA instead of full fine-tuning + +A LoRA for SDXL typically occupies 10 to 200 megabytes on disk versus several gigabytes for a full checkpoint. It trains in minutes to an hour on a single consumer GPU, and multiple LoRAs can be stacked on the same base model at generation time with independent strength sliders — something impossible when each variant is a separate full checkpoint. diff --git a/evals/corpus/lora-dataset-curation.md b/evals/corpus/lora-dataset-curation.md new file mode 100644 index 0000000..abe3e00 --- /dev/null +++ b/evals/corpus/lora-dataset-curation.md @@ -0,0 +1,19 @@ +# Curating a LoRA Training Dataset + +The quality of a LoRA is bounded by the quality of its training images. A well-curated small dataset beats a large messy one almost every time, so curation deserves more attention than hyperparameters. + +## How many images + +For a single subject — a person, a character, or an object — twenty to fifty images is the usual working range. Below about fifteen the model often fails to lock onto consistent identity details; above roughly eighty you are mostly paying in training time without gaining robustness, and you start needing more epochs control to avoid overfitting. + +## Variety that matters + +The dataset should vary what the subject does not: different angles (front, three-quarter, profile), lighting conditions, backgrounds, and distances from close-up to full body. What must stay consistent is the identity itself — face shape, hair color, distinctive features for a person; material and silhouette for an object. Including images where the subject looks like someone else actively teaches the model the wrong thing. + +## Captions + +Each image needs a caption that describes everything except the trigger word reserved for the subject. If the trigger is "skto woman", a good caption reads "a woman in a red coat walking through a market, overcast light" — describing scene and context while leaving identity to the adapter. Over-captioning (naming every trivial detail) makes the model attribute those details to the subject; under-captioning leaves it guessing. + +## Cleaning steps + +Before training: remove duplicates and near-duplicates (identical frames from a video count as one image), reject blurry or watermarked shots, and normalize resolution so nothing is far smaller than the training size — upscaling a 400-pixel thumbnail to 1024 only adds softness. Most curation pipelines report how many images were dropped at each stage so you can see where your dataset lost quality. diff --git a/evals/corpus/prompt-engineering.md b/evals/corpus/prompt-engineering.md new file mode 100644 index 0000000..73a5a27 --- /dev/null +++ b/evals/corpus/prompt-engineering.md @@ -0,0 +1,23 @@ +# Prompt Engineering for Image Models + +The text prompt is the main steering mechanism of a diffusion model, and small changes in wording can change the result dramatically. This document covers the conventions that reliably improve output quality. + +## Structure: subject first + +Models attend most strongly to the beginning of the prompt. Put the main subject in the first few words, then add setting, style, lighting, and finally technical modifiers such as "highly detailed" or "sharp focus". A prompt like "a weathered lighthouse on a cliff, storm clouds, dramatic lighting, highly detailed" will usually place the lighthouse front and center, while burying it at the end of a long sentence weakens its presence. + +## Weighting with parentheses + +Parentheses increase the relative importance of the words inside them: "(red fox):1.3" emphasizes "red fox", while "[red fox]:0.7" or double brackets reduce emphasis. Most interfaces accept explicit numeric weights in the form `(word:1.2)`. Weights between 1.1 and 1.5 are a safe range; pushing above about 2 often distorts anatomy or saturates colors because the model over-commits to that concept at every denoising step. + +## Negative prompts + +The negative prompt lists what should be avoided: "blurry, low quality, extra fingers, watermark". It works by conditioning the model to move away from those concepts during sampling. Keep it short — a wall of negative terms dilutes each one and can start fighting the positive prompt. For anatomy problems specifically, terms like "extra fingers", "deformed hands", and "bad anatomy" are the most effective entries. + +## Style tokens + +Certain phrases have become de facto style switches because they appear frequently in training data: "oil painting", "cyberpunk", "studio lighting", "35mm photograph", "isometric illustration". Combining two or three compatible style tokens works well; combining conflicting ones such as "watercolor" and "photorealistic" produces muddy, unpredictable results. + +## What to avoid + +All-caps text in prompts is treated the same as lowercase by most tokenizers, so it adds no emphasis. Extremely long prompts beyond roughly seventy-five tokens are truncated by the CLIP encoder, so anything past that point simply does not reach the model. diff --git a/evals/corpus/sampling-and-cfg.md b/evals/corpus/sampling-and-cfg.md new file mode 100644 index 0000000..2cf2815 --- /dev/null +++ b/evals/corpus/sampling-and-cfg.md @@ -0,0 +1,22 @@ +# Sampling Methods and CFG Scale + +Two settings control how a diffusion model turns noise into an image: the sampler (which numerical method steps through the denoising process) and the classifier-free guidance scale, usually written as CFG. + +## What CFG does + +Classifier-free guidance interpolates between "what the model thinks is likely" and "what matches the prompt". A CFG of 1 means pure model output with no extra steering; a CFG of 7 pulls each denoising step strongly toward the prompt's concepts. Low values (under about 4) give dreamy, loosely related images; high values (above about 9) make colors oversaturated and can introduce banding or harsh edges because every step is over-corrected toward the text. For most SDXL work a CFG between 5 and 7 is a sensible starting point. + +## Common samplers + +- **Euler**: simple and fast, good quality at moderate step counts; a solid default when speed matters. +- **DPM++ 2M Karras**: the most popular high-quality sampler; it pairs a second-order prediction with a Karras noise schedule that front-loads detail work in early steps. It typically needs 20 to 30 steps. +- **DDIM**: deterministic for a given seed, which makes it useful when reproducibility matters more than peak quality. +- **UniPC**: a newer fast sampler that reaches good quality with fewer steps than DPM++ variants. + +## Steps and seeds + +The step count sets the budget of denoising passes: 20 is usually enough for DPM++ 2M Karras, while Euler may want 30 to 40 for fine detail. The seed fixes the initial random noise; keeping the same seed with identical settings reproduces the same image, which is essential when comparing prompts or sampler changes one variable at a time. + +## Choosing a starting point + +A practical default combination is DPM++ 2M Karras, 25 steps, CFG 6, at the model's native resolution. Change only one setting at a time: if an image looks noisy, raise steps before raising CFG; if it ignores the prompt, raise CFG before rewriting the prompt. diff --git a/evals/corpus/sdxl.md b/evals/corpus/sdxl.md new file mode 100644 index 0000000..d9ceb3e --- /dev/null +++ b/evals/corpus/sdxl.md @@ -0,0 +1,17 @@ +# Stable Diffusion XL (SDXL) + +Stable Diffusion XL, usually abbreviated SDXL, is a latent diffusion model released by Stability AI in 2023. It builds on the original Stable Diffusion architecture but with larger components and a higher native resolution, which makes it one of the most common base models for local image generation. + +## Architecture changes over SD 1.5 + +SDXL keeps the overall pipeline — text encoder, U-Net denoiser, VAE decoder — but scales each part up. The UNet is roughly three times larger than in SD 1.5 and uses a deeper transformer-style attention block called the "big" attention layer. The variational autoencoder compresses images by a factor of eight per spatial dimension into a latent tensor with sixteen channels, compared to four channels in SD 1.5. + +The text conditioning also changed: SDXL uses two CLIP encoders at once, an openai/clip-vit-large-patch14 model and an open_clip ViT-bigG model. The hidden states of both encoders are concatenated and fed into the UNet, which gives the model access to richer semantic information from the prompt than a single encoder can provide. + +## Native resolution + +SDXL was trained primarily at 1024 by 1024 pixels. Generating at that square size is where the model performs best; other aspect ratios work but should stay close to roughly one megapixel in total area. Pushing SDXL far outside its training range — for example a very wide banner or an extremely tall portrait — tends to produce duplicated subjects, warped anatomy, and degraded text rendering. + +## Practical notes + +Because of the larger UNet, SDXL needs more VRAM than SD 1.5: comfortable interactive generation starts around eight gigabytes with optimizations such as attention slicing enabled. Community fine-tunes and LoRAs trained on SDXL are not compatible with SD 1.5 checkpoints, so a workflow must commit to one base model family. Prompt style also shifted slightly: SDXL responds well to natural-language descriptions in addition to the comma-separated tag style popular for SD 1.5, though both still work. diff --git a/evals/corpus/training-failure-modes.md b/evals/corpus/training-failure-modes.md new file mode 100644 index 0000000..c49406b --- /dev/null +++ b/evals/corpus/training-failure-modes.md @@ -0,0 +1,19 @@ +# Common LoRA Training Failure Modes + +Most failed LoRAs fail in one of a handful of predictable ways. Recognizing the symptom early saves hours of retraining. + +## Overfitting + +The classic failure: the adapter memorizes the training images instead of learning the concept. Symptoms include the subject appearing with the exact same background, pose, or clothing from the dataset no matter what the prompt says, plus plastic-looking skin and smeared textures. Causes are too many epochs for the dataset size, a learning rate that is too high, or a rank that is too large relative to the data. The fix is fewer epochs (often one to three for small datasets), a lower learning rate, and a smaller rank — then verify with test prompts that use backgrounds absent from the training set. + +## Identity drift + +The opposite problem: generations look like the subject only loosely. The model never locked onto distinguishing features because the dataset was too small, the trigger word appeared inconsistently in captions, or images of similar-but-different subjects were mixed in. Check the dataset first — identity drift is usually a data problem, not a hyperparameter problem. + +## Prompt bleed + +The adapter starts affecting unrelated generations: adding "skto woman" to a prompt about a cityscape changes the sky's color because one training image had an unusual sunset. This happens when captions under-described the scene, so the model attributed background details to the trigger word. Rewriting captions to explicitly describe backgrounds and lighting usually resolves it on retrain. + +## Silent no-ops + +A LoRA that does nothing at any strength is almost always a plumbing error: the adapter was trained for a different base model family (SD 1.5 weights loaded into an SDXL pipeline), the file was copied incompletely, or the strength slider sits at zero. Verify the base-model match and reload the file before suspecting the training itself. diff --git a/evals/corpus/upscaling-and-resolution.md b/evals/corpus/upscaling-and-resolution.md new file mode 100644 index 0000000..647309f --- /dev/null +++ b/evals/corpus/upscaling-and-resolution.md @@ -0,0 +1,19 @@ +# Resolution and Upscaling + +Diffusion models generate at a fixed native resolution; getting larger or sharper images requires a second stage. This document covers how the two stages fit together. + +## Why not just generate big? + +Generating directly at 4K would require a latent canvas far outside the model's training distribution: subjects duplicate, anatomy breaks down, and memory usage grows with pixel count. The standard approach is to generate at native resolution — 1024 by 1024 for SDXL — and then upscale the result with a dedicated upscaler network. + +## Upscaler networks + +Modern upscalers are small convolutional networks trained on paired low/high-resolution crops; they learn plausible high-frequency detail rather than merely interpolating pixels. Popular choices include ESRGAN variants and SwinIR-style transformers. An upscaler multiplies the image by a fixed factor, commonly 2x or 4x, so a 1024-pixel source becomes 2048 or 4096 pixels after one pass. + +## Tiled upscaling + +Upscaling a full 4K canvas in one go can exceed GPU memory, so upscalers run in tiles: the image is split into overlapping patches (typically 512 by 512 with some overlap), each patch is upscaled independently, and the results are blended back together. The overlap prevents visible seams at tile boundaries; too little overlap shows faint grid lines, while excessive overlap wastes compute without improving quality. + +## Two-stage refinement + +A common high-quality recipe is: generate at native resolution, upscale 2x with a strong upscaler, then run a light diffusion pass over the upscaled image (image-to-image with low denoise strength around 0.3 to 0.4). The second stage lets the diffusion model re-render fine detail — skin texture, fabric weave, foliage — at the higher resolution instead of trusting the upscaler's hallucinated detail alone. This is slower but usually the best-looking result for hero images. diff --git a/evals/corpus/vector-search-basics.md b/evals/corpus/vector-search-basics.md new file mode 100644 index 0000000..35a7052 --- /dev/null +++ b/evals/corpus/vector-search-basics.md @@ -0,0 +1,19 @@ +# Vector Search Basics + +Retrieval-augmented systems answer questions by finding the most similar stored text fragments, and that "most similar" is computed with vectors. This document explains the pieces behind a simple embedding-based search index. + +## Embeddings + +A text embedding model maps a piece of text to a fixed-length list of floating-point numbers — for example 384 or 768 values. Texts with similar meaning land close together in this vector space, so similarity between two texts reduces to a geometric question about their vectors. The same model must be used to embed both the stored documents and the query; mixing embeddings from different models is meaningless because each model defines its own coordinate system. + +## Cosine similarity + +The standard similarity measure is cosine similarity: the angle between two vectors, computed as the dot product of their L2-normalized versions. Values range from -1 (opposite) through 0 (unrelated) to 1 (identical direction). A practical trick used by most systems is to normalize every vector once at storage time; then plain inner products already equal cosine similarity and no normalization is needed per query. + +## Flat indexes + +The simplest index stores all vectors in a dense array and computes the inner product with the query against every row — an exact brute-force search, often called a flat index. FAISS provides this as `IndexFlatIP` (inner product). Exact search costs time proportional to the number of stored vectors, but for tens or hundreds of thousands of short vectors it completes in milliseconds on CPU, which is why local single-user tools rarely need approximate methods at all. + +## When to move on + +Approximate nearest-neighbor structures such as HNSW graphs trade a small loss in recall for large speedups at scale — millions of vectors and beyond. They add configuration (graph degree, construction ef) and memory overhead, so the rule of thumb is: stay flat until exact search measurably hurts latency, then switch. diff --git a/evals/questions.json b/evals/questions.json new file mode 100644 index 0000000..f26d85e --- /dev/null +++ b/evals/questions.json @@ -0,0 +1,409 @@ +[ + { + "id": "q01", + "question": "What does a diffusion model learn to do in order to generate an image?", + "source_docs": ["diffusion-basics"], + "key_facts": [ + "reversing a gradual noising process", + "remove a little noise at a time" + ] + }, + { + "id": "q02", + "question": "What network architecture is typically used for the denoiser, and what does it take as input?", + "source_docs": ["diffusion-basics"], + "key_facts": [ + "U-Net that takes a noisy image and a step counter as input" + ] + }, + { + "id": "q03", + "question": "How many sampling steps does a typical generation use?", + "source_docs": ["diffusion-basics"], + "key_facts": [ + "between 20 and 50 steps" + ] + }, + { + "id": "q04", + "question": "Why do modern systems such as Stable Diffusion operate in latent space instead of raw pixels?", + "source_docs": ["diffusion-basics"], + "key_facts": [ + "Running the full noising process on raw pixels is expensive", + "compressed latent space" + ] + }, + { + "id": "q05", + "question": "How does text conditioning steer image generation in a diffusion model?", + "source_docs": ["diffusion-basics"], + "key_facts": [ + "cross-attention layers let every part of the image attend to those tokens" + ] + }, + { + "id": "q06", + "question": "When was SDXL released and by whom?", + "source_docs": ["sdxl"], + "key_facts": [ + "released by Stability AI in 2023" + ] + }, + { + "id": "q07", + "question": "How does the size of SDXL's UNet compare to SD 1.5's?", + "source_docs": ["sdxl"], + "key_facts": [ + "roughly three times larger than in SD 1.5" + ] + }, + { + "id": "q08", + "question": "How does the VAE latent representation differ between SDXL and SD 1.5?", + "source_docs": ["sdxl"], + "key_facts": [ + "sixteen channels, compared to four channels in SD 1.5" + ] + }, + { + "id": "q09", + "question": "How does SDXL condition on text prompts differently from earlier models?", + "source_docs": ["sdxl"], + "key_facts": [ + "two CLIP encoders at once", + "open_clip ViT-bigG" + ] + }, + { + "id": "q10", + "question": "At what resolution was SDXL primarily trained?", + "source_docs": ["sdxl"], + "key_facts": [ + "trained primarily at 1024 by 1024 pixels" + ] + }, + { + "id": "q11", + "question": "How much VRAM is needed for comfortable interactive SDXL generation?", + "source_docs": ["sdxl"], + "key_facts": [ + "around eight gigabytes with optimizations such as attention slicing enabled" + ] + }, + { + "id": "q12", + "question": "Are LoRAs trained on SDXL compatible with SD 1.5 checkpoints?", + "source_docs": ["sdxl"], + "key_facts": [ + "not compatible with SD 1.5 checkpoints" + ] + }, + { + "id": "q13", + "question": "Where in a prompt should the main subject be placed, and why?", + "source_docs": ["prompt-engineering"], + "key_facts": [ + "Models attend most strongly to the beginning of the prompt", + "Put the main subject in the first few words" + ] + }, + { + "id": "q14", + "question": "What is a safe range for emphasis weights using parentheses?", + "source_docs": ["prompt-engineering"], + "key_facts": [ + "Weights between 1.1 and 1.5 are a safe range" + ] + }, + { + "id": "q15", + "question": "What happens if you push emphasis weights above about 2?", + "source_docs": ["prompt-engineering"], + "key_facts": [ + "distorts anatomy or saturates colors", + "over-commits to that concept at every denoising step" + ] + }, + { + "id": "q16", + "question": "How do negative prompts work?", + "source_docs": ["prompt-engineering"], + "key_facts": [ + "conditioning the model to move away from those concepts during sampling" + ] + }, + { + "id": "q17", + "question": "Which negative terms are most effective for anatomy problems?", + "source_docs": ["prompt-engineering"], + "key_facts": [ + "extra fingers", + "deformed hands", + "bad anatomy" + ] + }, + { + "id": "q18", + "question": "What happens to prompt text beyond roughly seventy-five tokens?", + "source_docs": ["prompt-engineering"], + "key_facts": [ + "beyond roughly seventy-five tokens are truncated by the CLIP encoder" + ] + }, + { + "id": "q19", + "question": "What does the CFG scale control?", + "source_docs": ["sampling-and-cfg"], + "key_facts": [ + "interpolates between \"what the model thinks is likely\" and \"what matches the prompt\"" + ] + }, + { + "id": "q20", + "question": "What CFG value means pure model output with no extra steering?", + "source_docs": ["sampling-and-cfg"], + "key_facts": [ + "A CFG of 1 means pure model output with no extra steering" + ] + }, + { + "id": "q21", + "question": "What is a sensible starting CFG range for SDXL work?", + "source_docs": ["sampling-and-cfg"], + "key_facts": [ + "a CFG between 5 and 7 is a sensible starting point" + ] + }, + { + "id": "q22", + "question": "Which sampler pairs a second-order prediction with a Karras noise schedule?", + "source_docs": ["sampling-and-cfg"], + "key_facts": [ + "DPM++ 2M Karras", + "pairs a second-order prediction with a Karras noise schedule" + ] + }, + { + "id": "q23", + "question": "Which sampler is deterministic for a given seed?", + "source_docs": ["sampling-and-cfg"], + "key_facts": [ + "deterministic for a given seed" + ] + }, + { + "id": "q24", + "question": "What practical default combination of sampler, steps, and CFG is recommended?", + "source_docs": ["sampling-and-cfg"], + "key_facts": [ + "DPM++ 2M Karras, 25 steps, CFG 6" + ] + }, + { + "id": "q25", + "question": "How does LoRA avoid updating all the weights of a large model?", + "source_docs": ["lora-concepts"], + "key_facts": [ + "freezes W and learns two smaller matrices A and B" + ] + }, + { + "id": "q26", + "question": "What does rank control in a LoRA, and which range captures a single strong concept?", + "source_docs": ["lora-concepts"], + "key_facts": [ + "Low ranks (4 to 8) capture a single strong concept" + ] + }, + { + "id": "q27", + "question": "How is the effective strength of a LoRA adapter at inference time determined?", + "source_docs": ["lora-concepts"], + "key_facts": [ + "alpha divided by rank" + ] + }, + { + "id": "q28", + "question": "How large is a typical SDXL LoRA file compared to a full checkpoint?", + "source_docs": ["lora-concepts"], + "key_facts": [ + "10 to 200 megabytes on disk versus several gigabytes for a full checkpoint" + ] + }, + { + "id": "q29", + "question": "How many training images is the usual working range for a single-subject LoRA?", + "source_docs": ["lora-dataset-curation"], + "key_facts": [ + "twenty to fifty images is the usual working range" + ] + }, + { + "id": "q30", + "question": "What should vary and what must stay consistent in a LoRA dataset?", + "source_docs": ["lora-dataset-curation"], + "key_facts": [ + "different angles (front, three-quarter, profile), lighting conditions, backgrounds, and distances", + "What must stay consistent is the identity itself" + ] + }, + { + "id": "q31", + "question": "How should captions for LoRA training describe each image?", + "source_docs": ["lora-dataset-curation"], + "key_facts": [ + "describes everything except the trigger word reserved for the subject" + ] + }, + { + "id": "q32", + "question": "What cleaning steps should be applied before LoRA training?", + "source_docs": ["lora-dataset-curation"], + "key_facts": [ + "remove duplicates and near-duplicates", + "reject blurry or watermarked shots", + "normalize resolution" + ] + }, + { + "id": "q33", + "question": "What core nodes does every ComfyUI workflow contain?", + "source_docs": ["comfyui-workflows"], + "key_facts": [ + "CheckpointLoader that loads the base model", + "KSampler that runs the denoising loop" + ] + }, + { + "id": "q34", + "question": "What does a KSampler denoise strength of 1.0 mean?", + "source_docs": ["comfyui-workflows"], + "key_facts": [ + "1.0 ignores it entirely (pure generation)" + ] + }, + { + "id": "q35", + "question": "How are ComfyUI workflows stored?", + "source_docs": ["comfyui-workflows"], + "key_facts": [ + "saved as JSON files describing nodes and their connections" + ] + }, + { + "id": "q36", + "question": "Where does Apollo store its built-in workflow templates?", + "source_docs": ["comfyui-workflows"], + "key_facts": [ + "stores its built-in workflow templates in a `workflows` directory" + ] + }, + { + "id": "q37", + "question": "What are the default chunking parameters for Apollo's knowledge base?", + "source_docs": ["apollo-rag-knowledge-base"], + "key_facts": [ + "overlapping chunks of 800 characters with 150 characters of overlap" + ] + }, + { + "id": "q38", + "question": "How does Apollo avoid re-embedding unchanged documents?", + "source_docs": ["apollo-rag-knowledge-base"], + "key_facts": [ + "tracked by content hash", + "re-uploading an unchanged file skips re-embedding entirely" + ] + }, + { + "id": "q39", + "question": "What kind of index does Apollo use for its knowledge base, and how is similarity computed?", + "source_docs": ["apollo-rag-knowledge-base"], + "key_facts": [ + "FAISS flat inner-product index on disk", + "L2-normalized before storage, which makes the inner product equivalent to cosine similarity" + ] + }, + { + "id": "q40", + "question": "How many chunks does Apollo retrieve by default when answering a chat question?", + "source_docs": ["apollo-rag-knowledge-base"], + "key_facts": [ + "top four most similar chunks are retrieved by default (configurable via `RAG_TOP_K`)" + ] + }, + { + "id": "q41", + "question": "What quality checks does Apollo run on LoRA dataset images before training?", + "source_docs": ["apollo-lora-pipeline"], + "key_facts": [ + "Images are decoded to verify they are not corrupt", + "near-duplicates are detected by perceptual hash", + "resolution is checked against a minimum threshold" + ] + }, + { + "id": "q42", + "question": "How does Apollo generate captions for training images?", + "source_docs": ["apollo-lora-pipeline"], + "key_facts": [ + "If Ollama with a vision model is available locally, Apollo uses it to generate descriptive captions automatically" + ] + }, + { + "id": "q43", + "question": "Why shouldn't you generate directly at 4K, and what is the two-stage refinement recipe?", + "source_docs": ["upscaling-and-resolution"], + "key_facts": [ + "far outside the model's training distribution: subjects duplicate, anatomy breaks down", + "upscale 2x with a strong upscaler", + "low denoise strength around 0.3 to 0.4" + ] + }, + { + "id": "q44", + "question": "Why must embeddings come from a single model, and how does Apollo enforce this?", + "source_docs": ["vector-search-basics", "apollo-rag-knowledge-base"], + "key_facts": [ + "each model defines its own coordinate system", + "loading an index built with a different model is refused" + ] + }, + { + "id": "q45", + "question": "What are the symptoms of an overfit LoRA?", + "source_docs": ["training-failure-modes"], + "key_facts": [ + "the subject appearing with the exact same background, pose, or clothing from the dataset", + "plastic-looking skin and smeared textures" + ] + }, + { + "id": "q46", + "question": "What usually causes identity drift in LoRA training?", + "source_docs": ["training-failure-modes", "lora-dataset-curation"], + "key_facts": [ + "identity drift is usually a data problem, not a hyperparameter problem", + "Including images where the subject looks like someone else actively teaches the model the wrong thing" + ] + }, + { + "id": "q47", + "question": "How do LoRA rank and alpha settings flow into Apollo's generated training configuration?", + "source_docs": ["lora-concepts", "apollo-lora-pipeline"], + "key_facts": [ + "alpha divided by rank", + "rank and alpha, learning rate, epochs, and batch size" + ] + }, + { + "id": "q48", + "question": "At what resolution should SDXL generate before upscaling, and why not directly larger?", + "source_docs": ["sdxl", "upscaling-and-resolution"], + "key_facts": [ + "trained primarily at 1024 by 1024 pixels", + "far outside the model's training distribution" + ] + } +] From e5640a5036a35900d48f9c97e1d9c07cbd7aeb79 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 16:46:54 +0200 Subject: [PATCH 16/48] Item 18: typed loader for the RAG eval dataset evals.dataset turns corpus/*.md + questions.json into frozen dataclasses (CorpusDoc, Question, EvalDataset) with validation: non-empty docs, unique question ids, well-formed fields, and cross-check that every source_docs reference resolves to a real document. 16 tests pin the committed dataset (12 docs, q01-q48, 4 cross-doc questions) and cover all error paths. --- evals/__init__.py | 6 ++ evals/dataset.py | 148 +++++++++++++++++++++++++++++++++++++ tests/test_eval_dataset.py | 132 +++++++++++++++++++++++++++++++++ 3 files changed, 286 insertions(+) create mode 100644 evals/__init__.py create mode 100644 evals/dataset.py create mode 100644 tests/test_eval_dataset.py diff --git a/evals/__init__.py b/evals/__init__.py new file mode 100644 index 0000000..5c963bc --- /dev/null +++ b/evals/__init__.py @@ -0,0 +1,6 @@ +"""RAG retrieval evaluation (portfolio items 17-24). + +Data lives in this directory: ground-truth documents under ``corpus/`` and the +question set in ``questions.json``. The Python modules here load that data, +build indexes, run retrievers against it, and write reports. +""" diff --git a/evals/dataset.py b/evals/dataset.py new file mode 100644 index 0000000..c98de88 --- /dev/null +++ b/evals/dataset.py @@ -0,0 +1,148 @@ +"""Loading of the RAG evaluation dataset (portfolio item 18). + +The dataset is plain data on disk: ground-truth documents under ``corpus/`` +and a question set in ``questions.json``. This module turns that into typed, +validated records so every later stage (index building, retrieval, metrics) +can rely on the same shapes and on referential integrity between the two. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path + +EVALS_DIR = Path(__file__).resolve().parent +CORPUS_DIR = EVALS_DIR / "corpus" +QUESTIONS_FILE = EVALS_DIR / "questions.json" + + +@dataclass(frozen=True) +class CorpusDoc: + """One ground-truth document from the corpus.""" + + doc_id: str # file stem, e.g. "sdxl" + title: str + text: str + + +@dataclass(frozen=True) +class Question: + """One evaluation question with its ground truth.""" + + id: str + question: str + source_docs: tuple[str, ...] + key_facts: tuple[str, ...] + + +@dataclass(frozen=True) +class EvalDataset: + """The full dataset: corpus documents plus the validated question set.""" + + docs: tuple[CorpusDoc, ...] + questions: tuple[Question, ...] + + @property + def doc_ids(self) -> frozenset[str]: + return frozenset(doc.doc_id for doc in self.docs) + + +class DatasetError(ValueError): + """Raised when the on-disk dataset is malformed or inconsistent.""" + + +def _first_heading(text: str) -> str | None: + for line in text.splitlines(): + if line.startswith("# "): + return line[2:].strip() + return None + + +def load_corpus(corpus_dir: Path = CORPUS_DIR) -> list[CorpusDoc]: + """Load every ``*.md`` document under *corpus_dir*, sorted by file name.""" + if not corpus_dir.is_dir(): + raise DatasetError(f"corpus directory not found: {corpus_dir}") + docs: list[CorpusDoc] = [] + for path in sorted(corpus_dir.glob("*.md")): + text = path.read_text(encoding="utf-8") + if not text.strip(): + raise DatasetError(f"empty corpus document: {path.name}") + title = _first_heading(text) or path.stem + docs.append(CorpusDoc(doc_id=path.stem, title=title, text=text)) + if not docs: + raise DatasetError(f"no markdown documents in {corpus_dir}") + return docs + + +def load_questions(path: Path = QUESTIONS_FILE) -> list[Question]: + """Load and validate the question set from *path*.""" + raw = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(raw, list): + raise DatasetError(f"questions file must contain a JSON array: {path}") + questions: list[Question] = [] + seen_ids: set[str] = set() + for index, entry in enumerate(raw): + question = _parse_question(entry, index) + if question.id in seen_ids: + raise DatasetError(f"duplicate question id: {question.id!r}") + seen_ids.add(question.id) + questions.append(question) + return questions + + +def load_dataset( + corpus_dir: Path = CORPUS_DIR, + questions_file: Path = QUESTIONS_FILE, +) -> EvalDataset: + """Load the corpus and question set, then validate that they agree. + + Every ``source_docs`` entry of every question must name a document that + exists in the corpus; this catches typos and documents renamed or deleted + after the questions were written. + """ + docs = load_corpus(corpus_dir) + questions = load_questions(questions_file) + doc_ids = {doc.doc_id for doc in docs} + for question in questions: + for ref in question.source_docs: + if ref not in doc_ids: + raise DatasetError( + f"question {question.id!r} references unknown document {ref!r}" + ) + return EvalDataset(docs=tuple(docs), questions=tuple(questions)) + + +def _parse_question(entry: object, index: int) -> Question: + if not isinstance(entry, dict): + raise DatasetError(f"question #{index} is not a JSON object") + try: + qid = entry["id"] + question_text = entry["question"] + source_docs = entry["source_docs"] + key_facts = entry["key_facts"] + except KeyError as exc: + raise DatasetError(f"question #{index} missing field {exc.args[0]!r}") from None + if not isinstance(qid, str) or not qid.strip(): + raise DatasetError(f"question #{index}: 'id' must be a non-empty string") + if not isinstance(question_text, str) or not question_text.strip(): + raise DatasetError(f"question {qid!r}: 'question' must be a non-empty string") + return Question( + id=qid.strip(), + question=question_text.strip(), + source_docs=_str_tuple(source_docs, qid, "source_docs"), + key_facts=_str_tuple(key_facts, qid, "key_facts"), + ) + + +def _str_tuple(value: object, qid: str, field: str) -> tuple[str, ...]: + if not isinstance(value, list): + raise DatasetError(f"question {qid!r}: '{field}' must be a list of strings") + items = [item.strip() for item in value if isinstance(item, str) and item.strip()] + if len(items) != len(value): + raise DatasetError( + f"question {qid!r}: '{field}' entries must all be non-empty strings" + ) + if not items: + raise DatasetError(f"question {qid!r}: '{field}' must not be empty") + return tuple(items) diff --git a/tests/test_eval_dataset.py b/tests/test_eval_dataset.py new file mode 100644 index 0000000..af32841 --- /dev/null +++ b/tests/test_eval_dataset.py @@ -0,0 +1,132 @@ +"""Loading of the RAG evaluation dataset (portfolio item 18). + +The first class pins the committed dataset itself (size, ids, referential +integrity) so a silent change to the ground truth cannot invalidate earlier +eval numbers. The remaining classes cover the loader's error paths with +synthetic data in tmp_path. +""" + +from __future__ import annotations + +import json + +import pytest + +from evals.dataset import DatasetError, load_corpus, load_dataset, load_questions + + +class TestCommittedDataset: + """The dataset committed by item 17 must stay exactly as pinned here.""" + + def test_corpus_has_twelve_documents(self): + docs = load_corpus() + assert len(docs) == 12 + assert all(doc.text.strip() for doc in docs) + assert all(doc.title for doc in docs) + + def test_questions_are_pinned_q01_to_q48(self): + questions = load_questions() + ids = [question.id for question in questions] + assert ids == [f"q{i:02d}" for i in range(1, 49)] + + def test_every_source_doc_resolves(self): + dataset = load_dataset() + for question in dataset.questions: + assert set(question.source_docs) <= dataset.doc_ids + + def test_cross_document_questions_exist(self): + cross = [q for q in load_questions() if len(q.source_docs) > 1] + assert len(cross) == 4 + + +class TestCorpusLoading: + def test_missing_directory_raises(self, tmp_path): + with pytest.raises(DatasetError, match="corpus directory not found"): + load_corpus(tmp_path / "nope") + + def test_empty_directory_raises(self, tmp_path): + (tmp_path / "corpus").mkdir() + with pytest.raises(DatasetError, match="no markdown documents"): + load_corpus(tmp_path / "corpus") + + def test_blank_file_raises(self, tmp_path): + corpus = tmp_path / "corpus" + corpus.mkdir() + (corpus / "blank.md").write_text(" \n", encoding="utf-8") + with pytest.raises(DatasetError, match="empty corpus document"): + load_corpus(corpus) + + def test_title_falls_back_to_stem_when_no_heading(self, tmp_path): + corpus = tmp_path / "corpus" + corpus.mkdir() + (corpus / "no-heading.md").write_text("just text\n", encoding="utf-8") + docs = load_corpus(corpus) + assert docs[0].title == "no-heading" + + def test_heading_becomes_title(self, tmp_path): + corpus = tmp_path / "corpus" + corpus.mkdir() + (corpus / "doc.md").write_text("# The Title\nBody.\n", encoding="utf-8") + docs = load_corpus(corpus) + assert docs[0].title == "The Title" + + +class TestQuestionLoading: + def _write(self, tmp_path, payload): + path = tmp_path / "questions.json" + path.write_text(json.dumps(payload), encoding="utf-8") + return path + + @staticmethod + def _entry(**overrides): + entry = {"id": "q01", "question": "Q?", "source_docs": ["a"], "key_facts": ["f"]} + entry.update(overrides) + return entry + + def test_non_array_raises(self, tmp_path): + with pytest.raises(DatasetError, match="JSON array"): + load_questions(self._write(tmp_path, {"id": "q01"})) + + def test_missing_field_raises(self, tmp_path): + entry = self._entry() + del entry["key_facts"] + with pytest.raises(DatasetError, match="missing field 'key_facts'"): + load_questions(self._write(tmp_path, [entry])) + + def test_duplicate_id_raises(self, tmp_path): + with pytest.raises(DatasetError, match="duplicate question id"): + load_questions(self._write(tmp_path, [self._entry(), dict(self._entry())])) + + def test_empty_key_facts_raises(self, tmp_path): + with pytest.raises(DatasetError, match="'key_facts' must not be empty"): + load_questions(self._write(tmp_path, [self._entry(key_facts=[])])) + + def test_non_string_fact_raises(self, tmp_path): + with pytest.raises(DatasetError, match="non-empty strings"): + load_questions(self._write(tmp_path, [self._entry(key_facts=[42])])) + + +class TestCrossValidation: + @pytest.fixture + def corpus_dir(self, tmp_path): + corpus = tmp_path / "corpus" + corpus.mkdir() + (corpus / "alpha.md").write_text("# Alpha\nText.\n", encoding="utf-8") + return corpus + + def _questions_file(self, tmp_path, source_docs): + path = tmp_path / "questions.json" + entry = {"id": "q01", "question": "Q?", "source_docs": source_docs, "key_facts": ["f"]} + path.write_text(json.dumps([entry]), encoding="utf-8") + return path + + def test_unknown_document_reference_raises(self, tmp_path, corpus_dir): + questions = self._questions_file(tmp_path, ["beta"]) + with pytest.raises(DatasetError, match="unknown document 'beta'"): + load_dataset(corpus_dir=corpus_dir, questions_file=questions) + + def test_valid_pair_loads(self, tmp_path, corpus_dir): + questions = self._questions_file(tmp_path, ["alpha"]) + dataset = load_dataset(corpus_dir=corpus_dir, questions_file=questions) + assert len(dataset.docs) == 1 + assert len(dataset.questions) == 1 From 49f2ffcaf1d58490cfea360da0d326d1d9cb14d2 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 16:54:12 +0200 Subject: [PATCH 17/48] Item 19: retrieval metrics for the RAG eval evals.metrics scores document-level retrieval quality: recall_at_k, reciprocal_rank (raw chunk ranks), hit_at_k, plus QuestionResult and summarize() -> MetricsSummary(mean_recall@k, mrr, hit_rate@k). Semantics match what the pipeline actually consumes: the top-k cutoff applies to chunks (repeats occupy slots) and each document counts once within a cutoff. 23 tests cover perfect/partial/zero recall, cutoff boundaries, rank shifts from repeats, error paths, and hand-computed aggregates. --- evals/metrics.py | 106 ++++++++++++++++++++++++++++++++++ tests/test_eval_metrics.py | 113 +++++++++++++++++++++++++++++++++++++ 2 files changed, 219 insertions(+) create mode 100644 evals/metrics.py create mode 100644 tests/test_eval_metrics.py diff --git a/evals/metrics.py b/evals/metrics.py new file mode 100644 index 0000000..a533c27 --- /dev/null +++ b/evals/metrics.py @@ -0,0 +1,106 @@ +"""Retrieval metrics for the RAG evaluation (portfolio item 19). + +The unit of scoring is the *document*: a question is answered well when the +retriever surfaces chunks from its ground-truth ``source_docs``. Metrics are +computed on the raw ranked chunk list exactly as the pipeline would consume +it - the top-*k* cutoff applies to chunks, so repeated chunks from one +document do occupy slots - and a document is then counted at most once when +scoring that cutoff. +""" + +from __future__ import annotations + +from collections.abc import Collection, Sequence +from dataclasses import dataclass + + +def recall_at_k( + retrieved_doc_ids: Sequence[str], relevant_doc_ids: Collection[str], k: int +) -> float: + """Fraction of relevant documents present in the top-*k* results. + + The cutoff applies to the raw ranked list (repeats occupy slots); within + the cutoff each document counts once. Returns a value in [0, 1]; 1.0 + means every ground-truth document was retrieved within the cutoff. + Raises ``ValueError`` for an empty relevance set or a non-positive *k*. + """ + if k <= 0: + raise ValueError(f"k must be positive, got {k}") + relevant = set(relevant_doc_ids) + if not relevant: + raise ValueError("relevant_doc_ids must be non-empty") + top_k_docs = set(retrieved_doc_ids[:k]) + return len(top_k_docs & relevant) / len(relevant) + + +def reciprocal_rank( + retrieved_doc_ids: Sequence[str], relevant_doc_ids: Collection[str] +) -> float: + """1/rank of the first result from a relevant document (ranks start at 1). + + Ranks are positions in the raw list, so earlier repeats of an irrelevant + document push the first hit down. Returns 0.0 when no result is relevant. + """ + relevant = set(relevant_doc_ids) + for rank, doc_id in enumerate(retrieved_doc_ids, start=1): + if doc_id in relevant: + return 1.0 / rank + return 0.0 + + +def hit_at_k( + retrieved_doc_ids: Sequence[str], relevant_doc_ids: Collection[str], k: int +) -> bool: + """Whether at least one of the top-*k* results comes from a relevant doc.""" + if k <= 0: + raise ValueError(f"k must be positive, got {k}") + relevant = set(relevant_doc_ids) + return any(doc_id in relevant for doc_id in retrieved_doc_ids[:k]) + + +@dataclass(frozen=True) +class QuestionResult: + """The retrieval outcome for one question, ready to be scored.""" + + question_id: str + retrieved_doc_ids: tuple[str, ...] # ranked, best first + relevant_doc_ids: tuple[str, ...] # ground truth from the dataset + + def recall_at(self, k: int) -> float: + return recall_at_k(self.retrieved_doc_ids, self.relevant_doc_ids, k) + + def reciprocal_rank(self) -> float: + return reciprocal_rank(self.retrieved_doc_ids, self.relevant_doc_ids) + + def hit_at(self, k: int) -> bool: + return hit_at_k(self.retrieved_doc_ids, self.relevant_doc_ids, k) + + +@dataclass(frozen=True) +class MetricsSummary: + """Aggregate retrieval quality over a set of question results.""" + + num_questions: int + k: int + mean_recall_at_k: float + mrr: float + hit_rate_at_k: float + + +def summarize(results: Sequence[QuestionResult], k: int = 5) -> MetricsSummary: + """Average the per-question metrics over *results*. + + ``mrr`` is the mean reciprocal rank; ``hit_rate_at_k`` is the fraction of + questions with at least one relevant document in the top-*k*. Raises + ``ValueError`` when there are no results to summarize. + """ + if not results: + raise ValueError("cannot summarize zero question results") + n = len(results) + return MetricsSummary( + num_questions=n, + k=k, + mean_recall_at_k=sum(r.recall_at(k) for r in results) / n, + mrr=sum(r.reciprocal_rank() for r in results) / n, + hit_rate_at_k=sum(1.0 if r.hit_at(k) else 0.0 for r in results) / n, + ) diff --git a/tests/test_eval_metrics.py b/tests/test_eval_metrics.py new file mode 100644 index 0000000..35078b4 --- /dev/null +++ b/tests/test_eval_metrics.py @@ -0,0 +1,113 @@ +"""Retrieval metrics for the RAG evaluation (portfolio item 19).""" + +from __future__ import annotations + +import pytest + +from evals.metrics import ( + QuestionResult, + hit_at_k, + recall_at_k, + reciprocal_rank, + summarize, +) + + +class TestRecallAtK: + def test_perfect_recall(self): + assert recall_at_k(["a", "b"], {"a", "b"}, 5) == 1.0 + + def test_partial_recall(self): + # One of the two relevant docs is in the cutoff: recall = 1/2. + assert recall_at_k(["a", "x"], {"a", "b"}, 5) == pytest.approx(0.5) + + def test_no_hits(self): + assert recall_at_k(["x", "y"], {"a"}, 5) == 0.0 + + def test_cutoff_excludes_later_hits(self): + # Relevant doc exists but only at rank 6; k=5 must not see it. + assert recall_at_k(["x"] * 5 + ["a"], {"a"}, 5) == 0.0 + assert recall_at_k(["x"] * 5 + ["a"], {"a"}, 6) == 1.0 + + def test_repeated_doc_counts_once(self): + # One of two relevant docs, repeated to fill the cutoff: still 0.5. + assert recall_at_k(["a", "a", "a"], {"a", "b"}, 3) == pytest.approx(0.5) + + def test_empty_retrieval_scores_zero(self): + assert recall_at_k([], {"a"}, 5) == 0.0 + + @pytest.mark.parametrize("k", [0, -1]) + def test_non_positive_k_raises(self, k): + with pytest.raises(ValueError, match="k must be positive"): + recall_at_k(["a"], {"a"}, k) + + def test_empty_relevance_set_raises(self): + with pytest.raises(ValueError, match="non-empty"): + recall_at_k(["a"], set(), 5) + + +class TestReciprocalRank: + def test_first_position(self): + assert reciprocal_rank(["a", "b"], {"a", "b"}) == 1.0 + + def test_second_position(self): + assert reciprocal_rank(["x", "a"], {"a"}) == pytest.approx(0.5) + + def test_no_relevant_results(self): + assert reciprocal_rank(["x", "y"], {"a"}) == 0.0 + + def test_empty_retrieval(self): + assert reciprocal_rank([], {"a"}) == 0.0 + + def test_repeats_of_irrelevant_doc_shift_first_hit(self): + # Raw ranks: three irrelevant chunks occupy slots, so the hit is rank 4. + assert reciprocal_rank(["x", "x", "x", "a"], {"a"}) == pytest.approx(0.25) + + +class TestHitAtK: + def test_hit_within_cutoff(self): + assert hit_at_k(["x", "a"], {"a"}, 2) is True + + def test_miss_beyond_cutoff(self): + assert hit_at_k(["x"] * 3 + ["a"], {"a"}, 3) is False + + def test_no_hits(self): + assert hit_at_k(["x"], {"a"}, 5) is False + + @pytest.mark.parametrize("k", [0, -2]) + def test_non_positive_k_raises(self, k): + with pytest.raises(ValueError, match="k must be positive"): + hit_at_k(["a"], {"a"}, k) + + +class TestQuestionResult: + def test_methods_delegate_to_functions(self): + result = QuestionResult("q01", ("x", "a"), ("a", "b")) + assert result.recall_at(2) == pytest.approx(0.5) + assert result.reciprocal_rank() == pytest.approx(0.5) + assert result.hit_at(2) is True + + +class TestSummarize: + @pytest.fixture + def results(self): + return [ + QuestionResult("q1", ("a", "b"), ("a",)), # recall 1, rr 1, hit + QuestionResult("q2", ("x", "a"), ("a", "b")), # recall .5, rr .5, hit + QuestionResult("q3", ("y",), ("z",)), # recall 0, rr 0, miss + ] + + def test_aggregates(self, results): + summary = summarize(results, k=2) + assert summary.num_questions == 3 + assert summary.k == 2 + assert summary.mean_recall_at_k == pytest.approx(0.5) + assert summary.mrr == pytest.approx(0.5) + assert summary.hit_rate_at_k == pytest.approx(2 / 3) + + def test_default_k_is_five(self, results): + assert summarize(results).k == 5 + + def test_empty_raises(self): + with pytest.raises(ValueError, match="zero question results"): + summarize([], k=5) From 7434682ae105306eac7b63400265ee66bca11a28 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 17:07:28 +0200 Subject: [PATCH 18/48] Item 20: build the eval retrieval index evals.index.build_index chunks every corpus document with the production chunker (app.services.rag.chunking) and indexes the chunks in a fresh in-memory VectorStore, so the evaluation measures exactly what the RAG pipeline does. Chunking parameters default to settings.rag_chunk_size/rag_chunk_overlap; the embedder is injected via a BatchEmbedder protocol (tests use a deterministic content-hashed fake, the runner will pass EmbeddingClient). Returns IndexBuildResult(store, num_chunks, chunks_per_doc); dimension is inferred from the embedder output. 11 tests: chunk counts/metadata/ordering vs the production chunker, single batch call in doc order, self-query ranks own doc first at score ~1.0, error paths, full committed corpus builds, and defaults-follow-settings. --- evals/index.py | 98 +++++++++++++++++++++++ tests/test_eval_index.py | 168 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 266 insertions(+) create mode 100644 evals/index.py create mode 100644 tests/test_eval_index.py diff --git a/evals/index.py b/evals/index.py new file mode 100644 index 0000000..2ab5fd7 --- /dev/null +++ b/evals/index.py @@ -0,0 +1,98 @@ +"""Build a retrieval index from the eval corpus (portfolio item 20). + +Reuses the app's production chunker (:func:`app.services.rag.chunking.chunk_text`) +and vector store (:class:`app.services.rag.vector_store.VectorStore`) so the +evaluation measures exactly what the RAG pipeline does. The embedder is +injected: tests pass a deterministic fake, and the runner (item 21) passes the +real :class:`~app.services.rag.embeddings.EmbeddingClient`. + +The built store is in-memory only - evaluation never touches ``DATA_DIR``. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Protocol + +import numpy as np + +from app.core.config import settings +from app.services.rag.chunking import chunk_text +from app.services.rag.vector_store import StoredChunk, VectorStore +from evals.dataset import EvalDataset + + +class BatchEmbedder(Protocol): + """Anything that can embed a batch of texts (e.g. ``EmbeddingClient``).""" + + def embed_batch(self, texts: list[str]) -> np.ndarray: ... + + +@dataclass(frozen=True) +class IndexBuildResult: + """A fresh in-memory index over the corpus plus build diagnostics.""" + + store: VectorStore + num_chunks: int + chunks_per_doc: dict[str, int] + + +def build_index( + dataset: EvalDataset, + embedder: BatchEmbedder, + *, + chunk_size: int | None = None, + overlap: int | None = None, +) -> IndexBuildResult: + """Chunk every corpus document and index the chunks in a fresh store. + + Chunking parameters default to the app's production settings + (``rag_chunk_size`` / ``rag_chunk_overlap``), so by default the evaluation + measures exactly what the RAG pipeline does; pass explicit values to test + other configurations. All chunks are embedded in a single batch call, in + document order, and the embedding dimension is inferred from the output. + + Raises: + ValueError: empty dataset, a document that yields no chunks, or an + embedder result whose shape does not match the chunk count. + """ + if chunk_size is None: + chunk_size = settings.rag_chunk_size + if overlap is None: + overlap = settings.rag_chunk_overlap + if not dataset.docs: + raise ValueError("dataset has no documents") + + chunks_by_doc: dict[str, list[str]] = {} + for doc in dataset.docs: + chunks = chunk_text(doc.text, chunk_size=chunk_size, overlap=overlap) + if not chunks: + raise ValueError(f"document {doc.doc_id!r} produced no chunks") + chunks_by_doc[doc.doc_id] = chunks + + all_chunks = [text for doc in dataset.docs for text in chunks_by_doc[doc.doc_id]] + vectors = np.asarray(embedder.embed_batch(all_chunks), dtype=np.float32) + if vectors.ndim != 2 or vectors.shape[0] != len(all_chunks): + raise ValueError( + f"embedder returned shape {vectors.shape} for {len(all_chunks)} chunks" + ) + + store = VectorStore(dimension=vectors.shape[1]) + stored: list[StoredChunk] = [] + for doc in dataset.docs: + for chunk_index, text in enumerate(chunks_by_doc[doc.doc_id]): + stored.append( + StoredChunk( + doc_id=doc.doc_id, + filename=doc.doc_id, + chunk_index=chunk_index, + text=text, + ) + ) + store.add(vectors, stored) + + return IndexBuildResult( + store=store, + num_chunks=len(stored), + chunks_per_doc={doc_id: len(chunks) for doc_id, chunks in chunks_by_doc.items()}, + ) diff --git a/tests/test_eval_index.py b/tests/test_eval_index.py new file mode 100644 index 0000000..df2d442 --- /dev/null +++ b/tests/test_eval_index.py @@ -0,0 +1,168 @@ +"""Index building for the RAG evaluation (portfolio item 20). + +``build_index`` reuses the production chunker and vector store; these tests +run it against a deterministic fake embedder so no Ollama or model download is +needed. One class pins the build against the committed corpus itself. +""" + +from __future__ import annotations + +import hashlib +import json + +import numpy as np +import pytest + +from app.core.config import settings +from app.services.rag.chunking import chunk_text +from evals.dataset import EvalDataset, load_dataset +from evals.index import build_index + + +def _unit_vector(text: str, dim: int) -> np.ndarray: + """Deterministic unit vector derived from the text content.""" + seed = int.from_bytes(hashlib.sha256(text.encode("utf-8")).digest()[:8], "big") + rng = np.random.default_rng(seed) + vector = rng.standard_normal(dim).astype(np.float32) + return vector / np.linalg.norm(vector) + + +class FakeEmbedder: + """Stand-in for ``EmbeddingClient``: content-hashed unit vectors. + + Like the real client, output rows are L2-normalized, so inner products in + the flat index equal cosine similarity and a chunk scores 1.0 against its + own query vector. + """ + + def __init__(self, dim: int = 16) -> None: + self.dim = dim + self.calls: list[list[str]] = [] + + def embed_batch(self, texts: list[str]) -> np.ndarray: + self.calls.append(list(texts)) + return np.vstack([_unit_vector(t, self.dim) for t in texts]).astype(np.float32) + + +@pytest.fixture +def synthetic_dataset(tmp_path): + """Two documents - one single-chunk, one multi-chunk - plus a question.""" + corpus = tmp_path / "corpus" + corpus.mkdir() + short = ( + "# Alpha\nAlpha covers one narrow topic in a single short paragraph. " + "It stays well under the chunk size.\n" + ) + long_text = " ".join( + f"Beta sentence number {i} adds detail to the beta document." for i in range(1, 25) + ) + (corpus / "alpha.md").write_text(short, encoding="utf-8") + (corpus / "beta.md").write_text("# Beta\n" + long_text, encoding="utf-8") + + questions = tmp_path / "questions.json" + entry = {"id": "q01", "question": "Q?", "source_docs": ["alpha"], "key_facts": ["f"]} + questions.write_text(json.dumps([entry]), encoding="utf-8") + return load_dataset(corpus_dir=corpus, questions_file=questions) + + +class TestBuildIndex: + def test_indexes_every_chunk_of_every_document(self, synthetic_dataset): + result = build_index(synthetic_dataset, FakeEmbedder()) + + expected_counts = {doc.doc_id: len(chunk_text(doc.text)) for doc in synthetic_dataset.docs} + assert result.chunks_per_doc == expected_counts + assert result.num_chunks == sum(expected_counts.values()) + assert result.store.size == result.num_chunks + assert result.store.indexed_doc_ids == {"alpha", "beta"} + + def test_long_document_splits_into_multiple_chunks(self, synthetic_dataset): + result = build_index(synthetic_dataset, FakeEmbedder()) + assert result.chunks_per_doc["alpha"] == 1 + assert result.chunks_per_doc["beta"] >= 2 + def test_stored_chunks_carry_metadata_in_order(self, synthetic_dataset): + result = build_index(synthetic_dataset, FakeEmbedder()) + + expected_texts: list[str] = [] + for doc in synthetic_dataset.docs: + expected_texts.extend(chunk_text(doc.text)) + stored = result.store._chunks # same access pattern as RAGService + assert [chunk.text for chunk in stored] == expected_texts + + for doc in synthetic_dataset.docs: + indices = [c.chunk_index for c in stored if c.doc_id == doc.doc_id] + assert indices == list(range(len(chunk_text(doc.text)))) + + def test_single_embed_batch_call_in_document_order(self, synthetic_dataset): + embedder = FakeEmbedder() + build_index(synthetic_dataset, embedder) + + expected: list[str] = [] + for doc in synthetic_dataset.docs: + expected.extend(chunk_text(doc.text)) + assert len(embedder.calls) == 1 + assert embedder.calls[0] == expected + + def test_dimension_inferred_from_embedder(self, synthetic_dataset): + result = build_index(synthetic_dataset, FakeEmbedder(dim=32)) + assert result.store.dimension == 32 + + +class TestSearchIntegration: + def test_querying_with_chunk_vector_ranks_its_doc_first(self, synthetic_dataset): + embedder = FakeEmbedder() + result = build_index(synthetic_dataset, embedder) + + target_text = chunk_text(synthetic_dataset.docs[0].text)[0] + query = embedder.embed_batch([target_text])[0] + hits = result.store.search(query, top_k=3) + + assert len(hits) == 3 + assert hits[0].doc_id == "alpha" + assert hits[0].score == pytest.approx(1.0, abs=1e-5) + + +class TestErrors: + def test_empty_dataset_raises(self): + with pytest.raises(ValueError, match="no documents"): + build_index(EvalDataset(docs=(), questions=()), FakeEmbedder()) + + def test_embedder_wrong_row_count_raises(self, synthetic_dataset): + class Broken(FakeEmbedder): + def embed_batch(self, texts: list[str]) -> np.ndarray: + return np.zeros((len(texts) - 1, self.dim), dtype=np.float32) + + with pytest.raises(ValueError, match="shape"): + build_index(synthetic_dataset, Broken()) + + +class TestCommittedCorpus: + """The committed corpus must index cleanly end to end.""" + + def test_full_corpus_builds(self): + dataset = load_dataset() + result = build_index(dataset, FakeEmbedder(dim=32)) + + assert set(result.chunks_per_doc) == dataset.doc_ids + assert all(count >= 1 for count in result.chunks_per_doc.values()) + assert result.num_chunks == sum(result.chunks_per_doc.values()) + assert result.store.size == result.num_chunks + + +class TestChunkingDefaults: + def test_defaults_follow_production_settings(self, synthetic_dataset): + default = build_index(synthetic_dataset, FakeEmbedder()) + explicit = build_index( + synthetic_dataset, + FakeEmbedder(), + chunk_size=settings.rag_chunk_size, + overlap=settings.rag_chunk_overlap, + ) + assert default.num_chunks == explicit.num_chunks + + def test_explicit_parameters_are_honored(self, synthetic_dataset): + # Tiny chunks force many splits; huge chunks collapse each doc to one. + small = build_index(synthetic_dataset, FakeEmbedder(), chunk_size=100, overlap=20) + large = build_index(synthetic_dataset, FakeEmbedder(), chunk_size=10_000, overlap=0) + assert all(count >= 1 for count in small.chunks_per_doc.values()) + assert sum(large.chunks_per_doc.values()) == len(synthetic_dataset.docs) + From 0cee35bb20c73b2fe652d1f6fc9e4aaab9b77ad2 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 17:28:54 +0200 Subject: [PATCH 19/48] Item 21: retrieval runner for the RAG eval --- evals/runner.py | 71 ++++++++++++++++++ tests/__init__.py | 1 + tests/conftest.py | 29 ++++++++ tests/fakes.py | 32 ++++++++ tests/test_eval_index.py | 51 +------------ tests/test_eval_runner.py | 150 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 285 insertions(+), 49 deletions(-) create mode 100644 evals/runner.py create mode 100644 tests/__init__.py create mode 100644 tests/fakes.py create mode 100644 tests/test_eval_runner.py diff --git a/evals/runner.py b/evals/runner.py new file mode 100644 index 0000000..035c611 --- /dev/null +++ b/evals/runner.py @@ -0,0 +1,71 @@ +"""Retrieval runner for the RAG evaluation (portfolio item 21). + +Runs every question in an ``EvalDataset`` through a built index and produces +one scored-ready ``QuestionResult`` per question. The embedder is injected so +tests can use a deterministic fake; the CLI passes the real +``EmbeddingClient``. +""" + +from __future__ import annotations + +import numpy as np + +from app.core.config import settings +from app.services.rag.vector_store import VectorStore +from evals.dataset import EvalDataset +from evals.index import BatchEmbedder +from evals.metrics import QuestionResult + + +def retrieve_doc_ids( + store: VectorStore, embedder: BatchEmbedder, query_text: str, *, top_k: int = 4 +) -> tuple[str, ...]: + """Embed *query_text* and return the ranked doc ids of its top-k chunks. + + The list is raw - one entry per chunk, repeats allowed - matching how the + metrics consume it: the top-k cutoff applies to chunks, not documents. + Raises ``ValueError`` for a non-positive *top_k* or an embedder result that + is not exactly one row of the store's dimension. + """ + if top_k <= 0: + raise ValueError(f"top_k must be positive, got {top_k}") + vectors = np.asarray(embedder.embed_batch([query_text]), dtype=np.float32) + if vectors.shape != (1, store.dimension): + raise ValueError( + f"embedder returned shape {vectors.shape}, expected (1, {store.dimension})" + ) + hits = store.search(vectors[0], top_k=top_k) + return tuple(hit.doc_id for hit in hits) + + +def run_retrieval( + dataset: EvalDataset, + store: VectorStore, + embedder: BatchEmbedder, + *, + top_k: int | None = None, +) -> list[QuestionResult]: + """Run every question through retrieval and pair it with its ground truth. + + ``top_k`` defaults to the production setting (``rag_top_k``), so an eval + run measures what the pipeline actually serves. Results come back in + dataset order; each is ready for ``summarize`` or per-question scoring. + Raises: + ValueError: if the dataset has no questions, or *top_k* is non-positive. + """ + if top_k is None: + top_k = settings.rag_top_k + if not dataset.questions: + raise ValueError("dataset has no questions to run") + + results: list[QuestionResult] = [] + for question in dataset.questions: + retrieved = retrieve_doc_ids(store, embedder, question.question, top_k=top_k) + results.append( + QuestionResult( + question_id=question.id, + retrieved_doc_ids=retrieved, + relevant_doc_ids=tuple(question.source_docs), + ) + ) + return results diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..c01c33a --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Test suite for Apollo (see conftest.py for shared fixtures).""" diff --git a/tests/conftest.py b/tests/conftest.py index 715c07f..137540f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -151,6 +151,35 @@ def _set(name: str, value: object) -> None: object.__setattr__(config.settings, name, value) +@pytest.fixture +def synthetic_dataset(tmp_path): + """Two documents - one single-chunk, one multi-chunk - plus a question. + + Shared by the eval index/runner tests so they exercise identical content; + see ``tests/fakes.py`` for the matching deterministic embedder. + """ + import json + + from evals.dataset import load_dataset + + corpus = tmp_path / "corpus" + corpus.mkdir() + short = ( + "# Alpha\nAlpha covers one narrow topic in a single short paragraph. " + "It stays well under the chunk size.\n" + ) + long_text = " ".join( + f"Beta sentence number {i} adds detail to the beta document." for i in range(1, 25) + ) + (corpus / "alpha.md").write_text(short, encoding="utf-8") + (corpus / "beta.md").write_text("# Beta\n" + long_text, encoding="utf-8") + + questions = tmp_path / "questions.json" + entry = {"id": "q01", "question": "What does Alpha cover?", "source_docs": ["alpha"], "key_facts": ["f"]} + questions.write_text(json.dumps([entry]), encoding="utf-8") + return load_dataset(corpus_dir=corpus, questions_file=questions) + + @pytest.fixture def project_service(tmp_settings): from app.services.lora_dataset_service import LoRAProjectService diff --git a/tests/fakes.py b/tests/fakes.py new file mode 100644 index 0000000..4125e63 --- /dev/null +++ b/tests/fakes.py @@ -0,0 +1,32 @@ +"""Shared fakes for the RAG evaluation tests (deterministic, no network).""" + +from __future__ import annotations + +import hashlib + +import numpy as np + + +def unit_vector(text: str, dim: int) -> np.ndarray: + """Deterministic L2-normalized vector derived from *text* content.""" + seed = int.from_bytes(hashlib.sha256(text.encode("utf-8")).digest()[:8], "big") + rng = np.random.default_rng(seed) + vector = rng.standard_normal(dim).astype(np.float32) + return vector / np.linalg.norm(vector) + + +class FakeEmbedder: + """Stand-in for ``EmbeddingClient``: content-hashed unit vectors. + + Like the real client, output rows are L2-normalized, so inner products in + the flat index equal cosine similarity and a chunk scores 1.0 against its + own query vector. Records every call so tests can assert batching. + """ + + def __init__(self, dim: int = 16) -> None: + self.dim = dim + self.calls: list[list[str]] = [] + + def embed_batch(self, texts: list[str]) -> np.ndarray: + self.calls.append(list(texts)) + return np.vstack([unit_vector(t, self.dim) for t in texts]).astype(np.float32) diff --git a/tests/test_eval_index.py b/tests/test_eval_index.py index df2d442..c3ca256 100644 --- a/tests/test_eval_index.py +++ b/tests/test_eval_index.py @@ -7,9 +7,6 @@ from __future__ import annotations -import hashlib -import json - import numpy as np import pytest @@ -17,52 +14,7 @@ from app.services.rag.chunking import chunk_text from evals.dataset import EvalDataset, load_dataset from evals.index import build_index - - -def _unit_vector(text: str, dim: int) -> np.ndarray: - """Deterministic unit vector derived from the text content.""" - seed = int.from_bytes(hashlib.sha256(text.encode("utf-8")).digest()[:8], "big") - rng = np.random.default_rng(seed) - vector = rng.standard_normal(dim).astype(np.float32) - return vector / np.linalg.norm(vector) - - -class FakeEmbedder: - """Stand-in for ``EmbeddingClient``: content-hashed unit vectors. - - Like the real client, output rows are L2-normalized, so inner products in - the flat index equal cosine similarity and a chunk scores 1.0 against its - own query vector. - """ - - def __init__(self, dim: int = 16) -> None: - self.dim = dim - self.calls: list[list[str]] = [] - - def embed_batch(self, texts: list[str]) -> np.ndarray: - self.calls.append(list(texts)) - return np.vstack([_unit_vector(t, self.dim) for t in texts]).astype(np.float32) - - -@pytest.fixture -def synthetic_dataset(tmp_path): - """Two documents - one single-chunk, one multi-chunk - plus a question.""" - corpus = tmp_path / "corpus" - corpus.mkdir() - short = ( - "# Alpha\nAlpha covers one narrow topic in a single short paragraph. " - "It stays well under the chunk size.\n" - ) - long_text = " ".join( - f"Beta sentence number {i} adds detail to the beta document." for i in range(1, 25) - ) - (corpus / "alpha.md").write_text(short, encoding="utf-8") - (corpus / "beta.md").write_text("# Beta\n" + long_text, encoding="utf-8") - - questions = tmp_path / "questions.json" - entry = {"id": "q01", "question": "Q?", "source_docs": ["alpha"], "key_facts": ["f"]} - questions.write_text(json.dumps([entry]), encoding="utf-8") - return load_dataset(corpus_dir=corpus, questions_file=questions) +from tests.fakes import FakeEmbedder class TestBuildIndex: @@ -79,6 +31,7 @@ def test_long_document_splits_into_multiple_chunks(self, synthetic_dataset): result = build_index(synthetic_dataset, FakeEmbedder()) assert result.chunks_per_doc["alpha"] == 1 assert result.chunks_per_doc["beta"] >= 2 + def test_stored_chunks_carry_metadata_in_order(self, synthetic_dataset): result = build_index(synthetic_dataset, FakeEmbedder()) diff --git a/tests/test_eval_runner.py b/tests/test_eval_runner.py new file mode 100644 index 0000000..ef12a94 --- /dev/null +++ b/tests/test_eval_runner.py @@ -0,0 +1,150 @@ +"""Retrieval runner tests (portfolio item 21). + +``run_retrieval`` pairs every question with its ground truth; these tests use +the shared synthetic dataset plus a marker-based embedder whose two orthogonal +vectors make rankings fully deterministic. One test pins the run against the +committed corpus itself. +""" + +from __future__ import annotations + +import numpy as np +import pytest + +from app.core.config import settings +from evals.dataset import EvalDataset, load_dataset +from evals.index import build_index +from evals.metrics import summarize +from evals.runner import retrieve_doc_ids, run_retrieval +from tests.fakes import FakeEmbedder + + +class MarkerEmbedder: + """Maps each text to one of two orthogonal unit vectors. + + Text mentioning "alpha" gets the first basis vector, everything else the + second - so a query about alpha ranks every alpha chunk at exactly 1.0 and + every other chunk at exactly 0.0, making rankings deterministic without + relying on hash collisions. + """ + + def __init__(self, dim: int = 8) -> None: + self.dim = dim + self.v_alpha = np.zeros(dim, dtype=np.float32) + self.v_alpha[0] = 1.0 + self.v_beta = np.zeros(dim, dtype=np.float32) + self.v_beta[1] = 1.0 + + def embed_batch(self, texts: list[str]) -> np.ndarray: + return np.vstack( + [self.v_alpha if "alpha" in t.lower() else self.v_beta for t in texts] + ) + + +class TestRetrieveDocIds: + def test_self_query_ranks_own_doc_first(self, synthetic_dataset): + result = build_index(synthetic_dataset, MarkerEmbedder()) + alpha_text = next(d.text for d in synthetic_dataset.docs if d.doc_id == "alpha") + + doc_ids = retrieve_doc_ids(result.store, MarkerEmbedder(), alpha_text, top_k=3) + + assert isinstance(doc_ids, tuple) + assert doc_ids[0] == "alpha" + + def test_repeats_are_preserved_in_the_raw_list(self, synthetic_dataset): + """Two beta chunks both score 1.0 for a beta query - both occupy slots.""" + result = build_index(synthetic_dataset, MarkerEmbedder()) + assert result.chunks_per_doc["beta"] >= 2 + + doc_ids = retrieve_doc_ids(result.store, MarkerEmbedder(), "BETA?", top_k=2) + + assert doc_ids == ("beta", "beta") + + def test_top_k_larger_than_store_returns_every_chunk(self, synthetic_dataset): + result = build_index(synthetic_dataset, FakeEmbedder()) + + doc_ids = retrieve_doc_ids(result.store, FakeEmbedder(), "anything", top_k=100) + + assert len(doc_ids) == result.num_chunks + + def test_non_positive_top_k_raises(self, synthetic_dataset): + result = build_index(synthetic_dataset, FakeEmbedder()) + with pytest.raises(ValueError, match="top_k must be positive"): + retrieve_doc_ids(result.store, FakeEmbedder(), "q", top_k=0) + + def test_wrong_dimension_embedder_raises(self, synthetic_dataset): + result = build_index(synthetic_dataset, MarkerEmbedder(dim=8)) + with pytest.raises(ValueError, match="shape"): + retrieve_doc_ids(result.store, MarkerEmbedder(dim=7), "q", top_k=2) + + +class TestRunRetrieval: + def test_one_result_per_question_in_dataset_order(self, synthetic_dataset): + result = build_index(synthetic_dataset, FakeEmbedder()) + + results = run_retrieval( + synthetic_dataset, result.store, FakeEmbedder(), top_k=3 + ) + + assert [r.question_id for r in results] == [q.id for q in synthetic_dataset.questions] + assert all(len(r.retrieved_doc_ids) <= 3 for r in results) + assert results[0].relevant_doc_ids == ("alpha",) + + def test_results_are_scoreable_and_perfect_for_marker_query(self, synthetic_dataset): + result = build_index(synthetic_dataset, MarkerEmbedder()) + + # The fixture question is about alpha; the marker embedder puts every + # alpha chunk at rank 1 with score 1.0. + results = run_retrieval( + synthetic_dataset, result.store, MarkerEmbedder(), top_k=4 + ) + summary = summarize(results, k=1) + + assert results[0].recall_at(1) == 1.0 + assert results[0].hit_at(1) is True + assert summary.mrr == pytest.approx(1.0) + assert summary.mean_recall_at_k == pytest.approx(1.0) + + def test_top_k_defaults_to_production_setting(self, synthetic_dataset, set_setting): + result = build_index(synthetic_dataset, FakeEmbedder()) + assert result.num_chunks >= 3 + set_setting("rag_top_k", 2) + + results = run_retrieval(synthetic_dataset, result.store, FakeEmbedder()) + + # No explicit top_k: the production setting (2) must be what was used. + assert all(len(r.retrieved_doc_ids) == 2 for r in results) + + def test_explicit_top_k_overrides_setting(self, synthetic_dataset, set_setting): + result = build_index(synthetic_dataset, FakeEmbedder()) + set_setting("rag_top_k", 1) + + results = run_retrieval( + synthetic_dataset, result.store, FakeEmbedder(), top_k=3 + ) + + assert all(len(r.retrieved_doc_ids) == 3 for r in results) + + def test_empty_dataset_raises(self): + from app.services.rag.vector_store import VectorStore + + with pytest.raises(ValueError, match="no questions"): + run_retrieval(EvalDataset(docs=[], questions=[]), VectorStore(8), FakeEmbedder()) + + +class TestCommittedCorpus: + def test_runs_every_committed_question(self): + dataset = load_dataset() + result = build_index(dataset, FakeEmbedder()) + + results = run_retrieval( + dataset, result.store, FakeEmbedder(), top_k=settings.rag_top_k + ) + + assert len(results) == 48 + by_id = {r.question_id: r for r in results} + for question in dataset.questions: + retrieved = by_id[question.id] + assert retrieved.relevant_doc_ids == tuple(question.source_docs) + assert 1 <= len(retrieved.retrieved_doc_ids) <= settings.rag_top_k + From 76774320fe0633fb987fd9fe744e755a68537f74 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 18:09:59 +0200 Subject: [PATCH 20/48] Item 22: evaluate the RAG service in the eval --- evals/runner.py | 56 ++++++++++++++++++- tests/fakes.py | 52 +++++++++++++++++ tests/test_eval_service.py | 112 +++++++++++++++++++++++++++++++++++++ 3 files changed, 218 insertions(+), 2 deletions(-) create mode 100644 tests/test_eval_service.py diff --git a/evals/runner.py b/evals/runner.py index 035c611..968d5cb 100644 --- a/evals/runner.py +++ b/evals/runner.py @@ -1,9 +1,11 @@ -"""Retrieval runner for the RAG evaluation (portfolio item 21). +"""Retrieval runner for the RAG evaluation (portfolio items 21-22). Runs every question in an ``EvalDataset`` through a built index and produces one scored-ready ``QuestionResult`` per question. The embedder is injected so tests can use a deterministic fake; the CLI passes the real -``EmbeddingClient``. +``EmbeddingClient``. Item 22 adds the same run against a live ``RAGService``, +so an eval can measure the production pipeline (its chunking defaults and +query path) instead of a bare store + embedder pair. """ from __future__ import annotations @@ -11,6 +13,7 @@ import numpy as np from app.core.config import settings +from app.services.rag.service import RAGService from app.services.rag.vector_store import VectorStore from evals.dataset import EvalDataset from evals.index import BatchEmbedder @@ -69,3 +72,52 @@ def run_retrieval( ) ) return results + + +def index_dataset(service: RAGService, dataset: EvalDataset) -> int: + """Index every corpus document into *service* through its production path. + + Uses ``add_document`` with the service's own chunking defaults so the eval + measures exactly what the app indexes. Returns the total number of chunks + stored (0 for documents whose content was already current). + """ + total = 0 + for doc in dataset.docs: + total += service.add_document( + doc.text, {"doc_id": doc.doc_id, "filename": doc.title} + ) + return total + + +def run_retrieval_on_service( + dataset: EvalDataset, + service: RAGService, + *, + top_k: int | None = None, +) -> list[QuestionResult]: + """Run every question through the real ``RAGService.query``. + + Same contract as :func:`run_retrieval` (dataset order, raw chunk ranks, + ground truth from ``source_docs``), but retrieval goes through the + production service instead of a bare store + embedder pair. An empty index + yields empty retrievals rather than an error, mirroring the app. + Raises: + ValueError: if the dataset has no questions. + """ + if top_k is None: + top_k = settings.rag_top_k + if not dataset.questions: + raise ValueError("dataset has no questions to run") + + results: list[QuestionResult] = [] + for question in dataset.questions: + hits = service.query(question.question, top_k=top_k) + retrieved = tuple(hit.doc_id for hit in hits) + results.append( + QuestionResult( + question_id=question.id, + retrieved_doc_ids=retrieved, + relevant_doc_ids=tuple(question.source_docs), + ) + ) + return results diff --git a/tests/fakes.py b/tests/fakes.py index 4125e63..b85ca94 100644 --- a/tests/fakes.py +++ b/tests/fakes.py @@ -30,3 +30,55 @@ def __init__(self, dim: int = 16) -> None: def embed_batch(self, texts: list[str]) -> np.ndarray: self.calls.append(list(texts)) return np.vstack([unit_vector(t, self.dim) for t in texts]).astype(np.float32) + + +class FakeServiceEmbedder(FakeEmbedder): + """``FakeEmbedder`` shaped like ``EmbeddingClient`` for ``RAGService``. + + Adds the attributes the service reads (``model``, ``backend``, + ``dimension``, single-text ``embed``); vectors are the same deterministic + sha256-seeded unit vectors, so rankings match what a bare store would give. + """ + + model = "fake-embed" + backend = "fake" + + @property + def dimension(self) -> int: + return self.dim + + def embed(self, text: str) -> np.ndarray: + return self.embed_batch([text])[0] + + +class MarkerServiceEmbedder: + """Two orthogonal basis vectors shaped like ``EmbeddingClient``. + + Text mentioning "alpha" gets the first basis vector, everything else the + second - so a query about alpha ranks every alpha chunk at exactly 1.0 and + every other chunk at exactly 0.0 (same marker rule as the store-level + ``MarkerEmbedder`` in ``tests/test_eval_runner.py``, plus the attributes + ``RAGService`` reads). + """ + + model = "marker-embed" + backend = "fake" + + def __init__(self, dim: int = 8) -> None: + self.dim = dim + self.v_alpha = np.zeros(dim, dtype=np.float32) + self.v_alpha[0] = 1.0 + self.v_beta = np.zeros(dim, dtype=np.float32) + self.v_beta[1] = 1.0 + + @property + def dimension(self) -> int: + return self.dim + + def embed(self, text: str) -> np.ndarray: + return self.embed_batch([text])[0] + + def embed_batch(self, texts: list[str]) -> np.ndarray: + return np.vstack( + [self.v_alpha if "alpha" in t.lower() else self.v_beta for t in texts] + ) diff --git a/tests/test_eval_service.py b/tests/test_eval_service.py new file mode 100644 index 0000000..59ef789 --- /dev/null +++ b/tests/test_eval_service.py @@ -0,0 +1,112 @@ +"""Service-level eval tests (portfolio item 22). + +``index_dataset`` and ``run_retrieval_on_service`` measure the production +``RAGService`` end to end - its chunking defaults, incremental indexing and +query path - using deterministic fakes shaped like ``EmbeddingClient``. +""" + +from __future__ import annotations + +import pytest + +from app.core.config import settings +from app.services.rag.service import RAGService +from evals.dataset import EvalDataset, load_dataset +from evals.metrics import summarize +from evals.runner import index_dataset, run_retrieval_on_service +from tests.fakes import FakeServiceEmbedder, MarkerServiceEmbedder + + +@pytest.fixture +def service(tmp_path): + """RAGService wired to temp persistence and the deterministic fake client.""" + return RAGService( + embedding_client=FakeServiceEmbedder(), persist_dir=str(tmp_path / "rag") + ) + + +class TestIndexDataset: + def test_stores_every_document(self, service, synthetic_dataset): + total = index_dataset(service, synthetic_dataset) + + assert total > 0 + assert total == service.chunk_count + assert set(service.document_versions()) == synthetic_dataset.doc_ids + + def test_is_incremental_on_unchanged_content(self, service, synthetic_dataset): + first = index_dataset(service, synthetic_dataset) + second = index_dataset(service, synthetic_dataset) + + assert first > 0 + assert second == 0 + assert service.chunk_count == first + + +class TestRunRetrievalOnService: + def test_one_result_per_question_in_dataset_order(self, service, synthetic_dataset): + index_dataset(service, synthetic_dataset) + + results = run_retrieval_on_service(synthetic_dataset, service, top_k=3) + + assert [r.question_id for r in results] == [q.id for q in synthetic_dataset.questions] + assert all(len(r.retrieved_doc_ids) <= 3 for r in results) + assert results[0].relevant_doc_ids == ("alpha",) + + def test_marker_query_scores_perfectly_through_the_service(self, tmp_path, synthetic_dataset): + """The fixture question is about alpha; every alpha chunk ranks at 1.0.""" + service = RAGService( + embedding_client=MarkerServiceEmbedder(), persist_dir=str(tmp_path / "rag") + ) + index_dataset(service, synthetic_dataset) + + results = run_retrieval_on_service(synthetic_dataset, service, top_k=4) + summary = summarize(results, k=1) + + assert results[0].recall_at(1) == 1.0 + assert results[0].hit_at(1) is True + assert summary.mrr == pytest.approx(1.0) + assert summary.mean_recall_at_k == pytest.approx(1.0) + + def test_top_k_defaults_to_production_setting(self, service, synthetic_dataset, set_setting): + index_dataset(service, synthetic_dataset) + assert service.chunk_count >= 2 + set_setting("rag_top_k", 2) + + results = run_retrieval_on_service(synthetic_dataset, service) + + assert all(len(r.retrieved_doc_ids) == 2 for r in results) + + def test_explicit_top_k_overrides_setting(self, service, synthetic_dataset, set_setting): + index_dataset(service, synthetic_dataset) + set_setting("rag_top_k", 1) + + results = run_retrieval_on_service(synthetic_dataset, service, top_k=3) + + assert all(len(r.retrieved_doc_ids) == 3 for r in results) + + def test_empty_index_yields_empty_retrievals(self, service, synthetic_dataset): + results = run_retrieval_on_service(synthetic_dataset, service, top_k=2) + + assert all(r.retrieved_doc_ids == () for r in results) + + def test_empty_dataset_raises(self, service): + with pytest.raises(ValueError, match="no questions"): + run_retrieval_on_service(EvalDataset(docs=[], questions=[]), service) + + +class TestCommittedCorpus: + def test_runs_every_committed_question_through_the_service(self, tmp_path): + dataset = load_dataset() + service = RAGService( + embedding_client=FakeServiceEmbedder(), persist_dir=str(tmp_path / "rag") + ) + index_dataset(service, dataset) + + results = run_retrieval_on_service(dataset, service) + + assert len(results) == 48 + by_id = {r.question_id: r for r in results} + for question in dataset.questions: + retrieved = by_id[question.id] + assert retrieved.relevant_doc_ids == tuple(question.source_docs) + assert 1 <= len(retrieved.retrieved_doc_ids) <= settings.rag_top_k From 70af68513d965d4904f0bd76c9aa0d70d1eef2b0 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 18:11:44 +0200 Subject: [PATCH 21/48] Item 23: report generation for the RAG eval --- evals/report.py | 77 ++++++++++++++++++++++++++++ tests/test_eval_report.py | 104 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 181 insertions(+) create mode 100644 evals/report.py create mode 100644 tests/test_eval_report.py diff --git a/evals/report.py b/evals/report.py new file mode 100644 index 0000000..ecc68a6 --- /dev/null +++ b/evals/report.py @@ -0,0 +1,77 @@ +"""Report generation for the RAG evaluation (portfolio item 23). + +Turns a list of ``QuestionResult`` into a JSON-serializable report: one +aggregate summary plus every question's retrieval and per-question metrics. +The output is deterministic - no timestamps, floats rounded to four decimals - +so committed reports diff cleanly and the CI regression gate (item 37) can +compare them field by field. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from app.core.config import settings +from evals.metrics import QuestionResult, summarize + + +def _round(value: float) -> float: + return round(float(value), 4) + + +def build_report( + results: list[QuestionResult], + *, + k: int | None = None, + config: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Build a JSON-serializable report from *results*. + + ``k`` is the cutoff used for recall/hit-rate and defaults to the production + setting (``rag_top_k``), matching what the runner retrieves. ``config`` is + echoed verbatim into the report so each file records how it was produced + (embedder model, chunking parameters, ...). Raises ``ValueError`` when + there are no results or *k* is non-positive. + """ + if k is None: + k = settings.rag_top_k + summary = summarize(results, k=k) + + questions = [ + { + "id": result.question_id, + "retrieved_doc_ids": list(result.retrieved_doc_ids), + "relevant_doc_ids": list(result.relevant_doc_ids), + "recall_at_k": _round(result.recall_at(k)), + "reciprocal_rank": _round(result.reciprocal_rank()), + "hit_at_k": result.hit_at(k), + } + for result in results + ] + return { + "schema_version": 1, + "config": dict(config or {}), + "summary": { + "num_questions": summary.num_questions, + "k": k, + "mean_recall_at_k": _round(summary.mean_recall_at_k), + "mrr": _round(summary.mrr), + "hit_rate_at_k": _round(summary.hit_rate_at_k), + }, + "questions": questions, + } + + +def write_report(report: dict[str, Any], path: Path | str) -> Path: + """Write *report* as pretty-printed JSON to *path*, creating parent dirs. + + Returns the resolved path so callers can report where the file landed. + """ + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text( + json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) + return target.resolve() diff --git a/tests/test_eval_report.py b/tests/test_eval_report.py new file mode 100644 index 0000000..95783c1 --- /dev/null +++ b/tests/test_eval_report.py @@ -0,0 +1,104 @@ +"""Report generation tests (portfolio item 23).""" + +from __future__ import annotations + +import json + +import pytest + +from app.core.config import settings +from evals.metrics import QuestionResult, summarize +from evals.report import build_report, write_report + + +def _results() -> list[QuestionResult]: + return [ + # alpha is rank 2 of the top-3: recall@3 = 1/2, rr = 0.5, hit True + QuestionResult( + question_id="q1", + retrieved_doc_ids=("gamma", "alpha", "delta"), + relevant_doc_ids=("alpha", "beta"), + ), + # nothing relevant at all: recall 0, rr 0, no hit + QuestionResult( + question_id="q2", + retrieved_doc_ids=("epsilon", "zeta"), + relevant_doc_ids=("theta",), + ), + ] + + +class TestBuildReport: + def test_summary_matches_summarize(self): + report = build_report(_results(), k=3) + + expected = summarize(_results(), k=3) + assert report["summary"]["num_questions"] == 2 + assert report["summary"]["k"] == 3 + assert report["summary"]["mean_recall_at_k"] == pytest.approx( + round(expected.mean_recall_at_k, 4), abs=1e-9 + ) + assert report["summary"]["mrr"] == pytest.approx(round(expected.mrr, 4), abs=1e-9) + assert report["summary"]["hit_rate_at_k"] == pytest.approx( + round(expected.hit_rate_at_k, 4), abs=1e-9 + ) + + def test_per_question_metrics_and_order(self): + report = build_report(_results(), k=3) + + questions = report["questions"] + assert [q["id"] for q in questions] == ["q1", "q2"] + first, second = questions + assert first["retrieved_doc_ids"] == ["gamma", "alpha", "delta"] + assert first["relevant_doc_ids"] == ["alpha", "beta"] + assert first["recall_at_k"] == pytest.approx(0.5) + assert first["reciprocal_rank"] == pytest.approx(0.5) + assert first["hit_at_k"] is True + assert second["recall_at_k"] == 0.0 + assert second["reciprocal_rank"] == 0.0 + assert second["hit_at_k"] is False + + def test_k_defaults_to_production_setting(self, set_setting): + set_setting("rag_top_k", 2) + + report = build_report(_results()) + + assert report["summary"]["k"] == settings.rag_top_k == 2 + + def test_config_is_echoed_verbatim(self): + config = {"embedder": "fake-embed", "chunk_size": 800, "overlap": 150} + + report = build_report(_results(), k=3, config=config) + + assert report["config"] == config + + def test_output_is_deterministic(self): + first = build_report(_results(), k=3) + second = build_report(_results(), k=3) + + assert json.dumps(first, sort_keys=True) == json.dumps(second, sort_keys=True) + + def test_empty_results_raise(self): + with pytest.raises(ValueError, match="zero question results"): + build_report([], k=3) + + +class TestWriteReport: + def test_writes_valid_json_with_trailing_newline(self, tmp_path): + target = tmp_path / "reports" / "nested" / "run.json" + + written = write_report(build_report(_results(), k=3), target) + + assert written == target.resolve() + text = target.read_text(encoding="utf-8") + assert text.endswith("\n") + loaded = json.loads(text) + assert loaded["summary"]["num_questions"] == 2 + + def test_round_trip_preserves_content(self, tmp_path): + report = build_report(_results(), k=3, config={"embedder": "fake"}) + target = tmp_path / "run.json" + + write_report(report, target) + + assert json.loads(target.read_text(encoding="utf-8")) == report From 7249591adf254c00ba3c32ad9b92632558ff3976 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 18:16:29 +0200 Subject: [PATCH 22/48] Item 24: command-line entry point for the RAG eval --- evals/cli.py | 116 +++++++++++++++++++++++++++++++++++++++++ tests/test_eval_cli.py | 108 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 224 insertions(+) create mode 100644 evals/cli.py create mode 100644 tests/test_eval_cli.py diff --git a/evals/cli.py b/evals/cli.py new file mode 100644 index 0000000..7b8f4c6 --- /dev/null +++ b/evals/cli.py @@ -0,0 +1,116 @@ +"""Command-line entry point for the RAG evaluation (portfolio item 24). + +Runs the committed corpus and question set through retrieval and writes a JSON +report (item 23). Two modes: + +* index mode (default): build an in-memory index with ``build_index``; the + chunking parameters can be overridden on the command line. +* service mode (``--service``): index into a real ``RAGService`` and query it, + measuring the production pipeline end to end. The service uses a temporary + persist dir - an eval never touches ``DATA_DIR``. + +Usage: + python -m evals.cli [--top-k N] [--chunk-size N] [--overlap N] + [--out PATH] [--service] +""" + +from __future__ import annotations + +import argparse +import shutil +import sys +import tempfile +from pathlib import Path +from typing import Any + +from app.core.config import settings +from app.services.rag.embeddings import EmbeddingClient +from app.services.rag.service import RAGService +from evals.dataset import DatasetError, load_dataset +from evals.index import build_index +from evals.report import build_report, write_report +from evals.runner import index_dataset, run_retrieval, run_retrieval_on_service + +DEFAULT_REPORT = Path(__file__).resolve().parent / "reports" / "rag_eval.json" + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="python -m evals.cli", + description="Run the RAG retrieval evaluation and write a JSON report.", + ) + parser.add_argument("--top-k", type=int, default=None, + help=f"retrieval cutoff (default: settings.rag_top_k = {settings.rag_top_k})") + parser.add_argument("--chunk-size", type=int, default=None, + help="index mode only; default: settings.rag_chunk_size") + parser.add_argument("--overlap", type=int, default=None, + help="index mode only; default: settings.rag_chunk_overlap") + parser.add_argument("--out", type=Path, default=DEFAULT_REPORT, + help=f"report path (default: {DEFAULT_REPORT})") + parser.add_argument("--service", action="store_true", + help="measure the production RAGService instead of a bare index") + return parser + + +def run(argv: list[str] | None = None, *, client: EmbeddingClient | None = None) -> int: + """Execute one eval run; returns a process exit code (0 on success).""" + args = build_parser().parse_args(argv) + if args.top_k is not None and args.top_k <= 0: + print("error: --top-k must be positive", file=sys.stderr) + return 1 + + client = client or EmbeddingClient() + try: + dataset = load_dataset() + top_k = args.top_k if args.top_k is not None else settings.rag_top_k + config: dict[str, Any] = { + "mode": "service" if args.service else "index", + "embedder_model": client.model, + "top_k": top_k, + "num_docs": len(dataset.docs), + } + + if args.service: + persist_dir = Path(tempfile.mkdtemp(prefix="apollo-eval-")) + try: + service = RAGService(embedding_client=client, persist_dir=str(persist_dir)) + config["num_chunks"] = index_dataset(service, dataset) + results = run_retrieval_on_service(dataset, service, top_k=top_k) + finally: + shutil.rmtree(persist_dir, ignore_errors=True) + else: + chunk_size = args.chunk_size if args.chunk_size is not None else settings.rag_chunk_size + overlap = (args.overlap if args.overlap is not None + else settings.rag_chunk_overlap) + result = build_index(dataset, client, chunk_size=chunk_size, overlap=overlap) + results = run_retrieval(dataset, result.store, client, top_k=top_k) + config["chunk_size"] = chunk_size + config["overlap"] = overlap + config["num_chunks"] = result.num_chunks + + # Read after indexing so the backend probe is free (already embedded). + config["backend"] = client.backend + report = build_report(results, k=top_k, config=config) + path = write_report(report, args.out) + except (DatasetError, ValueError) as exc: + print(f"error: {exc}", file=sys.stderr) + return 1 + + summary = report["summary"] + print( + f"{summary['num_questions']} questions | " + f"recall@{top_k}={summary['mean_recall_at_k']:.3f} " + f"MRR={summary['mrr']:.3f} hit_rate={summary['hit_rate_at_k']:.3f}" + ) + print(f"report: {path}") + return 0 + + +def main( + argv: list[str] | None = None, *, client: EmbeddingClient | None = None +) -> int: + return run(argv, client=client) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_eval_cli.py b/tests/test_eval_cli.py new file mode 100644 index 0000000..bbaef15 --- /dev/null +++ b/tests/test_eval_cli.py @@ -0,0 +1,108 @@ +"""CLI entry-point tests (portfolio item 24). + +The embedder client is injected so these run without Ollama; the real +``EmbeddingClient`` is only constructed by ``main`` in production runs. +""" + +from __future__ import annotations + +import json + +import pytest + +from app.core.config import settings +from evals.cli import build_parser, main, run +from tests.fakes import FakeServiceEmbedder + + +@pytest.fixture(autouse=True) +def _fake_client(): + return FakeServiceEmbedder() + + +class TestParser: + def test_defaults(self): + args = build_parser().parse_args([]) + + assert args.top_k is None + assert args.chunk_size is None + assert args.overlap is None + assert args.service is False + assert str(args.out).endswith("rag_eval.json") + + def test_flags(self, tmp_path): + out = tmp_path / "r.json" + args = build_parser().parse_args( + ["--top-k", "7", "--chunk-size", "500", "--overlap", "90", "--out", str(out), "--service"] + ) + + assert (args.top_k, args.chunk_size, args.overlap) == (7, 500, 90) + assert args.service is True + assert args.out == out + + +class TestRun: + def test_index_mode_writes_report(self, _fake_client, tmp_path): + out = tmp_path / "reports" / "index.json" + + code = run(["--top-k", "3", "--out", str(out)], client=_fake_client) + + assert code == 0 + report = json.loads(out.read_text(encoding="utf-8")) + assert report["config"]["mode"] == "index" + assert report["config"]["embedder_model"] == "fake-embed" + assert report["config"]["backend"] == "fake" + assert report["summary"]["num_questions"] == 48 + assert report["summary"]["k"] == 3 + + def test_service_mode_writes_report(self, _fake_client, tmp_path): + out = tmp_path / "service.json" + + code = run(["--top-k", "2", "--out", str(out), "--service"], client=_fake_client) + + assert code == 0 + report = json.loads(out.read_text(encoding="utf-8")) + assert report["config"]["mode"] == "service" + assert report["summary"]["num_questions"] == 48 + # service mode uses the production chunking defaults, not CLI overrides + assert "chunk_size" not in report["config"] + + def test_chunk_overrides_are_recorded(self, _fake_client, tmp_path): + out = tmp_path / "chunks.json" + + code = run( + ["--top-k", "2", "--chunk-size", "500", "--overlap", "90", "--out", str(out)], + client=_fake_client, + ) + + assert code == 0 + config = json.loads(out.read_text(encoding="utf-8"))["config"] + assert (config["chunk_size"], config["overlap"]) == (500, 90) + + def test_top_k_defaults_to_production_setting(self, _fake_client, tmp_path, set_setting): + out = tmp_path / "default.json" + set_setting("rag_top_k", 2) + + code = run(["--out", str(out)], client=_fake_client) + + assert code == 0 + report = json.loads(out.read_text(encoding="utf-8")) + assert report["summary"]["k"] == settings.rag_top_k == 2 + + def test_invalid_top_k_fails_cleanly(self, _fake_client, tmp_path): + out = tmp_path / "bad.json" + + code = run(["--top-k", "0", "--out", str(out)], client=_fake_client) + + assert code == 1 + assert not out.exists() + + +class TestMain: + def test_main_returns_run_code(self, _fake_client, tmp_path): + out = tmp_path / "main.json" + + code = main(["--top-k", "2", "--out", str(out)], client=_fake_client) + + assert code == 0 + assert json.loads(out.read_text(encoding="utf-8"))["summary"]["num_questions"] == 48 From a3db5c636989bd8f54b9394e59ef5c6709ae627c Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 18:21:03 +0200 Subject: [PATCH 23/48] Item 25: record actual embedding backend/model in eval reports --- evals/cli.py | 5 ++++- tests/test_eval_cli.py | 20 +++++++++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/evals/cli.py b/evals/cli.py index 7b8f4c6..9de3995 100644 --- a/evals/cli.py +++ b/evals/cli.py @@ -89,7 +89,10 @@ def run(argv: list[str] | None = None, *, client: EmbeddingClient | None = None) config["num_chunks"] = result.num_chunks # Read after indexing so the backend probe is free (already embedded). - config["backend"] = client.backend + config["embedding_backend"] = client.backend + if client.backend == "sentence-transformers": + # Ollama was unavailable; record what actually produced the vectors. + config["embedder_model"] = client.fallback_model report = build_report(results, k=top_k, config=config) path = write_report(report, args.out) except (DatasetError, ValueError) as exc: diff --git a/tests/test_eval_cli.py b/tests/test_eval_cli.py index bbaef15..72f7f71 100644 --- a/tests/test_eval_cli.py +++ b/tests/test_eval_cli.py @@ -51,7 +51,7 @@ def test_index_mode_writes_report(self, _fake_client, tmp_path): report = json.loads(out.read_text(encoding="utf-8")) assert report["config"]["mode"] == "index" assert report["config"]["embedder_model"] == "fake-embed" - assert report["config"]["backend"] == "fake" + assert report["config"]["embedding_backend"] == "fake" assert report["summary"]["num_questions"] == 48 assert report["summary"]["k"] == 3 @@ -98,6 +98,24 @@ def test_invalid_top_k_fails_cleanly(self, _fake_client, tmp_path): assert not out.exists() + def test_fallback_backend_records_actual_model(self, tmp_path): + """When Ollama is down and sentence-transformers serves the vectors, the + report must name the model that actually ran.""" + + class FallbackClient(FakeServiceEmbedder): + backend = "sentence-transformers" + fallback_model = "all-MiniLM-L6-v2" + + out = tmp_path / "fallback.json" + + code = run(["--top-k", "3", "--out", str(out)], client=FallbackClient()) + + assert code == 0 + config = json.loads(out.read_text(encoding="utf-8"))["config"] + assert config["embedding_backend"] == "sentence-transformers" + assert config["embedder_model"] == "all-MiniLM-L6-v2" + + class TestMain: def test_main_returns_run_code(self, _fake_client, tmp_path): out = tmp_path / "main.json" From 00c51bbdc2f45354607227dfd15ecfc76644ca02 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 18:24:47 +0200 Subject: [PATCH 24/48] Item 26: chunking grid for the RAG eval --- evals/grid.py | 115 +++++++++++++++++++++++++++++++++++++ tests/test_eval_grid.py | 124 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 239 insertions(+) create mode 100644 evals/grid.py create mode 100644 tests/test_eval_grid.py diff --git a/evals/grid.py b/evals/grid.py new file mode 100644 index 0000000..d87606a --- /dev/null +++ b/evals/grid.py @@ -0,0 +1,115 @@ +"""Chunking-parameter grid search for the RAG evaluation (portfolio item 26). + +Runs the full evaluation once per ``(chunk_size, overlap)`` cell so retrieval +quality can be compared across chunk granularities. Each cell builds its own +index with :func:`evals.index.build_index` and scores every question at a fixed +cutoff; results come back as one row per cell in grid order. Item 27 runs this +live and records the numbers. +""" + +from __future__ import annotations + +import json +from collections.abc import Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +from app.core.config import settings +from evals.dataset import EvalDataset +from evals.index import BatchEmbedder, build_index +from evals.metrics import MetricsSummary, summarize +from evals.runner import run_retrieval + +#: Default grid: production defaults (800/150) plus finer and coarser chunks. +DEFAULT_CHUNKING_GRID: tuple[tuple[int, int], ...] = ( + (400, 75), + (600, 120), + (800, 150), + (1200, 200), +) + + +@dataclass(frozen=True) +class GridCell: + """The evaluated outcome of one chunking configuration.""" + + chunk_size: int + overlap: int + num_chunks: int + summary: MetricsSummary + + def to_dict(self) -> dict[str, Any]: + return { + "chunk_size": self.chunk_size, + "overlap": self.overlap, + "num_chunks": self.num_chunks, + "num_questions": self.summary.num_questions, + "k": self.summary.k, + "mean_recall_at_k": round(self.summary.mean_recall_at_k, 4), + "mrr": round(self.summary.mrr, 4), + "hit_rate_at_k": round(self.summary.hit_rate_at_k, 4), + } + + +def run_grid( + dataset: EvalDataset, + embedder: BatchEmbedder, + *, + grid: Sequence[tuple[int, int]] | None = None, + top_k: int | None = None, +) -> list[GridCell]: + """Evaluate every ``(chunk_size, overlap)`` cell in *grid*. + + Each cell gets a fresh index built with its own chunking parameters and is + scored over the whole question set at cutoff *top_k* (default: the + production setting). Cells are evaluated in grid order; an invalid cell or + a build failure raises before any later cell runs. + Raises: + ValueError: on an empty grid, a non-positive *top_k*, or a cell whose + parameters do not satisfy ``0 <= overlap < chunk_size``. + """ + if grid is None: + grid = DEFAULT_CHUNKING_GRID + if top_k is None: + top_k = settings.rag_top_k + if top_k <= 0: + raise ValueError(f"top_k must be positive, got {top_k}") + if not grid: + raise ValueError("grid has no cells to run") + for chunk_size, overlap in grid: + if chunk_size <= 0 or overlap < 0 or overlap >= chunk_size: + raise ValueError( + f"invalid cell ({chunk_size}, {overlap}): need 0 <= overlap < chunk_size" + ) + + cells: list[GridCell] = [] + for chunk_size, overlap in grid: + built = build_index(dataset, embedder, chunk_size=chunk_size, overlap=overlap) + results = run_retrieval(dataset, built.store, embedder, top_k=top_k) + cells.append( + GridCell(chunk_size, overlap, built.num_chunks, summarize(results, k=top_k)) + ) + return cells + + +def write_grid_report(cells: list[GridCell], path: Path | str, *, top_k: int) -> Path: + """Write the grid results as deterministic JSON (same rules as item 23). + + The file records *top_k* once at the top level and one row per cell in run + order; parent directories are created. Returns the resolved path. + Raises ``ValueError`` when there are no cells to write. + """ + if not cells: + raise ValueError("cannot write a grid report with zero cells") + target = Path(path) + target.parent.mkdir(parents=True, exist_ok=True) + payload = { + "schema_version": 1, + "top_k": top_k, + "cells": [cell.to_dict() for cell in cells], + } + target.write_text( + json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" + ) + return target.resolve() diff --git a/tests/test_eval_grid.py b/tests/test_eval_grid.py new file mode 100644 index 0000000..2c3f394 --- /dev/null +++ b/tests/test_eval_grid.py @@ -0,0 +1,124 @@ +"""Chunking grid tests (portfolio item 26).""" + +from __future__ import annotations + +import json + +import pytest + +from app.core.config import settings +from evals.grid import DEFAULT_CHUNKING_GRID, GridCell, run_grid, write_grid_report +from evals.metrics import MetricsSummary +from tests.fakes import FakeEmbedder + + +class TestRunGrid: + def test_default_grid_returns_one_cell_per_entry_in_order(self, synthetic_dataset): + cells = run_grid(synthetic_dataset, FakeEmbedder(), top_k=3) + + assert len(cells) == len(DEFAULT_CHUNKING_GRID) + assert [(c.chunk_size, c.overlap) for c in cells] == list(DEFAULT_CHUNKING_GRID) + assert all(c.num_chunks > 0 for c in cells) + assert all(c.summary.num_questions == 1 for c in cells) + + def test_production_defaults_are_a_cell(self): + assert (settings.rag_chunk_size, settings.rag_chunk_overlap) in DEFAULT_CHUNKING_GRID + + def test_custom_grid_and_top_k_are_recorded(self, synthetic_dataset): + cells = run_grid( + synthetic_dataset, FakeEmbedder(), grid=[(500, 100), (900, 180)], top_k=2 + ) + + assert [(c.chunk_size, c.overlap) for c in cells] == [(500, 100), (900, 180)] + assert all(c.summary.k == 2 for c in cells) + + def test_top_k_defaults_to_production_setting(self, synthetic_dataset, set_setting): + set_setting("rag_top_k", 4) + + cells = run_grid(synthetic_dataset, FakeEmbedder(), grid=[(800, 150)]) + + assert cells[0].summary.k == settings.rag_top_k == 4 + + def test_invalid_cells_raise(self, synthetic_dataset): + for bad in [(0, 0), (100, -1), (100, 100)]: + with pytest.raises(ValueError, match="invalid cell"): + run_grid(synthetic_dataset, FakeEmbedder(), grid=[bad], top_k=2) + + def test_empty_grid_raises(self, synthetic_dataset): + with pytest.raises(ValueError, match="no cells"): + run_grid(synthetic_dataset, FakeEmbedder(), grid=[], top_k=2) + + def test_non_positive_top_k_raises(self, synthetic_dataset): + with pytest.raises(ValueError, match="top_k must be positive"): + run_grid(synthetic_dataset, FakeEmbedder(), grid=[(800, 150)], top_k=0) + + +class TestGridCell: + def test_to_dict_has_all_fields_with_rounded_metrics(self): + cell = GridCell( + chunk_size=800, + overlap=150, + num_chunks=7, + summary=MetricsSummary( + num_questions=3, k=5, mean_recall_at_k=0.987654, mrr=0.5, hit_rate_at_k=1.0 + ), + ) + + assert cell.to_dict() == { + "chunk_size": 800, + "overlap": 150, + "num_chunks": 7, + "num_questions": 3, + "k": 5, + "mean_recall_at_k": 0.9877, + "mrr": 0.5, + "hit_rate_at_k": 1.0, + } + + +class TestWriteGridReport: + def test_writes_valid_json_in_cell_order(self, tmp_path): + cells = [ + GridCell(400, 75, 9, _summary()), + GridCell(800, 150, 6, _summary()), + ] + + written = write_grid_report(cells, tmp_path / "grid" / "run.json", top_k=5) + + assert written == (tmp_path / "grid" / "run.json").resolve() + payload = json.loads(written.read_text(encoding="utf-8")) + assert payload["schema_version"] == 1 + assert payload["top_k"] == 5 + assert [c["chunk_size"] for c in payload["cells"]] == [400, 800] + + def test_round_trip_matches_to_dict(self, tmp_path): + cells = run_grid(_dataset(), FakeEmbedder(), grid=[(600, 120)], top_k=3) + target = tmp_path / "grid.json" + + write_grid_report(cells, target, top_k=3) + + payload = json.loads(target.read_text(encoding="utf-8")) + assert payload["cells"] == [cell.to_dict() for cell in cells] + + def test_empty_cells_raise(self, tmp_path): + with pytest.raises(ValueError, match="zero cells"): + write_grid_report([], tmp_path / "grid.json", top_k=5) + + +def _summary(): + return MetricsSummary( + num_questions=1, k=3, mean_recall_at_k=0.75, mrr=0.5, hit_rate_at_k=1.0 + ) + + +def _dataset(): + """A minimal two-doc dataset so the round-trip test is self-contained.""" + from evals.dataset import CorpusDoc, EvalDataset, Question + + return EvalDataset( + docs=( + CorpusDoc(doc_id="a", title="A", text="alpha " * 60), + CorpusDoc(doc_id="b", title="B", text="beta " * 120), + ), + questions=(Question(id="q1", question="what is alpha?", source_docs=("a",), key_facts=()),), + ) From d76652d7bb1f76611f35dbbcd20b7d7f82fbca61 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 18:31:35 +0200 Subject: [PATCH 25/48] Item 27 (prep): --grid mode on the eval command --- evals/cli.py | 48 +++++++++++++++++++++++++++++++----------- evals/grid.py | 19 ++++++++++------- tests/test_eval_cli.py | 22 +++++++++++++++++++ 3 files changed, 69 insertions(+), 20 deletions(-) diff --git a/evals/cli.py b/evals/cli.py index 9de3995..7b5d1ee 100644 --- a/evals/cli.py +++ b/evals/cli.py @@ -1,17 +1,19 @@ """Command-line entry point for the RAG evaluation (portfolio item 24). Runs the committed corpus and question set through retrieval and writes a JSON -report (item 23). Two modes: +report (item 23). Three modes: * index mode (default): build an in-memory index with ``build_index``; the chunking parameters can be overridden on the command line. * service mode (``--service``): index into a real ``RAGService`` and query it, measuring the production pipeline end to end. The service uses a temporary persist dir - an eval never touches ``DATA_DIR``. +* grid mode (``--grid``, item 27): run every cell of the chunking grid and + write one row per cell. Usage: python -m evals.cli [--top-k N] [--chunk-size N] [--overlap N] - [--out PATH] [--service] + [--out PATH] [--service | --grid] """ from __future__ import annotations @@ -27,6 +29,7 @@ from app.services.rag.embeddings import EmbeddingClient from app.services.rag.service import RAGService from evals.dataset import DatasetError, load_dataset +from evals.grid import DEFAULT_CHUNKING_GRID, run_grid, write_grid_report from evals.index import build_index from evals.report import build_report, write_report from evals.runner import index_dataset, run_retrieval, run_retrieval_on_service @@ -49,6 +52,9 @@ def build_parser() -> argparse.ArgumentParser: help=f"report path (default: {DEFAULT_REPORT})") parser.add_argument("--service", action="store_true", help="measure the production RAGService instead of a bare index") + parser.add_argument("--grid", action="store_true", + help=f"run every cell of the chunking grid " + f"(default: {DEFAULT_CHUNKING_GRID}) and write one row per cell") return parser @@ -58,19 +64,26 @@ def run(argv: list[str] | None = None, *, client: EmbeddingClient | None = None) if args.top_k is not None and args.top_k <= 0: print("error: --top-k must be positive", file=sys.stderr) return 1 + if args.grid and (args.service or args.chunk_size is not None or args.overlap is not None): + print("error: --grid cannot be combined with --service, --chunk-size or --overlap", + file=sys.stderr) + return 1 client = client or EmbeddingClient() try: dataset = load_dataset() top_k = args.top_k if args.top_k is not None else settings.rag_top_k + mode = "grid" if args.grid else ("service" if args.service else "index") config: dict[str, Any] = { - "mode": "service" if args.service else "index", + "mode": mode, "embedder_model": client.model, "top_k": top_k, "num_docs": len(dataset.docs), } - if args.service: + if args.grid: + cells = run_grid(dataset, client, top_k=top_k) + elif args.service: persist_dir = Path(tempfile.mkdtemp(prefix="apollo-eval-")) try: service = RAGService(embedding_client=client, persist_dir=str(persist_dir)) @@ -93,18 +106,29 @@ def run(argv: list[str] | None = None, *, client: EmbeddingClient | None = None) if client.backend == "sentence-transformers": # Ollama was unavailable; record what actually produced the vectors. config["embedder_model"] = client.fallback_model - report = build_report(results, k=top_k, config=config) - path = write_report(report, args.out) + + if args.grid: + path = write_grid_report(cells, args.out, top_k=top_k, config=config) + for cell in cells: + s = cell.summary + print( + f"{cell.chunk_size}/{cell.overlap} -> {cell.num_chunks} chunks | " + f"recall@{top_k}={s.mean_recall_at_k:.3f} MRR={s.mrr:.3f} " + f"hit_rate={s.hit_rate_at_k:.3f}" + ) + else: + report = build_report(results, k=top_k, config=config) + path = write_report(report, args.out) + summary = report["summary"] + print( + f"{summary['num_questions']} questions | " + f"recall@{top_k}={summary['mean_recall_at_k']:.3f} " + f"MRR={summary['mrr']:.3f} hit_rate={summary['hit_rate_at_k']:.3f}" + ) except (DatasetError, ValueError) as exc: print(f"error: {exc}", file=sys.stderr) return 1 - summary = report["summary"] - print( - f"{summary['num_questions']} questions | " - f"recall@{top_k}={summary['mean_recall_at_k']:.3f} " - f"MRR={summary['mrr']:.3f} hit_rate={summary['hit_rate_at_k']:.3f}" - ) print(f"report: {path}") return 0 diff --git a/evals/grid.py b/evals/grid.py index d87606a..9c8625a 100644 --- a/evals/grid.py +++ b/evals/grid.py @@ -93,22 +93,25 @@ def run_grid( return cells -def write_grid_report(cells: list[GridCell], path: Path | str, *, top_k: int) -> Path: +def write_grid_report( + cells: list[GridCell], path: Path | str, *, top_k: int, config: dict[str, Any] | None = None +) -> Path: """Write the grid results as deterministic JSON (same rules as item 23). - The file records *top_k* once at the top level and one row per cell in run - order; parent directories are created. Returns the resolved path. + The file records *top_k* once at the top level, an optional echoed *config* + block (embedder backend/model, ...), and one row per cell in run order; + parent directories are created. Returns the resolved path. Raises ``ValueError`` when there are no cells to write. """ if not cells: raise ValueError("cannot write a grid report with zero cells") target = Path(path) target.parent.mkdir(parents=True, exist_ok=True) - payload = { - "schema_version": 1, - "top_k": top_k, - "cells": [cell.to_dict() for cell in cells], - } + payload: dict[str, Any] = {"schema_version": 1} + if config is not None: + payload["config"] = dict(config) + payload["top_k"] = top_k + payload["cells"] = [cell.to_dict() for cell in cells] target.write_text( json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" ) diff --git a/tests/test_eval_cli.py b/tests/test_eval_cli.py index 72f7f71..a051732 100644 --- a/tests/test_eval_cli.py +++ b/tests/test_eval_cli.py @@ -28,6 +28,7 @@ def test_defaults(self): assert args.chunk_size is None assert args.overlap is None assert args.service is False + assert args.grid is False assert str(args.out).endswith("rag_eval.json") def test_flags(self, tmp_path): @@ -116,6 +117,27 @@ class FallbackClient(FakeServiceEmbedder): assert config["embedder_model"] == "all-MiniLM-L6-v2" + def test_grid_mode_writes_one_row_per_cell(self, _fake_client, tmp_path): + out = tmp_path / "grid.json" + + code = run(["--top-k", "3", "--out", str(out), "--grid"], client=_fake_client) + + assert code == 0 + report = json.loads(out.read_text(encoding="utf-8")) + assert report["config"]["mode"] == "grid" + assert report["top_k"] == 3 + assert [c["chunk_size"] for c in report["cells"]] == [400, 600, 800, 1200] + assert all(c["num_questions"] == 48 and c["k"] == 3 for c in report["cells"]) + + def test_grid_rejects_combined_flags(self, _fake_client, tmp_path): + out = tmp_path / "bad.json" + + code = run(["--grid", "--service", "--out", str(out)], client=_fake_client) + + assert code == 1 + assert not out.exists() + + class TestMain: def test_main_returns_run_code(self, _fake_client, tmp_path): out = tmp_path / "main.json" From 769b831cfb4da83ab78bec9f4a148893c311cd2b Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 18:44:51 +0200 Subject: [PATCH 26/48] Item 29: reciprocal rank fusion for hybrid retrieval --- app/services/rag/fusion.py | 60 +++++++++++++++++++++++ tests/test_rag_fusion.py | 99 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 159 insertions(+) create mode 100644 app/services/rag/fusion.py create mode 100644 tests/test_rag_fusion.py diff --git a/app/services/rag/fusion.py b/app/services/rag/fusion.py new file mode 100644 index 0000000..9717f58 --- /dev/null +++ b/app/services/rag/fusion.py @@ -0,0 +1,60 @@ +"""Reciprocal rank fusion for hybrid retrieval (portfolio item 29). + +Fuses the vector and keyword rankings into one. RRF (Cormack et al., 2009) is +used instead of score-level combination because the two scores live on +incompatible scales - cosine similarity in [0, 1] versus unbounded BM25 sums - +and rank fusion needs no calibration or per-corpus tuning. + +The function operates on opaque item ids (chunk identity strings), not chunk +objects, so it stays pure and trivially testable; the caller maps ids back to +chunks afterwards. +""" + +from __future__ import annotations + +from collections.abc import Sequence + + +def reciprocal_rank_fuse( + rankings: Sequence[Sequence[str]], + *, + k: int = 60, + top_k: int | None = None, +) -> list[tuple[str, float]]: + """Fuse ranked id lists into a single ranking. + + Each item's score is the sum of ``1 / (k + rank)`` over every ranking that + contains it, with 1-based ranks. Items absent from a ranking contribute + nothing for that ranking - so an item found by both retrievers always + outranks one found by only one at comparable depth. + + Args: + rankings: One ranked id list per retriever (e.g. vector then keyword). + Duplicates inside a single list count once, at the first position. + k: Smoothing constant; 60 is the value from the original paper and the + standard default in practice. + top_k: Optional truncation of the fused result. + + Returns: + ``(item_id, score)`` pairs sorted by score descending. Ties break by + item id ascending, so the output depends only on *which* rankings were + given - not their order (RRF is commutative over its inputs). + """ + if k <= 0: + raise ValueError(f"k must be positive, got {k}") + + scores: dict[str, float] = {} + for ranking in rankings: + seen: set[str] = set() + for rank, item in enumerate(ranking, start=1): + if item in seen: + continue + seen.add(item) + scores[item] = scores.get(item, 0.0) + 1.0 / (k + rank) + + fused = sorted(scores.items(), key=lambda pair: (-pair[1], pair[0])) + if top_k is not None: + if top_k < 0: + raise ValueError(f"top_k must be non-negative, got {top_k}") + fused = fused[:top_k] + return fused diff --git a/tests/test_rag_fusion.py b/tests/test_rag_fusion.py new file mode 100644 index 0000000..4185888 --- /dev/null +++ b/tests/test_rag_fusion.py @@ -0,0 +1,99 @@ +"""Reciprocal rank fusion tests (portfolio item 29). + +RRF scores are hand-computed in these tests against k=60, so a regression in +the formula or the tie-break is caught directly. +""" + +from __future__ import annotations + +import pytest + +from app.services.rag.fusion import reciprocal_rank_fuse + + +class TestBasics: + def test_single_ranking_preserves_order(self): + fused = reciprocal_rank_fuse([["a", "b", "c"]]) + + assert [item for item, _ in fused] == ["a", "b", "c"] + # 1-based ranks with k=60. + assert fused[0][1] == pytest.approx(1 / 61) + assert fused[1][1] == pytest.approx(1 / 62) + assert fused[2][1] == pytest.approx(1 / 63) + + def test_item_in_both_rankings_outranks_single_ranking_items(self): + # "x" appears in both lists (two contributions); the others in one. + fused = reciprocal_rank_fuse([["x", "a"], ["y", "x"]]) + scores = dict(fused) + + assert scores["x"] == pytest.approx(1 / 61 + 1 / 62) + assert fused[0][0] == "x" + + def test_hand_computed_two_ranking_fusion(self): + # a: rank 1 in list 1, rank 3 in list 2 -> 1/61 + 1/63 = 0.032266... + # b: rank 2 in both -> 1/62 + 1/62 = 0.032258... + # d: rank 1 in list 2 -> 1/61; c: rank 3 in list 1 -> 1/63 + fused = reciprocal_rank_fuse([["a", "b", "c"], ["d", "b", "a"]]) + scores = dict(fused) + + assert scores["a"] == pytest.approx(1 / 61 + 1 / 63) + assert scores["b"] == pytest.approx(2 / 62) + # a's rank-1 hit outweighs b's two rank-2 hits by a hair. + assert [item for item, _ in fused] == ["a", "b", "d", "c"] + + def test_items_absent_from_a_ranking_get_no_contribution(self): + fused = reciprocal_rank_fuse([["a"], []]) + + assert dict(fused) == {"a": pytest.approx(1 / 61)} + + +class TestEdgeCases: + def test_empty_input_returns_empty(self): + assert reciprocal_rank_fuse([]) == [] + assert reciprocal_rank_fuse([[], []]) == [] + + def test_duplicates_in_one_ranking_count_once(self): + fused = reciprocal_rank_fuse([["a", "a", "b"]]) + scores = dict(fused) + + # Second "a" at rank 2 must not add a contribution. + assert scores["a"] == pytest.approx(1 / 61) + assert scores["b"] == pytest.approx(1 / 63) + + def test_top_k_truncates(self): + fused = reciprocal_rank_fuse([["a", "b", "c", "d"]], top_k=2) + + assert [item for item, _ in fused] == ["a", "b"] + + def test_negative_top_k_raises(self): + with pytest.raises(ValueError, match="top_k"): + reciprocal_rank_fuse([["a"]], top_k=-1) + + def test_non_positive_k_raises(self): + with pytest.raises(ValueError, match="k must be positive"): + reciprocal_rank_fuse([["a"]], k=0) + + +class TestDeterminism: + def test_ties_break_by_item_id_ascending(self): + # z and a both score 1/61 (rank 1 of their list); m and q both 1/62. + fused = reciprocal_rank_fuse([["z", "m"], ["a", "q"]]) + + assert [item for item, _ in fused] == ["a", "z", "m", "q"] + + def test_independent_of_ranking_order(self): + vector = ["vec1", "vec2", "vec3"] + keyword = ["kw1", "vec1"] + + assert reciprocal_rank_fuse([vector, keyword]) == reciprocal_rank_fuse( + [keyword, vector] + ) + + def test_custom_k_changes_scores_but_not_typical_order(self): + base = reciprocal_rank_fuse([["a", "b"], ["b", "c"]], k=60) + tight = reciprocal_rank_fuse([["a", "b"], ["b", "c"]], k=1) + + assert [item for item, _ in base] == [item for item, _ in tight] + # With k=1 the rank-2 contribution (1/3) is much closer to rank 1 (1/2). + scores_tight = dict(tight) + assert scores_tight["b"] == pytest.approx(1 / 2 + 1 / 3) From bbcd47add1cd37870b148e10dacbdeebca9b2e1a Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 18:44:56 +0200 Subject: [PATCH 27/48] Item 28: BM25 keyword index (pure Python, no new deps) --- app/services/rag/bm25.py | 145 +++++++++++++++++++++++++++++ tests/test_rag_bm25.py | 193 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 338 insertions(+) create mode 100644 app/services/rag/bm25.py create mode 100644 tests/test_rag_bm25.py diff --git a/app/services/rag/bm25.py b/app/services/rag/bm25.py new file mode 100644 index 0000000..28c9bae --- /dev/null +++ b/app/services/rag/bm25.py @@ -0,0 +1,145 @@ +"""In-memory BM25 keyword index for hybrid retrieval (portfolio item 28). + +Complements the vector store with exact-term matching: embeddings generalize +across paraphrase but can miss distinctive identifiers, error codes and other +rare terms that a keyword score catches. This module is the scoring engine; +item 30 wires it into ``RAGService`` startup (rebuild from stored chunks) and +item 32 fuses its ranking with the vector ranking. + +Design decisions: + +* **No new dependency.** The corpus is small (tens to hundreds of chunks), so a + hand-rolled Okapi BM25 beats pulling in ``rank_bm25`` or an IR library. +* **In-memory only, no files of its own.** The index is fully derivable from the + chunk texts already persisted by :class:`VectorStore`, so there is nothing new + to corrupt, version or quarantine - it is rebuilt on startup and updated in + lockstep with vector adds/removes. +* **Standard Okapi parameters** (k1=1.5, b=0.75) and the non-negative IDF form + ``log(1 + (N - df + 0.5)/(df + 0.5))`` so terms present in every chunk score + zero instead of negative. +* **Deterministic.** Ties are broken by ``(doc_id, chunk_index)``, so repeated + runs over the same corpus produce identical rankings. +""" + +from __future__ import annotations + +import math +import re +from collections import Counter +from collections.abc import Iterable, Sequence + +from app.services.rag.vector_store import RetrievedChunk, StoredChunk + +_TOKEN_RE = re.compile(r"\w+", re.UNICODE) + + +def tokenize(text: str) -> list[str]: + """Lowercase word tokens; whitespace and punctuation are separators. + + Unicode-aware (``\\w`` matches accented letters), digits kept - error codes + like ``E1042`` are exactly the terms keyword search exists to catch. + """ + return _TOKEN_RE.findall(text.lower()) + + +class KeywordIndex: + """Okapi BM25 over stored chunk texts.""" + + def __init__(self, k1: float = 1.5, b: float = 0.75) -> None: + self.k1 = k1 + self.b = b + self._chunks: list[StoredChunk] = [] + self._term_freqs: list[Counter[str]] = [] + self._doc_lengths: list[int] = [] + self._df: Counter[str] = Counter() # chunks containing the term + self._total_tokens = 0 + + @property + def size(self) -> int: + return len(self._chunks) + + # ---------- mutation ---------- + + def add_chunks(self, chunks: Sequence[StoredChunk]) -> None: + """Index more chunks (appends; does not deduplicate).""" + for chunk in chunks: + tokens = tokenize(chunk.text) + self._chunks.append(chunk) + self._term_freqs.append(Counter(tokens)) + self._doc_lengths.append(len(tokens)) + self._total_tokens += len(tokens) + for term in set(tokens): + self._df[term] += 1 + + def remove_by_doc_id(self, doc_id: str) -> int: + """Drop every chunk of one document and recompute the statistics.""" + kept = [i for i, c in enumerate(self._chunks) if c.doc_id != doc_id] + removed = len(self._chunks) - len(kept) + if not removed: + return 0 + self._rebuild([self._chunks[i] for i in kept]) + return removed + + def clear(self) -> None: + """Remove all indexed chunks.""" + self._chunks.clear() + self._term_freqs.clear() + self._doc_lengths.clear() + self._df.clear() + self._total_tokens = 0 + + # ---------- search ---------- + + def search(self, query: str, top_k: int = 4) -> list[RetrievedChunk]: + """Rank chunks by BM25 score for the query; zero-score chunks omitted.""" + if not self._chunks or top_k <= 0: + return [] + query_terms = set(tokenize(query)) + if not query_terms: + return [] + + n = len(self._chunks) + avg_len = self._total_tokens / n + scored: list[tuple[float, StoredChunk]] = [] + for chunk, tf, length in zip( + self._chunks, self._term_freqs, self._doc_lengths, strict=True + ): + score = 0.0 + for term in query_terms: + freq = tf.get(term) + if not freq: + continue + df = self._df[term] + idf = math.log(1 + (n - df + 0.5) / (df + 0.5)) + denom = freq + self.k1 * ( + 1 - self.b + self.b * (length / avg_len if avg_len else 0.0) + ) + score += idf * (freq * (self.k1 + 1)) / denom + if score > 0: + scored.append((score, chunk)) + + # Deterministic: score desc, then stable identity of the chunk. + scored.sort(key=lambda item: (-item[0], item[1].doc_id, item[1].chunk_index)) + return [ + RetrievedChunk( + doc_id=chunk.doc_id, + filename=chunk.filename, + chunk_index=chunk.chunk_index, + text=chunk.text, + score=score, + ) + for score, chunk in scored[:top_k] + ] + + # ---------- internals ---------- + + def _rebuild(self, chunks: list[StoredChunk]) -> None: + self.clear() + self.add_chunks(chunks) + + +def build_keyword_index(chunks: Iterable[StoredChunk]) -> KeywordIndex: + """One-shot construction from stored chunks (startup rebuild path).""" + index = KeywordIndex() + index.add_chunks(list(chunks)) + return index diff --git a/tests/test_rag_bm25.py b/tests/test_rag_bm25.py new file mode 100644 index 0000000..f469107 --- /dev/null +++ b/tests/test_rag_bm25.py @@ -0,0 +1,193 @@ +"""BM25 keyword index tests (portfolio item 28). + +The index is pure Python with no external state, so these tests exercise the +scoring math directly against hand-computed expectations. +""" + +from __future__ import annotations + +from app.services.rag.bm25 import KeywordIndex, build_keyword_index, tokenize +from app.services.rag.vector_store import StoredChunk + + +def _chunk(doc_id: str, text: str, chunk_index: int = 0) -> StoredChunk: + return StoredChunk( + doc_id=doc_id, + filename=f"{doc_id}.md", + chunk_index=chunk_index, + text=text, + ) + + +class TestTokenize: + def test_lowercases_and_splits_on_punctuation(self): + assert tokenize("Hello, world! The E1042 error.") == [ + "hello", + "world", + "the", + "e1042", + "error", + ] + + def test_keeps_digits_and_underscore_words_together(self): + assert tokenize("v2.3 and snake_case") == ["v2", "3", "and", "snake_case"] + + def test_unicode_words_survive(self): + assert tokenize("Café naïve") == ["café", "naïve"] + + def test_empty_and_punctuation_only(self): + assert tokenize("") == [] + assert tokenize("!!! ??? ...") == [] + + +class TestAddAndSearch: + def test_search_returns_retrieved_chunks_with_positive_scores(self): + index = KeywordIndex() + index.add_chunks([_chunk("a", "the quick brown fox jumps"), _chunk("b", "lazy dogs sleep")]) + + results = index.search("quick fox", top_k=5) + + assert len(results) == 1 + result = results[0] + assert result.doc_id == "a" + assert result.filename == "a.md" + assert result.chunk_index == 0 + assert result.text == "the quick brown fox jumps" + assert result.score > 0 + + def test_exact_phrase_beats_partial_match(self): + index = KeywordIndex() + index.add_chunks([ + _chunk("partial", "quantum entanglement in photons"), + _chunk("full", "quantum entanglement of photon pairs over fiber"), + ]) + + results = index.search("quantum entanglement photon") + + assert [r.doc_id for r in results] == ["full", "partial"] + + def test_rare_term_outweighs_common_term(self): + # "system" appears everywhere (low IDF); "kubernetes" only once (high IDF). + index = KeywordIndex() + docs = [f"the system runs on {word}" for word in ("linux", "windows", "macos")] + for i, text in enumerate(docs): + index.add_chunks([_chunk(f"d{i}", text)]) + index.add_chunks([_chunk("k8s", "deploying kubernetes manifests")]) + + results = index.search("system kubernetes", top_k=1) + + assert results[0].doc_id == "k8s" + + def test_top_k_limits_results(self): + index = KeywordIndex() + for i in range(5): + index.add_chunks([_chunk(f"d{i}", f"common term number {i}")]) + + assert len(index.search("common", top_k=3)) == 3 + assert len(index.search("common", top_k=100)) == 5 + + def test_no_match_returns_empty(self): + index = KeywordIndex() + index.add_chunks([_chunk("a", "nothing to see here")]) + + assert index.search("zebra quantum") == [] + + def test_empty_or_punctuation_query_returns_empty(self): + index = KeywordIndex() + index.add_chunks([_chunk("a", "some text")]) + + assert index.search("") == [] + assert index.search("!!! ???") == [] + + def test_empty_index_returns_empty(self): + assert KeywordIndex().search("anything") == [] + + def test_repeated_query_terms_are_not_double_counted(self): + once = KeywordIndex() + twice = KeywordIndex() + for idx in (once, twice): + idx.add_chunks([_chunk("a", "the cat sat"), _chunk("b", "cat")]) + + # Deduped query terms: both indexes must rank identically. + assert [r.doc_id for r in once.search("cat")] == [ + r.doc_id for r in twice.search("cat cat cat") + ] + + +class TestMutation: + def test_remove_by_doc_id_drops_only_that_document(self): + index = KeywordIndex() + index.add_chunks([ + _chunk("a", "alpha beta"), + _chunk("a", "gamma delta", 1), + _chunk("b", "beta omega"), + ]) + + removed = index.remove_by_doc_id("a") + + assert removed == 2 + assert index.size == 1 + assert index.search("alpha gamma") == [] + assert [r.doc_id for r in index.search("beta")] == ["b"] + + def test_remove_unknown_doc_is_a_noop(self): + index = KeywordIndex() + index.add_chunks([_chunk("a", "hello world")]) + + assert index.remove_by_doc_id("zzz") == 0 + assert index.size == 1 + + def test_clear_empties_the_index(self): + index = KeywordIndex() + index.add_chunks([_chunk("a", "hello world")]) + index.clear() + + assert index.size == 0 + assert index.search("hello") == [] + + +class TestDeterminismAndBuild: + def test_ties_break_by_doc_id_then_chunk_index(self): + index = KeywordIndex() + # Identical texts from different docs: order must be stable. + index.add_chunks([_chunk("z", "same text"), _chunk("m", "same text"), _chunk("a", "same text")]) + + results = index.search("same text", top_k=10) + + assert [r.doc_id for r in results] == ["a", "m", "z"] + # Scores are equal - the ranking is purely the tie-break. + assert len({round(r.score, 9) for r in results}) == 1 + + def test_build_keyword_index_matches_incremental_adds(self): + chunks = [_chunk("a", "one two three"), _chunk("b", "two four six")] + + built = build_keyword_index(chunks) + incremental = KeywordIndex() + incremental.add_chunks([chunks[0]]) + incremental.add_chunks(chunks[1:]) + + assert built.size == incremental.size == 2 + assert [r.doc_id for r in built.search("two", top_k=5)] == [ + r.doc_id for r in incremental.search("two", top_k=5) + ] + + +class TestEdgeCases: + def test_empty_chunk_text_is_harmless(self): + index = KeywordIndex() + index.add_chunks([_chunk("empty", ""), _chunk("real", "hello there")]) + + assert [r.doc_id for r in index.search("hello")] == ["real"] + + def test_all_empty_corpus_search_is_safe(self): + index = KeywordIndex() + index.add_chunks([_chunk("a", ""), _chunk("b", " ")]) + + assert index.search("anything") == [] + + def test_non_positive_top_k_returns_empty(self): + index = KeywordIndex() + index.add_chunks([_chunk("a", "hello world")]) + + assert index.search("hello", top_k=0) == [] + From 155d0304c194431a78f889ff553112b497a229ab Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 18:54:19 +0200 Subject: [PATCH 28/48] Item 30: rebuild BM25 keyword index from stored chunks at startup --- app/services/rag/service.py | 18 +++++++++++++ tests/test_rag_hybrid.py | 50 +++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 tests/test_rag_hybrid.py diff --git a/app/services/rag/service.py b/app/services/rag/service.py index 7153300..12fa6cb 100644 --- a/app/services/rag/service.py +++ b/app/services/rag/service.py @@ -4,6 +4,9 @@ ``DATA_DIR/rag/`` and are reloaded on startup, so a restart does not re-embed the knowledge base. Indexing is incremental — a document is only embedded when its content hash differs from the version already in the index. + +The BM25 keyword index used for hybrid retrieval is derived from stored chunk +text and rebuilt in memory at startup, so it never needs persisting separately. """ from __future__ import annotations @@ -14,6 +17,7 @@ from typing import Any from app.core.config import settings +from app.services.rag.bm25 import KeywordIndex, build_keyword_index from app.services.rag.chunking import chunk_text from app.services.rag.embeddings import EmbeddingClient from app.services.rag.vector_store import ( @@ -47,6 +51,8 @@ def __init__( self._store: VectorStore | None = None # doc_id -> {"hash": ..., "chunks": N, "model": ..., "indexed_at": ...} self._doc_versions: dict[str, dict[str, Any]] = {} + # BM25 index over stored chunk text; rebuilt in memory at startup. + self._keyword_index: KeywordIndex | None = None self._load_store() # ---------- state ---------- @@ -55,6 +61,11 @@ def __init__( def chunk_count(self) -> int: return self._store.size if self._store else 0 + @property + def keyword_index(self) -> KeywordIndex | None: + """BM25 index over stored chunks; ``None`` until a vector store exists.""" + return self._keyword_index + def document_versions(self) -> dict[str, dict[str, Any]]: """Which version of each document is currently indexed.""" return {doc_id: dict(info) for doc_id, info in self._doc_versions.items()} @@ -261,6 +272,10 @@ def _load_store(self) -> None: # incremental indexing works across restarts. self._rebuild_version_map() + # The keyword index is derived from stored chunk text, so rebuild it in + # full at startup instead of persisting a second copy (item 30). + self._keyword_index = build_keyword_index(self._store._chunks) + def _quarantine_files(self) -> None: import shutil from pathlib import Path @@ -314,6 +329,9 @@ def _ensure_store(self, dimension: int) -> None: persist_dir=self.persist_dir, embedding_model=self.embedding_client.model, ) + # No persisted index to rebuild from; start empty and let the + # indexing path keep it in sync (item 33). + self._keyword_index = KeywordIndex() elif self._store.dimension != dimension: raise ValueError( "Embedding dimension changed; clear the RAG index before re-indexing " diff --git a/tests/test_rag_hybrid.py b/tests/test_rag_hybrid.py new file mode 100644 index 0000000..b082591 --- /dev/null +++ b/tests/test_rag_hybrid.py @@ -0,0 +1,50 @@ +"""Hybrid retrieval service wiring (portfolio items 30-35). + +Item 30 pins that a restarted ``RAGService`` rebuilds its BM25 keyword index +from every stored chunk, so keyword search works across restarts without any +separate persistence. Later items in this file cover the RAG_HYBRID setting, +fused queries and keeping the index in sync with indexing operations. +""" + +from __future__ import annotations + +import pytest + +from app.services.rag.service import RAGService +from tests.fakes import FakeServiceEmbedder + + +@pytest.fixture +def persist_dir(tmp_path) -> str: + return str(tmp_path / "rag") + + +class TestKeywordIndexStartup: + def test_rebuilt_from_all_saved_chunks_after_restart(self, persist_dir): + first = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + first.add_document( + "The quarterly report covers revenue and gross margins.", {"doc_id": "report"} + ) + first.add_document("Deployment runbook: restart the worker service.", {"doc_id": "ops"}) + + second = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + + assert second.keyword_index is not None + # Every stored chunk made it into the rebuilt keyword index. + assert second.keyword_index.size == second.chunk_count + hits = second.keyword_index.search("runbook", top_k=5) + assert [chunk.doc_id for chunk in hits] == ["ops"] + + def test_fresh_persist_dir_gives_empty_keyword_index(self, persist_dir): + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + + assert service.keyword_index is not None + assert service.keyword_index.size == 0 + assert service.keyword_index.search("anything") == [] + + def test_no_persistence_means_no_keyword_index_until_store_exists(self): + # Empty persist dir disables persistence entirely; the store (and with + # it the keyword index) only materializes on first upload. + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir="") + + assert service.keyword_index is None From 099ec5e073adfe6cd30cc8bb2979a3b6d56217ba Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 18:56:45 +0200 Subject: [PATCH 29/48] Item 31: RAG_HYBRID setting (auto/vector/keyword) with normalized hybrid_mode --- app/core/config.py | 2 ++ app/services/rag/service.py | 16 ++++++++++++++++ tests/test_rag_hybrid.py | 29 +++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+) diff --git a/app/core/config.py b/app/core/config.py index dfe217e..0d96a28 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -36,6 +36,8 @@ class Settings: rag_chunk_size: int = int(os.getenv("RAG_CHUNK_SIZE", "800")) rag_chunk_overlap: int = int(os.getenv("RAG_CHUNK_OVERLAP", "150")) rag_top_k: int = int(os.getenv("RAG_TOP_K", "4")) + # Hybrid retrieval mode: "auto" (fuses vector + BM25 keyword), "vector", or "keyword". + rag_hybrid: str = os.getenv("RAG_HYBRID", "auto") # ---- Ollama vision (LoRA caption generation) ---- vision_model: str = os.getenv("OLLAMA_VISION_MODEL", "llava") diff --git a/app/services/rag/service.py b/app/services/rag/service.py index 12fa6cb..cfacf60 100644 --- a/app/services/rag/service.py +++ b/app/services/rag/service.py @@ -66,6 +66,22 @@ def keyword_index(self) -> KeywordIndex | None: """BM25 index over stored chunks; ``None`` until a vector store exists.""" return self._keyword_index + @property + def hybrid_mode(self) -> str: + """Retrieval mode from ``RAG_HYBRID``: auto, vector, or keyword. + + Unknown values fall back to ``auto`` with a warning rather than + failing retrieval. + """ + mode = settings.rag_hybrid.strip().lower() + if mode not in ("auto", "vector", "keyword"): + logger.warning( + "[RAG] Unknown RAG_HYBRID value %r; falling back to auto", + settings.rag_hybrid, + ) + return "auto" + return mode + def document_versions(self) -> dict[str, dict[str, Any]]: """Which version of each document is currently indexed.""" return {doc_id: dict(info) for doc_id, info in self._doc_versions.items()} diff --git a/tests/test_rag_hybrid.py b/tests/test_rag_hybrid.py index b082591..fe2adcc 100644 --- a/tests/test_rag_hybrid.py +++ b/tests/test_rag_hybrid.py @@ -8,6 +8,8 @@ from __future__ import annotations +import logging + import pytest from app.services.rag.service import RAGService @@ -48,3 +50,30 @@ def test_no_persistence_means_no_keyword_index_until_store_exists(self): service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir="") assert service.keyword_index is None + + +class TestHybridModeSetting: + def test_defaults_to_auto(self): + # Config default; assumes RAG_HYBRID is not exported in the test env. + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir="") + + assert service.hybrid_mode == "auto" + + def test_normalizes_case_and_whitespace(self, set_setting): + set_setting("rag_hybrid", " VECTOR ") + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir="") + + assert service.hybrid_mode == "vector" + + def test_unknown_value_falls_back_to_auto_with_warning( + self, set_setting, caplog + ): + set_setting("rag_hybrid", "banana") + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir="") + + with caplog.at_level(logging.WARNING): + assert service.hybrid_mode == "auto" + assert any( + "RAG_HYBRID" in record.getMessage() for record in caplog.records + ) + From b0854fba8a87ffc145c06802ef8fbb9129854cec Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 19:09:17 +0200 Subject: [PATCH 30/48] Item 34: query() follows RAG_HYBRID (auto fuses vector + keyword) --- app/services/rag/service.py | 71 +++++++++++++++++- tests/test_rag_hybrid.py | 141 ++++++++++++++++++++++++++++++++++++ 2 files changed, 209 insertions(+), 3 deletions(-) diff --git a/app/services/rag/service.py b/app/services/rag/service.py index cfacf60..651ca92 100644 --- a/app/services/rag/service.py +++ b/app/services/rag/service.py @@ -20,6 +20,7 @@ from app.services.rag.bm25 import KeywordIndex, build_keyword_index from app.services.rag.chunking import chunk_text from app.services.rag.embeddings import EmbeddingClient +from app.services.rag.fusion import reciprocal_rank_fuse from app.services.rag.vector_store import ( IndexIncompatibleError, RetrievedChunk, @@ -154,6 +155,9 @@ def add_document( removed = self._store.remove_by_doc_id(doc_id) if removed: logger.info("[RAG] %s changed; dropped %d stale chunks", doc_id, removed) + # Keep the keyword index in sync with whatever was just dropped. + if self._keyword_index is not None and self._store is not None: + self._keyword_index.remove_by_doc_id(doc_id) chunks = chunk_text( text, @@ -180,6 +184,9 @@ def add_document( ] assert self._store is not None self._store.add(embeddings, stored_chunks) + # Keep the keyword index in sync with the freshly indexed chunks. + if self._keyword_index is not None: + self._keyword_index.add_chunks(stored_chunks) self._record_version(doc_id, text, len(chunks)) self._save() return len(chunks) @@ -198,6 +205,7 @@ def query_debug(self, question: str, top_k: int | None = None) -> dict[str, Any] "index_chunks": self.chunk_count, "embedding_model": self.embedding_client.model, "backend": self.embedding_client.backend, + "retrieval_mode": self.hybrid_mode, "retrieved": [ { "doc_id": chunk.doc_id, @@ -212,13 +220,66 @@ def query_debug(self, question: str, top_k: int | None = None) -> dict[str, Any] } def query(self, question: str, top_k: int | None = None) -> list[RetrievedChunk]: - """Retrieve the most relevant chunks for a question.""" + """Retrieve the most relevant chunks for a question. + + The retrieval mode follows ``RAG_HYBRID`` (see :attr:`hybrid_mode`): + ``auto`` fuses vector similarity with BM25 keyword ranking, while + ``vector`` and ``keyword`` use only that single signal. + """ + k = top_k or settings.rag_top_k + mode = self.hybrid_mode + if mode == "vector": + return self.query_vector(question, k) + if mode == "keyword": + if self._keyword_index is None: + return [] + return self._keyword_index.search(question, top_k=k) + return self.query_hybrid(question, top_k=k) + + def query_vector(self, question: str, top_k: int) -> list[RetrievedChunk]: + """Pure vector leg of retrieval (no keyword fusion).""" if not self._store or self._store.size == 0: return [] + query_embedding = self.embedding_client.embed(question) + return self._store.search(query_embedding, top_k=top_k) + def query_hybrid(self, question: str, top_k: int | None = None) -> list[RetrievedChunk]: + """Retrieve chunks by fusing vector similarity with BM25 keyword ranking. + + Both rankings are combined with reciprocal rank fusion (k=60), so a + chunk that ranks well in either signal surfaces even when the other + misses it entirely. Each returned chunk carries its fused RRF score + rather than a raw cosine or BM25 value, and results are sorted by that + score descending. Degrades to plain vector search when no keyword + index is available. + """ k = top_k or settings.rag_top_k - query_embedding = self.embedding_client.embed(question) - return self._store.search(query_embedding, top_k=k) + if not self._store or self._store.size == 0: + return [] + + vector_hits = self.query_vector(question, k) + keyword_hits = ( + self._keyword_index.search(question, top_k=k) + if self._keyword_index is not None + else [] + ) + fused = reciprocal_rank_fuse( + [ + [f"{chunk.doc_id}:{chunk.chunk_index}" for chunk in vector_hits], + [f"{chunk.doc_id}:{chunk.chunk_index}" for chunk in keyword_hits], + ], + top_k=k, + ) + by_id = { + f"{chunk.doc_id}:{chunk.chunk_index}": chunk + for chunk in [*vector_hits, *keyword_hits] + } + results: list[RetrievedChunk] = [] + for chunk_id, rrf_score in fused: + chunk = by_id[chunk_id] + chunk.score = rrf_score + results.append(chunk) + return results def format_context(self, chunks: list[RetrievedChunk]) -> str: """Format retrieved chunks for LLM prompt injection.""" @@ -239,6 +300,8 @@ def remove_document(self, doc_id: str) -> int: return 0 removed = self._store.remove_by_doc_id(doc_id) if removed: + if self._keyword_index is not None: + self._keyword_index.remove_by_doc_id(doc_id) self._doc_versions.pop(doc_id, None) self._save() return removed @@ -247,6 +310,8 @@ def clear(self) -> None: """Clear the entire vector index.""" if self._store: self._store.clear() + if self._keyword_index is not None: + self._keyword_index.clear() self._doc_versions.clear() self._save() diff --git a/tests/test_rag_hybrid.py b/tests/test_rag_hybrid.py index fe2adcc..b399b57 100644 --- a/tests/test_rag_hybrid.py +++ b/tests/test_rag_hybrid.py @@ -77,3 +77,144 @@ def test_unknown_value_falls_back_to_auto_with_warning( "RAG_HYBRID" in record.getMessage() for record in caplog.records ) + +class TestQueryHybrid: + def test_empty_index_returns_empty(self): + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir="") + + assert service.query_hybrid("anything") == [] + + def test_keyword_match_outranks_vector_only_chunk(self, persist_dir): + # "zebra" appears only in doc a, so a is rank 1 on keywords and must + # come out on top after fusion no matter how the fake embedder ranks + # the two chunks by cosine similarity. + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + service.add_document("The zebra migration runs every Sunday night.", {"doc_id": "a"}) + service.add_document("Quarterly revenue grew across all regions.", {"doc_id": "b"}) + + results = service.query_hybrid("zebra", top_k=2) + + assert [chunk.doc_id for chunk in results] == ["a", "b"] + + def test_fused_scores_are_rrf_scale_and_sorted(self, persist_dir): + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + service.add_document("The zebra migration runs every Sunday night.", {"doc_id": "a"}) + service.add_document("Quarterly revenue grew across all regions.", {"doc_id": "b"}) + + results = service.query_hybrid("zebra", top_k=2) + + assert len(results) == 2 + scores = [chunk.score for chunk in results] + # RRF with k=60: a single rank-1 hit is worth 1/61, and the maximum + # possible value (rank 1 on both lists) is 2/61. + assert all(0 < score <= 2 / 61 for score in scores) + assert scores == sorted(scores, reverse=True) + + def test_respects_top_k(self, persist_dir): + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + texts = { + "a": "The zebra migration runs every Sunday night.", + "b": "Quarterly revenue grew across all regions.", + "c": "Zebra stripes are a camouflage pattern.", + } + for doc_id, text in texts.items(): + service.add_document(text, {"doc_id": doc_id}) + + results = service.query_hybrid("zebra", top_k=2) + + assert len(results) == 2 + + def test_degrades_toquery_vector_when_keyword_index_missing(self, persist_dir): + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + service.add_document("The zebra migration runs every Sunday night.", {"doc_id": "a"}) + + vector_only = service.query("zebra", top_k=1) + service._keyword_index = None # simulate a missing keyword index + + results = service.query_hybrid("zebra", top_k=1) + + assert [chunk.doc_id for chunk in results] == [vector_only[0].doc_id] + + +class TestKeywordIndexSync: + def test_add_document_updates_keyword_index_immediately(self, persist_dir): + # No restart needed: the keyword index tracks indexing live. + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + + service.add_document("The zebra migration runs every Sunday night.", {"doc_id": "a"}) + + assert [chunk.doc_id for chunk in service.keyword_index.search("zebra")] == ["a"] + assert service.keyword_index.size == service.chunk_count + + def test_reindexing_changed_content_keeps_only_new_chunks(self, persist_dir): + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + service.add_document("The zebra migration runs every Sunday night.", {"doc_id": "a"}) + + service.add_document("The quantum rollout ships on Friday morning.", {"doc_id": "a"}) + + assert service.keyword_index.search("zebra") == [] + assert [chunk.doc_id for chunk in service.keyword_index.search("quantum")] == ["a"] + assert service.keyword_index.size == service.chunk_count + + def test_remove_document_updates_keyword_index(self, persist_dir): + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + service.add_document("The zebra migration runs every Sunday night.", {"doc_id": "a"}) + service.add_document("Quarterly revenue grew across all regions.", {"doc_id": "b"}) + + removed = service.remove_document("a") + + assert removed == 1 + assert service.keyword_index.search("zebra") == [] + assert [chunk.doc_id for chunk in service.keyword_index.search("revenue")] == ["b"] + assert service.keyword_index.size == service.chunk_count + + def test_clear_resets_keyword_index(self, persist_dir): + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + service.add_document("The zebra migration runs every Sunday night.", {"doc_id": "a"}) + + service.clear() + + assert service.keyword_index.size == 0 + assert service.keyword_index.search("zebra") == [] + + +class TestQueryModeRouting: + def test_auto_mode_fuses_by_default(self, persist_dir): + # RAG_HYBRID defaults to auto, so the plain query path is already hybrid. + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + service.add_document("The zebra migration runs every Sunday night.", {"doc_id": "a"}) + service.add_document("Quarterly revenue grew across all regions.", {"doc_id": "b"}) + + results = service.query("zebra", top_k=2) + + assert [chunk.doc_id for chunk in results] == ["a", "b"] + # Fused scores are RRF-scale, not raw cosine similarity. + assert all(0 < chunk.score <= 2 / 61 for chunk in results) + + def test_vector_mode_ignores_keywords(self, persist_dir, set_setting): + set_setting("rag_hybrid", "vector") + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + service.add_document("The zebra migration runs every Sunday night.", {"doc_id": "a"}) + + results = service.query("zebra", top_k=2) + + assert results == service.query_vector("zebra", 2) + + def test_keyword_mode_ignores_vectors(self, persist_dir, set_setting): + set_setting("rag_hybrid", "keyword") + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + service.add_document("The zebra migration runs every Sunday night.", {"doc_id": "a"}) + + results = service.query("zebra", top_k=2) + + assert results == service.keyword_index.search("zebra", top_k=2) + + def test_query_debug_reports_retrieval_mode(self, persist_dir, set_setting): + set_setting("rag_hybrid", "keyword") + service = RAGService(embedding_client=FakeServiceEmbedder(), persist_dir=persist_dir) + + assert service.query_debug("anything")["retrieval_mode"] == "keyword" + + + + From 4979763e4a98e1cf397540029e41e346fa1283fe Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 19:09:24 +0200 Subject: [PATCH 31/48] Item 35: hybrid eval mode (mode param + --hybrid-mode flag) --- evals/cli.py | 15 +++++++++++-- evals/runner.py | 34 +++++++++++++++++++++++++---- tests/test_eval_cli.py | 30 ++++++++++++++++++++++++++ tests/test_eval_service.py | 44 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 117 insertions(+), 6 deletions(-) diff --git a/evals/cli.py b/evals/cli.py index 7b5d1ee..588846e 100644 --- a/evals/cli.py +++ b/evals/cli.py @@ -13,7 +13,7 @@ Usage: python -m evals.cli [--top-k N] [--chunk-size N] [--overlap N] - [--out PATH] [--service | --grid] + [--out PATH] [--service | --grid] [--hybrid-mode M] """ from __future__ import annotations @@ -55,6 +55,9 @@ def build_parser() -> argparse.ArgumentParser: parser.add_argument("--grid", action="store_true", help=f"run every cell of the chunking grid " f"(default: {DEFAULT_CHUNKING_GRID}) and write one row per cell") + parser.add_argument("--hybrid-mode", choices=("auto", "vector", "keyword"), default=None, + help="service mode only; retrieval path to measure " + "(default: RAG_HYBRID setting)") return parser @@ -68,6 +71,9 @@ def run(argv: list[str] | None = None, *, client: EmbeddingClient | None = None) print("error: --grid cannot be combined with --service, --chunk-size or --overlap", file=sys.stderr) return 1 + if args.hybrid_mode is not None and not args.service: + print("error: --hybrid-mode requires --service", file=sys.stderr) + return 1 client = client or EmbeddingClient() try: @@ -88,7 +94,12 @@ def run(argv: list[str] | None = None, *, client: EmbeddingClient | None = None) try: service = RAGService(embedding_client=client, persist_dir=str(persist_dir)) config["num_chunks"] = index_dataset(service, dataset) - results = run_retrieval_on_service(dataset, service, top_k=top_k) + results = run_retrieval_on_service( + dataset, service, top_k=top_k, mode=args.hybrid_mode + ) + config["retrieval_mode"] = ( + args.hybrid_mode if args.hybrid_mode is not None else service.hybrid_mode + ) finally: shutil.rmtree(persist_dir, ignore_errors=True) else: diff --git a/evals/runner.py b/evals/runner.py index 968d5cb..f8db3ce 100644 --- a/evals/runner.py +++ b/evals/runner.py @@ -14,7 +14,7 @@ from app.core.config import settings from app.services.rag.service import RAGService -from app.services.rag.vector_store import VectorStore +from app.services.rag.vector_store import RetrievedChunk, VectorStore from evals.dataset import EvalDataset from evals.index import BatchEmbedder from evals.metrics import QuestionResult @@ -94,24 +94,38 @@ def run_retrieval_on_service( service: RAGService, *, top_k: int | None = None, + mode: str | None = None, ) -> list[QuestionResult]: - """Run every question through the real ``RAGService.query``. + """Run every question through the real ``RAGService``. Same contract as :func:`run_retrieval` (dataset order, raw chunk ranks, ground truth from ``source_docs``), but retrieval goes through the production service instead of a bare store + embedder pair. An empty index yields empty retrievals rather than an error, mirroring the app. + + ``mode`` selects the retrieval path under test - "auto" (fused vector + + keyword), "vector", or "keyword". It defaults to the production + ``RAG_HYBRID`` setting so a plain run measures what the app serves; pass + an explicit value to compare modes side by side. + Raises: - ValueError: if the dataset has no questions. + ValueError: if the dataset has no questions or *mode* is not one of + auto/vector/keyword. """ if top_k is None: top_k = settings.rag_top_k if not dataset.questions: raise ValueError("dataset has no questions to run") + if mode is None: + mode = service.hybrid_mode + if mode not in ("auto", "vector", "keyword"): + raise ValueError( + f"unknown retrieval mode {mode!r}; expected auto, vector or keyword" + ) results: list[QuestionResult] = [] for question in dataset.questions: - hits = service.query(question.question, top_k=top_k) + hits = _retrieve_on_service(service, question.question, top_k, mode) retrieved = tuple(hit.doc_id for hit in hits) results.append( QuestionResult( @@ -121,3 +135,15 @@ def run_retrieval_on_service( ) ) return results + + +def _retrieve_on_service( + service: RAGService, text: str, top_k: int, mode: str +) -> list[RetrievedChunk]: + """One retrieval through the requested mode of *service*.""" + if mode == "vector": + return service.query_vector(text, top_k=top_k) + if mode == "keyword": + index = service.keyword_index + return index.search(text, top_k=top_k) if index is not None else [] + return service.query_hybrid(text, top_k=top_k) diff --git a/tests/test_eval_cli.py b/tests/test_eval_cli.py index a051732..fe05308 100644 --- a/tests/test_eval_cli.py +++ b/tests/test_eval_cli.py @@ -98,6 +98,36 @@ def test_invalid_top_k_fails_cleanly(self, _fake_client, tmp_path): assert code == 1 assert not out.exists() + def test_hybrid_mode_requires_service_flag(self, _fake_client, tmp_path): + out = tmp_path / "hybrid.json" + + code = run(["--hybrid-mode", "vector", "--out", str(out)], client=_fake_client) + + assert code == 1 + assert not out.exists() + + def test_hybrid_mode_recorded_in_report(self, _fake_client, tmp_path): + out = tmp_path / "hybrid.json" + + code = run( + ["--top-k", "2", "--out", str(out), "--service", "--hybrid-mode", "keyword"], + client=_fake_client, + ) + + assert code == 0 + report = json.loads(out.read_text(encoding="utf-8")) + assert report["config"]["mode"] == "service" + assert report["config"]["retrieval_mode"] == "keyword" + + def test_service_mode_records_default_retrieval_mode(self, _fake_client, tmp_path): + out = tmp_path / "default-mode.json" + + code = run(["--top-k", "2", "--out", str(out), "--service"], client=_fake_client) + + assert code == 0 + report = json.loads(out.read_text(encoding="utf-8")) + assert report["config"]["retrieval_mode"] == settings.rag_hybrid + def test_fallback_backend_records_actual_model(self, tmp_path): """When Ollama is down and sentence-transformers serves the vectors, the diff --git a/tests/test_eval_service.py b/tests/test_eval_service.py index 59ef789..9341f09 100644 --- a/tests/test_eval_service.py +++ b/tests/test_eval_service.py @@ -94,6 +94,50 @@ def test_empty_dataset_raises(self, service): run_retrieval_on_service(EvalDataset(docs=[], questions=[]), service) +class TestRunRetrievalOnServiceModes: + """Item 35: explicit retrieval modes for side-by-side comparison.""" + + def test_mode_defaults_to_production_setting(self, service, synthetic_dataset): + index_dataset(service, synthetic_dataset) + + default = run_retrieval_on_service(synthetic_dataset, service, top_k=3) + explicit = run_retrieval_on_service( + synthetic_dataset, service, top_k=3, mode="auto" + ) + + assert [r.retrieved_doc_ids for r in default] == [r.retrieved_doc_ids for r in explicit] + + def test_keyword_mode_returns_only_keyword_matches(self, service, synthetic_dataset): + # The question's tokens appear only in the alpha document. + index_dataset(service, synthetic_dataset) + + results = run_retrieval_on_service( + synthetic_dataset, service, top_k=3, mode="keyword" + ) + + assert all(doc_id == "alpha" for r in results for doc_id in r.retrieved_doc_ids) + assert any(r.retrieved_doc_ids for r in results) + + def test_vector_mode_matches_query_vector(self, service, synthetic_dataset): + index_dataset(service, synthetic_dataset) + + results = run_retrieval_on_service( + synthetic_dataset, service, top_k=3, mode="vector" + ) + + for question, result in zip(synthetic_dataset.questions, results, strict=True): + expected = tuple( + hit.doc_id for hit in service.query_vector(question.question, top_k=3) + ) + assert result.retrieved_doc_ids == expected + + def test_invalid_mode_raises(self, service, synthetic_dataset): + index_dataset(service, synthetic_dataset) + + with pytest.raises(ValueError, match="unknown retrieval mode"): + run_retrieval_on_service(synthetic_dataset, service, top_k=3, mode="bm25") + + class TestCommittedCorpus: def test_runs_every_committed_question_through_the_service(self, tmp_path): dataset = load_dataset() From 0f6953262f3bcf5c4948a044c73cd3bec1a9129e Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 19:34:36 +0200 Subject: [PATCH 32/48] Item 36: docs/EVAL.md (harness guide + baselines); ignore generated eval reports --- .gitignore | 3 ++ docs/EVAL.md | 140 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 docs/EVAL.md diff --git a/.gitignore b/.gitignore index 02946e6..2839c5a 100644 --- a/.gitignore +++ b/.gitignore @@ -270,3 +270,6 @@ data/jobs.json # Runtime state (created by the app at startup) data/ + +# Eval reports (generated by python -m evals.cli; reproducible, see docs/EVAL.md) +evals/reports/ diff --git a/docs/EVAL.md b/docs/EVAL.md new file mode 100644 index 0000000..4a6c701 --- /dev/null +++ b/docs/EVAL.md @@ -0,0 +1,140 @@ +# RAG Retrieval Evaluation + +Apollo ships a small, self-contained evaluation harness for its document-RAG +retrieval pipeline. It answers one question: **when the user asks something, do +the chunks that get retrieved actually come from the documents that contain the +answer?** The harness is deterministic, dependency-light (no LLM calls), and fast +enough to run locally on every retrieval-related change. + +Everything lives in [`evals/`](../evals/) — data, code, and generated reports: + +| Path | What it is | +|------|------------| +| `evals/corpus/*.md` | 12 ground-truth documents (local-AI topics: diffusion, LoRA, ComfyUI, vector search, ...) | +| `evals/questions.json` | 48 questions, each with its ground-truth source docs and key facts | +| `evals/dataset.py` | Loads + validates the corpus and question set (referential integrity) | +| `evals/index.py` | Builds an in-memory index using the **production** chunker and vector store | +| `evals/runner.py` | Runs retrieval over a bare index or through the real `RAGService` | +| `evals/metrics.py` | Document-level recall@k, MRR, hit-rate | +| `evals/report.py` | Deterministic JSON report writer | +| `evals/grid.py` | Chunking-parameter grid sweep (item 27) | +| `evals/cli.py` | Command-line entry point: `python -m evals.cli` | + +## Metrics + +The unit of scoring is the **document**, not the chunk. A question names one or +more ground-truth documents (`source_docs`); retrieval returns a ranked list of +chunks, and each chunk carries its document id. For a cutoff *k*: + +- **recall@k** — fraction of the question's relevant documents present among the + top-*k* chunks (each document counts once). Averaged over all questions. +- **MRR** — mean reciprocal rank: for each question, `1 / rank` of the first + chunk from a relevant document; averaged over all questions. +- **hit_rate@k** — fraction of questions with at least one relevant-document + chunk in the top *k*. + +The cutoff applies to the raw ranked chunk list (repeated chunks occupy slots), +then documents are deduplicated for scoring — exactly how the pipeline consumes +results. + +## Running it + +```bash +# Index mode (default): bare in-memory index, production chunking defaults +python -m evals.cli + +# Override chunking (index mode only) and cutoff +python -m evals.cli --chunk-size 600 --overlap 120 --top-k 5 + +# Service mode: full RAGService end to end (temp persist dir, never DATA_DIR) +python -m evals.cli --service + +# Service mode with an explicit retrieval path (see "Hybrid modes" below) +python -m evals.cli --service --hybrid-mode vector + +# Chunking grid sweep: one row per cell of the default grid +python -m evals.cli --grid +``` + +Reports are written to `evals/reports/rag_eval.json` by default; use `--out PATH` +to redirect. Generated reports are **not** committed — they are reproducible from +the corpus, questions, and settings recorded inside each report's `config` block. + +### Embedding backend + +The CLI uses the same `EmbeddingClient` as production: it probes Ollama for the +configured embedding model (`OLLAMA_EMBEDDING_MODEL`, default `nomic-embed-text`) +and falls back to sentence-transformers (`EMBEDDING_FALLBACK_MODEL`, default +`all-MiniLM-L6-v2`) when Ollama is unreachable. The report's `config` block +records which backend actually produced the vectors (`embedding_backend` and, on +fallback, the real model name), so a report always tells you what it was made with. + +### Hybrid modes (service mode only) + +`--hybrid-mode {auto,vector,keyword}` selects the retrieval path measured in +service mode; without the flag the service's `RAG_HYBRID` setting applies +(default `auto`). The chosen path is recorded as `retrieval_mode` in the report. + +- **vector** — pure FAISS similarity search (`query_vector`). +- **keyword** — BM25 keyword index only (no embeddings at query time). +- **auto** — hybrid: both legs run and are fused with reciprocal-rank fusion + (`query_hybrid`). + +## Report format + +Single-run reports (`rag_eval.json`) have `schema_version`, a `config` block, an +aggregate `summary`, and one entry per question (retrieved + relevant doc ids and +per-question metrics). Grid reports carry the same config plus one flat row per +cell. Output is deterministic — no timestamps, floats rounded to four decimals — +so two runs over identical inputs diff cleanly, which is what the CI regression +gate relies on. + +## Baselines (2026-10-17) + +Measured with the MiniLM fallback backend (Ollama was down at measurement time), +top_k=4, 48 questions / 12 docs. + +Chunking grid (index mode): + +| chunk/overlap | chunks | recall@4 | MRR | hit_rate@4 | +|---------------|--------|----------|--------|------------| +| 400 / 75 | 128 | 0.9583 | 0.9028 | 0.9792 | +| 600 / 120 | 68 | 0.9583 | 0.9583 | 0.9792 | +| **800 / 150 (production)** | **46** | **0.9896** | **0.9757** | **1.0000** | +| 1200 / 200 | 27 | 0.9792 | 0.9444 | 1.0000 | + +Retrieval modes (service mode, production chunking): + +| mode | recall@4 | MRR | hit_rate@4 | +|----------|----------|--------|------------| +| vector | 0.9896 | 0.9757 | 1.0000 | +| auto | 0.9896 | 0.9514 | 1.0000 | +| keyword | 0.9896 | 0.9635 | 1.0000 | + +Reading: the production chunking (800/150) is the best cell of the grid, and all +three retrieval modes hit every question at k=4 on this corpus — the questions +are close paraphrases of document text, so vectors alone already rank correctly. +Hybrid fusion costs a little MRR here but never loses recall; it exists to help +where embeddings miss (exact identifiers, code-like tokens). Re-measure after any +change to chunking, embedding model, or retrieval logic and compare against these +numbers before merging. + +## Extending the dataset + +- **Add a document**: drop a `*.md` file into `evals/corpus/`. Its `doc_id` is + the file stem; its title is the first `# ` heading (falling back to the stem). +- **Add questions**: append objects to `questions.json` with fields `id`, + `question`, `source_docs` (list of corpus stems), and `key_facts`. Ids must be + unique, every `source_docs` entry must name an existing document, and both + lists must be non-empty — `load_dataset()` enforces all of this and fails the + run loudly otherwise. + +Keep questions answerable from the cited documents alone; `key_facts` are for +human review (they are not scored by retrieval metrics). + +## Tests + +The harness itself is covered by `tests/test_eval_*.py` (dataset validation, +metrics math, index building with a deterministic fake embedder, runner and CLI +wiring including grid and hybrid-mode routing) — all of it runs without Ollama or +a GPU. \ No newline at end of file From dc81ef614a5ca87e4d583094d034cce400283a88 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 19:49:19 +0200 Subject: [PATCH 33/48] Item 37: CI regression gate (pinned-backend baseline + one-sided pytest comparison) --- docs/EVAL.md | 34 +- evals/baselines/vector_service.json | 747 ++++++++++++++++++++++++++++ scripts/regen_eval_baseline.py | 77 +++ tests/test_eval_regression.py | 123 +++++ 4 files changed, 979 insertions(+), 2 deletions(-) create mode 100644 evals/baselines/vector_service.json create mode 100644 scripts/regen_eval_baseline.py create mode 100644 tests/test_eval_regression.py diff --git a/docs/EVAL.md b/docs/EVAL.md index 4a6c701..4d134eb 100644 --- a/docs/EVAL.md +++ b/docs/EVAL.md @@ -87,7 +87,35 @@ aggregate `summary`, and one entry per question (retrieved + relevant doc ids an per-question metrics). Grid reports carry the same config plus one flat row per cell. Output is deterministic — no timestamps, floats rounded to four decimals — so two runs over identical inputs diff cleanly, which is what the CI regression -gate relies on. +gate relies on (below). + +## Regression gate + +`tests/test_eval_regression.py` is the CI gate for retrieval quality. It runs +the real service-mode pipeline — production chunking, vector retrieval, top_k=4 +— with the sentence-transformers backend **pinned** (an `OllamaClient` stub that +always reports unreachable, so Ollama is never probed and results do not depend +on whether it happens to be running), then compares against the committed +baseline [`evals/baselines/vector_service.json`](../evals/baselines/vector_service.json): + +- summary metrics (`mean_recall_at_k`, `mrr`, `hit_rate_at_k`) may improve but + must not drop by more than float noise (tolerance 1e-3 — well below the + granularity of a single question flipping, ~0.02); +- no question that had a hit@4 in the baseline may lose it; +- the run's backend, retrieval mode, cutoff and production chunking must match + the baseline's `config` block (like-for-like comparison). + +It runs as part of the normal pytest suite (~5 s) and needs no Ollama or GPU. +After an **intentional** change to chunking, embeddings or retrieval logic, +re-baseline with: + +```bash +python -m scripts.regen_eval_baseline +``` + +and commit the updated `evals/baselines/vector_service.json` alongside that +change. The script pins the same fallback backend, so baselines are reproducible +on any machine with the requirements installed. ## Baselines (2026-10-17) @@ -137,4 +165,6 @@ human review (they are not scored by retrieval metrics). The harness itself is covered by `tests/test_eval_*.py` (dataset validation, metrics math, index building with a deterministic fake embedder, runner and CLI wiring including grid and hybrid-mode routing) — all of it runs without Ollama or -a GPU. \ No newline at end of file +a GPU. The one exception in spirit: the regression gate +(`test_eval_regression.py`) loads the real MiniLM model on CPU so it measures +actual retrieval quality against the committed baseline (see above). \ No newline at end of file diff --git a/evals/baselines/vector_service.json b/evals/baselines/vector_service.json new file mode 100644 index 0000000..991b133 --- /dev/null +++ b/evals/baselines/vector_service.json @@ -0,0 +1,747 @@ +{ + "schema_version": 1, + "config": { + "mode": "service", + "retrieval_mode": "vector", + "embedding_backend": "sentence-transformers", + "embedder_model": "all-MiniLM-L6-v2", + "top_k": 4, + "num_docs": 12, + "num_chunks": 46, + "chunk_size": 800, + "overlap": 150 + }, + "summary": { + "num_questions": 48, + "k": 4, + "mean_recall_at_k": 0.9896, + "mrr": 0.9757, + "hit_rate_at_k": 1.0 + }, + "questions": [ + { + "id": "q01", + "retrieved_doc_ids": [ + "diffusion-basics", + "diffusion-basics", + "diffusion-basics", + "upscaling-and-resolution" + ], + "relevant_doc_ids": [ + "diffusion-basics" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q02", + "retrieved_doc_ids": [ + "diffusion-basics", + "comfyui-workflows", + "comfyui-workflows", + "upscaling-and-resolution" + ], + "relevant_doc_ids": [ + "diffusion-basics" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q03", + "retrieved_doc_ids": [ + "diffusion-basics", + "sampling-and-cfg", + "diffusion-basics", + "sampling-and-cfg" + ], + "relevant_doc_ids": [ + "diffusion-basics" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q04", + "retrieved_doc_ids": [ + "diffusion-basics", + "diffusion-basics", + "sdxl", + "diffusion-basics" + ], + "relevant_doc_ids": [ + "diffusion-basics" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q05", + "retrieved_doc_ids": [ + "diffusion-basics", + "diffusion-basics", + "diffusion-basics", + "sdxl" + ], + "relevant_doc_ids": [ + "diffusion-basics" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q06", + "retrieved_doc_ids": [ + "sdxl", + "sdxl", + "sdxl", + "sdxl" + ], + "relevant_doc_ids": [ + "sdxl" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q07", + "retrieved_doc_ids": [ + "sdxl", + "sdxl", + "sdxl", + "sampling-and-cfg" + ], + "relevant_doc_ids": [ + "sdxl" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q08", + "retrieved_doc_ids": [ + "sdxl", + "sdxl", + "sdxl", + "sdxl" + ], + "relevant_doc_ids": [ + "sdxl" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q09", + "retrieved_doc_ids": [ + "sdxl", + "sdxl", + "sdxl", + "prompt-engineering" + ], + "relevant_doc_ids": [ + "sdxl" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q10", + "retrieved_doc_ids": [ + "sdxl", + "sdxl", + "sdxl", + "sampling-and-cfg" + ], + "relevant_doc_ids": [ + "sdxl" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q11", + "retrieved_doc_ids": [ + "sdxl", + "sampling-and-cfg", + "sdxl", + "sdxl" + ], + "relevant_doc_ids": [ + "sdxl" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q12", + "retrieved_doc_ids": [ + "sdxl", + "sdxl", + "lora-concepts", + "training-failure-modes" + ], + "relevant_doc_ids": [ + "sdxl" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q13", + "retrieved_doc_ids": [ + "prompt-engineering", + "prompt-engineering", + "prompt-engineering", + "lora-dataset-curation" + ], + "relevant_doc_ids": [ + "prompt-engineering" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q14", + "retrieved_doc_ids": [ + "prompt-engineering", + "prompt-engineering", + "prompt-engineering", + "prompt-engineering" + ], + "relevant_doc_ids": [ + "prompt-engineering" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q15", + "retrieved_doc_ids": [ + "prompt-engineering", + "prompt-engineering", + "prompt-engineering", + "lora-concepts" + ], + "relevant_doc_ids": [ + "prompt-engineering" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q16", + "retrieved_doc_ids": [ + "prompt-engineering", + "prompt-engineering", + "prompt-engineering", + "prompt-engineering" + ], + "relevant_doc_ids": [ + "prompt-engineering" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q17", + "retrieved_doc_ids": [ + "prompt-engineering", + "prompt-engineering", + "lora-dataset-curation", + "sdxl" + ], + "relevant_doc_ids": [ + "prompt-engineering" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q18", + "retrieved_doc_ids": [ + "prompt-engineering", + "prompt-engineering", + "prompt-engineering", + "prompt-engineering" + ], + "relevant_doc_ids": [ + "prompt-engineering" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q19", + "retrieved_doc_ids": [ + "sampling-and-cfg", + "sampling-and-cfg", + "upscaling-and-resolution", + "comfyui-workflows" + ], + "relevant_doc_ids": [ + "sampling-and-cfg" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q20", + "retrieved_doc_ids": [ + "sampling-and-cfg", + "sampling-and-cfg", + "comfyui-workflows", + "sampling-and-cfg" + ], + "relevant_doc_ids": [ + "sampling-and-cfg" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q21", + "retrieved_doc_ids": [ + "sampling-and-cfg", + "sampling-and-cfg", + "sdxl", + "sdxl" + ], + "relevant_doc_ids": [ + "sampling-and-cfg" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q22", + "retrieved_doc_ids": [ + "sampling-and-cfg", + "sampling-and-cfg", + "comfyui-workflows", + "comfyui-workflows" + ], + "relevant_doc_ids": [ + "sampling-and-cfg" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q23", + "retrieved_doc_ids": [ + "sampling-and-cfg", + "sampling-and-cfg", + "comfyui-workflows", + "comfyui-workflows" + ], + "relevant_doc_ids": [ + "sampling-and-cfg" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q24", + "retrieved_doc_ids": [ + "sampling-and-cfg", + "diffusion-basics", + "sampling-and-cfg", + "sampling-and-cfg" + ], + "relevant_doc_ids": [ + "sampling-and-cfg" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q25", + "retrieved_doc_ids": [ + "lora-concepts", + "lora-concepts", + "lora-dataset-curation", + "training-failure-modes" + ], + "relevant_doc_ids": [ + "lora-concepts" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q26", + "retrieved_doc_ids": [ + "lora-concepts", + "lora-concepts", + "lora-dataset-curation", + "training-failure-modes" + ], + "relevant_doc_ids": [ + "lora-concepts" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q27", + "retrieved_doc_ids": [ + "lora-concepts", + "training-failure-modes", + "lora-concepts", + "lora-concepts" + ], + "relevant_doc_ids": [ + "lora-concepts" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q28", + "retrieved_doc_ids": [ + "sdxl", + "lora-concepts", + "sdxl", + "sdxl" + ], + "relevant_doc_ids": [ + "lora-concepts" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 0.5, + "hit_at_k": true + }, + { + "id": "q29", + "retrieved_doc_ids": [ + "lora-dataset-curation", + "apollo-lora-pipeline", + "lora-concepts", + "training-failure-modes" + ], + "relevant_doc_ids": [ + "lora-dataset-curation" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q30", + "retrieved_doc_ids": [ + "lora-dataset-curation", + "lora-concepts", + "lora-concepts", + "training-failure-modes" + ], + "relevant_doc_ids": [ + "lora-dataset-curation" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q31", + "retrieved_doc_ids": [ + "apollo-lora-pipeline", + "apollo-lora-pipeline", + "lora-dataset-curation", + "lora-dataset-curation" + ], + "relevant_doc_ids": [ + "lora-dataset-curation" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 0.3333, + "hit_at_k": true + }, + { + "id": "q32", + "retrieved_doc_ids": [ + "lora-dataset-curation", + "apollo-lora-pipeline", + "training-failure-modes", + "lora-concepts" + ], + "relevant_doc_ids": [ + "lora-dataset-curation" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q33", + "retrieved_doc_ids": [ + "comfyui-workflows", + "comfyui-workflows", + "comfyui-workflows", + "sdxl" + ], + "relevant_doc_ids": [ + "comfyui-workflows" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q34", + "retrieved_doc_ids": [ + "comfyui-workflows", + "comfyui-workflows", + "comfyui-workflows", + "sampling-and-cfg" + ], + "relevant_doc_ids": [ + "comfyui-workflows" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q35", + "retrieved_doc_ids": [ + "comfyui-workflows", + "comfyui-workflows", + "apollo-lora-pipeline", + "comfyui-workflows" + ], + "relevant_doc_ids": [ + "comfyui-workflows" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q36", + "retrieved_doc_ids": [ + "comfyui-workflows", + "apollo-lora-pipeline", + "apollo-lora-pipeline", + "apollo-rag-knowledge-base" + ], + "relevant_doc_ids": [ + "comfyui-workflows" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q37", + "retrieved_doc_ids": [ + "apollo-rag-knowledge-base", + "apollo-lora-pipeline", + "apollo-lora-pipeline", + "comfyui-workflows" + ], + "relevant_doc_ids": [ + "apollo-rag-knowledge-base" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q38", + "retrieved_doc_ids": [ + "apollo-rag-knowledge-base", + "apollo-rag-knowledge-base", + "apollo-rag-knowledge-base", + "comfyui-workflows" + ], + "relevant_doc_ids": [ + "apollo-rag-knowledge-base" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q39", + "retrieved_doc_ids": [ + "apollo-rag-knowledge-base", + "vector-search-basics", + "comfyui-workflows", + "apollo-rag-knowledge-base" + ], + "relevant_doc_ids": [ + "apollo-rag-knowledge-base" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q40", + "retrieved_doc_ids": [ + "apollo-rag-knowledge-base", + "apollo-lora-pipeline", + "apollo-lora-pipeline", + "apollo-rag-knowledge-base" + ], + "relevant_doc_ids": [ + "apollo-rag-knowledge-base" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q41", + "retrieved_doc_ids": [ + "apollo-lora-pipeline", + "lora-dataset-curation", + "apollo-lora-pipeline", + "training-failure-modes" + ], + "relevant_doc_ids": [ + "apollo-lora-pipeline" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q42", + "retrieved_doc_ids": [ + "apollo-lora-pipeline", + "apollo-lora-pipeline", + "apollo-lora-pipeline", + "lora-dataset-curation" + ], + "relevant_doc_ids": [ + "apollo-lora-pipeline" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q43", + "retrieved_doc_ids": [ + "upscaling-and-resolution", + "upscaling-and-resolution", + "upscaling-and-resolution", + "sampling-and-cfg" + ], + "relevant_doc_ids": [ + "upscaling-and-resolution" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q44", + "retrieved_doc_ids": [ + "apollo-rag-knowledge-base", + "vector-search-basics", + "apollo-lora-pipeline", + "apollo-rag-knowledge-base" + ], + "relevant_doc_ids": [ + "vector-search-basics", + "apollo-rag-knowledge-base" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q45", + "retrieved_doc_ids": [ + "training-failure-modes", + "training-failure-modes", + "lora-dataset-curation", + "lora-concepts" + ], + "relevant_doc_ids": [ + "training-failure-modes" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q46", + "retrieved_doc_ids": [ + "training-failure-modes", + "lora-concepts", + "lora-concepts", + "training-failure-modes" + ], + "relevant_doc_ids": [ + "training-failure-modes", + "lora-dataset-curation" + ], + "recall_at_k": 0.5, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q47", + "retrieved_doc_ids": [ + "lora-concepts", + "apollo-lora-pipeline", + "apollo-lora-pipeline", + "lora-concepts" + ], + "relevant_doc_ids": [ + "lora-concepts", + "apollo-lora-pipeline" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + }, + { + "id": "q48", + "retrieved_doc_ids": [ + "sdxl", + "sdxl", + "upscaling-and-resolution", + "upscaling-and-resolution" + ], + "relevant_doc_ids": [ + "sdxl", + "upscaling-and-resolution" + ], + "recall_at_k": 1.0, + "reciprocal_rank": 1.0, + "hit_at_k": true + } + ] +} diff --git a/scripts/regen_eval_baseline.py b/scripts/regen_eval_baseline.py new file mode 100644 index 0000000..0db7223 --- /dev/null +++ b/scripts/regen_eval_baseline.py @@ -0,0 +1,77 @@ +"""Regenerate the committed RAG eval baseline (portfolio item 37). + +The CI regression gate (``tests/test_eval_regression.py``) compares live +retrieval against ``evals/baselines/vector_service.json``. Run this script to +re-baseline after an *intentional* change to chunking, embeddings or retrieval +logic: + + python -m scripts.regen_eval_baseline + +It pins the sentence-transformers fallback backend (Ollama is never probed), so +the baseline is reproducible on any machine with the requirements installed. +""" + +from __future__ import annotations + +import shutil +import tempfile +from pathlib import Path + +from app.clients.ollama_client import OllamaClient +from app.core.config import settings +from app.core.exceptions import OllamaServiceError +from app.services.rag.embeddings import EmbeddingClient +from app.services.rag.service import RAGService +from evals.dataset import load_dataset +from evals.report import build_report, write_report +from evals.runner import index_dataset, run_retrieval_on_service + +BASELINE_PATH = Path(__file__).resolve().parents[1] / "evals" / "baselines" / "vector_service.json" +TOP_K = 4 + + +class _OllamaDown(OllamaClient): + """``OllamaClient`` that always reports unreachable, forcing the fallback backend.""" + + def embed(self, *, model: str, inputs: list[str]) -> list[list[float]]: + raise OllamaServiceError("Ollama disabled for baseline generation", status_code=503) + + +def main() -> int: + dataset = load_dataset() + client = EmbeddingClient(ollama_client=_OllamaDown()) + persist_dir = Path(tempfile.mkdtemp(prefix="apollo-baseline-")) + try: + service = RAGService(embedding_client=client, persist_dir=str(persist_dir)) + num_chunks = index_dataset(service, dataset) + results = run_retrieval_on_service(dataset, service, top_k=TOP_K, mode="vector") + finally: + shutil.rmtree(persist_dir, ignore_errors=True) + + config = { + "mode": "service", + "retrieval_mode": "vector", + "embedding_backend": client.backend, + "embedder_model": ( + client.model if client.backend == "ollama" else client.fallback_model + ), + "top_k": TOP_K, + "num_docs": len(dataset.docs), + "num_chunks": num_chunks, + "chunk_size": settings.rag_chunk_size, + "overlap": settings.rag_chunk_overlap, + } + report = build_report(results, k=TOP_K, config=config) + path = write_report(report, BASELINE_PATH) + + summary = report["summary"] + print(f"baseline written: {path}") + print( + f"recall@{TOP_K}={summary['mean_recall_at_k']:.4f} " + f"MRR={summary['mrr']:.4f} hit_rate@{TOP_K}={summary['hit_rate_at_k']:.4f}" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_eval_regression.py b/tests/test_eval_regression.py new file mode 100644 index 0000000..3787c2f --- /dev/null +++ b/tests/test_eval_regression.py @@ -0,0 +1,123 @@ +"""CI regression gate for RAG retrieval quality (portfolio item 37). + +Runs the real service-mode pipeline against the committed dataset with the +sentence-transformers backend pinned (Ollama is never probed), and asserts that +retrieval quality has not regressed relative to +``evals/baselines/vector_service.json``. The baseline was measured in portfolio +item 35 (vector mode, top_k=4, production chunking): recall@4 = 0.9896, +MRR = 0.9757, hit_rate@4 = 1.0. + +Re-baseline with ``python -m scripts.regen_eval_baseline`` after an intentional +change to chunking, embeddings or retrieval logic. The comparison is one-sided: +improvements pass; any metric dropping by more than float noise, or a question +losing its hit, fails the gate. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from app.clients.ollama_client import OllamaClient +from app.core.config import settings +from app.core.exceptions import OllamaServiceError +from app.services.rag.embeddings import EmbeddingClient +from app.services.rag.service import RAGService +from evals.dataset import load_dataset +from evals.report import build_report +from evals.runner import index_dataset, run_retrieval_on_service + +BASELINE_PATH = Path(__file__).resolve().parents[1] / "evals" / "baselines" / "vector_service.json" +TOP_K = 4 +# Well below the granularity of a single question flipping (1/48 ≈ 0.02), so this +# absorbs float noise only, never a real regression. +TOLERANCE = 1e-3 + +SUMMARY_METRICS = ("mean_recall_at_k", "mrr", "hit_rate_at_k") + + +class _OllamaDown(OllamaClient): + """``OllamaClient`` that always reports unreachable, forcing the fallback backend.""" + + def embed(self, *, model: str, inputs: list[str]) -> list[list[float]]: + raise OllamaServiceError("Ollama disabled in the regression gate", status_code=503) + + +@pytest.fixture(scope="module") +def baseline() -> dict: + return json.loads(BASELINE_PATH.read_text(encoding="utf-8")) + + +@pytest.fixture(scope="module") +def current_report(tmp_path_factory: pytest.TempPathFactory) -> dict: + dataset = load_dataset() + client = EmbeddingClient(ollama_client=_OllamaDown()) + persist_dir = tmp_path_factory.mktemp("rag-regression") + service = RAGService(embedding_client=client, persist_dir=str(persist_dir)) + index_dataset(service, dataset) + results = run_retrieval_on_service(dataset, service, top_k=TOP_K, mode="vector") + return build_report( + results, + k=TOP_K, + config={ + "mode": "service", + "retrieval_mode": "vector", + "embedding_backend": client.backend, + "embedder_model": ( + client.model if client.backend == "ollama" else client.fallback_model + ), + "top_k": TOP_K, + }, + ) + + +def test_baseline_file_is_valid(baseline: dict) -> None: + assert baseline["schema_version"] == 1 + summary = baseline["summary"] + for metric in SUMMARY_METRICS: + assert isinstance(summary[metric], float) + assert summary["num_questions"] > 0 + assert len(baseline["questions"]) == summary["num_questions"] + + +def test_gate_configuration_matches_baseline( + current_report: dict, baseline: dict +) -> None: + config = current_report["config"] + # Like-for-like comparison: the gate must run on the same backend and mode as + # the baseline, with production chunking. + assert config["embedding_backend"] == "sentence-transformers" + assert config["retrieval_mode"] == "vector" + assert config["embedding_backend"] == baseline["config"]["embedding_backend"] + assert current_report["summary"]["k"] == baseline["summary"]["k"] + assert settings.rag_chunk_size == baseline["config"]["chunk_size"], ( + "Production chunking changed; re-baseline with `python -m scripts.regen_eval_baseline`" + ) + assert settings.rag_chunk_overlap == baseline["config"]["overlap"], ( + "Production chunking changed; re-baseline with `python -m scripts.regen_eval_baseline`" + ) + + +def test_no_summary_metric_regression(current_report: dict, baseline: dict) -> None: + current = current_report["summary"] + pinned = baseline["summary"] + assert current["num_questions"] == pinned["num_questions"], ( + "The eval dataset changed; re-baseline with `python -m scripts.regen_eval_baseline`" + ) + for metric in SUMMARY_METRICS: + assert current[metric] >= pinned[metric] - TOLERANCE, ( + f"{metric} regressed from {pinned[metric]:.4f} to {current[metric]:.4f}; " + "re-baseline with `python -m scripts.regen_eval_baseline` if the change is intentional" + ) + + +def test_no_question_lost_its_hit(current_report: dict, baseline: dict) -> None: + pinned_hits = {q["id"]: q["hit_at_k"] for q in baseline["questions"]} + current_questions = current_report["questions"] + assert {q["id"] for q in current_questions} == set(pinned_hits), ( + "The eval dataset changed; re-baseline with `python -m scripts.regen_eval_baseline`" + ) + lost = [q["id"] for q in current_questions if pinned_hits[q["id"]] and not q["hit_at_k"]] + assert not lost, f"These questions lost their hit@{TOP_K}: {lost}" From 10ad849426350300773df3f4dc30c8cf61095054 Mon Sep 17 00:00:00 2001 From: skl Date: Sat, 17 Oct 2026 20:09:10 +0200 Subject: [PATCH 34/48] Docker: image, compose file, and CI build+smoke job (items 38-40) --- .dockerignore | 20 +++++++++++++++++ .github/workflows/ci.yml | 26 ++++++++++++++++++++++ Dockerfile | 47 ++++++++++++++++++++++++++++++++++++++++ docker-compose.yml | 26 ++++++++++++++++++++++ 4 files changed, 119 insertions(+) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 docker-compose.yml diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..a65f278 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,20 @@ +# Keep the build context small and free of local state/secrets. +.git +.github +.env* +.venv* +__pycache__/ +*.py[cod] +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +.coverage + +# Runtime state — created at startup, lives in a volume (see Dockerfile). +data/ + +# Demo GIFs for the README; not used by the app. +images/ + +# Local test-suite logs. +*.log diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 875d2e2..175af80 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -55,3 +55,29 @@ jobs: # Coverage is reported for now; a minimum threshold will be added once the # eval work has established what the number should protect. run: python -m pytest --cov=app --cov-report=term-missing + + docker: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - name: Build image + run: docker build -t apollo:ci . + - name: Smoke test (start container, wait for /live) + # The app boots fine without Ollama — the embedding client falls back to + # sentence-transformers and the vector store starts empty. /live is the + # dependency-free liveness probe; /health would 503 without Ollama. + run: | + docker run -d --name apollo -p 8000:8000 apollo:ci + for i in $(seq 1 60); do + if curl -fs http://localhost:8000/live > /dev/null; then + echo "alive after ${i} polls" + exit 0 + fi + sleep 2 + done + docker logs apollo + exit 1 + - name: Stop container + if: always() + run: docker stop apollo || true diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1663d10 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,47 @@ +# Apollo — FastAPI backend (portfolio item 38) +# +# Build: docker build -t apollo . +# Run: docker run --rm -p 8000:8000 -v apollo-data:/app/data \ +# -e OLLAMA_BASE_URL=http://host.docker.internal:11434 apollo +# +# The app expects Ollama (and optionally ComfyUI) to run OUTSIDE the container; +# from inside, reach them via host.docker.internal (Docker Desktop) or with +# --network=host on Linux. + +FROM python:3.12-slim + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 + +WORKDIR /app + +# CPU-only torch first, so sentence-transformers does not pull the multi-GB +# CUDA build (same trick as .github/workflows/ci.yml). Runtime deps only — +# ruff/mypy/pytest stay out of the image. +COPY requirements.txt ./ +RUN pip install torch --index-url https://download.pytorch.org/whl/cpu \ + && pip install -r requirements.txt + +# Run as an unprivileged user; /app/data is a volume for runtime state +# (LoRA library, generated images, jobs.json — created at startup). The dir +# must exist in the image owned by appuser: Docker initializes an empty +# volume from the image contents on first run, which preserves ownership. +RUN useradd --create-home appuser \ + && mkdir -p data/loras data/generated \ + && chown -R appuser:appuser /app/data + +USER appuser + +COPY --chown=appuser:appuser . . + +VOLUME ["/app/data"] + +EXPOSE 8000 + +# Liveness check: /live is deliberately dependency-free (Ollama/ComfyUI down +# does not make the API "not started"); /health reports dependency state. +HEALTHCHECK --interval=30s --timeout=5s --start-period=15s \ + CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/live', timeout=4)" || exit 1 + +CMD ["python", "main.py", "--api"] diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..4d79ef5 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,26 @@ +# Apollo — local development stack (portfolio item 40) +# +# docker compose up --build +# +# The API runs in a container; Ollama and ComfyUI run on the HOST and are +# reached via host.docker.internal (provided by Docker Desktop out of the box). +# On Linux add to the service: +# extra_hosts: ["host.docker.internal:host-gateway"] + +services: + apollo: + build: . + image: apollo + ports: + - "8000:8000" + environment: + OLLAMA_BASE_URL: http://host.docker.internal:11434 + COMFYUI_BASE_URL: http://host.docker.internal:8188 + # Point these at host paths if you want the container to see your local + # ComfyUI LoRA folder / ai-toolkit install (forward slashes work): + # COMFYUI_LORA_DIR: C:/ComfyUI/models/loras + volumes: + - apollo-data:/app/data + +volumes: + apollo-data: From caab658c3e5e2fd8f04910626893a5489d266aad Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 09:59:10 +0200 Subject: [PATCH 35/48] Tests: never write into the real data/ folder Services persist under settings.data_dir and some are built at import time, so the suite appended to data/sessions.json on every run until it reached 24 GB and saving it raised MemoryError. conftest now points data_dir at a throwaway temp folder before anything is imported. Co-Authored-By: Claude Opus 5.5 --- tests/conftest.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/conftest.py b/tests/conftest.py index 137540f..0586101 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -11,6 +11,15 @@ if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) +# Every service persists under settings.data_dir, and some are built at import time (before any fixture runs). +# Point it at a throwaway folder first, so the suite never writes into the real data/ folder: that is how +# data/sessions.json grew to 24 GB. Tests that need their own storage still use tmp_settings. +import tempfile # noqa: E402 + +from app.core import config as _config # noqa: E402 + +object.__setattr__(_config.settings, "data_dir", tempfile.mkdtemp(prefix="apollo-test-data-")) + # These files predate the test suite: they are standalone diagnostic scripts # that print at import time and, in several cases, require a live Ollama server. # They are kept (they are useful to run by hand: `python tests/test_endpoints.py`) From d5ba9fb48271694be1282a1ea2f2f7364fd3a8c2 Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 10:32:33 +0200 Subject: [PATCH 36/48] Item 41: docs honesty test (tests/test_docs.py) Checks README.md and every docs/*.md for em/en dashes, backticked repo paths that do not exist (after cutting :line / ::name suffixes), and unclosed mermaid blocks. Keeps passing while those files are still missing. docs/EVAL.md: replaced 16 em dashes with colons/semicolons/commas so the new test passes; README.md needed no changes. Full suite: 425 passed in 84s (junitxml: 0 failures, 0 skipped). --- docs/EVAL.md | 32 ++++++++++----------- tests/test_docs.py | 71 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 16 deletions(-) create mode 100644 tests/test_docs.py diff --git a/docs/EVAL.md b/docs/EVAL.md index 4d134eb..5f3a923 100644 --- a/docs/EVAL.md +++ b/docs/EVAL.md @@ -6,7 +6,7 @@ the chunks that get retrieved actually come from the documents that contain the answer?** The harness is deterministic, dependency-light (no LLM calls), and fast enough to run locally on every retrieval-related change. -Everything lives in [`evals/`](../evals/) — data, code, and generated reports: +Everything lives in [`evals/`](../evals/): data, code, and generated reports. | Path | What it is | |------|------------| @@ -26,15 +26,15 @@ The unit of scoring is the **document**, not the chunk. A question names one or more ground-truth documents (`source_docs`); retrieval returns a ranked list of chunks, and each chunk carries its document id. For a cutoff *k*: -- **recall@k** — fraction of the question's relevant documents present among the +- **recall@k**: fraction of the question's relevant documents present among the top-*k* chunks (each document counts once). Averaged over all questions. -- **MRR** — mean reciprocal rank: for each question, `1 / rank` of the first +- **MRR**: mean reciprocal rank; for each question, `1 / rank` of the first chunk from a relevant document; averaged over all questions. -- **hit_rate@k** — fraction of questions with at least one relevant-document +- **hit_rate@k**: fraction of questions with at least one relevant-document chunk in the top *k*. The cutoff applies to the raw ranked chunk list (repeated chunks occupy slots), -then documents are deduplicated for scoring — exactly how the pipeline consumes +then documents are deduplicated for scoring, exactly how the pipeline consumes results. ## Running it @@ -57,7 +57,7 @@ python -m evals.cli --grid ``` Reports are written to `evals/reports/rag_eval.json` by default; use `--out PATH` -to redirect. Generated reports are **not** committed — they are reproducible from +to redirect. Generated reports are **not** committed; they are reproducible from the corpus, questions, and settings recorded inside each report's `config` block. ### Embedding backend @@ -75,9 +75,9 @@ fallback, the real model name), so a report always tells you what it was made wi service mode; without the flag the service's `RAG_HYBRID` setting applies (default `auto`). The chosen path is recorded as `retrieval_mode` in the report. -- **vector** — pure FAISS similarity search (`query_vector`). -- **keyword** — BM25 keyword index only (no embeddings at query time). -- **auto** — hybrid: both legs run and are fused with reciprocal-rank fusion +- **vector**: pure FAISS similarity search (`query_vector`). +- **keyword**: BM25 keyword index only (no embeddings at query time). +- **auto**: hybrid; both legs run and are fused with reciprocal-rank fusion (`query_hybrid`). ## Report format @@ -85,21 +85,21 @@ service mode; without the flag the service's `RAG_HYBRID` setting applies Single-run reports (`rag_eval.json`) have `schema_version`, a `config` block, an aggregate `summary`, and one entry per question (retrieved + relevant doc ids and per-question metrics). Grid reports carry the same config plus one flat row per -cell. Output is deterministic — no timestamps, floats rounded to four decimals — +cell. Output is deterministic (no timestamps, floats rounded to four decimals), so two runs over identical inputs diff cleanly, which is what the CI regression gate relies on (below). ## Regression gate `tests/test_eval_regression.py` is the CI gate for retrieval quality. It runs -the real service-mode pipeline — production chunking, vector retrieval, top_k=4 -— with the sentence-transformers backend **pinned** (an `OllamaClient` stub that +the real service-mode pipeline (production chunking, vector retrieval, +top_k=4) with the sentence-transformers backend **pinned** (an `OllamaClient` stub that always reports unreachable, so Ollama is never probed and results do not depend on whether it happens to be running), then compares against the committed baseline [`evals/baselines/vector_service.json`](../evals/baselines/vector_service.json): - summary metrics (`mean_recall_at_k`, `mrr`, `hit_rate_at_k`) may improve but - must not drop by more than float noise (tolerance 1e-3 — well below the + must not drop by more than float noise (tolerance 1e-3, well below the granularity of a single question flipping, ~0.02); - no question that had a hit@4 in the baseline may lose it; - the run's backend, retrieval mode, cutoff and production chunking must match @@ -140,7 +140,7 @@ Retrieval modes (service mode, production chunking): | keyword | 0.9896 | 0.9635 | 1.0000 | Reading: the production chunking (800/150) is the best cell of the grid, and all -three retrieval modes hit every question at k=4 on this corpus — the questions +three retrieval modes hit every question at k=4 on this corpus; the questions are close paraphrases of document text, so vectors alone already rank correctly. Hybrid fusion costs a little MRR here but never loses recall; it exists to help where embeddings miss (exact identifiers, code-like tokens). Re-measure after any @@ -154,7 +154,7 @@ numbers before merging. - **Add questions**: append objects to `questions.json` with fields `id`, `question`, `source_docs` (list of corpus stems), and `key_facts`. Ids must be unique, every `source_docs` entry must name an existing document, and both - lists must be non-empty — `load_dataset()` enforces all of this and fails the + lists must be non-empty; `load_dataset()` enforces all of this and fails the run loudly otherwise. Keep questions answerable from the cited documents alone; `key_facts` are for @@ -164,7 +164,7 @@ human review (they are not scored by retrieval metrics). The harness itself is covered by `tests/test_eval_*.py` (dataset validation, metrics math, index building with a deterministic fake embedder, runner and CLI -wiring including grid and hybrid-mode routing) — all of it runs without Ollama or +wiring including grid and hybrid-mode routing). All of it runs without Ollama or a GPU. The one exception in spirit: the regression gate (`test_eval_regression.py`) loads the real MiniLM model on CPU so it measures actual retrieval quality against the committed baseline (see above). \ No newline at end of file diff --git a/tests/test_docs.py b/tests/test_docs.py new file mode 100644 index 0000000..8c275d3 --- /dev/null +++ b/tests/test_docs.py @@ -0,0 +1,71 @@ +"""Keep the docs honest (item 41). + +Reads ``README.md`` and every ``docs/*.md`` that exists, then checks three +things per file: no em or en dash characters, backticked repo paths exist +relative to the repo root, and every mermaid block is closed. The test keeps +working while those files do not exist yet. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +PROJECT_ROOT = Path(__file__).resolve().parent.parent + +PATH_RE = re.compile(r"`((?:app|tests|eval|scripts|workflows|docs)/[^`\s]*)`") + + +def _doc_files() -> list[Path]: + files = [PROJECT_ROOT / "README.md"] + docs_dir = PROJECT_ROOT / "docs" + if docs_dir.is_dir(): + files.extend(sorted(docs_dir.glob("*.md"))) + return [f for f in files if f.is_file()] + + +def _strip_suffix(path: str) -> str: + """Cut a ``:`` or ``::`` suffix off a documented path.""" + if "::" in path: + return path.split("::", 1)[0] + if ":" in path: + return path.split(":", 1)[0] + return path + + +def _problems(doc: Path) -> list[str]: + text = doc.read_text(encoding="utf-8") + lines = text.splitlines() + problems: list[str] = [] + + for lineno, line in enumerate(lines, 1): + if "\u2014" in line: + problems.append(f"line {lineno}: contains an em dash") + if "\u2013" in line: + problems.append(f"line {lineno}: contains an en dash") + + for lineno, line in enumerate(lines, 1): + for match in PATH_RE.finditer(line): + raw = match.group(1) + if any(ch in raw for ch in "<*{"): + continue + path = _strip_suffix(raw) + if not (PROJECT_ROOT / path).exists(): + problems.append(f"line {lineno}: `{raw}` does not exist") + + for lineno, line in enumerate(lines, 1): + if "```mermaid" in line: + closed = any("```" in later for later in lines[lineno:]) + if not closed: + problems.append(f"line {lineno}: mermaid block is never closed") + + return problems + + +def test_docs_are_honest() -> None: + problems = [ + f"{doc.relative_to(PROJECT_ROOT).as_posix()}: {problem}" + for doc in _doc_files() + for problem in _problems(doc) + ] + assert problems == [], "\n".join(problems) From bb2e282fffc6e8f08f7567bf7101bcd21a1a98fb Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 10:40:27 +0200 Subject: [PATCH 37/48] Item 42: ARCHITECTURE.md with module map Intro paragraph plus a 15-row Module/Responsibility table, one sentence per module from its docstring and main class. Two spec paths were stale and are documented as they actually exist: app/services/rag/bm25.py (not keyword.py) and evals/runner.py (there is no app/eval package; the eval harness lives in top-level evals/). Full suite: 425 passed in 85s (junitxml: 0 failures, 0 skipped); test_docs validates every backticked path. --- docs/ARCHITECTURE.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 docs/ARCHITECTURE.md diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..34cfa3f --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,28 @@ +# Architecture + +Apollo is a local FastAPI application for working with documents and images on +your own machine. It has three independent parts: document storage with +retrieval-augmented chat (RAG), image generation through ComfyUI, and LoRA +training through the Ostris AI Toolkit. Each part works without the others; +what they share is configuration, path safety, job tracking, and the API layer +that serves a single-page frontend. + +## Module map + +| Module | Responsibility | +|--------|----------------| +| `app/main.py` | Application entry point: `create_app()` wires settings, CORS, the three API routers, static frontend serving, and startup checks into one FastAPI instance. | +| `app/api/routes.py` | Core endpoints: health probes (`/live`, `/ready`, `/health`), model listing, chat with session history, document upload/list/delete, RAG status and debug query, dashboard data, and the saved-prompt library. | +| `app/api/comfyui_routes.py` | Endpoints for ComfyUI generation, the workflow library, and background job tracking. | +| `app/api/lora_routes.py` | Endpoints for LoRA projects, datasets, captioning, training runs, and the trained-LoRA library. | +| `app/services/rag/service.py` | Orchestrates RAG: owns the persistent vector index under `DATA_DIR/rag` (a document is re-embedded only when its content hash changes), rebuilds the in-memory BM25 index at startup, and answers queries via vector or hybrid retrieval. | +| `app/services/rag/vector_store.py` | Persistent FAISS store for chunks with atomic temp-file saves and a self-describing `meta.json` that refuses to load an index built with a different embedding model. | +| `app/services/rag/embeddings.py` | Embedding client that prefers Ollama and falls back to local sentence-transformers when it is unreachable. | +| `app/services/rag/chunking.py` | Sentence-aware text chunker (default 800 characters, 150 overlap) used by both the app and the eval harness. | +| `app/services/rag/bm25.py` | In-memory Okapi BM25 keyword index (hand-rolled, no new dependency) that complements vectors with exact-term matching for hybrid retrieval. | +| `app/services/rag/fusion.py` | Reciprocal rank fusion of the vector and keyword rankings into one list; a pure function over opaque chunk ids so it needs no score calibration. | +| `app/core/jobs.py` | Stdlib-only background job store (threading plus uuid) shared by ComfyUI generation and LoRA training, deliberately avoiding Redis or Celery. | +| `app/services/comfyui_service.py` | ComfyUI orchestration: on-disk workflow library with per-workflow input mappings (no hardcoded node ids), input injection, and generation jobs. | +| `app/services/lora_training_service.py` | Treats the Ostris AI Toolkit strictly as an external process: writes a training config (verified against v0.12.26) and runs its `run.py`. | +| `app/services/dataset_validation.py` | Dataset quality control on bytes already on disk (no network): decodability, resolution sanity, exact and near-duplicate detection, and a per-image quality score. | +| `evals/runner.py` | Runs every question in the eval dataset through a built index or a live RAGService with an injected embedder, producing one scored result per question. | From 175ce8ef9fd8580662ccc27f70e1cd4c6cd4d52c Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 10:49:50 +0200 Subject: [PATCH 38/48] Item 43: ARCHITECTURE.md request flows Two sections with mermaid diagrams, every function name verified against the code first: 'Chat with documents' (sequenceDiagram browser -> chat route -> RAGService.query -> VectorStore.search and KeywordIndex.search when RAG_HYBRID includes the keyword leg -> LLMService.chat) and 'Document upload' (flowchart POST /documents/upload through extract_text, DocumentService.store_document, chunk_text, EmbeddingClient.embed_batch, VectorStore.add plus the OllamaServiceError rollback). Five numbered lines under each diagram with backticked file paths. Full suite: 425 passed in 85s (junitxml: 0 failures, 0 skipped); test_docs validates the mermaid blocks and every path. --- docs/ARCHITECTURE.md | 66 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 34cfa3f..ada0026 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -26,3 +26,69 @@ that serves a single-page frontend. | `app/services/lora_training_service.py` | Treats the Ostris AI Toolkit strictly as an external process: writes a training config (verified against v0.12.26) and runs its `run.py`. | | `app/services/dataset_validation.py` | Dataset quality control on bytes already on disk (no network): decodability, resolution sanity, exact and near-duplicate detection, and a per-image quality score. | | `evals/runner.py` | Runs every question in the eval dataset through a built index or a live RAGService with an injected embedder, producing one scored result per question. | + +## Chat with documents + +```mermaid +sequenceDiagram + participant B as Browser + participant C as chat route + participant M as MemoryService + participant Q as RAGService.query + participant E as EmbeddingClient.embed + participant V as VectorStore.search + participant K as KeywordIndex.search + participant L as LLMService.chat + + B->>C: POST /chat (prompt, session_id, use_documents) + C->>M: format_history_for_prompt(session_id) + alt use_documents is on + C->>Q: query(prompt) + Q->>E: embed(question) + E-->>Q: query vector + Q->>V: search(query_embedding, top_k) + V-->>Q: ranked chunks + opt RAG_HYBRID includes the keyword leg + Q->>K: search(question, top_k) + K-->>Q: keyword-ranked chunks + Note over Q: reciprocal_rank_fuse merges both rankings + end + end + C->>M: add_message(session_id, user message) + C->>L: chat(full_prompt, model) + L-->>C: response text + C->>M: add_message(session_id, assistant reply) + C-->>B: ChatResponse (response, session_id) +``` + +1. The `chat` route in `app/api/routes.py` loads the session history and, when `use_documents` is set, calls `RAGService.query` with the user's prompt. +2. `query` picks the retrieval mode from `RAG_HYBRID`: vector only, keyword only, or hybrid (`app/services/rag/service.py`). +3. The vector leg embeds the question via `EmbeddingClient.embed` (Ollama first, sentence-transformers fallback) and ranks chunks with `VectorStore.search` (`app/services/rag/embeddings.py`, `app/services/rag/vector_store.py`). +4. When the keyword leg is active, `KeywordIndex.search` scores the same chunks and `reciprocal_rank_fuse` merges the two rankings into one list (`app/services/rag/bm25.py`, `app/services/rag/fusion.py`). +5. The winning chunks are formatted by `format_context`, folded into the system prompt alongside history, sent to Ollama via `LLMService.chat`, and both turns are stored in session memory (`app/api/routes.py`). + +## Document upload + +```mermaid +flowchart TD + A["POST /documents/upload (upload_document)"] --> B{"extension in SUPPORTED_EXTENSIONS?"} + B -- no --> E1["400: unsupported file type"] + B -- yes --> C["extract_text(temp_path, filename)"] + C --> D["DocumentService.store_document(text, source) -> doc_id"] + D --> F{"is_indexed_current(doc_id, text)?"} + F -- "yes, unchanged" --> G["add_document returns 0 chunks (no re-embed)"] + F -- no --> H["drop stale data: VectorStore.remove_by_doc_id and KeywordIndex.remove_by_doc_id"] + H --> I["chunk_text(text, chunk_size, overlap)"] + I --> J["EmbeddingClient.embed_batch(chunks)"] + J --> K["VectorStore.add(embeddings, stored_chunks) and KeywordIndex.add_chunks(stored_chunks)"] + K --> L["_save: VectorStore.save writes index.faiss, chunks.json and meta.json under DATA_DIR/rag"] + G --> M["DocumentResponse (doc_id, filename)"] + L --> M + J -. OllamaServiceError .-> N["rollback: DocumentService.delete_document(doc_id), re-raise as HTTP error"] +``` + +1. `upload_document` in `app/api/routes.py` checks the extension against SUPPORTED_EXTENSIONS and writes the upload to a temp file before touching any service. +2. `extract_text` pulls plain text out of .txt, .pdf or .docx bytes (`app/services/rag/ingestion.py`). +3. `DocumentService.store_document` persists the document record and returns its id; if indexing then fails, that record is deleted again as a rollback (`app/services/document_service.py`). +4. `RAGService.add_document` skips unchanged content by hash, drops stale vectors for the doc, splits text with `chunk_text`, embeds it with `EmbeddingClient.embed_batch`, and appends to both stores (`app/services/rag/service.py`, `app/services/rag/chunking.py`, `app/services/rag/embeddings.py`). +5. `_save` flushes the FAISS index plus chunks.json and meta.json atomically under DATA_DIR/rag, so a restart resumes without re-embedding (`app/services/rag/vector_store.py`). From 754757bc69d0d4ae41ee02281c625972d75ce8a7 Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 11:13:25 +0200 Subject: [PATCH 39/48] Item 44: ARCHITECTURE.md state and failures --- docs/ARCHITECTURE.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ada0026..a081b5b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -92,3 +92,38 @@ flowchart TD 3. `DocumentService.store_document` persists the document record and returns its id; if indexing then fails, that record is deleted again as a rollback (`app/services/document_service.py`). 4. `RAGService.add_document` skips unchanged content by hash, drops stale vectors for the doc, splits text with `chunk_text`, embeds it with `EmbeddingClient.embed_batch`, and appends to both stores (`app/services/rag/service.py`, `app/services/rag/chunking.py`, `app/services/rag/embeddings.py`). 5. `_save` flushes the FAISS index plus chunks.json and meta.json atomically under DATA_DIR/rag, so a restart resumes without re-embedding (`app/services/rag/vector_store.py`). + +## What is stored where + +Everything persists under `data/`, which is created on first use. Nothing leaves +the machine except calls to Ollama or ComfyUI that you pointed it at. + +| Path | What | Written by | +|------|------|------------| +| data/documents.json | Uploaded document records (id, text, source) | DocumentService (`app/services/document_service.py`) via JsonPersist | +| data/sessions.json | Chat sessions and messages (last 50 sessions, last 200 messages each) | MemoryService (`app/services/memory_service.py`) via JsonPersist | +| data/jobs.json | The last 200 background jobs for ComfyUI generation and LoRA training | JobStore._save (`app/core/jobs.py`) | +| data/rag/index.faiss | The FAISS vector index of all document chunks | VectorStore.save (`app/services/rag/vector_store.py`) | +| data/rag/chunks.json | Chunk text and metadata, one record per vector row | VectorStore.save (`app/services/rag/vector_store.py`) | +| data/rag/meta.json | Index version, embedding model name, dimension and chunk count; a mismatch at load time is what triggers quarantine | VectorStore.save (`app/services/rag/vector_store.py`) | +| data/loras// | One folder per LoRA project: project.json, dataset images with captions, config/training.yml, trained .safetensors | LoRAProjectService (`app/services/lora_dataset_service.py`); training config and output written by LoRATrainingService (`app/services/lora_training_service.py`) | +| data/generated/ | Generated images plus a provenance sidecar .json next to each one (workflow, seed, params) | ComfyUIService._save_outputs and _write_provenance (`app/services/comfyui_service.py`) | + +## When something is down + +Each external dependency can be missing or broken without taking the rest of +the app down. Every row names the function that handles it. + +| Situation | What the user sees | Code | +|-----------|--------------------|------| +| Ollama is down while chatting | HTTP 503 with a safe message; embedding calls do not fail, they fall back silently to local sentence-transformers | `OllamaClient._request` raises OllamaServiceError (503); the chat route converts it via to_http_exception (`app/clients/ollama_client.py`, `app/api/routes.py`) | +| The embedding model is missing (nomic-embed-text not pulled) | RAG keeps working on the local backend; if sentence-transformers is also absent, a 503 with an install hint appears and /rag/status reports which backend is active | `EmbeddingClient.embed_batch` falls back to `_embed_with_sentence_transformers`, which raises that 503 (`app/services/rag/embeddings.py`) | +| ComfyUI is down | The status card shows disconnected; queued generation jobs appear as failed with the connection error message | `ComfyUIService.status` reports connected false plus the error; `JobStore._run` catches every worker exception and records it on the job (`app/services/comfyui_service.py`, `app/core/jobs.py`) | +| AI Toolkit is not configured | HTTP 503 telling you to set AI_TOOLKIT_PATH and AI_TOOLKIT_PYTHON in your .env file | `AIToolkitProcess.start` raises AIToolkitError before launching anything (`app/services/lora_training_service.py`) | +| The vector index is corrupted or built with a different model | The app boots normally; /rag/status shows 0 chunks until documents are re-uploaded, and the old files sit in data/rag/quarantined/ for inspection | `RAGService._load_store` catches IndexIncompatibleError and calls `_quarantine_files`, which moves index.faiss, chunks.json and meta.json out of the way (`app/services/rag/service.py`) | +| The server restarts while a job is running | Those jobs appear in the list as failed with "Interrupted by application restart" | `JobStore._load` marks RUNNING or QUEUED jobs as failed at startup (`app/core/jobs.py`) | + +## More + +- [EVAL.md](EVAL.md): how the RAG evals and their regression gate work. +- [DESIGN.md](DESIGN.md): design notes, not written yet; this link is a placeholder for it. From f617877cf5ce9521327b13ff5d8f17667263d5eb Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 12:36:07 +0200 Subject: [PATCH 40/48] Item 45: DESIGN.md opening and how a question becomes an answer --- docs/DESIGN.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 docs/DESIGN.md diff --git a/docs/DESIGN.md b/docs/DESIGN.md new file mode 100644 index 0000000..44b1c76 --- /dev/null +++ b/docs/DESIGN.md @@ -0,0 +1,23 @@ +# Design decisions and trade-offs + +Why Apollo is built the way it is, where each decision lives in the code, and what it costs. + +## In one minute + +Apollo is a local AI workspace: you upload documents and ask questions about them, generate images through +ComfyUI, and build and train LoRA models, all on your own machine with no cloud API. The part I care most about is +retrieval. It is measured with a small evaluation set instead of judged by feel, and changes such as hybrid search +are only switched on when the numbers support them. The rest is plain engineering: a FastAPI service layer, a +persistent FAISS index that survives restarts and corruption, background jobs that survive a restart, and tests +that run without Ollama or ComfyUI. + +## How a question becomes an answer + +1. The request arrives at `chat()` in `app/api/routes.py`, where FastAPI validates the body as a `ChatRequest` (session id, prompt, optional model and template id, and the use_documents flag). +2. If a template id was sent, `apply_template()` in `app/services/prompt_service.py` expands the stored template with the user's message; otherwise the raw message is used unchanged. +3. `format_history_for_prompt()` in `app/services/memory_service.py` renders the session's persisted messages as USER:/ASSISTANT: lines for prompt injection. +4. When use_documents is on, `query()` in `app/services/rag/service.py` retrieves chunks. In the default auto mode it embeds the question with `embed()` in `app/services/rag/embeddings.py`, searches the FAISS index through `search()` in `app/services/rag/vector_store.py`, scores the same chunks with BM25 via `search()` in `app/services/rag/bm25.py`, and merges both rankings with `reciprocal_rank_fuse()` (k=60) in `app/services/rag/fusion.py`. +5. `format_context()` in `app/services/rag/service.py` renders the winning chunks into a CONTEXT block, and `_build_system_prompt()` in `app/api/routes.py` assembles system instructions (the "default" template from `get_prompt_by_name()`, or a fallback string), context, history, and question. +6. The user's message is stored before the model call: `add_message()` in `app/services/memory_service.py` appends it to the session list and writes it through `save()` in `app/core/persistence.py` to data/sessions.json. +7. `LLMService.chat()` in `app/services/llm_service.py` sends the assembled prompt as a single user message through `chat_completion()` in `app/clients/ollama_client.py` to Ollama's OpenAI-compatible /v1/chat/completions endpoint and extracts choices[0].message.content from the reply. +8. The assistant's reply is stored with a second `add_message()` call (role "assistant"), which persists it the same way; the endpoint then returns a ChatResponse carrying the text and session id. From e78073a3047286127cbf068a3d5df88a7280f876 Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 12:41:49 +0200 Subject: [PATCH 41/48] Item 46: RAG design decisions --- docs/DESIGN.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 44b1c76..749622f 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -21,3 +21,40 @@ that run without Ollama or ComfyUI. 6. The user's message is stored before the model call: `add_message()` in `app/services/memory_service.py` appends it to the session list and writes it through `save()` in `app/core/persistence.py` to data/sessions.json. 7. `LLMService.chat()` in `app/services/llm_service.py` sends the assembled prompt as a single user message through `chat_completion()` in `app/clients/ollama_client.py` to Ollama's OpenAI-compatible /v1/chat/completions endpoint and extracts choices[0].message.content from the reply. 8. The assistant's reply is stored with a second `add_message()` call (role "assistant"), which persists it the same way; the endpoint then returns a ChatResponse carrying the text and session id. + +## Decisions + +### 1. A flat FAISS index on disk, not a vector database server + +**Decision:** Chunks live in a single `faiss.IndexFlatIP` over L2-normalized float32 vectors, persisted as three files under DATA_DIR/rag: index.faiss, chunks.json (one metadata record per row), and meta.json. +**Why:** A local single-user app does not need a server process to run alongside it, and with normalized vectors the inner product is cosine similarity, so the flat index answers exactly rather than approximately. +**Trade-off:** Search scans every chunk in memory each time, which is fine for thousands of chunks but not millions; there is no concurrent writing, replication, or query API beyond what this app needs. +**Where:** `app/services/rag/vector_store.py` (`VectorStore`, `_rebuild()`); normalization in `app/services/rag/embeddings.py` (`_normalize()`). + +### 2. Ollama embeddings with a sentence-transformers fallback + +**Decision:** `embed_batch()` tries Ollama's embed endpoint first (default model nomic-embed-text) and, when Ollama is unreachable, falls back to a local sentence-transformers model (default all-MiniLM-L6-v2), recording which backend served the batch. +**Why:** Everything stays on one machine, and retrieval keeps working with an installed local model instead of failing whenever Ollama is down or still starting up. +**Trade-off:** The two backends produce different vector spaces, so an index built under one cannot be searched under the other; the store refuses to mix them by quarantining the old index (decision 4). +**Where:** `app/services/rag/embeddings.py` (`EmbeddingClient.embed_batch()`, `_embed_with_ollama()`, `_embed_with_sentence_transformers()`); defaults in `app/core/config.py`. + +### 3. Incremental indexing by content hash and model + +**Decision:** Before embedding, `add_document()` compares the SHA-256 of the document text and the embedding model against a per-document version record; when both match it returns without touching the index, and changed documents have their stale chunks dropped first so two versions never coexist. +**Why:** Re-uploading or restarting should not re-embed an unchanged knowledge base, and hashing the text rather than the file time means only real edits trigger work. +**Trade-off:** A document is one unit: any edit re-embeds all of its chunks, and the version records are derived from chunk metadata at startup, so they cannot be inspected independently of the index. +**Where:** `app/services/rag/service.py` (`RAGService.add_document()`, `is_indexed_current()`, `_rebuild_version_map()`), hash in `content_hash()`. + +### 4. Index metadata and quarantine instead of deletion + +**Decision:** meta.json records the index version, embedding model, dimension, vector count, and update time; loading an index whose model or dimension no longer matches raises `IndexIncompatibleError`, and an unreadable FAISS file is treated as corruption. In both cases the three files are moved into the `quarantined` subdirectory with a timestamp appended to their names rather than deleted. +**Why:** Mixing vectors from different models would silently produce garbage answers, and keeping the old files means a bad upgrade can be inspected or restored instead of being thrown away. +**Trade-off:** After quarantine the index is empty, so retrieval returns nothing until documents are uploaded again; quarantined copies also accumulate in DATA_DIR/rag/quarantined until deleted by hand. +**Where:** `app/services/rag/vector_store.py` (`IndexMeta`, `VectorStore.__init__()`); `app/services/rag/service.py` (`_load_store()`, `_quarantine_files()`). + +### 5. Sentence-boundary chunking with character overlap + +**Decision:** `chunk_text()` splits text on sentence-ending punctuation, packs sentences into chunks of about 800 characters, and carries the trailing sentences that fit within a 150-character window over into the next chunk; text without sentence boundaries falls back to fixed windows split at spaces. +**Why:** Chunks that end mid-sentence hand the model broken context, and overlap keeps material straddling a boundary available in both neighbouring chunks. +**Trade-off:** The size target is approximate because one long sentence can push a chunk past it; the overlap also duplicates text, so the index holds more characters than the source documents contain. +**Where:** `app/services/rag/chunking.py` (`chunk_text()`, `_overlap_tail()`, `_chunk_by_characters()`); defaults in `app/core/config.py` (RAG_CHUNK_SIZE, RAG_CHUNK_OVERLAP). From 6493985f62e480e7582dde40f4c96a3f2924189a Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 13:02:17 +0200 Subject: [PATCH 42/48] Item 47: DESIGN.md decisions 6 to 10 --- docs/DESIGN.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 749622f..44c7ec5 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -58,3 +58,38 @@ that run without Ollama or ComfyUI. **Why:** Chunks that end mid-sentence hand the model broken context, and overlap keeps material straddling a boundary available in both neighbouring chunks. **Trade-off:** The size target is approximate because one long sentence can push a chunk past it; the overlap also duplicates text, so the index holds more characters than the source documents contain. **Where:** `app/services/rag/chunking.py` (`chunk_text()`, `_overlap_tail()`, `_chunk_by_characters()`); defaults in `app/core/config.py` (RAG_CHUNK_SIZE, RAG_CHUNK_OVERLAP). + +### 6. Hybrid retrieval behind a flag, judged by the eval + +**Decision:** `query()` follows RAG_HYBRID: in the default auto mode it fuses vector similarity with BM25 keyword ranking via reciprocal rank fusion (k=60), while vector and keyword modes use only that single signal; hybrid degrades to plain vector search when no keyword index is available. +**Why:** Embeddings generalize across paraphrase but miss distinctive terms like error codes, and rank fusion combines the two rankings without calibrating scores that live on incompatible scales. +**Trade-off:** Every auto query pays for an embedding call and a BM25 pass over all chunks, and the fused score is a rank statistic rather than a similarity, so it cannot be compared across queries or used as a threshold. +**Where:** `app/services/rag/service.py` (`RAGService.query()`, `query_hybrid()`); `app/services/rag/bm25.py` (`KeywordIndex`); `app/services/rag/fusion.py` (`reciprocal_rank_fuse()`); the eval harness in `evals/cli.py`. + +### 7. Background jobs in a thread pool, persisted as JSON + +**Decision:** `JobStore` runs work on a small ThreadPoolExecutor (two workers by default) and persists every job to a JSON file; on restart, any job still queued or running is marked failed with "Interrupted by application restart" rather than left spinning. +**Why:** A local single-user app does not need Redis or Celery, and two workers matches reality: ComfyUI and AI-Toolkit both want the whole GPU at once. +**Trade-off:** The file keeps only the most recent 200 jobs, and cancellation is cooperative, so a worker that never checks `is_cancelled()` runs to completion anyway. +**Where:** `app/core/jobs.py` (`JobStore`, `_load()`, `_run()`, `cancel()`). + +### 8. ComfyUI workflows as API-format JSON plus a field map + +**Decision:** Each workflow is two files on disk: `workflows/.json`, the raw ComfyUI API-format export, and `.map.json`, which names the node id and field each logical input (prompt, seed, steps, cfg, ...) writes to; Python never hardcodes a node id. +**Why:** A workflow can be swapped or extended by editing JSON without touching code, and the mapping keeps the UI controls in sync with whatever nodes the export contains. +**Trade-off:** The map must be written by hand for each new workflow, and only the logical inputs the service knows about are editable through it; the rest of the graph is sent to ComfyUI untouched. +**Where:** `app/services/comfyui_service.py` (workflow loading and input injection); `workflows/sdxl_txt2img.map.json`. + +### 9. Argument-list subprocesses and one traversal guard + +**Decision:** External processes are launched with fixed argument lists and no shell, and every path built from browser input goes through `safe_join` or `sanitize_filename`, which refuse absolute paths, drive letters, backslashes, and anything that resolves outside the data root. +**Why:** A command line assembled by string concatenation is a shell-injection hole, and one guard at the boundary means no other code in the app may concatenate user strings onto directories. +**Trade-off:** `safe_join` refuses backslash components on every platform, so Windows-style names cannot be used even where they would be harmless; uploads are limited to the extension sets the guards allow (images for generation, .safetensors for LoRA). +**Where:** `app/core/paths.py` (`safe_join`, `sanitize_filename`, `validate_image_upload`); `app/services/lora_training_service.py` (training subprocess launch). + +### 10. An access token for the public tunnel + +**Decision:** When APOLLO_ACCESS_TOKEN is set, every request needs that token in the X-Apollo-Token header or a cookie, except /live and /health which stay open for probes; opening the link with ?token=... once sets an HttpOnly cookie for 30 days. Unset (a plain local run) leaves Apollo fully open. +**Why:** launcher.py publishes Apollo through a public Cloudflare tunnel whose traffic reaches uvicorn from localhost, so "local" proves nothing and the token is the only gate between the dashboard and the internet. +**Trade-off:** The cookie lives for 30 days on any machine that opens the link, and there are no per-user accounts or revocation: losing the token means regenerating it in .env. +**Where:** `app/main.py` (`require_access_token`). From 998248330f5e123f35050eaa342e57605aa08bac Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 13:19:26 +0200 Subject: [PATCH 43/48] Item 48: DESIGN.md questions people ask --- docs/DESIGN.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 44c7ec5..83bfd7b 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -93,3 +93,29 @@ that run without Ollama or ComfyUI. **Why:** launcher.py publishes Apollo through a public Cloudflare tunnel whose traffic reaches uvicorn from localhost, so "local" proves nothing and the token is the only gate between the dashboard and the internet. **Trade-off:** The cookie lives for 30 days on any machine that opens the link, and there are no per-user accounts or revocation: losing the token means regenerating it in .env. **Where:** `app/main.py` (`require_access_token`). + +## Questions people ask + +### Why FAISS and not Chroma, pgvector or Qdrant? + +I chose a flat FAISS index persisted as three files under DATA_DIR/rag because this is a single-user local app and I do not want to run a database server alongside it. With L2-normalized vectors the inner product equals cosine similarity, so `faiss.IndexFlatIP` in `app/services/rag/vector_store.py` answers exactly rather than approximately. Chroma or Qdrant would add an embedded or remote engine with no benefit at this scale, and pgvector would mean a Postgres process for one user's documents. The cost is that every query scans all chunks, which I accept while the index stays in the thousands of chunks (see "How would this work with a million chunks?"). + +### How do you know the retrieval is any good? + +I score it against a committed set of 48 questions over 12 documents, run by `python -m evals.cli` in `evals/cli.py`, with document-level recall@k, MRR and hit-rate from `evals/metrics.py`. With production chunking (800/150) and the MiniLM fallback backend, vector retrieval hits every question at k=4: hit_rate@4 = 1.0, MRR = 0.9757, recall@4 = 0.9896. `tests/test_eval_regression.py` re-runs that pipeline in CI and fails if a summary metric drops by more than 1e-3 or a question loses its hit against the committed baseline in `evals/baselines/vector_service.json`. So "good" is a number I can diff, not a feeling. + +### What happens when the embedding model changes? + +meta.json records which model and dimension built the index, so `VectorStore.__init__()` in `app/services/rag/vector_store.py` raises `IndexIncompatibleError` on a mismatch instead of scoring vectors from different spaces against each other. The three index files are then moved into DATA_DIR/rag/quarantined with timestamps rather than deleted (decision 4), and the version map in `app/services/rag/service.py` keys documents by content hash plus model, so nothing is re-embedded until it changes again. In practice: switch models, upload your documents once, done; until then retrieval returns an empty index instead of wrong answers. + +### How do you avoid embedding the same document twice? + +`add_document()` in `app/services/rag/service.py` hashes the document text with SHA-256 and compares that hash, plus the embedding model name, against a per-document version record before it embeds anything. When both match it returns without touching the index, so re-uploading an unchanged file is free; when they differ, the stale chunks are dropped first so two versions of one document never coexist in the ranking. The records are rebuilt from chunk metadata at startup (`_rebuild_version_map()`), which means the check survives a restart with no extra state to corrupt. + +### Why is hybrid search not the default, or why is it? + +It is the default here: RAG_HYBRID in `app/core/config.py` defaults to auto, and `query()` in `app/services/rag/service.py` fuses vector and BM25 rankings with reciprocal rank fusion. The eval shows that on this corpus all three retrieval modes hit every question at k=4 (hit_rate@4 = 1.0), so fusion buys nothing here: plain vector scores MRR 0.9757 while auto fusion scores 0.9514, a small cost I accept because BM25 covers exact identifiers and code-like tokens where embeddings miss. The flag exists precisely because the numbers are this close; set RAG_HYBRID to vector or keyword if you want the other ranking back. + +### How would this work with a million chunks? + +What breaks first is the flat index: `faiss.IndexFlatIP` in `app/services/rag/vector_store.py` is exact but linear, so every query scans all one million vectors and latency grows in proportion to the corpus. I would move to an approximate index such as IVF or HNSW that trades a little recall for much shorter search time, batch the embedding calls harder (they already go through `embed_batch()`), and stop loading chunks.json whole into memory at startup. None of that was built: the indexed corpus here is 46 chunks, and I would not add approximate-search machinery until the numbers say I need it. From 3bcbfce9d388fec0b93f4f23f616071ccac8eff3 Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 13:24:00 +0200 Subject: [PATCH 44/48] Item 49: DESIGN.md numbers and weaknesses --- docs/DESIGN.md | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 83bfd7b..8ed0c61 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -94,6 +94,45 @@ that run without Ollama or ComfyUI. **Trade-off:** The cookie lives for 30 days on any machine that opens the link, and there are no per-user accounts or revocation: losing the token means regenerating it in .env. **Where:** `app/main.py` (`require_access_token`). +## Questions about numbers and weaknesses + +### How do you test code that depends on Ollama or ComfyUI without running them? + +I never start either service; the suite asserts what the app does when they are absent: errors, 503s, fallbacks. An autouse fixture in `tests/conftest.py` shrinks every external timeout to a few tenths of a second so probes at nonexistent services fail fast instead of hanging for seconds. Where a test needs success rather than failure it injects fakes: the deterministic sha256-seeded embedder from `tests/fakes.py`, StubClient and monkeypatched requests.request in `tests/test_comfyui.py`, or an OllamaClient stub that always reports unreachable in `tests/test_eval_regression.py`. Storage is isolated the same way, with tmp_settings pointing every writable storage root at a temp dir. + +### What happens to jobs when the server restarts mid-run? + +`JobStore` in `app/core/jobs.py` persists every job to a JSON file, so on startup it can see what was still queued or running. Those jobs are marked failed with "Interrupted by application restart" instead of being re-run or left spinning, because I do not know how far their side effects (a ComfyUI prompt, a training run) already went. The user sees the failure in the job list and can resubmit; nothing is retried silently. + +### How is the app protected when it is exposed through a tunnel? + +When APOLLO_ACCESS_TOKEN is set, `require_access_token` in `app/main.py` rejects every request that does not carry the token in the X-Apollo-Token header or cookie, with only /live and /health left open for probes. Opening the link once with ?token=... sets an HttpOnly cookie valid for 30 days so the browser stops asking. I chose a single shared token over accounts because this is one user's machine; the trade-off is that losing the token means regenerating it in .env, and there is no per-user revocation. + +### What would you change about chunking? + +I would keep the defaults: 800/150 was the best cell of the chunking grid on recall@4 (0.9896) and MRR (0.9757), so no number tells me to move it. What I would change is the boundary rule in `app/services/rag/chunking.py`: one long sentence can push a chunk well past its 800-character target, and I would cap that with a hard split instead of letting size drift. I would also like per-chunk version records rather than document-level ones, so editing one paragraph does not re-embed every other chunk in the same document. + +### How is a LoRA training config checked against hardware before it starts? + +`preflight()` in `app/services/lora_training_service.py` first checks the dataset (images present, captions written, base model set), then hands the options to `advise()` in `app/services/training_preflight.py`, which estimates VRAM from a resolution bucket (6 to 22 GB at batch 1) plus about 1.2 GB per extra batch slot and compares it against the GPU that `detect_hardware` in `app/services/hardware.py` finds. The report classifies the config as ok, heavy, risky or unsupported; only blocked or unsupported set can_proceed to false. I made it advisory on purpose: VRAM use depends on model internals no external estimator can see, so a "risky" verdict warns but never stops a run. + +### Where are the weak spots in this codebase? + +The flat index scans every chunk per query, so latency grows linearly with corpus size and I would hit a wall somewhere past tens of thousands of chunks (`app/services/rag/vector_store.py`). The two embedding backends produce different vector spaces, so switching models quarantines the whole index and retrieval returns nothing until every document is re-uploaded (`app/services/rag/embeddings.py`). Version records are per-document, so editing one paragraph re-embeds all of that document's chunks (`app/services/rag/service.py`), and the fused hybrid score is a rank statistic I cannot compare across queries or use as a threshold (`app/services/rag/fusion.py`). The job store also keeps only its 200 most recent jobs, so old history disappears on its own (`app/core/jobs.py`). + +## Numbers + +| What | Value | +|------|-------| +| Tests | 425 passed (latest full run) | +| Coverage | TOTAL 81% (`pytest --cov=app`) | +| Lint and type check | ruff clean; mypy clean | +| Retrieval MiniLM hit@4 | 1.0000 (48 questions, k=4, production chunking) | +| Retrieval MiniLM MRR | 0.9757 | +| Hashing hit@4 | 0.2292 (sha256-seeded unit vectors, same harness) | +| CI gate | one-sided: metrics may improve but not drop by more than 1e-3, and no question may lose its hit@4 against `evals/baselines/vector_service.json` | + + ## Questions people ask ### Why FAISS and not Chroma, pgvector or Qdrant? From 421f54667de9a348e81ef05d7734aee4d21d8760 Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 13:27:28 +0200 Subject: [PATCH 45/48] Item 50: README engineering section, Docker run and RAG_HYBRID --- README.md | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b914aea..7c7d749 100644 --- a/README.md +++ b/README.md @@ -176,6 +176,14 @@ or process adapter. Nothing in the document pipeline imports ComfyUI code. --- +## Engineering + +- **Tested:** the suite runs without Ollama or ComfyUI (425 tests). CI runs lint (ruff), a type check (mypy), the tests with coverage reporting, a retrieval regression gate and a Docker build. +- **Measured:** retrieval is scored on 48 questions: MiniLM hit@4 1.0000, MRR 0.9757. See [docs/EVAL.md](docs/EVAL.md). +- **Documented:** [architecture](docs/ARCHITECTURE.md) and [design decisions and trade-offs](docs/DESIGN.md). + +--- + ## Setup ### Prerequisites @@ -235,6 +243,14 @@ Run uvicorn directly without the variable and Apollo stays open, as a local tool python -m uvicorn app.main:app --host 0.0.0.0 --port 8000 ``` +**Docker:** + +```bash +docker compose up --build +``` + +The image is CPU-only. Ollama keeps running on the host; the container reaches it at `host.docker.internal`. + **Interactive CLI (legacy agent):** ```bash @@ -258,6 +274,7 @@ python main.py --api | `RAG_CHUNK_SIZE` | `800` | Characters per chunk | | `RAG_CHUNK_OVERLAP` | `150` | Overlap between chunks | | `RAG_TOP_K` | `4` | Retrieved chunks per query | +| `RAG_HYBRID` | `auto` | Retrieval mode; auto fuses BM25 and vector with reciprocal rank fusion (also accepts vector or keyword) | | `OLLAMA_VISION_MODEL` | `llava` | Vision model for AI dataset captions | | `COMFYUI_BASE_URL` | `http://127.0.0.1:8188` | Local ComfyUI instance | | `COMFYUI_WORKFLOW_DIR` | `./workflows` | Where workflow JSON + mappings are stored | @@ -474,7 +491,7 @@ Apollo/ │ ├── smoke_preflight.py # Live training-preflight demo │ └── smoke_rag_persistence.py # Restart-survival verification for the index ├── workflows/ # ComfyUI workflows + node-input mappings -├── tests/ # Test suite (261 tests) + legacy debug scripts +├── tests/ # Test suite (425 tests) + legacy debug scripts ├── data/ # Documents, sessions, jobs, LoRA projects, generated images, rag index ├── images/ # Feature demo GIFs (README showcase) ├── launcher.py # One-command startup (API + tunnel) @@ -648,7 +665,7 @@ Local-first does not mean unguarded: - Documents, sessions, jobs, LoRA projects, workflows and generated images all persist on disk - Upload debug logs appear in the server console: `[UPLOAD] filename`, `extracted chars`, `rag chunks indexed` - Utility scripts: `python scripts/verify_system.py`, `python scripts/diagnostics_ollama.py` -- Run the tests with `python -m pytest` (261 tests); stress tests: `pytest tests/test_stress.py -m slow` +- Run the tests with `python -m pytest` (425 tests); stress tests: `pytest tests/test_stress.py -m slow` - Log prefixes: `[COMFYUI]`, `[COMFYUI JOB]`, `[LORA]`, `[LORA TRAINING]`, `[DATASET]`, `[RAG]`, `[RUN HISTORY]` - `tests/` also contains standalone diagnostic scripts (`test_endpoints.py`, `test_ollama_detailed.py`, …) that predate the suite. They print at import time From 1a5cdc22a5c027360b279a89c08ea1c92a9375a3 Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 13:27:52 +0200 Subject: [PATCH 46/48] Item 51: CHANGELOG v1.1.0 entry --- CHANGELOG.MD | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/CHANGELOG.MD b/CHANGELOG.MD index 96d5966..50a6603 100644 --- a/CHANGELOG.MD +++ b/CHANGELOG.MD @@ -1,5 +1,13 @@ # Changelog +## v1.1.0 +- Retrieval evaluation: 48 questions, hit@k and MRR, a hashing baseline and MiniLM (`python -m evals.cli`) +- Optional hybrid retrieval: BM25 plus reciprocal rank fusion behind `RAG_HYBRID` +- CI: ruff, mypy, coverage reporting (TOTAL 81%), retrieval regression gate, Docker build +- Dockerfile and docker-compose.yml (CPU-only image) +- Test suite runs in about 89 seconds instead of 323 (network probes fail fast in tests) +- docs/ARCHITECTURE.md, docs/DESIGN.md and docs/EVAL.md + ## v1.0.0 - Initial release of AI Document Agent - Added RAG pipeline with FAISS From 1505e55608daba834c9061516a632bf87d130c0d Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 13:34:24 +0200 Subject: [PATCH 47/48] Item 49 follow-up: DESIGN.md question 12 --- docs/DESIGN.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 8ed0c61..cf69e53 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -116,6 +116,10 @@ I would keep the defaults: 800/150 was the best cell of the chunking grid on rec `preflight()` in `app/services/lora_training_service.py` first checks the dataset (images present, captions written, base model set), then hands the options to `advise()` in `app/services/training_preflight.py`, which estimates VRAM from a resolution bucket (6 to 22 GB at batch 1) plus about 1.2 GB per extra batch slot and compares it against the GPU that `detect_hardware` in `app/services/hardware.py` finds. The report classifies the config as ok, heavy, risky or unsupported; only blocked or unsupported set can_proceed to false. I made it advisory on purpose: VRAM use depends on model internals no external estimator can see, so a "risky" verdict warns but never stops a run. +### What would you change if you started over? + +The retrieval core I would keep as it is: the flat index in `app/services/rag/vector_store.py`, content-hash versioning and quarantine are doing their jobs at this scale. Three things I would do differently. First, build the evaluation harness before the first feature: the 48-question set now decides what ships through `tests/test_eval_regression.py`, but it arrived after the pipeline existed, so early choices were judged by feel. Second, make the job store a real queue from day one; two workers and a JSON file are enough for one user today, but cooperative cancellation and the 200-job cap in `app/core/jobs.py` are limits I keep explaining instead of removing. Third, put the path guards in place before the first upload endpoint: safe_join and sanitize_filename in `app/core/paths.py` are right now, and a boundary guard is cheaper to write once than to retrofit. + ### Where are the weak spots in this codebase? The flat index scans every chunk per query, so latency grows linearly with corpus size and I would hit a wall somewhere past tens of thousands of chunks (`app/services/rag/vector_store.py`). The two embedding backends produce different vector spaces, so switching models quarantines the whole index and retrieval returns nothing until every document is re-uploaded (`app/services/rag/embeddings.py`). Version records are per-document, so editing one paragraph re-embeds all of that document's chunks (`app/services/rag/service.py`), and the fused hybrid score is a rank statistic I cannot compare across queries or use as a threshold (`app/services/rag/fusion.py`). The job store also keeps only its 200 most recent jobs, so old history disappears on its own (`app/core/jobs.py`). From bd0d0645c89ac27433d67910aae30c2a73a4aa10 Mon Sep 17 00:00:00 2001 From: skl Date: Mon, 19 Oct 2026 17:15:05 +0200 Subject: [PATCH 48/48] dash scan: replace em dashes with hyphens in docs, code and eval corpus (item 84) --- .github/workflows/ci.yml | 2 +- Dockerfile | 6 +++--- ai_agent/cli.py | 2 +- app/api/routes.py | 6 +++--- app/clients/ollama_client.py | 2 +- app/services/comfyui_service.py | 6 +++--- app/services/dataset_validation.py | 18 +++++++++--------- app/services/lora_dataset_service.py | 2 +- app/services/lora_training_service.py | 4 ++-- app/services/rag/service.py | 4 ++-- app/services/rag/vector_store.py | 2 +- app/services/training_preflight.py | 12 ++++++------ docker-compose.yml | 2 +- evals/corpus/apollo-lora-pipeline.md | 4 ++-- evals/corpus/apollo-rag-knowledge-base.md | 2 +- evals/corpus/comfyui-workflows.md | 4 ++-- evals/corpus/lora-concepts.md | 2 +- evals/corpus/lora-dataset-curation.md | 8 ++++---- evals/corpus/prompt-engineering.md | 2 +- evals/corpus/sdxl.md | 4 ++-- evals/corpus/training-failure-modes.md | 4 ++-- evals/corpus/upscaling-and-resolution.md | 4 ++-- evals/corpus/vector-search-basics.md | 6 +++--- launcher.py | 12 ++++++------ scripts/smoke_rag_persistence.py | 2 +- tests/conftest.py | 8 ++++---- tests/test_comfyui.py | 2 +- tests/test_integration_pass.py | 2 +- tests/test_launcher.py | 2 +- tests/test_production_hardening.py | 2 +- tests/test_stress.py | 2 +- 31 files changed, 70 insertions(+), 70 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 175af80..4ed19d6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,7 +64,7 @@ jobs: - name: Build image run: docker build -t apollo:ci . - name: Smoke test (start container, wait for /live) - # The app boots fine without Ollama — the embedding client falls back to + # The app boots fine without Ollama - the embedding client falls back to # sentence-transformers and the vector store starts empty. /live is the # dependency-free liveness probe; /health would 503 without Ollama. run: | diff --git a/Dockerfile b/Dockerfile index 1663d10..8299b34 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -# Apollo — FastAPI backend (portfolio item 38) +# Apollo - FastAPI backend (portfolio item 38) # # Build: docker build -t apollo . # Run: docker run --rm -p 8000:8000 -v apollo-data:/app/data \ @@ -17,14 +17,14 @@ ENV PYTHONDONTWRITEBYTECODE=1 \ WORKDIR /app # CPU-only torch first, so sentence-transformers does not pull the multi-GB -# CUDA build (same trick as .github/workflows/ci.yml). Runtime deps only — +# CUDA build (same trick as .github/workflows/ci.yml). Runtime deps only - # ruff/mypy/pytest stay out of the image. COPY requirements.txt ./ RUN pip install torch --index-url https://download.pytorch.org/whl/cpu \ && pip install -r requirements.txt # Run as an unprivileged user; /app/data is a volume for runtime state -# (LoRA library, generated images, jobs.json — created at startup). The dir +# (LoRA library, generated images, jobs.json - created at startup). The dir # must exist in the image owned by appuser: Docker initializes an empty # volume from the image contents on first run, which preserves ownership. RUN useradd --create-home appuser \ diff --git a/ai_agent/cli.py b/ai_agent/cli.py index 0190486..c20c46c 100644 --- a/ai_agent/cli.py +++ b/ai_agent/cli.py @@ -10,7 +10,7 @@ def main(): if os.path.exists(default_path): document = import_document(default_path) - print('AI Document Agent — interactive') + print('AI Document Agent - interactive') print('Commands: load , summary, keywords, files, exit') while True: diff --git a/app/api/routes.py b/app/api/routes.py index adfa59b..0d4b026 100644 --- a/app/api/routes.py +++ b/app/api/routes.py @@ -71,7 +71,7 @@ def get_rag_service(request: Request) -> RAGService: def live() -> dict: """Process liveness probe: the HTTP server is up and responding. - Deliberately dependency-free — Ollama/ComfyUI/AI Toolkit being down does + Deliberately dependency-free - Ollama/ComfyUI/AI Toolkit being down does not make the API "not started". The launcher uses this to decide whether startup succeeded; `/health` reports dependency state separately. """ @@ -111,7 +111,7 @@ def health(service: LLMService = Depends(get_llm_service)) -> HealthResponse: try: payload = service.health_check() except OllamaServiceError as exc: - # A structured 503 with setup guidance, not a bare error — the UI + # A structured 503 with setup guidance, not a bare error - the UI # renders this as an actionable card rather than a dead endpoint. base_url = getattr(getattr(service, "client", None), "base_url", settings.ollama_base_url) @@ -171,7 +171,7 @@ def rag_debug_query( """Developer view of one retrieval: query → chunks → scores → context. Shows exactly what the model would see for this question. Not used by the - normal chat flow — it exists to explain why an answer came out the way it + normal chat flow - it exists to explain why an answer came out the way it did. """ if not q.strip(): diff --git a/app/clients/ollama_client.py b/app/clients/ollama_client.py index 19c1e61..bb8ad6a 100644 --- a/app/clients/ollama_client.py +++ b/app/clients/ollama_client.py @@ -33,7 +33,7 @@ def _request( # Never return 4xx status codes as that confuses clients about endpoint availability if response.status_code == 404: # Ollama returns 404 both for unknown routes AND for "model not - # found" — distinguish them so the message points at the real fix. + # found" - distinguish them so the message points at the real fix. detail = _extract_ollama_error(response) if "not found, try pulling" in detail: raise OllamaServiceError( diff --git a/app/services/comfyui_service.py b/app/services/comfyui_service.py index 5b5a372..636b304 100644 --- a/app/services/comfyui_service.py +++ b/app/services/comfyui_service.py @@ -6,7 +6,7 @@ ``workflows/.json`` raw ComfyUI **API-format** export (Save (API Format)) ``workflows/.map.json`` which node/field each logical input writes to -Node ids are never hardcoded here — everything goes through the mapping. +Node ids are never hardcoded here - everything goes through the mapping. """ from __future__ import annotations @@ -405,7 +405,7 @@ def _run_generation(self, job: Job, graph: dict) -> None: def _save_outputs(self, job_id: str, outputs: dict) -> list[str]: """Copy ComfyUI's images into our own managed folder. - The browser is never handed a ComfyUI filesystem path — it gets a + The browser is never handed a ComfyUI filesystem path - it gets a filename that only resolves inside ``generated_dir``. """ saved: list[str] = [] @@ -598,7 +598,7 @@ def prepare_lora_test( Picks (or validates) a workflow with a LoRA node, checks that ComfyUI can actually see the file, and returns a prefilled :class:`GenerationRequest`-shaped payload for ``POST /comfyui/generate``. - No generation is queued here — the user still presses Generate. + No generation is queued here - the user still presses Generate. """ workflows = self.list_workflows() candidates = [w for w in workflows if "lora_name" in w.supported_inputs] diff --git a/app/services/dataset_validation.py b/app/services/dataset_validation.py index 6f982f4..011df30 100644 --- a/app/services/dataset_validation.py +++ b/app/services/dataset_validation.py @@ -1,13 +1,13 @@ """Dataset quality control: validation, duplicate detection, quality score. -Runs entirely on bytes already on disk — no network calls — so it is safe to +Runs entirely on bytes already on disk - no network calls - so it is safe to run from a background job or synchronously for small datasets. Checks performed per image: * decodable by Pillow (catches truncated / corrupted files) * extreme resolutions (too small to train on, or absurdly large) -* inconsistent dimensions (informational — AI Toolkit buckets resolutions) +* inconsistent dimensions (informational - AI Toolkit buckets resolutions) * exact duplicates (SHA-256 of decoded pixels, so a re-encoded copy matches) * near-duplicates (multi-signal, see below) * missing / empty / suspicious captions @@ -16,10 +16,10 @@ perceptual hash produces false positives on solid-color images and other low-entropy content: -* **exact** — identical decoded pixels (SHA-256) -* **high** — small perceptual distance AND similar dimensions AND +* **exact** - identical decoded pixels (SHA-256) +* **high** - small perceptual distance AND similar dimensions AND (for low-entropy images) matching color statistics -* **possible** — small perceptual distance but differing structure +* **possible** - small perceptual distance but differing structure The classifier returns ``exact_duplicate``, ``near_duplicate_high``, ``near_duplicate_possible`` or nothing (unique). Solid-color and other flat @@ -174,7 +174,7 @@ def _is_low_entropy(hash_hex: str) -> bool: """True when an aHash is nearly all-0 or all-1 (flat/gradient images). Such hashes carry no structure, so hash similarity alone is meaningless - for them — two unrelated solid-color photos would "match". + for them - two unrelated solid-color photos would "match". """ bits = int(hash_hex, 16) ones = bin(bits).count("1") @@ -202,10 +202,10 @@ def classify_pair( Returns one of: - * ``"near_duplicate_high"`` — hash distance <= NEAR_HASH_CLOSE with + * ``"near_duplicate_high"`` - hash distance <= NEAR_HASH_CLOSE with corroborating signals (same aspect ratio; flat images also need the same mean color) - * ``"near_duplicate_possible"`` — hash-similar but signals disagree + * ``"near_duplicate_possible"`` - hash-similar but signals disagree (e.g. a crop or a reframe); surfaced for human review, never auto-merged * ``"unique"`` @@ -341,7 +341,7 @@ def validate_dataset( }) # ---- near-duplicates: multi-signal classification, O(n^2) on - # fingerprints only — cheap for realistic dataset sizes. ---- + # fingerprints only - cheap for realistic dataset sizes. ---- seen_pairs: set[tuple[str, str]] = set() for i, fp_a in enumerate(fingerprints): for fp_b in fingerprints[i + 1:]: diff --git a/app/services/lora_dataset_service.py b/app/services/lora_dataset_service.py index 32fc2e6..8e6aae5 100644 --- a/app/services/lora_dataset_service.py +++ b/app/services/lora_dataset_service.py @@ -366,7 +366,7 @@ def generate_captions( if project.trigger_word and project.trigger_word.lower() not in caption.lower(): caption = f"{project.trigger_word}, {caption}" - # Saved but NOT marked edited — the user still reviews and confirms. + # Saved but NOT marked edited - the user still reviews and confirms. self._write_caption_unmarked(project_id, image.id, caption) results.append({"image_id": image.id, "caption": caption, "skipped": False}) diff --git a/app/services/lora_training_service.py b/app/services/lora_training_service.py index cd94159..d64e9fe 100644 --- a/app/services/lora_training_service.py +++ b/app/services/lora_training_service.py @@ -38,7 +38,7 @@ ) _LOSS_PATTERN = re.compile(r"loss[=:\s]+([0-9]*\.?[0-9]+)", re.I) -# Sensible per-architecture defaults. Only what is actually needed today — +# Sensible per-architecture defaults. Only what is actually needed today - # new architectures get an entry here rather than branches sprinkled elsewhere. ARCH_DEFAULTS: dict[str, dict[str, Any]] = { "sdxl": { @@ -494,7 +494,7 @@ def preflight(self, project_id: str, options: dict[str, Any]) -> dict[str, Any]: from app.services.hardware import detect_hardware from app.services.training_preflight import advise - # Dataset checks first — they are cheap and independent of hardware. + # Dataset checks first - they are cheap and independent of hardware. checks: list[dict[str, Any]] = [] try: images = self.projects.list_images(project_id) diff --git a/app/services/rag/service.py b/app/services/rag/service.py index 651ca92..fa6f199 100644 --- a/app/services/rag/service.py +++ b/app/services/rag/service.py @@ -2,7 +2,7 @@ The vector index is persistent: chunks, vectors and index metadata live under ``DATA_DIR/rag/`` and are reloaded on startup, so a restart does not re-embed -the knowledge base. Indexing is incremental — a document is only embedded when +the knowledge base. Indexing is incremental - a document is only embedded when its content hash differs from the version already in the index. The BM25 keyword index used for hybrid retrieval is derived from stored chunk @@ -128,7 +128,7 @@ def add_document( *, force: bool = False, ) -> int: - """Chunk, embed, and index a document — incrementally. + """Chunk, embed, and index a document - incrementally. When the same ``doc_id`` is already indexed with the identical content hash and embedding model, nothing is re-embedded and 0 is returned. diff --git a/app/services/rag/vector_store.py b/app/services/rag/vector_store.py index 53307ce..18c57a6 100644 --- a/app/services/rag/vector_store.py +++ b/app/services/rag/vector_store.py @@ -14,7 +14,7 @@ loading an index built with a different model is refused rather than silently mixing incompatible vectors. * **Recoverable.** If the FAISS file is missing or unreadable but chunk - metadata survives, the store quarantines the bad files and reports the loss — + metadata survives, the store quarantines the bad files and reports the loss - the caller (RAGService) decides to re-embed from persisted documents. """ diff --git a/app/services/training_preflight.py b/app/services/training_preflight.py index e0853d9..8433489 100644 --- a/app/services/training_preflight.py +++ b/app/services/training_preflight.py @@ -2,12 +2,12 @@ The advisor classifies configurations into four honest buckets: -* ``ok`` — likely safe -* ``heavy`` — potentially heavy; may work depending on the model -* ``risky`` — high risk of OOM or extreme runtime -* ``unsupported`` — cannot run here at all (e.g. no accelerator configured) +* ``ok`` - likely safe +* ``heavy`` - potentially heavy; may work depending on the model +* ``risky`` - high risk of OOM or extreme runtime +* ``unsupported`` - cannot run here at all (e.g. no accelerator configured) -It never modifies the user's configuration and never guarantees a fit — VRAM +It never modifies the user's configuration and never guarantees a fit - VRAM use depends on the base model, sequence caching and AI Toolkit internals that no external estimator can see. The raw error from a failed run is always kept alongside the translated explanation. @@ -26,7 +26,7 @@ # Rough VRAM pressure model for LoRA fine-tuning (rank <= 64, adamw8bit). # These are heuristics calibrated against AI Toolkit's documented examples, -# not guarantees — their purpose is ranking configs, not predicting exact use. +# not guarantees - their purpose is ranking configs, not predicting exact use. VRAM_BASE_MB = { # per resolution bucket, batch 1 "low": 6 * 1024, # <= 512px "medium": 9 * 1024, # <= 768px diff --git a/docker-compose.yml b/docker-compose.yml index 4d79ef5..3293e49 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,4 +1,4 @@ -# Apollo — local development stack (portfolio item 40) +# Apollo - local development stack (portfolio item 40) # # docker compose up --build # diff --git a/evals/corpus/apollo-lora-pipeline.md b/evals/corpus/apollo-lora-pipeline.md index 680ab93..99f1799 100644 --- a/evals/corpus/apollo-lora-pipeline.md +++ b/evals/corpus/apollo-lora-pipeline.md @@ -4,7 +4,7 @@ Apollo automates the path from a folder of images to a trained LoRA adapter. The ## Dataset quality control -Before anything is trained on, every image in the project folder passes automated checks. Images are decoded to verify they are not corrupt, near-duplicates are detected by perceptual hash and flagged for removal, and resolution is checked against a minimum threshold so tiny thumbnails do not silently degrade the dataset. The result is a quality report listing how many images passed, which were dropped, and why — the user reviews this before training starts. +Before anything is trained on, every image in the project folder passes automated checks. Images are decoded to verify they are not corrupt, near-duplicates are detected by perceptual hash and flagged for removal, and resolution is checked against a minimum threshold so tiny thumbnails do not silently degrade the dataset. The result is a quality report listing how many images passed, which were dropped, and why - the user reviews this before training starts. ## Captioning @@ -16,4 +16,4 @@ Apollo writes a training configuration file in the YAML format expected by the O ## Execution and results -Training runs as a supervised background job: Apollo starts the toolkit process, polls its progress output, and records status transitions (queued, running, completed, failed) in its local job store. When training finishes, the resulting adapter file is copied into the LoRA library where it becomes selectable in generation workflows with an adjustable strength slider. Failed jobs keep their log files so the cause — usually out-of-memory or a path error — can be inspected without rerunning. +Training runs as a supervised background job: Apollo starts the toolkit process, polls its progress output, and records status transitions (queued, running, completed, failed) in its local job store. When training finishes, the resulting adapter file is copied into the LoRA library where it becomes selectable in generation workflows with an adjustable strength slider. Failed jobs keep their log files so the cause - usually out-of-memory or a path error - can be inspected without rerunning. diff --git a/evals/corpus/apollo-rag-knowledge-base.md b/evals/corpus/apollo-rag-knowledge-base.md index 640118b..a1b914f 100644 --- a/evals/corpus/apollo-rag-knowledge-base.md +++ b/evals/corpus/apollo-rag-knowledge-base.md @@ -8,7 +8,7 @@ When a document is added, its text is split into overlapping chunks of 800 chara ## The index -Vectors live in a FAISS flat inner-product index on disk under the application data directory. Embeddings are L2-normalized before storage, which makes the inner product equivalent to cosine similarity — higher score means more similar. The index file is written atomically (temp file plus rename) so a crash mid-save cannot corrupt the previous good state, and a small metadata file records the embedding model name and vector dimension; loading an index built with a different model is refused rather than silently mixing incompatible vectors. +Vectors live in a FAISS flat inner-product index on disk under the application data directory. Embeddings are L2-normalized before storage, which makes the inner product equivalent to cosine similarity - higher score means more similar. The index file is written atomically (temp file plus rename) so a crash mid-save cannot corrupt the previous good state, and a small metadata file records the embedding model name and vector dimension; loading an index built with a different model is refused rather than silently mixing incompatible vectors. ## Retrieval at query time diff --git a/evals/corpus/comfyui-workflows.md b/evals/corpus/comfyui-workflows.md index ed7b7d4..c322045 100644 --- a/evals/corpus/comfyui-workflows.md +++ b/evals/corpus/comfyui-workflows.md @@ -4,7 +4,7 @@ ComfyUI is a node-based interface for running diffusion models. Instead of fixed ## Core nodes -Every workflow contains the same skeleton: a **CheckpointLoader** that loads the base model (and exposes its CLIP text encoder, VAE, and UNet as separate outputs), one or two **CLIPTextEncode** nodes for the positive and negative prompts, a **KSampler** that runs the denoising loop, and a **VAEDecode** plus **SaveImage** pair to turn latents into pixels. The KSampler's inputs — model, positive prompt, negative prompt, latent image, seed, steps, CFG, sampler name, and denoise strength — are the same settings described in the sampling documentation. +Every workflow contains the same skeleton: a **CheckpointLoader** that loads the base model (and exposes its CLIP text encoder, VAE, and UNet as separate outputs), one or two **CLIPTextEncode** nodes for the positive and negative prompts, a **KSampler** that runs the denoising loop, and a **VAEDecode** plus **SaveImage** pair to turn latents into pixels. The KSampler's inputs - model, positive prompt, negative prompt, latent image, seed, steps, CFG, sampler name, and denoise strength - are the same settings described in the sampling documentation. ## Latent space plumbing @@ -12,4 +12,4 @@ Nodes exchange latents rather than images wherever possible: an **EmptyLatentIma ## Managing workflows -Workflows are saved as JSON files describing nodes and their connections, which makes them easy to version-control and share. Apollo stores its built-in workflow templates in a `workflows` directory and can load any compatible file from there; custom workflows added by the user appear in the picker automatically. Because the graph is data rather than code, swapping one node — for example replacing a plain upscaler with a tiled variant — changes behavior without touching anything else. +Workflows are saved as JSON files describing nodes and their connections, which makes them easy to version-control and share. Apollo stores its built-in workflow templates in a `workflows` directory and can load any compatible file from there; custom workflows added by the user appear in the picker automatically. Because the graph is data rather than code, swapping one node - for example replacing a plain upscaler with a tiled variant - changes behavior without touching anything else. diff --git a/evals/corpus/lora-concepts.md b/evals/corpus/lora-concepts.md index d4d36d6..554dfaf 100644 --- a/evals/corpus/lora-concepts.md +++ b/evals/corpus/lora-concepts.md @@ -14,4 +14,4 @@ The **rank** controls how much information the adapter can carry. Low ranks (4 t ## Why LoRA instead of full fine-tuning -A LoRA for SDXL typically occupies 10 to 200 megabytes on disk versus several gigabytes for a full checkpoint. It trains in minutes to an hour on a single consumer GPU, and multiple LoRAs can be stacked on the same base model at generation time with independent strength sliders — something impossible when each variant is a separate full checkpoint. +A LoRA for SDXL typically occupies 10 to 200 megabytes on disk versus several gigabytes for a full checkpoint. It trains in minutes to an hour on a single consumer GPU, and multiple LoRAs can be stacked on the same base model at generation time with independent strength sliders - something impossible when each variant is a separate full checkpoint. diff --git a/evals/corpus/lora-dataset-curation.md b/evals/corpus/lora-dataset-curation.md index abe3e00..694bf0f 100644 --- a/evals/corpus/lora-dataset-curation.md +++ b/evals/corpus/lora-dataset-curation.md @@ -4,16 +4,16 @@ The quality of a LoRA is bounded by the quality of its training images. A well-c ## How many images -For a single subject — a person, a character, or an object — twenty to fifty images is the usual working range. Below about fifteen the model often fails to lock onto consistent identity details; above roughly eighty you are mostly paying in training time without gaining robustness, and you start needing more epochs control to avoid overfitting. +For a single subject - a person, a character, or an object - twenty to fifty images is the usual working range. Below about fifteen the model often fails to lock onto consistent identity details; above roughly eighty you are mostly paying in training time without gaining robustness, and you start needing more epochs control to avoid overfitting. ## Variety that matters -The dataset should vary what the subject does not: different angles (front, three-quarter, profile), lighting conditions, backgrounds, and distances from close-up to full body. What must stay consistent is the identity itself — face shape, hair color, distinctive features for a person; material and silhouette for an object. Including images where the subject looks like someone else actively teaches the model the wrong thing. +The dataset should vary what the subject does not: different angles (front, three-quarter, profile), lighting conditions, backgrounds, and distances from close-up to full body. What must stay consistent is the identity itself - face shape, hair color, distinctive features for a person; material and silhouette for an object. Including images where the subject looks like someone else actively teaches the model the wrong thing. ## Captions -Each image needs a caption that describes everything except the trigger word reserved for the subject. If the trigger is "skto woman", a good caption reads "a woman in a red coat walking through a market, overcast light" — describing scene and context while leaving identity to the adapter. Over-captioning (naming every trivial detail) makes the model attribute those details to the subject; under-captioning leaves it guessing. +Each image needs a caption that describes everything except the trigger word reserved for the subject. If the trigger is "skto woman", a good caption reads "a woman in a red coat walking through a market, overcast light" - describing scene and context while leaving identity to the adapter. Over-captioning (naming every trivial detail) makes the model attribute those details to the subject; under-captioning leaves it guessing. ## Cleaning steps -Before training: remove duplicates and near-duplicates (identical frames from a video count as one image), reject blurry or watermarked shots, and normalize resolution so nothing is far smaller than the training size — upscaling a 400-pixel thumbnail to 1024 only adds softness. Most curation pipelines report how many images were dropped at each stage so you can see where your dataset lost quality. +Before training: remove duplicates and near-duplicates (identical frames from a video count as one image), reject blurry or watermarked shots, and normalize resolution so nothing is far smaller than the training size - upscaling a 400-pixel thumbnail to 1024 only adds softness. Most curation pipelines report how many images were dropped at each stage so you can see where your dataset lost quality. diff --git a/evals/corpus/prompt-engineering.md b/evals/corpus/prompt-engineering.md index 73a5a27..f79b234 100644 --- a/evals/corpus/prompt-engineering.md +++ b/evals/corpus/prompt-engineering.md @@ -12,7 +12,7 @@ Parentheses increase the relative importance of the words inside them: "(red fox ## Negative prompts -The negative prompt lists what should be avoided: "blurry, low quality, extra fingers, watermark". It works by conditioning the model to move away from those concepts during sampling. Keep it short — a wall of negative terms dilutes each one and can start fighting the positive prompt. For anatomy problems specifically, terms like "extra fingers", "deformed hands", and "bad anatomy" are the most effective entries. +The negative prompt lists what should be avoided: "blurry, low quality, extra fingers, watermark". It works by conditioning the model to move away from those concepts during sampling. Keep it short - a wall of negative terms dilutes each one and can start fighting the positive prompt. For anatomy problems specifically, terms like "extra fingers", "deformed hands", and "bad anatomy" are the most effective entries. ## Style tokens diff --git a/evals/corpus/sdxl.md b/evals/corpus/sdxl.md index d9ceb3e..80a76ce 100644 --- a/evals/corpus/sdxl.md +++ b/evals/corpus/sdxl.md @@ -4,13 +4,13 @@ Stable Diffusion XL, usually abbreviated SDXL, is a latent diffusion model relea ## Architecture changes over SD 1.5 -SDXL keeps the overall pipeline — text encoder, U-Net denoiser, VAE decoder — but scales each part up. The UNet is roughly three times larger than in SD 1.5 and uses a deeper transformer-style attention block called the "big" attention layer. The variational autoencoder compresses images by a factor of eight per spatial dimension into a latent tensor with sixteen channels, compared to four channels in SD 1.5. +SDXL keeps the overall pipeline - text encoder, U-Net denoiser, VAE decoder - but scales each part up. The UNet is roughly three times larger than in SD 1.5 and uses a deeper transformer-style attention block called the "big" attention layer. The variational autoencoder compresses images by a factor of eight per spatial dimension into a latent tensor with sixteen channels, compared to four channels in SD 1.5. The text conditioning also changed: SDXL uses two CLIP encoders at once, an openai/clip-vit-large-patch14 model and an open_clip ViT-bigG model. The hidden states of both encoders are concatenated and fed into the UNet, which gives the model access to richer semantic information from the prompt than a single encoder can provide. ## Native resolution -SDXL was trained primarily at 1024 by 1024 pixels. Generating at that square size is where the model performs best; other aspect ratios work but should stay close to roughly one megapixel in total area. Pushing SDXL far outside its training range — for example a very wide banner or an extremely tall portrait — tends to produce duplicated subjects, warped anatomy, and degraded text rendering. +SDXL was trained primarily at 1024 by 1024 pixels. Generating at that square size is where the model performs best; other aspect ratios work but should stay close to roughly one megapixel in total area. Pushing SDXL far outside its training range - for example a very wide banner or an extremely tall portrait - tends to produce duplicated subjects, warped anatomy, and degraded text rendering. ## Practical notes diff --git a/evals/corpus/training-failure-modes.md b/evals/corpus/training-failure-modes.md index c49406b..1e82bf8 100644 --- a/evals/corpus/training-failure-modes.md +++ b/evals/corpus/training-failure-modes.md @@ -4,11 +4,11 @@ Most failed LoRAs fail in one of a handful of predictable ways. Recognizing the ## Overfitting -The classic failure: the adapter memorizes the training images instead of learning the concept. Symptoms include the subject appearing with the exact same background, pose, or clothing from the dataset no matter what the prompt says, plus plastic-looking skin and smeared textures. Causes are too many epochs for the dataset size, a learning rate that is too high, or a rank that is too large relative to the data. The fix is fewer epochs (often one to three for small datasets), a lower learning rate, and a smaller rank — then verify with test prompts that use backgrounds absent from the training set. +The classic failure: the adapter memorizes the training images instead of learning the concept. Symptoms include the subject appearing with the exact same background, pose, or clothing from the dataset no matter what the prompt says, plus plastic-looking skin and smeared textures. Causes are too many epochs for the dataset size, a learning rate that is too high, or a rank that is too large relative to the data. The fix is fewer epochs (often one to three for small datasets), a lower learning rate, and a smaller rank - then verify with test prompts that use backgrounds absent from the training set. ## Identity drift -The opposite problem: generations look like the subject only loosely. The model never locked onto distinguishing features because the dataset was too small, the trigger word appeared inconsistently in captions, or images of similar-but-different subjects were mixed in. Check the dataset first — identity drift is usually a data problem, not a hyperparameter problem. +The opposite problem: generations look like the subject only loosely. The model never locked onto distinguishing features because the dataset was too small, the trigger word appeared inconsistently in captions, or images of similar-but-different subjects were mixed in. Check the dataset first - identity drift is usually a data problem, not a hyperparameter problem. ## Prompt bleed diff --git a/evals/corpus/upscaling-and-resolution.md b/evals/corpus/upscaling-and-resolution.md index 647309f..bd67374 100644 --- a/evals/corpus/upscaling-and-resolution.md +++ b/evals/corpus/upscaling-and-resolution.md @@ -4,7 +4,7 @@ Diffusion models generate at a fixed native resolution; getting larger or sharpe ## Why not just generate big? -Generating directly at 4K would require a latent canvas far outside the model's training distribution: subjects duplicate, anatomy breaks down, and memory usage grows with pixel count. The standard approach is to generate at native resolution — 1024 by 1024 for SDXL — and then upscale the result with a dedicated upscaler network. +Generating directly at 4K would require a latent canvas far outside the model's training distribution: subjects duplicate, anatomy breaks down, and memory usage grows with pixel count. The standard approach is to generate at native resolution - 1024 by 1024 for SDXL - and then upscale the result with a dedicated upscaler network. ## Upscaler networks @@ -16,4 +16,4 @@ Upscaling a full 4K canvas in one go can exceed GPU memory, so upscalers run in ## Two-stage refinement -A common high-quality recipe is: generate at native resolution, upscale 2x with a strong upscaler, then run a light diffusion pass over the upscaled image (image-to-image with low denoise strength around 0.3 to 0.4). The second stage lets the diffusion model re-render fine detail — skin texture, fabric weave, foliage — at the higher resolution instead of trusting the upscaler's hallucinated detail alone. This is slower but usually the best-looking result for hero images. +A common high-quality recipe is: generate at native resolution, upscale 2x with a strong upscaler, then run a light diffusion pass over the upscaled image (image-to-image with low denoise strength around 0.3 to 0.4). The second stage lets the diffusion model re-render fine detail - skin texture, fabric weave, foliage - at the higher resolution instead of trusting the upscaler's hallucinated detail alone. This is slower but usually the best-looking result for hero images. diff --git a/evals/corpus/vector-search-basics.md b/evals/corpus/vector-search-basics.md index 35a7052..762cd94 100644 --- a/evals/corpus/vector-search-basics.md +++ b/evals/corpus/vector-search-basics.md @@ -4,7 +4,7 @@ Retrieval-augmented systems answer questions by finding the most similar stored ## Embeddings -A text embedding model maps a piece of text to a fixed-length list of floating-point numbers — for example 384 or 768 values. Texts with similar meaning land close together in this vector space, so similarity between two texts reduces to a geometric question about their vectors. The same model must be used to embed both the stored documents and the query; mixing embeddings from different models is meaningless because each model defines its own coordinate system. +A text embedding model maps a piece of text to a fixed-length list of floating-point numbers - for example 384 or 768 values. Texts with similar meaning land close together in this vector space, so similarity between two texts reduces to a geometric question about their vectors. The same model must be used to embed both the stored documents and the query; mixing embeddings from different models is meaningless because each model defines its own coordinate system. ## Cosine similarity @@ -12,8 +12,8 @@ The standard similarity measure is cosine similarity: the angle between two vect ## Flat indexes -The simplest index stores all vectors in a dense array and computes the inner product with the query against every row — an exact brute-force search, often called a flat index. FAISS provides this as `IndexFlatIP` (inner product). Exact search costs time proportional to the number of stored vectors, but for tens or hundreds of thousands of short vectors it completes in milliseconds on CPU, which is why local single-user tools rarely need approximate methods at all. +The simplest index stores all vectors in a dense array and computes the inner product with the query against every row - an exact brute-force search, often called a flat index. FAISS provides this as `IndexFlatIP` (inner product). Exact search costs time proportional to the number of stored vectors, but for tens or hundreds of thousands of short vectors it completes in milliseconds on CPU, which is why local single-user tools rarely need approximate methods at all. ## When to move on -Approximate nearest-neighbor structures such as HNSW graphs trade a small loss in recall for large speedups at scale — millions of vectors and beyond. They add configuration (graph degree, construction ef) and memory overhead, so the rule of thumb is: stay flat until exact search measurably hurts latency, then switch. +Approximate nearest-neighbor structures such as HNSW graphs trade a small loss in recall for large speedups at scale - millions of vectors and beyond. They add configuration (graph degree, construction ef) and memory overhead, so the rule of thumb is: stay flat until exact search measurably hurts latency, then switch. diff --git a/launcher.py b/launcher.py index 5d6b4a8..5834b8e 100644 --- a/launcher.py +++ b/launcher.py @@ -117,7 +117,7 @@ def _announce_public_url(url: str) -> None: """Print, copy, and open the public dashboard URL.""" link = _with_token(url) print("\n" + "=" * 70) - print(" APOLLO — LIVE") + print(" APOLLO - LIVE") print("=" * 70) print(f"\n Local: {_with_token(f'http://localhost:{PORT}')}") print(f" Public: {link}") @@ -175,7 +175,7 @@ def _wait_for_backend(timeout: float = 45.0) -> StartupResult: Readiness semantics: - * **/live** decides startup success — it only means "the HTTP server is + * **/live** decides startup success - it only means "the HTTP server is up". Optional dependencies (Ollama etc.) being down must NOT fail the launch, so any HTTP response (including 503 from /health) counts as the process being alive. @@ -247,13 +247,13 @@ def _report_startup_failure(result: StartupResult) -> None: f" - Another process already holds port {PORT}\n" " (check with: netstat -ano | findstr " f"\":{PORT}.*LISTENING\")\n" - " - The app failed during import/startup — see [api] output above\n" + " - The app failed during import/startup - see [api] output above\n" " - Slow first start (embedding model download)", flush=True, ) elif not proc_alive: print( - "\n The API process exited during startup — see the [api] output\n" + "\n The API process exited during startup - see the [api] output\n" " above for the traceback.", flush=True, ) @@ -373,7 +373,7 @@ def _monitor() -> int: def main() -> int: """Entry point for the all-in-one dev launcher.""" print("=" * 70) - print(" APOLLO — STARTUP") + print(" APOLLO - STARTUP") print("=" * 70) print(f" Project: {PROJECT_ROOT}") print(f" Backend: {UVICORN_APP} on {HOST}:{PORT}") @@ -421,7 +421,7 @@ def main() -> int: def _local_fallback() -> None: if not _url_announced.wait(timeout=60): print( - f"\nTunnel URL not detected yet — opening local dashboard " + f"\nTunnel URL not detected yet - opening local dashboard " f"http://localhost:{PORT}\n", flush=True, ) diff --git a/scripts/smoke_rag_persistence.py b/scripts/smoke_rag_persistence.py index 5a5fb4c..5f1987f 100644 --- a/scripts/smoke_rag_persistence.py +++ b/scripts/smoke_rag_persistence.py @@ -46,7 +46,7 @@ def phase2() -> None: entry = next( (d for d in status["indexed_documents"] if d["doc_id"] == "doc_0"), None) print("restored doc record:", entry) - print("PHASE2 OK — persistent index verified") + print("PHASE2 OK - persistent index verified") if __name__ == "__main__": diff --git a/tests/conftest.py b/tests/conftest.py index 0586101..ba4262e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -42,8 +42,8 @@ def _install_shared_embedding_model() -> None: once per instance (app/services/rag/embeddings.py), and sentence-transformers 6.x keeps no class-level cache, so every RAGService construction re-reads the model from disk (~3-6 s each; ~14 s cold including the torch import). The - tests never assert on vector values or on how often a model is loaded — only - that an embedding backend exists and works — so sharing one real instance + tests never assert on vector values or on how often a model is loaded - only + that an embedding backend exists and works - so sharing one real instance preserves behaviour while removing the suite's dominant cost. Ollama itself stays genuinely unreachable: every client still attempts (and fails) its HTTP probe before falling back. @@ -86,8 +86,8 @@ def fast_external_timeouts(): On this machine a connect to a closed localhost port is refused only after ~2-4 s (delayed RST), so every real-client probe in the suite pays that delay - on top of its work. The tests assert on outcomes — unreachable services - surface as errors, 503s or fallbacks — not on how long an attempt took, and + on top of its work. The tests assert on outcomes - unreachable services + surface as errors, 503s or fallbacks - not on how long an attempt took, and none of them read these settings directly (the one test that needs specific values sets them itself via ``set_setting``). Originals are restored after each test. diff --git a/tests/test_comfyui.py b/tests/test_comfyui.py index 5a052de..b55315a 100644 --- a/tests/test_comfyui.py +++ b/tests/test_comfyui.py @@ -1,6 +1,6 @@ """ComfyUI client, workflow handling, and generation submission. -All tests run against a stub client — none of them require ComfyUI to be +All tests run against a stub client - none of them require ComfyUI to be running, and none of them fabricate a successful generation. """ diff --git a/tests/test_integration_pass.py b/tests/test_integration_pass.py index 13e0601..3337947 100644 --- a/tests/test_integration_pass.py +++ b/tests/test_integration_pass.py @@ -77,7 +77,7 @@ def test_runs_are_newest_first(self, project_service, project): assert [r["id"] for r in runs] == [second["id"], first["id"]] def test_history_lives_inside_project_folder(self, project_service, project): - """Deleting the project removes its history — no orphan records.""" + """Deleting the project removes its history - no orphan records.""" history = RunHistory(project_service) history.create_run( project.id, config={}, base_model="m", trigger_word="", arch="sdxl", diff --git a/tests/test_launcher.py b/tests/test_launcher.py index 27a1ef8..454c433 100644 --- a/tests/test_launcher.py +++ b/tests/test_launcher.py @@ -91,7 +91,7 @@ def _patch_port(self, launcher, port): return original def test_api_up_with_unhealthy_dependencies_still_starts(self, launcher, free_port): - """/health returning 503 must NOT fail startup — that's the core bug.""" + """/health returning 503 must NOT fail startup - that's the core bug.""" original = self._patch_port(launcher, free_port) server = _serve(_Handler, port=free_port) # live=200, health=503 try: diff --git a/tests/test_production_hardening.py b/tests/test_production_hardening.py index ab000fc..3344e5c 100644 --- a/tests/test_production_hardening.py +++ b/tests/test_production_hardening.py @@ -27,7 +27,7 @@ class FakeEmbeddingClient: """Deterministic stand-in for EmbeddingClient. Hashes text into a fixed-dimension vector so the same text always embeds - identically and different text differs — enough for real FAISS behaviour. + identically and different text differs - enough for real FAISS behaviour. """ model = "fake-embed-model" diff --git a/tests/test_stress.py b/tests/test_stress.py index c2dc01d..35c3504 100644 --- a/tests/test_stress.py +++ b/tests/test_stress.py @@ -1,7 +1,7 @@ """Stress test: 120-image dataset validation + large document indexing. Measures wall time and peak behavior; prints a summary. Not part of the -default suite (marked slow) — run explicitly with: +default suite (marked slow) - run explicitly with: pytest tests/test_stress.py -m slow -v """