diff --git a/CHANGELOG.MD b/CHANGELOG.MD index 50a6603..62fc637 100644 --- a/CHANGELOG.MD +++ b/CHANGELOG.MD @@ -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 diff --git a/README.md b/README.md index 9ab63b7..3494794 100644 --- a/README.md +++ b/README.md @@ -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). @@ -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) @@ -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 diff --git a/app/services/rag/vector_store.py b/app/services/rag/vector_store.py index 18c57a6..e694ad3 100644 --- a/app/services/rag/vector_store.py +++ b/app/services/rag/vector_store.py @@ -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: @@ -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)) @@ -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 diff --git a/tests/test_vector_store_behaviour.py b/tests/test_vector_store_behaviour.py index 2e3c0a5..402122c 100644 --- a/tests/test_vector_store_behaviour.py +++ b/tests/test_vector_store_behaviour.py @@ -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) diff --git a/tests/test_vector_store_restart.py b/tests/test_vector_store_restart.py new file mode 100644 index 0000000..3eebe31 --- /dev/null +++ b/tests/test_vector_store_restart.py @@ -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