Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
a7fd2e4
test(clients): cover ollama_client.py (34% -> 100%)
sklsp Oct 23, 2026
e5b2e57
test(services): cover llm_service.py (34% -> 100%)
sklsp Oct 23, 2026
30f6fdf
test(clients): cover comfyui_client.py (46% -> 100%)
sklsp Oct 23, 2026
f3dfbe5
test(rag): cover ingestion.py (56% -> 100%)
sklsp Oct 23, 2026
fc935b2
test(services): cover document_service.py (59% -> 100%)
sklsp Oct 23, 2026
086941a
test(services): cover prompt_service.py (60% -> 100%)
sklsp Oct 23, 2026
d8b0f2a
test(api): cover lora_routes.py (62% -> 98%)
sklsp Oct 23, 2026
6f4be50
test(services): cover hardware.py (65% -> 100%)
sklsp Oct 23, 2026
0fe3a4d
test(services): cover chunking.py (66% -> 98%)
sklsp Oct 23, 2026
fd91a5d
test(api): cover routes.py (67% -> 100%)
sklsp Oct 23, 2026
8483e32
test(api): cover comfyui_routes (75% -> 100%)
sklsp Oct 23, 2026
cfd1f99
test(services): cover lora_training_service; fix Windows JSON concurr…
sklsp Oct 23, 2026
74793f0
test(services): cover dashboard.py (80% -> 100%)
sklsp Oct 23, 2026
7bd1e5f
test(core): cover jobs.py (83% -> 99%)
sklsp Oct 23, 2026
e26b142
test(core): cover persistence.py (84% -> 100%)
sklsp Oct 23, 2026
55d43ef
test(services): cover dataset_validation.py (87% -> 100%)
sklsp Oct 23, 2026
dd61204
test(services): cover vector_store.py (88% -> 100%)
sklsp Oct 23, 2026
b3be7a9
test(services): cover embeddings.py (89% -> 100%)
sklsp Oct 23, 2026
b157428
ci: fail the build below 95% coverage
sklsp Oct 24, 2026
64b38fc
style(tests): fix ruff lint in new coverage tests
sklsp Oct 24, 2026
c9d09ad
test: fix mypy errors in new coverage tests
sklsp Oct 24, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
49 changes: 41 additions & 8 deletions app/core/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import os
import re
import tempfile
import time
from pathlib import Path

IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg"}
Expand Down Expand Up @@ -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(
Expand All @@ -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
26 changes: 20 additions & 6 deletions app/services/lora_dataset_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 ----------

Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions app/services/lora_training_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
41 changes: 28 additions & 13 deletions app/services/run_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from __future__ import annotations

import logging
import threading
import time
import uuid
from dataclasses import asdict, dataclass, field
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand Down
12 changes: 7 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
168 changes: 168 additions & 0 deletions tests/test_chunking_behaviour.py
Original file line number Diff line number Diff line change
@@ -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 ".<space>" 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"]
Loading
Loading