Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
9 changes: 8 additions & 1 deletion CHANGELOG.MD
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
# Changelog

## Unreleased
- Fix: removing or adding a document after a restart no longer fails; the embeddings are rebuilt from the saved
FAISS index

## v1.1.0
- Retrieval evaluation: 48 questions, hit@k and MRR, a hashing baseline and MiniLM (`python -m evals.cli`)
- Optional hybrid retrieval: BM25 plus reciprocal rank fusion behind `RAG_HYBRID`
- CI: ruff, mypy, coverage reporting (TOTAL 81%), retrieval regression gate, Docker build
- CI: ruff, mypy, coverage with a 95% floor, retrieval regression gate, Docker build
- Dockerfile and docker-compose.yml (CPU-only image)
- Test suite runs in about 89 seconds instead of 323 (network probes fail fast in tests)
- docs/ARCHITECTURE.md, docs/DESIGN.md and docs/EVAL.md
- ComfyUI image generation from the chat, with workflow maps in workflows/
- LoRA Studio: build and caption a LoRA training dataset
- 864 tests, 97% coverage

## v1.0.0
- Initial release of AI Document Agent
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ or process adapter. Nothing in the document pipeline imports ComfyUI code.

## Engineering

- **Tested:** the suite runs without Ollama or ComfyUI (864 tests, 97% line coverage). CI runs lint (ruff), a type check (mypy), the tests with a 95% coverage floor, a retrieval regression gate and a Docker build.
- **Tested:** the suite runs without Ollama or ComfyUI (878 tests, 96% line coverage). CI runs lint (ruff), a type check (mypy), the tests with a 95% coverage floor, a retrieval regression gate and a Docker build.
- **Measured:** retrieval is scored on 48 questions: MiniLM hit@4 1.0000, MRR 0.9757. See [docs/EVAL.md](docs/EVAL.md).
- **Documented:** [architecture](docs/ARCHITECTURE.md) and [design decisions and trade-offs](docs/DESIGN.md).

Expand Down Expand Up @@ -467,7 +467,7 @@ Apollo/
│ ├── smoke_preflight.py # Live training-preflight demo
│ └── smoke_rag_persistence.py # Restart-survival verification for the index
├── workflows/ # ComfyUI workflows + node-input mappings
├── tests/ # Test suite (864 tests) + legacy debug scripts
├── tests/ # Test suite (878 tests) + legacy debug scripts
├── data/ # Documents, sessions, jobs, LoRA projects, generated images, rag index
├── images/ # README screenshots
├── launcher.py # One-command startup (API + tunnel)
Expand Down Expand Up @@ -641,7 +641,7 @@ Local-first does not mean unguarded:
- Documents, sessions, jobs, LoRA projects, workflows and generated images all persist on disk
- Upload debug logs appear in the server console: `[UPLOAD] filename`, `extracted chars`, `rag chunks indexed`
- Utility scripts: `python scripts/verify_system.py`, `python scripts/diagnostics_ollama.py`
- Run the tests with `python -m pytest` (864 tests); stress tests: `pytest tests/test_stress.py -m slow`
- Run the tests with `python -m pytest` (878 tests); stress tests: `pytest tests/test_stress.py -m slow`
- Log prefixes: `[COMFYUI]`, `[COMFYUI JOB]`, `[LORA]`, `[LORA TRAINING]`, `[DATASET]`, `[RAG]`, `[RUN HISTORY]`
- `tests/` also contains standalone diagnostic scripts (`test_endpoints.py`,
`test_ollama_detailed.py`, …) that predate the suite. They print at import time
Expand Down
8 changes: 8 additions & 0 deletions app/services/rag/vector_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,12 @@ def _load(self) -> bool:
meta.vector_count, self.persist_dir)
return True

def _ensure_embeddings(self) -> None:
"""Rebuild the per-chunk embeddings from the FAISS index when a restored index left them empty."""
if len(self._embeddings) != len(self._chunks):
matrix = self._index.reconstruct_n(0, self._index.ntotal)
self._embeddings = [np.asarray(row, dtype=np.float32) for row in matrix]

def save(self) -> None:
"""Flush index + metadata atomically. Cheap enough to call per change."""
if self.persist_dir is None or not self._dirty:
Expand Down Expand Up @@ -270,6 +276,7 @@ def add(self, embeddings: np.ndarray, chunks: list[StoredChunk]) -> None:
f"Expected dimension {self.dimension}, got {embeddings.shape[1]}"
)

self._ensure_embeddings()
self._index.add(embeddings.astype(np.float32))
for row, chunk in zip(embeddings, chunks, strict=True):
self._embeddings.append(np.asarray(row, dtype=np.float32))
Expand Down Expand Up @@ -303,6 +310,7 @@ def search(self, query_embedding: np.ndarray, top_k: int = 4) -> list[RetrievedC

def remove_by_doc_id(self, doc_id: str) -> int:
"""Remove all chunks for a document and rebuild the index."""
self._ensure_embeddings()
remaining_chunks: list[StoredChunk] = []
remaining_embeddings: list[np.ndarray] = []
removed = 0
Expand Down
4 changes: 0 additions & 4 deletions tests/test_vector_store_behaviour.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,10 +377,6 @@ def test_remove_unknown_doc_is_noop(self):
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)
Expand Down
146 changes: 146 additions & 0 deletions tests/test_vector_store_restart.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
"""Restart behaviour for app/services/rag/vector_store.py: embedding rebuild."""

from __future__ import annotations

import numpy as np

from app.services.rag.vector_store import VectorStore
from tests.test_vector_store_behaviour import _chunk, _save_store, _vec


class TestEnsureEmbeddings:
def test_restarted_store_starts_without_embeddings(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)

reloaded = VectorStore(4, persist_dir=persist, embedding_model="model-a")

assert reloaded.size == 3
assert reloaded._embeddings == []

def test_ensure_embeddings_rebuilds_one_row_per_chunk(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)
reloaded = VectorStore(4, persist_dir=persist, embedding_model="model-a")

reloaded._ensure_embeddings()

assert len(reloaded._embeddings) == 3
for i, row in enumerate(reloaded._embeddings):
assert np.allclose(row, _vec(i))

def test_ensure_embeddings_is_a_noop_when_already_built(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)
reloaded = VectorStore(4, persist_dir=persist, embedding_model="model-a")
reloaded._ensure_embeddings()
first = reloaded._embeddings

reloaded._ensure_embeddings()

assert reloaded._embeddings is first


class TestRemoveAfterRestart:
def test_remove_then_second_restart_keeps_the_survivor(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)
reloaded = VectorStore(4, persist_dir=persist, embedding_model="model-a")

removed = reloaded.remove_by_doc_id("doc_a")

assert removed == 2
assert reloaded.size == 1
results = reloaded.search(_vec(2), top_k=5)
assert [r.doc_id for r in results] == ["doc_b"]

reloaded.save()
again = VectorStore(4, persist_dir=persist, embedding_model="model-a")
assert again.size == 1


class TestAddAfterRestart:
def test_add_then_remove_keeps_chunks_and_embeddings_aligned(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)
store = VectorStore(4, persist_dir=persist, embedding_model="model-a")

store.add(np.vstack([_vec(3)]), [_chunk("doc_new", 0)])
removed = store.remove_by_doc_id("doc_a")

assert removed == 2
assert store.size == 2
results = store.search(_vec(3), top_k=5)
assert results[0].doc_id == "doc_new"
assert len(store._embeddings) == len(store._chunks)


class TestTwoRestartCycles:
def test_two_full_restart_cycles_keep_the_store_consistent(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)

s1 = VectorStore(4, persist_dir=persist, embedding_model="model-a")
assert s1.remove_by_doc_id("doc_a") == 2
s1.save()

s2 = VectorStore(4, persist_dir=persist, embedding_model="model-a")
s2.add(np.vstack([_vec(3)]), [_chunk("doc_c", 0)])
assert s2.remove_by_doc_id("doc_b") == 1
s2.save()

s3 = VectorStore(4, persist_dir=persist, embedding_model="model-a")
assert s3.size == 1
assert s3.indexed_doc_ids == {"doc_c"}
results = s3.search(_vec(3), top_k=5)
assert [r.doc_id for r in results] == ["doc_c"]


class TestEveryPublicMethodAfterRestart:
def test_size(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)
store = VectorStore(4, persist_dir=persist, embedding_model="model-a")
assert store.size == 3

def test_indexed_doc_ids(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)
store = VectorStore(4, persist_dir=persist, embedding_model="model-a")
assert store.indexed_doc_ids == {"doc_a", "doc_b"}

def test_search(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)
store = VectorStore(4, persist_dir=persist, embedding_model="model-a")
results = store.search(_vec(0), top_k=1)
assert [r.doc_id for r in results] == ["doc_a"]

def test_add(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)
store = VectorStore(4, persist_dir=persist, embedding_model="model-a")
store.add(np.vstack([_vec(3)]), [_chunk("doc_c", 0)])
assert store.size == 4

def test_remove_by_doc_id(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)
store = VectorStore(4, persist_dir=persist, embedding_model="model-a")
assert store.remove_by_doc_id("doc_a") == 2

def test_clear(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)
store = VectorStore(4, persist_dir=persist, embedding_model="model-a")
store.clear()
assert store.size == 0

def test_save(self, tmp_path):
persist = tmp_path / "rag"
_save_store(persist)
store = VectorStore(4, persist_dir=persist, embedding_model="model-a")
store.add(np.vstack([_vec(3)]), [_chunk("doc_c", 0)])
store.save()
reloaded = VectorStore(4, persist_dir=persist, embedding_model="model-a")
assert reloaded.size == 4
Loading