DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(knowledge): preserve source-relative directory structure when syncing linked folders (#899)
Amir Fathi3c20bb9251c5
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 4a4b867b3..24c259a6a 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -905,6 +905,7 @@ async def run_upload_processing_task(task_id: str,rag_provider: str = None,folder_id: str = None,+ folder_root: str = None,):"""Background task for processing uploaded files.@@ -914,6 +915,9 @@ async def run_upload_processing_task(uploaded_file_paths: List of file paths to processrag_provider: RAG provider already matched against the KB bindingfolder_id: Optional folder ID for sync state update+ folder_root: Linked folder's own root path, when these files came+ from a folder sync. Preserves each file's path relative to it+ instead of flattening to the bare filename."""task_manager = TaskIDManager.get_instance()task_stream_manager = get_task_stream_manager()@@ -945,7 +949,10 @@ async def run_upload_processing_task(# *sync* callables to its threadpool — so doing this inline stalled# every other request for the length of the batch (#777).staged_files = await asyncio.to_thread(- adder.add_documents, uploaded_file_paths, allow_duplicates=False+ adder.add_documents,+ uploaded_file_paths,+ allow_duplicates=False,+ source_root=folder_root,)_task_log(task_id, f"Staged {len(staged_files)} new file(s)")@@ -3172,6 +3179,7 @@ async def sync_folder(kb_name: str, folder_id: str, background_tasks: Backgroundtask_id=task_id,rag_provider=kb_provider,folder_id=folder_id, # Pass folder_id to update state on success+ folder_root=folder_path, # Preserve each file's path relative to this root)return {diff --git a/deeptutor/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.pyindex abb8e2eb8..498181b40 100644--- a/deeptutor/knowledge/add_documents.py+++ b/deeptutor/knowledge/add_documents.py@@ -213,12 +213,26 @@ class DocumentAdder:return {}return {}- def add_documents(self, source_files: List[str], allow_duplicates: bool = False) -> List[Path]:- """Validate and stage files into raw/ before indexing."""+ def add_documents(+ self,+ source_files: List[str],+ allow_duplicates: bool = False,+ source_root: str | Path | None = None,+ ) -> List[Path]:+ """Validate and stage files into raw/ before indexing.++ ``source_root``, when given, is the root a caller is syncing from+ (e.g. a linked folder). Any source file found under it is staged at+ the same path *relative to that root*, instead of being flattened to+ its bare filename: without this, every externally-sourced subfolder+ collapses into raw/'s top level and same-named files in different+ subfolders collide.+ """logger.info(f"Validating documents for '{self.kb_name}'...")ingested_hashes = self.get_ingested_hashes()files_to_process: list[Path] = []+ resolved_source_root = Path(source_root).resolve() if source_root else Nonefor source in source_files:source_path = Path(source)@@ -231,14 +245,20 @@ class DocumentAdder:logger.info(f"Skipped (content already indexed): {source_path.name}")continue+ resolved_source = source_path.resolve()+# Files already saved under raw/ (e.g. by the upload route, possibly# inside a folder) are indexed in place — never flattened to the# basename — so the uploaded folder structure is preserved verbatim.- if source_path.resolve().is_relative_to(self.raw_dir.resolve()):+ if resolved_source.is_relative_to(self.raw_dir.resolve()):files_to_process.append(source_path)continue- dest_path = self.raw_dir / source_path.name+ if resolved_source_root and resolved_source.is_relative_to(resolved_source_root):+ dest_path = self.raw_dir / resolved_source.relative_to(resolved_source_root)+ else:+ dest_path = self.raw_dir / source_path.name+if dest_path.exists():dest_hash = self._get_file_hash(dest_path)if dest_hash == current_hash:@@ -249,6 +269,7 @@ class DocumentAdder:logger.info(f"Skipped (filename collision): {source_path.name}")continue+ dest_path.parent.mkdir(parents=True, exist_ok=True)shutil.copy2(source_path, dest_path)logger.info(f"Staged to raw: {source_path.name}")files_to_process.append(dest_path)diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.pyindex a36aa5af0..29b1ee4a6 100644--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@ -849,6 +849,64 @@ def test_upload_task_marks_provider_failures_as_error(monkeypatch, tmp_path: Patassert entry["progress"]["indexed_count"] == 0+def test_upload_task_with_folder_root_preserves_subfolder_structure(+ monkeypatch, tmp_path: Path+) -> None:+ """A linked-folder sync (folder_root set) stages a nested file under the+ same relative subpath in raw/, instead of flattening it to its basename+ and colliding with a same-named file from another subfolder (#866)."""+ base_dir = tmp_path / "knowledge_bases"+ kb_dir = base_dir / "kb"+ raw_dir = kb_dir / "raw"+ raw_dir.mkdir(parents=True)+ _write_ready_llamaindex_version(kb_dir)+ (base_dir / "kb_config.json").write_text(+ json.dumps(+ {+ "knowledge_bases": {+ "kb": {+ "path": "kb",+ "rag_provider": "llamaindex",+ "status": "ready",+ }+ }+ }+ ),+ encoding="utf-8",+ )++ linked_folder = tmp_path / "linked"+ (linked_folder / "sub").mkdir(parents=True)+ doc = linked_folder / "sub" / "note.md"+ doc.write_text("hello", encoding="utf-8")++ class _SucceedingRagService:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ async def add_documents(self, *_args, **_kwargs) -> bool:+ return True++ monkeypatch.setattr(+ "deeptutor.knowledge.add_documents.RAGService",+ _SucceedingRagService,+ )++ asyncio.run(+ knowledge_router_module.run_upload_processing_task(+ kb_name="kb",+ base_dir=str(base_dir),+ uploaded_file_paths=[str(doc)],+ task_id="folder-sync-test",+ rag_provider="llamaindex",+ folder_root=str(linked_folder),+ )+ )++ assert (raw_dir / "sub" / "note.md").read_text(encoding="utf-8") == "hello"+ assert not (raw_dir / "note.md").exists()++def test_list_files_accepts_default_alias(monkeypatch, tmp_path: Path) -> None:manager = _FakeKBManager(tmp_path / "knowledge_bases")manager.config["knowledge_bases"]["actual-kb"] = {diff --git a/tests/knowledge/test_add_documents_linked_folder.py b/tests/knowledge/test_add_documents_linked_folder.pynew file mode 100644index 000000000..8eccde881--- /dev/null+++ b/tests/knowledge/test_add_documents_linked_folder.py@@ -0,0 +1,106 @@+"""``DocumentAdder.add_documents(source_root=...)`` staging for linked-folder sync.++Without ``source_root``, every externally-sourced file is staged to+``raw/<basename>`` regardless of where it lived, so syncing a linked folder+with subdirectories collapses them all into raw/'s top level (#866) and two+subfolders with a same-named file collide. These tests pin the fix: a file+under ``source_root`` stages at the same path relative to it.+"""++from __future__ import annotations++import json+from pathlib import Path++from deeptutor.knowledge.add_documents import DocumentAdder+++def _ready_llamaindex_kb(kb_dir: Path) -> None:+ (kb_dir / "raw").mkdir(parents=True)+ version_dir = kb_dir / "version-1"+ version_dir.mkdir()+ (version_dir / "docstore.json").write_text("{}", encoding="utf-8")+ (version_dir / "index_store.json").write_text("{}", encoding="utf-8")+ (version_dir / "meta.json").write_text(+ json.dumps({"provider": "llamaindex", "signature": "llamaindex", "version": "version-1"}),+ encoding="utf-8",+ )+++def test_add_documents_preserves_subfolder_structure_under_source_root(tmp_path: Path) -> None:+ kb_dir = tmp_path / "kb"+ _ready_llamaindex_kb(kb_dir)++ linked_folder = tmp_path / "linked"+ sub = linked_folder / "sub"+ sub.mkdir(parents=True)+ doc = sub / "note.md"+ doc.write_text("hello", encoding="utf-8")++ adder = DocumentAdder(kb_name="kb", base_dir=str(tmp_path))+ staged = adder.add_documents([str(doc)], source_root=str(linked_folder))++ assert staged == [kb_dir / "raw" / "sub" / "note.md"]+ assert (kb_dir / "raw" / "sub" / "note.md").read_text(encoding="utf-8") == "hello"+ assert not (kb_dir / "raw" / "note.md").exists()+++def test_add_documents_same_name_in_different_subfolders_does_not_collide(+ tmp_path: Path,+) -> None:+ kb_dir = tmp_path / "kb"+ _ready_llamaindex_kb(kb_dir)++ linked_folder = tmp_path / "linked"+ (linked_folder / "a").mkdir(parents=True)+ (linked_folder / "b").mkdir(parents=True)+ doc_a = linked_folder / "a" / "note.md"+ doc_b = linked_folder / "b" / "note.md"+ doc_a.write_text("from a", encoding="utf-8")+ doc_b.write_text("from b", encoding="utf-8")++ adder = DocumentAdder(kb_name="kb", base_dir=str(tmp_path))+ staged = adder.add_documents([str(doc_a), str(doc_b)], source_root=str(linked_folder))++ assert set(staged) == {+ kb_dir / "raw" / "a" / "note.md",+ kb_dir / "raw" / "b" / "note.md",+ }+ assert (kb_dir / "raw" / "a" / "note.md").read_text(encoding="utf-8") == "from a"+ assert (kb_dir / "raw" / "b" / "note.md").read_text(encoding="utf-8") == "from b"+++def test_add_documents_without_source_root_still_flattens_to_basename(tmp_path: Path) -> None:+ """Direct (non-folder-sync) uploads are unaffected: no source_root, same as before."""+ kb_dir = tmp_path / "kb"+ _ready_llamaindex_kb(kb_dir)++ external = tmp_path / "somewhere-else" / "deep" / "path"+ external.mkdir(parents=True)+ doc = external / "note.md"+ doc.write_text("hello", encoding="utf-8")++ adder = DocumentAdder(kb_name="kb", base_dir=str(tmp_path))+ staged = adder.add_documents([str(doc)])++ assert staged == [kb_dir / "raw" / "note.md"]+++def test_add_documents_source_outside_source_root_falls_back_to_basename(+ tmp_path: Path,+) -> None:+ """A file that is not actually under source_root still flattens, not KeyErrors."""+ kb_dir = tmp_path / "kb"+ _ready_llamaindex_kb(kb_dir)++ linked_folder = tmp_path / "linked"+ linked_folder.mkdir()+ unrelated = tmp_path / "unrelated"+ unrelated.mkdir()+ doc = unrelated / "note.md"+ doc.write_text("hello", encoding="utf-8")++ adder = DocumentAdder(kb_name="kb", base_dir=str(tmp_path))+ staged = adder.add_documents([str(doc)], source_root=str(linked_folder))++ assert staged == [kb_dir / "raw" / "note.md"]