DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: pin LightRAG indexing models per knowledge base (#1171)
NoxsMediaecc150d960eb
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 560134722..b3e383242 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -43,7 +43,12 @@ from deeptutor.knowledge.manager import KnowledgeBaseManagerfrom deeptutor.knowledge.naming import validate_knowledge_base_namefrom deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTrackerfrom deeptutor.logging import PROCESS_LOG_PRIVATE_ATTR-from deeptutor.multi_user.context import get_current_user+from deeptutor.multi_user.context import (+ get_current_user,+ get_current_user_or_none,+ reset_current_user,+ set_current_user,+)from deeptutor.multi_user.knowledge_access import (assert_writable,current_kb_base_dir,@@ -651,6 +656,35 @@ def _validate_registered_provider(raw_provider: str | None) -> str:return normalize_provider_name(raw_provider)+def _freeze_indexing_llm_form(raw: str):+ """Parse and resolve the optional LightRAG selection exactly once."""+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (+ IndexingPolicyError,+ freeze_snapshot,+ )++ try:+ selection = json.loads(raw)+ if not isinstance(selection, dict) or not selection:+ raise ValueError("indexing_llm must be a non-empty JSON object.")+ return selection, freeze_snapshot(selection)+ except (json.JSONDecodeError, ValueError, PermissionError, IndexingPolicyError) as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+++def _freeze_default_indexing_llm():+ """Freeze the released LightRAG model default for one create or rebuild."""+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (+ IndexingPolicyError,+ freeze_default_snapshot,+ )++ try:+ return freeze_default_snapshot()+ except (ValueError, PermissionError, IndexingPolicyError) as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc++def _assert_provider_ready(provider: str) -> None:"""Block creating/using a KB whose engine isn't ready.@@ -846,6 +880,14 @@ def _matching_index_is_valid(kb_name: str, matching_version: dict | None) -> booasync def run_initialization_task(initializer: KnowledgeBaseInitializer, task_id: str):"""Background task for knowledge base initialization"""+ owner = getattr(initializer, "owner", None)+ if owner is not None and get_current_user_or_none() != owner:+ token = set_current_user(owner)+ try:+ return await run_initialization_task(initializer, task_id)+ finally:+ reset_current_user(token)+task_manager = TaskIDManager.get_instance()task_stream_manager = get_task_stream_manager()task_stream_manager.ensure_task(task_id)@@ -908,6 +950,19 @@ async def run_initialization_task(initializer: KnowledgeBaseInitializer, task_iderror_msg = str(e)trace = _tb.format_exc()+ if getattr(initializer, "index_published", False):+ _task_log(+ task_id,+ "LightRAG index was published; final status bookkeeping will be reconciled.",+ level="warning",+ )+ _server_task_trace(task_id, trace)+ task_manager.update_task_status(task_id, "completed")+ task_stream_manager.emit_complete(+ task_id,+ f"Knowledge base '{initializer.kb_name}' index published",+ )+ returnfailure_metadata = _exception_failure_metadata(e)_task_log(task_id, f"Initialization failed: {error_msg}", level="error")@@ -949,6 +1004,7 @@ async def run_upload_processing_task(rag_provider: str = None,folder_id: str = None,folder_root: str = None,+ owner=None,):"""Background task for processing uploaded files.@@ -962,9 +1018,25 @@ async def run_upload_processing_task(from a folder sync. Preserves each file's path relative to itinstead of flattening to the bare filename."""+ if owner is not None and get_current_user_or_none() != owner:+ token = set_current_user(owner)+ try:+ return await run_upload_processing_task(+ kb_name=kb_name,+ base_dir=base_dir,+ uploaded_file_paths=uploaded_file_paths,+ task_id=task_id,+ rag_provider=rag_provider,+ folder_id=folder_id,+ folder_root=folder_root,+ )+ finally:+ reset_current_user(token)+task_manager = TaskIDManager.get_instance()task_stream_manager = get_task_stream_manager()task_stream_manager.ensure_task(task_id)+ index_published = Falseprogress_tracker = ProgressTracker(kb_name, Path(base_dir))progress_tracker.task_id = task_id@@ -1059,6 +1131,10 @@ async def run_upload_processing_task()return+ index_published = rag_provider == LIGHTRAG_PROVIDER and bool(+ index_result.processed_count+ )+progress_tracker.update(ProgressStage.PROCESSING_DOCUMENTS,message_key="Saving metadata...",@@ -1103,6 +1179,19 @@ async def run_upload_processing_task(error_msg = f"Upload processing failed (KB '{kb_name}'): {e}"trace = _tb.format_exc()+ if index_published:+ _task_log(+ task_id,+ "LightRAG index changes were published; final upload bookkeeping "+ "will be reconciled.",+ level="warning",+ )+ _server_task_trace(task_id, trace)+ task_manager.update_task_status(task_id, "completed")+ task_stream_manager.emit_complete(+ task_id, f"LightRAG changes for '{kb_name}' published"+ )+ returnfailure_metadata = _exception_failure_metadata(e)_task_log(task_id, error_msg, level="error")_server_task_trace(task_id, trace)@@ -2822,6 +2911,7 @@ async def upload_files(uploaded_file_paths=uploaded_file_paths,task_id=task_id,rag_provider=kb_provider,+ owner=get_current_user(),)return {@@ -2848,6 +2938,7 @@ async def create_knowledge_base(pageindex_mode: str = Form(""),search_mode: str = Form(""),rel_paths: list[str] = Form(None),+ indexing_llm: str = Form(""),):"""Create a new knowledge base and initialize it with files."""try:@@ -2862,6 +2953,17 @@ async def create_knowledge_base(raise HTTPException(status_code=400, detail=f"Knowledge base '{name}' already exists")rag_provider = _validate_registered_provider(rag_provider)+ indexing_snapshot = None+ if rag_provider == LIGHTRAG_PROVIDER:+ if indexing_llm:+ _, indexing_snapshot = _freeze_indexing_llm_form(indexing_llm)+ else:+ indexing_snapshot = _freeze_default_indexing_llm()+ elif indexing_llm:+ raise HTTPException(+ status_code=400,+ detail="indexing_llm is supported only for built-in LightRAG.",+ )pageindex_mode = str(pageindex_mode or "").strip().lower()if rag_provider == PAGEINDEX_OSS_PROVIDER and pageindex_mode not in {"",@@ -2925,6 +3027,10 @@ async def create_knowledge_base(manager.config["knowledge_bases"][name]["pageindex_mode"] = pageindex_modeif search_mode:manager.config["knowledge_bases"][name]["search_mode"] = search_mode+ if indexing_snapshot is not None:+ pending_policy = indexing_snapshot.persisted_policy()+ pending_policy["policy"] = "pending_pinned"+ manager.config["knowledge_bases"][name]["pending_indexing_policy"] = pending_policymanager._save_config()progress_tracker = ProgressTracker(name, kb_base_dir)@@ -2934,6 +3040,8 @@ async def create_knowledge_base(base_dir=str(kb_base_dir),progress_tracker=progress_tracker,rag_provider=rag_provider,+ indexing_snapshot=indexing_snapshot,+ owner=get_current_user(),)initializer.create_directory_structure()@@ -3006,7 +3114,14 @@ async def create_knowledge_base(raise HTTPException(status_code=500, detail=str(e))-async def run_reindex_task(kb_name: str, base_dir: str, task_id: str, signature_hash: str) -> None:+async def run_reindex_task(+ kb_name: str,+ base_dir: str,+ task_id: str,+ signature_hash: str,+ indexing_snapshot=None,+ owner=None,+) -> None:"""Re-index a KB's raw documents against the currently-active embedding config.Each ``(profile, model, dimension, base_url)`` combination gets its own@@ -3014,9 +3129,23 @@ async def run_reindex_task(kb_name: str, base_dir: str, task_id: str, signature_untouched so switching the active embedding model back to apreviously-indexed one reuses the existing version with no extra work."""+ if owner is not None and get_current_user_or_none() != owner:+ token = set_current_user(owner)+ try:+ return await run_reindex_task(+ kb_name=kb_name,+ base_dir=base_dir,+ task_id=task_id,+ signature_hash=signature_hash,+ indexing_snapshot=indexing_snapshot,+ )+ finally:+ reset_current_user(token)+task_manager = TaskIDManager.get_instance()task_stream_manager = get_task_stream_manager()task_stream_manager.ensure_task(task_id)+ index_published = Falsewith capture_task_logs(task_id):try:@@ -3072,9 +3201,11 @@ async def run_reindex_task(kb_name: str, base_dir: str, task_id: str, signature_kb_name=kb_name,file_paths=file_paths,progress_callback=_on_progress,+ indexing_snapshot=indexing_snapshot,)if not success:raise RuntimeError(f"Re-index found no valid documents to index in '{kb_name}'.")+ index_published = signature_hash == LIGHTRAG_PROVIDERcompleted_at = datetime.now().isoformat()metadata_file = kb_dir / "metadata.json"@@ -3156,6 +3287,16 @@ async def run_reindex_task(kb_name: str, base_dir: str, task_id: str, signature_error_msg = str(e)trace = _tb.format_exc()+ if index_published:+ _task_log(+ task_id,+ "LightRAG version was published; final status bookkeeping will be reconciled.",+ level="warning",+ )+ _server_task_trace(task_id, trace)+ task_manager.update_task_status(task_id, "completed")+ task_stream_manager.emit_complete(task_id, f"Re-index of '{kb_name}' published")+ returnfailure_metadata = _exception_failure_metadata(e)_task_log(task_id, f"Re-index failed: {error_msg}", level="error")_server_task_trace(task_id, trace)@@ -3176,6 +3317,7 @@ async def run_reindex_task(kb_name: str, base_dir: str, task_id: str, signature_async def reindex_knowledge_base(kb_name: str,background_tasks: BackgroundTasks,+ indexing_llm: str = Form(""),):"""Re-index ``kb_name`` through its bound RAG provider.@@ -3192,6 +3334,17 @@ async def reindex_knowledge_base(kb_entry.get("rag_provider") or DEFAULT_PROVIDER)_assert_provider_ready(kb_provider)+ indexing_snapshot = None+ if kb_provider == LIGHTRAG_PROVIDER:+ if indexing_llm:+ _, indexing_snapshot = _freeze_indexing_llm_form(indexing_llm)+ else:+ indexing_snapshot = _freeze_default_indexing_llm()+ elif indexing_llm:+ raise HTTPException(+ status_code=400,+ detail="indexing_llm is supported only for built-in LightRAG.",+ )kb_dir = kb_base_dir / kb_namesignature_hash = kb_provider@@ -3243,6 +3396,8 @@ async def reindex_knowledge_base(base_dir=str(kb_base_dir),task_id=task_id,signature_hash=signature_hash,+ indexing_snapshot=indexing_snapshot,+ owner=get_current_user(),)return {@@ -3278,7 +3433,7 @@ async def retry_knowledge_base("Use re-index when you want to rebuild a healthy knowledge base."),)- return await reindex_knowledge_base(resolved_name, background_tasks)+ return await reindex_knowledge_base(resolved_name, background_tasks, indexing_llm="")except HTTPException:raiseexcept Exception as e:@@ -3708,6 +3863,7 @@ async def sync_folder(kb_name: str, folder_id: str, background_tasks: Backgroundrag_provider=kb_provider,folder_id=folder_id, # Pass folder_id to update state on successfolder_root=folder_path, # Preserve each file's path relative to this root+ owner=get_current_user(),)return {diff --git a/deeptutor/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.pyindex 68f6f40d6..8212af3b9 100644--- a/deeptutor/knowledge/add_documents.py+++ b/deeptutor/knowledge/add_documents.py@@ -19,10 +19,12 @@ from deeptutor.services.config import resolve_llm_runtime_configfrom deeptutor.services.file_io import atomic_write_jsonfrom deeptutor.services.rag.factory import (DEFAULT_PROVIDER,+ LIGHTRAG_PROVIDER,has_ready_provider_index,normalize_provider_name,)from deeptutor.services.rag.file_routing import FileTypeRouter+from deeptutor.services.rag.index_versioning import list_kb_versionsfrom deeptutor.services.rag.provider_binding import resolve_bound_providerfrom deeptutor.services.rag.service import RAGService@@ -188,7 +190,10 @@ class DocumentAdder:f"Knowledge base '{kb_name}' uses legacy index format and requires reindex before incremental add")- if not has_provider_index:+ allows_lightrag_bootstrap = self.rag_provider == LIGHTRAG_PROVIDER and not list_kb_versions(+ self.kb_dir+ )+ if not has_provider_index and not allows_lightrag_bootstrap:raise ValueError(f"Knowledge base not initialized ({self.rag_provider}): {kb_name}")self.api_key = api_key@@ -328,7 +333,17 @@ class DocumentAdder:# this runs inside a FastAPI BackgroundTasks entry, which is# awaited on the loop and would otherwise stall unrelated# requests once per indexed file (#777).- await asyncio.to_thread(self._record_successful_hash, doc_file)+ try:+ await asyncio.to_thread(self._record_successful_hash, doc_file)+ except Exception:+ if self.rag_provider != LIGHTRAG_PROVIDER:+ raise+ logger.warning(+ "LightRAG published '%s' before its duplicate-detection hash "+ "was recorded",+ doc_file.name,+ exc_info=True,+ )logger.info(f"Processed: {doc_file.name}")if self.progress_tracker is not None:self.progress_tracker.update(@@ -413,43 +428,53 @@ async def _bootstrap_index_from_files(f"Failed to initialize index for KB '{kb_name}' from {len(source_files)} file(s)")- # Record hashes so future syncs detect unchanged files.- metadata = _read_metadata(metadata_file)- hashes = metadata.setdefault("file_hashes", {})- for fpath_str in source_files:- fpath = Path(fpath_str)- sha = hashlib.sha256()- with open(fpath, "rb") as fh:- for block in iter(lambda: fh.read(65536), b""):- sha.update(block)- hashes[_raw_hash_key(fpath, raw_dir)] = sha.hexdigest()- metadata["rag_provider"] = rag_service._resolve_provider(kb_name)- metadata["needs_reindex"] = False- ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")- metadata["last_updated"] = ts- metadata["last_indexed_at"] = ts- metadata["last_indexed_count"] = len(source_files)- metadata["last_indexed_action"] = "create"- _write_metadata(metadata_file, metadata)-indexed = len(source_files)- manager.update_kb_status(- name=kb_name,- status="ready",- progress={- "stage": "completed",- "message": f"Initialized index with {indexed} file(s).",- "percent": 100,- "current": indexed,- "total": max(indexed, 1),- "file_name": "",- "error": None,- "timestamp": datetime.now().isoformat(),- "indexed_count": indexed,- "index_changed": True,- "index_action": "create",- },- )+ provider = rag_service._resolve_provider(kb_name)+ try:+ # Record hashes so future syncs detect unchanged files.+ metadata = _read_metadata(metadata_file)+ hashes = metadata.setdefault("file_hashes", {})+ for fpath_str in source_files:+ fpath = Path(fpath_str)+ sha = hashlib.sha256()+ with open(fpath, "rb") as fh:+ for block in iter(lambda: fh.read(65536), b""):+ sha.update(block)+ hashes[_raw_hash_key(fpath, raw_dir)] = sha.hexdigest()+ metadata["rag_provider"] = provider+ metadata["needs_reindex"] = False+ ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")+ metadata["last_updated"] = ts+ metadata["last_indexed_at"] = ts+ metadata["last_indexed_count"] = indexed+ metadata["last_indexed_action"] = "create"+ _write_metadata(metadata_file, metadata)++ manager.update_kb_status(+ name=kb_name,+ status="ready",+ progress={+ "stage": "completed",+ "message": f"Initialized index with {indexed} file(s).",+ "percent": 100,+ "current": indexed,+ "total": max(indexed, 1),+ "file_name": "",+ "error": None,+ "timestamp": datetime.now().isoformat(),+ "indexed_count": indexed,+ "index_changed": True,+ "index_action": "create",+ },+ )+ except Exception:+ if provider != LIGHTRAG_PROVIDER:+ raise+ logger.warning(+ "LightRAG bootstrap for '%s' published before bookkeeping failed",+ kb_name,+ exc_info=True,+ )logger.info("Bootstrapped index for empty KB '%s' with %d file(s)", kb_name, indexed)return indexed@@ -466,6 +491,7 @@ async def add_documents(from deeptutor.knowledge.manager import KnowledgeBaseManagermanager = KnowledgeBaseManager(base_dir=base_dir)+ published_count = 0try:manager.update_kb_status(name=kb_name,@@ -524,6 +550,8 @@ async def add_documents(f"Failed to index {result.failed_count}/{len(new_files)} file(s): "f"{result.failure_summary()}")+ if adder.rag_provider == LIGHTRAG_PROVIDER:+ published_count = result.processed_countadder.update_metadata(result.processed_count)manager.update_kb_status(@@ -545,6 +573,13 @@ async def add_documents()return result.processed_countexcept Exception as exc:+ if published_count:+ logger.warning(+ "LightRAG append for '%s' published before bookkeeping failed",+ kb_name,+ exc_info=True,+ )+ return published_countmanager.update_kb_status(name=kb_name,status="error",diff --git a/deeptutor/knowledge/initializer.py b/deeptutor/knowledge/initializer.pyindex 40feed435..33eb935b2 100644--- a/deeptutor/knowledge/initializer.py+++ b/deeptutor/knowledge/initializer.py@@ -10,7 +10,11 @@ import jsonimport loggingfrom pathlib import Pathimport shutil-from typing import Optional+from typing import TYPE_CHECKING, Optional++if TYPE_CHECKING:+ from deeptutor.multi_user.models import CurrentUser+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import IndexingLLMSnapshotfrom deeptutor.knowledge.naming import validate_knowledge_base_namefrom deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker@@ -34,6 +38,8 @@ class KnowledgeBaseInitializer:base_url: str | None = None,progress_tracker: ProgressTracker | None = None,rag_provider: str | None = None,+ indexing_snapshot: IndexingLLMSnapshot | None = None,+ owner: CurrentUser | None = None,):self.kb_name = validate_knowledge_base_name(kb_name)self.base_dir = Path(base_dir)@@ -46,6 +52,9 @@ class KnowledgeBaseInitializer:self.base_url = base_urlself.progress_tracker = progress_tracker or ProgressTracker(self.kb_name, self.base_dir)self.rag_provider = normalize_provider_name(rag_provider)+ self.indexing_snapshot = indexing_snapshot+ self.owner = owner+ self.index_published = Falsedef _register_to_config(self) -> None:"""Register KB in kb_config.json with initializing state."""@@ -205,6 +214,7 @@ class KnowledgeBaseInitializer:file_paths=file_paths,progress_callback=_on_progress,image_progress_callback=_on_image_progress,+ indexing_snapshot=self.indexing_snapshot,)if not success:self.progress_tracker.update(@@ -214,13 +224,23 @@ class KnowledgeBaseInitializer:)raise RuntimeError("RAG pipeline returned failure")- self._update_metadata_with_provider(provider)- self.progress_tracker.update(- ProgressStage.PROCESSING_DOCUMENTS,- message_key="Documents processed successfully",- current=len(doc_files),- total=len(doc_files),- )+ self.index_published = provider == "lightrag"+ try:+ self._update_metadata_with_provider(provider)+ self.progress_tracker.update(+ ProgressStage.PROCESSING_DOCUMENTS,+ message_key="Documents processed successfully",+ current=len(doc_files),+ total=len(doc_files),+ )+ except Exception:+ if not self.index_published:+ raise+ logger.warning(+ "LightRAG index for %s was published before metadata bookkeeping failed",+ self.kb_name,+ exc_info=True,+ )except Exception as e:error_msg = str(e)logger.error(f"Error processing documents: {error_msg}")@@ -231,8 +251,17 @@ class KnowledgeBaseInitializer:)raise- await self.fix_structure()- await self.display_statistics_generic()+ try:+ await self.fix_structure()+ await self.display_statistics_generic()+ except Exception:+ if not self.index_published:+ raise+ logger.warning(+ "LightRAG index for %s was published before statistics bookkeeping failed",+ self.kb_name,+ exc_info=True,+ )return Trueasync def fix_structure(self) -> None:diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.pyindex 1bea6daf9..a5e2c5cfe 100644--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -35,6 +35,7 @@ from deeptutor.services.rag.factory import (DEFAULT_PROVIDER,IMA_PROVIDER,KNOWN_PROVIDERS,+ LIGHTRAG_PROVIDER,LIGHTRAG_SERVER_PROVIDER,PAGEINDEX_OSS_PROVIDER,PAGEINDEX_PROVIDER,@@ -1390,6 +1391,21 @@ class KnowledgeBaseManager:if kb_config.get("knowledge_base_id"):metadata["knowledge_base_id"] = kb_config.get("knowledge_base_id")+ if rag_provider == LIGHTRAG_PROVIDER:+ from deeptutor.services.rag.pipelines.lightrag.storage import (+ latest_published_root,+ read_published_policy,+ )++ published_root = latest_published_root(kb_dir) if dir_exists else None+ indexing_policy = read_published_policy(published_root)+ if indexing_policy is None:+ pending = kb_config.get("pending_indexing_policy")+ indexing_policy = (+ pending if isinstance(pending, dict) else {"policy": "legacy_unpinned"}+ )+ metadata["indexing_policy"] = indexing_policy+metadata.update(self._embedding_fields(kb_config))# Remove None valuesdiff --git a/deeptutor/services/github_source/sync.py b/deeptutor/services/github_source/sync.pyindex a4f1e4804..6cc2839d9 100644--- a/deeptutor/services/github_source/sync.py+++ b/deeptutor/services/github_source/sync.py@@ -6,6 +6,8 @@ from dataclasses import dataclassfrom datetime import datetime, timezoneimport loggingfrom pathlib import Path+import re+from urllib.parse import urlsplit, urlunsplitfrom deeptutor.knowledge.add_documents import DEFAULT_BASE_DIRfrom deeptutor.services.github_source.client import (@@ -33,6 +35,46 @@ def _utcnow_iso() -> str:return datetime.now(timezone.utc).isoformat()+def redact_sync_error(exc: Exception) -> str:+ """Return a bounded sync error without credential-shaped values."""+ message = str(exc).strip() or type(exc).__name__++ def redact_url(match: re.Match[str]) -> str:+ try:+ parsed = urlsplit(match.group(0))+ host = parsed.hostname or ""+ if parsed.port is not None:+ host = f"{host}:{parsed.port}"+ return urlunsplit((parsed.scheme, host, parsed.path, "", ""))+ except ValueError:+ # Error strings are untrusted input too. A malformed bracket or port+ # must not make credential redaction mask the original sync failure.+ return "[redacted-url]"++ message = re.sub(r"https?://[^\s,;]+", redact_url, message)+ message = re.sub(r"\bsk-[A-Za-z0-9_-]{4,}\b", "[redacted]", message)+ message = re.sub(+ r"(?i)((?:api[_-]?key|authorization|token|password)\s*[:=]\s*)[^\s,;]+",+ r"\1[redacted]",+ message,+ )+ return message[:1000]+++def _record_sync_failure(kb_name: str, source: dict, base_dir: str, error: str) -> None:+ try:+ from deeptutor.knowledge.manager import KnowledgeBaseManager++ KnowledgeBaseManager(base_dir=base_dir).update_github_source_state(+ kb_name=kb_name,+ source_id=source["id"],+ last_sync_status="error",+ last_sync_error=error,+ )+ except Exception:+ logger.warning("Could not persist GitHub sync failure status for '%s'", kb_name)++def _is_markdown(path: str) -> bool:return path.lower().endswith(MARKDOWN_EXTENSIONS)@@ -107,9 +149,13 @@ async def sync_source(kb_name, source, *, base_dir=DEFAULT_BASE_DIR, client=Nonetry:latest_sha = await client.get_latest_commit_sha(repo, branch)except GitHubAPIError as exc:- return SyncResult(ok=False, error=str(exc))+ error = redact_sync_error(exc)+ _record_sync_failure(kb_name, source, base_dir, error)+ return SyncResult(ok=False, error=error)except Exception as exc:- return SyncResult(ok=False, error=f"Failed to fetch latest SHA: {exc}")+ error = f"Failed to fetch latest SHA: {redact_sync_error(exc)}"+ _record_sync_failure(kb_name, source, base_dir, error)+ return SyncResult(ok=False, error=error)if old_sha and old_sha == latest_sha:return SyncResult(ok=True, skipped=True)@@ -133,11 +179,16 @@ async def sync_source(kb_name, source, *, base_dir=DEFAULT_BASE_DIR, client=Nonebase_dir,)except GitHubAPIError as exc:- return SyncResult(ok=False, error=str(exc))+ error = redact_sync_error(exc)+ _record_sync_failure(kb_name, source, base_dir, error)+ return SyncResult(ok=False, error=error)except Exception as exc:- return SyncResult(ok=False, error=str(exc))+ error = redact_sync_error(exc)+ _record_sync_failure(kb_name, source, base_dir, error)+ return SyncResult(ok=False, error=error)if not result.ok:+ _record_sync_failure(kb_name, source, base_dir, result.error)return resultfrom deeptutor.knowledge.manager import KnowledgeBaseManager@@ -218,13 +269,9 @@ async def _incremental_sync(async def _index_files(kb_name, file_paths, base_dir):if not file_paths:return 0- try:- from deeptutor.knowledge.add_documents import add_documents+ from deeptutor.knowledge.add_documents import add_documents- count = await add_documents(- kb_name=kb_name, source_files=file_paths, base_dir=base_dir, allow_duplicates=False- )- return count or 0- except Exception as exc:- logger.warning("Indexing failed: %s", exc)- return 0+ count = await add_documents(+ kb_name=kb_name, source_files=file_paths, base_dir=base_dir, allow_duplicates=False+ )+ return count or 0diff --git a/deeptutor/services/github_source/sync_service.py b/deeptutor/services/github_source/sync_service.pyindex c291ada6c..8e8fa11e3 100644--- a/deeptutor/services/github_source/sync_service.py+++ b/deeptutor/services/github_source/sync_service.py@@ -2,11 +2,13 @@from __future__ import annotations-from datetime import datetime, timezoneimport logging+from pathlib import Path-from deeptutor.services.base_sync import BaseSourceSyncService, is_stale-from deeptutor.services.github_source.sync import SYNC_INTERVAL_HOURS+from deeptutor.multi_user.context import reset_current_user, set_current_user+from deeptutor.multi_user.paths import local_admin_user+from deeptutor.services.base_sync import BaseSourceSyncService, default_base_dir, is_stale+from deeptutor.services.github_source.sync import SYNC_INTERVAL_HOURS, redact_sync_errorlogger = logging.getLogger(__name__)@@ -14,9 +16,13 @@ logger = logging.getLogger(__name__)class GitHubSourceSyncService(BaseSourceSyncService):"""Periodically syncs all GitHub sources."""- def __init__(self, *, base_dir=None, client=None, check_interval_s=3600):+ def __init__(self, *, base_dir=None, client=None, check_interval_s=3600, owner=None):+ if owner is None and base_dir is not None:+ if Path(base_dir).resolve() != Path(default_base_dir()).resolve():+ raise ValueError("A custom GitHub sync base_dir requires an explicit owner.")super().__init__(base_dir=base_dir, check_interval_s=check_interval_s)self._client = client+ self._owner = owner or local_admin_user()@propertydef task_name(self) -> str:@@ -26,39 +32,34 @@ class GitHubSourceSyncService(BaseSourceSyncService):from deeptutor.knowledge.manager import KnowledgeBaseManagerfrom deeptutor.services.github_source.sync import sync_source- base_dir = self.effective_base_dir- manager = KnowledgeBaseManager(base_dir=base_dir)+ token = set_current_user(self._owner)+ try:+ base_dir = self.effective_base_dir+ manager = KnowledgeBaseManager(base_dir=base_dir)- all_sources = manager.get_all_github_sources()- for kb_name, source in all_sources:- if not source.get("enabled", True):- continue- if not is_stale(source, stale_hours=SYNC_INTERVAL_HOURS):- continue- sid = source.get("id", "?")- try:- result = await sync_source(- kb_name=kb_name,- source=source,- base_dir=base_dir,- client=self._client,- )- if not result.ok:+ all_sources = manager.get_all_github_sources()+ for kb_name, source in all_sources:+ if not source.get("enabled", True):+ continue+ if not is_stale(source, stale_hours=SYNC_INTERVAL_HOURS):+ continue+ sid = source.get("id", "?")+ try:+ await sync_source(+ kb_name=kb_name,+ source=source,+ base_dir=base_dir,+ client=self._client,+ )+ except Exception as exc:manager.update_github_source_state(kb_name=kb_name,source_id=sid,last_sync_status="error",- last_sync_error=result.error,- last_synced_at=datetime.now(timezone.utc).isoformat(),+ last_sync_error=redact_sync_error(exc),)- except Exception as exc:- manager.update_github_source_state(- kb_name=kb_name,- source_id=sid,- last_sync_status="error",- last_sync_error=str(exc),- last_synced_at=datetime.now(timezone.utc).isoformat(),- )+ finally:+ reset_current_user(token)_sync_service = Nonediff --git a/deeptutor/services/llm/client.py b/deeptutor/services/llm/client.pyindex a8f805ff7..eb36b9ed5 100644--- a/deeptutor/services/llm/client.py+++ b/deeptutor/services/llm/client.py@@ -14,7 +14,67 @@ from typing import Any, castfrom .capabilities import supports_visionfrom .config import LLMConfig, get_llm_config-from .utils import sanitize_url+++def build_model_func_for_config(+ config: LLMConfig,+ *,+ allow_multimodal: bool,+) -> Callable[..., object]:+ """Build a model callable owned solely by one resolved configuration."""+ from . import factory++ def _resolve_messages(+ prompt: str,+ system_prompt: str | None,+ history_messages: list[dict[str, object]] | None,+ messages: list[dict[str, object]] | None,+ ) -> list[dict[str, Any]] | None:+ if messages:+ return cast(list[dict[str, Any]], messages)+ if not history_messages:+ return None++ full_messages: list[dict[str, Any]] = []+ if system_prompt and not (history_messages and history_messages[0].get("role") == "system"):+ full_messages.append({"role": "system", "content": system_prompt})+ full_messages.extend(cast(list[dict[str, Any]], history_messages))+ if prompt:+ full_messages.append({"role": "user", "content": prompt})+ return full_messages or None++ async def model_func(+ prompt: str,+ system_prompt: str | None = None,+ history_messages: list[dict[str, object]] | None = None,+ image_data: str | None = None,+ messages: list[dict[str, object]] | None = None,+ **kwargs: object,+ ) -> str:+ payload_kwargs: dict[str, object] = dict(kwargs)+ for alias in ("history_messages", "messages", "prompt", "system_prompt"):+ payload_kwargs.pop(alias, None)++ default_system_prompt = system_prompt or "You are a helpful assistant."+ resolved_messages = _resolve_messages(+ prompt,+ default_system_prompt,+ history_messages,+ messages,+ )+ if allow_multimodal and image_data is not None:+ payload_kwargs["image_data"] = image_data++ factory_complete = cast(Callable[..., Awaitable[str]], factory.complete_with_config)+ return await factory_complete(+ config=config,+ prompt=prompt,+ system_prompt=default_system_prompt,+ messages=resolved_messages,+ **payload_kwargs,+ )++ return model_funcclass LLMClient:@@ -132,7 +192,7 @@ class LLMClient:Returns:Callable that can be used as llm_model_func"""- return self._build_factory_model_func(allow_multimodal=False)+ return build_model_func_for_config(self.config, allow_multimodal=False)def get_vision_model_func(self) -> Callable[..., object]:"""@@ -141,81 +201,12 @@ class LLMClient:Returns:Callable that can be used as vision_model_func"""- return self._build_factory_model_func(allow_multimodal=True)+ return build_model_func_for_config(self.config, allow_multimodal=True)def supports_multimodal_images(self) -> bool:"""Return whether the configured LLM can accept image input."""return supports_vision(getattr(self.config, "binding", "openai"), self.config.model)- def _build_factory_model_func(self, allow_multimodal: bool) -> Callable[..., object]:- """Build adapter callables on top of the unified factory.complete API."""- from . import factory-- def _resolve_messages(- prompt: str,- system_prompt: str | None,- history_messages: list[dict[str, object]] | None,- messages: list[dict[str, object]] | None,- ) -> list[dict[str, Any]] | None:- if messages:- return cast(list[dict[str, Any]], messages)- if not history_messages:- return None-- full_messages: list[dict[str, Any]] = []- if system_prompt and not (- history_messages and history_messages[0].get("role") == "system"- ):- full_messages.append({"role": "system", "content": system_prompt})- full_messages.extend(cast(list[dict[str, Any]], history_messages))- if prompt:- full_messages.append({"role": "user", "content": prompt})- return full_messages or None-- async def model_func(- prompt: str,- system_prompt: str | None = None,- history_messages: list[dict[str, object]] | None = None,- image_data: str | None = None,- messages: list[dict[str, object]] | None = None,- **kwargs: object,- ) -> str:- payload_kwargs: dict[str, object] = dict(kwargs)-- # Normalize aliases from legacy callsites.- payload_kwargs.pop("history_messages", None)- payload_kwargs.pop("messages", None)- payload_kwargs.pop("prompt", None)- payload_kwargs.pop("system_prompt", None)-- default_system_prompt = system_prompt or "You are a helpful assistant."- resolved_messages = _resolve_messages(- prompt,- default_system_prompt,- history_messages,- messages,- )-- if allow_multimodal and image_data is not None:- payload_kwargs["image_data"] = image_data-- factory_complete = cast(Callable[..., Awaitable[str]], factory.complete)- return await factory_complete(- prompt=prompt,- system_prompt=default_system_prompt,- model=self.config.model,- api_key=self.config.api_key,- base_url=sanitize_url(self.config.base_url) if self.config.base_url else None,- api_version=getattr(self.config, "api_version", None),- binding=getattr(self.config, "binding", "openai"),- reasoning_effort=getattr(self.config, "reasoning_effort", None),- extra_headers=getattr(self.config, "extra_headers", None),- messages=resolved_messages,- **payload_kwargs,- )-- return model_func-_client: LLMClient | None = Nonediff --git a/deeptutor/services/llm/factory.py b/deeptutor/services/llm/factory.pyindex 451899447..efa02b987 100644--- a/deeptutor/services/llm/factory.py+++ b/deeptutor/services/llm/factory.py@@ -23,7 +23,8 @@ from .capabilities import supports_response_format, supports_visionfrom .config import LLMConfig, get_llm_configfrom .error_mapping import map_errorfrom .multimodal import prepare_multimodal_messages-from .provider_factory import get_runtime_provider+from .provider_core.base import LLMProvider+from .provider_factory import build_isolated_provider, get_runtime_providerfrom .utils import is_local_llm_serverDEFAULT_MAX_RETRIES = settings.retry.max_retries@@ -328,8 +329,12 @@ def _sanitize_call_kwargs("base_url","api_version","binding",+ "effective_url","extra_headers",+ "provider_mode",+ "provider_name","reasoning_effort",+ "wire_api",):extra_kwargs.pop(key, None)@@ -338,37 +343,25 @@ def _sanitize_call_kwargs(return extra_kwargs-async def complete(+async def _complete_with_resolved_config(+ config: LLMConfig,+ provider_spec: Any,+ *,prompt: str,- system_prompt: str = "You are a helpful assistant.",- model: str | None = None,- api_key: str | list[str] | None = None,- base_url: str | None = None,- api_version: str | None = None,- binding: str | None = None,- messages: list[dict[str, Any]] | None = None,- max_retries: int = DEFAULT_MAX_RETRIES,- retry_delay: float = DEFAULT_RETRY_DELAY,- exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,- allow_image_fallback: bool | None = None,- **kwargs: Any,+ system_prompt: str,+ messages: list[dict[str, Any]] | None,+ max_retries: int,+ retry_delay: float,+ exponential_backoff: bool,+ allow_image_fallback: bool | None,+ image_data: str | None,+ image_mime_type: str,+ image_filename: str,+ kwargs: dict[str, Any],+ provider: LLMProvider | None = None,) -> str:- caller_extra_headers = kwargs.pop("extra_headers", None)- reasoning_effort = kwargs.pop("reasoning_effort", None)- image_data = kwargs.pop("image_data", None)- image_mime_type = kwargs.pop("image_mime_type", "image/png")- image_filename = kwargs.pop("image_filename", "image.png")-- config, provider_spec = _resolve_call_config(- model=model,- api_key=api_key,- base_url=base_url,- api_version=api_version,- binding=binding,- extra_headers=caller_extra_headers,- reasoning_effort=reasoning_effort,- )- provider = get_runtime_provider(config)+ """Execute one completion from an already resolved configuration."""+ provider = provider or get_runtime_provider(config)capability_binding = _capability_binding(config, provider_spec)request_messages = _build_messages(prompt, system_prompt, messages)request_messages = _apply_inline_image_data(@@ -408,6 +401,114 @@ async def complete(return response.content or ""+async def complete(+ prompt: str,+ system_prompt: str = "You are a helpful assistant.",+ model: str | None = None,+ api_key: str | list[str] | None = None,+ base_url: str | None = None,+ api_version: str | None = None,+ binding: str | None = None,+ messages: list[dict[str, Any]] | None = None,+ max_retries: int = DEFAULT_MAX_RETRIES,+ retry_delay: float = DEFAULT_RETRY_DELAY,+ exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,+ allow_image_fallback: bool | None = None,+ **kwargs: Any,+) -> str:+ caller_extra_headers = kwargs.pop("extra_headers", None)+ reasoning_effort = kwargs.pop("reasoning_effort", None)+ image_data = kwargs.pop("image_data", None)+ image_mime_type = kwargs.pop("image_mime_type", "image/png")+ image_filename = kwargs.pop("image_filename", "image.png")++ config, provider_spec = _resolve_call_config(+ model=model,+ api_key=api_key,+ base_url=base_url,+ api_version=api_version,+ binding=binding,+ extra_headers=caller_extra_headers,+ reasoning_effort=reasoning_effort,+ )+ return await _complete_with_resolved_config(+ config,+ provider_spec,+ prompt=prompt,+ system_prompt=system_prompt,+ messages=messages,+ max_retries=max_retries,+ retry_delay=retry_delay,+ exponential_backoff=exponential_backoff,+ allow_image_fallback=allow_image_fallback,+ image_data=image_data,+ image_mime_type=str(image_mime_type or "image/png"),+ image_filename=str(image_filename or "image.png"),+ kwargs=kwargs,+ )+++async def complete_with_config(+ config: LLMConfig,+ prompt: str,+ system_prompt: str = "You are a helpful assistant.",+ messages: list[dict[str, Any]] | None = None,+ max_retries: int = DEFAULT_MAX_RETRIES,+ retry_delay: float = DEFAULT_RETRY_DELAY,+ exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,+ allow_image_fallback: bool | None = None,+ **kwargs: Any,+) -> str:+ """Complete using only the supplied, fully resolved configuration."""+ forbidden = {+ "model",+ "api_key",+ "base_url",+ "api_version",+ "binding",+ "effective_url",+ "extra_headers",+ "provider_mode",+ "provider_name",+ "reasoning_effort",+ "wire_api",+ }.intersection(kwargs)+ if forbidden:+ names = ", ".join(sorted(forbidden))+ raise TypeError(f"complete_with_config does not accept config overrides: {names}")++ image_data = kwargs.pop("image_data", None)+ image_mime_type = kwargs.pop("image_mime_type", "image/png")+ image_filename = kwargs.pop("image_filename", "image.png")+ provider_spec = _resolve_provider_spec(+ binding=config.provider_name or config.binding,+ model=config.model,+ api_key=config.api_key,+ base_url=config.effective_url or config.base_url,+ fallback=config.provider_name or config.binding,+ )+ provider = build_isolated_provider(config)+ try:+ return await _complete_with_resolved_config(+ config,+ provider_spec,+ prompt=prompt,+ system_prompt=system_prompt,+ messages=messages,+ max_retries=max_retries,+ retry_delay=retry_delay,+ exponential_backoff=exponential_backoff,+ allow_image_fallback=allow_image_fallback,+ image_data=image_data,+ image_mime_type=str(image_mime_type or "image/png"),+ image_filename=str(image_filename or "image.png"),+ kwargs=kwargs,+ provider=provider,+ )+ finally:+ await provider.aclose()++async def stream(prompt: str,system_prompt: str = "You are a helpful assistant.",diff --git a/deeptutor/services/llm/provider_core/codebuddy_http_provider.py b/deeptutor/services/llm/provider_core/codebuddy_http_provider.pyindex 41c61d18b..bea9452d2 100644--- a/deeptutor/services/llm/provider_core/codebuddy_http_provider.py+++ b/deeptutor/services/llm/provider_core/codebuddy_http_provider.py@@ -51,6 +51,8 @@ class CodeBuddyHTTPProvider(OpenAICompatProvider):self,api_key: str | None = None,default_model: str = DEFAULT_CODEBUDDY_MODEL,+ *,+ configure_env: bool = True,):self._explicit_api_key = normalize_api_key(api_key)self._credentials: CodeBuddyCredentials | None = (@@ -70,6 +72,7 @@ class CodeBuddyHTTPProvider(OpenAICompatProvider):extra_headers=extra_headers,spec=find_by_name("codebuddy"),provider_name="codebuddy",+ configure_env=configure_env,)if self._explicit_api_key:self._apply_token(self._explicit_api_key)@@ -208,6 +211,8 @@ def sdk_installed() -> bool:def build_codebuddy_provider(api_key: str | None = None,default_model: str = DEFAULT_CODEBUDDY_MODEL,+ *,+ configure_env: bool = True,) -> Any:"""Return the HTTP transport when it can authenticate, else the Agent SDK.@@ -226,7 +231,11 @@ def build_codebuddy_provider(use_http = codebuddy_http_available(api_key) or not has_sdkif use_http:- return CodeBuddyHTTPProvider(api_key=api_key, default_model=default_model)+ return CodeBuddyHTTPProvider(+ api_key=api_key,+ default_model=default_model,+ configure_env=configure_env,+ )from deeptutor.services.llm.provider_core.codebuddy_provider import CodeBuddyProviderdiff --git a/deeptutor/services/llm/provider_core/github_copilot_provider.py b/deeptutor/services/llm/provider_core/github_copilot_provider.pyindex 5fa4db94c..d4a3aa686 100644--- a/deeptutor/services/llm/provider_core/github_copilot_provider.py+++ b/deeptutor/services/llm/provider_core/github_copilot_provider.py@@ -24,7 +24,12 @@ _EXPIRY_SKEW_SECONDS = 60class GitHubCopilotProvider(OpenAICompatProvider):"""Provider that first tries existing Copilot auth, then oauth-cli-kit tokens."""- def __init__(self, default_model: str = "github-copilot/gpt-4.1"):+ def __init__(+ self,+ default_model: str = "github-copilot/gpt-4.1",+ *,+ configure_env: bool = True,+ ):self._copilot_access_token: str | None = Noneself._copilot_expires_at: float = 0.0super().__init__(@@ -38,6 +43,7 @@ class GitHubCopilotProvider(OpenAICompatProvider):},spec=find_by_name("github_copilot"),provider_name="github_copilot",+ configure_env=configure_env,)async def _try_existing_local_auth(self) -> None:diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.pyindex 089f0b45b..f6cda4a90 100644--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py@@ -133,6 +133,7 @@ class OpenAICompatProvider(LLMProvider):spec: Any = None,provider_name: str | None = None,wire_api: str = "auto",+ configure_env: bool = True,):keys = api_key if isinstance(api_key, list) else [api_key]keys = [str(key).strip() for key in keys if str(key or "").strip()]@@ -145,7 +146,7 @@ class OpenAICompatProvider(LLMProvider):self._provider_name = provider_nameself._wire_api = normalize_wire_api(wire_api)- if primary_key and spec and spec.env_key:+ if configure_env and primary_key and spec and spec.env_key:self._setup_env(primary_key, api_base)effective_base = api_base or (spec.default_api_base if spec else None) or Nonediff --git a/deeptutor/services/llm/provider_factory.py b/deeptutor/services/llm/provider_factory.pyindex 7268a9f83..b2be33e49 100644--- a/deeptutor/services/llm/provider_factory.py+++ b/deeptutor/services/llm/provider_factory.py@@ -45,7 +45,11 @@ def _provider_cache_key(config: LLMConfig, loop: asyncio.AbstractEventLoop) -> t)-def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:+def _build_runtime_provider(+ llm_config: LLMConfig,+ *,+ configure_env: bool = True,+) -> LLMProvider:"""Construct one provider, importing only the selected backend SDK."""provider_name = llm_config.provider_name or llm_config.bindingapi_key = llm_config.get_api_key()@@ -68,7 +72,10 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:GitHubCopilotProvider,)- provider = GitHubCopilotProvider(default_model=llm_config.model)+ provider = GitHubCopilotProvider(+ default_model=llm_config.model,+ configure_env=configure_env,+ )elif backend == "codebuddy":from deeptutor.services.llm.provider_core.codebuddy_http_provider import (build_codebuddy_provider,@@ -77,6 +84,7 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:provider = build_codebuddy_provider(api_key=api_key or None,default_model=llm_config.model,+ configure_env=configure_env,)elif backend == "azure_openai":from deeptutor.services.llm.provider_core.azure_openai_provider import AzureOpenAIProvider@@ -109,6 +117,7 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:spec=spec,provider_name=provider_name,wire_api=llm_config.wire_api,+ configure_env=configure_env,)provider.generation = GenerationSettings(@@ -119,6 +128,11 @@ def _build_runtime_provider(llm_config: LLMConfig) -> LLMProvider:return provider+def build_isolated_provider(config: LLMConfig) -> LLMProvider:+ """Build an unpooled provider without mutating process-global provider env."""+ return _build_runtime_provider(config, configure_env=False)++def _schedule_close(provider: LLMProvider, loop: asyncio.AbstractEventLoop) -> None:async def _close() -> None:with contextlib.suppress(Exception):@@ -190,6 +204,7 @@ def runtime_provider_pool_size() -> int:__all__ = [+ "build_isolated_provider","close_runtime_provider_pool","get_runtime_provider","reset_runtime_provider_pool",diff --git a/deeptutor/services/rag/pipelines/lightrag/config.py b/deeptutor/services/rag/pipelines/lightrag/config.pyindex 9017a8735..6f45e3365 100644--- a/deeptutor/services/rag/pipelines/lightrag/config.py+++ b/deeptutor/services/rag/pipelines/lightrag/config.py@@ -24,6 +24,9 @@ import refrom typing import TYPE_CHECKING, TypeVarif TYPE_CHECKING:+ from deeptutor.multi_user.models import CurrentUser+ from deeptutor.services.llm.config import LLMConfig+from .worker import OwnerLoopBridgelogger = logging.getLogger(__name__)@@ -188,8 +191,7 @@ def constructor_kwargs_from_settings() -> dict:return {}-def lightrag_llm_selection_from_settings() -> dict[str, str] | None:- """Return a complete dedicated catalog reference, or use the active LLM."""+def _lightrag_llm_selection_from_settings(*, strict: bool) -> dict[str, str] | None:try:from deeptutor.services.config import load_lightrag_settings@@ -199,10 +201,14 @@ def lightrag_llm_selection_from_settings() -> dict[str, str] | None:if not profile_id and not model_id:return Noneif not profile_id or not model_id:+ if strict:+ raise ValueError("The LightRAG LLM selection is incomplete.")logger.warning("Ignoring incomplete LightRAG LLM selection; using the active model")return Nonereturn {"profile_id": profile_id, "model_id": model_id}except Exception:+ if strict:+ raiselogger.warning("Could not read LightRAG LLM selection; using the active model",exc_info=True,@@ -210,41 +216,49 @@ def lightrag_llm_selection_from_settings() -> dict[str, str] | None:return None-def _resolve_override_llm_config(selection: dict[str, str] | None):- if selection is None:- return None- try:- from deeptutor.services.model_selection.runtime import (- resolve_llm_config_for_selection,- )+def lightrag_llm_selection_from_settings() -> dict[str, str] | None:+ """Return the released query-model selection with its fallback semantics."""+ return _lightrag_llm_selection_from_settings(strict=False)++def lightrag_indexing_selection_from_settings() -> dict[str, str] | None:+ """Return the indexing default, rejecting unreadable or partial settings."""+ return _lightrag_llm_selection_from_settings(strict=True)+++def resolve_lightrag_query_llm_config():+ """Resolve the current LightRAG query model with the released fallback contract."""+ from deeptutor.services.model_selection.runtime import resolve_llm_config_for_selection++ selection = lightrag_llm_selection_from_settings()+ try:return resolve_llm_config_for_selection(selection)except ValueError:logger.warning("LightRAG LLM selection %s no longer exists in the catalog; using the active model",selection,)- return None+ return resolve_llm_config_for_selection(None)def build_llm_model_func(*,io_bridge: OwnerLoopBridge | None = None,- llm_selection: dict[str, str] | None = None,+ llm_config: LLMConfig | None = None,+ owner: CurrentUser | None = None,):"""Wrap DeepTutor's unified LLM callable for LightRAG.Drops LightRAG's internal kwargs while preserving explicit ``messages``."""- override = _resolve_override_llm_config(llm_selection)- if override is None:+ if llm_config is None:from deeptutor.services.llm import get_llm_clientbase = get_llm_client().get_model_func()else:- from deeptutor.services.llm.client import LLMClient+ from deeptutor.services.llm.client import build_model_func_for_config- base = LLMClient(config=override, configure_env=False).get_model_func()+ base = build_model_func_for_config(llm_config, allow_multimodal=False)async def llm_model_func(prompt="",@@ -254,14 +268,22 @@ def build_llm_model_func(**_ignored,):async def request():- return await base(- prompt or "",- system_prompt=system_prompt,- history_messages=history_messages or [],- messages=messages,- max_retries=0,- allow_image_fallback=False,- )+ async def complete():+ return await base(+ prompt or "",+ system_prompt=system_prompt,+ history_messages=history_messages or [],+ messages=messages,+ max_retries=0,+ allow_image_fallback=False,+ )++ if owner is None:+ return await complete()+ from deeptutor.multi_user.paths import user_context++ with user_context(owner):+ return await complete()return await _run_adapter_with_retry(request, io_bridge=io_bridge)@@ -271,18 +293,18 @@ def build_llm_model_func(def build_vision_model_func(*,io_bridge: OwnerLoopBridge | None = None,- llm_selection: dict[str, str] | None = None,+ llm_config: LLMConfig | None = None,+ owner: CurrentUser | None = None,):"""Map rc2 ``image_inputs`` to DeepTutor's vision callable."""- override = _resolve_override_llm_config(llm_selection)- if override is None:+ if llm_config is None:from deeptutor.services.llm import get_llm_clientbase = get_llm_client().get_vision_model_func()else:- from deeptutor.services.llm.client import LLMClient+ from deeptutor.services.llm.client import build_model_func_for_config- base = LLMClient(config=override, configure_env=False).get_vision_model_func()+ base = build_model_func_for_config(llm_config, allow_multimodal=True)async def vision_model_func(prompt="",@@ -302,15 +324,23 @@ def build_vision_model_func(raise ValueError("LightRAG vision image input requires a non-empty base64 value")async def request():- return await base(- prompt or "",- system_prompt=system_prompt,- history_messages=history_messages or [],- image_data=image_data,- messages=messages,- max_retries=0,- allow_image_fallback=False,- )+ async def complete():+ return await base(+ prompt or "",+ system_prompt=system_prompt,+ history_messages=history_messages or [],+ image_data=image_data,+ messages=messages,+ max_retries=0,+ allow_image_fallback=False,+ )++ if owner is None:+ return await complete()+ from deeptutor.multi_user.paths import user_context++ with user_context(owner):+ return await complete()return await _run_adapter_with_retry(request, io_bridge=io_bridge)@@ -380,6 +410,7 @@ __all__ = ["indexing_kwargs_from_settings","constructor_kwargs_from_settings","lightrag_llm_selection_from_settings",+ "resolve_lightrag_query_llm_config","build_llm_model_func","build_vision_model_func","vision_model_available",diff --git a/deeptutor/services/rag/pipelines/lightrag/engine.py b/deeptutor/services/rag/pipelines/lightrag/engine.pyindex 9fe8db9dc..3b5f2cb85 100644--- a/deeptutor/services/rag/pipelines/lightrag/engine.py+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py@@ -17,9 +17,9 @@ from .config import (build_vision_model_func,constructor_kwargs_from_settings,indexing_kwargs_from_settings,- lightrag_llm_selection_from_settings,normalize_mode,query_kwargs_from_settings,+ resolve_lightrag_query_llm_config,)from .ingress import IngressError, StagedDocument, pending_rootfrom .worker import OwnerLoopBridge@@ -188,31 +188,86 @@ def build_rag(*,io_bridge: OwnerLoopBridge | None = None,enable_vlm: bool = False,+ indexing_snapshot: Any | None = None,) -> Any:"""Construct one exact-version, version-isolated LightRAG instance."""_require_exact_version()_register_parser()from lightrag.llm_roles import RoleLLMConfig- llm_adapter_kwargs: dict[str, Any] = {"llm_selection": lightrag_llm_selection_from_settings()}+ llm_adapter_kwargs: dict[str, Any] = {}embedding_adapter_kwargs: dict[str, Any] = {}if io_bridge is not None:llm_adapter_kwargs["io_bridge"] = io_bridgeembedding_adapter_kwargs["io_bridge"] = io_bridge+ from .indexing_policy import cache_identity_for_config++ query_config = resolve_lightrag_query_llm_config()+ query_func = build_llm_model_func(+ **llm_adapter_kwargs,+ llm_config=query_config,+ )+ query_identity = cache_identity_for_config(query_config)+ query_metadata = {+ "binding": query_config.binding,+ "model": query_identity,+ }constructor = {"working_dir": str(Path(working_dir)),"workspace": workspace_for(working_dir),- "llm_model_func": build_llm_model_func(**llm_adapter_kwargs),+ "llm_model_func": query_func,+ "llm_model_name": query_identity,"embedding_func": build_embedding_func(**embedding_adapter_kwargs),"auto_manage_storages_states": False,"vlm_process_enable": bool(enable_vlm),**indexing_kwargs_from_settings(),**constructor_kwargs_from_settings(),}- if enable_vlm:- constructor["role_llm_configs"] = {- "vlm": RoleLLMConfig(func=build_vision_model_func(**llm_adapter_kwargs))+ role_configs: dict[str, Any] = {+ "keyword": RoleLLMConfig(func=query_func, metadata=query_metadata),+ "query": RoleLLMConfig(func=query_func, metadata=query_metadata),+ }+ if indexing_snapshot is not None:+ from .indexing_policy import cache_identity++ snapshot_kwargs = {+ **llm_adapter_kwargs,+ "llm_config": indexing_snapshot.config,+ "owner": indexing_snapshot.owner,+ }+ metadata = {+ "binding": indexing_snapshot.config.binding,+ "model": cache_identity(indexing_snapshot),+ "host": indexing_snapshot.descriptor.get("endpoint"),}+ role_configs["extract"] = RoleLLMConfig(+ func=build_llm_model_func(**snapshot_kwargs), metadata=metadata+ )+ if enable_vlm:+ if indexing_snapshot is None:+ raise LightRagContractError(+ "LightRAG vision indexing requires a frozen indexing-model policy."+ )+ vision_kwargs = llm_adapter_kwargs+ metadata = None+ if indexing_snapshot is not None:+ from .indexing_policy import cache_identity++ vision_kwargs = {+ **llm_adapter_kwargs,+ "llm_config": indexing_snapshot.config,+ "owner": indexing_snapshot.owner,+ }+ metadata = {+ "binding": indexing_snapshot.config.binding,+ "model": cache_identity(indexing_snapshot),+ "host": indexing_snapshot.descriptor.get("endpoint"),+ }+ role_configs["vlm"] = RoleLLMConfig(+ func=build_vision_model_func(**vision_kwargs), metadata=metadata+ )+ if role_configs:+ constructor["role_llm_configs"] = role_configsreturn _controlled_class()(**constructor)diff --git a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.pynew file mode 100644index 000000000..bbfa81284--- /dev/null+++ b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py@@ -0,0 +1,274 @@+"""Immutable model identity for native LightRAG indexing writes."""++from __future__ import annotations++from dataclasses import dataclass+import hashlib+import json+from pathlib import Path+from typing import Any+from urllib.parse import urlsplit, urlunsplit++from deeptutor.multi_user.context import get_current_user, get_current_user_or_none+from deeptutor.multi_user.model_access import (+ OWNER_BOUND_BINDINGS,+ apply_allowed_llm_selection,+)+from deeptutor.multi_user.models import CurrentUser+from deeptutor.services.llm.capabilities import supports_vision+from deeptutor.services.llm.config import LLMConfig+from deeptutor.services.llm.exceptions import LLMConfigError+from deeptutor.services.model_selection.llm import LLMSelection+from deeptutor.services.model_selection.runtime import resolve_llm_config_for_selection++POLICY_PINNED = "pinned"+POLICY_PENDING = "pending_pinned"+POLICY_LEGACY = "legacy_unpinned"+++class IndexingPolicyError(RuntimeError):+ """A pinned model can no longer be used without changing index identity."""++ code = "indexing_model_unavailable"+ retryable = False+++class IndexingModelChangedError(IndexingPolicyError):+ """The selected catalog entry no longer matches the published fingerprint."""++ code = "reindex_required"+++def _endpoint_identity(value: str | None) -> str:+ if not value:+ return ""+ parsed = urlsplit(value)+ host = parsed.hostname or ""+ if parsed.port is not None:+ host = f"{host}:{parsed.port}"+ return urlunsplit((parsed.scheme.lower(), host.lower(), parsed.path.rstrip("/"), "", ""))+++def _canonical_identity(+ selection: LLMSelection | None,+ config: LLMConfig,+ *,+ vision_available: bool | None = None,+) -> dict[str, Any]:+ identity = {+ "binding": config.binding,+ "provider_mode": config.provider_mode,+ "endpoint": _endpoint_identity(config.effective_url or config.base_url),+ "api_version": config.api_version or None,+ "model": config.model,+ "reasoning_effort": config.reasoning_effort,+ }+ if selection is not None:+ identity["profile_id"] = selection.profile_id+ identity["model_id"] = selection.model_id+ if vision_available is not None:+ identity["vision_available"] = vision_available+ return identity+++def _fingerprint(identity: dict[str, Any]) -> str:+ encoded = json.dumps(identity, sort_keys=True, separators=(",", ":")).encode("utf-8")+ return hashlib.sha256(encoded).hexdigest()+++@dataclass(frozen=True, slots=True)+class IndexingLLMSnapshot:+ config: LLMConfig+ owner: CurrentUser+ policy: str+ selection: LLMSelection | None+ descriptor: dict[str, Any]+ fingerprint: str | None+ vision_available: bool++ def persisted_policy(self) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "policy": self.policy,+ "descriptor": self.descriptor,+ "fingerprint": self.fingerprint,+ "vision_available": self.vision_available,+ }+ if self.selection is not None:+ payload["selection"] = self.selection.to_dict()+ return payload+++def freeze_snapshot(+ selection_value: Any = None,+ *,+ policy: str | None = None,+ require_explicit_user: bool = True,+) -> IndexingLLMSnapshot:+ """Resolve and freeze one access-checked indexing model in the caller scope."""+ selection = LLMSelection.from_payload(selection_value)+ explicit_user = get_current_user_or_none()+ if selection is not None and explicit_user is None and require_explicit_user:+ raise IndexingPolicyError(+ "Pinned indexing models require an explicit initiating user scope."+ )+ try:+ if selection is not None:+ apply_allowed_llm_selection(selection.to_dict())+ config = resolve_llm_config_for_selection(selection)+ except (LLMConfigError, PermissionError, ValueError) as exc:+ raise IndexingPolicyError(str(exc)) from exc++ if config.binding in OWNER_BOUND_BINDINGS and explicit_user is None:+ raise IndexingPolicyError(+ "Owner-bound indexing models require an explicit initiating user scope."+ )+ owner = explicit_user or get_current_user()+ resolved_policy = policy or (POLICY_PINNED if selection is not None else POLICY_LEGACY)+ vision_available = supports_vision(config.binding, config.model)+ if resolved_policy == POLICY_LEGACY:+ descriptor = {+ "model": config.model,+ "binding": config.binding,+ "reasoning_effort": config.reasoning_effort,+ }+ fingerprint = None+ else:+ identity = _canonical_identity(+ selection,+ config,+ vision_available=vision_available,+ )+ descriptor = identity+ fingerprint = _fingerprint(identity)+ return IndexingLLMSnapshot(+ config=config,+ owner=owner,+ policy=resolved_policy,+ selection=None if resolved_policy == POLICY_LEGACY else selection,+ descriptor=descriptor,+ fingerprint=fingerprint,+ vision_available=vision_available,+ )+++def pending_policy_for_selection(selection_value: Any) -> dict[str, Any]:+ snapshot = freeze_snapshot(selection_value, policy=POLICY_PENDING)+ return snapshot.persisted_policy()+++def _active_catalog_selection() -> dict[str, str] | None:+ from deeptutor.services.config import get_model_catalog_service++ catalog = get_model_catalog_service().load()+ service = catalog.get("services", {}).get("llm", {})+ profile_id = str(service.get("active_profile_id") or "").strip()+ model_id = str(service.get("active_model_id") or "").strip()+ if not profile_id or not model_id:+ return None+ return {"profile_id": profile_id, "model_id": model_id}+++def freeze_default_snapshot() -> IndexingLLMSnapshot:+ """Freeze the released LightRAG model, or the active model when it is unset."""+ from .config import lightrag_indexing_selection_from_settings++ try:+ selection = lightrag_indexing_selection_from_settings()+ except Exception as exc:+ raise IndexingPolicyError(+ "The LightRAG indexing-model setting could not be resolved."+ ) from exc+ if selection is None:+ selection = _active_catalog_selection()+ return freeze_snapshot(+ selection,+ policy=POLICY_PINNED,+ require_explicit_user=False,+ )+++def snapshot_from_persisted(policy: dict[str, Any]) -> IndexingLLMSnapshot:+ selection = policy.get("selection")+ if selection is not None and not isinstance(selection, dict):+ raise IndexingPolicyError("Pinned LightRAG metadata has an invalid model selection.")+ snapshot = freeze_snapshot(selection, policy=POLICY_PINNED)+ expected = str(policy.get("fingerprint") or "")+ if not expected or snapshot.fingerprint != expected:+ raise IndexingModelChangedError(+ "The pinned LightRAG indexing model changed; run a full re-index to publish "+ "the new model identity."+ )+ return snapshot+++def effective_policy(kb_dir: Path, *, base_dir: str, kb_name: str) -> dict[str, Any] | None:+ """Return published policy first, then pre-publication pending policy."""+ from .storage import latest_published_root, read_published_policy++ root = latest_published_root(kb_dir)+ published = read_published_policy(root)+ if published is not None:+ return published++ from deeptutor.knowledge.manager import KnowledgeBaseManager++ manager = KnowledgeBaseManager(base_dir=base_dir)+ entry = manager.config.get("knowledge_bases", {}).get(kb_name) or {}+ pending = entry.get("pending_indexing_policy")+ return pending if isinstance(pending, dict) else None+++def resolve_write_snapshot(+ kb_dir: Path,+ *,+ base_dir: str,+ kb_name: str,+ explicit: IndexingLLMSnapshot | None = None,+) -> IndexingLLMSnapshot:+ if explicit is not None:+ return explicit+ policy = effective_policy(kb_dir, base_dir=base_dir, kb_name=kb_name)+ if policy is None:+ return freeze_default_snapshot()+ if policy.get("policy") == POLICY_LEGACY:+ raise IndexingModelChangedError(+ "This LightRAG index has no verified indexing model; run a full re-index "+ "before appending documents."+ )+ return snapshot_from_persisted(policy)+++def cache_identity(snapshot: IndexingLLMSnapshot) -> str:+ if snapshot.fingerprint:+ return snapshot.fingerprint+ identity = {+ "binding": snapshot.config.binding,+ "provider_mode": snapshot.config.provider_mode,+ "endpoint": _endpoint_identity(snapshot.config.effective_url or snapshot.config.base_url),+ "model": snapshot.config.model,+ "reasoning_effort": snapshot.config.reasoning_effort,+ }+ return _fingerprint(identity)+++def cache_identity_for_config(config: LLMConfig) -> str:+ """Return a credential-free cache identity for a resolved query model."""+ return _fingerprint(_canonical_identity(None, config))+++__all__ = [+ "IndexingLLMSnapshot",+ "IndexingModelChangedError",+ "IndexingPolicyError",+ "POLICY_LEGACY",+ "POLICY_PENDING",+ "POLICY_PINNED",+ "cache_identity",+ "cache_identity_for_config",+ "effective_policy",+ "freeze_default_snapshot",+ "freeze_snapshot",+ "pending_policy_for_selection",+ "resolve_write_snapshot",+ "snapshot_from_persisted",+]diff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.pyindex 679d51d34..5818ce487 100644--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py@@ -13,13 +13,19 @@ from typing import Any, Callable, Dict, List, Optionalfrom deeptutor.runtime.home import get_runtime_data_rootfrom deeptutor.services.rag.index_versioning import (list_kb_versions,- resolve_storage_dir_for_read,resolve_storage_dir_for_rebuild,)from deeptutor.services.rag.kb_paths import resolve_kb_dir-from . import block_policy, engine, ingress, storage+from . import block_policy, engine, indexing_policy, ingress, storagefrom . import config as lr_config+from .indexing_policy import (+ IndexingLLMSnapshot,+ IndexingPolicyError,+ effective_policy,+ freeze_default_snapshot,+ resolve_write_snapshot,+)from .worker import OwnerLoopBridge, run_in_worker_looplogger = logging.getLogger(__name__)@@ -36,6 +42,8 @@ class BatchOutcome:nonterminal: dict[str, str] = field(default_factory=dict)missing: tuple[str, ...] = ()track_id: str = ""+ vlm_used: bool = False+ indexing_policy: dict[str, Any] = field(default_factory=dict)@propertydef complete(self) -> bool:@@ -111,7 +119,11 @@ class LightRagPipeline:)def _stage_documents(- self, working_dir: Path, file_paths: List[str]+ self,+ working_dir: Path,+ file_paths: List[str],+ *,+ vision_available: bool,) -> tuple[list[ingress.StagedDocument], dict[str, str]]:from deeptutor.services.parsing import get_parse_service@@ -119,7 +131,6 @@ class LightRagPipeline:staged: list[ingress.StagedDocument] = []failures: dict[str, str] = {}seen: set[str] = set()- vision_available = lr_config.vision_model_available()for raw_path in file_paths:path = Path(raw_path)name = path.name@@ -232,7 +243,10 @@ class LightRagPipeline:block_policy.write_decision_ledger(Path(rag.working_dir), doc_id, item.audit_ledger)- return outcome+ return replace(+ outcome,+ vlm_used=any("i" in getattr(item, "process_options", "") for item in staged),+ )if unknown:return BatchOutcome(requested=len(expected) + len(preflight_failed),@@ -265,10 +279,18 @@ class LightRagPipeline:working_dir: Path,file_paths: List[str],progress_callback: Callable[[int, int], Any] | None,+ snapshot: IndexingLLMSnapshot | None = None,) -> BatchOutcome:+ if snapshot is None:+ snapshot = freeze_default_snapshot()+async def job(io_bridge: OwnerLoopBridge) -> BatchOutcome:io_bridge.raise_if_cancelled()- staged, preflight_failed = self._stage_documents(working_dir, file_paths)+ staged, preflight_failed = self._stage_documents(+ working_dir,+ file_paths,+ vision_available=snapshot.vision_available,+ )if not staged:raise LightRagBatchError(BatchOutcome(requested=len(file_paths), preflight_failed=preflight_failed)@@ -278,6 +300,7 @@ class LightRagPipeline:working_dir,io_bridge=io_bridge,enable_vlm=any("i" in item.process_options for item in staged),+ indexing_snapshot=snapshot,)except BaseException:for item in staged:@@ -332,7 +355,8 @@ class LightRagPipeline:for item in cleanup:ingress.remove_unaccepted(item)- return await run_in_worker_loop(job)+ outcome = await run_in_worker_loop(job)+ return replace(outcome, indexing_policy=snapshot.persisted_policy())def _remove_zero_accepted_candidate(self, root_dir: Path) -> None:if not root_dir.is_dir() or storage.has_any_doc_status(root_dir):@@ -345,14 +369,28 @@ class LightRagPipeline:async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)+ snapshot = kwargs.get("indexing_snapshot")+ if snapshot is None:+ policy = effective_policy(+ kb_dir,+ base_dir=self.kb_base_dir,+ kb_name=kb_name,+ )+ if policy is not None and policy.get("policy") == "pending_pinned":+ snapshot = indexing_policy.snapshot_from_persisted(policy)+ else:+ snapshot = freeze_default_snapshot()root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)try:outcome = await self._run_indexing(- root_dir, file_paths, kwargs.get("progress_callback")+ root_dir, file_paths, kwargs.get("progress_callback"), snapshot)if not storage.has_output(root_dir):raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")- storage.write_meta(root_dir)+ policy = dict(outcome.indexing_policy)+ policy["vlm_used"] = outcome.vlm_used+ storage.write_meta(root_dir, indexing_policy=policy)+ self._clear_pending_policy(kb_name)return outcome.completeexcept asyncio.CancelledError:raise@@ -367,25 +405,52 @@ class LightRagPipeline:async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)- existing = resolve_storage_dir_for_read(kb_dir, None)- if existing is not None and storage.meta_is_native_published(existing):- root_dir = existing- is_update = True- elif existing is not None or list_kb_versions(kb_dir):+ existing = storage.latest_published_root(kb_dir)+ versions = list_kb_versions(kb_dir)+ explicit = kwargs.get("indexing_snapshot")+ if explicit is not None and (existing is not None or versions):+ raise IndexingPolicyError(+ "An explicit LightRAG indexing model cannot override an existing index; "+ "run a full re-index."+ )+ if existing is None and versions:raise LightRagNeedsReindexError("This LightRAG index is legacy, unpublished, or corrupt and must be rebuilt ""before appending.")+ snapshot = resolve_write_snapshot(+ kb_dir,+ base_dir=self.kb_base_dir,+ kb_name=kb_name,+ explicit=explicit,+ )+ if existing is not None:+ root_dir = existing+ is_update = Trueelse:root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)is_update = Falsetry:outcome = await self._run_indexing(- root_dir, file_paths, kwargs.get("progress_callback")+ root_dir, file_paths, kwargs.get("progress_callback"), snapshot)if not storage.has_output(root_dir):raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")- storage.write_meta(root_dir)+ policy = dict(outcome.indexing_policy)+ policy["vlm_used"] = outcome.vlm_used+ if not is_update:+ storage.write_meta(root_dir, indexing_policy=policy)+ self._clear_pending_policy(kb_name)+ else:+ try:+ storage.write_meta(root_dir, indexing_policy=policy)+ self._clear_pending_policy(kb_name)+ except Exception:+ self.logger.warning(+ "LightRAG append completed but metadata refresh failed; preserving the "+ "existing published policy",+ exc_info=True,+ )return outcome.completeexcept LightRagBatchError as exc:if not is_update and exc.outcome.accepted == 0:@@ -396,10 +461,27 @@ class LightRagPipeline:self._remove_zero_accepted_candidate(root_dir)raise+ def _clear_pending_policy(self, kb_name: str) -> None:+ """Best-effort cleanup after version metadata became authoritative."""+ try:+ from deeptutor.knowledge.manager import KnowledgeBaseManager++ manager = KnowledgeBaseManager(base_dir=self.kb_base_dir)+ entry = manager.config.get("knowledge_bases", {}).get(kb_name) or {}+ if "pending_indexing_policy" in entry:+ entry.pop("pending_indexing_policy", None)+ manager._save_config()+ except Exception:+ self.logger.warning(+ "Published LightRAG policy for %s but could not clear pending cache",+ kb_name,+ exc_info=True,+ )+async def search(self, query: str, kb_name: str, **kwargs) -> Dict[str, Any]:kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)- root_dir = resolve_storage_dir_for_read(kb_dir, None)- if root_dir is None or not storage.meta_is_native_published(root_dir):+ root_dir = storage.latest_published_root(kb_dir)+ if root_dir is None:return {"query": query,"answer": "This LightRAG knowledge base must be rebuilt for the native pipeline.",diff --git a/deeptutor/services/rag/pipelines/lightrag/storage.py b/deeptutor/services/rag/pipelines/lightrag/storage.pyindex 0e477ddf9..a79a9e392 100644--- a/deeptutor/services/rag/pipelines/lightrag/storage.py+++ b/deeptutor/services/rag/pipelines/lightrag/storage.py@@ -211,7 +211,28 @@ def _parser_inputs(root_dir: Path) -> list[dict[str, str]]:]-def write_meta(root_dir: Path) -> None:+def read_published_policy(root_dir: Path | None) -> dict[str, Any] | None:+ if root_dir is None or not meta_is_native_published(root_dir):+ return None+ meta = _read_meta(Path(root_dir)) or {}+ policy = meta.get("indexing_policy")+ if isinstance(policy, dict):+ return policy+ return {"policy": "legacy_unpinned"}+++def latest_published_root(kb_dir: Path) -> Path | None:+ """Return the newest native published version, ignoring failed candidates."""+ from deeptutor.services.rag.index_versioning import list_kb_versions++ for entry in list_kb_versions(Path(kb_dir)):+ root = Path(str(entry.get("storage_path") or ""))+ if meta_is_native_published(root):+ return root+ return None+++def write_meta(root_dir: Path, *, indexing_policy: dict[str, Any] | None = None) -> None:"""Write a flat-layout ``meta.json`` so the version lists as ready.Mirrors ``index_versioning.write_version_meta`` but carries a synthetic@@ -240,6 +261,9 @@ def write_meta(root_dir: Path) -> None:"layout": "flat","created_at": str(previous.get("created_at") or now),"updated_at": now,+ "indexing_policy": indexing_policy+ or previous.get("indexing_policy")+ or {"policy": "legacy_unpinned"},**embedding_meta_fields(),}atomic_write_json(target / META_FILENAME, payload)@@ -254,5 +278,7 @@ __all__ = ["working_dir","has_output","meta_is_native_published",+ "latest_published_root",+ "read_published_policy","write_meta",]diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.pyindex 7736621b9..84fe4a682 100644--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@ -8,6 +8,12 @@ from types import SimpleNamespaceimport pytest+from deeptutor.multi_user.context import (+ get_current_user_or_none,+ reset_current_user,+ set_current_user,+)+from deeptutor.multi_user.models import CurrentUser, UserScopeimport deeptutor.services.config as config_modulefrom deeptutor.services.config.runtime_settings import RuntimeSettingsServicefrom deeptutor.services.rag.pipelines.ima.client import (@@ -811,6 +817,55 @@ def test_create_normalizes_uploaded_extension_to_lowercase(monkeypatch, tmp_pathassert (tmp_path / "knowledge_bases" / "kb-uppercase" / "raw" / "报告.pdf").exists()[email protected](("role", "fail"), [("user", False), ("admin", True)])+def test_initialization_task_installs_owner_scope_and_restores_caller(+ monkeypatch, tmp_path: Path, role: str, fail: bool+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ manager.config["knowledge_bases"]["kb"] = {"path": "kb", "status": "initializing"}+ raw_dir = manager.base_dir / "kb" / "raw"+ raw_dir.mkdir(parents=True)+ owner = CurrentUser(+ id=f"owner-{role}",+ username=f"owner-{role}",+ role=role,+ scope=UserScope(kind=role, user_id=f"owner-{role}", root=tmp_path / "owner"),+ )+ ambient = CurrentUser(+ id="ambient",+ username="ambient",+ role="user",+ scope=UserScope(kind="user", user_id="ambient", root=tmp_path / "ambient"),+ )++ async def process_documents():+ assert get_current_user_or_none() == owner+ if fail:+ raise RuntimeError("indexing failed")++ tracker = SimpleNamespace(task_id=None, update=lambda *_args, **_kwargs: None)+ initializer = SimpleNamespace(+ owner=owner,+ progress_tracker=tracker,+ kb_name="kb",+ base_dir=manager.base_dir,+ raw_dir=raw_dir,+ process_documents=process_documents,+ index_published=False,+ )+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ token = set_current_user(ambient)+ try:+ asyncio.run(+ knowledge_router_module.run_initialization_task(+ initializer, f"owner-scope-{role}-{fail}"+ )+ )+ assert get_current_user_or_none() == ambient+ finally:+ reset_current_user(token)++def test_upload_returns_409_when_kb_needs_reindex(monkeypatch, tmp_path: Path) -> None:manager = _FakeKBManager(tmp_path / "knowledge_bases")manager.config["knowledge_bases"]["legacy-kb"] = {@@ -1581,8 +1636,54 @@ def test_reindex_task_persists_completed_progress(monkeypatch, tmp_path: Path) -assert "embedding_mismatch" not in entry+def test_reindex_task_preserves_prepublication_failure(monkeypatch, tmp_path: Path) -> None:+ base_dir = tmp_path / "knowledge_bases"+ raw_dir = base_dir / "kb" / "raw"+ raw_dir.mkdir(parents=True)+ (raw_dir / "fixture.txt").write_text("fixture", encoding="utf-8")+ (base_dir / "kb_config.json").write_text(+ json.dumps(+ {+ "knowledge_bases": {+ "kb": {+ "path": "kb",+ "rag_provider": "lightrag",+ "status": "processing",+ }+ }+ }+ ),+ encoding="utf-8",+ )++ class _FailingRagService:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ async def initialize(self, *_args, **_kwargs) -> bool:+ raise RuntimeError("original indexing failure")++ rag_service_module = importlib.import_module("deeptutor.services.rag.service")+ monkeypatch.setattr(rag_service_module, "RAGService", _FailingRagService)+ task_id = knowledge_router_module._build_unique_task_id("kb_reindex", "prepublish-fail")++ asyncio.run(+ knowledge_router_module.run_reindex_task(+ kb_name="kb",+ base_dir=str(base_dir),+ task_id=task_id,+ signature_hash="lightrag",+ )+ )++ task = knowledge_router_module.TaskIDManager.get_instance().get_task_metadata(task_id)+ assert task is not None+ assert task["status"] == "error"+ assert task["error"] == "original indexing failure"++@pytest.mark.parametrize("failed_sink", ["progress_file", "central_config"])-def test_reindex_task_fails_closed_when_terminal_progress_is_not_persisted(+def test_reindex_task_does_not_report_a_published_version_as_failed_when_bookkeeping_fails(monkeypatch, tmp_path: Path, failed_sink: str) -> None:base_dir = tmp_path / "knowledge_bases"@@ -1659,13 +1760,16 @@ def test_reindex_task_fails_closed_when_terminal_progress_is_not_persisted(task = task_manager.get_task_metadata(task_id)assert task is not None- assert task["status"] == "error"- assert "terminal state" in task["error"]+ assert task["status"] == "completed"progress = json.loads((base_dir / "kb" / ".progress.json").read_text(encoding="utf-8"))- assert progress["stage"] == "error"persisted = json.loads((base_dir / "kb_config.json").read_text(encoding="utf-8"))entry = persisted["knowledge_bases"]["kb"]- assert entry["status"] == "error"+ if failed_sink == "progress_file":+ assert progress["stage"] != "error"+ assert entry["status"] == "ready"+ else:+ assert progress["stage"] == "completed"+ assert entry["status"] == "processing"assert entry["needs_reindex"] is Trueassert entry["embedding_mismatch"] == {"reason": "test"}@@ -2141,6 +2245,13 @@ def test_create_pageindex_oss_persists_optional_mode(monkeypatch, tmp_path: Pathdef test_create_mode_aware_kb_persists_per_kb_search_mode(monkeypatch, tmp_path: Path) -> None:manager = _FakeKBManager(tmp_path / "knowledge_bases")+ snapshot = SimpleNamespace(+ persisted_policy=lambda: {+ "policy": "pinned",+ "selection": {"profile_id": "profile-1", "model_id": "model-1"},+ "fingerprint": "a" * 64,+ }+ )monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)monkeypatch.setattr(knowledge_router_module, "KnowledgeBaseInitializer", _FakeInitializer)monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", tmp_path / "knowledge_bases")@@ -2148,6 +2259,11 @@ def test_create_mode_aware_kb_persists_per_kb_search_mode(monkeypatch, tmp_path:monkeypatch.setattr(preflight, "engine_preflight", lambda _provider: {"ok": True, "checks": []})lightrag_config = importlib.import_module("deeptutor.services.rag.pipelines.lightrag.config")monkeypatch.setattr(lightrag_config, "is_lightrag_available", lambda: True)+ monkeypatch.setattr(+ knowledge_router_module,+ "_freeze_default_indexing_llm",+ lambda: snapshot,+ )async def _noop_init_task(*_args, **_kwargs):return None@@ -2168,6 +2284,107 @@ def test_create_mode_aware_kb_persists_per_kb_search_mode(monkeypatch, tmp_path:assert manager.config["knowledge_bases"]["kb-light"]["search_mode"] == "hybrid"+def test_create_empty_lightrag_kb_persists_redacted_pending_policy(+ monkeypatch, tmp_path: Path+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ snapshot = SimpleNamespace(+ persisted_policy=lambda: {+ "policy": "pinned",+ "selection": {"profile_id": "profile-1", "model_id": "model-1"},+ "descriptor": {"model": "safe-model"},+ "fingerprint": "a" * 64,+ "vision_available": True,+ }+ )+ seen: list[str] = []++ def freeze_form(raw: str):+ seen.append(raw)+ return {"profile_id": "profile-1", "model_id": "model-1"}, snapshot++ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(knowledge_router_module, "KnowledgeBaseInitializer", _FakeInitializer)+ monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", manager.base_dir)+ monkeypatch.setattr(knowledge_router_module, "_assert_provider_ready", lambda _provider: None)+ monkeypatch.setattr(knowledge_router_module, "_freeze_indexing_llm_form", freeze_form)++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/knowledge-bases",+ data={+ "name": "kb-pending",+ "rag_provider": "lightrag",+ "indexing_llm": json.dumps({"profile_id": "profile-1", "model_id": "model-1"}),+ },+ )++ assert response.status_code == 200+ assert len(seen) == 1+ pending = manager.config["knowledge_bases"]["kb-pending"]["pending_indexing_policy"]+ assert pending["policy"] == "pending_pinned"+ assert pending["fingerprint"] == "a" * 64+ assert pending["selection"] == {"profile_id": "profile-1", "model_id": "model-1"}+ assert not list((manager.base_dir / "kb-pending").glob("version-*"))+++def test_create_rejects_indexing_selection_for_other_provider_before_registration(+ monkeypatch, tmp_path: Path+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", manager.base_dir)++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/knowledge-bases",+ data={+ "name": "wrong-provider",+ "rag_provider": "llamaindex",+ "indexing_llm": json.dumps({"profile_id": "profile-1", "model_id": "model-1"}),+ },+ )++ assert response.status_code == 400+ assert manager.config["knowledge_bases"] == {}+++def test_reindex_passes_frozen_lightrag_snapshot_to_background_task(+ monkeypatch, tmp_path: Path+) -> None:+ manager = _FakeKBManager(tmp_path / "knowledge_bases")+ manager.config["knowledge_bases"]["kb"] = {+ "path": "kb",+ "rag_provider": "lightrag",+ "status": "ready",+ }+ (manager.base_dir / "kb" / "raw").mkdir(parents=True)+ snapshot = object()+ captured: dict[str, object] = {}++ async def capture_task(*_args, **kwargs):+ captured.update(kwargs)++ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)+ monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", manager.base_dir)+ monkeypatch.setattr(knowledge_router_module, "_assert_provider_ready", lambda _provider: None)+ monkeypatch.setattr(+ knowledge_router_module,+ "_freeze_indexing_llm_form",+ lambda _raw: ({"profile_id": "profile-1", "model_id": "model-1"}, snapshot),+ )+ monkeypatch.setattr(knowledge_router_module, "run_reindex_task", capture_task)++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/knowledge-bases/kb/reindex",+ data={"indexing_llm": json.dumps({"profile_id": "profile-1", "model_id": "model-1"})},+ )++ assert response.status_code == 200+ assert captured["indexing_snapshot"] is snapshot++def test_create_pageindex_oss_rejects_non_pdf(monkeypatch, tmp_path: Path) -> None:manager = _FakeKBManager(tmp_path / "knowledge_bases")monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)diff --git a/tests/knowledge/test_document_adder_provider.py b/tests/knowledge/test_document_adder_provider.pyindex 4a100177b..680ba25ca 100644--- a/tests/knowledge/test_document_adder_provider.py+++ b/tests/knowledge/test_document_adder_provider.py@@ -23,17 +23,25 @@ def _write_provider_version(kb_dir: Path, provider: str) -> None:output_dir = version_dir / "output"output_dir.mkdir()(output_dir / "entities.parquet").write_bytes(b"placeholder")+ elif provider == "lightrag":+ (version_dir / "kv_store_doc_status.json").write_text(+ json.dumps({"doc": {"status": "processed", "chunks_list": ["chunk"]}}),+ encoding="utf-8",+ )else:(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(+ meta = {"provider": provider, "signature": provider, "version": "version-1"}+ if provider == "lightrag":+ meta.update({- "provider": provider,- "signature": provider,- "version": "version-1",+ "lightrag_adapter_schema": 2,+ "parser_bridge_schema": 1,+ "state": "published",}- ),+ )+ (version_dir / "meta.json").write_text(+ json.dumps(meta),encoding="utf-8",)@@ -70,6 +78,19 @@ def test_document_adder_preserves_explicit_bound_provider(tmp_path: Path) -> Nonassert adder.rag_provider == "graphrag"+def test_document_adder_allows_empty_lightrag_kb_to_bootstrap(tmp_path: Path) -> None:+ (tmp_path / "empty-kb").mkdir()++ adder = DocumentAdder(+ kb_name="empty-kb",+ base_dir=str(tmp_path),+ rag_provider="lightrag",+ )++ assert adder.rag_provider == "lightrag"+ assert adder.raw_dir.is_dir()++def test_process_new_documents_returns_failures_without_marking_processed(monkeypatch, tmp_path: Path) -> None:@@ -101,6 +122,37 @@ def test_process_new_documents_returns_failures_without_marking_processed(assert adder.get_ingested_hashes() == {}+def test_lightrag_hash_bookkeeping_failure_does_not_deny_published_success(+ monkeypatch, tmp_path: Path+) -> None:+ kb_dir = tmp_path / "kb"+ raw_dir = kb_dir / "raw"+ raw_dir.mkdir(parents=True)+ _write_provider_version(kb_dir, "lightrag")+ doc = raw_dir / "published.txt"+ doc.write_text("hello", encoding="utf-8")++ class _SuccessfulRagService:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ async def add_documents(self, *_args, **_kwargs) -> bool:+ return True++ monkeypatch.setattr("deeptutor.knowledge.add_documents.RAGService", _SuccessfulRagService)+ adder = DocumentAdder(kb_name="kb", base_dir=str(tmp_path), rag_provider="lightrag")+ monkeypatch.setattr(+ adder,+ "_record_successful_hash",+ lambda _path: (_ for _ in ()).throw(OSError("metadata unavailable")),+ )++ result = asyncio.run(adder.process_new_documents([doc]))++ assert result.processed_files == [doc]+ assert result.failures == []++def test_remove_raw_document_deletes_file_and_hash_without_index(tmp_path: Path,) -> None:diff --git a/tests/services/config/test_graphrag_lightrag_settings.py b/tests/services/config/test_graphrag_lightrag_settings.pyindex 9c13c6fc7..4cf3b4720 100644--- a/tests/services/config/test_graphrag_lightrag_settings.py+++ b/tests/services/config/test_graphrag_lightrag_settings.py@@ -81,20 +81,6 @@ def test_lightrag_indexing_knobs_round_trip_and_clamp(tmp_path: Path) -> None:assert clamped["response_type"] == "Multiple Paragraphs"-def test_lightrag_dedicated_llm_selection_round_trip(tmp_path: Path) -> None:- """Empty references mean the global model; a complete pair is preserved."""- svc = RuntimeSettingsService(tmp_path, process_env={})- assert svc.load_lightrag()["llm_profile_id"] == ""-- saved = svc.save_lightrag({"llm_profile_id": " profile-1 ", "llm_model_id": " model-1 "})- assert saved["llm_profile_id"] == "profile-1"- assert saved["llm_model_id"] == "model-1"-- cleared = svc.save_lightrag({"llm_profile_id": "", "llm_model_id": ""})- assert cleared["llm_profile_id"] == ""- assert cleared["llm_model_id"] == ""--def test_lightrag_settings_written_before_the_indexing_knobs_still_load(tmp_path: Path,) -> None:@@ -112,6 +98,20 @@ def test_lightrag_settings_written_before_the_indexing_knobs_still_load(assert loaded["llm_model_id"] == ""+def test_lightrag_dedicated_llm_selection_round_trip(tmp_path: Path) -> None:+ """Empty references mean the active model; a complete pair is preserved."""+ svc = RuntimeSettingsService(tmp_path, process_env={})+ assert svc.load_lightrag()["llm_profile_id"] == ""++ saved = svc.save_lightrag({"llm_profile_id": " profile-1 ", "llm_model_id": " model-1 "})+ assert saved["llm_profile_id"] == "profile-1"+ assert saved["llm_model_id"] == "model-1"++ cleared = svc.save_lightrag({"llm_profile_id": "", "llm_model_id": ""})+ assert cleared["llm_profile_id"] == ""+ assert cleared["llm_model_id"] == ""++def test_lightrag_server_defaults_round_trip_without_exposing_shape_drift(tmp_path: Path,) -> None:diff --git a/tests/services/llm/test_client.py b/tests/services/llm/test_client.pyindex 968035c24..53c18541c 100644--- a/tests/services/llm/test_client.py+++ b/tests/services/llm/test_client.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom _pytest.monkeypatch import MonkeyPatchimport pytest-from deeptutor.services.llm.client import LLMClient+from deeptutor.services.llm.client import LLMClient, build_model_func_for_configfrom deeptutor.services.llm.config import LLMConfig@@ -80,7 +80,7 @@ async def test_client_get_model_func_uses_factory(monkeypatch: MonkeyPatch) -> Ncaptured.update(kwargs)return "ok"- monkeypatch.setattr("deeptutor.services.llm.factory.complete", _fake_complete)+ monkeypatch.setattr("deeptutor.services.llm.factory.complete_with_config", _fake_complete)func = client.get_model_func()result = await func(@@ -90,6 +90,7 @@ async def test_client_get_model_func_uses_factory(monkeypatch: MonkeyPatch) -> N)assert result == "ok"+ assert captured["config"] is configassert captured["prompt"] == "hello"assert captured["system_prompt"] == "sys"assert captured["messages"] == [@@ -113,7 +114,7 @@ async def test_client_get_model_func_empty_history_uses_prompt(captured.update(kwargs)return "ok"- monkeypatch.setattr("deeptutor.services.llm.factory.complete", _fake_complete)+ monkeypatch.setattr("deeptutor.services.llm.factory.complete_with_config", _fake_complete)func = client.get_model_func()result = await func("hello", system_prompt="sys", history_messages=[])@@ -138,7 +139,7 @@ async def test_client_get_model_func_explicit_messages_override_prompt(captured.update(kwargs)return "ok"- monkeypatch.setattr("deeptutor.services.llm.factory.complete", _fake_complete)+ monkeypatch.setattr("deeptutor.services.llm.factory.complete_with_config", _fake_complete)messages = [{"role": "user", "content": "from messages"}]func = client.get_model_func()@@ -160,7 +161,7 @@ async def test_client_get_vision_model_func_uses_factory(monkeypatch: MonkeyPatccaptured.update(kwargs)return "ok"- monkeypatch.setattr("deeptutor.services.llm.factory.complete", _fake_complete)+ monkeypatch.setattr("deeptutor.services.llm.factory.complete_with_config", _fake_complete)func = client.get_vision_model_func()result = await func(@@ -173,3 +174,27 @@ async def test_client_get_vision_model_func_uses_factory(monkeypatch: MonkeyPatcassert captured["prompt"] == "hello"assert captured["messages"] == [{"role": "user", "content": "hi"}]assert captured["image_data"] == "abc123"+++async def test_explicit_config_model_func_does_not_mutate_process_environment(+ monkeypatch: MonkeyPatch,+) -> None:+ config = LLMConfig(+ model="snapshot-model",+ api_key="snapshot-key",+ base_url="https://snapshot.example.com/v1",+ )+ monkeypatch.setenv("OPENAI_API_KEY", "global-key")+ monkeypatch.setenv("OPENAI_BASE_URL", "https://global.example.com/v1")++ async def _fake_complete(**kwargs: object) -> str:+ assert kwargs["config"] is config+ return "ok"++ monkeypatch.setattr("deeptutor.services.llm.factory.complete_with_config", _fake_complete)++ func = build_model_func_for_config(config, allow_multimodal=False)+ assert await func("hello") == "ok"+ assert __import__("os").environ["OPENAI_API_KEY"] == "global-key"+ assert __import__("os").environ["OPENAI_BASE_URL"] == "https://global.example.com/v1"diff --git a/tests/services/llm/test_factory_provider_exec.py b/tests/services/llm/test_factory_provider_exec.pyindex 7234fccb3..39e4c2b55 100644--- a/tests/services/llm/test_factory_provider_exec.py+++ b/tests/services/llm/test_factory_provider_exec.py@@ -7,7 +7,7 @@ from typing import Anyimport pytestfrom deeptutor.services.llm.config import LLMConfig-from deeptutor.services.llm.factory import complete, stream+from deeptutor.services.llm.factory import complete, complete_with_config, streamfrom deeptutor.services.llm.provider_core.base import LLMResponse@@ -26,6 +26,10 @@ class _FakeProvider:self.stream_response = stream_response or LLMResponse(content=stream_chunk)self.stream_chunk = stream_chunkself.reasoning_chunk = reasoning_chunk+ self.closed = 0++ async def aclose(self) -> None:+ self.closed += 1async def chat_with_retry(self, **kwargs: Any) -> LLMResponse:self.complete_kwargs = kwargs@@ -155,6 +159,42 @@ async def test_explicit_call_inherits_matching_profile_headers_and_reasoning(assert provider.complete_kwargs["reasoning_effort"] == "minimal"+async def test_complete_with_config_never_resolves_or_merges_global_config(monkeypatch) -> None:+ snapshot = _make_cfg(extra_headers={}, reasoning_effort=None)+ provider = _FakeProvider()+ captured_config: dict[str, LLMConfig] = {}++ def _unexpected_resolver(**_kwargs: Any):+ raise AssertionError("explicit config path must not resolve global config")++ def _fake_build_isolated_provider(config: LLMConfig):+ captured_config["config"] = config+ return provider++ monkeypatch.setattr("deeptutor.services.llm.factory._resolve_call_config", _unexpected_resolver)+ monkeypatch.setattr("deeptutor.services.llm.factory.get_llm_config", _unexpected_resolver)+ monkeypatch.setattr("deeptutor.services.llm.factory._resolve_provider_spec", lambda **_: None)+ monkeypatch.setattr(+ "deeptutor.services.llm.factory.build_isolated_provider",+ _fake_build_isolated_provider,+ )++ assert await complete_with_config(snapshot, "hello") == "ok"+ assert captured_config["config"] is snapshot+ assert captured_config["config"].extra_headers == {}+ assert provider.complete_kwargs["reasoning_effort"] is None+ assert provider.closed == 1+++async def test_complete_with_config_rejects_identity_overrides() -> None:+ snapshot = _make_cfg()++ with pytest.raises(TypeError, match="reasoning_effort"):+ await complete_with_config(snapshot, "hello", reasoning_effort="high")++@pytest.mark.asyncioasync def test_stream_does_not_replay_reasoning_as_final_content(monkeypatch) -> None:cfg = _make_cfg()diff --git a/tests/services/llm/test_provider_pool.py b/tests/services/llm/test_provider_pool.pyindex 6464abc90..be282f9ba 100644--- a/tests/services/llm/test_provider_pool.py+++ b/tests/services/llm/test_provider_pool.py@@ -59,6 +59,24 @@ async def test_runtime_provider_reuses_identical_config(monkeypatch) -> None:assert provider_factory.runtime_provider_pool_size() == 1+def test_isolated_provider_disables_environment_setup_and_skips_pool(monkeypatch) -> None:+ captured: dict[str, Any] = {}+ provider = _FakeProvider()++ def _build(config: LLMConfig, *, configure_env: bool = True) -> _FakeProvider:+ captured["config"] = config+ captured["configure_env"] = configure_env+ return provider++ monkeypatch.setattr(provider_factory, "_build_runtime_provider", _build)++ result = provider_factory.build_isolated_provider(_config())++ assert result is provider+ assert captured["configure_env"] is False+ assert provider_factory.runtime_provider_pool_size() == 0++@pytest.mark.asyncioasync def test_runtime_provider_pool_is_bounded_and_closes_evictions(monkeypatch) -> None:built: list[_FakeProvider] = []diff --git a/tests/services/rag/test_lightrag_indexing_policy.py b/tests/services/rag/test_lightrag_indexing_policy.pynew file mode 100644index 000000000..bed6ae302--- /dev/null+++ b/tests/services/rag/test_lightrag_indexing_policy.py@@ -0,0 +1,214 @@+from __future__ import annotations++import json+from pathlib import Path++import pytest++from deeptutor.multi_user.models import CurrentUser, UserScope+from deeptutor.services.llm.config import LLMConfig+from deeptutor.services.rag.pipelines.lightrag import indexing_policy, storage+++def _user(tmp_path: Path) -> CurrentUser:+ return CurrentUser(+ id="user-1",+ username="person",+ role="user",+ scope=UserScope(kind="user", user_id="user-1", root=tmp_path / "workspace"),+ )+++def _config(*, key: str = "secret-a", reasoning: str | None = "high") -> LLMConfig:+ return LLMConfig(+ model="model-v1",+ api_key=key,+ base_url="https://name:[email protected]/v1?token=secret",+ binding="openai",+ provider_name="openai",+ api_version="2026-01-01",+ reasoning_effort=reasoning,+ extra_headers={"Authorization": "private"},+ )+++def _freeze(monkeypatch, tmp_path: Path, config: LLMConfig):+ monkeypatch.setattr(indexing_policy, "get_current_user_or_none", lambda: _user(tmp_path))+ monkeypatch.setattr(indexing_policy, "apply_allowed_llm_selection", lambda value: value)+ monkeypatch.setattr(+ indexing_policy, "resolve_llm_config_for_selection", lambda _selection: config+ )+ monkeypatch.setattr(indexing_policy, "supports_vision", lambda binding, model: True)+ return indexing_policy.freeze_snapshot(+ {"profile_id": "profile-1", "model_id": "model-1", "reasoning_effort": "high"}+ )+++def test_fingerprint_excludes_credentials_and_endpoint_secrets(monkeypatch, tmp_path: Path) -> None:+ first = _freeze(monkeypatch, tmp_path, _config(key="secret-a"))+ second = _freeze(monkeypatch, tmp_path, _config(key="secret-b"))++ assert first.fingerprint == second.fingerprint+ serialized = json.dumps(first.persisted_policy(), sort_keys=True)+ assert "secret" not in serialized+ assert "password" not in serialized+ assert "Authorization" not in serialized+ assert "user-1" not in serialized+ assert first.descriptor["endpoint"] == "https://example.test/v1"+++def test_reasoning_drift_changes_fingerprint_and_blocks_append(monkeypatch, tmp_path: Path) -> None:+ original = _freeze(monkeypatch, tmp_path, _config(reasoning="high"))+ drifted = _config(reasoning=None)+ monkeypatch.setattr(+ indexing_policy, "resolve_llm_config_for_selection", lambda _selection: drifted+ )++ with pytest.raises(indexing_policy.IndexingModelChangedError, match="full re-index"):+ indexing_policy.snapshot_from_persisted(original.persisted_policy())+++def test_reasoning_none_and_literal_none_have_distinct_identity(+ monkeypatch, tmp_path: Path+) -> None:+ unset = _freeze(monkeypatch, tmp_path, _config(reasoning=None))+ literal_none = _freeze(monkeypatch, tmp_path, _config(reasoning="none"))++ assert unset.fingerprint != literal_none.fingerprint+ assert unset.descriptor["reasoning_effort"] is None+ assert literal_none.descriptor["reasoning_effort"] == "none"+++def test_vision_capability_drift_changes_fingerprint_and_blocks_append(+ monkeypatch, tmp_path: Path+) -> None:+ original = _freeze(monkeypatch, tmp_path, _config())+ assert original.vision_available is True+ assert original.descriptor["vision_available"] is True+ monkeypatch.setattr(indexing_policy, "supports_vision", lambda _binding, _model: False)++ with pytest.raises(indexing_policy.IndexingModelChangedError, match="full re-index"):+ indexing_policy.snapshot_from_persisted(original.persisted_policy())+++def test_published_policy_wins_over_residual_pending(tmp_path: Path) -> None:+ kb_dir = tmp_path / "kb"+ version = kb_dir / "version-1"+ version.mkdir(parents=True)+ (version / "kv_store_doc_status.json").write_text(+ json.dumps({"doc": {"status": "processed", "chunks_list": ["chunk"]}}),+ encoding="utf-8",+ )+ published = {+ "policy": "pinned",+ "selection": {"profile_id": "published", "model_id": "model"},+ "fingerprint": "a" * 64,+ }+ (version / "meta.json").write_text(+ json.dumps(+ {+ "provider": "lightrag",+ "signature": "lightrag",+ "lightrag_adapter_schema": storage.ADAPTER_SCHEMA,+ "parser_bridge_schema": 1,+ "state": "published",+ "indexing_policy": published,+ }+ ),+ encoding="utf-8",+ )+ (tmp_path / "kb_config.json").write_text(+ json.dumps(+ {+ "knowledge_bases": {+ "kb": {+ "path": "kb",+ "pending_indexing_policy": {+ "policy": "pending_pinned",+ "selection": {"profile_id": "pending", "model_id": "model"},+ },+ }+ }+ }+ ),+ encoding="utf-8",+ )++ assert (+ indexing_policy.effective_policy(kb_dir, base_dir=str(tmp_path), kb_name="kb") == published+ )+++def test_owner_bound_model_requires_explicit_scope(monkeypatch) -> None:+ monkeypatch.setattr(indexing_policy, "get_current_user_or_none", lambda: None)+ monkeypatch.setattr(indexing_policy, "apply_allowed_llm_selection", lambda value: value)+ monkeypatch.setattr(+ indexing_policy,+ "resolve_llm_config_for_selection",+ lambda _selection: LLMConfig(+ model="gpt",+ api_key="",+ binding="openai_codex",+ provider_name="openai_codex",+ ),+ )++ with pytest.raises(indexing_policy.IndexingPolicyError, match="explicit initiating user"):+ indexing_policy.freeze_snapshot({"profile_id": "personal", "model_id": "gpt"})+++def test_default_snapshot_prefers_released_lightrag_selection(monkeypatch) -> None:+ from deeptutor.services.rag.pipelines.lightrag import config++ selection = {"profile_id": "dedicated", "model_id": "indexer"}+ expected = object()+ calls: list[tuple[object, str | None, bool]] = []+ monkeypatch.setattr(config, "lightrag_indexing_selection_from_settings", lambda: selection)+ monkeypatch.setattr(+ indexing_policy,+ "freeze_snapshot",+ lambda value, *, policy=None, require_explicit_user=True: (+ calls.append((value, policy, require_explicit_user)) or expected+ ),+ )++ assert indexing_policy.freeze_default_snapshot() is expected+ assert calls == [(selection, indexing_policy.POLICY_PINNED, False)]+++def test_default_snapshot_rejects_unreadable_released_setting(monkeypatch) -> None:+ from deeptutor.services.rag.pipelines.lightrag import config++ def fail():+ raise OSError("settings unreadable")++ monkeypatch.setattr(config, "lightrag_indexing_selection_from_settings", fail)++ with pytest.raises(indexing_policy.IndexingPolicyError, match="could not be resolved"):+ indexing_policy.freeze_default_snapshot()+++def test_latest_published_root_ignores_newer_unpublished_candidate(tmp_path: Path) -> None:+ kb_dir = tmp_path / "kb"+ published = kb_dir / "version-1"+ candidate = kb_dir / "version-2"+ for root in (published, candidate):+ root.mkdir(parents=True)+ (root / "kv_store_doc_status.json").write_text(+ json.dumps({"doc": {"status": "processed", "chunks_list": ["chunk"]}}),+ encoding="utf-8",+ )+ (published / "meta.json").write_text(+ json.dumps(+ {+ "provider": "lightrag",+ "signature": "lightrag",+ "lightrag_adapter_schema": storage.ADAPTER_SCHEMA,+ "parser_bridge_schema": 1,+ "state": "published",+ }+ ),+ encoding="utf-8",+ )++ assert storage.latest_published_root(kb_dir) == publisheddiff --git a/tests/services/rag/test_lightrag_pipeline.py b/tests/services/rag/test_lightrag_pipeline.pyindex 3e82371ef..a1dc03be0 100644--- a/tests/services/rag/test_lightrag_pipeline.py+++ b/tests/services/rag/test_lightrag_pipeline.py@@ -10,11 +10,17 @@ import typesimport pytest+from deeptutor.multi_user.context import (+ get_current_user_or_none,+ reset_current_user,+ set_current_user,+)+from deeptutor.multi_user.models import CurrentUser, UserScopefrom deeptutor.services.llm.exceptions import LLMAPIError, LLMAuthenticationErrorfrom deeptutor.services.parsing.types import ParsedDocumentfrom deeptutor.services.rag.factory import get_pipeline, list_pipelines, normalize_provider_namefrom deeptutor.services.rag.index_versioning import list_kb_versions-from deeptutor.services.rag.pipelines.lightrag import config, engine, storage+from deeptutor.services.rag.pipelines.lightrag import config, engine, indexing_policy, storagefrom deeptutor.services.rag.pipelines.lightrag.ingress import (IngressError,bundles_root,@@ -52,6 +58,13 @@ class _Bridge:return await value if inspect.isawaitable(value) else value+def _indexing_snapshot():+ return types.SimpleNamespace(+ vision_available=True,+ persisted_policy=lambda: {"policy": "pinned", "fingerprint": "a" * 64},+ )++def test_factory_routes_without_importing_optional_sdk(tmp_path: Path, monkeypatch) -> None:sys.modules.pop("lightrag", None)pipeline = get_pipeline("lightrag", kb_base_dir=str(tmp_path))@@ -83,71 +96,139 @@ def test_availability_checks_native_lightrag_module(monkeypatch) -> None:assert seen == ["lightrag"]-def test_lightrag_llm_selection_requires_both_catalog_ids(monkeypatch) -> None:- settings_cases = [+ ("settings", "expected"),+ [({}, None),- ({"llm_profile_id": "p", "llm_model_id": "m"}, {"profile_id": "p", "model_id": "m"}),- ({"llm_profile_id": "p", "llm_model_id": ""}, None),- ({"llm_profile_id": "", "llm_model_id": "m"}, None),- ]- for settings, expected in settings_cases:- monkeypatch.setattr(- "deeptutor.services.config.load_lightrag_settings",- lambda settings=settings: settings,- )- assert config.lightrag_llm_selection_from_settings() == expected+ (+ {"llm_profile_id": " profile ", "llm_model_id": " model "},+ {"profile_id": "profile", "model_id": "model"},+ ),+ ({"llm_profile_id": "profile", "llm_model_id": ""}, None),+ ],+)+def test_released_lightrag_query_selection_keeps_fallback_contract(+ monkeypatch, settings, expected+) -> None:+ monkeypatch.setattr("deeptutor.services.config.load_lightrag_settings", lambda: settings)+ assert config.lightrag_llm_selection_from_settings() == expected-def test_lightrag_llm_adapter_resolves_dedicated_catalog_selection(monkeypatch) -> None:- class Client:- def __init__(self, *, config, configure_env) -> None:- assert config is selected_config- assert configure_env is False- def get_model_func(self):- async def model_func(_prompt, **kwargs):- assert kwargs["max_retries"] == 0- return "ok"+def test_indexing_selection_rejects_partial_released_setting(monkeypatch) -> None:+ monkeypatch.setattr(+ "deeptutor.services.config.load_lightrag_settings",+ lambda: {"llm_profile_id": "profile", "llm_model_id": ""},+ )- return model_func+ with pytest.raises(ValueError, match="incomplete"):+ config.lightrag_indexing_selection_from_settings()+++def test_query_model_resolver_falls_back_only_when_selected_entry_is_missing(+ monkeypatch,+) -> None:+ selection = {"profile_id": "profile", "model_id": "model"}+ fallback = object()+ calls: list[object] = []+ monkeypatch.setattr(config, "lightrag_llm_selection_from_settings", lambda: selection)++ def resolve(value):+ calls.append(value)+ if value is selection:+ raise ValueError("missing")+ return fallback- selected_config = object()monkeypatch.setattr("deeptutor.services.model_selection.runtime.resolve_llm_config_for_selection",- lambda selection: selected_config,+ resolve,)- monkeypatch.setattr("deeptutor.services.llm.client.LLMClient", Client)- adapter = config.build_llm_model_func(llm_selection={"profile_id": "p", "model_id": "m"})+ assert config.resolve_lightrag_query_llm_config() is fallback+ assert calls == [selection, None]+++def test_lightrag_llm_adapter_uses_explicit_snapshot_config(monkeypatch) -> None:+ def build_model(config, *, allow_multimodal):+ assert config is selected_config+ assert allow_multimodal is False++ async def model_func(_prompt, **kwargs):+ assert kwargs["max_retries"] == 0+ return "ok"++ return model_func++ selected_config = object()+ monkeypatch.setattr("deeptutor.services.llm.client.build_model_func_for_config", build_model)++ adapter = config.build_llm_model_func(llm_config=selected_config)assert asyncio.run(adapter("prompt")) == "ok"-def test_lightrag_vision_adapter_resolves_dedicated_catalog_selection(monkeypatch) -> None:- class Client:- def __init__(self, *, config, configure_env) -> None:- assert config is selected_config- assert configure_env is False+def test_lightrag_vision_adapter_uses_explicit_snapshot_config(monkeypatch) -> None:+ def build_model(config, *, allow_multimodal):+ assert config is selected_config+ assert allow_multimodal is True- def get_vision_model_func(self):- async def model_func(_prompt, **kwargs):- assert kwargs["allow_image_fallback"] is False- assert kwargs["image_data"] == "sentinel"- return "ok"+ async def model_func(_prompt, **kwargs):+ assert kwargs["allow_image_fallback"] is False+ assert kwargs["image_data"] == "sentinel"+ return "ok"- return model_func+ return model_funcselected_config = object()- monkeypatch.setattr(- "deeptutor.services.model_selection.runtime.resolve_llm_config_for_selection",- lambda selection: selected_config,- )- monkeypatch.setattr("deeptutor.services.llm.client.LLMClient", Client)+ monkeypatch.setattr("deeptutor.services.llm.client.build_model_func_for_config", build_model)- adapter = config.build_vision_model_func(llm_selection={"profile_id": "p", "model_id": "m"})+ adapter = config.build_vision_model_func(llm_config=selected_config)assert asyncio.run(adapter("prompt", image_inputs=[{"base64": "sentinel"}])) == "ok"-def test_build_rag_keeps_dedicated_llm_selection_out_of_embedding_kwargs([email protected]("role", ["user", "admin"])[email protected]("fail", [False, True])+def test_explicit_adapter_installs_owner_scope_and_restores_ambient_scope(+ monkeypatch, tmp_path: Path, role: str, fail: bool+) -> None:+ owner = CurrentUser(+ id=f"owner-{role}",+ username=f"owner-{role}",+ role=role,+ scope=UserScope(kind=role, user_id=f"owner-{role}", root=tmp_path / "owner"),+ )+ ambient = CurrentUser(+ id="ambient",+ username="ambient",+ role="user",+ scope=UserScope(kind="user", user_id="ambient", root=tmp_path / "ambient"),+ )++ def build_model(_config, *, allow_multimodal):+ assert allow_multimodal is False++ async def model_func(_prompt, **_kwargs):+ assert get_current_user_or_none() == owner+ if fail:+ raise RuntimeError("provider failed")+ return "ok"++ return model_func++ monkeypatch.setattr("deeptutor.services.llm.client.build_model_func_for_config", build_model)+ adapter = config.build_llm_model_func(llm_config=object(), owner=owner)+ token = set_current_user(ambient)+ try:+ if fail:+ with pytest.raises(RuntimeError, match="provider failed"):+ asyncio.run(adapter("prompt"))+ else:+ assert asyncio.run(adapter("prompt")) == "ok"+ assert get_current_user_or_none() == ambient+ finally:+ reset_current_user(token)+++def test_build_rag_keeps_indexing_snapshot_out_of_embedding_kwargs(monkeypatch, tmp_path: Path) -> None:"""The 1.6 native adapter must not pass LLM-only kwargs to embedding."""@@ -159,7 +240,12 @@ def test_build_rag_keeps_dedicated_llm_selection_out_of_embedding_kwargs(fake_lightrag = types.ModuleType("lightrag")fake_lightrag.__path__ = [] # type: ignore[attr-defined]fake_roles = types.ModuleType("lightrag.llm_roles")- fake_roles.RoleLLMConfig = object # type: ignore[attr-defined]++ class RoleLLMConfig:+ def __init__(self, **kwargs) -> None:+ self.__dict__.update(kwargs)++ fake_roles.RoleLLMConfig = RoleLLMConfig # type: ignore[attr-defined]monkeypatch.setitem(sys.modules, "lightrag", fake_lightrag)monkeypatch.setitem(sys.modules, "lightrag.llm_roles", fake_roles)monkeypatch.setattr(engine, "_require_exact_version", lambda: None)@@ -167,8 +253,9 @@ def test_build_rag_keeps_dedicated_llm_selection_out_of_embedding_kwargs(monkeypatch.setattr(engine, "_controlled_class", lambda: NativeLightRag)monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)- selection = {"profile_id": "profile-1", "model_id": "model-1"}- monkeypatch.setattr(engine, "lightrag_llm_selection_from_settings", lambda: selection)+ query_config = types.SimpleNamespace(binding="openai")+ monkeypatch.setattr(engine, "resolve_lightrag_query_llm_config", lambda: query_config)+ monkeypatch.setattr(indexing_policy, "cache_identity_for_config", lambda _config: "query-id")llm_calls: list[dict[str, object]] = []embedding_calls: list[object] = []@@ -185,7 +272,7 @@ def test_build_rag_keeps_dedicated_llm_selection_out_of_embedding_kwargs(rag = engine.build_rag(tmp_path)- assert llm_calls == [{"llm_selection": selection}]+ assert llm_calls == [{"llm_config": query_config}]assert embedding_calls == [None]assert rag.kwargs["embedding_func"] == "embedding"@@ -401,7 +488,9 @@ def test_preparse_runs_once_and_bundle_ignores_later_parser_drift(monkeypatch.setattr("deeptutor.services.parsing.get_parse_service", ParseService)monkeypatch.setattr(config, "vision_model_available", lambda: False)pipeline = LightRagPipeline(kb_base_dir=str(tmp_path / "kb"))- staged, failures = pipeline._stage_documents(tmp_path / "version-1", [str(source)])+ staged, failures = pipeline._stage_documents(+ tmp_path / "version-1", [str(source)], vision_available=True+ )source.write_text("changed after staging", encoding="utf-8")manifest, bundle = load_verified_bundle(tmp_path / "version-1", "source.md")@@ -536,6 +625,207 @@ def test_flat_schema_two_candidate_fails_closed_until_published(tmp_path: Path)assert list_kb_versions(tmp_path)[0]["ready"] is True+def _write_published_version(root: Path, *, indexing_policy_value: dict | None = None) -> None:+ root.mkdir(parents=True)+ (root / "kv_store_doc_status.json").write_text(+ json.dumps({"doc": {"status": "processed", "chunks_list": ["chunk"]}}),+ encoding="utf-8",+ )+ (root / "meta.json").write_text(+ json.dumps(+ {+ "provider": "lightrag",+ "signature": "lightrag",+ "lightrag_adapter_schema": storage.ADAPTER_SCHEMA,+ "parser_bridge_schema": 1,+ "state": "published",+ "indexing_policy": indexing_policy_value or {"policy": "legacy_unpinned"},+ }+ ),+ encoding="utf-8",+ )+++def test_rebuild_failure_before_index_output_keeps_previous_published_version(+ tmp_path: Path, monkeypatch+) -> None:+ kb_dir = tmp_path / "kb"+ old = kb_dir / "version-1"+ _write_published_version(old)+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ async def fail_before_output(*_args, **_kwargs):+ raise RuntimeError("indexing failed")++ monkeypatch.setattr(pipeline, "_run_indexing", fail_before_output)++ with pytest.raises(RuntimeError, match="indexing failed"):+ asyncio.run(+ pipeline.initialize(+ "kb",+ [str(tmp_path / "doc.md")],+ indexing_snapshot=_indexing_snapshot(),+ )+ )++ assert storage.latest_published_root(kb_dir) == old+ assert not (kb_dir / "version-2").exists()+++def test_atomic_meta_failure_leaves_new_candidate_unpublished(tmp_path: Path, monkeypatch) -> None:+ kb_dir = tmp_path / "kb"+ old = kb_dir / "version-1"+ _write_published_version(old)+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ async def finish_index(root: Path, *_args, **_kwargs):+ (root / "kv_store_doc_status.json").write_text(+ json.dumps({"new": {"status": "processed", "chunks_list": ["chunk"]}}),+ encoding="utf-8",+ )+ return BatchOutcome(+ requested=1,+ accepted=1,+ processed=("doc.md",),+ indexing_policy={"policy": "legacy_unpinned"},+ )++ def fail_meta(*_args, **_kwargs):+ raise OSError("atomic publication failed")++ monkeypatch.setattr(pipeline, "_run_indexing", finish_index)+ monkeypatch.setattr(storage, "write_meta", fail_meta)++ with pytest.raises(OSError, match="atomic publication failed"):+ asyncio.run(+ pipeline.initialize(+ "kb",+ [str(tmp_path / "doc.md")],+ indexing_snapshot=_indexing_snapshot(),+ )+ )++ candidate = kb_dir / "version-2"+ assert candidate.is_dir()+ assert not (candidate / "meta.json").exists()+ assert storage.latest_published_root(kb_dir) == old+++def test_append_metadata_refresh_failure_preserves_published_success(+ tmp_path: Path, monkeypatch+) -> None:+ kb_dir = tmp_path / "kb"+ published = kb_dir / "version-1"+ _write_published_version(+ published,+ indexing_policy_value={+ "policy": "pinned",+ "selection": {"profile_id": "profile", "model_id": "model"},+ "fingerprint": "a" * 64,+ },+ )+ original_meta = (published / "meta.json").read_bytes()+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ async def finish_index(*_args, **_kwargs):+ return BatchOutcome(+ requested=1,+ accepted=1,+ processed=("doc.md",),+ indexing_policy={"policy": "legacy_unpinned"},+ )++ monkeypatch.setattr(pipeline, "_run_indexing", finish_index)+ monkeypatch.setattr(+ indexing_policy,+ "snapshot_from_persisted",+ lambda _policy: _indexing_snapshot(),+ )+ monkeypatch.setattr(+ storage,+ "write_meta",+ lambda *_args, **_kwargs: (_ for _ in ()).throw(OSError("metadata unavailable")),+ )++ assert asyncio.run(pipeline.add_documents("kb", [str(tmp_path / "doc.md")])) is True+ assert (published / "meta.json").read_bytes() == original_meta+++def test_append_rejects_legacy_unpinned_index_before_mutation(tmp_path: Path, monkeypatch) -> None:+ published = tmp_path / "kb" / "version-1"+ _write_published_version(published)+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ async def unexpected(*_args, **_kwargs):+ raise AssertionError("legacy append must not reach indexing")++ monkeypatch.setattr(pipeline, "_run_indexing", unexpected)++ with pytest.raises(indexing_policy.IndexingModelChangedError, match="full re-index"):+ asyncio.run(pipeline.add_documents("kb", [str(tmp_path / "doc.md")]))+++def test_append_rejects_explicit_indexing_snapshot_before_mutation(+ tmp_path: Path, monkeypatch+) -> None:+ published = tmp_path / "kb" / "version-1"+ _write_published_version(published)+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ async def unexpected(*_args, **_kwargs):+ raise AssertionError("append must not reach indexing")++ monkeypatch.setattr(pipeline, "_run_indexing", unexpected)++ with pytest.raises(indexing_policy.IndexingPolicyError, match="full re-index"):+ asyncio.run(+ pipeline.add_documents(+ "kb",+ [str(tmp_path / "doc.md")],+ indexing_snapshot=_indexing_snapshot(),+ )+ )+++def test_pending_policy_drift_fails_before_creating_a_version(tmp_path: Path, monkeypatch) -> None:+ kb_dir = tmp_path / "kb"+ kb_dir.mkdir()+ (tmp_path / "kb_config.json").write_text(+ json.dumps(+ {+ "knowledge_bases": {+ "kb": {+ "path": "kb",+ "pending_indexing_policy": {+ "policy": "pending_pinned",+ "selection": {"profile_id": "profile", "model_id": "model"},+ "fingerprint": "a" * 64,+ },+ }+ }+ }+ ),+ encoding="utf-8",+ )+ pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ def changed(_policy):+ raise indexing_policy.IndexingModelChangedError("reindex required")++ monkeypatch.setattr(indexing_policy, "snapshot_from_persisted", changed)++ with pytest.raises(indexing_policy.IndexingModelChangedError):+ asyncio.run(pipeline.initialize("kb", [str(tmp_path / "doc.md")]))++ assert not any(kb_dir.glob("version-*"))++def test_schema_two_metadata_without_processed_workspace_output_is_not_ready(tmp_path: Path,) -> None:@@ -616,8 +906,28 @@ def test_indexing_initializes_processes_reconciles_and_finalizes(rag = Rag()pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))- monkeypatch.setattr(pipeline, "_stage_documents", lambda *_args: ([staged], {}))- monkeypatch.setattr(engine, "build_rag", lambda *_args, **_kwargs: rag)+ snapshot = _indexing_snapshot()+ freeze_calls = 0++ def freeze_default():+ nonlocal freeze_calls+ freeze_calls += 1+ return snapshot++ def stage(*_args, **kwargs):+ assert kwargs["vision_available"] is True+ return [staged], {}++ def build(*_args, **kwargs):+ assert kwargs["indexing_snapshot"] is snapshot+ return rag++ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.pipeline.freeze_default_snapshot",+ freeze_default,+ )+ monkeypatch.setattr(pipeline, "_stage_documents", stage)+ monkeypatch.setattr(engine, "build_rag", build)async def initialize(_rag):events.append("initialize")@@ -637,6 +947,8 @@ def test_indexing_initializes_processes_reconciles_and_finalizes(outcome = asyncio.run(pipeline._run_indexing(tmp_path, ["doc.pdf"], None))assert outcome.complete is True+ assert freeze_calls == 1+ assert outcome.indexing_policy == {"policy": "pinned", "fingerprint": "a" * 64}assert events == ["initialize", "enqueue", "process", ("finalize", False)]@@ -660,7 +972,7 @@ def test_partial_failure_is_typed_and_finalizes_with_cancellation(}pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))- monkeypatch.setattr(pipeline, "_stage_documents", lambda *_args: ([staged], {}))+ monkeypatch.setattr(pipeline, "_stage_documents", lambda *_args, **_kwargs: ([staged], {}))monkeypatch.setattr(engine, "build_rag", lambda *_args, **_kwargs: Rag())async def no_op(*_args, **_kwargs):@@ -677,7 +989,7 @@ def test_partial_failure_is_typed_and_finalizes_with_cancellation(monkeypatch.setattr(engine, "finalize", finalize)with pytest.raises(LightRagBatchError) as caught:- asyncio.run(pipeline._run_indexing(tmp_path, ["bad.pdf"], None))+ asyncio.run(pipeline._run_indexing(tmp_path, ["bad.pdf"], None, _indexing_snapshot()))assert caught.value.outcome.failed == {"bad.pdf": "parse failed"}assert events == [("finalize", True)]@@ -710,7 +1022,7 @@ def test_pre_acceptance_failure_removes_ingress_and_allows_same_name_retry(pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))- def stage(_working, paths):+ def stage(_working, paths, **_kwargs):staged = freeze_document(working,Path(paths[0]),@@ -738,12 +1050,14 @@ def test_pre_acceptance_failure_removes_ingress_and_allows_same_name_retry(monkeypatch.setattr(engine, "finalize", finalize)with pytest.raises(RuntimeError, match=failure_stage):- asyncio.run(pipeline._run_indexing(working, [str(source)], None))+ asyncio.run(pipeline._run_indexing(working, [str(source)], None, _indexing_snapshot()))assert not (pending_root(working) / "doc.md").exists()assert not (bundles_root(working) / "doc.md.bundle").exists()attempt = 1- outcome = asyncio.run(pipeline._run_indexing(working, [str(source)], None))+ outcome = asyncio.run(+ pipeline._run_indexing(working, [str(source)], None, _indexing_snapshot())+ )assert outcome.complete is True@@ -768,7 +1082,7 @@ def test_enqueue_partial_commit_removes_only_confirmed_unaccepted_ingress(pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))- def stage(_working, paths):+ def stage(_working, paths, **_kwargs):return [freeze_document(working,@@ -792,7 +1106,14 @@ def test_enqueue_partial_commit_removes_only_confirmed_unaccepted_ingress(monkeypatch.setattr(engine, "finalize", no_op)with pytest.raises(RuntimeError, match="partially committed"):- asyncio.run(pipeline._run_indexing(working, [str(path) for path in sources], None))+ asyncio.run(+ pipeline._run_indexing(+ working,+ [str(path) for path in sources],+ None,+ _indexing_snapshot(),+ )+ )assert len(status_reads) == 1assert status_reads[0][1] is True@@ -819,7 +1140,7 @@ def test_enqueue_status_read_failure_retains_all_ingress(tmp_path: Path, monkeyppipeline = LightRagPipeline(kb_base_dir=str(tmp_path))- def stage(_working, paths):+ def stage(_working, paths, **_kwargs):return [freeze_document(working,@@ -841,7 +1162,7 @@ def test_enqueue_status_read_failure_retains_all_ingress(tmp_path: Path, monkeypmonkeypatch.setattr(engine, "finalize", no_op)with pytest.raises(ValueError, match="enqueue failed"):- asyncio.run(pipeline._run_indexing(working, [str(source)], None))+ asyncio.run(pipeline._run_indexing(working, [str(source)], None, _indexing_snapshot()))assert (pending_root(working) / "doc.md").is_file()assert (bundles_root(working) / "doc.md.bundle").is_dir()@@ -866,7 +1187,7 @@ def test_public_initial_ingestion_retains_uncertain_ingress(pipeline = LightRagPipeline(kb_base_dir=str(tmp_path / "knowledge-bases"))- def stage(working, paths):+ def stage(working, paths, **_kwargs):nonlocal staged_workingstaged_working = workingreturn [@@ -891,7 +1212,16 @@ def test_public_initial_ingestion_retains_uncertain_ingress(monkeypatch.setattr(engine, "finalize", no_op)with pytest.raises(ValueError, match="original enqueue failure"):- asyncio.run(getattr(pipeline, operation)("kb", [str(source)]))+ asyncio.run(+ getattr(pipeline, operation)(+ "kb",+ [str(source)],+ indexing_snapshot=types.SimpleNamespace(+ vision_available=True,+ persisted_policy=lambda: {"policy": "legacy_unpinned"},+ ),+ )+ )assert staged_working is not Noneassert (pending_root(staged_working) / "doc.md").is_file()@@ -940,7 +1270,12 @@ def test_append_rejects_corrupt_or_unpublished_existing_version(monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)with pytest.raises(LightRagNeedsReindexError, match="unpublished, or corrupt"):- asyncio.run(pipeline.add_documents("kb", [str(tmp_path / "new.md")]))+ asyncio.run(+ pipeline.add_documents(+ "kb",+ [str(tmp_path / "new.md")],+ )+ )assert not (tmp_path / "kb" / "version-2").exists()assert {@@ -954,11 +1289,7 @@ def test_search_failure_is_not_reported_as_empty_success(tmp_path: Path, monkeyproot = tmp_path / "version-1"root.mkdir()pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))- monkeypatch.setattr(- "deeptutor.services.rag.pipelines.lightrag.pipeline.resolve_storage_dir_for_read",- lambda *_args: root,- )- monkeypatch.setattr(storage, "meta_is_native_published", lambda _root: True)+ monkeypatch.setattr(storage, "latest_published_root", lambda _kb_dir: root)monkeypatch.setattr(pipeline, "_resolve_mode", lambda *_args: "hybrid")monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)monkeypatch.setattr(engine, "build_rag", lambda *_args, **_kwargs: object())diff --git a/tests/services/rag/test_lightrag_settings_wiring.py b/tests/services/rag/test_lightrag_settings_wiring.pyindex a72c2ca99..4b9f7ad0d 100644--- a/tests/services/rag/test_lightrag_settings_wiring.py+++ b/tests/services/rag/test_lightrag_settings_wiring.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport importlib.utilfrom pathlib import Path+import typesimport pytest@@ -21,12 +22,17 @@ class _NativeLightRag:def _stub_build(monkeypatch) -> None:+ query_config = types.SimpleNamespace(binding="openai")monkeypatch.setattr(engine, "_require_exact_version", lambda: None)monkeypatch.setattr(engine, "_register_parser", lambda: None)monkeypatch.setattr(engine, "_controlled_class", lambda: _NativeLightRag)monkeypatch.setattr(engine, "build_llm_model_func", lambda **_kwargs: "llm")monkeypatch.setattr(engine, "build_embedding_func", lambda **_kwargs: "embedding")- monkeypatch.setattr(engine, "lightrag_llm_selection_from_settings", lambda: None)+ monkeypatch.setattr(engine, "resolve_lightrag_query_llm_config", lambda: query_config)+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.indexing_policy.cache_identity_for_config",+ lambda _config: "query-fingerprint",+ )def test_native_constructor_receives_every_supported_knob(monkeypatch, tmp_path: Path) -> None:@@ -51,15 +57,15 @@ def test_native_constructor_receives_every_supported_knob(monkeypatch, tmp_path:assert rag.kwargs["llm_model_max_async"] == 8assert rag.kwargs["entity_extract_max_gleaning"] == 2assert rag.kwargs["vlm_process_enable"] is False- assert "role_llm_configs" not in rag.kwargs+ assert rag.kwargs["llm_model_name"] == "query-fingerprint"+ assert set(rag.kwargs["role_llm_configs"]) == {"keyword", "query"}-def test_dedicated_selection_reaches_llm_but_not_embedding_adapter(+def test_global_dedicated_selection_drives_query_roles_not_embedding(monkeypatch, tmp_path: Path) -> None:_stub_build(monkeypatch)- selection = {"profile_id": "profile-1", "model_id": "model-1"}- monkeypatch.setattr(engine, "lightrag_llm_selection_from_settings", lambda: selection)+ query_config = types.SimpleNamespace(binding="dedicated")llm_calls: list[dict[str, object]] = []embedding_calls: list[dict[str, object]] = []@@ -73,12 +79,13 @@ def test_dedicated_selection_reaches_llm_but_not_embedding_adapter(monkeypatch.setattr(engine, "build_llm_model_func", build_llm)monkeypatch.setattr(engine, "build_embedding_func", build_embedding)+ monkeypatch.setattr(engine, "resolve_lightrag_query_llm_config", lambda: query_config)monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)engine.build_rag(tmp_path)- assert llm_calls == [{"llm_selection": selection}]+ assert llm_calls == [{"llm_config": query_config}]assert embedding_calls == [{}]@@ -88,8 +95,59 @@ def test_vlm_role_is_only_configured_when_enabled(monkeypatch, tmp_path: Path) -monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)- rag = engine.build_rag(tmp_path, enable_vlm=True)+ snapshot = types.SimpleNamespace(+ config=types.SimpleNamespace(binding="openai"),+ owner=object(),+ descriptor={"endpoint": "https://example.test/v1"},+ )+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.indexing_policy.cache_identity",+ lambda _snapshot: "snapshot-fingerprint",+ )++ rag = engine.build_rag(tmp_path, enable_vlm=True, indexing_snapshot=snapshot)role = rag.kwargs["role_llm_configs"]["vlm"]assert role.func == "vision"assert rag.kwargs["vlm_process_enable"] is True+++def test_snapshot_routes_only_extract_and_vlm_while_query_base_stays_global(+ monkeypatch, tmp_path: Path+) -> None:+ _stub_build(monkeypatch)+ monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)+ monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)+ llm_calls: list[dict[str, object]] = []+ vision_calls: list[dict[str, object]] = []++ def build_llm(**kwargs):+ llm_calls.append(kwargs)+ return f"llm-{len(llm_calls)}"++ def build_vision(**kwargs):+ vision_calls.append(kwargs)+ return "vision"++ monkeypatch.setattr(engine, "build_llm_model_func", build_llm)+ monkeypatch.setattr(engine, "build_vision_model_func", build_vision)+ snapshot = types.SimpleNamespace(+ config=types.SimpleNamespace(binding="openai"),+ owner=object(),+ descriptor={"endpoint": "https://example.test/v1"},+ )+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.indexing_policy.cache_identity",+ lambda _snapshot: "snapshot-fingerprint",+ )++ rag = engine.build_rag(tmp_path, enable_vlm=True, indexing_snapshot=snapshot)++ assert "llm_config" in llm_calls[0]+ assert llm_calls[1] == {"llm_config": snapshot.config, "owner": snapshot.owner}+ assert vision_calls == [{"llm_config": snapshot.config, "owner": snapshot.owner}]+ assert rag.kwargs["llm_model_func"] == "llm-1"+ assert rag.kwargs["role_llm_configs"]["extract"].func == "llm-2"+ assert rag.kwargs["role_llm_configs"]["vlm"].func == "vision"+ assert rag.kwargs["role_llm_configs"]["keyword"].func == "llm-1"+ assert rag.kwargs["role_llm_configs"]["query"].func == "llm-1"diff --git a/tests/services/test_github_source_path_containment.py b/tests/services/test_github_source_path_containment.pyindex 4242827da..e646addcc 100644--- a/tests/services/test_github_source_path_containment.py+++ b/tests/services/test_github_source_path_containment.py@@ -13,6 +13,8 @@ import asynciofrom dataclasses import dataclassfrom pathlib import Path+import pytest+from deeptutor.services.github_source import sync as sync_module@@ -93,3 +95,124 @@ def test_removal_of_an_escaping_path_leaves_the_target_alone(tmp_path: Path) ->assert sync_module._contained_dest(raw_dir, "../victim.md") is Noneassert victim.read_text(encoding="utf-8") == "keep me"+++def test_indexing_failure_propagates_and_retains_downloaded_raw_file(+ tmp_path: Path, monkeypatch+) -> None:+ raw_dir = tmp_path / "kb" / "raw"+ raw_dir.mkdir(parents=True)+ client = _Client([_Entry("guide.md")])++ async def reject_indexing(_kb_name, _files, _base_dir):+ raise RuntimeError("indexing policy rejected")++ monkeypatch.setattr(sync_module, "_index_files", reject_indexing)++ with pytest.raises(RuntimeError, match="indexing policy rejected"):+ asyncio.run(+ sync_module._full_sync(+ client,+ "kb",+ raw_dir,+ "owner/repo",+ "main",+ "",+ "*.md",+ "new-sha",+ str(tmp_path),+ )+ )++ assert (raw_dir / "guide.md").read_bytes() == b"# owned\n"+++def test_failed_sync_does_not_advance_success_markers(tmp_path: Path, monkeypatch) -> None:+ class Client(_Client):+ async def get_latest_commit_sha(self, _repo, _branch):+ return "new-sha"++ class Manager:+ calls: list[dict] = []++ def __init__(self, *, base_dir):+ self.base_dir = base_dir++ def update_github_source_state(self, **kwargs):+ self.calls.append(kwargs)++ async def reject_indexing(_kb_name, _files, _base_dir):+ raise RuntimeError("indexing policy rejected")++ monkeypatch.setattr(sync_module, "_index_files", reject_indexing)+ monkeypatch.setattr("deeptutor.knowledge.manager.KnowledgeBaseManager", Manager)+ source = {"id": "source-1", "repo": "owner/repo", "branch": "main"}++ result = asyncio.run(+ sync_module.sync_source(+ "kb",+ source,+ base_dir=str(tmp_path),+ client=Client([_Entry("guide.md")]),+ )+ )++ assert result.ok is False+ assert result.error == "indexing policy rejected"+ assert Manager.calls == [+ {+ "kb_name": "kb",+ "source_id": "source-1",+ "last_sync_status": "error",+ "last_sync_error": "indexing policy rejected",+ }+ ]+ assert "last_synced_sha" not in Manager.calls[0]+ assert "last_synced_at" not in Manager.calls[0]+ assert (tmp_path / "kb" / "raw" / "guide.md").is_file()+++def test_failed_sync_redacts_credentials_from_result_and_state(tmp_path: Path, monkeypatch) -> None:+ class Client(_Client):+ async def get_latest_commit_sha(self, _repo, _branch):+ return "new-sha"++ class Manager:+ calls: list[dict] = []++ def __init__(self, *, base_dir):+ self.base_dir = base_dir++ def update_github_source_state(self, **kwargs):+ self.calls.append(kwargs)++ async def reject_indexing(_kb_name, _files, _base_dir):+ raise RuntimeError(+ "token=private https://name:[email protected]/v1?api_key=private sk-secret"+ )++ monkeypatch.setattr(sync_module, "_index_files", reject_indexing)+ monkeypatch.setattr("deeptutor.knowledge.manager.KnowledgeBaseManager", Manager)+ result = asyncio.run(+ sync_module.sync_source(+ "kb",+ {"id": "source-1", "repo": "owner/repo", "branch": "main"},+ base_dir=str(tmp_path),+ client=Client([_Entry("guide.md")]),+ )+ )++ assert "private" not in result.error+ assert "password" not in result.error+ assert "sk-secret" not in result.error+ assert Manager.calls[0]["last_sync_error"] == result.error+++def test_sync_error_redaction_fails_closed_for_malformed_urls() -> None:+ error = sync_module.redact_sync_error(+ RuntimeError("token=private https://user:[email protected]:not-a-port/v1")+ )++ assert "private" not in error+ assert "secret" not in error+ assert "[redacted-url]" in errordiff --git a/tests/services/test_github_source_sync_service.py b/tests/services/test_github_source_sync_service.pynew file mode 100644index 000000000..cd78009b9--- /dev/null+++ b/tests/services/test_github_source_sync_service.py@@ -0,0 +1,56 @@+from __future__ import annotations++from pathlib import Path++import pytest++from deeptutor.multi_user.context import (+ get_current_user_or_none,+ reset_current_user,+ set_current_user,+)+from deeptutor.multi_user.models import CurrentUser, UserScope+from deeptutor.services.github_source.sync_service import GitHubSourceSyncService+++async def test_periodic_github_sync_installs_owner_and_restores_ambient(+ monkeypatch, tmp_path: Path+) -> None:+ owner = CurrentUser(+ id="owner",+ username="owner",+ role="user",+ scope=UserScope(kind="user", user_id="owner", root=tmp_path / "owner"),+ )+ ambient = CurrentUser(+ id="ambient",+ username="ambient",+ role="user",+ scope=UserScope(kind="user", user_id="ambient", root=tmp_path / "ambient"),+ )+ source = {"id": "source", "enabled": True}++ class _Manager:+ def __init__(self, *, base_dir: str) -> None:+ assert base_dir == str(tmp_path / "kbs")++ def get_all_github_sources(self):+ return [("kb", source)]++ def update_github_source_state(self, **_kwargs) -> None:+ raise AssertionError("sync should succeed")++ async def _sync_source(**_kwargs) -> None:+ assert get_current_user_or_none() == owner++ monkeypatch.setattr("deeptutor.knowledge.manager.KnowledgeBaseManager", _Manager)+ monkeypatch.setattr("deeptutor.services.github_source.sync.sync_source", _sync_source)+ service = GitHubSourceSyncService(base_dir=str(tmp_path / "kbs"), owner=owner)++ token = set_current_user(ambient)+ try:+ await service._sync_one_cycle()+ assert get_current_user_or_none() == ambient+ finally:+ reset_current_user(token)