diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4ed19d6..e292554 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -52,9 +52,9 @@ jobs: pip install torch --index-url https://download.pytorch.org/whl/cpu 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 + # The gate sits two points under the current TOTAL (97%) so small platform + # differences in CI cannot flip the build; raise it as coverage grows. + run: python -m pytest --cov=app --cov-report=term-missing --cov-fail-under=95 docker: runs-on: ubuntu-latest diff --git a/app/core/paths.py b/app/core/paths.py index 497ac78..0a03dc6 100644 --- a/app/core/paths.py +++ b/app/core/paths.py @@ -11,6 +11,7 @@ import os import re import tempfile +import time from pathlib import Path IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg"} @@ -120,7 +121,11 @@ def is_safetensors(path: Path) -> bool: def write_json_atomic(path: str | Path, payload: object) -> None: - """Write JSON via a temp file + replace, so a crash cannot truncate state.""" + """Write JSON via a temp file + replace, so a crash cannot truncate state. + + On Windows ``os.replace`` can fail with PermissionError when another thread + replaces the same target at the same instant; retry briefly before giving up. + """ target = Path(path) target.parent.mkdir(parents=True, exist_ok=True) handle = tempfile.NamedTemporaryFile( @@ -129,16 +134,44 @@ def write_json_atomic(path: str | Path, payload: object) -> None: try: with handle: json.dump(payload, handle, indent=2, default=str) - os.replace(handle.name, target) + _replace_with_retry(handle.name, target) except BaseException: Path(handle.name).unlink(missing_ok=True) raise +def _replace_with_retry(source: str, target: Path, attempts: int = 10) -> None: + """``os.replace`` with a short backoff for Windows replace races.""" + delay = 0.005 + for attempt in range(attempts): + try: + os.replace(source, target) + return + except PermissionError: + if attempt + 1 >= attempts: + raise + time.sleep(delay) + delay *= 2 + + def read_json(path: str | Path, default: object = None) -> object: - """Read JSON, returning ``default`` when the file is missing or corrupt.""" - try: - with open(path, encoding="utf-8") as handle: - return json.load(handle) - except (OSError, json.JSONDecodeError): - return default + """Read JSON, returning ``default`` when the file is missing or corrupt. + + On Windows, opening a file that another thread is atomically replacing can + transiently fail with Access Denied; retry briefly before giving up. + """ + delay = 0.005 + for attempt in range(10): + try: + with open(path, encoding="utf-8") as handle: + return json.load(handle) + except FileNotFoundError: + return default + except OSError: + if attempt + 1 >= 10: + return default + time.sleep(delay) + delay *= 2 + except json.JSONDecodeError: + return default + return default diff --git a/app/services/lora_dataset_service.py b/app/services/lora_dataset_service.py index 8e6aae5..38f886e 100644 --- a/app/services/lora_dataset_service.py +++ b/app/services/lora_dataset_service.py @@ -14,6 +14,7 @@ import base64 import logging import re +import threading import uuid from dataclasses import asdict, dataclass, field from datetime import UTC, datetime @@ -87,6 +88,18 @@ def __init__( self.data_dir = Path(data_dir or settings.lora_data_dir) self.data_dir.mkdir(parents=True, exist_ok=True) self.ollama_client = ollama_client or OllamaClient() + # Per-project locks: update_project is a read-modify-write on project.json and + # runs from both the request thread and training worker threads concurrently. + self._project_locks: dict[str, threading.Lock] = {} + self._locks_guard = threading.Lock() + + def _lock_for(self, project_id: str) -> threading.Lock: + with self._locks_guard: + lock = self._project_locks.get(project_id) + if lock is None: + lock = threading.Lock() + self._project_locks[project_id] = lock + return lock # ---------- paths ---------- @@ -165,12 +178,13 @@ def list_projects(self) -> list[LoRAProject]: return projects def update_project(self, project_id: str, **fields: Any) -> LoRAProject: - project = self.get_project(project_id) - for key, value in fields.items(): - if value is not None and hasattr(project, key): - setattr(project, key, value) - self._save_project(project) - return project + with self._lock_for(project_id): + project = self.get_project(project_id) + for key, value in fields.items(): + if value is not None and hasattr(project, key): + setattr(project, key, value) + self._save_project(project) + return project def delete_project(self, project_id: str) -> bool: import shutil diff --git a/app/services/lora_training_service.py b/app/services/lora_training_service.py index d64e9fe..c72c69f 100644 --- a/app/services/lora_training_service.py +++ b/app/services/lora_training_service.py @@ -660,6 +660,7 @@ def _run(self, job: Job, project_id: str, config_path: Path, log_path: Path) -> while trainer.is_running(): if self.jobs.is_cancelled(job.id): trainer.stop() + self._active.pop(project_id, None) self.projects.update_project(project_id, training_status="cancelled") self._finish_run_record(project_id, job.id, status="cancelled") logger.info("[LORA TRAINING] %s cancelled", project_id) diff --git a/app/services/run_history.py b/app/services/run_history.py index 127897a..f65a849 100644 --- a/app/services/run_history.py +++ b/app/services/run_history.py @@ -10,6 +10,7 @@ from __future__ import annotations import logging +import threading import time import uuid from dataclasses import asdict, dataclass, field @@ -64,6 +65,18 @@ class RunHistory: def __init__(self, projects_service: Any) -> None: self.projects = projects_service + # Per-project locks: runs.json is read-modify-written by the request thread + # (create_run) and training worker threads (update_run) concurrently. + self._locks: dict[str, threading.Lock] = {} + self._guard = threading.Lock() + + def _lock_for(self, project_id: str) -> threading.Lock: + with self._guard: + lock = self._locks.get(project_id) + if lock is None: + lock = threading.Lock() + self._locks[project_id] = lock + return lock def _path(self, project_id: str) -> Path: return self.projects.project_dir(project_id) / "runs.json" @@ -109,23 +122,25 @@ def create_run( job_id=job_id, ).to_dict() - runs = self.list_runs(project_id) - runs.insert(0, run) - self._save(project_id, runs) + with self._lock_for(project_id): + runs = self.list_runs(project_id) + runs.insert(0, run) + self._save(project_id, runs) logger.info("[RUN HISTORY] %s: created run %s", project_id, run["id"]) return run def update_run(self, project_id: str, run_id: str, **fields: Any) -> dict[str, Any] | None: - runs = self.list_runs(project_id) - for run in runs: - if run.get("id") != run_id: - continue - for key, value in fields.items(): - if key in TrainingRun.__dataclass_fields__: - run[key] = value - self._save(project_id, runs) - return run - return None + with self._lock_for(project_id): + runs = self.list_runs(project_id) + for run in runs: + if run.get("id") != run_id: + continue + for key, value in fields.items(): + if key in TrainingRun.__dataclass_fields__: + run[key] = value + self._save(project_id, runs) + return run + return None def latest_run(self, project_id: str) -> dict[str, Any] | None: runs = self.list_runs(project_id) diff --git a/tests/conftest.py b/tests/conftest.py index ba4262e..53c8a38 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -206,9 +206,11 @@ def project(project_service): def png_bytes(size: int = 64) -> bytes: """A minimal but genuinely valid 1x1 PNG, padded to ``size`` bytes.""" - png = bytes.fromhex( - "89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4" - "890000000a49444154789c6360000002000100ffff0300000600055773d8b400" - "00000049454e44ae426082" - ) + from io import BytesIO + + from PIL import Image + + buffer = BytesIO() + Image.new("RGBA", (1, 1), color=(255, 0, 0, 255)).save(buffer, format="PNG") + png = buffer.getvalue() return png + b"\x00" * max(0, size - len(png)) diff --git a/tests/test_chunking_behaviour.py b/tests/test_chunking_behaviour.py new file mode 100644 index 0000000..eba9718 --- /dev/null +++ b/tests/test_chunking_behaviour.py @@ -0,0 +1,168 @@ +"""Unit tests for ``app.services.rag.chunking`` (sentence-aware text chunker). + +The module is pure string processing, so every test feeds a short hand-built +document and asserts the exact list of chunks returned. Expected values were +computed by tracing the algorithm by hand: sentence lengths, overlap windows +and character offsets are all pinned to literals, never re-derived from the +code under test. +""" + +from __future__ import annotations + +from app.services.rag.chunking import ( + _chunk_by_characters, + _overlap_tail, + chunk_text, +) + + +# --------------------------------------------------------------------------- # +# chunk_text: normalization and short-text paths +# --------------------------------------------------------------------------- # +class TestChunkTextShortPaths: + def test_empty_string_returns_no_chunks(self): + assert chunk_text("") == [] + + def test_whitespace_only_returns_no_chunks(self): + assert chunk_text(" \n\t ") == [] + + def test_short_text_is_single_normalized_chunk(self): + # Newlines, tabs and repeated spaces collapse to single spaces. + result = chunk_text("Hello\n world!\tHow are you?") + assert result == ["Hello world! How are you?"] + + def test_text_exactly_at_chunk_size_stays_single(self): + text = "x" * 10 + assert chunk_text(text, chunk_size=10) == [text] + + def test_one_char_over_chunk_size_uses_character_fallback(self): + # No sentence boundaries at all: the character fallback cuts at the + # size limit and keeps the remainder. + result = chunk_text("x" * 11, chunk_size=10, overlap=0) + assert result == ["x" * 10, "x"] + + def test_newlines_and_tabs_normalize_before_sentence_split(self): + result = chunk_text("First line.\n\nSecond line!\tThird?") + assert result == ["First line. Second line! Third?"] + + +# --------------------------------------------------------------------------- # +# chunk_text: sentence path with overlap carry-over +# --------------------------------------------------------------------------- # +class TestChunkTextSentencePath: + # Sentences used below, with exact lengths: + # s1 "Alpha beta gamma." 17 chars + # s2 "Delta epsilon zeta." 19 chars + # s3 "Eta theta iota kappa." 21 chars + # s4 "Lambda mu nu xi." 16 chars + + def test_overflow_carries_overlap_tail(self): + text = "Alpha beta gamma. Delta epsilon zeta. Eta theta iota kappa." + result = chunk_text(text, chunk_size=40, overlap=20) + # s1+s2 fit (37 <= 40); s3 overflows (59 > 40). The overlap window of + # 20 keeps only the trailing sentence s2 for the next chunk. + assert result == [ + "Alpha beta gamma. Delta epsilon zeta.", + "Delta epsilon zeta. Eta theta iota kappa.", + ] + + def test_zero_overlap_carries_nothing(self): + text = "Alpha beta gamma. Delta epsilon zeta. Eta theta iota kappa." + result = chunk_text(text, chunk_size=40, overlap=0) + assert result == [ + "Alpha beta gamma. Delta epsilon zeta.", + "Eta theta iota kappa.", + ] + + def test_large_overlap_keeps_every_previous_sentence(self): + text = "Alpha beta gamma. Delta epsilon zeta. Eta theta iota kappa." + result = chunk_text(text, chunk_size=40, overlap=100) + # The whole previous chunk fits inside the 100-char window, so the + # second chunk repeats it in full (and may exceed chunk_size). + assert result == [ + "Alpha beta gamma. Delta epsilon zeta.", + "Alpha beta gamma. Delta epsilon zeta. Eta theta iota kappa.", + ] + + def test_multiple_flushes_produce_three_chunks(self): + text = ( + "Alpha beta gamma. Delta epsilon zeta. " + "Eta theta iota kappa. Lambda mu nu xi." + ) + result = chunk_text(text, chunk_size=40, overlap=20) + # Each flush keeps only the last sentence of the previous chunk: + # s2 (19 chars) fits the 20-char window alone; s3 (21) does not share + # it with anything. + assert result == [ + "Alpha beta gamma. Delta epsilon zeta.", + "Delta epsilon zeta. Eta theta iota kappa.", + "Eta theta iota kappa. Lambda mu nu xi.", + ] + + +# --------------------------------------------------------------------------- # +# chunk_text: entry into the character fallback (no usable boundaries) +# --------------------------------------------------------------------------- # +class TestChunkTextCharacterFallbackEntry: + def test_word_text_without_boundaries_splits_on_spaces(self): + result = chunk_text("aaaa bbbb cccc dddd", chunk_size=10, overlap=0) + assert result == ["aaaa bbbb", "cccc dddd"] + + def test_period_not_followed_by_space_is_not_a_boundary(self): + # "abc.def" has no "." pair, so the whole text is one sentence + # and falls through to character chunking. + result = chunk_text("abc.def ghi", chunk_size=5, overlap=0) + assert result == ["abc.d", "ef", "ghi"] + + +# --------------------------------------------------------------------------- # +# _overlap_tail: direct behaviour of the carry-over window +# --------------------------------------------------------------------------- # +class TestOverlapTail: + def test_empty_parts_returns_empty_list(self): + assert _overlap_tail([], 50) == [] + + def test_zero_overlap_returns_empty_list(self): + assert _overlap_tail(["one", "two"], 0) == [] + + def test_negative_overlap_returns_empty_list(self): + assert _overlap_tail(["one", "two"], -5) == [] + + def test_exact_fit_keeps_all_parts(self): + # "bb" (2) + space (1) + "aa" (2) = 5, exactly the window: kept. + assert _overlap_tail(["aa", "bb"], 5) == ["aa", "bb"] + + def test_first_trailing_part_always_kept_even_if_too_big(self): + # The last sentence is always carried over, even when it alone exceeds + # the overlap window; only earlier sentences are dropped. + assert _overlap_tail(["aaaaa", "bbbb"], 3) == ["bbbb"] + + +# --------------------------------------------------------------------------- # +# _chunk_by_characters: direct behaviour of the fallback chunker +# --------------------------------------------------------------------------- # +class TestChunkByCharacters: + def test_no_overlap_walks_word_by_word(self): + result = _chunk_by_characters("aaaa bbbb cccc dddd", 10, 0) + assert result == ["aaaa bbbb", "cccc dddd"] + + def test_window_without_space_is_cut_at_size(self): + # The first window ("abcdef") contains no space, so it is cut at the + # raw size limit mid-word; later windows snap back to a space. + result = _chunk_by_characters("abcdefghij klmn", 6, 0) + assert result == ["abcdef", "ghij", "klmn"] + + def test_overlap_larger_than_chunk_advances_one_char(self): + # With overlap (5) bigger than chunk_size (4), the start pointer can + # only advance by one character per step, re-reading partial words. + result = _chunk_by_characters("aaaa bbbb", 4, 5) + assert result == ["aaaa", "aaa", "aa", "a", "bbb", "bbbb"] + + def test_whitespace_only_window_is_dropped(self): + # The window at start=1 is a single space: it strips to "" and must be + # skipped rather than emitted. + result = _chunk_by_characters("a b", 2, 0) + assert result == ["a", "b"] + + def test_text_shorter_than_chunk_returns_whole_text(self): + assert _chunk_by_characters("hello world", 100, 10) == ["hello world"] diff --git a/tests/test_comfyui_client_behaviour.py b/tests/test_comfyui_client_behaviour.py new file mode 100644 index 0000000..0acfc6c --- /dev/null +++ b/tests/test_comfyui_client_behaviour.py @@ -0,0 +1,431 @@ +"""Unit tests for ``app.clients.comfyui_client`` (HTTP layer). + +The client is exercised with a fake ``requests.request`` injected via +monkeypatch, so no ComfyUI server or network access is needed. Covers the +request plumbing and every error branch of ``_request``, each public API +method including its failure paths, model discovery helpers, and the +module-level ``_extract_error`` helper. +""" + +from __future__ import annotations + +import json + +import pytest +import requests + +from app.clients.comfyui_client import ComfyUIClient, _extract_error +from app.core.exceptions import ComfyUIServiceError + + +class FakeResponse: + """Minimal stand-in for ``requests.Response``.""" + + def __init__(self, status_code=200, payload=None, content=b"", text=""): + self.status_code = status_code + self.text = text or (content.decode("utf-8", errors="replace") if content else "") + if content: + self.content = content + elif payload is not None: + self.content = json.dumps(payload).encode("utf-8") + else: + self.content = b"" + self._payload = payload + + def json(self): + if self._payload is None and self.content: + return json.loads(self.content) + return self._payload + + +def make_client(monkeypatch, captured, response=None, base_url="http://localhost:8188", timeout=60.0): + """Build a ``ComfyUIClient`` whose HTTP calls land in ``captured``.""" + + def fake_request(*args, **kwargs): + captured.append((args, kwargs)) + return response if response is not None else FakeResponse() + + monkeypatch.setattr("app.clients.comfyui_client.requests.request", fake_request) + from types import SimpleNamespace + + monkeypatch.setattr( + "app.clients.comfyui_client.settings", + SimpleNamespace(comfyui_base_url=base_url + "/", comfyui_timeout=timeout), + ) + return ComfyUIClient() + + +# --------------------------------------------------------------------------- # +# construction and transport +# --------------------------------------------------------------------------- # + + +def test_init_defaults_strip_slash_and_use_settings(monkeypatch): + captured = [] + client = make_client(monkeypatch, captured) + + assert client.base_url == "http://localhost:8188" + assert client.timeout == 60.0 + assert len(client.client_id) == 32 + + +def test_init_explicit_base_and_timeout(monkeypatch): + from types import SimpleNamespace + + monkeypatch.setattr( + "app.clients.comfyui_client.settings", + SimpleNamespace(comfyui_base_url="http://other:1/", comfyui_timeout=99.0), + ) + + client = ComfyUIClient(base_url="http://mine:2/", timeout=7) + + assert client.base_url == "http://mine:2" + assert client.timeout == 7 + + +def test_request_success_returns_json(monkeypatch): + captured = [] + client = make_client(monkeypatch, captured, FakeResponse(200, payload={"ok": True})) + + result = client._request("GET", "/system_stats") + + assert result == {"ok": True} + (args, kwargs), = captured + assert args[0] == "GET" + assert args[1] == "http://localhost:8188/system_stats" + assert kwargs["timeout"] == 60.0 + + +def test_request_raw_returns_content_bytes(monkeypatch): + captured = [] + client = make_client(monkeypatch, captured, FakeResponse(200, content=b"PNGDATA")) + + result = client._request("GET", "/view", raw=True) + + assert result == b"PNGDATA" + + +def test_request_empty_body_returns_empty_dict(monkeypatch): + captured = [] + client = make_client(monkeypatch, captured, FakeResponse(204)) + + result = client._request("GET", "/queue") + + assert result == {} + + +def test_request_malformed_json_raises_502(monkeypatch): + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(200, content=b"{not json"), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + with pytest.raises(ComfyUIServiceError, match="malformed response"): + client._request("GET", "/queue") + + +def test_request_timeout_raises_504(monkeypatch): + def boom(*args, **kwargs): + raise requests.exceptions.Timeout("timed out") + + monkeypatch.setattr("app.clients.comfyui_client.requests.request", boom) + client = ComfyUIClient(base_url="http://localhost:8188", timeout=60.0) + + with pytest.raises(ComfyUIServiceError, match="timed out after 60s") as excinfo: + client._request("GET", "/system_stats") + assert excinfo.value.status_code == 504 + + +def test_request_unreachable_raises_503(monkeypatch): + def boom(*args, **kwargs): + raise requests.exceptions.ConnectionError("connection refused") + + monkeypatch.setattr("app.clients.comfyui_client.requests.request", boom) + client = ComfyUIClient(base_url="http://localhost:8188") + + with pytest.raises(ComfyUIServiceError, match="not reachable at http://localhost:8188"): + client._request("GET", "/system_stats") + + +def test_request_http_error_raises_502_with_extracted_detail(monkeypatch): + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(400, payload={"error": {"message": "bad node"}}), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + with pytest.raises(ComfyUIServiceError) as excinfo: + client._request("POST", "/prompt") + assert excinfo.value.status_code == 502 + assert "rejected the request (400)" in str(excinfo.value) + assert excinfo.value.detail == "bad node" + + +# --------------------------------------------------------------------------- # +# api methods +# --------------------------------------------------------------------------- # + + +def test_ping_returns_stats_and_uses_short_timeout(monkeypatch): + captured = [] + client = make_client( + monkeypatch, captured, FakeResponse(200, payload={"system": {"os": "linux"}}) + ) + + stats = client.ping() + + assert stats == {"system": {"os": "linux"}} + (args, kwargs), = captured + assert args[1].endswith("/system_stats") + assert kwargs["timeout"] == 5 + + +def test_ping_non_dict_raises(monkeypatch): + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(200, payload=[1, 2]), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + with pytest.raises(ComfyUIServiceError, match="unexpected system stats"): + client.ping() + + +def test_object_info_all_nodes_path(monkeypatch): + captured = [] + client = make_client(monkeypatch, captured, FakeResponse(200, payload={"KSampler": {}})) + + result = client.object_info() + + assert result == {"KSampler": {}} + (args, kwargs), = captured + assert args[1].endswith("/object_info") + + +def test_object_info_single_node_path(monkeypatch): + captured = [] + client = make_client(monkeypatch, captured, FakeResponse(200, payload={"KSampler": {}})) + + result = client.object_info("KSampler") + + assert result == {"KSampler": {}} + (args, kwargs), = captured + assert args[1].endswith("/object_info/KSampler") + + +def test_object_info_non_dict_returns_empty(monkeypatch): + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(200, payload=["nope"]), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + assert client.object_info() == {} + + + +def test_queue_prompt_returns_prompt_id(monkeypatch): + captured = [] + client = make_client( + monkeypatch, captured, FakeResponse(200, payload={"prompt_id": "abc-123"}) + ) + + prompt_id = client.queue_prompt({"1": {"class": "KSampler"}}) + + assert prompt_id == "abc-123" + (args, kwargs), = captured + assert args[1].endswith("/prompt") + assert kwargs["json"]["client_id"] == client.client_id + assert kwargs["json"]["prompt"] == {"1": {"class": "KSampler"}} + + +def test_queue_prompt_without_prompt_id_raises_with_node_errors(monkeypatch): + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(200, payload={"node_errors": {"1": "missing input"}}), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + with pytest.raises(ComfyUIServiceError) as excinfo: + client.queue_prompt({"1": {}}) + assert excinfo.value.status_code == 502 + assert "missing input" in excinfo.value.detail + + +def test_queue_prompt_without_prompt_id_uses_payload_in_detail(monkeypatch): + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(200, payload={"status": 400}), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + with pytest.raises(ComfyUIServiceError) as excinfo: + client.queue_prompt({"1": {}}) + assert excinfo.value.detail == "{}" + + +def test_history_returns_record_for_prompt_id(monkeypatch): + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(200, payload={"pid-1": {"status": "complete"}}), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + assert client.history("pid-1") == {"status": "complete"} + + +def test_history_missing_key_or_null_value_returns_empty(monkeypatch): + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(200, payload={"other": 1, "pid-1": None}), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + assert client.history("pid-1") == {} + assert client.history("unknown") == {} + + +def test_history_non_dict_returns_empty(monkeypatch): + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(200, payload=[1]), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + assert client.history("pid-1") == {} + + +def test_queue_state_returns_dict(monkeypatch): + captured = [] + client = make_client( + monkeypatch, captured, FakeResponse(200, payload={"queue_running": [], "queue_pending": []}) + ) + + assert client.queue_state() == {"queue_running": [], "queue_pending": []} + + +def test_view_image_passes_params_and_returns_bytes(monkeypatch): + captured = [] + client = make_client(monkeypatch, captured, FakeResponse(200, content=b"IMGBYTES")) + + data = client.view_image("a.png", subfolder="sf", folder_type="temp") + + assert data == b"IMGBYTES" + (args, kwargs), = captured + assert args[1].endswith("/view") + assert kwargs["params"] == {"filename": "a.png", "subfolder": "sf", "type": "temp"} + + +def test_upload_image_posts_files_and_overwrite_flag(monkeypatch): + captured = [] + client = make_client( + monkeypatch, captured, FakeResponse(200, payload={"name": "b.png", "subfolder": ""}) + ) + + result = client.upload_image("b.png", b"X", overwrite=False) + + assert result == {"name": "b.png", "subfolder": ""} + (args, kwargs), = captured + assert args[1].endswith("/upload/image") + assert kwargs["files"] == {"image": ("b.png", b"X")} + assert kwargs["data"] == {"overwrite": "false"} + + +def test_upload_image_non_dict_returns_empty(monkeypatch): + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(200, payload=["nope"]), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + assert client.upload_image("b.png", b"X") == {} + + +# --------------------------------------------------------------------------- # +# model discovery +# --------------------------------------------------------------------------- # + + +def test_list_loras_extracts_dropdown_options(monkeypatch): + payload = { + "LoraLoader": { + "input": { + "required": { + "lora_name": [["a.safetensors", 2], {"options": ["a.safetensors"]}] + } + } + } + } + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(200, payload=payload), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + assert client.list_loras() == ["a.safetensors", "2"] + + +def test_list_checkpoints_missing_spec_returns_empty(monkeypatch): + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(200, payload={"CheckpointLoaderSimple": {}}), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + assert client.list_checkpoints() == [] + + +def test_combo_options_non_list_spec_returns_empty(monkeypatch): + payload = { + "CheckpointLoaderSimple": {"input": {"required": {"ckpt_name": "not-a-list"}}} + } + monkeypatch.setattr( + "app.clients.comfyui_client.requests.request", + lambda *a, **kw: FakeResponse(200, payload=payload), + ) + client = ComfyUIClient(base_url="http://localhost:8188") + + assert client.list_checkpoints() == [] + + +# --------------------------------------------------------------------------- # +# _extract_error helper +# --------------------------------------------------------------------------- # + + +def test_extract_error_dict_with_message(): + response = FakeResponse(400, payload={"error": {"message": "boom", "code": 7}}) + assert _extract_error(response) == "boom" + + +def test_extract_error_dict_without_message_falls_back_to_str(): + response = FakeResponse(400, payload={"error": {"code": 7}}) + result = _extract_error(response) + assert "code" in result and "7" in result + + +def test_extract_error_plain_string_error(): + response = FakeResponse(400, payload={"error": "plain problem"}) + assert _extract_error(response) == "plain problem" + + +def test_extract_error_node_errors_fallback(): + response = FakeResponse(400, payload={"node_errors": {"1": "bad edge"}}) + assert _extract_error(response) == str({"1": "bad edge"})[:500] + + +def test_extract_error_plain_body_truncated(): + response = FakeResponse(400, payload={"foo": "x" * 600}) + assert len(_extract_error(response)) <= 500 + + +def test_extract_error_bad_json_returns_text(): + response = FakeResponse(400, content=b"oops", text="plain error text") + assert _extract_error(response) == "plain error text"[:500] + + +def test_extract_error_non_dict_body(): + response = FakeResponse(400, payload=[1, 2, 3]) + assert _extract_error(response) == "[1, 2, 3]" + diff --git a/tests/test_comfyui_routes_behaviour.py b/tests/test_comfyui_routes_behaviour.py new file mode 100644 index 0000000..ca43947 --- /dev/null +++ b/tests/test_comfyui_routes_behaviour.py @@ -0,0 +1,700 @@ +"""Behavioural tests for app/api/comfyui_routes.py.""" + +from __future__ import annotations + +from typing import Any + +import pytest +from fastapi import FastAPI, HTTPException +from fastapi.testclient import TestClient + +from app.api.comfyui_routes import _http_error, jobs_router, router +from app.core.exceptions import ComfyUIServiceError, ServiceError, WorkflowError +from app.core.jobs import TERMINAL_STATUSES, Job, JobStatus +from app.core.paths import UnsafePathError + + +class FakeWorkflowInfo: + def __init__(self, data: dict) -> None: + self._data = dict(data) + + def to_dict(self) -> dict: + return dict(self._data) + + +def _job(job_id: str, status: JobStatus = JobStatus.QUEUED, **overrides) -> Job: + data: dict[str, Any] = { + "id": job_id, + "type": "generation", + "status": status, + "created_at": "2026-01-01T00:00:00+00:00", + } + data.update(overrides) + return Job(**data) + + +class FakeComfyUIService: + def __init__(self) -> None: + self.status_payload = { + "connected": True, + "base_url": "http://127.0.0.1:8188", + "version": "0.3.45", + "python_version": "3.12.4", + "devices": [{"name": "NVIDIA GeForce RTX 4090", "vram_gb": 24}], + "checkpoints": ["sd_xl_base.safetensors"], + "loras": ["cat_lora.safetensors"], + "error": None, + } + self.workflows = [ + FakeWorkflowInfo({ + "id": "txt2img", + "name": "SDXL txt2img", + "description": "Base text to image", + "arch": "sdxl", + "inputs": {"prompt": {"3": "text"}}, + "supported_inputs": ["prompt"], + "node_count": 7, + }), + FakeWorkflowInfo({ + "id": "img2img", + "name": "SDXL img2img", + "description": "", + "arch": "sdxl", + "inputs": {}, + "supported_inputs": [], + "node_count": 9, + }), + ] + self.save_calls: list[dict] = [] + self.save_error: Exception | None = None + self.load_result: tuple[dict, dict] = ( + { + "1": {"class_type": "KSampler"}, + "2": {"class_type": "CheckpointLoaderSimple"}, + }, + {"prompt": {"1": "seed"}}, + ) + self.load_error: Exception | None = None + self.delete_result = True + self.delete_error: Exception | None = None + self.submit_result = _job("gen-new") + self.submit_calls: list[tuple] = [] + self.submit_error: Exception | None = None + self.validate_result: dict = {} + self.validate_calls: list[tuple] = [] + self.validate_error: Exception | None = None + self.generated: list[dict] = [] + self.list_error: Exception | None = None + self.list_calls: list[int] = [] + self.lora_result: dict = {} + self.lora_calls: list[tuple] = [] + self.lora_error: Exception | None = None + self.image_bytes = b"" + self.read_calls: list[str] = [] + self.read_error: Exception | None = None + + def status(self) -> dict: + return dict(self.status_payload) + + def list_workflows(self) -> list[FakeWorkflowInfo]: + return list(self.workflows) + + def save_workflow( + self, + name: str, + graph: dict, + description: str = "", + arch: str = "generic", + inputs: dict | None = None, + ) -> FakeWorkflowInfo: + self.save_calls.append({ + "name": name, + "graph": graph, + "description": description, + "arch": arch, + "inputs": inputs, + }) + if self.save_error is not None: + raise self.save_error + mapping = inputs or {} + return FakeWorkflowInfo({ + "id": name.lower().replace(" ", "_"), + "name": name, + "description": description, + "arch": arch, + "inputs": mapping, + "supported_inputs": sorted(mapping), + "node_count": len(graph), + }) + + def load_workflow(self, workflow_id: str) -> tuple[dict, dict]: + if self.load_error is not None: + raise self.load_error + return self.load_result + + def delete_workflow(self, workflow_id: str) -> bool: + if self.delete_error is not None: + raise self.delete_error + return self.delete_result + + def submit_generation(self, workflow_id: str, params: dict) -> Job: + self.submit_calls.append((workflow_id, params)) + if self.submit_error is not None: + raise self.submit_error + return self.submit_result + + def validate_workflow_request(self, workflow_id: str, params: dict) -> dict: + self.validate_calls.append((workflow_id, params)) + if self.validate_error is not None: + raise self.validate_error + return self.validate_result + + def list_generated(self, limit: int = 50) -> list[dict]: + self.list_calls.append(limit) + if self.list_error is not None: + raise self.list_error + return list(self.generated) + + def prepare_lora_test( + self, + lora_filename: str, + workflow_id: str | None = None, + prompt: str | None = None, + trigger_word: str | None = None, + ) -> dict: + self.lora_calls.append((lora_filename, workflow_id, prompt, trigger_word)) + if self.lora_error is not None: + raise self.lora_error + return self.lora_result + + def read_generated(self, filename: str) -> bytes: + self.read_calls.append(filename) + if self.read_error is not None: + raise self.read_error + return self.image_bytes + + +class FakeJobStore: + """Mirrors JobStore.get/list/cancel semantics with fixed timestamps.""" + + def __init__(self, jobs: list[Job]) -> None: + self.jobs = {job.id: job for job in jobs} + self.list_calls: list[tuple] = [] + self.cancel_calls: list[str] = [] + + def get(self, job_id: str) -> Job | None: + return self.jobs.get(job_id) + + def list(self, job_type: str | None = None, limit: int = 50) -> list[Job]: + self.list_calls.append((job_type, limit)) + jobs = [j for j in self.jobs.values() if not job_type or j.type == job_type] + jobs.sort(key=lambda job: job.created_at, reverse=True) + return jobs[:limit] + + def cancel(self, job_id: str) -> bool: + self.cancel_calls.append(job_id) + job = self.jobs.get(job_id) + if job is None or job.status in TERMINAL_STATUSES: + return False + job.status = JobStatus.CANCELLED + job.completed_at = "2026-01-01T00:00:10+00:00" + return True + + +@pytest.fixture() +def client(): + app = FastAPI() + app.include_router(router) + app.include_router(jobs_router) + app.state.comfyui_service = FakeComfyUIService() + app.state.job_store = FakeJobStore([ + _job("gen-1"), + _job( + "train-1", + type="training", + status=JobStatus.COMPLETED, + started_at="2026-01-01T00:00:05+00:00", + completed_at="2026-01-01T00:00:35+00:00", + ), + ]) + return TestClient(app) + + +QUEUED_JOB_RESPONSE: dict[str, Any] = { + "id": "gen-1", + "type": "generation", + "status": "queued", + "created_at": "2026-01-01T00:00:00+00:00", + "started_at": None, + "completed_at": None, + "elapsed_seconds": None, + "progress": None, + "message": None, + "error": None, + "outputs": [], + "metadata": {}, +} + +DONE_JOB_RESPONSE = { + "id": "train-1", + "type": "training", + "status": "completed", + "created_at": "2026-01-01T00:00:00+00:00", + "started_at": "2026-01-01T00:00:05+00:00", + "completed_at": "2026-01-01T00:00:35+00:00", + "elapsed_seconds": 30.0, + "progress": None, + "message": None, + "error": None, + "outputs": [], + "metadata": {}, +} + + +# ============================================ +# CONNECTION +# ============================================ + + +def test_status_returns_service_payload(client): + resp = client.get("/comfyui/status") + assert resp.status_code == 200 + assert resp.json() == { + "connected": True, + "base_url": "http://127.0.0.1:8188", + "version": "0.3.45", + "python_version": "3.12.4", + "devices": [{"name": "NVIDIA GeForce RTX 4090", "vram_gb": 24}], + "checkpoints": ["sd_xl_base.safetensors"], + "loras": ["cat_lora.safetensors"], + "error": None, + } + + +def test_status_reports_offline_without_raising(client): + service = client.app.state.comfyui_service + service.status_payload.update(connected=False, version=None, error="Connection refused") + resp = client.get("/comfyui/status") + assert resp.status_code == 200 + body = resp.json() + assert body["connected"] is False + assert body["error"] == "Connection refused" + + +def test_test_connection_returns_same_payload(client): + resp = client.post("/comfyui/test") + assert resp.status_code == 200 + body = resp.json() + assert body["connected"] is True + assert body["base_url"] == "http://127.0.0.1:8188" + + +# ============================================ +# WORKFLOWS +# ============================================ + + +def test_list_workflows_maps_summaries_and_count(client): + resp = client.get("/comfyui/workflows") + assert resp.status_code == 200 + body = resp.json() + assert body["count"] == 2 + assert body["workflows"][0] == { + "id": "txt2img", + "name": "SDXL txt2img", + "description": "Base text to image", + "arch": "sdxl", + "inputs": {"prompt": {"3": "text"}}, + "supported_inputs": ["prompt"], + "node_count": 7, + } + assert body["workflows"][1]["id"] == "img2img" + + +def test_list_workflows_empty(client): + client.app.state.comfyui_service.workflows = [] + resp = client.get("/comfyui/workflows") + assert resp.status_code == 200 + assert resp.json() == {"workflows": [], "count": 0} + + +def test_import_workflow_passes_all_fields(client): + service = client.app.state.comfyui_service + payload = { + "name": "Flux dev", + "workflow": {"3": {"class_type": "KSampler"}}, + "description": "Flux pipeline", + "arch": "flux", + "inputs": {"prompt": {"6": "text"}}, + } + resp = client.post("/comfyui/workflows", json=payload) + assert resp.status_code == 200 + assert service.save_calls == [{ + "name": "Flux dev", + "graph": {"3": {"class_type": "KSampler"}}, + "description": "Flux pipeline", + "arch": "flux", + "inputs": {"prompt": {"6": "text"}}, + }] + assert resp.json() == { + "id": "flux_dev", + "name": "Flux dev", + "description": "Flux pipeline", + "arch": "flux", + "inputs": {"prompt": {"6": "text"}}, + "supported_inputs": ["prompt"], + "node_count": 1, + } + + +def test_import_workflow_applies_defaults(client): + service = client.app.state.comfyui_service + resp = client.post( + "/comfyui/workflows", + json={"name": "Minimal", "workflow": {"1": {"class_type": "KSampler"}}}, + ) + assert resp.status_code == 200 + call = service.save_calls[0] + assert call["description"] == "" + assert call["arch"] == "generic" + assert call["inputs"] is None + assert resp.json() == { + "id": "minimal", + "name": "Minimal", + "description": "", + "arch": "generic", + "inputs": {}, + "supported_inputs": [], + "node_count": 1, + } + + +def test_import_workflow_maps_service_errors(client): + service = client.app.state.comfyui_service + payload = {"name": "Broken", "workflow": {}} + + service.save_error = WorkflowError( + "bad graph", status_code=400, detail="Node 3 has no class_type") + resp = client.post("/comfyui/workflows", json=payload) + assert resp.status_code == 400 + assert resp.json()["detail"] == "Node 3 has no class_type" + + service.save_error = ComfyUIServiceError( + "ComfyUI unreachable", status_code=502, detail="Connection refused") + resp = client.post("/comfyui/workflows", json=payload) + assert resp.status_code == 502 + assert resp.json()["detail"] == "Connection refused" + + +def test_get_workflow_returns_graph_mapping_and_nodes(client): + resp = client.get("/comfyui/workflows/txt2img") + assert resp.status_code == 200 + assert resp.json() == { + "id": "txt2img", + "workflow": { + "1": {"class_type": "KSampler"}, + "2": {"class_type": "CheckpointLoaderSimple"}, + }, + "inputs": {"prompt": {"1": "seed"}}, + "nodes": [ + {"id": "1", "class_type": "KSampler"}, + {"id": "2", "class_type": "CheckpointLoaderSimple"}, + ], + } + + +def test_get_workflow_maps_errors(client): + service = client.app.state.comfyui_service + + service.load_error = WorkflowError( + "no such workflow", status_code=404, detail="Workflow 'ghost' not found") + resp = client.get("/comfyui/workflows/ghost") + assert resp.status_code == 404 + assert resp.json()["detail"] == "Workflow 'ghost' not found" + + service.load_error = UnsafePathError("../outside/graph.json") + resp = client.get("/comfyui/workflows/evil") + assert resp.status_code == 400 + assert resp.json()["detail"] == "Invalid path" + + +def test_delete_workflow_found_missing_and_unsafe(client): + service = client.app.state.comfyui_service + + resp = client.delete("/comfyui/workflows/txt2img") + assert resp.status_code == 200 + assert resp.json() == {"message": "Workflow txt2img deleted"} + + service.delete_result = False + resp = client.delete("/comfyui/workflows/ghost") + assert resp.status_code == 404 + assert resp.json()["detail"] == "Workflow 'ghost' not found" + + service.delete_error = UnsafePathError("../outside/graph.json") + resp = client.delete("/comfyui/workflows/evil") + assert resp.status_code == 400 + assert resp.json()["detail"] == "Invalid path" + + +# ============================================ +# GENERATION +# ============================================ + + +def test_generate_queues_job_and_strips_none_params(client): + service = client.app.state.comfyui_service + resp = client.post( + "/comfyui/generate", json={"workflow_id": "txt2img", "prompt": "a cat", "seed": 42}) + assert resp.status_code == 200 + assert service.submit_calls == [("txt2img", {"prompt": "a cat", "seed": 42})] + body = resp.json() + assert body["id"] == "gen-new" + assert body["status"] == "queued" + assert body["elapsed_seconds"] is None + + +def test_generate_rejects_out_of_range_steps(client): + service = client.app.state.comfyui_service + resp = client.post("/comfyui/generate", json={"workflow_id": "txt2img", "steps": 0}) + assert resp.status_code == 422 + assert service.submit_calls == [] + + +def test_generate_maps_errors(client): + service = client.app.state.comfyui_service + + service.submit_error = ComfyUIServiceError( + "ComfyUI unreachable", status_code=503, detail="ComfyUI is not running") + resp = client.post("/comfyui/generate", json={"workflow_id": "txt2img"}) + assert resp.status_code == 503 + assert resp.json()["detail"] == "ComfyUI is not running" + + service.submit_error = UnsafePathError("../outside/graph.json") + resp = client.post("/comfyui/generate", json={"workflow_id": "evil"}) + assert resp.status_code == 400 + assert resp.json()["detail"] == "Invalid path" + + +def test_validate_generation_reports_gaps(client): + service = client.app.state.comfyui_service + service.validate_result = { + "ok": False, + "checks": [{"field": "checkpoint", "problem": "not installed"}], + } + resp = client.post( + "/comfyui/validate-generation", json={"workflow_id": "txt2img", "prompt": "x"}) + assert resp.status_code == 200 + assert resp.json() == { + "ok": False, + "checks": [{"field": "checkpoint", "problem": "not installed"}], + } + assert service.validate_calls == [("txt2img", {"prompt": "x"})] + + +def test_validate_generation_maps_errors(client): + service = client.app.state.comfyui_service + service.validate_error = WorkflowError( + "no such workflow", status_code=404, detail="Workflow 'ghost' not found") + resp = client.post("/comfyui/validate-generation", json={"workflow_id": "ghost"}) + assert resp.status_code == 404 + assert resp.json()["detail"] == "Workflow 'ghost' not found" + + +def test_list_generated_clamps_limit_and_counts(client): + service = client.app.state.comfyui_service + service.generated = [{"filename": "out-1.png"}, {"filename": "out-2.jpg"}] + + resp = client.get("/comfyui/generated", params={"limit": 999}) + assert resp.status_code == 200 + assert resp.json() == { + "images": [{"filename": "out-1.png"}, {"filename": "out-2.jpg"}], + "count": 2, + } + + client.get("/comfyui/generated", params={"limit": 0}) + client.get("/comfyui/generated") + assert service.list_calls == [200, 1, 50] + + +def test_list_generated_maps_errors(client): + service = client.app.state.comfyui_service + service.list_error = ServiceError( + "disk gone", status_code=502, detail="Output folder missing") + resp = client.get("/comfyui/generated") + assert resp.status_code == 502 + assert resp.json()["detail"] == "Output folder missing" + + +# ============================================ +# LORA TESTS +# ============================================ + + +def test_lora_test_passes_all_fields(client): + service = client.app.state.comfyui_service + service.lora_result = {"job_id": "train-1", "status": "queued"} + resp = client.get( + "/comfyui/test-lora", + params={ + "lora": "cat_lora.safetensors", + "workflow_id": "txt2img", + "prompt": "a cat", + "trigger_word": "cat", + }, + ) + assert resp.status_code == 200 + assert service.lora_calls == [("cat_lora.safetensors", "txt2img", "a cat", "cat")] + assert resp.json() == {"job_id": "train-1", "status": "queued"} + + +def test_lora_test_defaults_and_error(client): + service = client.app.state.comfyui_service + + resp = client.get("/comfyui/test-lora", params={"lora": "cat.safetensors"}) + assert resp.status_code == 200 + assert service.lora_calls[0] == ("cat.safetensors", None, None, None) + + service.lora_error = WorkflowError( + "no such workflow", status_code=404, detail="Workflow 'ghost' not found") + resp = client.get("/comfyui/test-lora", params={"lora": "cat.safetensors"}) + assert resp.status_code == 404 + assert resp.json()["detail"] == "Workflow 'ghost' not found" + + +# ============================================ +# JOBS ROUTER +# ============================================ + + +def test_get_job_returns_full_response(client): + resp = client.get("/jobs/gen-1") + assert resp.status_code == 200 + assert resp.json() == QUEUED_JOB_RESPONSE + + resp = client.get("/jobs/train-1") + assert resp.status_code == 200 + assert resp.json() == DONE_JOB_RESPONSE + + +def test_get_job_missing(client): + resp = client.get("/jobs/nope") + assert resp.status_code == 404 + assert resp.json()["detail"] == "Job nope not found" + + +def test_list_jobs_filters_sorts_and_limits(client): + store = client.app.state.job_store + + resp = client.get("/jobs") + assert resp.status_code == 200 + body = resp.json() + assert body["count"] == 2 + assert [job["id"] for job in body["jobs"]] == ["gen-1", "train-1"] + assert store.list_calls[-1] == (None, 50) + + resp = client.get("/jobs", params={"job_type": "training", "limit": 1}) + assert resp.status_code == 200 + body = resp.json() + assert body["count"] == 1 + assert [job["id"] for job in body["jobs"]] == ["train-1"] + assert store.list_calls[-1] == ("training", 1) + + +def test_cancel_job_marks_cancelled(client): + store = client.app.state.job_store + resp = client.delete("/jobs/gen-1") + assert resp.status_code == 200 + body = resp.json() + assert body["id"] == "gen-1" + assert body["status"] == "cancelled" + assert body["completed_at"] == "2026-01-01T00:00:10+00:00" + assert body["elapsed_seconds"] is None # never started + assert store.cancel_calls == ["gen-1"] + + +def test_cancel_job_missing_returns_404(client): + resp = client.delete("/jobs/nope") + assert resp.status_code == 404 + assert resp.json()["detail"] == "Job nope not found" + + +def test_cancel_finished_job_returns_409(client): + resp = client.delete("/jobs/train-1") + assert resp.status_code == 409 + assert resp.json()["detail"] == "Job train-1 has already finished" + + +def test_get_generation_job_via_comfyui_prefix(client): + resp = client.get("/comfyui/jobs/gen-1") + assert resp.status_code == 200 + assert resp.json() == QUEUED_JOB_RESPONSE + + resp = client.get("/comfyui/jobs/nope") + assert resp.status_code == 404 + assert resp.json()["detail"] == "Job nope not found" + + +# ============================================ +# GENERATED IMAGES +# ============================================ + + +def test_generated_image_streams_bytes_with_content_type(client): + service = client.app.state.comfyui_service + service.image_bytes = b"\x89PNG fake bytes" + resp = client.get("/comfyui/images/out-1.png") + assert resp.status_code == 200 + assert resp.content == b"\x89PNG fake bytes" + assert resp.headers["content-type"] == "image/png" + assert service.read_calls == ["out-1.png"] + + +def test_generated_image_jpeg_content_type(client): + client.app.state.comfyui_service.image_bytes = b"jpeg-bytes" + resp = client.get("/comfyui/images/out-2.jpg") + assert resp.status_code == 200 + assert resp.headers["content-type"] == "image/jpeg" + + +def test_generated_image_maps_errors(client): + service = client.app.state.comfyui_service + + service.read_error = UnsafePathError("../outside/secret.png") + resp = client.get("/comfyui/images/evil.png") + assert resp.status_code == 400 + assert resp.json()["detail"] == "Invalid path" + + service.read_error = ServiceError( + "file gone", status_code=502, detail="Image 'ghost.png' not found") + resp = client.get("/comfyui/images/ghost.png") + assert resp.status_code == 502 + assert resp.json()["detail"] == "Image 'ghost.png' not found" + + +# ============================================ +# _http_error HELPER +# ============================================ + + +def test_http_error_uses_exception_status_and_detail(): + exc = WorkflowError("bad", status_code=418, detail="teapot") + err = _http_error(exc) + assert isinstance(err, HTTPException) + assert err.status_code == 418 + assert err.detail == "teapot" + + +def test_http_error_defaults_to_502_and_message(): + exc = ComfyUIServiceError("ComfyUI unreachable") + err = _http_error(exc) + assert isinstance(err, HTTPException) + assert err.status_code == 502 + assert err.detail == "ComfyUI unreachable" + + +def test_http_error_falls_back_to_500_for_unknown(): + exc = RuntimeError("boom") + err = _http_error(exc) + assert isinstance(err, HTTPException) + assert err.status_code == 500 + assert err.detail == "Unexpected error" diff --git a/tests/test_dashboard_behaviour.py b/tests/test_dashboard_behaviour.py new file mode 100644 index 0000000..7c4ed58 --- /dev/null +++ b/tests/test_dashboard_behaviour.py @@ -0,0 +1,378 @@ +"""Behaviour tests for app/services/dashboard.py (build_dashboard and probes).""" + +from __future__ import annotations + +import re +import time +from pathlib import Path +from types import SimpleNamespace + +import pytest +import requests + +# ---------- fakes ----------------------------------------------------------- + + +class FakeDocumentService: + def __init__(self, documents=None, error=None): + self._documents = list(documents or []) + self._error = error + + def get_all_documents(self): + if self._error is not None: + raise self._error + return list(self._documents) + + +class FakeRagService: + def __init__(self, chunk_count=0, backend="ollama", model="nomic-embed-text"): + self.chunk_count = chunk_count + self.embedding_client = SimpleNamespace(backend=backend, model=model) + + +class FakeImage: + def __init__(self, caption): + self.caption = caption + + +class FakeProjectService: + def __init__(self, projects=None, images_by_project=None, error=None): + self._projects = list(projects or []) + self._images = dict(images_by_project or {}) + self._error = error + + def list_projects(self): + if self._error is not None: + raise self._error + return list(self._projects) + + def list_images(self, project_id): + return list(self._images.get(project_id, [])) + + +class FakeTrainingService: + def __init__(self, runs_by_project=None): + self._runs = dict(runs_by_project or {}) + + def list_runs(self, project_id): + return list(self._runs.get(project_id, [])) + + +class FakeComfyuiService: + def __init__(self, generated=None, error=None): + self._generated = list(generated or []) + self._error = error + self.limit_calls = [] + + def list_generated(self, limit=50): + self.limit_calls.append(limit) + if self._error is not None: + raise self._error + return list(self._generated) + + +class BrokenJobStore: + def __init__(self, error): + self._error = error + + def list(self, limit=50): + raise self._error + + +def make_project(project_id, name="P", trained_lora_path=None): + return SimpleNamespace( + id=project_id, + name=name, + arch="sdxl", + trigger_word="p3r5on", + training_status="idle", + trained_lora_path=trained_lora_path, + ) + + +def healthy_fakes(): + return dict( + document_service=FakeDocumentService(), + rag_service=FakeRagService(), + project_service=FakeProjectService(), + training_service=FakeTrainingService(), + comfyui_service=FakeComfyuiService(), + job_store=None, # filled per test (real JobStore) + ) + + +def build(fakes): + from app.services.dashboard import build_dashboard + + return build_dashboard(**fakes) + + +@pytest.fixture(autouse=True) +def offline_probes(monkeypatch): + """build_dashboard always probes Ollama/ComfyUI; keep it off the network.""" + calls = [] + + def fake_get(url, timeout=None): + calls.append((url, timeout)) + return SimpleNamespace(status_code=200) + + monkeypatch.setattr(requests, "get", fake_get) + return calls + + +# ---------- documents section ----------------------------------------------- + + +class TestDocumentsSection: + def test_reports_counts_and_embedding_info(self, offline_probes): + fakes = healthy_fakes() + fakes["document_service"] = FakeDocumentService(documents=["d1", "d2"]) + fakes["rag_service"] = FakeRagService( + chunk_count=7, backend="sentence-transformers", model="all-MiniLM-L6-v2" + ) + + data = build(fakes) + + assert data["documents"] == { + "count": 2, + "indexed_chunks": 7, + "embedding_backend": "sentence-transformers", + "embedding_model": "all-MiniLM-L6-v2", + } + + def test_error_message_is_truncated_to_120_chars(self, offline_probes): + fakes = healthy_fakes() + fakes["document_service"] = FakeDocumentService(error=RuntimeError("x" * 300)) + + data = build(fakes) + + assert data["documents"] == {"error": "x" * 120} + # the other sections are still built + assert set(data) >= {"datasets", "generations", "jobs", "health"} + + +# ---------- datasets section ------------------------------------------------- + + +class TestDatasetsSection: + def test_aggregates_images_captions_and_runs(self, offline_probes): + p1 = make_project("p1", name="Alpha", trained_lora_path="/loras/alpha.safetensors") + p2 = make_project("p2", name="Beta") + images = { + "p1": [FakeImage(""), FakeImage(" "), FakeImage("a cat")], + "p2": [FakeImage("one"), FakeImage("two")], + } + runs = { + "p1": [{"id": "r2", "status": "completed"}, {"id": "r1", "status": "failed"}], + } + fakes = healthy_fakes() + fakes["project_service"] = FakeProjectService(projects=[p1, p2], images_by_project=images) + fakes["training_service"] = FakeTrainingService(runs_by_project=runs) + + data = build(fakes) + + datasets = data["datasets"] + assert datasets["project_count"] == 2 + assert datasets["image_count"] == 5 + assert datasets["lora_count"] == 1 + alpha, beta = datasets["projects"] + assert alpha == { + "id": "p1", + "name": "Alpha", + "arch": "sdxl", + "trigger_word": "p3r5on", + "training_status": "idle", + "image_count": 3, + "captioned_count": 1, + "run_count": 2, + "latest_run": {"id": "r2", "status": "completed"}, + "trained_lora_path": "/loras/alpha.safetensors", + } + assert beta["image_count"] == 2 + assert beta["captioned_count"] == 2 + assert beta["run_count"] == 0 + assert beta["latest_run"] is None + assert beta["trained_lora_path"] is None + + def test_error_reports_truncated_message(self, offline_probes): + fakes = healthy_fakes() + fakes["project_service"] = FakeProjectService(error=RuntimeError("d" * 200)) + + data = build(fakes) + + assert data["datasets"] == {"error": "d" * 120} + + +# ---------- generations section ---------------------------------------------- + + +class TestGenerationsSection: + def test_passes_limit_12_and_lists_recent(self, offline_probes): + generated = [{"file": f"g{i}.png"} for i in range(3)] + comfyui = FakeComfyuiService(generated=generated) + fakes = healthy_fakes() + fakes["comfyui_service"] = comfyui + + data = build(fakes) + + assert comfyui.limit_calls == [12] + assert data["generations"]["recent_count"] == 3 + assert data["generations"]["recent"] == generated + + def test_error_reports_message(self, offline_probes): + fakes = healthy_fakes() + fakes["comfyui_service"] = FakeComfyuiService(error=RuntimeError("comfyui down")) + + data = build(fakes) + + assert data["generations"] == {"error": "comfyui down"} + + +# ---------- jobs section ------------------------------------------------------ + + +class TestJobsSection: + def test_active_jobs_are_queued_or_running_only(self, offline_probes): + from app.core.jobs import JobStatus, JobStore + + store = JobStore() + queued = store.create("caption") + running = store.create("generate") + store.update( + running.id, status=JobStatus.RUNNING, progress=40.0, message="halfway" + ) + done = store.create("train") + store.update(done.id, status=JobStatus.COMPLETED) + + fakes = healthy_fakes() + fakes["job_store"] = store + + data = build(fakes) + + jobs = data["jobs"] + assert jobs["active_count"] == 2 + # newest first: running (created second), then queued + assert jobs["active"][0] == { + "id": running.id, + "type": "generate", + "status": "running", + "progress": 40.0, + "message": "halfway", + "elapsed_seconds": None, # never started (no started_at) + "created_at": running.created_at, + } + assert jobs["active"][1]["id"] == queued.id + assert jobs["active"][1]["status"] == "queued" + assert jobs["active"][1]["progress"] is None + assert jobs["active"][1]["message"] is None + + def test_recent_is_capped_at_six(self, offline_probes): + from app.core.jobs import JobStore + + store = JobStore() + created = [store.create("generate") for _ in range(8)] + newest_first = sorted(created, key=lambda job: job.created_at, reverse=True) + + fakes = healthy_fakes() + fakes["job_store"] = store + + data = build(fakes) + + recent_ids = [entry["id"] for entry in data["jobs"]["recent"]] + assert len(recent_ids) == 6 + assert recent_ids == [job.id for job in newest_first[:6]] + + def test_error_reports_message(self, offline_probes): + fakes = healthy_fakes() + fakes["job_store"] = BrokenJobStore(RuntimeError("jobs broken")) + + data = build(fakes) + + assert data["jobs"] == {"error": "jobs broken"} + + +# ---------- health section ---------------------------------------------------- + + +class TestHealthSection: + def test_probe_reports_online_for_status_below_500(self, offline_probes): + from app.services.dashboard import _probe + + result = _probe("http://ollama.test/api/version") + + assert result == {"online": True, "url": "http://ollama.test/api/version"} + assert offline_probes == [("http://ollama.test/api/version", 2.0)] + + def test_probe_reports_offline_for_server_error_status(self, monkeypatch): + from app.services.dashboard import _probe + + monkeypatch.setattr( + requests, "get", lambda url, timeout=None: SimpleNamespace(status_code=503) + ) + + assert _probe("http://comfy.test/system_stats") == { + "online": False, + "url": "http://comfy.test/system_stats", + } + + def test_probe_reports_offline_when_connection_fails(self, monkeypatch): + from app.services.dashboard import _probe + + def fake_get(url, timeout=None): + raise requests.ConnectionError("connection refused") + + monkeypatch.setattr(requests, "get", fake_get) + + assert _probe("http://down.test/api/version") == { + "online": False, + "url": "http://down.test/api/version", + } + + def test_health_uses_configured_urls_and_toolkit_state( + self, tmp_settings, set_setting, offline_probes + ): + set_setting("ollama_base_url", "http://ollama.test") + set_setting("comfyui_base_url", "http://comfy.test") + + data = build(healthy_fakes()) + + assert data["health"]["ollama"] == { + "online": True, + "url": "http://ollama.test/api/version", + } + assert data["health"]["comfyui"] == { + "online": True, + "url": "http://comfy.test/system_stats", + } + # tmp_settings leaves the toolkit unconfigured (empty path) + assert data["health"]["ai_toolkit"] == {"configured": False, "detail": "not configured"} + + def test_health_reports_configured_toolkit_path( + self, tmp_settings, set_setting, offline_probes + ): + toolkit = Path(tmp_settings.data_dir) / "ai-toolkit" + toolkit.mkdir(parents=True) + (toolkit / "run.py").write_text("print('hi')\n", encoding="utf-8") + interpreter = Path(tmp_settings.data_dir) / "python.exe" + interpreter.write_text("", encoding="utf-8") + set_setting("ai_toolkit_path", str(toolkit)) + set_setting("ai_toolkit_python", str(interpreter)) + + data = build(healthy_fakes()) + + assert data["health"]["ai_toolkit"] == { + "configured": True, + "detail": str(toolkit), + } + + +# ---------- generated_at ------------------------------------------------------- + + +class TestGeneratedAt: + def test_is_utc_timestamp(self, offline_probes): + data = build(healthy_fakes()) + + stamp = data["generated_at"] + assert re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}", stamp) is not None + assert stamp.startswith(time.strftime("%Y-%m-%d", time.gmtime())) diff --git a/tests/test_dataset_validation_behaviour.py b/tests/test_dataset_validation_behaviour.py new file mode 100644 index 0000000..e662d50 --- /dev/null +++ b/tests/test_dataset_validation_behaviour.py @@ -0,0 +1,619 @@ +"""Behaviour tests for app/services/dataset_validation.py.""" + +from __future__ import annotations + +import pytest + + +def _png(width: int, height: int, color=(200, 30, 90)) -> bytes: + """A solid-color RGB PNG of the given size.""" + from io import BytesIO + + from PIL import Image + + buffer = BytesIO() + Image.new("RGB", (width, height), color=color).save(buffer, format="PNG") + return buffer.getvalue() + + +def _gradient_png(width: int, height: int) -> bytes: + """A vertical grayscale gradient - structured aHash, not low-entropy.""" + from io import BytesIO + + from PIL import Image + + img = Image.linear_gradient("L").resize((width, height)).convert("RGB") + buffer = BytesIO() + img.save(buffer, format="PNG") + return buffer.getvalue() + + +def _entry(image_id: str, caption="a proper caption", filename=None) -> dict: + entry = {"id": image_id, "caption": caption} + if filename is not None: + entry["filename"] = filename + return entry + + +# ---------- ImageFinding / DatasetReport -------------------------------------- + + +class TestImageFindingToDict: + def test_to_dict_returns_all_fields(self): + from app.services.dataset_validation import ImageFinding + + finding = ImageFinding("img1", "a.png", "duplicate", "identical to img0") + + assert finding.to_dict() == { + "image_id": "img1", + "filename": "a.png", + "kind": "duplicate", + "detail": "identical to img0", + } + + +class TestDatasetReport: + def test_issue_count_tracks_findings(self): + from app.services.dataset_validation import DatasetReport, ImageFinding + + report = DatasetReport(total_images=3) + assert report.issue_count == 0 + report.findings.append(ImageFinding("a", "a.png", "invalid")) + report.findings.append(ImageFinding("b", "b.png", "duplicate")) + + assert report.issue_count == 2 + + def test_to_dict_aggregates_finding_kinds(self): + from app.services.dataset_validation import DatasetReport, ImageFinding + + report = DatasetReport(total_images=4, valid_images=3, captioned=1) + report.average_resolution = (512, 512) + report.score = 78 + for image_id, kind in [ + ("a", "missing_caption"), + ("b", "duplicate"), + ("c", "near_duplicate"), + ("d", "near_duplicate_possible"), + ("e", "extreme_resolution"), + ]: + report.findings.append(ImageFinding(image_id, f"{image_id}.png", kind)) + + data = report.to_dict() + + assert data["total_images"] == 4 + assert data["valid_images"] == 3 + assert data["invalid_images"] == 1 + assert data["captioned"] == 1 + assert data["missing_captions"] == 1 + assert data["duplicates"] == 1 + assert data["near_duplicates"] == 1 + assert data["possible_duplicates"] == 1 + assert data["extreme_resolutions"] == 1 + assert data["average_resolution"] == [512, 512] + assert data["issue_count"] == 5 + assert data["score"] == 78 + assert len(data["findings"]) == 5 + + def test_to_dict_average_resolution_none_when_unset(self): + from app.services.dataset_validation import DatasetReport + + assert DatasetReport().to_dict()["average_resolution"] is None + + +# ---------- classify_pair ----------------------------------------------------- + + +class TestClassifyPair: + def test_identical_flat_hashes_need_matching_color(self): + from app.services.dataset_validation import classify_pair + + flat = "0" * 16 + # Far apart mean colors -> not the same picture. + assert ( + classify_pair(flat, flat, color_a=(255, 0, 0), color_b=(0, 0, 255)) + == "unique" + ) + # Close mean colors -> high-confidence near-duplicate. + assert ( + classify_pair(flat, flat, color_a=(100, 100, 100), color_b=(105, 98, 102)) + == "near_duplicate_high" + ) + + def test_identical_hash_without_colors_is_high(self): + from app.services.dataset_validation import classify_pair + + assert ( + classify_pair("5555555555555555", "5555555555555555") + == "near_duplicate_high" + ) + + def test_identical_structured_hash_ignores_color(self): + from app.services.dataset_validation import classify_pair + + # Not low-entropy, so the color corroboration does not apply. + assert ( + classify_pair( + "5555555555555555", + "5555555555555555", + color_a=(255, 0, 0), + color_b=(0, 0, 255), + ) + == "near_duplicate_high" + ) + + def test_distance_above_close_band_is_unique(self): + from app.services.dataset_validation import classify_pair + + # Hamming distance 7 > NEAR_HASH_CLOSE (6). + assert classify_pair("5555555555555555", "555555555555552a") == "unique" + + def test_close_distance_with_matching_aspect_is_high(self): + from app.services.dataset_validation import classify_pair + + # Distance 3, same aspect ratio -> corroborated. + assert ( + classify_pair( + "5555555555555555", + "5555555555555552", + dims_a=(400, 300), + dims_b=(800, 600), + ) + == "near_duplicate_high" + ) + + def test_close_distance_at_band_edge_is_not_unique(self): + from app.services.dataset_validation import classify_pair + + # Distance exactly 6 (band edge) with no signals -> still high. + assert ( + classify_pair("5555555555555555", "555555555555556a") + == "near_duplicate_high" + ) + + def test_close_distance_with_mismatched_aspect_is_possible(self): + from app.services.dataset_validation import classify_pair + + assert ( + classify_pair( + "5555555555555555", + "5555555555555552", + dims_a=(400, 300), + dims_b=(800, 400), + ) + == "near_duplicate_possible" + ) + + def test_close_distance_without_signals_is_high(self): + from app.services.dataset_validation import classify_pair + + # Nothing to corroborate against -> nothing can disagree. + assert ( + classify_pair("5555555555555555", "5555555555555552") + == "near_duplicate_high" + ) + + def test_close_flat_hashes_with_far_colors_are_possible(self): + from app.services.dataset_validation import classify_pair + + assert ( + classify_pair( + "0" * 16, + "0000000000000007", + color_a=(255, 0, 0), + color_b=(0, 255, 0), + ) + == "near_duplicate_possible" + ) + + def test_close_flat_hashes_with_matching_colors_are_high(self): + from app.services.dataset_validation import classify_pair + + assert ( + classify_pair( + "0" * 16, + "0000000000000007", + color_a=(10, 10, 10), + color_b=(14, 9, 11), + ) + == "near_duplicate_high" + ) + + + +# ---------- pure helpers ------------------------------------------------------ + + +class TestHamming: + def test_identical_hashes_distance_zero(self): + from app.services.dataset_validation import _hamming + + assert _hamming("5555555555555555", "5555555555555555") == 0 + + def test_opposite_hashes_distance_sixty_four(self): + from app.services.dataset_validation import _hamming + + assert _hamming("0" * 16, "f" * 16) == 64 + + +class TestColorDistance: + def test_uses_max_channel_difference(self): + from app.services.dataset_validation import _color_distance + + assert _color_distance((10, 200, 30), (15, 205, 90)) == 60 + assert _color_distance((100, 100, 100), (100, 100, 100)) == 0 + + +class TestIsLowEntropy: + @pytest.mark.parametrize( + "hash_hex", + [ + "0" * 16, # zero ones + "f" * 16, # sixty-four ones + "000000000000001b", # exactly four ones (boundary) + "ffffffffffffffe4", # exactly sixty ones (boundary) + ], + ) + def test_flat_hashes_are_low_entropy(self, hash_hex): + from app.services.dataset_validation import _is_low_entropy + + assert _is_low_entropy(hash_hex) is True + + @pytest.mark.parametrize( + "hash_hex", + [ + "000000000000002f", # five ones - just above the boundary + "5555555555555555", # thirty-two ones + ], + ) + def test_structured_hashes_are_not_low_entropy(self, hash_hex): + from app.services.dataset_validation import _is_low_entropy + + assert _is_low_entropy(hash_hex) is False + + +class TestSameAspectRatio: + def test_same_ratio_within_tolerance(self): + from app.services.dataset_validation import _same_aspect_ratio + + assert _same_aspect_ratio(400, 300, 800, 600) is True + # 5% tolerance: 1.333 vs ~1.332 stays inside the band. + assert _same_aspect_ratio(400, 300, 800, 601) is True + + def test_different_ratios_rejected(self): + from app.services.dataset_validation import _same_aspect_ratio + + assert _same_aspect_ratio(400, 300, 600, 400) is False + + def test_zero_width_is_never_the_same_shape(self): + from app.services.dataset_validation import _same_aspect_ratio + + assert _same_aspect_ratio(0, 100, 0, 200) is False + + +class TestFilenameOf: + def test_returns_filename_for_matching_entry(self): + from app.services.dataset_validation import _filename_of + + entries = [{"id": "a", "filename": "a.png"}, {"id": "b"}] + + assert _filename_of(entries, "a") == "a.png" + # Entry without a filename key falls back to its id. + assert _filename_of(entries, "b") == "b" + + def test_falls_back_to_image_id_when_no_entry_matches(self): + from app.services.dataset_validation import _filename_of + + assert _filename_of([{"id": "a", "filename": "a.png"}], "zzz") == "zzz" + assert _filename_of([], "solo") == "solo" + + +# ---------- validate_dataset -------------------------------------------------- + + +class TestValidateDatasetClean: + def test_clean_dataset_scores_hundred(self): + from app.services.dataset_validation import validate_dataset + + images = { + "a": _png(300, 300, color=(255, 0, 0)), + "b": _png(300, 300, color=(0, 0, 255)), + } + entries = [ + _entry("a", caption="red square", filename="a.png"), + _entry("b", caption="blue square", filename="b.png"), + ] + + report = validate_dataset(entries, lambda image_id: images[image_id]) + + assert report.total_images == 2 + assert report.valid_images == 2 + assert report.captioned == 2 + assert report.findings == [] + assert report.score == 100 + # Both images are 300x300. + assert report.average_resolution == (300, 300) + + def test_empty_dataset_reports_nothing(self): + from app.services.dataset_validation import validate_dataset + + report = validate_dataset([], lambda image_id: b"") + + assert report.total_images == 0 + assert report.valid_images == 0 + assert report.average_resolution is None + assert report.findings == [] + assert report.score == 100 + + +class TestValidateDatasetCaptions: + def test_missing_empty_and_suspicious_captions_flagged(self): + from app.services.dataset_validation import validate_dataset + + # Distinct colors keep every image unique (no duplicate findings). + images = { + "a": _png(300, 300, color=(255, 0, 0)), + "b": _png(300, 300, color=(0, 0, 255)), + "c": _png(300, 300, color=(0, 180, 0)), + "d": _png(300, 300, color=(240, 200, 0)), + } + entries = [ + {"id": "a"}, # no caption key at all + _entry("b", caption=" "), # whitespace only + _entry("c", caption="ab"), # too short + _entry( + "d", + caption="Sorry, I cannot describe this image because it is not safe.", + ), + ] + + report = validate_dataset(entries, lambda image_id: images[image_id]) + + by_kind = {f.kind for f in report.findings} + assert {"missing_caption", "empty_caption", "suspicious_caption"} <= by_kind + details = {f.image_id: f.detail for f in report.findings} + assert details["a"] == "" # missing caption carries no detail + assert details["b"] == "" + assert details["c"] == "ab" + assert details["d"].startswith("Sorry, I cannot describe") + assert report.captioned == 0 + + @pytest.mark.parametrize( + "caption", + [ + "As an AI language model, I ...", + "I cannot generate this image.", + "I can't help you with that.", + "Sorry, something went wrong.", + "lorem ipsum dolor sit amet", + "the background is undefined here", + "caption: null, end of line", + "[error] failed to caption", + ], + ) + def test_each_suspicious_marker_is_detected(self, caption): + from app.services.dataset_validation import validate_dataset + + images = {"a": _png(300, 300)} + report = validate_dataset([_entry("a", caption=caption)], lambda i: images[i]) + + assert [f.kind for f in report.findings] == ["suspicious_caption"] + + +class TestValidateDatasetDecoding: + def test_garbage_bytes_flagged_invalid(self): + from app.services.dataset_validation import validate_dataset + + entries = [_entry("a", filename="a.png")] + + report = validate_dataset(entries, lambda image_id: b"not an image") + + assert report.valid_images == 0 + invalid = [f for f in report.findings if f.kind == "invalid"] + assert len(invalid) == 1 + assert invalid[0].image_id == "a" + assert invalid[0].filename == "a.png" + + def test_read_bytes_exception_flagged_invalid(self): + from app.services.dataset_validation import validate_dataset + + entries = [_entry("a", filename="missing.png")] + + def _boom(image_id): + raise FileNotFoundError(f"no such file: {image_id}") + + report = validate_dataset(entries, _boom) + + assert [f.kind for f in report.findings] == ["invalid"] + + +class TestValidateDatasetResolution: + def test_below_minimum_flagged(self): + from app.services.dataset_validation import validate_dataset + + images = {"a": _png(100, 300)} + report = validate_dataset([_entry("a")], lambda i: images[i]) + + extreme = [f for f in report.findings if f.kind == "extreme_resolution"] + assert len(extreme) == 1 + assert "below" in extreme[0].detail and "256" in extreme[0].detail + + def test_above_maximum_flagged(self): + from app.services.dataset_validation import validate_dataset + + images = {"a": _png(9000, 300)} + report = validate_dataset([_entry("a")], lambda i: images[i]) + + extreme = [f for f in report.findings if f.kind == "extreme_resolution"] + assert len(extreme) == 1 + assert "above" in extreme[0].detail and "8192" in extreme[0].detail + + +class TestValidateDatasetDuplicates: + def test_identical_bytes_flagged_duplicate(self): + from app.services.dataset_validation import validate_dataset + + blob = _png(300, 300) + images = {"a": blob, "b": blob} + entries = [_entry("a"), _entry("b")] + + report = validate_dataset(entries, lambda image_id: images[image_id]) + + dups = [f for f in report.findings if f.kind == "duplicate"] + assert len(dups) == 1 + assert dups[0].image_id == "b" + assert dups[0].detail == "identical to a" + + def test_same_structure_different_size_flagged_near_duplicate(self): + from app.services.dataset_validation import validate_dataset + + images = { + "a": _gradient_png(260, 260), + "b": _gradient_png(400, 400), + } + entries = [_entry("a"), _entry("b")] + + report = validate_dataset(entries, lambda image_id: images[image_id]) + + near = [f for f in report.findings if f.kind == "near_duplicate"] + assert len(near) == 1 + assert near[0].image_id == "b" + assert near[0].detail == "near duplicate high vs a" + + def test_possible_verdict_flagged_with_lower_severity(self, monkeypatch): + import app.services.dataset_validation as dv + from app.services.dataset_validation import validate_dataset + + images = {k: _png(300, 300) for k in ("a", "b", "c")} + entries = [_entry("a"), _entry("b"), _entry("c")] + + monkeypatch.setattr(dv, "classify_pair", lambda *a, **kw: "near_duplicate_possible") + + report = validate_dataset(entries, lambda image_id: images[image_id]) + + near = [f for f in report.findings if f.kind == "near_duplicate_possible"] + # Pairs (a,b), (a,c), (b,c) -> later ids b, c, c. + assert sorted(f.image_id for f in near) == ["b", "c", "c"] + assert all("possible" in f.detail for f in near) + + def test_entry_without_filename_falls_back_to_image_id(self): + from app.services.dataset_validation import validate_dataset + + blob = _png(300, 300) + images = {"a": blob, "b": blob} + entries = [{"id": "a"}, {"id": "b"}] # no filename keys anywhere + + report = validate_dataset(entries, lambda image_id: images[image_id]) + + dup = next(f for f in report.findings if f.kind == "duplicate") + assert dup.filename == "b" + + def test_repeated_id_pair_produces_single_finding(self, monkeypatch): + import app.services.dataset_validation as dv + from app.services.dataset_validation import validate_dataset + + # First and third entries share id "a", so the (a, b) id-pair is seen + # twice by index. Every pair classifies as a near duplicate; the + # repeated id-pair must still be flagged only once. + red = _png(300, 300, color=(255, 0, 0)) + blue = _png(300, 300, color=(0, 0, 255)) + entries = [_entry("a"), _entry("b"), _entry("a")] + + monkeypatch.setattr(dv, "classify_pair", lambda *a, **kw: "near_duplicate_high") + + report = validate_dataset(entries, lambda image_id: {"a": red, "b": blue}[image_id]) + + near = [f for f in report.findings if f.kind == "near_duplicate"] + assert [(f.image_id, f.detail) for f in near] == [ + ("b", "near duplicate high vs a"), + ("a", "near duplicate high vs a"), + ] + + +class TestValidateDatasetDimensions: + def test_mixed_dimensions_flagged_once(self): + from app.services.dataset_validation import validate_dataset + + images = { + "a": _png(300, 300, color=(255, 0, 0)), + "b": _png(400, 400, color=(0, 0, 255)), + } + entries = [_entry("a"), _entry("b")] + + report = validate_dataset(entries, lambda image_id: images[image_id]) + + dim_findings = [f for f in report.findings if f.kind == "dimension_inconsistency"] + assert len(dim_findings) == 1 + finding = dim_findings[0] + assert finding.image_id == "*" + assert finding.filename == "(dataset)" + assert "2 distinct dimensions" in finding.detail + + def test_uniform_dimensions_not_flagged(self): + from app.services.dataset_validation import validate_dataset + + images = { + "a": _png(300, 300, color=(255, 0, 0)), + "b": _png(300, 300, color=(0, 0, 255)), + } + entries = [_entry("a"), _entry("b")] + + report = validate_dataset(entries, lambda image_id: images[image_id]) + + assert not [f for f in report.findings if f.kind == "dimension_inconsistency"] + + +# ---------- scoring ----------------------------------------------------------- + + +class TestScore: + def test_clean_report_scores_hundred(self): + from app.services.dataset_validation import DatasetReport, _score + + assert _score(DatasetReport(total_images=5, valid_images=5)) == 100 + + def test_penalties_are_weighted_per_kind(self): + from app.services.dataset_validation import DatasetReport, ImageFinding, _score + + report = DatasetReport(total_images=4, valid_images=2) + # 2 invalid (30) + 1 missing caption (5) + 1 extreme resolution (6) = 41. + for image_id, kind in [ + ("a", "invalid"), + ("b", "invalid"), + ("c", "missing_caption"), + ("d", "extreme_resolution"), + ]: + report.findings.append(ImageFinding(image_id, f"{image_id}.png", kind)) + + assert _score(report) == 59 + + def test_per_kind_penalty_is_capped(self): + from app.services.dataset_validation import DatasetReport, ImageFinding, _score + + report = DatasetReport(total_images=12) + for i in range(12): + report.findings.append(ImageFinding(f"i{i}", "x.png", "missing_caption")) + + # 12 * 5 would be 60; the cap limits it to 10 * 5 = 50. + assert _score(report) == 50 + + def test_score_never_goes_below_zero(self): + from app.services.dataset_validation import DatasetReport, ImageFinding, _score + + report = DatasetReport(total_images=10) + for i in range(10): + report.findings.append(ImageFinding(f"i{i}", "x.png", "invalid")) + + # 10 * 15 = 150 penalty -> clamped to zero. + assert _score(report) == 0 + + def test_unknown_kind_uses_default_weight(self): + from app.services.dataset_validation import DatasetReport, ImageFinding, _score + + report = DatasetReport(total_images=3) + for i in range(3): + report.findings.append(ImageFinding(f"i{i}", "x.png", "mystery")) + + assert _score(report) == 94 + + + diff --git a/tests/test_document_service_behaviour.py b/tests/test_document_service_behaviour.py new file mode 100644 index 0000000..5744f11 --- /dev/null +++ b/tests/test_document_service_behaviour.py @@ -0,0 +1,150 @@ +"""Behavioural tests for app/services/document_service.py.""" + +import json +from pathlib import Path + +from app.services.document_service import DocumentService + + +def _seed_documents(tmp_settings, payload) -> None: + """Write a raw documents.json into the tmp data dir before construction.""" + data_dir = Path(tmp_settings.data_dir) + data_dir.mkdir(parents=True, exist_ok=True) + (data_dir / "documents.json").write_text(json.dumps(payload), encoding="utf-8") + + +def _read_documents_file(tmp_settings): + return json.loads((Path(tmp_settings.data_dir) / "documents.json").read_text(encoding="utf-8")) + + +class TestStoreAndRetrieve: + def test_store_returns_sequential_ids_and_persists_across_restart(self, tmp_settings): + svc = DocumentService() + first_id = svc.store_document("first body", source="a.txt") + second_id = svc.store_document("second body") + + assert (first_id, second_id) == ("doc_0", "doc_1") + stored = _read_documents_file(tmp_settings) + assert [d["id"] for d in stored] == ["doc_0", "doc_1"] + assert stored[1]["source"] == "upload" # default source + + fresh = DocumentService() + restored = {d["id"]: d for d in fresh.get_all_documents()} + assert set(restored) == {"doc_0", "doc_1"} + assert restored["doc_0"]["content"] == "first body" + assert restored["doc_0"]["source"] == "a.txt" + + def test_store_documents_batch_returns_ids_in_order(self, tmp_settings): + svc = DocumentService() + ids = svc.store_documents([("c1", "s1"), ("c2", "s2")]) + + assert ids == ["doc_0", "doc_1"] + assert svc.get_document("doc_0")["source"] == "s1" + assert svc.get_document("doc_1")["content"] == "c2" + + def test_get_document_missing_returns_none(self, tmp_settings): + assert DocumentService().get_document("nope") is None + + def test_delete_existing_and_missing(self, tmp_settings): + svc = DocumentService() + svc.store_documents([("one", "s"), ("two", "s")]) + + assert svc.delete_document("doc_0") is True + assert svc.get_document("doc_0") is None + assert [d["id"] for d in _read_documents_file(tmp_settings)] == ["doc_1"] + + assert svc.delete_document("doc_99") is False + + def test_clear_all_resets_storage_and_counter(self, tmp_settings): + svc = DocumentService() + svc.store_documents([("one", "s"), ("two", "s")]) + + svc.clear_all() + + assert svc.get_all_documents() == [] + assert _read_documents_file(tmp_settings) == [] + assert svc.store_document("again") == "doc_0" + + +class TestLoad: + def test_load_skips_malformed_entries_and_syncs_counter(self, tmp_settings): + _seed_documents( + tmp_settings, + [ + {"id": "doc_9", "content": "kept"}, + "junk", + 42, + {"no_id": True}, + {"id": 7}, + {"id": "legacy_doc"}, + ], + ) + + svc = DocumentService() + docs = {d["id"]: d for d in svc.get_all_documents()} + + # Only non-dict entries and dicts without an id are skipped; "legacy_doc" is a valid doc. + assert set(docs) == {"doc_9", "7", "legacy_doc"} + assert docs["doc_9"]["content"] == "kept" + assert docs["7"]["content"] == "" # missing content defaults to empty string + assert docs["7"]["source"] == "upload" # missing source defaults to upload + + # Counter sits ahead of doc_9; the non-numeric suffixes never raised. + assert svc.store_document("next") == "doc_10" + + def test_load_ignores_non_list_payload(self, tmp_settings): + _seed_documents(tmp_settings, {"id": "doc_0", "content": "not a list"}) + + svc = DocumentService() + assert svc.get_all_documents() == [] + + +class TestRelevantContext: + def test_empty_storage_returns_empty_string(self, tmp_settings): + assert DocumentService().get_relevant_context("anything") == "" + + def test_ranks_by_keyword_overlap_and_drops_zero_score_docs(self, tmp_settings): + svc = DocumentService() + svc.store_document("the quick brown fox", source="a") + svc.store_document("quick silver jumps", source="b") + svc.store_document("zebra stripes only", source="c") + + ctx = svc.get_relevant_context("quick brown", top_k=3) + + assert "[Source: a]" in ctx and "[Source: b]" in ctx + assert ctx.index("[Source: a]") < ctx.index("[Source: b]") # score 2 beats 1 + assert "[Source: c]" not in ctx + + def test_respects_top_k(self, tmp_settings): + svc = DocumentService() + for i in range(4): + svc.store_document(f"alpha filler {i}", source=f"s{i}") + + ctx = svc.get_relevant_context("alpha", top_k=2) + assert ctx.count("[Source:") == 2 + + def test_no_overlap_returns_empty_string(self, tmp_settings): + svc = DocumentService() + svc.store_document("completely unrelated words") + + assert svc.get_relevant_context("zzz qqq") == "" + + def test_truncates_content_to_500_chars(self, tmp_settings): + svc = DocumentService() + content = "word " * 200 # 1000 chars of one repeated word + svc.store_document(content, source="s") + + ctx = svc.get_relevant_context("word") + assert ctx == "[Source: s]\n" + content[:500] + + def test_matching_ignores_case_and_punctuation(self, tmp_settings): + svc = DocumentService() + svc.store_document("Hello, World!") + + ctx = svc.get_relevant_context("hello world") + assert "[Source: upload]" in ctx + + +class TestNormalizeText: + def test_lowercases_and_strips_special_characters(self): + assert DocumentService._normalize_text("MiXeD 123, case!") == "mixed 123 case" diff --git a/tests/test_embeddings_behaviour.py b/tests/test_embeddings_behaviour.py new file mode 100644 index 0000000..635f27c --- /dev/null +++ b/tests/test_embeddings_behaviour.py @@ -0,0 +1,244 @@ +"""Unit tests for ``app.services.rag.embeddings`` (EmbeddingClient). + +The client is exercised with a fake ``OllamaClient`` injected through the +constructor, so no Ollama server or network access is needed. The sentence- +transformers fallback is covered two ways: its lazy construction path uses a +patched ``SentenceTransformer`` class (no model download), and its import-failure +path poisons ``sys.modules`` to force an ``ImportError``. Covers construction, +both backends, the empty-batch short circuit, normalization (including the +zero-vector guard) and the lazy ``dimension``/``backend`` probes. +""" + +from __future__ import annotations + +import sys +from types import SimpleNamespace +from typing import Any + +import numpy as np +import pytest + +from app.core.exceptions import OllamaServiceError +from app.services.rag.embeddings import EmbeddingClient + + +class FakeOllamaClient: + """Minimal stand-in for ``OllamaClient`` with canned or failing embed calls.""" + + def __init__(self, vectors=None, error=None): + self.embed_calls = [] + self._vectors = vectors if vectors is not None else [[1.0, 0.0]] + self._error = error + + def embed(self, *, model, inputs): + self.embed_calls.append({"model": model, "inputs": list(inputs)}) + if self._error is not None: + raise self._error + return [list(row) for row in self._vectors] + + +class FakeSentenceTransformer: + """Records construction and encode calls; returns canned vectors.""" + + instances: list[Any] = [] + + def __init__(self, model_name_or_path): + self.model_name_or_path = model_name_or_path + self.encode_calls = [] + FakeSentenceTransformer.instances.append(self) + + def encode(self, texts, convert_to_numpy=False, show_progress_bar=True): + self.encode_calls.append( + { + "texts": list(texts), + "convert_to_numpy": convert_to_numpy, + "show_progress_bar": show_progress_bar, + } + ) + return np.asarray([[1.0, 0.0], [0.0, 2.0]], dtype=np.float32) + + +def make_client(monkeypatch, ollama=None, model="test-embed-model", fallback_model="test-fallback-model"): + """Build an ``EmbeddingClient`` with a stubbed settings object.""" + monkeypatch.setattr( + "app.services.rag.embeddings.settings", + SimpleNamespace(embedding_model=model, embedding_fallback_model=fallback_model), + ) + return EmbeddingClient(ollama_client=ollama) + + +# --------------------------------------------------------------------------- # +# construction +# --------------------------------------------------------------------------- # + + +def test_init_uses_provided_client_and_models(monkeypatch): + ollama = FakeOllamaClient() + + client = make_client(monkeypatch, ollama=ollama, model="m1", fallback_model="f1") + + assert client.ollama_client is ollama + assert client.model == "m1" + assert client.fallback_model == "f1" + assert client._backend is None + assert client._dimension is None + + +def test_init_defaults_from_settings_and_creates_ollama_client(monkeypatch): + created = [] + + class RecorderOllama: + def __init__(self): + created.append(True) + + monkeypatch.setattr("app.services.rag.embeddings.OllamaClient", RecorderOllama) + client = make_client(monkeypatch, model="settings-model", fallback_model="settings-fallback") + + assert len(created) == 1 + assert client.model == "settings-model" + assert client.fallback_model == "settings-fallback" + + +# --------------------------------------------------------------------------- # +# embed / embed_batch via the ollama backend +# --------------------------------------------------------------------------- # + + +def test_embed_batch_empty_returns_zero_shape_without_calling_backend(monkeypatch): + ollama = FakeOllamaClient() + client = make_client(monkeypatch, ollama=ollama) + + result = client.embed_batch([]) + + assert result.shape == (0, 0) + assert result.dtype == np.float32 + assert ollama.embed_calls == [] + + +def test_embed_single_returns_normalized_first_row(monkeypatch): + ollama = FakeOllamaClient(vectors=[[3.0, 4.0]]) + client = make_client(monkeypatch, ollama=ollama) + + vector = client.embed("hello") + + assert vector.tolist() == pytest.approx([0.6, 0.8]) + assert vector.dtype == np.float32 + assert ollama.embed_calls == [{"model": "test-embed-model", "inputs": ["hello"]}] + + +def test_embed_batch_normalizes_rows_and_sets_backend(monkeypatch): + ollama = FakeOllamaClient(vectors=[[3.0, 4.0], [0.0, 2.0]]) + client = make_client(monkeypatch, ollama=ollama) + + matrix = client.embed_batch(["a", "b"]) + + assert np.allclose(matrix, [[0.6, 0.8], [0.0, 1.0]]) + assert matrix.dtype == np.float32 + assert client.backend == "ollama" + assert client.dimension == 2 + + +def test_embed_batch_casts_integer_vectors_to_float32(monkeypatch): + ollama = FakeOllamaClient(vectors=[[4, 0]]) + client = make_client(monkeypatch, ollama=ollama) + + matrix = client.embed_batch(["a"]) + + assert matrix.dtype == np.float32 + assert np.allclose(matrix, [[1.0, 0.0]]) + + +def test_zero_vector_row_stays_finite(monkeypatch): + """The zero-norm guard in _normalize must not produce NaN or inf.""" + ollama = FakeOllamaClient(vectors=[[0.0, 0.0], [2.0, 0.0]]) + client = make_client(monkeypatch, ollama=ollama) + + matrix = client.embed_batch(["zero", "nonzero"]) + + assert np.isfinite(matrix).all() + assert matrix[0].tolist() == [0.0, 0.0] + assert matrix[1].tolist() == pytest.approx([1.0, 0.0]) + + +# --------------------------------------------------------------------------- # +# lazy dimension / backend probes +# --------------------------------------------------------------------------- # + + +def test_backend_property_probes_lazily(monkeypatch): + ollama = FakeOllamaClient(vectors=[[1.0, 2.0]]) + client = make_client(monkeypatch, ollama=ollama) + + assert client.backend == "ollama" + + assert ollama.embed_calls == [{"model": "test-embed-model", "inputs": ["backend probe"]}] + + +def test_dimension_property_probes_once_and_caches(monkeypatch): + ollama = FakeOllamaClient(vectors=[[1.0, 2.0, 3.0]]) + client = make_client(monkeypatch, ollama=ollama) + + first = client.dimension + second = client.dimension + + assert first == 3 + assert second == 3 + assert len(ollama.embed_calls) == 1 + assert ollama.embed_calls[0]["inputs"] == ["dimension probe"] + + +# --------------------------------------------------------------------------- # +# sentence-transformers fallback +# --------------------------------------------------------------------------- # + + +def test_ollama_failure_falls_back_to_sentence_transformers(monkeypatch, caplog): + FakeSentenceTransformer.instances.clear() + failing = FakeOllamaClient(error=OllamaServiceError("Ollama is down", status_code=503)) + monkeypatch.setattr("sentence_transformers.SentenceTransformer", FakeSentenceTransformer) + client = make_client(monkeypatch, ollama=failing) + + with caplog.at_level("WARNING", logger="app.services.rag.embeddings"): + matrix = client.embed_batch(["a", "b"]) + + assert client.backend == "sentence-transformers" + assert np.allclose(matrix, [[1.0, 0.0], [0.0, 1.0]]) + assert len(FakeSentenceTransformer.instances) == 1 + model = FakeSentenceTransformer.instances[0] + assert model.model_name_or_path == "test-fallback-model" + assert model.encode_calls == [ + { + "texts": ["a", "b"], + "convert_to_numpy": True, + "show_progress_bar": False, + } + ] + warning = [r for r in caplog.records if r.levelname == "WARNING"] + assert len(warning) == 1 + assert warning[0].message == "Ollama embeddings unavailable (Ollama is down); using fallback." + + +def test_fallback_model_is_reused_across_calls(monkeypatch): + FakeSentenceTransformer.instances.clear() + failing = FakeOllamaClient(error=OllamaServiceError("down", status_code=503)) + monkeypatch.setattr("sentence_transformers.SentenceTransformer", FakeSentenceTransformer) + client = make_client(monkeypatch, ollama=failing) + + client.embed_batch(["a"]) + client.embed_batch(["b"]) + + assert len(FakeSentenceTransformer.instances) == 1 + assert client._st_model is FakeSentenceTransformer.instances[0] + + +def test_fallback_import_error_raises_ollama_service_error(monkeypatch): + failing = FakeOllamaClient(error=OllamaServiceError("down", status_code=503)) + monkeypatch.setitem(sys.modules, "sentence_transformers", None) + client = make_client(monkeypatch, ollama=failing) + + with pytest.raises(OllamaServiceError, match="Embedding fallback unavailable: install sentence-transformers") as excinfo: + client.embed_batch(["a"]) + + assert excinfo.value.status_code == 503 + # The failed import must not have left a half-built model behind. + assert client._st_model is None diff --git a/tests/test_hardware_behaviour.py b/tests/test_hardware_behaviour.py new file mode 100644 index 0000000..a3ce3f0 --- /dev/null +++ b/tests/test_hardware_behaviour.py @@ -0,0 +1,545 @@ +"""Behaviour tests for app/services/hardware.py (training preflight detection). + +Detection is best-effort by design: every detector degrades to an empty list +or ``None`` instead of raising, and the advisor then gives conservative advice. +These tests pin down each degradation path and each response parse with +literal expected values. Fakes are injected via monkeypatch so no ComfyUI, +network or GPU is required; the real nvidia-smi subprocess path is only +exercised on machines that have a GPU (all of its parse branches are covered +by fakes here). +""" + +from __future__ import annotations + +import io +import os +import subprocess +import sys +from types import SimpleNamespace + +from app.services.hardware import ( + GPUInfo, + HardwareInfo, + _detect_cpu, + _detect_ram, + _detect_via_comfyui, + _detect_via_nvidia_smi, + _detect_via_torch, + detect_disk_free_gb, + detect_gpus, + detect_hardware, +) + +MODULE = "app.services.hardware" + + +def _fake_response(payload): + """A stand-in for requests.Response: only .json() is used.""" + return SimpleNamespace(status_code=200, json=lambda: payload) + + +# ============================================ +# Dataclasses +# ============================================ + + +class TestGPUInfo: + def test_to_dict_round_trips_all_fields(self): + gpu = GPUInfo( + vendor="nvidia", + name="NVIDIA GeForce RTX 4090", + vram_total_mb=24576, + vram_free_mb=18432, + source="comfyui", + ) + assert gpu.to_dict() == { + "vendor": "nvidia", + "name": "NVIDIA GeForce RTX 4090", + "vram_total_mb": 24576, + "vram_free_mb": 18432, + "source": "comfyui", + } + + +class TestHardwareInfo: + def test_empty_snapshot_is_cpu_with_no_vram(self): + info = HardwareInfo() + assert info.primary_gpu is None + assert info.vram_total_mb is None + assert info.accelerator == "cpu" + + def test_accelerator_cuda_for_nvidia_primary(self): + info = HardwareInfo(gpus=[GPUInfo(vendor="nvidia", name="RTX 4090")]) + assert info.primary_gpu.name == "RTX 4090" + assert info.accelerator == "cuda" + + def test_accelerator_rocm_only_when_flag_set(self): + amd = GPUInfo(vendor="amd", name="RX 7900 XTX") + assert HardwareInfo(gpus=[amd]).accelerator == "amd" + flagged = HardwareInfo(gpus=[amd], rocm_available=True) + assert flagged.accelerator == "rocm" + + def test_accelerator_unknown_vendor(self): + info = HardwareInfo(gpus=[GPUInfo(vendor="unknown", name="M3 Ultra")]) + assert info.accelerator == "unknown" + + def test_to_dict_includes_primary_and_flags(self): + gpu = GPUInfo( + vendor="nvidia", + name="RTX 4090", + vram_total_mb=24576, + vram_free_mb=None, + source="torch", + ) + info = HardwareInfo( + gpus=[gpu], + cpu_name="Ryzen 9", + cpu_cores=16, + ram_total_mb=32768, + ram_available_mb=16384, + disk_free_gb=512.0, + cuda_available=True, + ) + assert info.to_dict() == { + "gpus": [ + { + "vendor": "nvidia", + "name": "RTX 4090", + "vram_total_mb": 24576, + "vram_free_mb": None, + "source": "torch", + } + ], + "primary_gpu": { + "vendor": "nvidia", + "name": "RTX 4090", + "vram_total_mb": 24576, + "vram_free_mb": None, + "source": "torch", + }, + "accelerator": "cuda", + "cpu_name": "Ryzen 9", + "cpu_cores": 16, + "ram_total_mb": 32768, + "ram_available_mb": 16384, + "disk_free_gb": 512.0, + "cuda_available": True, + "rocm_available": False, + } + + +# ============================================ +# ComfyUI detector +# ============================================ + + +class TestComfyUIDetection: + def test_parses_nvidia_device_and_converts_bytes_to_mb(self, monkeypatch): + payload = { + "devices": [ + { + "name": "NVIDIA GeForce RTX 4090", + # ComfyUI reports bytes: 24 GiB total, 18 GiB free. + "vram_total": 25769803776, + "vram_free": 19327352832, + } + ] + } + monkeypatch.setattr("requests.get", lambda *a, **k: _fake_response(payload)) + + gpus = _detect_via_comfyui("http://127.0.0.1:8188") + + assert gpus == [ + GPUInfo( + vendor="nvidia", + name="NVIDIA GeForce RTX 4090", + vram_total_mb=24576, + vram_free_mb=18432, + source="comfyui", + ) + ] + + def test_parses_amd_by_radeon_name(self, monkeypatch): + payload = {"devices": [{"name": "AMD Radeon RX 7900 XTX"}]} + monkeypatch.setattr("requests.get", lambda *a, **k: _fake_response(payload)) + + gpus = _detect_via_comfyui("http://127.0.0.1:8188") + + assert [gpu.vendor for gpu in gpus] == ["amd"] + assert gpus[0].name == "AMD Radeon RX 7900 XTX" + + def test_unknown_vendor_and_missing_vram_stay_none(self, monkeypatch): + payload = {"devices": [{"name": ""}, {"name": "Apple M3 Ultra"}]} + monkeypatch.setattr("requests.get", lambda *a, **k: _fake_response(payload)) + + gpus = _detect_via_comfyui("http://127.0.0.1:8188") + + assert len(gpus) == 2 + # Empty name falls back to the literal "GPU". + assert gpus[0].name == "GPU" + assert gpus[0].vendor == "unknown" + assert gpus[1].vram_total_mb is None + assert gpus[1].vram_free_mb is None + + def test_empty_devices_list_returns_empty(self, monkeypatch): + monkeypatch.setattr("requests.get", lambda *a, **k: _fake_response({"devices": []})) + assert _detect_via_comfyui("http://127.0.0.1:8188") == [] + + def test_connection_error_returns_empty(self, monkeypatch): + import requests as real_requests + + def raise_conn(*args, **kwargs): + raise real_requests.ConnectionError("refused") + + monkeypatch.setattr("requests.get", raise_conn) + assert _detect_via_comfyui("http://127.0.0.1:8188") == [] + + def test_malformed_json_returns_empty(self, monkeypatch): + def broken_json(): + raise ValueError("No JSON object could be decoded") + + response = SimpleNamespace(status_code=200, json=broken_json) + monkeypatch.setattr("requests.get", lambda *a, **k: response) + assert _detect_via_comfyui("http://127.0.0.1:8188") == [] + + def test_url_strips_trailing_slash_and_passes_timeout(self, monkeypatch): + seen = {} + + def record(url, **kwargs): + seen["url"] = url + seen.update(kwargs) + return _fake_response({"devices": []}) + + monkeypatch.setattr("requests.get", record) + _detect_via_comfyui("http://127.0.0.1:8188/", timeout=1.5) + + assert seen["url"] == "http://127.0.0.1:8188/system_stats" + assert seen["timeout"] == 1.5 + + +# ============================================ +# nvidia-smi detector +# ============================================ + + +class TestNvidiaSmiDetection: + def test_missing_binary_returns_empty(self, monkeypatch): + monkeypatch.setattr("shutil.which", lambda name: None) + assert _detect_via_nvidia_smi() == [] + + def test_parses_csv_output_into_gpu_info(self, monkeypatch): + monkeypatch.setattr("shutil.which", lambda name: "C:\\WINDOWS\\system32\\nvidia-smi.EXE") + result = SimpleNamespace(stdout="NVIDIA GeForce RTX 4090, 24564, 18321\n") + monkeypatch.setattr("subprocess.run", lambda *a, **k: result) + + gpus = _detect_via_nvidia_smi() + + assert gpus == [ + GPUInfo( + vendor="nvidia", + name="NVIDIA GeForce RTX 4090", + vram_total_mb=24564, + vram_free_mb=18321, + source="nvidia-smi", + ) + ] + + def test_skips_malformed_lines_but_keeps_valid_ones(self, monkeypatch): + monkeypatch.setattr("shutil.which", lambda name: "C:\\WINDOWS\\system32\\nvidia-smi.EXE") + result = SimpleNamespace( + stdout=( + "NVIDIA A100 80GB, 81920, 70000\n" + "garbage line without commas\n" + "BROKEN GPU, not-a-number, also-bad\n" + ) + ) + monkeypatch.setattr("subprocess.run", lambda *a, **k: result) + + gpus = _detect_via_nvidia_smi() + + assert len(gpus) == 1 + assert gpus[0].name == "NVIDIA A100 80GB" + assert (gpus[0].vram_total_mb, gpus[0].vram_free_mb) == (81920, 70000) + + def test_oserror_returns_empty(self, monkeypatch): + monkeypatch.setattr("shutil.which", lambda name: "C:\\WINDOWS\\system32\\nvidia-smi.EXE") + + def raise_oserror(*args, **kwargs): + raise OSError("access denied") + + monkeypatch.setattr("subprocess.run", raise_oserror) + assert _detect_via_nvidia_smi() == [] + + def test_timeout_returns_empty(self, monkeypatch): + monkeypatch.setattr("shutil.which", lambda name: "C:\\WINDOWS\\system32\\nvidia-smi.EXE") + + def raise_timeout(*args, **kwargs): + raise subprocess.TimeoutExpired(cmd="nvidia-smi", timeout=5) + + monkeypatch.setattr("subprocess.run", raise_timeout) + assert _detect_via_nvidia_smi() == [] + + + +# ============================================ +# torch detector (fake module injected into sys.modules) +# ============================================ + + +def _install_fake_torch(monkeypatch, available, hip=None, devices=()): + fake = SimpleNamespace( + cuda=SimpleNamespace( + is_available=lambda: available, + device_count=lambda: len(devices), + get_device_properties=lambda index: devices[index], + ), + version=SimpleNamespace(hip=hip), + ) + monkeypatch.setitem(sys.modules, "torch", fake) + + +class TestTorchDetection: + def test_import_error_returns_empty(self, monkeypatch): + # None in sys.modules makes `import torch` raise ImportError. + monkeypatch.setitem(sys.modules, "torch", None) + assert _detect_via_torch() == [] + + def test_cuda_unavailable_returns_empty(self, monkeypatch): + _install_fake_torch(monkeypatch, available=False) + assert _detect_via_torch() == [] + + def test_enumerates_nvidia_devices_with_vram(self, monkeypatch): + # 80 GiB in bytes -> 81920 MB. + device = SimpleNamespace(name="NVIDIA A100 80GB", total_memory=85899345920) + _install_fake_torch(monkeypatch, available=True, hip=None, devices=[device]) + + gpus = _detect_via_torch() + + assert gpus == [ + GPUInfo( + vendor="nvidia", + name="NVIDIA A100 80GB", + vram_total_mb=81920, + vram_free_mb=None, + source="torch", + ) + ] + + def test_hip_build_reports_amd_vendor(self, monkeypatch): + device = SimpleNamespace(name="AMD Instinct MI300X", total_memory=4294967296) + _install_fake_torch(monkeypatch, available=True, hip="6.3", devices=[device]) + + gpus = _detect_via_torch() + + assert gpus[0].vendor == "amd" + # 4 GiB -> 4096 MB. + assert gpus[0].vram_total_mb == 4096 + + def test_missing_name_and_memory_attrs_use_defaults(self, monkeypatch): + _install_fake_torch(monkeypatch, available=True, hip=None, devices=[SimpleNamespace()]) + + gpus = _detect_via_torch() + + assert gpus[0].name == "CUDA device" + assert gpus[0].vram_total_mb == 0 + + +# ============================================ +# detect_gpus orchestration (fallback order) +# ============================================ + + +class TestDetectGpus: + def test_comfyui_wins_when_it_answers(self, monkeypatch): + comfy = [GPUInfo(vendor="nvidia", name="from-comfyui")] + monkeypatch.setattr(f"{MODULE}._detect_via_comfyui", lambda url: comfy) + + called = {} + + def boom(): + called["yes"] = True + return [] + + monkeypatch.setattr(f"{MODULE}._detect_via_nvidia_smi", boom) + + assert detect_gpus("http://127.0.0.1:8188") == comfy + # nvidia-smi must not be consulted once ComfyUI answered. + assert "yes" not in called + + def test_falls_back_to_nvidia_smi_when_comfyui_empty(self, monkeypatch): + smi = [GPUInfo(vendor="nvidia", name="from-smi")] + monkeypatch.setattr(f"{MODULE}._detect_via_comfyui", lambda url: []) + monkeypatch.setattr(f"{MODULE}._detect_via_nvidia_smi", lambda: smi) + + assert detect_gpus("http://127.0.0.1:8188") == smi + + def test_falls_back_to_torch_when_others_empty(self, monkeypatch): + torch_gpu = [GPUInfo(vendor="nvidia", name="from-torch")] + monkeypatch.setattr(f"{MODULE}._detect_via_comfyui", lambda url: []) + monkeypatch.setattr(f"{MODULE}._detect_via_nvidia_smi", lambda: []) + monkeypatch.setattr(f"{MODULE}._detect_via_torch", lambda: torch_gpu) + + assert detect_gpus("http://127.0.0.1:8188") == torch_gpu + + def test_without_url_skips_comfyui_entirely(self, monkeypatch): + smi = [GPUInfo(vendor="nvidia", name="from-smi")] + + def must_not_run(url): + raise AssertionError("comfyui detector should not run without a URL") + + monkeypatch.setattr(f"{MODULE}._detect_via_comfyui", must_not_run) + monkeypatch.setattr(f"{MODULE}._detect_via_nvidia_smi", lambda: smi) + + assert detect_gpus() == smi + + + +# ============================================ +# CPU / RAM / disk +# ============================================ + + +class TestCpuRamDisk: + def test_detect_cpu_returns_real_machine_values(self): + name, cores = _detect_cpu() + # os.cpu_count is the source of truth here, not the code under test. + assert cores == os.cpu_count() + assert isinstance(cores, int) and cores > 0 + assert name is None or isinstance(name, str) + + def test_detect_cpu_swallows_platform_errors(self, monkeypatch): + def broken_processor(): + raise RuntimeError("no processor info") + + monkeypatch.setattr("platform.processor", broken_processor) + # The exception aborts the whole try block: both values stay None. + assert _detect_cpu() == (None, None) + + def test_detect_ram_with_psutil_converts_bytes_to_mb(self, monkeypatch): + fake_psutil = SimpleNamespace( + virtual_memory=lambda: SimpleNamespace(total=16 * 1024**3, available=8 * 1024**3) + ) + monkeypatch.setitem(sys.modules, "psutil", fake_psutil) + + assert _detect_ram() == (16384, 8192) + + def test_detect_ram_psutil_crash_falls_back_to_meminfo(self, monkeypatch): + # psutil is importable but its call blows up: the except-Exception + # branch must swallow it and fall through to /proc/meminfo. + def broken_virtual_memory(): + raise RuntimeError("psutil exploded") + + fake_psutil = SimpleNamespace(virtual_memory=broken_virtual_memory) + monkeypatch.setitem(sys.modules, "psutil", fake_psutil) + meminfo = "MemTotal: 8192000 kB\nMemAvailable: 4096000 kB\n" + real_open = open + + def fake_open(path, *args, **kwargs): + if str(path) == "/proc/meminfo": + return io.StringIO(meminfo) + return real_open(path, *args, **kwargs) + + monkeypatch.setattr("builtins.open", fake_open) + + assert _detect_ram() == (8000, 4000) + + def test_detect_ram_meminfo_parse_without_psutil(self, monkeypatch): + # psutil absent -> ImportError path; /proc/meminfo faked for Windows. + monkeypatch.setitem(sys.modules, "psutil", None) + meminfo = ( + "MemTotal: 16384000 kB\n" + "MemFree: 1024000 kB\n" + "MemAvailable: 8192000 kB\n" + ) + real_open = open + + def fake_open(path, *args, **kwargs): + if str(path) == "/proc/meminfo": + return io.StringIO(meminfo) + return real_open(path, *args, **kwargs) + + monkeypatch.setattr("builtins.open", fake_open) + + # kB -> MB: 16384000/1024 = 16000; MemAvailable wins over MemFree. + assert _detect_ram() == (16000, 8000) + + def test_detect_ram_meminfo_uses_memfree_when_no_available(self, monkeypatch): + monkeypatch.setitem(sys.modules, "psutil", None) + meminfo = "MemTotal: 4096000 kB\nMemFree: 2048000 kB\n" + real_open = open + + def fake_open(path, *args, **kwargs): + if str(path) == "/proc/meminfo": + return io.StringIO(meminfo) + return real_open(path, *args, **kwargs) + + monkeypatch.setattr("builtins.open", fake_open) + + assert _detect_ram() == (4000, 2000) + + def test_detect_ram_meminfo_malformed_returns_none(self, monkeypatch): + monkeypatch.setitem(sys.modules, "psutil", None) + meminfo = "MemTotal: garbage\n" + real_open = open + + def fake_open(path, *args, **kwargs): + if str(path) == "/proc/meminfo": + return io.StringIO(meminfo) + return real_open(path, *args, **kwargs) + + monkeypatch.setattr("builtins.open", fake_open) + + assert _detect_ram() == (None, None) + + def test_detect_disk_free_gb_reports_real_drive(self, tmp_path): + free = detect_disk_free_gb(str(tmp_path)) + assert isinstance(free, float) + assert free >= 0.0 + + def test_detect_disk_free_gb_oserror_returns_none(self, monkeypatch): + def raise_oserror(path): + raise OSError("drive not ready") + + monkeypatch.setattr("shutil.disk_usage", raise_oserror) + assert detect_disk_free_gb("/definitely/missing") is None + + +# ============================================ +# Public entry point +# ============================================ + + +class TestDetectHardware: + def test_nvidia_gpu_sets_cuda_flag(self, monkeypatch): + gpus = [GPUInfo(vendor="nvidia", name="RTX 4090")] + monkeypatch.setattr(f"{MODULE}.detect_gpus", lambda url=None: gpus) + + info = detect_hardware() + + assert info.gpus == gpus + assert info.cuda_available is True + assert info.rocm_available is False + assert info.accelerator == "cuda" + + def test_amd_gpu_sets_rocm_flag(self, monkeypatch): + gpus = [GPUInfo(vendor="amd", name="RX 7900 XTX")] + monkeypatch.setattr(f"{MODULE}.detect_gpus", lambda url=None: gpus) + + info = detect_hardware() + + assert info.cuda_available is False + assert info.rocm_available is True + # detect_hardware sets rocm_available for AMD GPUs, so the property + # reports "rocm" rather than plain "amd". + assert info.accelerator == "rocm" + + def test_no_gpu_reports_cpu(self, monkeypatch): + monkeypatch.setattr(f"{MODULE}.detect_gpus", lambda url=None: []) + + info = detect_hardware() + + assert info.gpus == [] + assert info.cuda_available is False + assert info.rocm_available is False + assert info.accelerator == "cpu" + diff --git a/tests/test_ingestion_behaviour.py b/tests/test_ingestion_behaviour.py new file mode 100644 index 0000000..e2d0956 --- /dev/null +++ b/tests/test_ingestion_behaviour.py @@ -0,0 +1,169 @@ +"""Unit tests for ``app.services.rag.ingestion`` (text extraction). + +Real files are written to a tmp dir for the .txt paths; the PDF and DOCX +parsers are exercised with fakes injected into ``pypdf.PdfReader`` and +``docx.Document`` so no binary fixtures or network access are needed. +""" + +from __future__ import annotations + +import pytest + +from app.services.rag.ingestion import ( + SUPPORTED_EXTENSIONS, + _extract_from_bytes, + extract_text, +) + + +class FakePage: + def __init__(self, text): + self._text = text + + def extract_text(self): + return self._text + + +def make_pdf_reader(pages): + """Return a ``PdfReader`` stand-in whose pages yield the given texts.""" + + class FakeReader: + last_stream = None + + def __init__(self, stream): + type(self).last_stream = stream + self.pages = [FakePage(text) for text in pages] + + return FakeReader + + +class FakeParagraph: + def __init__(self, text): + self.text = text + + +def make_docx_document(paragraphs): + """Return a ``Document`` stand-in with the given paragraph texts.""" + + class FakeDoc: + last_stream = None + + def __init__(self, stream): + type(self).last_stream = stream + self.paragraphs = [FakeParagraph(text) for text in paragraphs] + + return FakeDoc + + +# --------------------------------------------------------------------------- # +# extract_text: .txt and extension handling +# --------------------------------------------------------------------------- # + + +def test_extract_txt_returns_stripped_text(tmp_path): + file = tmp_path / "notes.txt" + file.write_bytes(b"\n hello world \n\n") + + assert extract_text(file) == "hello world" + + +def test_extract_txt_invalid_utf8_raises(tmp_path): + file = tmp_path / "bad.txt" + file.write_bytes(b"\xff\xfe not utf-8") + + with pytest.raises(UnicodeDecodeError): + extract_text(file) + + +def test_extract_empty_txt_raises_no_text(tmp_path): + file = tmp_path / "empty.txt" + file.write_bytes(b" \n\t ") + + with pytest.raises(ValueError, match="No extractable text found in 'empty.txt'"): + extract_text(file) + + +def test_unsupported_extension_raises_with_supported_list(tmp_path): + file = tmp_path / "virus.exe" + file.write_bytes(b"MZ") + + with pytest.raises(ValueError, match="Unsupported file type '\\.exe'") as excinfo: + extract_text(file) + assert ".docx, .pdf, .txt" in str(excinfo.value) + + +def test_missing_file_raises_not_found(tmp_path): + with pytest.raises(FileNotFoundError): + extract_text(tmp_path / "missing.txt") + + +def test_filename_param_overrides_and_lowercases_extension(tmp_path): + file = tmp_path / "data" + file.write_bytes(b"payload text") + + assert extract_text(file, filename="Report.TXT") == "payload text" + + +def test_supported_extensions_constant(): + assert SUPPORTED_EXTENSIONS == {".txt", ".pdf", ".docx"} + + +# --------------------------------------------------------------------------- # +# pdf extraction (pypdf faked) +# --------------------------------------------------------------------------- # + + +def test_pdf_extracts_pages_and_joins_non_empty(tmp_path, monkeypatch): + reader_cls = make_pdf_reader(["Hello", None, " ", "World"]) + monkeypatch.setattr("pypdf.PdfReader", reader_cls) + file = tmp_path / "doc.pdf" + content = b"%PDF-1.4 fake bytes" + file.write_bytes(content) + + assert extract_text(file) == "Hello\n\nWorld" + assert reader_cls.last_stream.getvalue() == content + + +def test_pdf_all_empty_pages_raises_no_text(tmp_path, monkeypatch): + monkeypatch.setattr("pypdf.PdfReader", make_pdf_reader([None, " "])) + file = tmp_path / "blank.pdf" + file.write_bytes(b"%PDF-1.4") + + with pytest.raises(ValueError, match="No extractable text found in 'blank.pdf'"): + extract_text(file) + + +# --------------------------------------------------------------------------- # +# docx extraction (python-docx faked) +# --------------------------------------------------------------------------- # + + +def test_docx_extracts_paragraphs_and_joins_non_empty(tmp_path, monkeypatch): + doc_cls = make_docx_document([" Alpha ", "", "Beta"]) + monkeypatch.setattr("docx.Document", doc_cls) + file = tmp_path / "brief.docx" + content = b"PK fake docx bytes" + file.write_bytes(content) + + assert extract_text(file) == "Alpha\n\nBeta" + assert doc_cls.last_stream.getvalue() == content + + +def test_docx_all_empty_paragraphs_raises_no_text(tmp_path, monkeypatch): + monkeypatch.setattr("docx.Document", make_docx_document(["", " "])) + file = tmp_path / "empty.docx" + file.write_bytes(b"PK") + + with pytest.raises(ValueError, match="No extractable text found in 'empty.docx'"): + extract_text(file) + + +# --------------------------------------------------------------------------- # +# _extract_from_bytes fallback branch +# --------------------------------------------------------------------------- # + + +def test_extract_from_bytes_unsupported_extension_raises(): + with pytest.raises(ValueError, match="Unsupported file type '\\.xyz'"): + _extract_from_bytes("file.xyz", ".xyz", b"data") + diff --git a/tests/test_jobs_behaviour.py b/tests/test_jobs_behaviour.py new file mode 100644 index 0000000..1e9e99c --- /dev/null +++ b/tests/test_jobs_behaviour.py @@ -0,0 +1,379 @@ +"""Behaviour tests for app/core/jobs.py (Job dataclass and JobStore).""" + +from __future__ import annotations + +import json +import threading +import time + +import pytest + + +def _wait_terminal(store, job_id, timeout=2.0): + """Poll until the job reaches a terminal status; fail if it does not.""" + from app.core.jobs import TERMINAL_STATUSES + + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + job = store.get(job_id) + if job is not None and job.status in TERMINAL_STATUSES: + return job + time.sleep(0.01) + pytest.fail(f"job {job_id} did not reach a terminal status within {timeout}s") + + +def _write_jobs_file(path, records): + path.write_text(json.dumps(records), encoding="utf-8") + + +# ---------- Job.to_dict / elapsed_seconds ------------------------------------ + + +class TestJobElapsedSeconds: + def test_elapsed_between_start_and_finish(self): + from app.core.jobs import Job + + job = Job( + id="j1", + type="generate", + started_at="2026-01-01T00:00:00+00:00", + completed_at="2026-01-01T00:00:05.500000+00:00", + ) + + assert job.to_dict()["elapsed_seconds"] == 5.5 + + def test_elapsed_clamps_negative_to_zero(self): + from app.core.jobs import Job + + job = Job( + id="j2", + type="generate", + started_at="2026-01-01T00:00:10+00:00", + completed_at="2026-01-01T00:00:00+00:00", + ) + + assert job.to_dict()["elapsed_seconds"] == 0.0 + + def test_elapsed_none_when_not_started(self): + from app.core.jobs import Job + + data = Job(id="j3", type="caption").to_dict() + + assert data["elapsed_seconds"] is None + assert data["status"] == "queued" + + def test_elapsed_none_for_unparseable_timestamps(self): + from app.core.jobs import Job + + job = Job(id="j4", type="generate", started_at="not-a-date") + + assert job.to_dict()["elapsed_seconds"] is None + + +# ---------- persistence: load -------------------------------------------------- + + +class TestPersistenceLoad: + def test_load_restores_terminal_jobs_and_drops_unknown_fields(self, tmp_path): + from app.core.jobs import JobStore + + path = tmp_path / "jobs.json" + _write_jobs_file( + path, + [ + { + "id": "done1", + "type": "generate", + "status": "completed", + "created_at": "2026-01-01T00:00:00+00:00", + "started_at": "2026-01-01T00:00:01+00:00", + "completed_at": "2026-01-01T00:00:05+00:00", + "progress": 100.0, + "message": None, + "error": None, + "outputs": ["/out/a.png"], + "metadata": {"prompt": "a cat"}, + "elapsed_seconds": 9.9, # derived field: must be dropped + }, + { + "id": "stop1", + "type": "train", + "status": "cancelled", + "created_at": "2026-01-01T00:01:00+00:00", + "started_at": None, + "completed_at": "2026-01-01T00:01:02+00:00", + "progress": None, + "message": None, + "error": None, + "outputs": [], + "metadata": {}, + }, + ], + ) + + store = JobStore(persist_path=str(path)) + done = store.get("done1") + stopped = store.get("stop1") + + assert done is not None and done.status.value == "completed" + assert done.outputs == ["/out/a.png"] + assert done.metadata == {"prompt": "a cat"} + # the stored 9.9 was dropped; to_dict re-derives it from the timestamps + assert done.to_dict()["elapsed_seconds"] == 4.0 + assert stopped is not None and stopped.status.value == "cancelled" + + def test_load_marks_interrupted_jobs_failed(self, tmp_path): + from app.core.jobs import JobStore + + path = tmp_path / "jobs.json" + _write_jobs_file( + path, + [ + { + "id": "run1", + "type": "generate", + "status": "running", + "created_at": "2026-01-01T00:00:00+00:00", + "started_at": "2026-01-01T00:00:01+00:00", + "completed_at": None, + "progress": 40.0, + "message": "halfway", + "error": None, + "outputs": [], + "metadata": {}, + }, + { + "id": "wait1", + "type": "caption", + "status": "queued", + "created_at": "2026-01-01T00:00:02+00:00", + "started_at": None, + "completed_at": None, + "progress": None, + "message": None, + "error": None, + "outputs": [], + "metadata": {}, + }, + ], + ) + + store = JobStore(persist_path=str(path)) + + for job_id in ("run1", "wait1"): + job = store.get(job_id) + assert job.status.value == "failed" + assert job.error == "Interrupted by application restart" + assert job.completed_at is not None + + def test_load_skips_unreadable_records(self, tmp_path): + from app.core.jobs import JobStore + + path = tmp_path / "jobs.json" + _write_jobs_file( + path, + [ + { + "id": "ok1", + "type": "generate", + "status": "failed", + "created_at": "2026-01-01T00:00:00+00:00", + "started_at": None, + "completed_at": "2026-01-01T00:00:03+00:00", + "progress": None, + "message": None, + "error": "old error", + "outputs": [], + "metadata": {}, + }, + {"id": "bad1", "type": "x", "status": "bogus"}, # ValueError + "just a string", # TypeError in dict(raw) + ], + ) + + store = JobStore(persist_path=str(path)) + + jobs = store.list() + assert [job.id for job in jobs] == ["ok1"] + assert jobs[0].error == "old error" + + def test_load_ignores_non_list_file(self, tmp_path): + from app.core.jobs import JobStore + + path = tmp_path / "jobs.json" + _write_jobs_file(path, {"id": "not-a-list"}) + + store = JobStore(persist_path=str(path)) + + assert store.list() == [] + + +# ---------- persistence: save -------------------------------------------------- + + +class TestPersistenceSave: + def test_save_keeps_only_most_recent_two_hundred(self, tmp_path): + from app.core.jobs import JobStore + + path = tmp_path / "jobs.json" + store = JobStore(persist_path=str(path)) + created = [store.create("generate") for _ in range(205)] + + stored = json.loads(path.read_text(encoding="utf-8")) + assert len(stored) == 200 + assert [job["id"] for job in stored] == [job.id for job in created[5:]] + + def test_save_swallows_oserror_and_keeps_job_in_memory(self, tmp_path): + from app.core.jobs import JobStore + + # A regular file where the parent directory should be makes every + # write raise NotADirectoryError (an OSError). + blocker = tmp_path / "blocker" + blocker.write_text("not a directory", encoding="utf-8") + store = JobStore(persist_path=str(blocker / "jobs.json")) + + job = store.create("generate") + + assert store.get(job.id) is not None + assert not (blocker / "jobs.json").exists() + + + +# ---------- submit / worker lifecycle ------------------------------------------ + + +class TestSubmitLifecycle: + def test_submit_completes_work_with_progress_100(self): + from app.core.jobs import JobStore + + store = JobStore() + + def work(job): + store.update(job.id, progress=50.0, message="working") + + job = store.submit("generate", work) + finished = _wait_terminal(store, job.id) + + assert finished.status.value == "completed" + assert finished.progress == 100.0 + assert finished.started_at is not None + assert finished.completed_at is not None + assert isinstance(finished.to_dict()["elapsed_seconds"], float) + + def test_failed_work_records_error_message(self): + from app.core.jobs import JobStore + + store = JobStore() + + def work(job): + raise RuntimeError("boom") + + job = store.submit("train", work) + finished = _wait_terminal(store, job.id) + + assert finished.status.value == "failed" + assert finished.error == "boom" + + def test_cancelled_queued_job_never_runs(self): + from app.core.jobs import JobStore + + store = JobStore(max_workers=1) + gate = threading.Event() + ran_second = False + + def first_work(job): + gate.wait(2.0) # hold the only worker slot + + def second_work(job): + nonlocal ran_second + ran_second = True + + try: + first = store.submit("generate", first_work) + second = store.submit("caption", second_work) + assert store.is_cancelled(second.id) is False + assert store.cancel(second.id) is True + assert store.is_cancelled(second.id) is True + finally: + gate.set() + + _wait_terminal(store, first.id) + finished = _wait_terminal(store, second.id) + + assert ran_second is False + assert finished.status.value == "cancelled" + assert finished.error is None + assert store.get(first.id).status.value == "completed" + + def test_worker_terminal_status_is_not_overwritten(self): + from app.core.jobs import JobStatus, JobStore + + store = JobStore() + + def work(job): + # cooperative cancellation: the worker itself goes terminal + store.update(job.id, status=JobStatus.CANCELLED, progress=50.0) + + job = store.submit("generate", work) + finished = _wait_terminal(store, job.id) + + assert finished.status.value == "cancelled" + assert finished.progress == 50.0 + + +# ---------- update / list / cancel ---------------------------------------------- + + +class TestUpdateListCancel: + def test_update_unknown_job_returns_none(self): + from app.core.jobs import JobStore + + store = JobStore() + + assert store.update("nope", message="x") is None + assert store.list() == [] + + def test_update_terminal_status_fills_completed_at(self): + from app.core.jobs import JobStatus, JobStore + + store = JobStore() + job = store.create("generate") + assert job.completed_at is None + + updated = store.update(job.id, status=JobStatus.COMPLETED) + + assert updated.status.value == "completed" + assert updated.completed_at is not None + + def test_list_filters_by_type_and_limit(self): + from app.core.jobs import JobStore + + store = JobStore() + generated = [] + captioned = [] + for _ in range(2): + time.sleep(0.002) # keep created_at values distinct + generated.append(store.create("generate")) + for _ in range(3): + time.sleep(0.002) + captioned.append(store.create("caption")) + + by_type = store.list(job_type="caption") + assert [job.id for job in by_type] == [job.id for job in reversed(captioned)] + + limited = store.list(limit=2) + assert len(limited) == 2 + assert limited[0].id == captioned[-1].id + assert limited[1].id == captioned[-2].id + + def test_cancel_unknown_and_terminal_jobs(self): + from app.core.jobs import JobStatus, JobStore + + store = JobStore() + job = store.create("generate") + store.update(job.id, status=JobStatus.COMPLETED) + + assert store.cancel("nope") is False + assert store.is_cancelled("nope") is False + assert store.cancel(job.id) is False # already terminal + assert store.get(job.id).status.value == "completed" diff --git a/tests/test_llm_service_behaviour.py b/tests/test_llm_service_behaviour.py new file mode 100644 index 0000000..4b22b56 --- /dev/null +++ b/tests/test_llm_service_behaviour.py @@ -0,0 +1,226 @@ +"""Unit tests for ``app.services.llm_service`` (service layer over Ollama). + +The service is exercised with a fake ``OllamaClient`` injected through the +constructor, so no Ollama server or network access is needed. Covers client +injection, every branch of ``health_check``, ``chat`` and ``list_models`` +including their failure paths. +""" + +from __future__ import annotations + +import pytest + +from app.core.exceptions import OllamaServiceError +from app.services.llm_service import LLMService + + +class FakeLLMClient: + """Minimal stand-in for ``OllamaClient`` with canned responses.""" + + def __init__(self, chat_response=None, models_payload=None): + self.chat_calls = [] + self.models_calls = 0 + self._chat_response = chat_response if chat_response is not None else {} + self._models_payload = models_payload if models_payload is not None else {} + + def chat_completion(self, model, messages): + self.chat_calls.append({"model": model, "messages": messages}) + return self._chat_response + + def list_models(self): + self.models_calls += 1 + return self._models_payload + + +def make_service(monkeypatch, client=None, default_model="test-model"): + """Build an ``LLMService`` with a stubbed settings object.""" + from types import SimpleNamespace + + monkeypatch.setattr( + "app.services.llm_service.settings", SimpleNamespace(default_model=default_model) + ) + return LLMService(client=client) + + +# --------------------------------------------------------------------------- # +# construction +# --------------------------------------------------------------------------- # + + +def test_init_uses_provided_client(): + client = FakeLLMClient() + + service = LLMService(client=client) + + assert service.client is client + + +def test_init_creates_default_client_when_none(monkeypatch): + created = [] + + class SentinelClient: + def __init__(self, *args, **kwargs): + created.append((args, kwargs)) + + monkeypatch.setattr("app.services.llm_service.OllamaClient", SentinelClient) + + service = LLMService() + + assert isinstance(service.client, SentinelClient) + assert len(created) == 1 + + +# --------------------------------------------------------------------------- # +# health_check +# --------------------------------------------------------------------------- # + + +def test_health_check_reports_ok_with_models(monkeypatch): + client = FakeLLMClient(models_payload={"data": [{"id": "llama3.2"}, {"id": "llava"}]}) + + service = make_service(monkeypatch, client) + result = service.health_check() + + assert result == { + "status": "ok", + "ollama_reachable": True, + "model": "test-model", + "available_models": ["llama3.2", "llava"], + } + assert client.models_calls == 1 + + +def test_health_check_propagates_service_error(monkeypatch): + class UnreachableClient(FakeLLMClient): + def list_models(self): + raise OllamaServiceError("Ollama is unreachable", status_code=503) + + service = make_service(monkeypatch, UnreachableClient()) + + with pytest.raises(OllamaServiceError, match="Ollama is unreachable"): + service.health_check() + + +# --------------------------------------------------------------------------- # +# chat +# --------------------------------------------------------------------------- # + + +def test_chat_returns_content_with_default_model(monkeypatch): + client = FakeLLMClient( + chat_response={"choices": [{"message": {"content": "hello back"}}]} + ) + + service = make_service(monkeypatch, client) + reply = service.chat("hi there") + + assert reply == "hello back" + (call,) = client.chat_calls + assert call["model"] == "test-model" + assert call["messages"] == [{"role": "user", "content": "hi there"}] + + +def test_chat_uses_explicit_model(monkeypatch): + client = FakeLLMClient( + chat_response={"choices": [{"message": {"content": "ok"}}]} + ) + + service = make_service(monkeypatch, client) + reply = service.chat("hi", model="llava") + + assert reply == "ok" + (call,) = client.chat_calls + assert call["model"] == "llava" + + +def test_chat_missing_choices_raises(monkeypatch): + client = FakeLLMClient(chat_response={"foo": "bar"}) + + service = make_service(monkeypatch, client) + + with pytest.raises(OllamaServiceError, match="Ollama returned an invalid chat response"): + service.chat("hi") + + +def test_chat_empty_choices_raises(monkeypatch): + client = FakeLLMClient(chat_response={"choices": []}) + + service = make_service(monkeypatch, client) + + with pytest.raises(OllamaServiceError, match="Ollama returned an invalid chat response"): + service.chat("hi") + + +def test_chat_non_string_content_raises(monkeypatch): + client = FakeLLMClient(chat_response={"choices": [{"message": {"content": None}}]}) + + service = make_service(monkeypatch, client) + + with pytest.raises(OllamaServiceError, match="Ollama returned an invalid chat response"): + service.chat("hi") + + +def test_chat_missing_message_key_raises(monkeypatch): + client = FakeLLMClient(chat_response={"choices": [{"index": 0}]}) + + service = make_service(monkeypatch, client) + + with pytest.raises(OllamaServiceError, match="Ollama returned an invalid chat response"): + service.chat("hi") + + +# --------------------------------------------------------------------------- # +# list_models +# --------------------------------------------------------------------------- # + + +def test_list_models_openai_format_filters_entries(monkeypatch): + payload = { + "data": [ + {"id": "llama3.2"}, + "not-a-dict", + {"no_id": True}, + {"id": "llava:7b"}, + ] + } + client = FakeLLMClient(models_payload=payload) + + service = make_service(monkeypatch, client) + models = service.list_models() + + assert models == ["llama3.2", "llava:7b"] + + +def test_list_models_legacy_format_filters_entries(monkeypatch): + payload = { + "models": [ + {"name": "mistral"}, + 42, + {"other": True}, + {"name": "nomic-embed-text"}, + ] + } + client = FakeLLMClient(models_payload=payload) + + service = make_service(monkeypatch, client) + models = service.list_models() + + assert models == ["mistral", "nomic-embed-text"] + + +def test_list_models_invalid_payload_raises(monkeypatch): + client = FakeLLMClient(models_payload={"unexpected": True}) + + service = make_service(monkeypatch, client) + + with pytest.raises(OllamaServiceError, match="Ollama returned an invalid model list"): + service.list_models() + + +def test_list_models_non_list_data_falls_through_to_error(monkeypatch): + client = FakeLLMClient(models_payload={"data": "not-a-list"}) + + service = make_service(monkeypatch, client) + + with pytest.raises(OllamaServiceError, match="Ollama returned an invalid model list"): + service.list_models() diff --git a/tests/test_lora_routes_behaviour.py b/tests/test_lora_routes_behaviour.py new file mode 100644 index 0000000..22d2a3e --- /dev/null +++ b/tests/test_lora_routes_behaviour.py @@ -0,0 +1,575 @@ +"""Behaviour tests for the LoRA API routes (app/api/lora_routes.py). + +Complements test_lora.py (service level) and test_api_generation.py (full-app +smoke): these drive the router itself with a minimal app that wires only the +LoRA dependencies, so every route handler runs against real services on temp +data dirs. Ollama, ComfyUI, and the AI Toolkit are intentionally absent - the +tests assert how the API degrades without them (skipped captions, honest +hardware reports, fail-fast jobs) instead of mocking the services out. +""" + +from __future__ import annotations + +import time +from pathlib import Path +from types import SimpleNamespace + +import pytest +from fastapi import FastAPI, HTTPException +from fastapi.testclient import TestClient + +from app.api.lora_routes import _http_error +from app.api.lora_routes import router as lora_router +from app.core.config import settings +from app.core.exceptions import ServiceError +from app.core.jobs import JobStatus, JobStore +from app.core.paths import UnsafePathError +from app.services.hardware import GPUInfo, HardwareInfo +from app.services.lora_dataset_service import LoRAProjectService +from app.services.lora_training_service import TRAINING_PRESETS, LoRATrainingService +from tests.conftest import png_bytes + + +def _fake_detect_hardware(comfyui_base_url=None): # noqa: ARG001 - mirrors the real signature + """Deterministic stand-in for GPU probing (see ``lora_env``).""" + return HardwareInfo( + gpus=[GPUInfo(vendor="nvidia", name="Test GPU", vram_total_mb=8 * 1024, + vram_free_mb=7 * 1024, source="test-fake")], + cpu_name="Test CPU", + cpu_cores=8, + ram_total_mb=32 * 1024, + ram_available_mb=16 * 1024, + disk_free_gb=100.0, + cuda_available=True, + ) + + +@pytest.fixture +def lora_env(tmp_settings, monkeypatch): + """Minimal FastAPI app with only the LoRA router and real services.""" + # Real GPU detection shells out to nvidia-smi (~2s per call on Windows) and + # depends on this machine's accelerators. The routes under test only need a + # HardwareInfo back, so pin it; hardware.py is covered by its own tests. + monkeypatch.setattr("app.services.hardware.detect_hardware", _fake_detect_hardware) + + projects = LoRAProjectService(data_dir=tmp_settings.lora_data_dir) + jobs = JobStore() + training = LoRATrainingService(projects=projects, jobs=jobs) + + app = FastAPI() + app.include_router(lora_router) + app.state.lora_project_service = projects + app.state.lora_training_service = training + app.state.job_store = jobs + + return SimpleNamespace(client=TestClient(app), projects=projects, + training=training, jobs=jobs) + + +def _create_project(client: TestClient, name="Route Character", **extra): + response = client.post("/loras/projects", json={"name": name, **extra}) + assert response.status_code == 200, response.text + return response.json() + + +def _upload_image(client: TestClient, project_id: str, filename="a.png"): + response = client.post( + f"/loras/projects/{project_id}/images", + files=[("files", (filename, png_bytes(), "image/png"))], + ) + assert response.status_code == 200, response.text + return response.json() + + +def _caption_image(client: TestClient, project_id: str, image_id: str): + response = client.put( + f"/loras/projects/{project_id}/captions/{image_id}", + json={"caption": "a red test subject"}, + ) + assert response.status_code == 200, response.text + return response.json() + + +def _wait_for_job(jobs: JobStore, job_id: str, timeout: float = 30.0): + deadline = time.monotonic() + timeout + while True: + job = jobs.get(job_id) + if job is not None and job.status in ( + JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.CANCELLED + ): + return job + assert time.monotonic() < deadline, f"job {job_id} did not finish: {job}" + time.sleep(0.1) + + +# ============================================ +# LIBRARY AND TOOLKIT +# ============================================ + + +class TestLibraryAndToolkit: + def test_lora_files_alias_matches_library(self, lora_env): + client = lora_env.client + library = client.get("/loras") + files = client.get("/loras/files") + assert library.status_code == 200 and files.status_code == 200 + assert files.json()["count"] == library.json()["count"] + + def test_training_presets_endpoint_returns_documented_set(self, lora_env): + response = lora_env.client.get("/loras/training/presets") + assert response.status_code == 200 + body = response.json() + assert body["count"] == len(TRAINING_PRESETS) + ids = [preset["id"] for preset in body["presets"]] + assert set(ids) == set(TRAINING_PRESETS) + for preset in body["presets"]: + assert preset["label"] and preset["description"] + assert isinstance(preset["values"], dict) + + def test_hardware_presets_reports_tier_and_variants(self, lora_env): + response = lora_env.client.get("/loras/training/hardware-presets") + assert response.status_code == 200 + body = response.json() + assert body["hardware"]["tier"] in {"unknown", "small", "medium", "large"} + for preset_id, variants in body["presets"].items(): + # Each preset carries a display label plus the three variant tiers. + assert {"conservative", "balanced", "quality"} <= set(variants), preset_id + # The conservative variant must always fit on the smallest GPU. + assert variants["conservative"]["batch_size"] == 1 + + def test_hardware_info_endpoint_shape(self, lora_env): + response = lora_env.client.get("/loras/hardware") + assert response.status_code == 200 + body = response.json() + for key in ("gpus", "accelerator", "cpu_cores", "ram_total_mb", + "disk_free_gb", "cuda_available"): + assert key in body, f"missing {key}" + assert isinstance(body["gpus"], list) + + def test_toolkit_status_reports_unconfigured(self, lora_env): + response = lora_env.client.get("/loras/toolkit/status") + assert response.status_code == 200 + body = response.json() + # No AI_TOOLKIT_PATH in the test environment: honest "not configured". + assert body["configured"] is False + assert body["error"] + assert isinstance(body["supported_archs"], list) and body["supported_archs"] + + +# ============================================ +# PROJECTS +# ============================================ + + +class TestProjects: + def test_create_project_with_blank_name_is_400(self, lora_env): + response = lora_env.client.post("/loras/projects", json={"name": " "}) + assert response.status_code == 400 + + def test_delete_missing_project_is_404(self, lora_env): + response = lora_env.client.delete("/loras/projects/ghost") + assert response.status_code == 404 + + def test_update_project_persists_fields(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + updated = client.put( + f"/loras/projects/{project_id}", + json={"name": "Renamed", "description": "fresh", "arch": "sd15"}, + ) + assert updated.status_code == 200 + fetched = client.get(f"/loras/projects/{project_id}").json() + assert fetched["name"] == "Renamed" + assert fetched["description"] == "fresh" + assert fetched["arch"] == "sd15" + + def test_list_projects_returns_every_created_project(self, lora_env): + client = lora_env.client + first = _create_project(client, name="First")["id"] + second = _create_project(client, name="Second")["id"] + + response = client.get("/loras/projects") + assert response.status_code == 200 + body = response.json() + assert body["count"] == 2 + assert {project["id"] for project in body["projects"]} == {first, second} + + def test_get_missing_project_is_404(self, lora_env): + assert lora_env.client.get("/loras/projects/ghost").status_code == 404 + + def test_update_missing_project_is_404(self, lora_env): + response = lora_env.client.put( + "/loras/projects/ghost", json={"name": "Nope"} + ) + assert response.status_code == 404 + + def test_delete_project_removes_it(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + + response = client.delete(f"/loras/projects/{project_id}") + assert response.status_code == 200 + assert "deleted" in response.json()["message"].lower() + # The directory is gone, so every follow-up call 404s. + assert client.get(f"/loras/projects/{project_id}").status_code == 404 + + def test_delete_project_traversal_is_rejected(self, lora_env): + # Percent-encoded ".." survives the HTTP layer; safe_join must reject + # it before any filesystem access escapes the data directory. + response = lora_env.client.delete("/loras/projects/%2e%2e") + assert response.status_code == 400 + assert "invalid path" in response.json()["detail"].lower() + + +# ============================================ +# DATASET +# ============================================ + + +class TestDataset: + def test_upload_mixed_files_keeps_valid_and_reports_rejected(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + response = client.post( + f"/loras/projects/{project_id}/images", + files=[("files", ("a.png", png_bytes(), "image/png")), + ("files", ("notes.txt", b"not an image", "text/plain"))], + ) + # One bad file must not discard the good one. + assert response.status_code == 200, response.text + body = response.json() + assert body["count"] == 1 + listed = client.get(f"/loras/projects/{project_id}/images").json() + assert [image["filename"] for image in listed["images"]] == ["a.png"] + + def test_upload_all_invalid_is_400_with_reasons(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + response = client.post( + f"/loras/projects/{project_id}/images", + files=[("files", ("notes.txt", b"not an image", "text/plain"))], + ) + assert response.status_code == 400 + assert "notes.txt" in response.json()["detail"] + + def test_image_file_endpoint_serves_bytes_and_media_type(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + uploaded = _upload_image(client, project_id) + image_id = uploaded["images"][0]["id"] + response = client.get(f"/loras/projects/{project_id}/images/{image_id}/file") + assert response.status_code == 200 + assert response.headers["content-type"].startswith("image/png") + assert response.content == png_bytes() + + def test_delete_missing_image_is_404(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + response = client.delete(f"/loras/projects/{project_id}/images/ghost") + assert response.status_code == 404 + + def test_validate_dataset_reports_quality_score(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + uploaded = _upload_image(client, project_id) + image_id = uploaded["images"][0]["id"] + _caption_image(client, project_id, image_id) + + response = client.get(f"/loras/projects/{project_id}/validate") + assert response.status_code == 200 + body = response.json() + assert body["total_images"] == 1 + assert body["valid_images"] >= 1 + assert isinstance(body["score"], int) and 0 <= body["score"] <= 100 + assert isinstance(body["findings"], list) + + def test_list_images_missing_project_is_404(self, lora_env): + response = lora_env.client.get("/loras/projects/ghost/images") + assert response.status_code == 404 + + def test_image_file_unknown_image_is_404(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + response = client.get(f"/loras/projects/{project_id}/images/ghost/file") + assert response.status_code == 404 + + def test_delete_image_removes_it(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + image_id = _upload_image(client, project_id)["images"][0]["id"] + + response = client.delete(f"/loras/projects/{project_id}/images/{image_id}") + assert response.status_code == 200 + listed = client.get(f"/loras/projects/{project_id}/images").json() + assert listed["count"] == 0 + + def test_validate_missing_project_is_404(self, lora_env): + response = lora_env.client.get("/loras/projects/ghost/validate") + assert response.status_code == 404 + + def test_delete_image_traversal_project_is_rejected(self, lora_env): + # Percent-encoded ".." survives the HTTP layer; safe_join must reject + # it before any filesystem access escapes the data directory. + response = lora_env.client.delete("/loras/projects/%2e%2e/images/whatever") + assert response.status_code == 400 + assert "invalid path" in response.json()["detail"].lower() + + +# ============================================ +# CAPTIONS (Ollama intentionally down) +# ============================================ + + +class TestCaptions: + def test_generate_captions_on_empty_project_is_400(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + response = client.post( + f"/loras/projects/{project_id}/generate-captions", json={} + ) + assert response.status_code == 400 + + def test_generate_captions_without_ollama_skips_images(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + uploaded = _upload_image(client, project_id) + image_id = uploaded["images"][0]["id"] + + response = client.post( + f"/loras/projects/{project_id}/generate-captions", json={} + ) + assert response.status_code == 200, response.text + body = response.json() + # Ollama is not running in the test environment: every image must be + # reported as skipped with a reason, never silently dropped. + assert body["generated"] == 0 + assert body["skipped"] == 1 + result = body["results"][0] + assert result["image_id"] == image_id + assert result["skipped"] is True + assert result["reason"] + assert body["model"] == settings.vision_model + + def test_caption_job_unknown_project_is_404(self, lora_env): + response = lora_env.client.post( + "/loras/projects/ghost/caption-jobs", json={} + ) + assert response.status_code == 404 + + def test_caption_job_empty_dataset_fails_fast_with_400(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + response = client.post( + f"/loras/projects/{project_id}/caption-jobs", json={} + ) + assert response.status_code == 400 + assert "no images" in response.json()["detail"].lower() + + def test_caption_job_runs_to_completion_with_metadata(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + _upload_image(client, project_id) + + response = client.post( + f"/loras/projects/{project_id}/caption-jobs", json={} + ) + assert response.status_code == 200, response.text + job_id = response.json()["id"] + + job = _wait_for_job(lora_env.jobs, job_id) + # Ollama is down: the batch degrades to all-skipped and still completes. + assert job.status is JobStatus.COMPLETED + assert job.metadata["generated"] == 0 + assert job.metadata["skipped"] == 1 + assert "Captioned 0" in job.message + + def test_update_caption_missing_project_is_404(self, lora_env): + response = lora_env.client.put( + "/loras/projects/ghost/captions/some-image", json={"caption": "x"} + ) + assert response.status_code == 404 + + def test_caption_job_reports_progress_through_job_store(self, lora_env, monkeypatch): + """The job's progress callback must flow into the JobStore. + + Ollama is absent here, so a real batch never reports progress (every + image skips before the callback fires); stub only the batch method to + prove the route wires progress_cb into store updates. The batch + algorithm itself belongs to lora_dataset_service's own tests. + """ + client = lora_env.client + project_id = _create_project(client)["id"] + _upload_image(client, project_id) + + calls: list[tuple[int, int]] = [] + + def fake_batch(project_id_, progress_cb=None, cancel_check=None, # noqa: ARG001 + model=None, overwrite=False): + for done in (1, 2): + if progress_cb: + progress_cb(done, 2) + calls.append((done, 2)) + return [{"image_id": "img", "caption": "a caption", "skipped": False}] + + monkeypatch.setattr(lora_env.projects, "generate_captions_batch", fake_batch) + + response = client.post(f"/loras/projects/{project_id}/caption-jobs") + assert response.status_code == 200, response.text + job = _wait_for_job(lora_env.jobs, response.json()["id"]) + + assert calls == [(1, 2), (2, 2)] + assert job.progress == 100.0 + assert job.metadata["generated"] == 1 + assert job.metadata["skipped"] == 0 + + +# ============================================ +# TRAINING (AI Toolkit intentionally absent) +# ============================================ + + +class TestTraining: + def test_preflight_returns_structured_report(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + uploaded = _upload_image(client, project_id) + image_id = uploaded["images"][0]["id"] + _caption_image(client, project_id, image_id) + + response = client.post( + f"/loras/projects/{project_id}/preflight", json={} + ) + assert response.status_code == 200, response.text + body = response.json() + assert body["verdict"] in {"ok", "heavy", "risky", "unsupported", "blocked"} + names = {check["name"] for check in body["checks"]} + assert {"Dataset", "Captions", "Base model"} <= names + assert isinstance(body["summary"], str) and body["summary"] + + def test_write_config_endpoint_persists_yaml_without_training(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + uploaded = _upload_image(client, project_id) + image_id = uploaded["images"][0]["id"] + _caption_image(client, project_id, image_id) + + response = client.post( + f"/loras/projects/{project_id}/config", json={"steps": 500} + ) + assert response.status_code == 200, response.text + body = response.json() + assert body["path"] == "training.yml" + assert "500" in body["config"] + + config_path = Path(lora_env.projects.config_dir(project_id)) / "training.yml" + assert config_path.is_file() + # Previewing the config must not mark the project as training. + fetched = client.get(f"/loras/projects/{project_id}").json() + assert fetched["training_status"] in (None, "not_started", "idle", "stopped") + + def test_list_runs_endpoint_returns_empty_history(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + response = client.get(f"/loras/projects/{project_id}/runs") + assert response.status_code == 200 + body = response.json() + assert body["runs"] == [] and body["count"] == 0 + + def test_training_log_tails_and_clamps_lines(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + + # No log file yet: empty string, not an error. + response = client.get(f"/loras/projects/{project_id}/training/log") + assert response.status_code == 200 + assert response.json()["log"] == "" + + log_path = Path(lora_env.projects.output_dir(project_id)) / "training.log" + log_path.write_text("\n".join(f"step {i}" for i in range(10)), encoding="utf-8") + + tail = client.get( + f"/loras/projects/{project_id}/training/log", params={"lines": 3} + ).json()["log"] + assert tail.splitlines() == ["step 7", "step 8", "step 9"] + + # lines=0 clamps to 1; huge values clamp to the cap, not an error. + one = client.get( + f"/loras/projects/{project_id}/training/log", params={"lines": 0} + ).json()["log"] + assert one.splitlines() == ["step 9"] + all_lines = client.get( + f"/loras/projects/{project_id}/training/log", params={"lines": 99999} + ).json()["log"] + assert len(all_lines.splitlines()) == 10 + + def test_preflight_missing_project_is_404(self, lora_env): + response = lora_env.client.post("/loras/projects/ghost/preflight", json={}) + assert response.status_code == 404 + + def test_runs_missing_project_is_404(self, lora_env): + response = lora_env.client.get("/loras/projects/ghost/runs") + assert response.status_code == 404 + + def test_training_log_missing_project_is_404(self, lora_env): + response = lora_env.client.get("/loras/projects/ghost/training/log") + assert response.status_code == 404 + + def test_write_config_missing_project_is_404(self, lora_env): + response = lora_env.client.post( + "/loras/projects/ghost/config", json={"steps": 500} + ) + assert response.status_code == 404 + + def test_start_training_without_toolkit_fails_with_503(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + response = client.post(f"/loras/projects/{project_id}/train", json={}) + assert response.status_code == 503 + assert "toolkit" in response.json()["detail"].lower() + + def test_stop_training_with_nothing_running_is_409(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + response = client.post(f"/loras/projects/{project_id}/stop") + assert response.status_code == 409 + + def test_training_status_reports_idle_for_fresh_project(self, lora_env): + client = lora_env.client + project_id = _create_project(client)["id"] + response = client.get(f"/loras/projects/{project_id}/training") + assert response.status_code == 200 + body = response.json() + assert body["running"] is False + assert body["progress"] is None + + def test_training_status_missing_project_is_404(self, lora_env): + response = lora_env.client.get("/loras/projects/ghost/training") + assert response.status_code == 404 + + +# ============================================ +# ERROR MAPPING +# ============================================ + + +class TestHttpErrorMapper: + def test_http_error_mapper_covers_all_branches(self): + # ServiceError keeps its own status code and detail. + mapped = _http_error(ServiceError("toolkit missing", status_code=503)) + assert isinstance(mapped, HTTPException) + assert mapped.status_code == 503 + assert mapped.detail == "toolkit missing" + + # Unsafe paths are rejected without echoing the attempted path. + mapped = _http_error(UnsafePathError("../etc/passwd")) + assert mapped.status_code == 400 + assert mapped.detail == "Invalid path" + + # Plain ValueErrors surface their message; anything else is a 500. + mapped = _http_error(ValueError("bad value")) + assert (mapped.status_code, mapped.detail) == (400, "bad value") + mapped = _http_error(RuntimeError("boom")) + assert (mapped.status_code, mapped.detail) == (500, "Unexpected error") + + + diff --git a/tests/test_lora_training_service.py b/tests/test_lora_training_service.py new file mode 100644 index 0000000..70adeeb --- /dev/null +++ b/tests/test_lora_training_service.py @@ -0,0 +1,447 @@ +"""Service-level tests for LoRA training orchestration (app/services/lora_training_service.py). + +``test_lora.py`` covers config generation, the process-management primitives, and library +discovery; ``test_lora_routes_behaviour.py`` covers API degradation without a toolkit. What +remained untested is the full lifecycle of ``LoRATrainingService._run`` - success, failure, +no-output, and cancellation paths that tie together jobs, run history, project state, and +the trainer process - plus the duplicate-start guard, ``stop_training``, and hardware-preset +tiering. + +The "AI Toolkit" is a fake ``run.py`` executed as a real subprocess under ``sys.executable``, +so spawn/stream/kill all happen for real; only the training itself is faked. +""" + +from __future__ import annotations + +import sys +import textwrap +import time +import types +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from app.core.exceptions import AIToolkitError, LoRAProjectError +from app.core.jobs import JobStatus, JobStore +from app.services.hardware import GPUInfo, HardwareInfo +from app.services.lora_dataset_service import LoRAProjectService +from app.services.lora_training_service import ( + LoRATrainingService, +) +from tests.conftest import png_bytes + +# ============================================ +# FAKE AI TOOLKIT +# ============================================ + +RUN_PY = """\ +import json +import sys +import time +from pathlib import Path + +import yaml + +root = Path(__file__).resolve().parent +mode = (root / "mode.txt").read_text(encoding="utf-8").strip() +config_path = Path(sys.argv[1]) +process = yaml.safe_load(config_path.read_text(encoding="utf-8"))["config"]["process"][0] +out_dir = Path(process["training_folder"]) + +if mode == "slow": + for i in range(60): + print(f" {i}/60 [sleeping]", flush=True) + time.sleep(1) +elif mode == "fail": + print("Loading model weights...", flush=True) + print("CUDA error: out of memory", flush=True) + sys.exit(3) +else: + steps = process["train"]["steps"] + for i in range(1, 5): + step = int(steps * i / 5) + print(f" {step}/{steps} [00:{i*2:<02d}<00:{(5-i)*2:<02d}, loss={0.9 - i * 0.15:.3f}", flush=True) + if mode == "success": + header = json.dumps({"__metadata__": {"format": "pt"}}).encode("utf-8") + (out_dir / "model.safetensors").write_bytes(len(header).to_bytes(8, "little") + header) +""" + + +def _install_toolkit(base: Path, name: str, mode: str) -> Path: + """Create a fake AI Toolkit directory (run.py + mode.txt) and return its path.""" + root = base / f"toolkit_{name}" + root.mkdir(parents=True, exist_ok=False) + (root / "mode.txt").write_text(mode, encoding="utf-8") + (root / "run.py").write_text(textwrap.dedent(RUN_PY), encoding="utf-8") + return root + + +def _fake_detect_hardware(vram_mb: int | None = 8192): + def detect(*args, **kwargs) -> HardwareInfo: + gpus = ( + [GPUInfo(vendor="NVIDIA", name="Fake GPU", vram_total_mb=vram_mb, vram_free_mb=7000)] + if vram_mb is not None + else [] + ) + return HardwareInfo( + gpus=gpus, cpu_name="Fake CPU", cpu_cores=8, ram_total_mb=16384, + ram_available_mb=8192, disk_free_gb=500.0, cuda_available=vram_mb is not None, + ) + + return detect + + +def _wait_for_terminal(jobs: JobStore, job_id: str, timeout: float = 20.0) -> object: + deadline = time.monotonic() + timeout + while True: + job = jobs.get(job_id) + assert job is not None + if job.status in (JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.CANCELLED): + return job + assert time.monotonic() < deadline, f"job {job_id} stuck in {job.status}" + time.sleep(0.05) + + +def _wait_for_status(jobs: JobStore, job_id: str, status: JobStatus, timeout: float = 20.0) -> object | None: + """Wait until a job reaches ``status``; return None if it goes terminal first.""" + deadline = time.monotonic() + timeout + while True: + job = jobs.get(job_id) + assert job is not None + if job.status is status: + return job + if job.status in (JobStatus.COMPLETED, JobStatus.FAILED, JobStatus.CANCELLED): + return None + assert time.monotonic() < deadline, f"job {job_id} stuck in {job.status}" + time.sleep(0.05) + + +def _wait_for_active(training: LoRATrainingService, project_id: str, timeout: float = 20.0) -> None: + """Wait until the worker thread has registered a live trainer for the project.""" + deadline = time.monotonic() + timeout + while True: + trainer = training._active.get(project_id) + if trainer is not None and trainer.is_running(): + return + assert time.monotonic() < deadline, "trainer never became active" + time.sleep(0.05) + + +def _wait_for_cancelled(env: SimpleNamespace, project_id: str, job_id: str) -> dict: + """Wait for the worker's cancel branch to land on disk and return the run record. + + ``jobs.cancel()`` flips the job synchronously, but the *project* status and the + *run record* are written by the worker thread a beat later - so both must be + polled rather than asserted immediately after the job goes terminal. + """ + deadline = time.monotonic() + 10 + while True: + assert time.monotonic() < deadline, "cancel effects never landed on disk" + if env.projects.get_project(project_id).training_status != "cancelled": + time.sleep(0.05) + continue + run = next( + (r for r in env.training.list_runs(project_id) if r.get("job_id") == job_id), None + ) + if run and run.get("status") == "cancelled" and run.get("completed_at"): + return run + time.sleep(0.05) + + +def _ready_project(env: SimpleNamespace, name: str = "Train Character") -> object: + project = env.projects.create_project(name, arch="sdxl", trigger_word="p3r5on") + env.projects.add_image(project.id, "img1.png", png_bytes()) + env.projects.set_caption(project.id, "img1", "p3r5on, red subject") + return project + + +@pytest.fixture +def training_env(tmp_settings, monkeypatch): + """Projects + in-memory jobs + the service under test. + + ``detect_hardware`` is faked (8 GB GPU) so tests never shell out to nvidia-smi; + every call site in lora_training_service imports it locally, so patching the source + attribute covers start_training, preflight, and hardware_presets alike. + """ + monkeypatch.setattr("app.services.hardware.detect_hardware", _fake_detect_hardware()) + projects = LoRAProjectService(data_dir=tmp_settings.lora_data_dir) + jobs = JobStore() + return SimpleNamespace(projects=projects, jobs=jobs, training=LoRATrainingService(projects=projects, jobs=jobs)) + + +@pytest.fixture +def fast_poll(monkeypatch): + """Shrink the 2 s poll interval in LoRATrainingService._run to keep tests quick. + + The shim proxies every public attribute of the real ``time`` module (the service + also calls ``time.gmtime``/``strftime`` for run records) and only caps ``sleep``. + """ + import app.services.lora_training_service as svc + + shim = types.SimpleNamespace( + **{name: getattr(time, name) for name in dir(time) if not name.startswith("_")} + ) + shim.sleep = lambda seconds: time.sleep(min(seconds, 0.02)) + monkeypatch.setattr(svc, "time", shim) + + +@pytest.fixture +def toolkit(tmp_path, set_setting): + """Install a fake toolkit of the requested mode and point settings at it.""" + + def _install(mode: str = "success") -> Path: + root = _install_toolkit(tmp_path, mode, mode) + set_setting("ai_toolkit_path", str(root)) + set_setting("ai_toolkit_python", sys.executable) + return root + + return _install + + +# ============================================ +# _RUN LIFECYCLE (fake trainer, real subprocess) +# ============================================ + + +class TestRunLifecycle: + def test_success_completes_job_project_and_run_record( + self, training_env, fast_poll, toolkit + ): + env = training_env + project = _ready_project(env) + toolkit("success") + + job = env.training.start_training(project.id, {}) + finished = _wait_for_terminal(env.jobs, job.id) + + assert finished.status is JobStatus.COMPLETED + assert finished.outputs == ["model.safetensors"] + assert "LoRA ready" in (finished.message or "") + + loaded = env.projects.get_project(project.id) + assert loaded.training_status == "completed" + assert loaded.trained_lora_path and Path(loaded.trained_lora_path).is_file() + + runs = env.training.list_runs(project.id) + assert len(runs) == 1 + run = runs[0] + assert run["status"] == "completed" + assert run["lora_filename"] == "model.safetensors" + assert (run["lora_size_bytes"] or 0) > 0 + assert run["final_loss"] == pytest.approx(0.3, abs=0.01) + assert run["total_steps"] == 2000 + + info = env.training.training_status(project.id) + assert info["status"] == "completed" + assert info["running"] is False + assert info["progress"] == 100.0 + + def test_success_tees_output_into_the_training_log( + self, training_env, fast_poll, toolkit + ): + env = training_env + project = _ready_project(env) + toolkit("success") + + job = env.training.start_training(project.id, {}) + _wait_for_terminal(env.jobs, job.id) + + log = env.training.read_log(project.id) + assert "Training started" in log + assert "loss=" in log # trainer stdout was tee'd, not just exit codes + + def test_failure_records_diagnosis_and_marks_project_failed( + self, training_env, fast_poll, toolkit + ): + env = training_env + project = _ready_project(env) + toolkit("fail") + + job = env.training.start_training(project.id, {}) + finished = _wait_for_terminal(env.jobs, job.id) + + assert finished.status is JobStatus.FAILED + assert "exited with code 3" in (finished.error or "") + + loaded = env.projects.get_project(project.id) + assert loaded.training_status == "failed" + + run = env.training.list_runs(project.id)[0] + assert run["status"] == "failed" + # diagnose_failure maps the OOM line to a human explanation, keeps the raw line. + assert "GPU memory" in (run["error"] or "") + assert "CUDA error: out of memory" in (run["error"] or "") + + info = env.training.training_status(project.id) + assert info["status"] == "failed" + assert info["error"] + + def test_no_output_marks_completed_no_output( + self, training_env, fast_poll, toolkit + ): + env = training_env + project = _ready_project(env) + toolkit("no_output") + + job = env.training.start_training(project.id, {}) + finished = _wait_for_terminal(env.jobs, job.id) + + assert finished.status is JobStatus.FAILED + assert ".safetensors" in (finished.error or "") + + loaded = env.projects.get_project(project.id) + assert loaded.training_status == "completed_no_output" + assert not loaded.trained_lora_path + + run = env.training.list_runs(project.id)[0] + assert run["status"] == "failed" + assert ".safetensors" in (run["error"] or "") + + +# ============================================ +# CANCELLATION +# ============================================ + + +class TestCancellation: + def test_cooperative_cancel_via_job_store( + self, training_env, fast_poll, toolkit + ): + """jobs.cancel() is observed in the _run poll loop; the worker stops the trainer itself.""" + env = training_env + project = _ready_project(env) + toolkit("slow") + + job = env.training.start_training(project.id, {}) + assert _wait_for_status(env.jobs, job.id, JobStatus.RUNNING) is not None + _wait_for_active(env.training, project.id) + + assert env.jobs.cancel(job.id) is True + finished = _wait_for_terminal(env.jobs, job.id) + + # The cancel branch returns cleanly: the worker must not overwrite CANCELLED. + assert finished.status is JobStatus.CANCELLED + run = _wait_for_cancelled(env, project.id, job.id) + assert env.projects.get_project(project.id).training_status == "cancelled" + assert run["status"] == "cancelled" + assert run["completed_at"] + # Trainer deregistered and its process gone. + assert project.id not in env.training._active + + def test_stop_training_cancels_synchronously(self, training_env, fast_poll, toolkit): + """stop_training() cancels + kills synchronously; the settled state may race with _run. + + Known race: after stop_training kills the process, the _run worker wakes to a non-zero + exit code and can mark job/project FAILED/"failed" before it ever sees the cancel flag. + The synchronous guarantees below are deterministic; the settled state is asserted + loosely so both outcomes of that race stay green. + """ + env = training_env + project = _ready_project(env) + toolkit("slow") + + job = env.training.start_training(project.id, {}) + assert _wait_for_status(env.jobs, job.id, JobStatus.RUNNING) is not None + _wait_for_active(env.training, project.id) + + assert env.training.stop_training(project.id) is True + # Synchronous guarantees (hold the moment stop_training returns): + loaded = env.projects.get_project(project.id) + assert loaded.training_status == "cancelled" + assert env.jobs.get(job.id).status is JobStatus.CANCELLED + assert project.id not in env.training._active + + # Let the _run worker settle (it polls every ~20 ms under fast_poll). + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + if env.jobs.get(job.id).status is JobStatus.FAILED: + break + time.sleep(0.05) + + assert env.jobs.get(job.id).status in (JobStatus.CANCELLED, JobStatus.FAILED) + assert env.projects.get_project(project.id).training_status in ("cancelled", "failed") + + def test_stop_training_with_nothing_running_returns_false(self, training_env): + env = training_env + project = _ready_project(env) + assert env.training.stop_training(project.id) is False + + +# ============================================ +# START GUARDS +# ============================================ + + +class TestStartGuards: + def test_duplicate_start_is_rejected(self, training_env, fast_poll, toolkit): + env = training_env + project = _ready_project(env) + toolkit("slow") + + job = env.training.start_training(project.id, {}) + assert _wait_for_status(env.jobs, job.id, JobStatus.RUNNING) is not None + _wait_for_active(env.training, project.id) + try: + with pytest.raises(LoRAProjectError): + env.training.start_training(project.id, {}) + finally: + env.jobs.cancel(job.id) + _wait_for_terminal(env.jobs, job.id) + + def test_start_without_toolkit_raises(self, training_env): + # tmp_settings leaves ai_toolkit_path / ai_toolkit_python empty. + env = training_env + project = _ready_project(env) + with pytest.raises(AIToolkitError): + env.training.start_training(project.id, {}) + + +# ============================================ +# HARDWARE PRESET TIERING +# ============================================ + + +class TestHardwarePresets: + def test_default_fixture_is_small_tier(self, training_env): + # Fixture default: 8 GB GPU -> "small" (<= 8 GiB). + result = training_env.training.hardware_presets() + assert result["hardware"]["tier"] == "small" + assert result["hardware"]["vram_mb"] == 8192 + + def test_medium_and_large_tiers(self, training_env, monkeypatch): + for vram, tier in ((16384, "medium"), (24576, "large")): + monkeypatch.setattr( + "app.services.hardware.detect_hardware", _fake_detect_hardware(vram) + ) + result = training_env.training.hardware_presets() + assert result["hardware"]["tier"] == tier + + def test_no_gpu_reports_unknown_tier(self, training_env, monkeypatch): + monkeypatch.setattr( + "app.services.hardware.detect_hardware", _fake_detect_hardware(None) + ) + result = training_env.training.hardware_presets() + assert result["hardware"]["tier"] == "unknown" + assert result["hardware"]["vram_mb"] is None + + def test_variants_scale_with_tier(self, training_env): + variants = training_env.training.hardware_presets()["presets"] + assert set(variants) == {"character", "style", "product", "concept", "general"} + for variant in variants.values(): + conservative = variant["conservative"] + balanced = variant["balanced"] + quality = variant["quality"] + assert conservative["batch_size"] == 1 + assert conservative["resolution"] and all(r <= 512 for r in conservative["resolution"]) + assert balanced["batch_size"] == 1 + assert quality["batch_size"] >= 2 + assert quality["lora_rank"] > conservative["lora_rank"] + + def test_variant_caps(self, training_env): + variants = training_env.training.hardware_presets()["presets"] + # style: base rank 32 -> quality capped at 64; product: base rank 8 kept in conservative. + assert variants["style"]["quality"]["lora_rank"] == 64 + assert variants["product"]["conservative"]["lora_rank"] == 8 + # concept is the only preset with batch_size 2; balanced normalises it to 1. + assert variants["concept"]["balanced"]["batch_size"] == 1 diff --git a/tests/test_ollama_client_behaviour.py b/tests/test_ollama_client_behaviour.py new file mode 100644 index 0000000..4234475 --- /dev/null +++ b/tests/test_ollama_client_behaviour.py @@ -0,0 +1,363 @@ +"""Unit tests for ``app.clients.ollama_client`` (HTTP layer). + +The client is exercised with a fake ``requests.request`` injected via +monkeypatch, so no Ollama server or network access is needed. Covers the +request plumbing (URL building, timeout), every error branch of +``_request``, each public method including its failure paths, and the +module-level ``_extract_ollama_error`` helper. +""" + +from __future__ import annotations + +import json + +import pytest + +from app.clients.ollama_client import OllamaClient, _extract_ollama_error +from app.core.exceptions import OllamaServiceError + + +class FakeResponse: + """Minimal stand-in for ``requests.Response``.""" + + def __init__(self, status_code=200, payload=None, text=""): + self.status_code = status_code + self.text = text + self._payload = payload if payload is not None else {} + + def json(self): + return self._payload + + +def make_client(monkeypatch, captured, response=None, base_url="http://localhost:11434", timeout=30.0): + """Build an ``OllamaClient`` whose HTTP calls land in ``captured``.""" + + def fake_request(*args, **kwargs): + captured.append((args, kwargs)) + return response if response is not None else FakeResponse() + + monkeypatch.setattr("app.clients.ollama_client.requests.request", fake_request) + return OllamaClient(base_url=base_url, timeout=timeout) + + +# --------------------------------------------------------------------------- # +# _request plumbing and error branches +# --------------------------------------------------------------------------- # + + +def test_request_success_builds_url_and_default_timeout(monkeypatch): + captured = [] + client = make_client( + monkeypatch, captured, FakeResponse(200, payload={"data": [{"id": "llama3.2"}]}) + ) + + result = client._request("GET", "/v1/models") + + assert result == {"data": [{"id": "llama3.2"}]} + (args, kwargs), = captured + assert args == () + assert kwargs["method"] == "GET" + assert kwargs["url"] == "http://localhost:11434/v1/models" + assert kwargs["json"] is None + assert kwargs["timeout"] == 30.0 + + +def test_request_explicit_timeout_overrides_default(monkeypatch): + captured = [] + client = make_client(monkeypatch, captured) + + client._request("POST", "/api/generate", json={"model": "llava"}, timeout=120) + + (args, kwargs), = captured + assert kwargs["timeout"] == 120 + + +def test_request_unreachable_raises_503(monkeypatch): + import requests + + def boom(*args, **kwargs): + raise requests.exceptions.ConnectionError("connection refused") + + monkeypatch.setattr("app.clients.ollama_client.requests.request", boom) + client = OllamaClient() + + with pytest.raises(OllamaServiceError, match="Ollama is unreachable") as excinfo: + client._request("GET", "/v1/models") + assert excinfo.value.status_code == 503 + assert "connection refused" in excinfo.value.detail + + +def test_request_timeout_exception_is_unreachable(monkeypatch): + import requests + + def boom(*args, **kwargs): + raise requests.exceptions.Timeout("timed out") + + monkeypatch.setattr("app.clients.ollama_client.requests.request", boom) + client = OllamaClient() + + with pytest.raises(OllamaServiceError, match="Ollama is unreachable"): + client._request("GET", "/v1/models") + + +def test_request_404_model_not_found(monkeypatch): + monkeypatch.setattr( + "app.clients.ollama_client.requests.request", + lambda *a, **kw: FakeResponse( + 404, payload={"error": "model 'llava' not found, try pulling it with 'ollama pull llava'"} + ), + ) + client = OllamaClient() + + with pytest.raises(OllamaServiceError, match="Ollama model not available: /v1/models") as excinfo: + client._request("GET", "/v1/models") + assert excinfo.value.status_code == 502 + + +def test_request_404_unknown_endpoint(monkeypatch): + monkeypatch.setattr( + "app.clients.ollama_client.requests.request", + lambda *a, **kw: FakeResponse(404, payload={"error": "not found"}), + ) + client = OllamaClient() + + with pytest.raises(OllamaServiceError, match="Ollama endpoint not found: /v1/models") as excinfo: + client._request("GET", "/v1/models") + assert excinfo.value.status_code == 502 + + +def test_request_server_error_raises_502(monkeypatch): + monkeypatch.setattr( + "app.clients.ollama_client.requests.request", lambda *a, **kw: FakeResponse(500) + ) + client = OllamaClient() + + with pytest.raises(OllamaServiceError, match="Ollama returned a server error") as excinfo: + client._request("GET", "/v1/models") + assert excinfo.value.status_code == 502 + + +def test_request_client_error_includes_status(monkeypatch): + monkeypatch.setattr( + "app.clients.ollama_client.requests.request", lambda *a, **kw: FakeResponse(413) + ) + client = OllamaClient() + + with pytest.raises(OllamaServiceError, match="Ollama request failed with status 413"): + client._request("POST", "/api/generate") + + +def test_request_invalid_json_raises(monkeypatch): + class BadResponse: + status_code = 200 + + def json(self): + raise json.JSONDecodeError("bad", "", 0) + + monkeypatch.setattr( + "app.clients.ollama_client.requests.request", lambda *a, **kw: BadResponse() + ) + client = OllamaClient() + + with pytest.raises(OllamaServiceError, match="Ollama returned an invalid response"): + client._request("GET", "/v1/models") + + +# --------------------------------------------------------------------------- # +# Public methods +# --------------------------------------------------------------------------- # + + +def test_chat_completion_posts_openai_payload(monkeypatch): + captured = [] + client = make_client( + monkeypatch, + captured, + FakeResponse(200, payload={"choices": [{"message": {"content": "hi"}}]}), + ) + + result = client.chat_completion(model="llama3.2", messages=[{"role": "user", "content": "hello"}]) + + assert result["choices"][0]["message"]["content"] == "hi" + (args, kwargs), = captured + assert kwargs["url"].endswith("/v1/chat/completions") + assert kwargs["json"] == { + "model": "llama3.2", + "messages": [{"role": "user", "content": "hello"}], + "stream": False, + } + + +def test_chat_is_alias_for_chat_completion(monkeypatch): + captured = [] + client = make_client( + monkeypatch, + captured, + FakeResponse(200, payload={"choices": [{"message": {"content": "hi"}}]}), + ) + + result = client.chat(model="llama3.2", messages=[{"role": "user", "content": "hello"}]) + + assert result["choices"][0]["message"]["content"] == "hi" + (args, kwargs), = captured + assert kwargs["url"].endswith("/v1/chat/completions") + + +def test_generate_converts_chat_response(monkeypatch): + captured = [] + client = make_client( + monkeypatch, + captured, + FakeResponse(200, payload={"choices": [{"message": {"content": "answer"}}]}), + ) + + result = client.generate(model="llama3.2", prompt="say something") + + assert result == {"response": "answer", "model": "llama3.2", "done": True} + (args, kwargs), = captured + assert kwargs["json"]["messages"] == [{"role": "user", "content": "say something"}] + + +def test_generate_without_choices_raises(monkeypatch): + monkeypatch.setattr( + "app.clients.ollama_client.requests.request", lambda *a, **kw: FakeResponse(200, payload={}) + ) + client = OllamaClient() + + with pytest.raises(OllamaServiceError, match="Invalid response from chat completion"): + client.generate(model="llama3.2", prompt="say something") + + +def test_list_models_uses_get(monkeypatch): + captured = [] + client = make_client( + monkeypatch, captured, FakeResponse(200, payload={"data": [{"id": "llama3.2"}]}) + ) + + result = client.list_models() + + assert result["data"] == [{"id": "llama3.2"}] + (args, kwargs), = captured + assert kwargs["method"] == "GET" + assert kwargs["url"].endswith("/v1/models") + + +def test_generate_with_images_returns_stripped_text(monkeypatch): + captured = [] + client = make_client( + monkeypatch, + captured, + FakeResponse(200, payload={"response": " a cat on a keyboard \n"}), + ) + + caption = client.generate_with_images( + model="llava", prompt="describe this image", images=["aGVsbG8="], timeout=120 + ) + + assert caption == "a cat on a keyboard" + (args, kwargs), = captured + assert kwargs["url"].endswith("/api/generate") + assert kwargs["json"] == { + "model": "llava", + "prompt": "describe this image", + "images": ["aGVsbG8="], + "stream": False, + } + assert kwargs["timeout"] == 120 + + +def test_generate_with_images_invalid_response_raises(monkeypatch): + monkeypatch.setattr( + "app.clients.ollama_client.requests.request", + lambda *a, **kw: FakeResponse(200, payload={"response": 42}), + ) + client = OllamaClient() + + with pytest.raises(OllamaServiceError, match="Ollama returned an invalid vision response"): + client.generate_with_images(model="llava", prompt="describe", images=["aGVsbG8="]) + + +def test_embed_returns_embeddings_list(monkeypatch): + captured = [] + client = make_client( + monkeypatch, + captured, + FakeResponse(200, payload={"embeddings": [[0.1, 0.2], [0.3, 0.4]]}), + ) + + vectors = client.embed(model="nomic-embed-text", inputs=["alpha", "beta"]) + + assert vectors == [[0.1, 0.2], [0.3, 0.4]] + (args, kwargs), = captured + assert kwargs["url"].endswith("/api/embed") + assert kwargs["json"] == {"model": "nomic-embed-text", "input": ["alpha", "beta"]} + + +def test_embed_legacy_fallback_for_single_input(monkeypatch): + captured = [] + responses = iter( + [ + FakeResponse(200, payload={"embeddings": []}), + FakeResponse(200, payload={"embedding": [0.5, 0.6]}), + ] + ) + + def fake_request(*args, **kwargs): + captured.append((args, kwargs)) + return next(responses) + + monkeypatch.setattr("app.clients.ollama_client.requests.request", fake_request) + client = OllamaClient(base_url="http://localhost:11434", timeout=30.0) + + vectors = client.embed(model="nomic-embed-text", inputs=["only one"]) + + assert vectors == [[0.5, 0.6]] + assert len(captured) == 2 + first_kwargs = captured[0][1] + second_kwargs = captured[1][1] + assert first_kwargs["url"].endswith("/api/embed") + assert second_kwargs["url"].endswith("/api/embeddings") + assert second_kwargs["json"] == {"model": "nomic-embed-text", "prompt": "only one"} + + +def test_embed_invalid_response_raises(monkeypatch): + monkeypatch.setattr( + "app.clients.ollama_client.requests.request", lambda *a, **kw: FakeResponse(200, payload={}) + ) + client = OllamaClient() + + with pytest.raises(OllamaServiceError, match="Ollama returned an invalid embedding response"): + client.embed(model="nomic-embed-text", inputs=["only one"]) + + +# --------------------------------------------------------------------------- # +# _extract_ollama_error helper +# --------------------------------------------------------------------------- # + + +def test_extract_ollama_error_prefers_error_field(): + response = FakeResponse(404, payload={"error": "model 'x' not found"}, text="raw body") + assert _extract_ollama_error(response) == "model 'x' not found" + + +def test_extract_ollama_error_truncates_long_errors(): + response = FakeResponse(404, payload={"error": "x" * 500}, text="raw body") + assert _extract_ollama_error(response) == "x" * 300 + + +def test_extract_ollama_error_falls_back_to_text_on_bad_json(): + class BadResponse: + status_code = 404 + text = "plain text error" + + def json(self): + raise json.JSONDecodeError("bad", "", 0) + + assert _extract_ollama_error(BadResponse()) == "plain text error" + + +def test_extract_ollama_error_no_error_key_returns_text(): + response = FakeResponse(404, payload={"foo": "bar"}, text="raw body") + assert _extract_ollama_error(response) == "raw body" + + diff --git a/tests/test_persistence_behaviour.py b/tests/test_persistence_behaviour.py new file mode 100644 index 0000000..269f96a --- /dev/null +++ b/tests/test_persistence_behaviour.py @@ -0,0 +1,91 @@ +"""Behaviour tests for app/core/persistence.py (JsonPersist).""" + +from __future__ import annotations + +import json +import logging +from pathlib import Path + +# ---------- construction ------------------------------------------------------ + + +class TestInit: + def test_explicit_data_dir_builds_path_and_creates_parent(self, tmp_path): + from app.core.persistence import JsonPersist + + store = JsonPersist("mem.json", data_dir=str(tmp_path / "nested" / "data")) + + assert str(store.path) == str(tmp_path / "nested" / "data" / "mem.json") + assert (tmp_path / "nested" / "data").is_dir() + + def test_without_data_dir_uses_settings(self, tmp_settings): + from app.core.persistence import JsonPersist + + store = JsonPersist("mem.json") + + assert str(store.path) == str(Path(tmp_settings.data_dir) / "mem.json") + + +# ---------- load -------------------------------------------------------------- + + +class TestLoad: + def test_missing_file_returns_default(self, tmp_path): + from app.core.persistence import JsonPersist + + store = JsonPersist("mem.json", data_dir=str(tmp_path)) + + assert store.load({"fallback": True}) == {"fallback": True} + + def test_corrupt_file_returns_default(self, tmp_path): + from app.core.persistence import JsonPersist + + store = JsonPersist("mem.json", data_dir=str(tmp_path)) + store.path.write_text("{not json", encoding="utf-8") + + assert store.load(None) is None + + +# ---------- save -------------------------------------------------------------- + + +class TestSave: + def test_save_then_load_roundtrip(self, tmp_path): + from app.core.persistence import JsonPersist + + store = JsonPersist("mem.json", data_dir=str(tmp_path)) + payload = {"entries": [{"id": 1}], "count": 1} + store.save(payload) + + assert store.load(None) == payload + + def test_save_writes_valid_json_and_leaves_no_temp_files(self, tmp_path): + from app.core.persistence import JsonPersist + + store = JsonPersist("mem.json", data_dir=str(tmp_path)) + store.save({"a": [1, 2]}) + + on_disk = json.loads(store.path.read_text(encoding="utf-8")) + assert on_disk == {"a": [1, 2]} + assert list(store.path.parent.glob("*.tmp")) == [] + + def test_save_swallows_oserror_and_logs_warning(self, tmp_path, monkeypatch, caplog): + from app.core import persistence + from app.core.persistence import JsonPersist + + store = JsonPersist("mem.json", data_dir=str(tmp_path)) + + def _boom(path, payload): + raise OSError("disk full") + + monkeypatch.setattr(persistence, "write_json_atomic", _boom) + + with caplog.at_level(logging.WARNING, logger="app.core.persistence"): + store.save({"a": 1}) # must not raise + + assert store.path.exists() is False + warnings = [r for r in caplog.records if r.levelno == logging.WARNING] + assert len(warnings) == 1 + message = warnings[0].getMessage() + assert "Could not write mem.json" in message + assert "disk full" in message diff --git a/tests/test_prompt_service_behaviour.py b/tests/test_prompt_service_behaviour.py new file mode 100644 index 0000000..91d0fc1 --- /dev/null +++ b/tests/test_prompt_service_behaviour.py @@ -0,0 +1,128 @@ +"""Behavioural tests for app/services/prompt_service.py.""" + +import pytest + +from app.services import prompt_service as module +from app.services.prompt_service import PromptService + + +class TestDefaultsAndCreate: + def test_constructor_seeds_four_default_prompts(self): + svc = PromptService() + + prompts = {p["name"]: p for p in svc.list_prompts()} + assert set(prompts) == {"default", "code_helper", "document_analyzer", "summarizer"} + # Creation order: default, code_helper, document_analyzer, summarizer. + assert [p["id"] for p in (prompts[n] for n in ("default", "code_helper", "document_analyzer", "summarizer"))] == [ + "prompt_0", + "prompt_1", + "prompt_2", + "prompt_3", + ] + + def test_create_prompt_returns_incrementing_ids(self): + svc = PromptService() + + new_id = svc.create_prompt("custom", "body {input}") + + assert new_id == "prompt_4" # counter continues past the four defaults + stored = svc.get_prompt(new_id) + assert stored["name"] == "custom" + assert stored["content"] == "body {input}" + + +class TestRetrieve: + def test_get_prompt_missing_returns_none(self): + assert PromptService().get_prompt("prompt_99") is None + + def test_get_prompt_by_name_found_and_missing(self): + svc = PromptService() + + found = svc.get_prompt_by_name("summarizer") + assert found is not None and "{input}" in found["content"] + + assert svc.get_prompt_by_name("nope") is None + + def test_list_prompts_sorted_case_insensitively(self): + svc = PromptService() + svc.create_prompt("Zeta", "z") + svc.create_prompt("alpha", "a") + + names = [p["name"] for p in svc.list_prompts()] + assert names == ["alpha", "code_helper", "default", "document_analyzer", "summarizer", "Zeta"] + + +class TestUpdate: + def test_update_missing_id_returns_false(self): + assert PromptService().update_prompt("prompt_99", name="x") is False + + @pytest.fixture() + def clock(self, monkeypatch): + """Deterministic _utc_now: t0, t1, t2, ... in call order.""" + ticks = iter(f"t{i}" for i in range(50)) + monkeypatch.setattr(module, "_utc_now", lambda: next(ticks)) + return ticks + + def test_update_name_and_content_bumps_updated_at(self, clock): + svc = PromptService() # consumes t0..t7 (4 defaults x created+updated) + prompt_id = svc.create_prompt("old", "old body") # t8/t9 + original_created = svc.get_prompt(prompt_id)["created_at"] + + assert svc.update_prompt(prompt_id, name="new", content="new body") is True + + updated = svc.get_prompt(prompt_id) + assert (updated["name"], updated["content"]) == ("new", "new body") + assert updated["created_at"] == original_created # created_at untouched + assert updated["updated_at"] != original_created # bumped by the update + + def test_update_partial_fields_only_touches_given_ones(self, clock): + svc = PromptService() + prompt_id = svc.create_prompt("keep-name", "keep-content") + + assert svc.update_prompt(prompt_id, name="renamed") is True + renamed = svc.get_prompt(prompt_id) + assert (renamed["name"], renamed["content"]) == ("renamed", "keep-content") + + assert svc.update_prompt(prompt_id, content="new-body") is True + edited = svc.get_prompt(prompt_id) + assert (edited["name"], edited["content"]) == ("renamed", "new-body") + + def test_update_with_no_fields_still_bumps_timestamp(self, clock): + svc = PromptService() + prompt_id = svc.create_prompt("x", "y") + before = svc.get_prompt(prompt_id)["updated_at"] + + assert svc.update_prompt(prompt_id) is True + + after = svc.get_prompt(prompt_id)["updated_at"] + assert (after, before) != (before, after) + + +class TestDelete: + def test_delete_existing_and_missing(self): + svc = PromptService() + prompt_id = svc.create_prompt("doomed", "x") + + assert svc.delete_prompt(prompt_id) is True + assert svc.get_prompt(prompt_id) is None + assert svc.delete_prompt(prompt_id) is False + + +class TestApplyTemplate: + def test_replaces_input_placeholder(self): + svc = PromptService() + prompt_id = svc.create_prompt("tpl", "Do this: {input} now") + + result = svc.apply_template(prompt_id, "the task") + assert result == "Do this: the task now" + + def test_appends_user_input_when_no_placeholder(self): + svc = PromptService() + prompt_id = svc.create_prompt("plain", "Just a system line") + + result = svc.apply_template(prompt_id, "user says hi") + assert result == "Just a system line\n\nuser says hi" + + def test_missing_id_raises_keyerror(self): + with pytest.raises(KeyError, match="prompt_99"): + PromptService().apply_template("prompt_99", "x") diff --git a/tests/test_routes_behaviour.py b/tests/test_routes_behaviour.py new file mode 100644 index 0000000..d351deb --- /dev/null +++ b/tests/test_routes_behaviour.py @@ -0,0 +1,839 @@ +"""Behaviour tests for the core API routes (app/api/routes.py). + +Complements test_api_app.py (full-app smoke) and the per-service behaviour +files: these drive the router itself with a minimal app that wires only the +five route dependencies, so every handler runs against recording fakes. The +tests pin how each endpoint assembles responses, degrades when Ollama is down +(503 guidance card on /health, degraded payload on /ready), rolls back a +document whose RAG indexing failed, and maps service errors onto HTTP status +codes - without touching disk or the network. +""" + +from __future__ import annotations + +import asyncio +from types import SimpleNamespace +from typing import Any, cast + +import pytest +from fastapi import FastAPI, HTTPException +from fastapi.testclient import TestClient + +from app.api.routes import _build_system_prompt, router, upload_document +from app.core.config import settings +from app.core.exceptions import OllamaServiceError + +# ============================================ +# FAKES (recording stand-ins for the five services) +# ============================================ + + +class FakeLLM: + """Stand-in for ``LLMService``; optional per-method errors, records chats.""" + + def __init__( + self, + *, + health_error: Exception | None = None, + models_error: Exception | None = None, + chat_error: Exception | None = None, + base_url: str | None = "http://127.0.0.1:11435", + ) -> None: + self.health_error = health_error + self.models_error = models_error + self.chat_error = chat_error + # ``None`` mirrors a service whose client was never built, so the + # routes fall back to settings.ollama_base_url. + self.client = SimpleNamespace(base_url=base_url) if base_url is not None else None + self.chat_calls: list[tuple[str, str | None]] = [] + + def health_check(self) -> dict: + if self.health_error: + raise self.health_error + return {"status": "ok", "ollama_reachable": True, "model": "llama3.2"} + + def chat(self, prompt: str, model: str | None = None) -> str: + if self.chat_error: + raise self.chat_error + self.chat_calls.append((prompt, model)) + return "REPLY" + + def list_models(self) -> list[str]: + if self.models_error: + raise self.models_error + return ["llama3.2", "mistral"] + + +class FakeMemory: + """Stand-in for ``MemoryService``; records every mutation.""" + + def __init__(self, history_text: str = "HISTORY") -> None: + self.history_text = history_text + self.use_documents_calls: list[tuple[str, bool]] = [] + self.added: list[tuple[str, str, str]] = [] + self.cleared: list[str] = [] + + def set_use_documents(self, session_id: str, flag: bool) -> None: + self.use_documents_calls.append((session_id, flag)) + + def format_history_for_prompt(self, session_id: str) -> str: + return self.history_text + + def add_message(self, session_id: str, role: str, content: str) -> None: + self.added.append((session_id, role, content)) + + def get_history(self, session_id: str) -> list[dict]: + return [ + {"role": "user", "content": "hi", "timestamp": "2026-01-01T00:00:00"}, + {"role": "assistant", "content": "hello!", "timestamp": "2026-01-01T00:00:05"}, + ] + + def clear_history(self, session_id: str) -> None: + self.cleared.append(session_id) + + +class FakeDocs: + """Stand-in for ``DocumentService``; ids are sequential doc-N.""" + + def __init__(self, docs=(), delete_result: bool = True) -> None: + self.docs = list(docs) + self.delete_result = delete_result + self.stored: list[tuple[str, str]] = [] + self.deleted: list[str] = [] + self.cleared = 0 + + def store_document(self, text: str, source: str) -> str: + doc_id = f"doc-{len(self.stored) + 1}" + self.stored.append((text, source)) + return doc_id + + def get_all_documents(self) -> list[dict]: + return list(self.docs) + + def delete_document(self, doc_id: str) -> bool: + self.deleted.append(doc_id) + return self.delete_result + + def clear_all(self) -> None: + self.cleared += 1 + + +class FakePrompts: + """Stand-in for ``PromptService``; in-memory store with fixed timestamps.""" + + def __init__( + self, + prompts=(), + default: dict | None = None, + update_result: bool = True, + delete_result: bool = True, + get_after_create: bool = True, + ) -> None: + self.store = {p["id"]: dict(p) for p in prompts} + self.default = default + self.update_result = update_result + self.delete_result = delete_result + self.get_after_create = get_after_create + self.created: list[tuple[str, str]] = [] + self.updated: list[tuple[str, str | None, str | None]] = [] + self.deleted: list[str] = [] + + def create_prompt(self, name: str, content: str) -> str: + prompt_id = f"p{len(self.created) + 1}" + self.created.append((name, content)) + if self.get_after_create: + self.store[prompt_id] = { + "id": prompt_id, + "name": name, + "content": content, + "created_at": "2026-01-02T03:04:05", + "updated_at": "2026-01-02T03:04:05", + } + return prompt_id + + def get_prompt(self, prompt_id: str) -> dict | None: + prompt = self.store.get(prompt_id) + return dict(prompt) if prompt else None + + def get_prompt_by_name(self, name: str) -> dict | None: + if self.default and name == "default": + return dict(self.default) + return None + + def apply_template(self, prompt_id: str, message: str) -> str: + return f"[tpl:{prompt_id}] {message}" + + def update_prompt( + self, prompt_id: str, name: str | None = None, content: str | None = None + ) -> bool: + self.updated.append((prompt_id, name, content)) + if prompt_id in self.store: + if name is not None: + self.store[prompt_id]["name"] = name + if content is not None: + self.store[prompt_id]["content"] = content + return self.update_result + + def delete_prompt(self, prompt_id: str) -> bool: + self.deleted.append(prompt_id) + if prompt_id not in self.store: + return False + del self.store[prompt_id] + return self.delete_result + + def list_prompts(self) -> list[dict]: + return [dict(p) for p in self.store.values()] + + +class FakeRAG: + """Stand-in for ``RAGService``; fixed chunks/context, records calls.""" + + def __init__( + self, + chunks=("chunk-a", "chunk-b"), + context: str = "CTX", + add_error: Exception | None = None, + ) -> None: + self.chunks = list(chunks) + self.context = context + self.add_error = add_error + self.query_calls: list[str] = [] + self.debug_calls: list[tuple[str, int]] = [] + self.added: list[tuple[str, dict]] = [] + self.removed: list[str] = [] + self.cleared = 0 + + def status(self) -> dict: + return {"model": "fake-embed", "documents": 2} + + def query(self, text: str) -> list[dict]: + self.query_calls.append(text) + return list(self.chunks) + + def format_context(self, chunks: list[dict]) -> str: + return self.context if chunks else "" + + def add_document(self, text: str, meta: dict) -> int: + if self.add_error: + raise self.add_error + self.added.append((text, dict(meta))) + return 3 + + def remove_document(self, doc_id: str) -> None: + self.removed.append(doc_id) + + def clear(self) -> None: + self.cleared += 1 + + def query_debug(self, q: str, top_k: int = 4) -> dict: + self.debug_calls.append((q, top_k)) + return {"query": q} + + +# ============================================ +# FIXTURES & HELPERS +# ============================================ + + +@pytest.fixture +def routes_env(): + """Minimal FastAPI app with only the core router and fake services.""" + llm = FakeLLM() + memory = FakeMemory() + docs = FakeDocs() + prompts = FakePrompts() + rag = FakeRAG() + + app = FastAPI() + app.include_router(router) + app.state.llm_service = llm + app.state.memory_service = memory + app.state.document_service = docs + app.state.prompt_service = prompts + app.state.rag_service = rag + # /dashboard reads four more services off the app state. + app.state.lora_project_service = SimpleNamespace(kind="lora_projects") + app.state.lora_training_service = SimpleNamespace(kind="training") + app.state.comfyui_service = SimpleNamespace(kind="comfyui") + app.state.job_store = SimpleNamespace(kind="jobs") + + return SimpleNamespace( + client=TestClient(app), + llm=llm, + memory=memory, + docs=docs, + prompts=prompts, + rag=rag, + ) + + +def _chat(client: TestClient, **overrides) -> dict: + payload = {"prompt": "hello", "session_id": "s1"} + payload.update(overrides) + response = client.post("/chat", json=payload) + assert response.status_code == 200, response.text + return response.json() + + +DEFAULT_PROMPT = { + "id": "default", + "name": "default", + "content": "Be terse.", + "created_at": "2026-01-01T00:00:00", + "updated_at": "2026-01-01T00:00:00", +} + + +# ============================================ +# HEALTH & STATUS ENDPOINTS +# ============================================ + + +def test_live_is_dependency_free(routes_env) -> None: + response = routes_env.client.get("/live") + + assert response.status_code == 200 + assert response.json() == {"status": "alive"} + + +def test_ready_ok_when_ollama_answers(routes_env) -> None: + response = routes_env.client.get("/ready") + + assert response.status_code == 200 + assert response.json() == {"status": "ready"} + + +def test_ready_degraded_reports_url_and_detail(routes_env) -> None: + routes_env.llm.models_error = OllamaServiceError( + "Ollama is unreachable", status_code=503, detail="connect ECONNREFUSED" + ) + + response = routes_env.client.get("/ready") + + assert response.status_code == 503 + assert response.json()["detail"] == { + "status": "degraded", + "reason": "Ollama is unreachable", + "url": "http://127.0.0.1:11435", + "detail": "connect ECONNREFUSED", + } + + +def test_ready_falls_back_to_settings_url_without_client(routes_env) -> None: + routes_env.llm.client = None + routes_env.llm.models_error = OllamaServiceError( + "Ollama is unreachable", status_code=503, detail="down" + ) + + response = routes_env.client.get("/ready") + + assert response.status_code == 503 + assert response.json()["detail"]["url"] == settings.ollama_base_url + + +def test_health_ok_returns_payload(routes_env) -> None: + response = routes_env.client.get("/health") + + assert response.status_code == 200 + assert response.json() == { + "status": "ok", + "ollama_reachable": True, + "model": "llama3.2", + "available_models": None, + } + + +def test_health_unreachable_returns_setup_card(routes_env) -> None: + routes_env.llm.health_error = OllamaServiceError( + "Ollama is unreachable", status_code=503, detail="raw probe failure" + ) + + response = routes_env.client.get("/health") + + assert response.status_code == 503 + detail = response.json()["detail"] + assert detail["message"] == "Ollama is not reachable." + assert detail["url_checked"] == "http://127.0.0.1:11435" + assert detail["expected_model"] == settings.default_model + assert detail["how_to_fix"][1] == ( + "Start it with: ollama serve (listening on http://127.0.0.1:11435)" + ) + assert detail["unavailable_features"] == [ + "Chat", + "RAG document Q&A", + "AI dataset captioning", + ] + assert detail["working_features"] == [ + "ComfyUI image generation", + "Dataset management", + "Dataset validation", + "LoRA training", + ] + assert detail["raw_detail"] == "raw probe failure" + + +def test_models_ok(routes_env) -> None: + response = routes_env.client.get("/models") + + assert response.status_code == 200 + assert response.json() == {"models": ["llama3.2", "mistral"]} + + +def test_models_maps_service_error_status_and_detail(routes_env) -> None: + routes_env.llm.models_error = OllamaServiceError( + "Ollama is unreachable", status_code=502, detail="bad gateway" + ) + + response = routes_env.client.get("/models") + + assert response.status_code == 502 + assert response.json()["detail"] == "bad gateway" + + +def test_rag_status_passthrough(routes_env) -> None: + response = routes_env.client.get("/rag/status") + + assert response.status_code == 200 + assert response.json() == {"model": "fake-embed", "documents": 2} + + +@pytest.mark.parametrize("q", ["", " "]) +def test_debug_query_rejects_blank_q(routes_env, q: str) -> None: + response = routes_env.client.get("/rag/debug-query", params={"q": q}) + + assert response.status_code == 400 + assert response.json()["detail"] == "Query 'q' is required" + + +def test_debug_query_strips_q_and_clamps_top_k(routes_env) -> None: + client = routes_env.client + + response = client.get("/rag/debug-query", params={"q": " hi ", "top_k": 99}) + assert response.status_code == 200 + assert response.json() == {"query": "hi"} + + client.get("/rag/debug-query", params={"q": "hi", "top_k": 0}) + + assert routes_env.rag.debug_calls == [("hi", 20), ("hi", 1)] + + +def test_dashboard_delegates_to_build_dashboard(routes_env, monkeypatch) -> None: + calls: list[dict] = [] + + def fake_build(**kwargs): + calls.append(kwargs) + return {"ok": True} + + monkeypatch.setattr("app.services.dashboard.build_dashboard", fake_build) + + response = routes_env.client.get("/dashboard") + + assert response.status_code == 200 + assert response.json() == {"ok": True} + assert len(calls) == 1 + # The route passes the live service objects straight through. + kwargs = calls[0] + assert kwargs["document_service"] is routes_env.docs + assert kwargs["rag_service"] is routes_env.rag + assert kwargs["project_service"].kind == "lora_projects" + assert kwargs["training_service"].kind == "training" + assert kwargs["comfyui_service"].kind == "comfyui" + assert kwargs["job_store"].kind == "jobs" + + +# ============================================ +# CHAT ENDPOINTS +# ============================================ + + +def test_chat_plain_assembles_prompt_and_records_turns(routes_env) -> None: + routes_env.prompts.default = DEFAULT_PROMPT + + body = _chat(routes_env.client, use_documents=False) + + assert body == {"response": "REPLY", "session_id": "s1"} + (full_prompt, model), = routes_env.llm.chat_calls + assert model is None + assert full_prompt == ( + "You are an AI assistant.\nBe terse.\n\n" + "CHAT HISTORY:\nHISTORY\n\n" + "USER QUESTION:\nhello" + ) + assert routes_env.memory.use_documents_calls == [("s1", False)] + assert routes_env.memory.added == [ + ("s1", "user", "hello"), + ("s1", "assistant", "REPLY"), + ] + + +def test_chat_with_documents_injects_context(routes_env) -> None: + routes_env.prompts.default = DEFAULT_PROMPT + + _chat(routes_env.client, use_documents=True) + + assert routes_env.rag.query_calls == ["hello"] + (full_prompt, model), = routes_env.llm.chat_calls + assert full_prompt == ( + "You are an AI assistant.\nBe terse.\n\n" + "Use the context below if relevant.\n\nCONTEXT:\nCTX\n\n" + "CHAT HISTORY:\nHISTORY\n\n" + "USER QUESTION:\nhello" + ) + + +def test_chat_applies_template_but_stores_original_message(routes_env) -> None: + routes_env.prompts.default = DEFAULT_PROMPT + routes_env.prompts.store["p9"] = { + "id": "p9", + "name": "tpl", + "content": "Template body.", + "created_at": "2026-01-01T00:00:00", + "updated_at": "2026-01-01T00:00:00", + } + + _chat(routes_env.client, prompt_id="p9", use_documents=False) + + (full_prompt, model), = routes_env.llm.chat_calls + assert full_prompt.endswith("USER QUESTION:\n[tpl:p9] hello") + # The session memory keeps the user's original words, not the templated form. + assert routes_env.memory.added[0] == ("s1", "user", "hello") + + +def test_chat_unknown_prompt_id_404_without_side_effects(routes_env) -> None: + response = routes_env.client.post( + "/chat", json={"prompt": "hello", "session_id": "s1", "prompt_id": "nope"} + ) + + assert response.status_code == 404 + assert response.json()["detail"] == "Prompt nope not found" + assert routes_env.llm.chat_calls == [] + assert routes_env.memory.added == [] + + +def test_chat_falls_back_to_builtin_system_prompt_without_default(routes_env) -> None: + routes_env.memory.history_text = "" + + _chat(routes_env.client, use_documents=False) + + (full_prompt, model), = routes_env.llm.chat_calls + # Empty doc context and history drop those sections entirely. + assert full_prompt == ( + "You are an AI assistant.\nYou are a helpful AI assistant.\n\n" + "USER QUESTION:\nhello" + ) + + +def test_chat_maps_ollama_error_to_http(routes_env) -> None: + routes_env.llm.chat_error = OllamaServiceError( + "model not found", status_code=404, detail="no such model" + ) + + response = routes_env.client.post("/chat", json={"prompt": "hello"}) + + assert response.status_code == 404 + assert response.json()["detail"] == "no such model" + + +# ============================================ +# SESSION ENDPOINTS +# ============================================ + + +def test_session_history_shape(routes_env) -> None: + response = routes_env.client.get("/sessions/s1/history") + + assert response.status_code == 200 + body = response.json() + assert body["session_id"] == "s1" + assert body["message_count"] == 2 + assert [m["role"] for m in body["messages"]] == ["user", "assistant"] + assert body["messages"][0]["content"] == "hi" + + +def test_clear_session_history(routes_env) -> None: + response = routes_env.client.delete("/sessions/s1/history") + + assert response.status_code == 200 + assert response.json() == {"message": "History cleared for session s1"} + assert routes_env.memory.cleared == ["s1"] + + +# ============================================ +# DOCUMENT ENDPOINTS +# ============================================ + + +def test_documents_list_projects_id_and_source(routes_env) -> None: + routes_env.docs.docs = [ + { + "id": "doc-1", + "source": "notes.txt", + "char_count": 42, + "created_at": "2026-01-01T00:00:00", + } + ] + + response = routes_env.client.get("/documents") + + assert response.status_code == 200 + body = response.json() + # Only id + source are exposed; internal fields stay server-side. + assert body["count"] == 1 + assert body["documents"] == [{"id": "doc-1", "source": "notes.txt"}] + + +def test_document_upload_stores_and_indexes(routes_env) -> None: + response = routes_env.client.post( + "/documents/upload", files={"file": ("notes.txt", b"hello docs", "text/plain")} + ) + + assert response.status_code == 200 + assert response.json() == { + "id": "doc-1", + "source": "notes.txt", + "message": "Document stored successfully", + } + assert routes_env.docs.stored == [("hello docs", "notes.txt")] + # RAG indexing is keyed by doc_id so chunks can be removed with the document. + (indexed_text, meta), = routes_env.rag.added + assert indexed_text == "hello docs" + assert meta == {"doc_id": "doc-1", "filename": "notes.txt"} + + +def test_upload_document_rejects_falsy_filename(routes_env) -> None: + # Starlette validates UploadFile at the framework level, so an empty + # filename arrives as a 422 before the handler body runs. Call the + # handler directly to pin the guard's own contract. + + async def _never_read() -> bytes: + raise AssertionError("file.read must not run for an empty filename") + + fake_file = SimpleNamespace(filename="", read=_never_read) + with pytest.raises(HTTPException) as excinfo: + asyncio.run(upload_document(cast(Any, fake_file), routes_env.docs, routes_env.rag)) + + assert excinfo.value.status_code == 400 + assert excinfo.value.detail == "Filename is required" + + +def test_document_upload_rejects_unsupported_extension(routes_env) -> None: + response = routes_env.client.post( + "/documents/upload", files={"file": ("virus.exe", b"MZ", "application/octet-stream")} + ) + + assert response.status_code == 400 + assert ( + response.json()["detail"] + == "Unsupported file type. Supported: .docx, .pdf, .txt" + ) + assert routes_env.docs.stored == [] + + +def test_document_upload_rejects_invalid_utf8(routes_env) -> None: + response = routes_env.client.post( + "/documents/upload", files={"file": ("notes.txt", b"\xff\xfe\xfa", "text/plain")} + ) + + assert response.status_code == 400 + assert response.json()["detail"] == "File must be valid UTF-8 text" + + +def test_document_upload_rejects_blank_text(routes_env) -> None: + response = routes_env.client.post( + "/documents/upload", files={"file": ("notes.txt", b" \n", "text/plain")} + ) + + assert response.status_code == 400 + assert response.json()["detail"] == "No extractable text found in 'notes.txt'" + + +def test_document_upload_rolls_back_when_rag_fails(routes_env) -> None: + routes_env.rag.add_error = OllamaServiceError( + "down", status_code=503, detail="nope" + ) + + response = routes_env.client.post( + "/documents/upload", files={"file": ("notes.txt", b"hello docs", "text/plain")} + ) + + assert response.status_code == 503 + assert response.json()["detail"] == "nope" + # The stored document is deleted again so the store and the index stay in sync. + assert routes_env.docs.stored == [("hello docs", "notes.txt")] + assert routes_env.docs.deleted == ["doc-1"] + + +def test_document_upload_500s_on_generic_failure_without_rollback(routes_env) -> None: + routes_env.rag.add_error = RuntimeError("indexer exploded") + + response = routes_env.client.post( + "/documents/upload", files={"file": ("notes.txt", b"hello docs", "text/plain")} + ) + + assert response.status_code == 500 + assert ( + response.json()["detail"] == "Error uploading document: indexer exploded" + ) + # Only OllamaServiceError triggers the rollback path. + assert routes_env.docs.deleted == [] + + +def test_document_delete_found_and_missing(routes_env) -> None: + client = routes_env.client + + response = client.delete("/documents/doc-7") + assert response.status_code == 200 + assert response.json() == {"message": "Document doc-7 deleted"} + # A successful delete also drops the document's chunks from RAG. + assert routes_env.rag.removed == ["doc-7"] + + routes_env.docs.delete_result = False + response = client.delete("/documents/doc-8") + assert response.status_code == 404 + assert response.json()["detail"] == "Document doc-8 not found" + + assert routes_env.docs.deleted == ["doc-7", "doc-8"] + + +def test_documents_clear_all(routes_env) -> None: + response = routes_env.client.delete("/documents") + + assert response.status_code == 200 + assert response.json() == {"message": "All documents cleared"} + assert routes_env.docs.cleared == 1 + assert routes_env.rag.cleared == 1 + + +# ============================================ +# PROMPT ENDPOINTS +# ============================================ + + +def test_prompts_list_includes_count(routes_env) -> None: + routes_env.prompts.store["p1"] = { + "id": "p1", + "name": "one", + "content": "c1", + "created_at": "2026-01-01T00:00:00", + "updated_at": "2026-01-01T00:00:00", + } + + response = routes_env.client.get("/prompts") + + assert response.status_code == 200 + body = response.json() + assert body["count"] == 1 + assert body["prompts"][0]["name"] == "one" + + +def test_prompt_create_returns_fresh_record(routes_env) -> None: + response = routes_env.client.post( + "/prompts", json={"name": "one", "content": "c1"} + ) + + assert response.status_code == 200 + body = response.json() + assert body["id"] == "p1" + assert body["created_at"] == "2026-01-02T03:04:05" + assert routes_env.prompts.created == [("one", "c1")] + + +def test_prompt_create_500_when_record_missing(routes_env) -> None: + routes_env.prompts.get_after_create = False + + response = routes_env.client.post( + "/prompts", json={"name": "ghost", "content": "c"} + ) + + assert response.status_code == 500 + assert response.json()["detail"] == "Failed to create prompt" + + +def test_prompt_get_found_and_missing(routes_env) -> None: + routes_env.prompts.store["p1"] = { + "id": "p1", + "name": "one", + "content": "c1", + "created_at": "2026-01-01T00:00:00", + "updated_at": "2026-01-01T00:00:00", + } + client = routes_env.client + + response = client.get("/prompts/p1") + assert response.status_code == 200 + # The record is returned flat, not wrapped in a "prompt" key. + assert response.json() == routes_env.prompts.store["p1"] + + response = client.get("/prompts/missing") + assert response.status_code == 404 + assert response.json()["detail"] == "Prompt missing not found" + + +def test_prompt_update_partial_and_missing(routes_env) -> None: + routes_env.prompts.store["p1"] = { + "id": "p1", + "name": "one", + "content": "c1", + "created_at": "2026-01-01T00:00:00", + "updated_at": "2026-01-01T00:00:00", + } + client = routes_env.client + + response = client.put("/prompts/p1", json={"name": "renamed"}) + assert response.status_code == 200 + body = response.json() + # Partial update: only the provided field changes, content is untouched. + assert body["id"] == "p1" + assert body["name"] == "renamed" + assert body["content"] == "c1" + assert routes_env.prompts.updated == [("p1", "renamed", None)] + + routes_env.prompts.update_result = False + response = client.put("/prompts/p2", json={"content": "x"}) + assert response.status_code == 404 + assert response.json()["detail"] == "Prompt p2 not found" + + +def test_prompt_delete_found_and_missing(routes_env) -> None: + routes_env.prompts.store["p1"] = { + "id": "p1", + "name": "one", + "content": "c1", + "created_at": "2026-01-01T00:00:00", + "updated_at": "2026-01-01T00:00:00", + } + client = routes_env.client + + response = client.delete("/prompts/p1") + assert response.status_code == 200 + assert response.json() == {"message": "Prompt p1 deleted"} + assert "p1" not in routes_env.prompts.store + + response = client.delete("/prompts/missing") + assert response.status_code == 404 + assert response.json()["detail"] == "Prompt missing not found" + + assert routes_env.prompts.deleted == ["p1", "missing"] + + +# ============================================ +# _build_system_prompt HELPER +# ============================================ + + +def test_build_system_prompt_includes_all_sections() -> None: + full = _build_system_prompt("Be terse.", "CTX", "HISTORY", "hello") + + assert full == ( + "You are an AI assistant.\nBe terse.\n\n" + "Use the context below if relevant.\n\nCONTEXT:\nCTX\n\n" + "CHAT HISTORY:\nHISTORY\n\n" + "USER QUESTION:\nhello" + ) + + +def test_build_system_prompt_omits_empty_sections() -> None: + # Empty doc context and history drop those sections entirely. + assert _build_system_prompt("Be terse.", "", "", "hello") == ( + "You are an AI assistant.\nBe terse.\n\nUSER QUESTION:\nhello" + ) diff --git a/tests/test_vector_store_behaviour.py b/tests/test_vector_store_behaviour.py new file mode 100644 index 0000000..2e3c0a5 --- /dev/null +++ b/tests/test_vector_store_behaviour.py @@ -0,0 +1,411 @@ +"""Behaviour tests for app/services/rag/vector_store.py.""" + +from __future__ import annotations + +import json + +import numpy as np +import pytest + +from app.services.rag.vector_store import ( + INDEX_VERSION, + IndexIncompatibleError, + IndexMeta, + RetrievedChunk, + StoredChunk, + VectorStore, +) + + +def _vec(i: int, dim: int = 4) -> np.ndarray: + """A deterministic unit vector; basis vectors keep inner products exact.""" + row = np.zeros(dim, dtype="float32") + row[i % dim] = 1.0 + return row + + +def _chunk(doc_id: str, i: int = 0, text: str | None = None) -> StoredChunk: + return StoredChunk( + doc_id=doc_id, + filename=f"{doc_id}.txt", + chunk_index=i, + text=text if text is not None else f"text of {doc_id} part {i}", + ) + + +def _save_store(persist_dir, dimension: int = 4, model: str = "model-a") -> VectorStore: + """Build a store with two docs (doc_a x2 chunks, doc_b x1), save it.""" + store = VectorStore(dimension, persist_dir=persist_dir, embedding_model=model) + embeddings = np.vstack([_vec(0), _vec(1), _vec(2)]) + store.add(embeddings, [_chunk("doc_a", 0), _chunk("doc_a", 1), _chunk("doc_b", 0)]) + store.save() + return store + + +def _read_meta(persist_dir) -> dict: + return json.loads((persist_dir / "meta.json").read_text(encoding="utf-8")) + + +def _write_json(path, payload) -> None: + path.write_text(json.dumps(payload), encoding="utf-8") + + +class _FakeIndex: + """Test double for faiss.Index that returns one negative (invalid) slot.""" + + ntotal = 2 + + def search(self, vector, k): + return np.array([[0.9, -1.0]], dtype="float32"), np.array([[0, -1]]) + + +def _quarantined_names(persist_dir) -> list[str]: + q = persist_dir / "quarantined" + return sorted(p.name for p in q.iterdir()) if q.is_dir() else [] + + +# ---------- IndexMeta --------------------------------------------------------- + + +class TestIndexMeta: + def test_to_dict_round_trip(self): + meta = IndexMeta(embedding_model="m", dimension=768, vector_count=12) + restored = IndexMeta.from_dict(meta.to_dict()) + assert restored == meta + + def test_from_dict_defaults_and_casts(self): + raw = {"embedding_model": 42, "dimension": "768", "vector_count": "3"} + meta = IndexMeta.from_dict(raw) + assert meta.version == 0 # missing key -> 0, not INDEX_VERSION + assert meta.embedding_model == "42" + assert meta.dimension == 768 + assert meta.vector_count == 3 + assert meta.updated_at == 0.0 + + def test_from_dict_casts_every_field(self): + raw = { + "version": str(INDEX_VERSION), + "embedding_model": "m", + "dimension": "8", + "vector_count": "2", + "updated_at": "1761290435.5", + } + meta = IndexMeta.from_dict(raw) + assert (meta.version, meta.embedding_model, meta.dimension, meta.vector_count) == ( + INDEX_VERSION, "m", 8, 2, + ) + assert meta.updated_at == pytest.approx(1761290435.5) + + +# ---------- add / search ------------------------------------------------------ + + +class TestAddAndSearch: + def test_empty_store(self): + store = VectorStore(4) + assert store.size == 0 + assert store.indexed_doc_ids == set() + assert store.search(_vec(0)) == [] + + def test_add_empty_is_noop(self, tmp_path): + persist = tmp_path / "rag" + store = VectorStore(4, persist_dir=persist) + store.add(np.zeros((0, 4), dtype="float32"), []) + assert store.size == 0 + store.save() # never dirtied -> nothing written + assert not (persist / "meta.json").exists() + + def test_add_count_mismatch_raises(self): + store = VectorStore(4) + with pytest.raises(ValueError, match="Embedding count must match chunk count"): + store.add(np.vstack([_vec(0), _vec(1)]), [_chunk("doc_a")]) + + def test_add_dimension_mismatch_raises(self): + store = VectorStore(4) + bad = np.zeros((1, 8), dtype="float32") + with pytest.raises(ValueError, match=r"Expected dimension 4, got 8"): + store.add(bad, [_chunk("doc_a")]) + + def test_add_grows_store_and_doc_ids(self): + store = VectorStore(4) + store.add(np.vstack([_vec(0), _vec(1)]), [_chunk("doc_a"), _chunk("doc_b")]) + assert store.size == 2 + assert store.indexed_doc_ids == {"doc_a", "doc_b"} + + def test_search_ranks_by_inner_product(self): + store = VectorStore(4) + store.add(np.vstack([_vec(0), _vec(1)]), [_chunk("doc_a"), _chunk("doc_b")]) + results = store.search(_vec(0), top_k=2) + assert [r.doc_id for r in results] == ["doc_a", "doc_b"] + assert all(isinstance(r, RetrievedChunk) for r in results) + assert results[0].score == pytest.approx(1.0) + assert results[1].score == pytest.approx(0.0) + assert (results[0].filename, results[0].chunk_index, results[0].text) == ( + "doc_a.txt", 0, "text of doc_a part 0", + ) + + def test_search_clamps_top_k_to_size(self): + store = VectorStore(4) + store.add(np.vstack([_vec(0), _vec(1)]), [_chunk("doc_a"), _chunk("doc_b")]) + assert len(store.search(_vec(0), top_k=50)) == 2 + + def test_search_skips_negative_indices(self, monkeypatch): + store = VectorStore(4) + store.add(np.vstack([_vec(0), _vec(1)]), [_chunk("doc_a"), _chunk("doc_b")]) + # FAISS reports an invalid slot as index -1; search() must skip it. + monkeypatch.setattr(store, "_index", _FakeIndex()) + + results = store.search(_vec(0), top_k=2) + + assert [r.doc_id for r in results] == ["doc_a"] + assert results[0].score == pytest.approx(0.9) + + +# ---------- persistence ------------------------------------------------------- + + +class TestPersistence: + def test_save_without_persist_dir_is_noop(self): + store = VectorStore(4) + store.add(np.vstack([_vec(0)]), [_chunk("doc_a")]) + store.save() # must not raise + + def test_save_when_clean_writes_nothing(self, tmp_path): + persist = tmp_path / "rag" + VectorStore(4, persist_dir=persist).save() + assert list(persist.iterdir()) == [] if persist.exists() else True + + def test_save_writes_all_three_files(self, tmp_path): + persist = tmp_path / "rag" + _save_store(persist) + for name in ("index.faiss", "chunks.json", "meta.json"): + assert (persist / name).is_file(), name + meta = _read_meta(persist) + assert meta["version"] == INDEX_VERSION + assert meta["embedding_model"] == "model-a" + assert meta["dimension"] == 4 + assert meta["vector_count"] == 3 + chunks = json.loads((persist / "chunks.json").read_text(encoding="utf-8")) + assert len(chunks) == 3 + assert chunks[0] == { + "doc_id": "doc_a", + "filename": "doc_a.txt", + "chunk_index": 0, + "text": "text of doc_a part 0", + "content_hash": "", + } + + def test_restart_restores_state(self, tmp_path): + persist = tmp_path / "rag" + first = _save_store(persist) + before = first.search(_vec(1), top_k=3) + + second = VectorStore(4, persist_dir=persist, embedding_model="model-a") + assert second.size == 3 + assert second.indexed_doc_ids == {"doc_a", "doc_b"} + after = second.search(_vec(1), top_k=3) + assert [r.doc_id for r in after] == [r.doc_id for r in before] + assert [r.score for r in after] == pytest.approx([r.score for r in before]) + + def test_load_missing_meta_starts_fresh(self, tmp_path): + persist = tmp_path / "rag" + persist.mkdir() + store = VectorStore(4, persist_dir=persist) + assert store.size == 0 + + def test_load_non_dict_meta_starts_fresh(self, tmp_path): + persist = tmp_path / "rag" + persist.mkdir() + _write_json(persist / "meta.json", [1, 2, 3]) + store = VectorStore(4, persist_dir=persist) + assert store.size == 0 + + +# ---------- load failure: quarantine ------------------------------------------ + + +class TestLoadQuarantine: + def test_version_mismatch_quarantines(self, tmp_path): + persist = tmp_path / "rag" + _save_store(persist) + meta = _read_meta(persist) + meta["version"] = 999 + _write_json(persist / "meta.json", meta) + + store = VectorStore(4, persist_dir=persist, embedding_model="model-a") + assert store.size == 0 + for name in ("index.faiss", "chunks.json", "meta.json"): + assert not (persist / name).exists(), name + assert len(_quarantined_names(persist)) == 3 + + def test_embedding_model_mismatch_raises(self, tmp_path): + persist = tmp_path / "rag" + _save_store(persist) + with pytest.raises(IndexIncompatibleError) as excinfo: + VectorStore(4, persist_dir=persist, embedding_model="model-b") + message = str(excinfo.value) + assert "model-a" in message and "model-b" in message + # Incompatibility is reported, not quarantined: files stay put. + assert (persist / "meta.json").is_file() + + def test_dimension_mismatch_in_meta_raises(self, tmp_path): + persist = tmp_path / "rag" + _save_store(persist) + meta = _read_meta(persist) + meta["dimension"] = 8 + _write_json(persist / "meta.json", meta) + + with pytest.raises(IndexIncompatibleError, match=r"dimension 8"): + VectorStore(4, persist_dir=persist, embedding_model="model-a") + + def test_missing_chunks_file_quarantines(self, tmp_path): + persist = tmp_path / "rag" + _save_store(persist) + (persist / "chunks.json").unlink() + + store = VectorStore(4, persist_dir=persist, embedding_model="model-a") + assert store.size == 0 + assert len(_quarantined_names(persist)) >= 1 + + def test_chunk_count_mismatch_quarantines(self, tmp_path): + persist = tmp_path / "rag" + _save_store(persist) + chunks = json.loads((persist / "chunks.json").read_text(encoding="utf-8")) + _write_json(persist / "chunks.json", chunks[:1]) # meta still says 3 + + store = VectorStore(4, persist_dir=persist, embedding_model="model-a") + assert store.size == 0 + assert len(_quarantined_names(persist)) == 3 + + def test_corrupt_index_file_quarantines(self, tmp_path): + persist = tmp_path / "rag" + _save_store(persist) + (persist / "index.faiss").write_bytes(b"this is not a faiss index") + + store = VectorStore(4, persist_dir=persist, embedding_model="model-a") + assert store.size == 0 + assert len(_quarantined_names(persist)) == 3 + + def test_index_ntotal_mismatch_quarantines(self, tmp_path): + persist = tmp_path / "rag" + _save_store(persist) + meta = _read_meta(persist) + meta["vector_count"] = 5 + _write_json(persist / "meta.json", meta) + chunks = json.loads((persist / "chunks.json").read_text(encoding="utf-8")) + while len(chunks) < 5: + chunks.append({"doc_id": f"pad{len(chunks)}"}) + _write_json(persist / "chunks.json", chunks) + + store = VectorStore(4, persist_dir=persist, embedding_model="model-a") + assert store.size == 0 + assert len(_quarantined_names(persist)) == 3 + + def test_index_dimension_mismatch_quarantines(self, tmp_path): + persist = tmp_path / "rag" + _save_store(persist) # real index is dim 4 + meta = _read_meta(persist) + meta["dimension"] = 8 # lie so the meta check passes... + _write_json(persist / "meta.json", meta) + + store = VectorStore(8, persist_dir=persist, embedding_model="model-a") + assert store.size == 0 + assert len(_quarantined_names(persist)) == 3 + + def test_incomplete_chunk_records_quarantines(self, tmp_path): + persist = tmp_path / "rag" + _save_store(persist) + chunks = json.loads((persist / "chunks.json").read_text(encoding="utf-8")) + chunks[1] = "not a dict" # same length, but one record is unusable + _write_json(persist / "chunks.json", chunks) + + store = VectorStore(4, persist_dir=persist, embedding_model="model-a") + assert store.size == 0 + assert len(_quarantined_names(persist)) == 3 + + def test_quarantine_survives_move_failure(self, tmp_path, monkeypatch): + persist = tmp_path / "rag" + _save_store(persist) + meta = _read_meta(persist) + meta["version"] = 999 + _write_json(persist / "meta.json", meta) + + def boom(src, dst): + raise OSError("disk on fire") + + monkeypatch.setattr("app.services.rag.vector_store.shutil.move", boom) + + store = VectorStore(4, persist_dir=persist, embedding_model="model-a") + + assert store.size == 0 + # The move failed, so the originals must still be where they were. + for name in ("index.faiss", "chunks.json", "meta.json"): + assert (persist / name).is_file(), name + + def test_chunk_record_defaults_on_load(self, tmp_path): + persist = tmp_path / "rag" + _save_store(persist) + # Keep 3 records (matching vector_count) but strip the optional fields + # from one: it must load with default filename/text/chunk_index. + chunks = json.loads((persist / "chunks.json").read_text(encoding="utf-8")) + chunks[1] = {"doc_id": "doc_a"} + _write_json(persist / "chunks.json", chunks) + + store = VectorStore(4, persist_dir=persist, embedding_model="model-a") + assert store.size == 3 + top = store.search(_vec(1), top_k=1)[0] + assert (top.doc_id, top.filename, top.chunk_index, top.text) == ("doc_a", "", 0, "") + + +# ---------- remove / clear ---------------------------------------------------- + + +class TestRemoveAndClear: + def test_remove_by_doc_id_removes_all_chunks_for_doc(self): + store = VectorStore(4) + store.add(np.vstack([_vec(0), _vec(1), _vec(2)]), + [_chunk("doc_a", 0), _chunk("doc_a", 1), _chunk("doc_b")]) + removed = store.remove_by_doc_id("doc_a") + assert removed == 2 + assert store.size == 1 + results = store.search(_vec(2), top_k=5) + assert [r.doc_id for r in results] == ["doc_b"] + + def test_remove_unknown_doc_is_noop(self): + store = VectorStore(4) + store.add(np.vstack([_vec(0)]), [_chunk("doc_a")]) + assert store.remove_by_doc_id("ghost") == 0 + assert store.size == 1 + + @pytest.mark.xfail( + strict=True, + reason="bug: _load() drops embeddings but remove_by_doc_id zips them with strict=True", + ) + def test_remove_after_restart(self, tmp_path): + persist = tmp_path / "rag" + _save_store(persist) + reloaded = VectorStore(4, persist_dir=persist, embedding_model="model-a") + assert reloaded.size == 3 + removed = reloaded.remove_by_doc_id("doc_a") + assert removed == 2 + + def test_clear_empties_in_memory_store(self): + store = VectorStore(4) + store.add(np.vstack([_vec(0), _vec(1)]), [_chunk("doc_a"), _chunk("doc_b")]) + store.clear() + assert store.size == 0 + assert store.indexed_doc_ids == set() + store.add(np.vstack([_vec(2)]), [_chunk("doc_c")]) + assert store.size == 1 + + def test_clear_deletes_persisted_files(self, tmp_path): + persist = tmp_path / "rag" + store = _save_store(persist) + store.clear() + for name in ("index.faiss", "chunks.json", "meta.json"): + assert not (persist / name).exists(), name + # The store is usable again and re-persists cleanly. + store.add(np.vstack([_vec(0)]), [_chunk("doc_c")]) + store.save() + meta = _read_meta(persist) + assert meta["vector_count"] == 1