DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
merge: integrate LightRAG roles with embedding compatibility
Bingxi Zhao (Frank)3800028fa867
diff --cc deeptutor/api/routers/knowledge.pyindex 95368267b,7f86ba24f..31f682673--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@@ -3516,83 -3396,6 +3516,83 @@@ async def run_reindex_task# rather than being swallowed into a generic wrapper. A False# return is reserved for "no documents to index" — surface that# specifically too.+ def persist_terminal_state(candidate_root=None):+ if candidate_root is None:+ completed_at = datetime.now().isoformat()+ metadata_file = kb_dir / "metadata.json"+ try:+ metadata = {}+ if metadata_file.exists():+ with open(metadata_file, encoding="utf-8") as handle:+ loaded_metadata = json.load(handle)+ if isinstance(loaded_metadata, dict):+ metadata = loaded_metadata+ metadata["last_updated"] = completed_at+ metadata["last_indexed_at"] = completed_at+ metadata["last_indexed_count"] = len(file_paths)+ metadata["last_indexed_action"] = "reindex"+ atomic_write_json(metadata_file, metadata)+ except Exception:+ raise++ progress_tracker.update(+ ProgressStage.COMPLETED,+ "Re-index complete",+ current=len(file_paths),+ total=len(file_paths),+ indexed_count=len(file_paths),+ index_changed=True,+ index_action="reindex",+ publication_version=candidate_root.name if candidate_root else None,+ )+ try:+ with open(progress_tracker.progress_file, encoding="utf-8") as handle:+ persisted_progress = json.load(handle)+ except Exception as progress_err:+ raise RuntimeError(+ f"Re-index terminal state was not persisted for '{kb_name}'."+ ) from progress_err+ expected_terminal_progress = {+ "stage": ProgressStage.COMPLETED.value,+ "task_id": task_id,+ "progress_percent": 100,+ "current": len(file_paths),+ "total": len(file_paths),+ "indexed_count": len(file_paths),+ "index_changed": True,+ "index_action": "reindex",+ }+ if not isinstance(persisted_progress, dict) or any(+ persisted_progress.get(key) != value+ for key, value in expected_terminal_progress.items()+ ):+ raise RuntimeError(+ f"Re-index terminal state was not persisted for '{kb_name}'."+ )+ manager = KnowledgeBaseManager(base_dir=str(base_path))+ # ProgressTracker persists through its own manager instance. Refresh+ # this cached instance before clearing flags so stale processing+ # state cannot overwrite the completed status it just wrote.+ manager.config = manager._load_config()+ # Clear the legacy mismatch / needs_reindex flags now that an+ # index version matching the active config exists on disk.+ kb_entry = manager.config.get("knowledge_bases", {}).get(kb_name) or {}+ if kb_entry.get("status") != ("processing" if candidate_root else "ready"):+ raise RuntimeError(+ f"Re-index terminal state was not persisted for '{kb_name}'."+ )+ if candidate_root is not None:+ return+ mutated = False- if kb_entry.get("needs_reindex"):++ if signature_hash != LIGHTRAG_PROVIDER and kb_entry.get("needs_reindex"):+ kb_entry["needs_reindex"] = False+ mutated = True- if kb_entry.get("embedding_mismatch"):++ if signature_hash != LIGHTRAG_PROVIDER and kb_entry.get("embedding_mismatch"):+ kb_entry.pop("embedding_mismatch", None)+ mutated = True+ if mutated:+ manager._save_config()+success = await rag_service.initialize(kb_name=kb_name,file_paths=file_paths,diff --cc deeptutor/knowledge/manager.pyindex b057b4e7c,a508a0d2a..2a54894e2--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@@ -1423,30 -1467,30 +1467,51 @@@ class KnowledgeBaseManagerif indexing_policy is None:pending = kb_config.get("pending_indexing_policy")indexing_policy = (- pending if isinstance(pending, dict) else {"policy": "legacy_unpinned"}+ {"policy": "defaults"}+ if not index_versions+ else pending+ if isinstance(pending, dict)+ else {"policy": "legacy_unpinned"}+ )+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import public_policy++ metadata["indexing_policy"] = public_policy(indexing_policy)+ if published_root is not None and indexing_policy.get("policy") == "pinned":+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (+ IndexingPolicyError,+ snapshot_from_persisted,)- metadata["indexing_policy"] = indexing_policy++ try:+ snapshot_from_persisted(indexing_policy)+ except (IndexingPolicyError, ValueError, PermissionError):+ # This is local catalog/access validation, not a model health probe.+ # Keep credential/provider exception details out of public metadata.+ metadata["indexing_model_unavailable"] = True+ for version in index_versions:+ if isinstance(version.get("indexing_policy"), dict):+ version["indexing_policy"] = public_policy(version["indexing_policy"])+ if published_root is not None or kb_config.get("embedding_selection"):+ from deeptutor.services.rag.embedding_binding import entry_signature++ published = next(+ (+ v+ for v in index_versions+ if published_root is not None and v.get("version") == published_root.name+ ),+ {},+ )+ metadata["indexed_embedding_model"] = published.get(+ "embedding_model"+ ) or kb_config.get("embedding_model")+ metadata["indexed_embedding_dim"] = published.get("embedding_dim") or kb_config.get(+ "embedding_dim"+ )+ current_embedding = entry_signature(kb_config)+ if current_embedding is not None:+ metadata["current_embedding_model"] = current_embedding.model+ metadata["current_embedding_dim"] = current_embedding.dimensionmetadata.update(self._embedding_fields(kb_config))diff --cc deeptutor/services/rag/pipelines/lightrag/engine.pyindex dd289b3f0,9fac40379..7a543ca64--- a/deeptutor/services/rag/pipelines/lightrag/engine.py+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py@@@ -188,8 -192,7 +191,8 @@@ def build_ragio_bridge: OwnerLoopBridge | None = None,enable_vlm: bool = False,indexing_snapshot: Any | None = None,+ query_roles: dict[str, Any] | None = None,- embedding_config: Any | None = None,+ embedding_config: EmbeddingConfig | None = None,) -> Any:"""Construct one exact-version, version-isolated LightRAG instance."""_require_exact_version()diff --cc deeptutor/services/rag/pipelines/lightrag/pipeline.pyindex c80620d50,95dd92110..f3f2d7456--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py@@@ -278,7 -283,9 +282,9 @@@ class LightRagPipelineworking_dir: Path,file_paths: List[str],progress_callback: Callable[[int, int], Any] | None,- snapshot: IndexingLLMSnapshot | None = None,+ snapshot: IndexingPolicySnapshot | None = None,+ *,+ embedding_config: EmbeddingConfig | None = None,) -> BatchOutcome:if snapshot is None:snapshot = freeze_default_snapshot()@@@ -369,52 -378,22 +380,56 @@@shutil.rmtree(root_dir)async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:+ from .write_lock import write_ownership++ kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)+ with write_ownership(kb_dir):+ if validate_binding := kwargs.pop("validate_embedding_binding", None):+ validate_binding()+ snapshot = kwargs.get("indexing_snapshot") or kwargs.get("accepted_indexing_snapshot")+ if snapshot is not None:+ indexing_policy.validate_target(snapshot, kb_dir)+ fresh = indexing_policy.revalidate_snapshot(snapshot)+ key = (+ "indexing_snapshot"+ if kwargs.get("indexing_snapshot") is not None+ else "accepted_indexing_snapshot"+ )+ kwargs[key] = fresh+ return await self._initialize_owned(kb_name, file_paths, **kwargs)++ def _publish_new_version(+ self,+ root_dir: Path,+ policy: dict[str, Any],+ embedding_config: Any,+ publish_binding: Callable[[], None] | None,+ ) -> None:+ storage.write_meta(root_dir, indexing_policy=policy, embedding_config=embedding_config)+ try:+ if publish_binding is not None:+ publish_binding()+ except BaseException:+ # A same-embedding rebuild would otherwise become the newest+ # compatible version even though its binding publication failed.+ # Withdraw only this new candidate's publication marker; retain+ # its data and the previous version for recovery.+ (root_dir / "meta.json").unlink()+ raise++ async def _initialize_owned(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()+ from deeptutor.services.embedding import get_embedding_config++ embedding_config = deepcopy(get_embedding_config())kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)- snapshot = kwargs.get("indexing_snapshot")+ snapshot = kwargs.get("indexing_snapshot") or kwargs.get("accepted_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()+ snapshot = freeze_default_snapshot()+ snapshot = indexing_policy.with_embedding(snapshot)++ embedding_config = snapshot.embedding_config+ if "image_analysis" in kwargs:+ snapshot = indexing_policy.with_image_analysis(snapshot, kwargs["image_analysis"])root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)try:outcome = await self._run_indexing(@@@ -446,33 -421,10 +465,36 @@@raiseasync def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:+ from .write_lock import write_ownership++ kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)+ with write_ownership(kb_dir):+ if validate_binding := kwargs.pop("validate_embedding_binding", None):+ validate_binding()+ if kwargs.get("indexing_snapshot") is not None and (+ storage.latest_published_root(kb_dir) is not None or list_kb_versions(kb_dir)+ ):+ raise IndexingPolicyError(+ "An explicit LightRAG indexing model cannot override an existing index; "+ "run a full re-index."+ )+ snapshot = kwargs.get("indexing_snapshot") or kwargs.get("accepted_indexing_snapshot")+ if snapshot is not None:+ indexing_policy.validate_target(snapshot, kb_dir)+ fresh = indexing_policy.revalidate_snapshot(snapshot)+ key = (+ "indexing_snapshot"+ if kwargs.get("indexing_snapshot") is not None+ else "accepted_indexing_snapshot"+ )+ kwargs[key] = fresh+ return await self._add_documents_owned(kb_name, file_paths, **kwargs)++ async def _add_documents_owned(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()+ from deeptutor.services.embedding import get_embedding_config++ embedding_config = deepcopy(get_embedding_config())kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)existing = storage.latest_published_root(kb_dir)from deeptutor.services.rag.embedding_binding import bound_graph_storage_root@@@ -485,15 -442,15 +507,20 @@@"This LightRAG index is legacy, unpublished, or corrupt and must be rebuilt ""before appending.")- snapshot = kwargs.get("accepted_indexing_snapshot") or resolve_write_snapshot(++ accepted_snapshot = kwargs.get("accepted_indexing_snapshot")++ compatibility_config = getattr(accepted_snapshot, "embedding_config", None)+ if existing is not None:- storage.require_compatible_embedding(existing, embedding_config)- snapshot = resolve_write_snapshot(++ storage.require_compatible_embedding(existing, compatibility_config or embedding_config)++ snapshot = accepted_snapshot or resolve_write_snapshot(kb_dir,base_dir=self.kb_base_dir,kb_name=kb_name,explicit=explicit,- published_root=existing,)+ snapshot = indexing_policy.with_embedding(snapshot)++ embedding_config = snapshot.embedding_config+ if "image_analysis" in kwargs:+ snapshot = indexing_policy.with_image_analysis(snapshot, kwargs["image_analysis"])if existing is not None:root_dir = existingis_update = True@@@ -581,15 -531,10 +612,13 @@@mode = self._resolve_mode(kb_name, kwargs)try:self._ensure_available()-- from copy import deepcopy-from deeptutor.services.embedding import get_embedding_config+ from .roles import resolve_query_roles+embedding_config = deepcopy(get_embedding_config())+ storage.require_compatible_embedding(root_dir, embedding_config)+ query_roles = resolve_query_roles()async def job(io_bridge: OwnerLoopBridge) -> Any:rag = engine.build_rag(diff --cc deeptutor/services/rag/pipelines/lightrag/roles.pyindex 8a009a8f4,000000000..23db05f23mode 100644,000000..100644--- a/deeptutor/services/rag/pipelines/lightrag/roles.py+++ b/deeptutor/services/rag/pipelines/lightrag/roles.py@@@ -1,131 -1,0 +1,132 @@@+"""Resolve native LightRAG role choices inside the initiating user's scope."""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from deeptutor.multi_user.context import get_current_user+from deeptutor.multi_user.model_access import allowed_llm_options, apply_allowed_llm_selection+from deeptutor.multi_user.models import CurrentUser+from deeptutor.services.config.lightrag_roles import LightRagRoleModels+from deeptutor.services.llm.capabilities import supports_vision+from deeptutor.services.llm.config import LLMConfig+from deeptutor.services.model_selection.llm import LLMSelection+from deeptutor.services.model_selection.reasoning import supported_reasoning_efforts+from deeptutor.services.model_selection.runtime import resolve_llm_config_for_selection++ROLES = ("extract", "keyword", "query", "vlm")+++def model_options() -> dict[str, Any]:+ """Access-filtered choices shared by the editor and runtime validator."""+ result = allowed_llm_options()+ options = []+ for row in result["options"]:+ levels = row.get("supported_reasoning_efforts")+ metadata = {"codex_supported_reasoning_levels": levels} if levels is not None else {}+ metadata["capabilities"] = {"reasoning": row.get("declared_reasoning")}+ options.append(+ {+ **row,+ "supported_reasoning_efforts": supported_reasoning_efforts(+ row["provider"], row["model"], metadata=metadata+ ),+ "supports_vision": row.get(+ "declared_vision", supports_vision(row["provider"], row["model"])+ ),+ }+ )+ return {**result, "options": options}+++def resolve_selection(+ selection: LLMSelection, *, vision: bool = False, provider_default: bool = True+) -> LLMConfig:+ """Resolve an accessible model and validate its reasoning and vision support."""+ apply_allowed_llm_selection(selection.to_dict())+ config = resolve_llm_config_for_selection(selection)+ if provider_default and selection.reasoning_effort is None:+ # Empty explicitly omits provider reasoning controls; None retains the+ # legacy resolver defaults when restoring an older pinned index.+ config = config.model_copy(update={"reasoning_effort": ""})++ option = next(++ (++ item++ for item in model_options()["options"]++ if item["profile_id"] == selection.profile_id and item["model_id"] == selection.model_id++ ),++ None,++ )++ if option is None:++ raise ValueError("The selected model is unavailable.")+ if config.reasoning_effort:- option = next(- (- item- for item in model_options()["options"]- if item["profile_id"] == selection.profile_id- and item["model_id"] == selection.model_id- ),- None,- )- if option is None or config.reasoning_effort not in option["supported_reasoning_efforts"]:++ if config.reasoning_effort not in option["supported_reasoning_efforts"]:+ raise ValueError("The selected model does not support this reasoning effort.")- if vision and not supports_vision(config.binding, config.model):++ if vision and not option["supports_vision"]:+ raise ValueError("The selected VLM model does not support image inputs.")+ return config+++def settings_models(settings: dict[str, Any]) -> LightRagRoleModels | None:+ """Parse configured role models, returning None for legacy settings."""+ value = settings.get("role_models")+ return LightRagRoleModels.model_validate(value) if "role_models" in settings else None+++def validate_models(models: LightRagRoleModels) -> None:+ """Validate access and capabilities for the base and all enabled roles."""+ resolve_selection(LLMSelection(**models.base.model_dump()))+ for role in ROLES:+ selection = models.selection_for(role)+ if selection is not None:+ resolve_selection(LLMSelection(**selection.model_dump()), vision=role == "vlm")+++@dataclass(frozen=True)+class RoleCall:+ """Carry a resolved role model, initiating user, and execution limits."""++ config: LLMConfig+ owner: CurrentUser+ max_async: int+ timeout: int+++def runtime_limits(settings: dict[str, Any]) -> dict[str, dict[str, int]]:+ """Resolve per-role concurrency and timeouts, including legacy defaults."""+ models = settings_models(settings)+ return {+ role: {+ "max_async": getattr(models, role).max_async+ if models+ else int(settings.get("llm_model_max_async", 4)),+ "timeout": getattr(models, role).timeout if models else 240,+ }+ for role in ROLES+ }+++def resolve_query_roles() -> dict[str, RoleCall]:+ """Resolve keyword and query models within the initiating user scope."""+ from deeptutor.services.config import load_lightrag_settings++ from .config import resolve_lightrag_query_llm_config++ settings = load_lightrag_settings()+ models = settings_models(settings)+ if models is None and settings.get("version") == 2:+ raise ValueError("Choose and save a LightRAG base model before querying.")+ limits = runtime_limits(settings)+ owner = get_current_user()+ result = {}+ # The legacy resolver is intentionally used only for old-format settings.+ legacy = resolve_lightrag_query_llm_config() if models is None else None+ for role in ("keyword", "query"):+ config = (+ legacy+ if models is None+ else resolve_selection(LLMSelection(**models.selection_for(role).model_dump()))+ )+ result[role] = RoleCall(config=config, owner=owner, **limits[role])+ return resultdiff --cc tests/services/rag/test_embedding_binding.pyindex e1c622130,213d1a88f..fff505b9c--- a/tests/services/rag/test_embedding_binding.py+++ b/tests/services/rag/test_embedding_binding.py@@@ -77,130 -77,6 +77,130 @@@ def read_entry(root, name="kb")return json.loads((root / "kb_config.json").read_text())["knowledge_bases"][name][email protected]("failure", [None, "metadata", "binding"])[email protected]("target_model", ["a", "b"])+async def test_lightrag_rebuild_persists_binding_after_meta_under_write_ownership(+ catalog, tmp_path, monkeypatch, failure, target_model+):+ from deeptutor.services.rag.pipelines.lightrag import engine, storage+ from deeptutor.services.rag.pipelines.lightrag import pipeline as pipeline_module+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import IndexingPolicyError+ from deeptutor.services.rag.pipelines.lightrag.write_lock import write_ownership++ monkeypatch.setattr(engine, "installed_version", lambda: "synthetic-test-version")+ write_entry(tmp_path, rag_provider="lightrag")+ old = tmp_path / "kb" / "version-1"+ old.mkdir()+ (old / "kv_store_doc_status.json").write_text('{"old":{"status":"processed"}}')+ storage.write_meta(old, embedding_config=get_embedding_config(selection("a")))+ old_meta = (old / "meta.json").read_bytes()+ service = RAGService(kb_base_dir=str(tmp_path))+ pipeline = pipeline_module.LightRagPipeline(str(tmp_path))+ service._pipelines["lightrag"] = pipeline+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)+ monkeypatch.setattr(+ pipeline_module,+ "freeze_default_snapshot",+ lambda: SimpleNamespace(embedding_config=get_embedding_config()),+ )+- async def finish_index(root, *_args):++ async def finish_index(root, *_args, **_kwargs):+ (root / "kv_store_doc_status.json").write_text(+ json.dumps({"doc": {"status": "processed", "chunks_list": ["chunk"]}})+ )+ return pipeline_module.BatchOutcome(+ requested=1,+ accepted=1,+ processed=("doc",),+ indexing_policy={"policy": "legacy_unpinned"},+ )++ monkeypatch.setattr(pipeline, "_run_indexing", finish_index)+ original_persist = binding.persist_binding+ calls = []++ def persist(*args):+ root = storage.latest_published_root(tmp_path / "kb")+ assert root is not None+ assert (+ json.loads((root / "meta.json").read_text())["embedding_model"]+ == f"embed-{target_model}"+ )+ with pytest.raises(IndexingPolicyError, match="Another indexing operation"):+ with write_ownership(tmp_path / "kb"):+ pytest.fail("Binding publication must retain indexing ownership")+ calls.append(True)+ if failure == "binding":+ raise OSError("binding publication failed")+ original_persist(*args)++ monkeypatch.setattr(binding, "persist_binding", persist)+ if failure == "metadata":++ def fail_meta(*args, **kwargs):+ raise OSError("publication failed")++ monkeypatch.setattr(storage, "write_meta", fail_meta)+ if failure:+ with pytest.raises(OSError, match="publication failed"):+ await service.initialize("kb", ["doc"], embedding_selection=selection(target_model))+ assert calls == ([True] if failure == "binding" else [])+ assert read_entry(tmp_path)["embedding_selection"] == selection("a")+ assert storage.latest_published_root(tmp_path / "kb") == old+ assert (+ storage.published_root_for_embedding(+ tmp_path / "kb", read_entry(tmp_path)["embedding_signature"]+ )+ == old+ )+ assert not (tmp_path / "kb" / "version-2" / "meta.json").exists()+ assert (old / "meta.json").read_bytes() == old_meta+ else:+ assert await service.initialize("kb", ["doc"], embedding_selection=selection(target_model))+ assert calls == [True]+ assert read_entry(tmp_path)["embedding_selection"] == selection(target_model)+ assert storage.latest_published_root(tmp_path / "kb").name == "version-2"+ with write_ownership(tmp_path / "kb"):+ pass # Ownership is released on success and failure.++[email protected]("operation", ["initialize", "add_documents"])+async def test_lightrag_rejects_binding_changed_between_resolution_and_write_lock(+ catalog, tmp_path, monkeypatch, operation+):+ from contextlib import contextmanager++ from deeptutor.services.rag.pipelines.lightrag import write_lock+ from deeptutor.services.rag.pipelines.lightrag.pipeline import LightRagPipeline++ write_entry(tmp_path, rag_provider="lightrag")+ service = RAGService(kb_base_dir=str(tmp_path))+ pipeline = LightRagPipeline(str(tmp_path))+ service._pipelines["lightrag"] = pipeline+ original_lock = write_lock.write_ownership++ @contextmanager+ def changed_before_lock(kb_dir):+ # Another worker completed its rebuild after decorator resolution.+ binding.persist_binding(+ tmp_path, "kb", selection("b"), get_embedding_config(selection("b"))+ )+ with original_lock(kb_dir):+ yield++ async def unexpected(*args, **kwargs):+ pytest.fail("Stale binding must be rejected before any index write")++ monkeypatch.setattr(write_lock, "write_ownership", changed_before_lock)+ monkeypatch.setattr(pipeline, "_initialize_owned", unexpected)+ monkeypatch.setattr(pipeline, "_add_documents_owned", unexpected)+ with pytest.raises(ValueError, match="binding changed before indexing started"):+ await getattr(service, operation)("kb", ["doc"])+ assert read_entry(tmp_path)["embedding_selection"] == selection("b")++def test_default_change_and_key_rotation_do_not_invalidate_binding(catalog, tmp_path):entry = write_entry(tmp_path)catalog["services"]["embedding"]["active_model_id"] = "b"@@@ -212,6 -88,118 +212,122 @@@assert "original-key" not in json.dumps(entry)+ @pytest.mark.parametrize("missing_identity", [False, True])+ def test_lightrag_reconciliation_checks_bound_index_not_global_default(+ catalog, tmp_path, monkeypatch, missing_identity+ ):+ from deeptutor.knowledge.manager import _reconcile_embedding_flags+ from deeptutor.services.rag.pipelines.lightrag import engine, storage++ monkeypatch.setattr(engine, "installed_version", lambda: "synthetic-test-version")+ entry = write_entry(tmp_path, rag_provider="lightrag")+ root = tmp_path / "kb" / "version-1"+ root.mkdir()+ (root / "kv_store_doc_status.json").write_text('{"doc":{"status":"processed"}}')+ storage.write_meta(root, embedding_config=get_embedding_config(selection("a")))+ workspace = root / engine.workspace_for(root)+ workspace.mkdir()+ (workspace / "kv_store_doc_status.json").write_text('{"doc":{"status":"processed"}}')+ if missing_identity:+ meta = json.loads((root / "meta.json").read_text())+ meta.pop("embedding_signature")+ (root / "meta.json").write_text(json.dumps(meta))+ catalog["services"]["embedding"]["active_model_id"] = "b"+ _reconcile_embedding_flags({"kb": entry}, tmp_path)+ assert bool(entry.get("embedding_mismatch")) is missing_identity+ assert entry["embedding_selection"] == selection("a")+++ @pytest.mark.parametrize("drift", [False, True])+ def test_lightrag_detail_and_reconciliation_keep_recorded_bound_version(+ catalog, tmp_path, monkeypatch, drift+ ):+ from deeptutor.knowledge.manager import KnowledgeBaseManager, _reconcile_embedding_flags+ from deeptutor.services.rag.pipelines.lightrag import engine, storage++ monkeypatch.setattr(engine, "installed_version", lambda: "synthetic-test-version")+ entry = write_entry(tmp_path, rag_provider="lightrag")+ for number, model in [(1, "a"), (2, "b")]:+ root = tmp_path / "kb" / f"version-{number}"+ root.mkdir()+ (root / "kv_store_doc_status.json").write_text('{"doc":{"status":"processed"}}')+ storage.write_meta(+ root,+ embedding_config=get_embedding_config(selection(model)),- indexing_policy={"policy": "pinned", "label": model},++ indexing_policy={"policy": "pinned", "fingerprint": model * 64},+ )+ workspace = root / engine.workspace_for(root)+ workspace.mkdir()+ (workspace / "kv_store_doc_status.json").write_text('{"doc":{"status":"processed"}}')+ _reconcile_embedding_flags({"kb": entry}, tmp_path)+ assert not entry.get("embedding_mismatch")+ assert entry["embedding_selection"] == selection("a")+ manager = KnowledgeBaseManager(str(tmp_path))+ if drift:+ catalog["services"]["embedding"]["profiles"][0]["models"][0]["model"] = "changed-a"+ _reconcile_embedding_flags(manager.config["knowledge_bases"], tmp_path)+ metadata = manager.get_info("kb")["metadata"]+ assert metadata["indexed_embedding_model"] == "embed-a"+ assert metadata["current_embedding_model"] == ("changed-a" if drift else "embed-a")- assert metadata["indexing_policy"]["label"] == "a"++ assert metadata["indexing_policy"]["fingerprint"] == "a" * 64+ assert metadata["indexed_version"] == "version-1"+++ def test_lightrag_append_uses_policy_of_actual_bound_index(catalog, tmp_path, monkeypatch):+ from deeptutor.services.embedding.config import embedding_config_scope+ from deeptutor.services.rag.pipelines.lightrag import engine, indexing_policy, storage+ from deeptutor.services.rag.pipelines.lightrag.pipeline import BatchOutcome, LightRagPipeline++ monkeypatch.setattr(engine, "installed_version", lambda: "synthetic-test-version")+ write_entry(tmp_path, rag_provider="lightrag")+ for number, model in [(1, "a"), (2, "b")]:+ root = tmp_path / "kb" / f"version-{number}"+ root.mkdir()+ workspace = root / engine.workspace_for(root)+ workspace.mkdir()+ (workspace / "kv_store_doc_status.json").write_text('{"doc":{"status":"processed"}}')+ storage.write_meta(+ root,+ embedding_config=get_embedding_config(selection(model)),+ indexing_policy={"policy": "pinned", "label": model},+ )+ newer = tmp_path / "kb" / "version-2" / "meta.json"+ before = newer.read_bytes()+ monkeypatch.setattr(+ indexing_policy,+ "snapshot_from_persisted",- lambda policy: SimpleNamespace(vision_available=False, persisted_policy=lambda: policy),++ lambda policy: SimpleNamespace(++ vision_available=False,++ embedding_config=get_embedding_config(selection("a")),++ persisted_policy=lambda: policy,++ ),+ )+ pipeline = LightRagPipeline(str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ async def index(root, files, progress, snapshot, *, embedding_config):+ assert root.name == "version-1"+ assert snapshot.persisted_policy()["label"] == "a"+ assert embedding_config.model == "embed-a"+ return BatchOutcome(+ requested=1,+ accepted=1,+ processed=("new.md",),+ indexing_policy=snapshot.persisted_policy(),+ )++ monkeypatch.setattr(pipeline, "_run_indexing", index)+ with embedding_config_scope(get_embedding_config(selection("a"))):+ assert asyncio.run(pipeline.add_documents("kb", ["new.md"]))+ assert newer.read_bytes() == before+ assert (+ json.loads((tmp_path / "kb" / "version-1" / "meta.json").read_text())["indexing_policy"][+ "label"+ ]+ == "a"+ )++def test_deleted_or_edited_model_does_not_fall_back(catalog, tmp_path):entry = write_entry(tmp_path)catalog["services"]["embedding"]["profiles"][0]["models"][0]["model"] = "other-space"diff --cc tests/services/rag/test_lightrag_embedding_compatibility.pyindex 000000000,c8d0e3a0a..d5f618120mode 000000,100644..100644--- a/tests/services/rag/test_lightrag_embedding_compatibility.py+++ b/tests/services/rag/test_lightrag_embedding_compatibility.py@@@ -1,0 -1,253 +1,267 @@@+ """Published vector identity and operation-local embedding consistency."""++ from __future__ import annotations++ import asyncio+ from copy import deepcopy+ import importlib.util+ import json+ from pathlib import Path+ from types import SimpleNamespace+ from typing import Any++ import pytest++ from deeptutor.knowledge.manager import KnowledgeBaseManager, _reconcile_embedding_flags+ from deeptutor.services.embedding.config import EmbeddingConfig+ from deeptutor.services.rag.embedding_signature import signature_from_config+ from deeptutor.services.rag.pipelines.lightrag import config, engine, indexing_policy, storage+ from deeptutor.services.rag.pipelines.lightrag import pipeline as pipeline_module+ from deeptutor.services.rag.pipelines.lightrag.pipeline import BatchOutcome, LightRagPipeline+++ @pytest.fixture+ def embedding(monkeypatch: pytest.MonkeyPatch) -> EmbeddingConfig:+ cfg = EmbeddingConfig(+ model="embed-original", dim=3, base_url="https://embedding.test/v1", api_key="test-key"+ )+ monkeypatch.setattr("deeptutor.services.embedding.get_embedding_config", lambda: cfg)+ monkeypatch.setattr(engine, "installed_version", lambda: "1.5.7rc2")+ return cfg+++ def _snapshot() -> SimpleNamespace:+ return SimpleNamespace(+ vision_available=False,++ embedding_config=None,+ persisted_policy=lambda: {"policy": "pinned", "fingerprint": "a" * 64},+ )+++ def _published(root: Path) -> None:+ root.mkdir(parents=True)+ (root / "kv_store_doc_status.json").write_text(+ json.dumps({"doc": {"status": "processed"}}), encoding="utf-8"+ )+ storage.write_meta(root, indexing_policy=_snapshot().persisted_policy())+++ def _pipeline(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> LightRagPipeline:++ from deeptutor.services.embedding import get_embedding_config++ from deeptutor.services.rag.pipelines.lightrag import roles+++ pipeline = LightRagPipeline(str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)+ monkeypatch.setattr(pipeline, "_resolve_mode", lambda *_args: "hybrid")+ monkeypatch.setattr(pipeline_module, "resolve_write_snapshot", lambda *_a, **_k: _snapshot())++ monkeypatch.setattr(indexing_policy, "validate_target", lambda *_a, **_k: None)++ monkeypatch.setattr(indexing_policy, "revalidate_snapshot", lambda snapshot: snapshot)++++ def with_embedding(snapshot, **_kwargs):++ if snapshot.embedding_config is None:++ snapshot.embedding_config = deepcopy(get_embedding_config())++ return snapshot++++ monkeypatch.setattr(indexing_policy, "with_embedding", with_embedding)++ monkeypatch.setattr(roles, "resolve_query_roles", dict)+ monkeypatch.setattr(pipeline, "_clear_pending_policy", lambda *_args: None)+ return pipeline+++ @pytest.mark.parametrize(+ "field,value",+ [("model", "embed-other"), ("dim", 4), ("base_url", "https://other.test/v1")],+ )+ def test_changed_identity_blocks_query_and_append_before_vectors_open(+ embedding: EmbeddingConfig,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ field: str,+ value: Any,+ ) -> None:+ root = tmp_path / "kb" / "version-1"+ _published(root)+ before = (root / "meta.json").read_bytes()+ setattr(embedding, field, value)+ pipeline = _pipeline(tmp_path, monkeypatch)+ monkeypatch.setattr(engine, "build_rag", lambda *_a, **_k: pytest.fail("opened vectors"))++ result = asyncio.run(pipeline.search("question", "kb"))+ assert result["sources"] == []+ assert result["error_type"] == "lightrag_embedding_incompatible"+ assert "Restore the original" in result["answer"]+ with pytest.raises(indexing_policy.IndexingPolicyError, match="Restore the original"):+ asyncio.run(pipeline.add_documents("kb", ["new.md"]))+ assert (root / "meta.json").read_bytes() == before+++ def test_missing_identity_requires_rebuild(+ embedding: EmbeddingConfig, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ root = tmp_path / "kb" / "version-1"+ _published(root)+ meta_path = root / "meta.json"+ meta = json.loads(meta_path.read_text())+ del meta["embedding_signature"]+ meta_path.write_text(json.dumps(meta))+ entries = {"kb": {"rag_provider": "lightrag", "status": "ready"}}+ assert _reconcile_embedding_flags(entries, tmp_path)+ assert entries["kb"]["embedding_mismatch"] is True+ pipeline = _pipeline(tmp_path, monkeypatch)+ monkeypatch.setattr(engine, "build_rag", lambda *_a, **_k: pytest.fail("opened vectors"))+ assert asyncio.run(pipeline.search("question", "kb"))["error_type"] == (+ "lightrag_embedding_incompatible"+ )+ with pytest.raises(indexing_policy.IndexingPolicyError):+ asyncio.run(pipeline.add_documents("kb", ["new.md"]))+++ def test_restoring_identity_recovers_query_and_incremental_append(+ embedding: EmbeddingConfig, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ root = tmp_path / "kb" / "version-1"+ _published(root)+ index_before = (root / "kv_store_doc_status.json").read_bytes()+ original = embedding.model+ embedding.model = "other"+ entries = {"kb": {"rag_provider": "lightrag", "status": "ready"}}+ assert _reconcile_embedding_flags(entries, tmp_path)+ embedding.model = original+ assert _reconcile_embedding_flags(entries, tmp_path)+ assert not entries["kb"].get("embedding_mismatch")+ assert entries["kb"]["needs_reindex"] is False+ assert (root / "kv_store_doc_status.json").read_bytes() == index_before++ pipeline = _pipeline(tmp_path, monkeypatch)+ monkeypatch.setattr(engine, "build_rag", lambda *_a, **_k: object())++ async def noop(*_a: Any, **_k: Any) -> None:+ return None++ async def query(*_a: Any, **_k: Any) -> tuple[str, list]:+ return "retrieved", []++ roots = []++ async def append(path: Path, *_a: Any, **_k: Any) -> BatchOutcome:+ roots.append(path)+ return BatchOutcome(requested=1, accepted=1, processed=("new.md",))++ monkeypatch.setattr(engine, "initialize", noop)+ monkeypatch.setattr(engine, "finalize", noop)+ monkeypatch.setattr(engine, "query_with_sources", query)+ monkeypatch.setattr(pipeline, "_run_indexing", append)+ assert asyncio.run(pipeline.search("question", "kb"))["answer"] == "retrieved"+ assert asyncio.run(pipeline.add_documents("kb", ["new.md"]))+ assert roots == [root]+ assert not (root.parent / "version-2").exists()+++ @pytest.mark.parametrize("operation", ["initialize", "add_documents"])+ def test_index_operation_metadata_uses_captured_embedding_after_default_change(+ embedding: EmbeddingConfig,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ operation: str,+ ) -> None:+ original = deepcopy(embedding)+ if operation == "add_documents":+ _published(tmp_path / "kb" / "version-1")+ pipeline = _pipeline(tmp_path, monkeypatch)+ captured = []++ async def index(root: Path, *_a: Any, embedding_config: EmbeddingConfig) -> BatchOutcome:+ captured.append(embedding_config)+ embedding.model = "later-default"+ assert embedding_config.model == original.model+ root.mkdir(parents=True, exist_ok=True)+ (root / "kv_store_doc_status.json").write_text('{"doc":{"status":"processed"}}')+ return BatchOutcome(requested=1, accepted=1, processed=("doc.md",))++ monkeypatch.setattr(pipeline, "_run_indexing", index)+ kwargs = {"indexing_snapshot": _snapshot()} if operation == "initialize" else {}+ assert asyncio.run(getattr(pipeline, operation)("kb", ["doc.md"], **kwargs))+ root = storage.latest_published_root(tmp_path / "kb")+ assert root is not None+ meta = json.loads((root / "meta.json").read_text())+ assert len(captured) == 1+ assert meta["embedding_signature"] == signature_from_config(original).hash()+ assert meta["embedding_model"] == original.model+ assert meta["embedding_dim"] == original.dim+ assert "test-key" not in json.dumps(meta)+++ def test_query_keeps_captured_embedding_while_worker_waits(+ embedding: EmbeddingConfig, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ _published(tmp_path / "kb" / "version-1")+ original = embedding.model+ pipeline = _pipeline(tmp_path, monkeypatch)+ captured = []++ async def worker(job: Any) -> Any:+ embedding.model = "later-default"+ return await job(None)++ def build(*_a: Any, embedding_config: EmbeddingConfig, **_k: Any) -> object:+ captured.append(embedding_config.model)+ return object()++ async def noop(*_a: Any, **_k: Any) -> None:+ return None++ async def query(*_a: Any, **_k: Any) -> tuple[str, list]:+ return "retrieved", []++ monkeypatch.setattr(pipeline_module, "run_in_worker_loop", worker)+ monkeypatch.setattr(engine, "build_rag", build)+ monkeypatch.setattr(engine, "initialize", noop)+ monkeypatch.setattr(engine, "finalize", noop)+ monkeypatch.setattr(engine, "query_with_sources", query)+ assert asyncio.run(pipeline.search("question", "kb"))["answer"] == "retrieved"+ assert captured == [original]+++ @pytest.mark.skipif(importlib.util.find_spec("lightrag") is None, reason="optional LightRAG SDK")+ def test_adapter_calls_captured_config_and_preserves_query_role(+ embedding: EmbeddingConfig, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ original = deepcopy(embedding)+ embedding.model = "later-default"+ calls = []++ class Client:+ def __init__(self, *, config: EmbeddingConfig) -> None:+ self.config = config++ async def embed(self, texts: list[str], *, input_type: str | None) -> list[list[float]]:+ calls.append((self.config.model, texts, input_type))+ return [[1.0, 2.0, 3.0]]++ monkeypatch.setattr("deeptutor.services.embedding.client.EmbeddingClient", Client)+ adapter = config.build_embedding_func(embedding_config=original)+ original.model = "mutated-input"+ asyncio.run(adapter(["question"], context="query"))+ assert calls == [("embed-original", ["question"], "search_query")]+ assert adapter.embedding_dim == 3+++ def test_manager_surfaces_old_current_identity_and_ignores_llm_default(+ embedding: EmbeddingConfig, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ root = tmp_path / "kb" / "version-1"+ _published(root)+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))+ manager.config["knowledge_bases"]["kb"] = {"rag_provider": "lightrag", "status": "ready"}+ monkeypatch.setattr(+ "deeptutor.services.config.load_lightrag_settings",+ lambda: {"llm_profile_id": "different", "llm_model_id": "different"},+ )+ assert not _reconcile_embedding_flags(manager.config["knowledge_bases"], tmp_path)+ embedding.model = "current-model"+ assert _reconcile_embedding_flags(manager.config["knowledge_bases"], tmp_path)+ info = manager.get_info("kb")+ assert info["metadata"]["indexed_embedding_model"] == "embed-original"+ assert info["metadata"]["current_embedding_model"] == "current-model"+ assert info["metadata"]["indexed_embedding_dim"] == 3+ assert info["metadata"]["current_embedding_dim"] == 3diff --cc tests/services/rag/test_lightrag_pipeline.pyindex 097c60df5,f3fcbfb1e..6fb96bfab--- a/tests/services/rag/test_lightrag_pipeline.py+++ b/tests/services/rag/test_lightrag_pipeline.py@@@ -16,10 -16,8 +16,9 @@@ from deeptutor.multi_user.context imporset_current_user,)from deeptutor.multi_user.models import CurrentUser, UserScope+from deeptutor.services.embedding.config import EmbeddingConfigfrom deeptutor.services.llm.exceptions import LLMAPIError, LLMAuthenticationErrorfrom deeptutor.services.parsing.types import ParsedDocument- from deeptutor.services.rag.embedding_signature import signature_from_configfrom deeptutor.services.rag.factory import get_pipeline, list_pipelines, normalize_provider_namefrom deeptutor.services.rag.index_versioning import list_kb_versionsfrom deeptutor.services.rag.pipelines.lightrag import config, engine, indexing_policy, storage@@@ -875,24 -828,15 +885,24 @@@ def test_first_index_uses_defaults_inst)pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)+ snapshot = _indexing_snapshot()+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.pipeline.freeze_default_snapshot",+ lambda: snapshot,+ )+ monkeypatch.setattr(+ indexing_policy,+ "snapshot_from_persisted",+ lambda _: pytest.fail("restored old empty policy"),+ )- async def check_defaults(_root, _files, _progress, accepted):- def changed(_policy):- raise indexing_policy.IndexingModelChangedError("reindex required")-- monkeypatch.setattr(indexing_policy, "snapshot_from_persisted", changed)++ async def check_defaults(_root, _files, _progress, accepted, **_kwargs):+ assert accepted is snapshot+ raise RuntimeError("checked defaults before provider call")- with pytest.raises(indexing_policy.IndexingModelChangedError):+ monkeypatch.setattr(pipeline, "_run_indexing", check_defaults)+ with pytest.raises(RuntimeError, match="checked defaults"):asyncio.run(pipeline.initialize("kb", [str(tmp_path / "doc.md")]))-assert not any(kb_dir.glob("version-*"))diff --cc tests/services/rag/test_lightrag_roles.pyindex b004f6938,000000000..ccd221a8dmode 100644,000000..100644--- a/tests/services/rag/test_lightrag_roles.py+++ b/tests/services/rag/test_lightrag_roles.py@@@ -1,1134 -1,0 +1,1161 @@@+"""Four-role calls, task freezing, legacy policies, and write ownership contracts."""++from __future__ import annotations++import asyncio+from copy import deepcopy+from dataclasses import replace+import json+from pathlib import Path+from types import SimpleNamespace++from pydantic import ValidationError+import pytest++from deeptutor.multi_user.context import reset_current_user, set_current_user+from deeptutor.multi_user.models import CurrentUser, UserScope+from deeptutor.services.config.lightrag_roles import LightRagRoleModels+from deeptutor.services.embedding.config import EmbeddingConfig+from deeptutor.services.llm.config import LLMConfig+from deeptutor.services.model_selection.llm import LLMSelection+from deeptutor.services.rag.embedding_signature import embedding_meta_fields+from deeptutor.services.rag.pipelines.lightrag import engine, roles, storage+from deeptutor.services.rag.pipelines.lightrag import indexing_policy as policy+from deeptutor.services.rag.pipelines.lightrag.pipeline import BatchOutcome, LightRagPipeline+from deeptutor.services.rag.pipelines.lightrag.write_lock import write_ownership+++def choice(number: int, effort: str | None = None) -> dict:+ result = {"profile_id": f"p{number}", "model_id": f"m{number}"}+ if effort is not None:+ result["reasoning_effort"] = effort+ return result+++def role_environment(tmp_path, monkeypatch):+ user = CurrentUser(+ id="role-user",+ username="tester",+ role="user",+ scope=UserScope(kind="user", user_id="role-user", root=tmp_path / "owner"),+ )+ token = set_current_user(user)+ models = LightRagRoleModels.model_validate(+ {+ "base": choice(0),+ "extract": {+ "mode": "inherit",+ "reasoning_effort": "none",+ "max_async": 2,+ "timeout": 101,+ },+ "keyword": {+ "mode": "model",+ "selection": choice(1),+ "reasoning_effort": "low",+ "max_async": 3,+ "timeout": 102,+ },+ "query": {+ "mode": "model",+ "selection": choice(2),+ "reasoning_effort": "high",+ "max_async": 4,+ "timeout": 103,+ },+ "vlm": {+ "mode": "model",+ "selection": choice(3),+ "reasoning_effort": "none",+ "max_async": 5,+ "timeout": 104,+ },+ }+ )+ state = {+ "embedding": EmbeddingConfig(+ model="embed-one", api_key="fake", dim=3, base_url="https://embed.test/v1"+ ),+ "settings": {"role_models": models.model_dump()},+ "allowed": {f"p{i}" for i in range(4)},+ "configs": {+ f"p{i}": LLMConfig(+ model=f"model-{i}",+ binding="custom",+ provider_name="custom",+ api_key="private-key",+ base_url=f"https://name:password@provider-{i}.test/v1?key=private",+ reasoning_effort="medium",+ )+ for i in range(4)+ },+ "vision": {f"model-{i}": i == 3 for i in range(4)},+ }++ def allowed(value):+ if value["profile_id"] not in state["allowed"]:+ raise PermissionError("Model access was revoked.")+ return value++ def resolve(value):+ selection = LLMSelection.from_payload(value)+ config = state["configs"][selection.profile_id]+ return config.model_copy(+ update={"reasoning_effort": selection.reasoning_effort or config.reasoning_effort}+ )++ def options():+ return {+ "active": choice(0),+ "options": [+ {+ **choice(i),+ "model": f"model-{i}",+ "provider": "custom",+ "model_name": f"Model {i}",+ "profile_name": f"Provider {i}",+ "is_active_default": i == 0,+ "supported_reasoning_efforts": ["none", "low", "medium", "high"],+ }+ for i in range(4)+ if f"p{i}" in state["allowed"]+ ],+ }++ monkeypatch.setattr(+ "deeptutor.services.config.load_lightrag_settings", lambda: deepcopy(state["settings"])+ )+ monkeypatch.setattr(roles, "allowed_llm_options", options)+ monkeypatch.setattr(roles, "apply_allowed_llm_selection", allowed)+ monkeypatch.setattr(roles, "resolve_llm_config_for_selection", resolve)+ monkeypatch.setattr(+ roles, "supports_vision", lambda _binding, model: state["vision"].get(model, False)+ )+ monkeypatch.setattr(policy, "apply_allowed_llm_selection", allowed)+ monkeypatch.setattr(policy, "resolve_llm_config_for_selection", resolve)+ monkeypatch.setattr(+ policy, "supports_vision", lambda _binding, model: state["vision"].get(model, False)+ )+ monkeypatch.setattr(policy, "_active_catalog_selection", lambda: choice(0))+ from deeptutor.services.embedding.config import scoped_embedding_config++ monkeypatch.setattr(+ "deeptutor.services.embedding.get_embedding_config",+ lambda: scoped_embedding_config() or state["embedding"],+ )+ yield state+ reset_current_user(token)+++def test_role_contract_distinguishes_inherit_explicit_disabled_and_none():+ models = LightRagRoleModels.model_validate(+ {"base": choice(0, "high"), "extract": {"reasoning_effort": "none"}}+ )+ assert models.selection_for("query").reasoning_effort == "high"+ assert models.selection_for("extract").reasoning_effort == "none"+ assert models.selection_for("vlm") is None+ for invalid in (+ {"base": choice(0), "query": {"mode": "disabled"}},+ {"base": choice(0), "vlm": {"mode": "disabled", "selection": choice(3)}},+ {"base": choice(0), "query": {"mode": "model"}},+ {"base": choice(0), "query": {"mode": "inherit", "selection": choice(1)}},+ {"base": choice(0), "query": {"max_async": 0}},+ {"base": choice(0), "query": {"timeout": True}},+ {"base": {**choice(0), "api_key": "private"}},+ ):+ with pytest.raises(ValidationError):+ LightRagRoleModels.model_validate(invalid)+++def test_new_settings_do_not_fall_back_to_chat(role_environment, monkeypatch):+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.config.resolve_lightrag_query_llm_config",+ lambda: pytest.fail("new settings must not resolve chat fallback"),+ )+ first = roles.resolve_query_roles()+ assert first["keyword"].config.model == "model-1"+ assert first["query"].config.model == "model-2"+ role_environment["settings"]["role_models"]["query"] = {"mode": "inherit"}+ role_environment["settings"]["role_models"]["base"] = choice(3)+ second = roles.resolve_query_roles()+ assert second["query"].config.model == "model-3"+ assert first["query"].config.model == "model-2"+ assert (first["query"].max_async, first["query"].timeout) == (4, 103)+++def test_all_four_native_roles_call_their_frozen_models(role_environment, monkeypatch, tmp_path):+ pytest.importorskip("lightrag")+ calls = []++ def build(config, *, allow_multimodal):+ async def complete(prompt, **kwargs):+ calls.append((config.model, config.reasoning_effort, allow_multimodal, kwargs))+ return config.model++ return complete++ monkeypatch.setattr("deeptutor.services.llm.client.build_model_func_for_config", build)+ monkeypatch.setattr(engine, "_require_exact_version", lambda: None)+ monkeypatch.setattr(engine, "_register_parser", lambda: None)+ monkeypatch.setattr(engine, "_controlled_class", lambda: lambda **kwargs: kwargs)+ monkeypatch.setattr(engine, "build_embedding_func", lambda **kwargs: "independent embedding")+ monkeypatch.setattr(engine, "constructor_kwargs_from_settings", dict)+ monkeypatch.setattr(engine, "indexing_kwargs_from_settings", dict)+ snapshot = policy.freeze_roles()+ queries = roles.resolve_query_roles()+ indexed = engine.build_rag(tmp_path, indexing_snapshot=snapshot, enable_vlm=True)+ queried = engine.build_rag(tmp_path, query_roles=queries)++ async def exercise():+ await indexed["role_llm_configs"]["extract"].func("extract")+ await indexed["role_llm_configs"]["vlm"].func("vision", image_inputs=[{"base64": "image"}])+ await queried["role_llm_configs"]["keyword"].func("keyword")+ await queried["role_llm_configs"]["query"].func("query")++ asyncio.run(exercise())+ assert [(model, effort, vision) for model, effort, vision, _ in calls] == [+ ("model-0", "none", False),+ ("model-3", "none", True),+ ("model-1", "low", False),+ ("model-2", "high", False),+ ]+ assert all(kwargs["allow_image_fallback"] is False for *_, kwargs in calls)+ all_roles = {**indexed["role_llm_configs"], **queried["role_llm_configs"]}+ assert {name: (value.max_async, value.timeout) for name, value in all_roles.items()} == {+ "extract": (2, 101),+ "vlm": (5, 104),+ "keyword": (3, 102),+ "query": (4, 103),+ }+ assert len({value.metadata["model"] for value in all_roles.values()}) == 4+++def test_index_policy_freezes_defaults_and_limits_but_refreshes_credentials(role_environment):+ snapshot = policy.freeze_roles()+ persisted = snapshot.persisted_policy()+ role_environment["settings"]["role_models"]["extract"]["max_async"] = 12+ role_environment["settings"]["role_models"]["extract"]["timeout"] = 900+ role_environment["settings"]["role_models"]["base"] = choice(2)+ role_environment["configs"]["p0"].api_key = "rotated-secret"+ fresh = policy.revalidate_snapshot(snapshot)+ assert fresh.extract.config.api_key == "rotated-secret"+ assert fresh.extract.config.model == "model-0"+ assert fresh.limits["extract"] == {"max_async": 2, "timeout": 101}+ assert fresh.persisted_policy() == persisted+ assert policy.freeze_roles().extract.config.model == "model-2"+ serialized = json.dumps(persisted)+ for forbidden in ("private", "password", "api_key", "role-user"):+ assert forbidden not in serialized+ assert "endpoint" not in json.dumps(policy.public_policy(persisted))+++ "change", ["endpoint", "model", "wire_api", "context_window", "access", "vision"]+)+def test_invalid_pinned_identity_blocks_before_writes(role_environment, change):+ snapshot = policy.freeze_roles()+ if change == "endpoint":+ role_environment["configs"]["p0"].effective_url = "https://other.test/v1"+ elif change == "model":+ role_environment["configs"]["p0"].model = "different"+ elif change == "wire_api":+ role_environment["configs"]["p0"].api_format = "openai_responses"+ elif change == "context_window":+ role_environment["configs"]["p0"].context_window = 100000+ elif change == "access":+ role_environment["allowed"].remove("p3")+ else:+ role_environment["vision"]["model-3"] = False+ with pytest.raises(policy.IndexingPolicyError):+ policy.revalidate_snapshot(snapshot)+++def test_unsupported_reasoning_and_nonvision_inheritance_fail(role_environment):+ models = deepcopy(role_environment["settings"]["role_models"])+ models["query"]["reasoning_effort"] = "max"+ with pytest.raises(ValueError, match="reasoning"):+ roles.validate_models(LightRagRoleModels.model_validate(models))+ models["query"]["reasoning_effort"] = "high"+ models["vlm"] = {"mode": "inherit"}+ with pytest.raises(ValueError, match="image inputs"):+ roles.validate_models(LightRagRoleModels.model_validate(models))++++def test_explicit_catalog_vision_capability_is_used_for_custom_model(role_environment, monkeypatch):++ role_environment["vision"]["model-0"] = False++ monkeypatch.setattr(++ roles,++ "allowed_llm_options",++ lambda: {++ "active": choice(0),++ "options": [++ {++ **choice(0),++ "model": "model-0",++ "provider": "custom",++ "model_name": "Custom vision model",++ "profile_name": "Custom provider",++ "is_active_default": True,++ "declared_vision": True,++ "supported_reasoning_efforts": ["none", "low", "medium", "high"],++ }++ ],++ },++ )++++ config = roles.resolve_selection(LLMSelection(**choice(0)), vision=True)++++ assert config.model == "model-0"+++++def test_legacy_single_policy_keeps_its_original_algorithm_and_vision(role_environment):+ legacy = policy.freeze_snapshot(choice(3, "none")).persisted_policy()+ adapted = policy.snapshot_from_persisted(legacy)+ assert adapted.vision_available+ assert adapted.extract.fingerprint == legacy["fingerprint"]+ assert adapted.vlm.fingerprint == legacy["fingerprint"]+ assert adapted.persisted_policy() == legacy+ assert "schema_version" not in adapted.persisted_policy()+ del legacy["vision_available"]+ with pytest.raises(policy.IndexingModelChangedError, match="historical vision"):+ policy.snapshot_from_persisted(legacy)+++ "bad",+ [+ {},+ {"policy": "legacy_unpinned"},+ {"policy": "pinned", "schema_version": 99},+ {"policy": "pinned", "schema_version": 2, "extract": {}, "vlm": {"mode": "enabled"}},+ {+ "policy": "pinned",+ "schema_version": 2,+ "extract": {},+ "vlm": {"mode": "disabled", "snapshot": {}},+ },+ ],+)+def test_malformed_policies_never_acquire_current_defaults(role_environment, bad):+ with pytest.raises(policy.IndexingPolicyError):+ policy.snapshot_from_persisted(bad)+++def test_disabled_vlm_requires_rebuild_for_explicit_analysis(role_environment):+ disabled = policy.freeze_roles({"extract": choice(0), "vlm": {"mode": "disabled"}})+ assert not disabled.vision_available+ assert policy.with_image_analysis(disabled, False).vlm is None+ with pytest.raises(policy.IndexingModelChangedError, match="full re-index"):+ policy.with_image_analysis(disabled, True)+ enabled = policy.freeze_roles(+ {"extract": choice(0), "vlm": {"mode": "enabled", "selection": choice(3)}}+ )+ assert policy.with_image_analysis(enabled, True).vision_available+ assert (+ policy.with_image_analysis(enabled, False).persisted_policy() == enabled.persisted_policy()+ )+++def _published(path: Path, value: dict):+ path.mkdir(parents=True, exist_ok=True)+ (path / "kv_store_doc_status.json").write_text('{"doc": {"status": "processed"}}')+ (path / "meta.json").write_text(+ json.dumps(+ {+ "provider": "lightrag",+ "signature": "lightrag",+ "lightrag_adapter_schema": storage.ADAPTER_SCHEMA,+ "parser_bridge_schema": 1,+ "state": "published",+ "indexing_policy": value,+ **embedding_meta_fields(),+ }+ )+ )+++def test_stale_queued_target_is_rejected_before_graph_write(+ role_environment, tmp_path, monkeypatch+):+ kb = tmp_path / "kb"+ first = policy.freeze_roles()+ _published(kb / "version-1", first.persisted_policy())+ accepted = policy.bind_target(first, kb)+ _published(kb / "version-2", first.persisted_policy())+ pipeline = LightRagPipeline(str(tmp_path))+ monkeypatch.setattr(+ pipeline, "_run_indexing", lambda *_args: pytest.fail("stale job wrote graph")+ )+ with pytest.raises(policy.IndexingPolicyError, match="target index"):+ asyncio.run(pipeline.add_documents("kb", ["doc.md"], accepted_indexing_snapshot=accepted))+ assert storage.latest_published_root(kb) == kb / "version-2"+++def test_two_writers_cannot_own_one_knowledge_base(tmp_path):+ kb = tmp_path / "kb"+ with write_ownership(kb):+ with pytest.raises(policy.IndexingPolicyError, match="Another indexing"):+ with write_ownership(kb):+ pytest.fail("both writers acquired ownership")+ with write_ownership(kb):+ pass+++def test_failed_terminal_persistence_does_not_publish_candidate(+ role_environment, tmp_path, monkeypatch+):+ snapshot = policy.freeze_roles()+ kb = tmp_path / "kb"+ _published(kb / "version-1", snapshot.persisted_policy())+ pipeline = LightRagPipeline(str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)+ monkeypatch.setattr(storage, "has_output", lambda _root: True)+- async def indexed(root, *_args):++ async def indexed(root, *_args, **_kwargs):+ (root / "kv_store_doc_status.json").write_text('{"doc": {"status": "processed"}}')+ return BatchOutcome(+ 1, accepted=1, processed=("doc.md",), indexing_policy=snapshot.persisted_policy()+ )++ def fail_terminal(_root):+ raise OSError("terminal persistence failed")++ monkeypatch.setattr(pipeline, "_run_indexing", indexed)+ with pytest.raises(OSError, match="terminal persistence"):+ asyncio.run(+ pipeline.initialize(+ "kb", ["doc.md"], indexing_snapshot=snapshot, before_publish=fail_terminal+ )+ )+ assert storage.latest_published_root(kb) == kb / "version-1"+ assert not (kb / "version-2" / "meta.json").exists()+++def test_prepared_terminal_is_not_announced_or_read_as_completed(tmp_path, monkeypatch):+ from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker++ entry = {"status": "processing"}++ class Manager:+ def __init__(self, **_kwargs):+ pass++ def update_kb_status(self, *, status, progress, **_kwargs):+ entry.update(status=status, progress=progress)++ def get_kb_entry(self, _name):+ return entry++ monkeypatch.setattr("deeptutor.knowledge.manager.KnowledgeBaseManager", Manager)+ monkeypatch.setattr(+ "deeptutor.knowledge.progress_events.emit_task_progress", lambda *_args: None+ )+ tracker = ProgressTracker("kb", tmp_path)+ tracker.task_id = "rebuild-1"+ seen = []+ tracker.set_callback(lambda progress: seen.append(progress["stage"]))+ tracker.update(+ ProgressStage.COMPLETED,+ "Rebuild complete",+ current=1,+ total=1,+ indexed_count=1,+ index_changed=True,+ index_action="reindex",+ publication_version="version-2",+ )+ tracker.verify_terminal(+ current=1, total=1, indexed_count=1, index_action="reindex", publication_version="version-2"+ )+ assert entry["status"] == "processing"+ assert seen == ["processing_documents"]+ assert tracker.get_progress()["stage"] == "processing_documents"+ # A process interrupted here has a prepared record, not a published index.+ _published(tmp_path / "kb" / "version-2", {"policy": "pinned"})+ assert tracker.get_progress()["stage"] == "completed"++[email protected]("lost_write", ["progress_file", "kb_status"])+def test_lost_terminal_write_is_detected_before_publication(tmp_path, monkeypatch, lost_write):+ from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker++ entry = {"status": "ready"}++ class Manager:+ def __init__(self, **_kwargs):+ pass++ def update_kb_status(self, *, status, progress, **_kwargs):+ if lost_write == "kb_status":+ raise OSError("status storage unavailable")+ entry.update(status=status, progress=progress)++ def get_kb_entry(self, _name):+ return entry++ monkeypatch.setattr("deeptutor.knowledge.manager.KnowledgeBaseManager", Manager)+ if lost_write == "progress_file":++ def fail(*_args):+ raise OSError("progress storage unavailable")++ monkeypatch.setattr("deeptutor.knowledge.progress_tracker.atomic_write_json", fail)+ tracker = ProgressTracker("kb", tmp_path)+ tracker.task_id = "new-task"+ tracker.update(+ ProgressStage.COMPLETED,+ current=1,+ total=1,+ indexed_count=1,+ index_changed=True,+ index_action="reindex",+ publication_version="version-2",+ )+ with pytest.raises(RuntimeError, match="terminal state was not persisted"):+ tracker.verify_terminal(+ current=1,+ total=1,+ indexed_count=1,+ index_action="reindex",+ publication_version="version-2",+ )+++def test_concurrent_first_writers_do_not_publish_different_policies(+ role_environment, tmp_path, monkeypatch+):+ snapshot = policy.bind_target(policy.freeze_roles(), tmp_path / "kb")+ pipeline = LightRagPipeline(str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)+ monkeypatch.setattr(pipeline, "_clear_pending_policy", lambda _name: None)+ monkeypatch.setattr(+ storage,+ "write_meta",+ lambda root, *, indexing_policy, embedding_config: _published(root, indexing_policy),+ )++ async def exercise():+ entered = asyncio.Event()+ release = asyncio.Event()+- async def indexed(root, *_args):++ async def indexed(root, *_args, **_kwargs):+ (root / "kv_store_doc_status.json").write_text('{"doc": {"status": "processed"}}')+ entered.set()+ await release.wait()+ return BatchOutcome(+ 1, accepted=1, processed=("doc.md",), indexing_policy=snapshot.persisted_policy()+ )++ monkeypatch.setattr(pipeline, "_run_indexing", indexed)+ first = asyncio.create_task(+ pipeline.add_documents("kb", ["doc.md"], accepted_indexing_snapshot=snapshot)+ )+ await entered.wait()+ try:+ with pytest.raises(policy.IndexingPolicyError, match="Another indexing"):+ await pipeline.add_documents(+ "kb", ["other.md"], accepted_indexing_snapshot=snapshot+ )+ finally:+ release.set()+ assert await first+ with pytest.raises(policy.IndexingPolicyError, match="target index"):+ await pipeline.add_documents("kb", ["other.md"], accepted_indexing_snapshot=snapshot)++ asyncio.run(exercise())+ published = storage.latest_published_root(tmp_path / "kb")+ assert published.name == "version-1"+ assert (+ storage.read_published_policy(published)["extract"]["fingerprint"]+ == snapshot.extract.fingerprint+ )+++def test_pending_policy_change_invalidates_a_queued_first_write(role_environment, tmp_path):+ from deeptutor.knowledge.manager import KnowledgeBaseManager++ kb = tmp_path / "kb"+ kb.mkdir()+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))+ original = policy.freeze_roles(policy=policy.POLICY_PENDING)+ manager.config["knowledge_bases"]["kb"] = {+ "path": "kb",+ "rag_provider": "lightrag",+ "pending_indexing_policy": original.persisted_policy(),+ }+ manager._save_config()+ accepted = policy.bind_target(original, kb)+ replacement = policy.freeze_roles(+ {"extract": choice(1), "vlm": {"mode": "disabled"}}, policy=policy.POLICY_PENDING+ )+ manager.config["knowledge_bases"]["kb"]["pending_indexing_policy"] = (+ replacement.persisted_policy()+ )+ manager._save_config()+ with pytest.raises(policy.IndexingPolicyError, match="pending policy changed"):+ policy.validate_target(accepted, kb)+++def test_queued_rebuild_rejects_same_version_append_but_append_remains_valid(+ role_environment, tmp_path+):+ kb = tmp_path / "kb"+ snapshot = policy.freeze_roles()+ root = kb / "version-1"+ _published(root, snapshot.persisted_policy())+ rebuild = policy.bind_target(snapshot, kb, protect_contents=True)+ append = policy.bind_target(snapshot, kb)+ (root / "kv_store_doc_status.json").write_text(+ '{"doc": {"status": "processed"}, "later": {"status": "processed"}}'+ )+ with pytest.raises(policy.IndexingPolicyError, match="target index"):+ policy.validate_target(rebuild, kb)+ policy.validate_target(append, kb)+++def test_disabled_vision_keeps_table_and_equation_processing(tmp_path, monkeypatch):+ pipeline = LightRagPipeline(str(tmp_path))+ from dataclasses import dataclass++ from deeptutor.services.rag.pipelines.lightrag import ingress++ @dataclass+ class Staged:+ process_options: str = "ite"++ monkeypatch.setattr(+ "deeptutor.services.parsing.get_parse_service",+ lambda: SimpleNamespace(parse=lambda path: object()),+ )+ monkeypatch.setattr(ingress, "freeze_document", lambda *args: Staged())+ disabled, failures = pipeline._stage_documents(tmp_path, ["doc.md"], vision_available=False)+ enabled, _ = pipeline._stage_documents(tmp_path, ["doc.md"], vision_available=True)+ assert not failures+ assert disabled[0].process_options == "te"+ assert enabled[0].process_options == "ite"+++async def test_github_sync_freezes_policy_before_download(role_environment, tmp_path, monkeypatch):+ from deeptutor.services.github_source import sync++ kb = tmp_path / "kb"+ pinned = policy.freeze_roles()+ _published(kb / "version-1", pinned.persisted_policy())+ monkeypatch.setattr(+ "deeptutor.services.rag.provider_binding.resolve_bound_provider", lambda *args: "lightrag"+ )+ recorded = []+ monkeypatch.setattr(+ "deeptutor.knowledge.manager.KnowledgeBaseManager",+ lambda **kwargs: SimpleNamespace(+ update_github_source_state=lambda **data: recorded.append(data)+ ),+ )+ accepted = []++ async def add_documents(**kwargs):+ accepted.append(kwargs["accepted_indexing_snapshot"])+ return 1++ monkeypatch.setattr("deeptutor.knowledge.add_documents.add_documents", add_documents)++ class Client:+ async def get_latest_commit_sha(self, *args):+ role_environment["settings"]["role_models"]["base"] = choice(2)+ return "new-sha"++ async def get_tree(self, *args, **kwargs):+ return [SimpleNamespace(path="doc.md", type="blob")]++ async def download_file(self, *args):+ return b"test source"++ result = await sync.sync_source(+ "kb", {"id": "src", "repo": "owner/repo"}, base_dir=str(tmp_path), client=Client()+ )+ assert result.ok+ assert accepted[0].extract.fingerprint == pinned.extract.fingerprint+ assert accepted[0].vlm.fingerprint == pinned.vlm.fingerprint+ assert accepted[0].target_bound+ assert recorded[0]["last_synced_sha"] == "new-sha"++[email protected]("outcome_kind", ["partial_append", "metadata_refresh_failure"])+def test_native_workspace_append_invalidates_queued_rebuild_without_meta_change(+ role_environment, tmp_path, monkeypatch, outcome_kind+):+ from deeptutor.services.rag.pipelines.lightrag.pipeline import LightRagBatchError++ kb = tmp_path / "kb"+ root = kb / "version-1"+ snapshot = policy.freeze_roles()+ _published(root, snapshot.persisted_policy())+ workspace = root / engine.workspace_for(root)+ workspace.mkdir()+ status = workspace / "kv_store_doc_status.json"+ (root / status.name).rename(status)+ before_meta = (root / "meta.json").read_bytes()+ rebuild = policy.bind_target(snapshot, kb, protect_contents=True)+ append = policy.bind_target(snapshot, kb)+ pipeline = LightRagPipeline(str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)+- async def append_native(*args):++ async def append_native(*args, **_kwargs):+ status.write_text('{"doc":{"status":"processed"},"later":{"status":"processed"}}')+ result = BatchOutcome(+ requested=2 if outcome_kind == "partial_append" else 1,+ accepted=2 if outcome_kind == "partial_append" else 1,+ processed=("later.md",),+ failed={"bad.md": "provider rejected"} if outcome_kind == "partial_append" else {},+ indexing_policy=snapshot.persisted_policy(),+ )+ if outcome_kind == "partial_append":+ raise LightRagBatchError(result)+ return result++ def fail_metadata(*args, **kwargs):+ raise OSError("metadata refresh failed")++ monkeypatch.setattr(pipeline, "_run_indexing", append_native)+ monkeypatch.setattr(storage, "write_meta", fail_metadata)+ if outcome_kind == "partial_append":+ with pytest.raises(LightRagBatchError):+ asyncio.run(+ pipeline.add_documents(+ "kb", ["later.md", "bad.md"], accepted_indexing_snapshot=append+ )+ )+ else:+ assert asyncio.run(+ pipeline.add_documents("kb", ["later.md"], accepted_indexing_snapshot=append)+ )+ assert (root / "meta.json").read_bytes() == before_meta+ assert storage.latest_published_root(kb) == root+ with pytest.raises(policy.IndexingPolicyError, match="target index"):+ policy.validate_target(rebuild, kb)+ policy.validate_target(append, kb)++[email protected]("model", ["qwen3-32b", "deepseek-r1"])+def test_custom_binary_reasoning_choices_match_actual_request(model):+ from deeptutor.services.llm.provider_core.openai_compat_provider import OpenAICompatProvider+ from deeptutor.services.model_selection.reasoning import supported_reasoning_efforts+ from deeptutor.services.provider_registry import find_by_name++ assert supported_reasoning_efforts("custom", model) == ["minimal", "high"]+ assert supported_reasoning_efforts(+ "custom", model, metadata={"codex_supported_reasoning_levels": ["none", "low", "high"]}+ ) == ["high"]+ provider = OpenAICompatProvider(+ api_key="synthetic", default_model=model, spec=find_by_name("custom"), configure_env=False+ )+ disabled = provider._build_kwargs(+ [{"role": "user", "content": "test"}], None, model, 100, 0, "minimal", None+ )+ enabled = provider._build_kwargs(+ [{"role": "user", "content": "test"}], None, model, 100, 0, "high", None+ )+ if "qwen" in model:+ assert disabled["extra_body"]["enable_thinking"] is False+ assert enabled["extra_body"]["enable_thinking"] is True+ else:+ assert disabled["extra_body"]["thinking"]["type"] == "disabled"+ assert enabled["extra_body"]["thinking"]["type"] == "enabled"+++def test_binary_provider_none_is_rejected_before_snapshot(role_environment):+ role_environment["configs"]["p0"].model = "qwen3-32b"+ # Use the real capability mapper with the same catalog model name.+ options = roles.allowed_llm_options++ def catalog():+ value = options()+ value["options"][0]["model"] = "qwen3-32b"+ return value++ from unittest.mock import patch++ with patch.object(roles, "allowed_llm_options", catalog):+ with pytest.raises(policy.IndexingPolicyError, match="reasoning effort"):+ policy.freeze_roles()+++def test_fresh_defaults_do_not_enter_legacy_model_or_vision_fallback(role_environment, tmp_path):+ from deeptutor.services.config.runtime_settings import RuntimeSettingsService++ service = RuntimeSettingsService(tmp_path / "settings", process_env={})+ fresh = service.load_lightrag()+ assert fresh["version"] == 2+ role_environment["settings"] = fresh+ with pytest.raises(policy.IndexingPolicyError, match="base model"):+ policy.freeze_roles()+ with pytest.raises(ValueError, match="base model"):+ roles.resolve_query_roles()+ # An old-form explicit model input on a fresh configuration still defaults VLM off.+ created = policy.freeze_roles(choice(3))+ assert created.vlm is None+ legacy_path = service.path_for("lightrag")+ legacy_path.write_text('{"llm_profile_id":"p3","llm_model_id":"m3"}')+ legacy = service.load_lightrag()+ assert legacy["version"] == 1+ role_environment["settings"] = legacy+ # The compatibility path retains historical vision semantics.+ assert policy.freeze_roles(choice(3)).vlm is not None++[email protected]("version", [3, "2", True])+def test_invalid_settings_version_never_becomes_legacy_fallback(tmp_path, version):+ from deeptutor.services.config.runtime_settings import RuntimeSettingsService++ service = RuntimeSettingsService(tmp_path, process_env={})+ path = service.path_for("lightrag")+ path.write_text(json.dumps({"version": version}))+ before = path.read_bytes()+ with pytest.raises(ValueError, match="settings version"):+ service.load_lightrag()+ assert path.read_bytes() == before+++def test_provider_auto_ignores_saved_effort_and_survives_catalog_changes(role_environment):+ """Automatic indexing keeps provider defaults across catalog edits and reloads."""+ snapshot = policy.freeze_roles({"extract": choice(0), "vlm": {"mode": "disabled"}})+ assert snapshot.extract.config.reasoning_effort == ""+ persisted = snapshot.persisted_policy()+ assert persisted["extract"]["descriptor"]["reasoning_effort"] == ""+ role_environment["configs"]["p0"].reasoning_effort = "high"+ restored = policy.snapshot_from_persisted(persisted)+ assert restored.extract.config.reasoning_effort == ""+ assert restored.extract.fingerprint == snapshot.extract.fingerprint+ explicit = roles.resolve_selection(LLMSelection(**choice(0, "none")))+ assert explicit.reasoning_effort == "none"+++def test_restoring_pre_auto_policy_preserves_legacy_resolution(role_environment):+ """Old pinned policies do not silently acquire the new automatic semantics."""+ role_environment["configs"]["p0"].reasoning_effort = None+ original = policy._freeze_role(choice(0), provider_default=False)+ persisted = policy.IndexingPolicySnapshot(original, None).persisted_policy()+ assert persisted["extract"]["descriptor"]["reasoning_effort"] is None+ restored = policy.snapshot_from_persisted(persisted)+ assert restored.extract.config.reasoning_effort is None+ assert restored.extract.fingerprint == original.fingerprint+ role_environment["configs"]["p0"].reasoning_effort = "high"+ with pytest.raises(policy.IndexingModelChangedError):+ policy.snapshot_from_persisted(persisted)+++ "binding,model",+ [+ ("gemini", "gemini-3.5-flash-lite"),+ ("custom", "qwen3-32b"),+ ("custom", "deepseek-v4-pro"),+ ("openai", "gpt-5"),+ ],+)+def test_provider_auto_omits_actual_reasoning_request_fields(role_environment, binding, model):+ """Automatic roles produce no explicit reasoning or thinking request controls."""+ from deeptutor.services.llm.provider_core.openai_compat_provider import OpenAICompatProvider+ from deeptutor.services.provider_registry import find_by_name++ role_environment["configs"]["p0"].binding = binding+ role_environment["configs"]["p0"].model = model+ config = roles.resolve_selection(LLMSelection(**choice(0)))+ provider = OpenAICompatProvider(+ api_key="synthetic", default_model=model, spec=find_by_name(binding), configure_env=False+ )+ body = provider._build_kwargs(+ [{"role": "user", "content": "test"}],+ None,+ model,+ 100,+ 0,+ config.reasoning_effort,+ None,+ )+ assert "reasoning_effort" not in body+ assert "reasoning" not in body+ assert "thinking" not in body.get("extra_body", {})+ assert "enable_thinking" not in body.get("extra_body", {})+++def test_empty_existing_kb_ignores_old_pending_and_freezes_current_defaults(+ role_environment, tmp_path+):+ from deeptutor.knowledge.manager import KnowledgeBaseManager++ manager = KnowledgeBaseManager(base_dir=str(tmp_path))+ kb = tmp_path / "empty"+ kb.mkdir()+ old = policy.freeze_roles()+ manager.config["knowledge_bases"]["empty"] = {+ "rag_provider": "lightrag",+ "pending_indexing_policy": old.persisted_policy(),+ }+ manager._save_config()+ role_environment["settings"]["role_models"]["extract"]["reasoning_effort"] = "high"+ current = policy.resolve_write_snapshot(kb, base_dir=str(tmp_path), kb_name="empty")+ accepted = policy.bind_target(current, kb)+ assert accepted.extract.config.reasoning_effort == "high"+ role_environment["settings"]["role_models"]["extract"]["reasoning_effort"] = "low"+ role_environment["embedding"].model = "new-global-embedding"+ fresh = policy.revalidate_snapshot(accepted)+ assert fresh.extract.config.reasoning_effort == "high"+ assert fresh.embedding_config.model == "embed-one"+++def test_task_publishes_actual_frozen_embedding_after_defaults_change(+ role_environment, tmp_path, monkeypatch+):+ monkeypatch.setattr(engine, "installed_version", lambda: engine.LIGHTRAG_VERSION)+ kb = tmp_path / "kb"+ accepted = policy.bind_target(policy.freeze_roles(), kb, protect_contents=True)+ role_environment["embedding"].model = "later-default"+ pipeline = LightRagPipeline(str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)+- async def index(root, _files, _progress, snapshot):++ async def index(root, _files, _progress, snapshot, **_kwargs):+ assert snapshot.embedding_config.model == "embed-one"+ (root / "kv_store_doc_status.json").write_text('{"doc": {"status": "processed"}}')+ return BatchOutcome(+ 1, accepted=1, processed=("doc.md",), indexing_policy=snapshot.persisted_policy()+ )++ monkeypatch.setattr(pipeline, "_run_indexing", index)+ assert asyncio.run(pipeline.initialize("kb", ["doc.md"], indexing_snapshot=accepted))+ published = storage.latest_published_root(kb)+ meta = json.loads((published / "meta.json").read_text())+ assert meta["embedding_model"] == "embed-one"+ assert meta["embedding_dim"] == 3+ assert "fake" not in json.dumps(meta)++[email protected]("status", ["ready", "error"])+def test_rebuild_confirmation_rejects_changed_defaults_without_queueing(+ role_environment, tmp_path, monkeypatch, status+):+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ from deeptutor.api.routers import knowledge++ entry = {"rag_provider": "lightrag", "status": status}+ monkeypatch.setattr(knowledge, "_writable_kb", lambda _name: (object(), "kb", tmp_path))+ monkeypatch.setattr(knowledge, "_load_kb_entry_or_404", lambda *_a: entry)+ monkeypatch.setattr(knowledge, "_assert_provider_ready", lambda _provider: None)+ queued = []+ monkeypatch.setattr(+ knowledge, "_mark_kb_queued_for_processing", lambda *_a, **_k: queued.append(True)+ )+ captured = []++ async def task(**kwargs):+ captured.append(kwargs["indexing_snapshot"])++ monkeypatch.setattr(knowledge, "run_reindex_task", task)+ app = FastAPI()+ app.include_router(knowledge.router, prefix="/api")+ with TestClient(app) as client:+ for data in ({}, {"config_fingerprint": ""}):+ response = client.post("/api/knowledge-bases/kb/reindex", data=data)+ assert response.status_code == 409+ assert "confirm" in response.json()["detail"]+ assert not queued and not captured+ preview = client.get("/api/knowledge-bases/kb/reindex-config")+ assert preview.status_code == 200+ payload = preview.json()+ assert "private-key" not in preview.text and "password" not in preview.text+ role_environment["embedding"].model = "new-default"+ response = client.post(+ "/api/knowledge-bases/kb/reindex", data={"config_fingerprint": payload["fingerprint"]}+ )+ assert response.status_code == 409+ assert not queued and not captured+ refreshed = client.get("/api/knowledge-bases/kb/reindex-config").json()+ assert refreshed["embedding"]["model"] == "new-default"+ # Credential rotation is not an identity change.+ role_environment["embedding"].api_key = "rotated-secret"+ response = client.post(+ "/api/knowledge-bases/kb/reindex", data={"config_fingerprint": refreshed["fingerprint"]}+ )+ assert response.status_code == 200+ assert len(queued) == 1 and len(captured) == 1+ assert captured[0].embedding_config.model == "new-default"+++def test_rebuild_confirmation_preserves_binding_and_freezes_explicit_selection(+ role_environment, tmp_path, monkeypatch+):+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ from deeptutor.api.routers import knowledge++ selections = {name: {"profile_id": "embedding", "model_id": name} for name in ("a", "b")}+ configs = {+ name: EmbeddingConfig(+ model=f"embed-{name}", dim=3, api_key="secret", base_url="https://embed.test"+ )+ for name in selections+ }+ entry = {"rag_provider": "lightrag", "status": "ready", "embedding_selection": selections["b"]}+ monkeypatch.setattr(knowledge, "_writable_kb", lambda _name: (object(), "kb", tmp_path))+ monkeypatch.setattr(knowledge, "_load_kb_entry_or_404", lambda *_a: entry)+ monkeypatch.setattr(knowledge, "_assert_provider_ready", lambda _provider: None)++ def resolve(value, provider, saved=None):+ selection = json.loads(value) if value else saved["embedding_selection"]+ return selection, configs[selection["model_id"]]++ monkeypatch.setattr(knowledge, "_resolve_embedding_form", resolve)+ monkeypatch.setattr(knowledge, "_mark_kb_queued_for_processing", lambda *_a, **_k: None)+ (tmp_path / "kb" / "raw").mkdir(parents=True)+ (tmp_path / "kb" / "raw" / "doc.md").write_text("document")+ captured = []++ async def task(**kwargs):+ role_environment["embedding"].model = "later-global"+ captured.append(kwargs)++ monkeypatch.setattr(knowledge, "run_reindex_task", task)+ app = FastAPI()+ app.include_router(knowledge.router, prefix="/api")+ with TestClient(app) as client:+ bound = client.get("/api/knowledge-bases/kb/reindex-config").json()+ assert bound["embedding"]["model"] == "embed-b"+ assert bound["embedding_selection"] == selections["b"]+ role_environment["embedding"].model = "changed-global"+ assert (+ client.get("/api/knowledge-bases/kb/reindex-config").json()["fingerprint"]+ == bound["fingerprint"]+ )+ data = {+ "embedding_model": json.dumps(selections["a"]),+ "config_fingerprint": bound["fingerprint"],+ }+ assert client.post("/api/knowledge-bases/kb/reindex", data=data).status_code == 409+ assert not captured+ selected = client.get(+ "/api/knowledge-bases/kb/reindex-config",+ params={"embedding_model": data["embedding_model"]},+ ).json()+ data["config_fingerprint"] = selected["fingerprint"]+ assert client.post("/api/knowledge-bases/kb/reindex", data=data).status_code == 200+ assert captured[0]["embedding_selection"] == selections["a"]+ assert captured[0]["embedding_config"].model == "embed-a"+ assert captured[0]["indexing_snapshot"].embedding_config.model == "embed-a"+ assert entry["embedding_selection"] == selections["b"]+++def test_append_policy_and_target_follow_older_bound_version(+ role_environment, monkeypatch, tmp_path+):+ from deeptutor.services.embedding.config import embedding_config_scope+ from deeptutor.services.rag import embedding_binding++ monkeypatch.setattr(engine, "installed_version", lambda: engine.LIGHTRAG_VERSION)+ kb = tmp_path / "kb"+ original = deepcopy(role_environment["embedding"])+ first_policy = policy.freeze_roles().persisted_policy()+ first = kb / "version-1"+ _published(first, first_policy)+ role_environment["embedding"].model = "other-vector-space"+ role_environment["settings"]["role_models"]["extract"] = {+ "mode": "model",+ "selection": choice(1),+ }+ second = kb / "version-2"+ _published(second, policy.freeze_roles().persisted_policy())+ for root in (first, second):+ workspace = root / engine.workspace_for(root)+ workspace.mkdir()+ (workspace / "kv_store_doc_status.json").write_text('{"doc":{"status":"processed"}}')+ second_before = (second / "meta.json").read_bytes()+ (tmp_path / "kb_config.json").write_text(+ json.dumps(+ {+ "knowledge_bases": {+ "kb": {+ "rag_provider": "lightrag",+ **embedding_binding.binding_fields(+ {"profile_id": "embedding", "model_id": "a"}, original+ ),+ }+ }+ }+ )+ )+ monkeypatch.setattr(embedding_binding, "binding_status", lambda _entry: ("ready", original))+ accepted = policy.bind_target(+ policy.resolve_write_snapshot(kb, base_dir=str(tmp_path), kb_name="kb"), kb+ )+ assert accepted.target_version == str(first)+ assert accepted.extract.config.model == "model-0"+ assert accepted.embedding_config.model == original.model+ pipeline = LightRagPipeline(str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)+- async def index(root, _files, _progress, snapshot):++ async def index(root, _files, _progress, snapshot, **_kwargs):+ assert root == first+ assert snapshot.extract.config.model == "model-0"+ return BatchOutcome(+ 1, accepted=1, processed=("new.md",), indexing_policy=snapshot.persisted_policy()+ )++ monkeypatch.setattr(pipeline, "_run_indexing", index)+ with embedding_config_scope(original):+ assert asyncio.run(+ pipeline.add_documents("kb", ["new.md"], accepted_indexing_snapshot=accepted)+ )+ assert (second / "meta.json").read_bytes() == second_before+++def test_query_does_not_require_old_extract_or_vlm_access(role_environment, monkeypatch, tmp_path):+ kb = tmp_path / "kb"+ _published(kb / "version-1", policy.freeze_roles().persisted_policy())+ role_environment["allowed"].remove("p3")+ role_environment["allowed"].remove("p0")+ pipeline = LightRagPipeline(str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)+ monkeypatch.setattr(engine, "build_rag", lambda *_a, **_k: object())++ async def noop(*_a, **_k):+ return None++ async def query(*_a, **_k):+ return "answer", []++ monkeypatch.setattr(engine, "initialize", noop)+ monkeypatch.setattr(engine, "finalize", noop)+ monkeypatch.setattr(engine, "query_with_sources", query)+ assert asyncio.run(pipeline.search("q", "kb"))["answer"] == "answer"+ with pytest.raises(policy.IndexingPolicyError, match="revoked"):+ policy.resolve_write_snapshot(kb, base_dir=str(tmp_path), kb_name="kb")+++def test_embedding_adapter_calls_accepted_config_after_default_switch(+ role_environment, monkeypatch+):+ pytest.importorskip("lightrag.utils", reason="requires the optional rag-lightrag extra")+ from deeptutor.services.rag.pipelines.lightrag.config import build_embedding_func++ accepted = policy.with_embedding(policy.freeze_roles())+ role_environment["embedding"].model = "later-default"+ calls = []++ class Client:+ def __init__(self, *, config):+ self.config = config++ async def embed(self, texts, *, input_type):+ calls.append((self.config.model, texts, input_type))+ return [[1.0, 2.0, 3.0]]++ monkeypatch.setattr("deeptutor.services.embedding.client.EmbeddingClient", Client)+ adapter = build_embedding_func(embedding_config=accepted.embedding_config)+ result = asyncio.run(adapter.func(["fixture"], context="document"))+ assert adapter.embedding_dim == 3+ assert result.tolist() == [[1.0, 2.0, 3.0]]+ assert calls == [("embed-one", ["fixture"], "search_document")]diff --cc web/components/knowledge/KbDocumentsSection.tsxindex 05cf30540,c51df4ed4..233a60ce0--- a/web/components/knowledge/KbDocumentsSection.tsx+++ b/web/components/knowledge/KbDocumentsSection.tsx@@@ -110,26 -106,26 +110,30 @@@ export default function KbDocumentsSectconst blockedReason = canUpload? null- : requiresLightRagRebuild- ? kb.metadata?.embedding_mismatch- ? t(- "The current embedding configuration does not match this index. Restore the original configuration or rebuild with the current embedding before querying or adding documents.",- )- : t(- "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.",+ : kb.metadata?.indexing_model_unavailable+ ? t(+ "Restore access to the pinned indexing models in Settings before adding documents.",)- : needsReindex- ? t(- "This knowledge base is in legacy index format and needs reindex before upload.",- )- : status !== "ready"+ : requiresLightRagRebuild- ? t(- "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.",- )++ ? kb.metadata?.embedding_mismatch+ ? t(- "This knowledge base is currently {{status}} and cannot accept uploads yet.",- {- status: status.replaceAll("_", " "),- },++ "The current embedding configuration does not match this index. Restore the original configuration or rebuild with the current embedding before querying or adding documents.",+ )- : null;++ : t(++ "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.",++ )+ : needsReindex+ ? t(+ "This knowledge base is in legacy index format and needs reindex before upload.",+ )+ : status !== "ready"+ ? t(+ "This knowledge base is currently {{status}} and cannot accept uploads yet.",+ {+ status: status.replaceAll("_", " "),+ },+ )+ : null;const selection = validateFiles(files, policyForProvider, t);const canRetry = Boolean(onRetry) && isError && !isIndexingHere;diff --cc web/components/knowledge/KbIndexVersionsSection.tsxindex 0028c21b1,c08068665..b58b6ccf3--- a/web/components/knowledge/KbIndexVersionsSection.tsx+++ b/web/components/knowledge/KbIndexVersionsSection.tsx@@@ -28,14 -28,43 +28,15 @@@ import} from "@/lib/knowledge-helpers";import type { TaskState } from "@/hooks/useKnowledgeProgress";import Modal from "@/components/common/Modal";-import { useLLMOptions } from "@/hooks/useLLMOptions";-import { getLightRagConfig } from "@/features/knowledge/api/engines";-import type { LLMOption } from "@/lib/llm-options";-import type {- IndexingLLMSelection,- LightRagConfig,-} from "@/features/knowledge/model/types";+import {+ getReindexConfig,+ type LightRagRebuildConfig,+} from "@/features/knowledge/api/catalog";import KbIndexFailureBanner from "./KbIndexFailureBanner";-import IndexingModelSelector, {- selectionFromLightRagDefault,- selectionFromLLMOption,-} from "./IndexingModelSelector";import LightRagIndexingProvenance from "./LightRagIndexingProvenance";+import { knowledgeBaseRef } from "@/lib/knowledge-helpers";+ import LightRagEmbeddingWarning from "./LightRagEmbeddingWarning";-export function selectionForLightRagModelDialog(- options: LLMOption[],- config: Pick<LightRagConfig, "llm_profile_id" | "llm_model_id">,- activeDefault: {- profile_id?: string | null;- model_id?: string | null;- } | null,- savedPending: IndexingLLMSelection | undefined,- preserveSavedPending: boolean,-): IndexingLLMSelection | null {- const savedOption = preserveSavedPending- ? options.find(- (option) =>- option.profile_id === savedPending?.profile_id &&- option.model_id === savedPending?.model_id,- )- : undefined;- return savedOption- ? selectionFromLLMOption(savedOption, savedPending?.reasoning_effort || "")- : selectionFromLightRagDefault(options, config, activeDefault);-}-interface KbIndexVersionsSectionProps {kb: KnowledgeBase;task?: TaskState;diff --cc web/contracts/generated/api.tsindex 00d037a86,edff22318..6dc2c2490--- a/web/contracts/generated/api.ts+++ b/web/contracts/generated/api.ts@@@ -12786,7 -12627,7 +12786,7 @@@ export interface components* @default*/readonly result:-- ("correct" | "incorrect" | "partial" | "ungraded") | string;++ ("correct" | "incorrect" | "partial" | "ungraded" | "voided") | string;/*** Score Trend* @default new@@@ -12891,6 -12732,6 +12891,11 @@@* @default null*/readonly filename: string | null;++ /**++ * Id++ * @default null++ */++ readonly id: string | null;/*** Mime Type* @default nulldiff --cc web/contracts/generated/turn-protocol.tsindex 586acf231,586acf231..c151a9191--- a/web/contracts/generated/turn-protocol.ts+++ b/web/contracts/generated/turn-protocol.ts@@@ -19,6 -19,6 +19,7 @@@ export type ClientCommand| PingCommand;export type Base64 = string | null;export type Filename = string | null;++export type Id = string | null;export type MimeType = string | null;export type Type = string;export type Url = string | null;@@@ -231,7 -231,7 +232,7 @@@ export type TurnFailureCode| "internal_error"| "rejected"| "server_shutdown";--export type Id = string;++export type Id1 = string;export type LastSeq = number;export type OwnerId1 = string;export type Retryable2 = boolean;@@@ -244,14 -244,14 +245,14 @@@ export type TurnStatus"queued" | "running" | "waiting_input" | "completed" | "failed" | "cancelled";export type UpdatedAt = number | null;export type CreatedAt1 = number | null;--export type Id1 = string;++export type Id2 = string;export type Messages = {[k: string]: unknown;}[];export type Title = string;export type UpdatedAt1 = number | null;export type CreatedAt2 = number | null;--export type Id2 = string;++export type Id3 = string;export type Title1 = string;export type UpdatedAt2 = number | null;@@@ -324,6 -324,6 +325,7 @@@ export interface StartTurnCommandexport interface OutgoingAttachment {base64?: Base64;filename?: Filename;++ id?: Id;mime_type?: MimeType;type: Type;url?: Url;@@@ -622,7 -622,7 +624,7 @@@ export interface ProtocolErrorEventexport interface SessionDetail {active_turn?: TurnSummary | null;created_at?: CreatedAt1;-- id: Id1;++ id: Id2;messages?: Messages;preferences?: Preferences;title: Title;@@@ -637,7 -637,7 +639,7 @@@ export interface TurnSummarycreated_at?: CreatedAt;error?: Error;error_code?: TurnFailureCode | null;-- id: Id;++ id: Id1;last_seq?: LastSeq;owner_id?: OwnerId1;query_state?: TurnQueryState | null;@@@ -656,7 -656,7 +658,7 @@@ export interface Preferencesexport interface SessionSummary {active_turn?: TurnSummary | null;created_at?: CreatedAt2;-- id: Id2;++ id: Id3;title: Title1;updated_at?: UpdatedAt2;}diff --cc web/contracts/schema/openapi.jsonindex 6367b61c9,3fc5cc8a5..a5a6f9942--- a/web/contracts/schema/openapi.json+++ b/web/contracts/schema/openapi.json@@@ -6152,7 -5885,7 +6152,8 @@@"correct","incorrect","partial",-- "ungraded"++ "ungraded",++ "voided"],"type": "string"},@@@ -6350,6 -6083,6 +6351,18 @@@"default": null,"title": "Filename"},++ "id": {++ "anyOf": [++ {++ "type": "string"++ },++ {++ "type": "null"++ }++ ],++ "default": null,++ "title": "Id"++ },"mime_type": {"anyOf": [{diff --cc web/contracts/schema/turn-protocol.jsonindex 69ef0674d,69ef0674d..6630ddbfd--- a/web/contracts/schema/turn-protocol.json+++ b/web/contracts/schema/turn-protocol.json@@@ -321,6 -321,6 +321,18 @@@"default": null,"title": "Filename"},++ "id": {++ "anyOf": [++ {++ "type": "string"++ },++ {++ "type": "null"++ }++ ],++ "default": null,++ "title": "Id"++ },"mime_type": {"anyOf": [{diff --cc web/locales/en/app.jsonindex e1b43a66e,bc9bde0e6..93d56e1a3--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@@ -4016,59 -4015,9 +4016,62 @@@"readiness.detail.redis_not_configured": "not configured","readiness.detail.multiple_workers_require_redis": "more than one backend worker needs Redis coordination","readiness.detail.redis_available_but_memory_selected": "Redis is reachable — coordination could be switched to it",+ "After publication, enabling, disabling or replacing VLM requires a full rebuild. A VLM pinned now can process later image uploads.": "After publication, enabling, disabling or replacing VLM requires a full rebuild. A VLM pinned now can process later image uploads.",+ "Choose a LightRAG base model before saving.": "Choose a LightRAG base model before saving.",+ "Concurrency and timeout values must stay within the displayed limits.": "Concurrency and timeout values must stay within the displayed limits.",+ "Choose a vision model": "Choose a vision model",+ "EXTRACT model": "EXTRACT model",+ "Effective reasoning": "Effective reasoning",+ "Image analysis disabled": "Image analysis disabled",+ "Image analysis is disabled. Enable a VLM through a full rebuild.": "Image analysis is disabled. Enable a VLM through a full rebuild.",+ "Inherit LightRAG base model": "Inherit LightRAG base model",+ "KEYWORD and QUERY apply to subsequent queries. EXTRACT and VLM apply to new or fully rebuilt indexes; published indexes keep their pinned models.": "KEYWORD and QUERY apply to subsequent queries. EXTRACT and VLM apply to new or fully rebuilt indexes; published indexes keep their pinned models.",+ "Legacy model settings are shown below. Saving fixes the LightRAG base selection independently of chat.": "Legacy model settings are shown below. Saving fixes the LightRAG base selection independently of chat.",+ "LightRAG base model": "LightRAG base model",+ "LightRAG recommends disabling reasoning for EXTRACT and KEYWORD and enabling it for QUERY when supported.": "LightRAG recommends disabling reasoning for EXTRACT and KEYWORD and enabling it for QUERY when supported.",+ "Model default / unspecified": "Model default / unspecified",+ "Model source": "Model source",+ "Only administrators can change shared LightRAG engine settings.": "Only administrators can change shared LightRAG engine settings.",+ "Prefilled from the engine's EXTRACT and VLM settings. Changes here apply only to this new or rebuilt index.": "Prefilled from the engine's EXTRACT and VLM settings. Changes here apply only to this new or rebuilt index.",+ "Role concurrency and timeouts apply to subsequent tasks without rebuilding.": "Role concurrency and timeouts apply to subsequent tasks without rebuilding.",+ "The selected VLM model does not support image inputs.": "The selected VLM model does not support image inputs.",+ "The LightRAG base model is unavailable. Choose an accessible model.": "The LightRAG base model is unavailable. Choose an accessible model.",+ "The selected reasoning effort is no longer supported.": "The selected reasoning effort is no longer supported.",+ "Unsupported reasoning effort": "Unsupported reasoning effort",+ "VLM image analysis": "VLM image analysis",+ "VLM model": "VLM model",+ "effective model": "effective model",+ "Finalizing index publication": "Finalizing index publication",+ "Inherit base reasoning": "Inherit base reasoning",+ "With no role override, reasoning follows the LightRAG base.": "With no role override, reasoning follows the LightRAG base.",+ "The default model when no role model is specified. Role models can inherit its model and reasoning setting.": "The default model when no role model is specified. Role models can inherit its model and reasoning setting.",+ "Used to extract entities and relationships during indexing. Choose a fast, economical model with reasoning disabled.": "Used to extract entities and relationships during indexing. Choose a fast, economical model with reasoning disabled.",+ "Used to generate retrieval keywords before a query. Choose a fast model with reasoning disabled.": "Used to generate retrieval keywords before a query. Choose a fast model with reasoning disabled.",+ "Used to produce the final answer from long, complex retrieval context. Choose a capable model; reasoning can be enabled.": "Used to produce the final answer from long, complex retrieval context. Choose a capable model; reasoning can be enabled.",+ "Used to analyze images during indexing. The model must support image input.": "Used to analyze images during indexing. The model must support image input.",+ "Currently effective": "Currently effective",+ "Unavailable model": "Unavailable model",+ "One or more role models are unavailable. Choose accessible models before saving.": "One or more role models are unavailable. Choose accessible models before saving.",+ "One or more selected indexing models are unavailable. Choose accessible models before continuing.": "One or more selected indexing models are unavailable. Choose accessible models before continuing.",+ "Use engine default": "Use engine default",+ "Not selected": "Not selected",+ "Choose indexing models": "Choose indexing models",+ "Indexing models (optional override)": "Indexing models (optional override)",+ "Engine model settings are used by default. The resolved models are pinned when this index is created.": "Engine model settings are used by default. The resolved models are pinned when this index is created.",+ "After creation, changing EXTRACT or enabling, disabling, or replacing VLM requires a full rebuild.": "After creation, changing EXTRACT or enabling, disabling, or replacing VLM requires a full rebuild.",+ "Configure valid LightRAG defaults in Settings before creating a knowledge base.": "Configure valid LightRAG defaults in Settings before creating a knowledge base.",+ "Rebuild with current defaults. The previous index version is preserved until the rebuild succeeds.": "Rebuild with current defaults. The previous index version is preserved until the rebuild succeeds.",+ "Rebuild index with current defaults": "Rebuild index with current defaults",+ "Confirm rebuild": "Confirm rebuild",+ "This rebuild uses the selected embedding and the role defaults shown below. Change role models in Settings. The configuration is fixed when you confirm; the previous version is preserved if rebuilding fails.": "This rebuild uses the selected embedding and the role defaults shown below. Change role models in Settings. The configuration is fixed when you confirm; the previous version is preserved if rebuilding fails.",+ "Rebuild configuration": "Rebuild configuration",+ "Index configuration": "Index configuration",+ "The pinned EXTRACT or VLM configuration is unavailable. Restore model access in Settings, or update defaults and rebuild to replace the model. Existing text retrieval does not require these indexing models.": "The pinned EXTRACT or VLM configuration is unavailable. Restore model access in Settings, or update defaults and rebuild to replace the model. Existing text retrieval does not require these indexing models.",+ "Restore access to the pinned indexing models in Settings before adding documents.": "Restore access to the pinned indexing models in Settings before adding documents.",+ "Default configuration changed. Review the updated configuration and confirm again.": "Default configuration changed. Review the updated configuration and confirm again.",+ "Index embedding": "Index embedding",+ "Current embedding": "Current embedding",+ "The current embedding configuration does not match this index. Restore the original configuration or rebuild with the current embedding before querying or adding documents.": "The current embedding configuration does not match this index. Restore the original configuration or rebuild with the current embedding before querying or adding documents.","Could not copy": "Could not copy","The clipboard is not available in this browser.": "The clipboard is not available in this browser.","attachments": "attachments",diff --cc web/locales/zh/app.jsonindex 84db86b88,17af722fe..48aa217f7--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@@ -4016,59 -4015,9 +4016,62 @@@"readiness.detail.redis_not_configured": "未配置","readiness.detail.multiple_workers_require_redis": "多进程后端必须用 Redis 协调","readiness.detail.redis_available_but_memory_selected": "Redis 可用,可以把轮次协调切到它",+ "After publication, enabling, disabling or replacing VLM requires a full rebuild. A VLM pinned now can process later image uploads.": "发布后,启用、禁用或更换 VLM 均需完整重建。现在固定的 VLM 可以处理以后上传的图片。",+ "Choose a LightRAG base model before saving.": "请先选择 LightRAG 基础模型再保存。",+ "Concurrency and timeout values must stay within the displayed limits.": "并发数和超时值必须保持在界面显示的范围内。",+ "Choose a vision model": "选择视觉模型",+ "EXTRACT model": "EXTRACT 模型",+ "Effective reasoning": "实际推理强度",+ "Image analysis disabled": "禁用图片分析",+ "Image analysis is disabled. Enable a VLM through a full rebuild.": "图片分析已禁用。请通过完整重建启用 VLM。",+ "Inherit LightRAG base model": "继承 LightRAG 基础模型",+ "KEYWORD and QUERY apply to subsequent queries. EXTRACT and VLM apply to new or fully rebuilt indexes; published indexes keep their pinned models.": "KEYWORD 和 QUERY 应用于后续查询。EXTRACT 和 VLM 应用于新建或完整重建的索引;已发布的索引保留固定的模型。",+ "Legacy model settings are shown below. Saving fixes the LightRAG base selection independently of chat.": "下方显示旧版模型设置。保存后,LightRAG 基础模型将独立于聊天模型。",+ "LightRAG base model": "LightRAG 基础模型",+ "LightRAG recommends disabling reasoning for EXTRACT and KEYWORD and enabling it for QUERY when supported.": "LightRAG 建议关闭 EXTRACT 和 KEYWORD 的推理,并在模型支持时为 QUERY 开启推理。",+ "Model default / unspecified": "模型默认值 / 未指定",+ "Model source": "模型来源",+ "Only administrators can change shared LightRAG engine settings.": "只有管理员可以修改共享的 LightRAG 引擎设置。",+ "Prefilled from the engine's EXTRACT and VLM settings. Changes here apply only to this new or rebuilt index.": "已从引擎的 EXTRACT 和 VLM 设置预填。此处修改仅应用于本次新建或重建的索引。",+ "Role concurrency and timeouts apply to subsequent tasks without rebuilding.": "角色并发数和超时设置应用于后续任务,无需重建。",+ "The selected VLM model does not support image inputs.": "所选 VLM 模型不支持图片输入。",+ "The LightRAG base model is unavailable. Choose an accessible model.": "LightRAG 基础模型不可用,请选择有权访问的模型。",+ "The selected reasoning effort is no longer supported.": "所选推理强度已不再受支持。",+ "Unsupported reasoning effort": "不支持的推理强度",+ "VLM image analysis": "VLM 图片分析",+ "VLM model": "VLM 模型",+ "effective model": "实际模型",+ "Finalizing index publication": "正在完成索引发布",+ "Inherit base reasoning": "继承基础模型推理设置",+ "With no role override, reasoning follows the LightRAG base.": "未设置角色覆盖值时,推理强度继承 LightRAG 基础模型。",+ "The default model when no role model is specified. Role models can inherit its model and reasoning setting.": "未单独指定角色模型时使用的默认模型;角色模型可以继承它的模型和推理设置。",+ "Used to extract entities and relationships during indexing. Choose a fast, economical model with reasoning disabled.": "用于索引时抽取实体和关系;调用频繁,建议选择快速、经济并关闭推理的模型。",+ "Used to generate retrieval keywords before a query. Choose a fast model with reasoning disabled.": "用于查询前生成检索关键词;延迟敏感,应选择快速并关闭推理的模型。",+ "Used to produce the final answer from long, complex retrieval context. Choose a capable model; reasoning can be enabled.": "用于根据较长且复杂的检索上下文生成最终回答;宜选择能力较强的模型,可开启推理。",+ "Used to analyze images during indexing. The model must support image input.": "用于索引时分析图片;必须选择支持视觉输入的模型。",+ "Currently effective": "当前生效",+ "Unavailable model": "不可用的模型",+ "One or more role models are unavailable. Choose accessible models before saving.": "一个或多个角色模型不可用,请在保存前选择有权访问的模型。",+ "One or more selected indexing models are unavailable. Choose accessible models before continuing.": "一个或多个索引模型不可用,请先选择有权访问的模型。",+ "Use engine default": "使用引擎默认值",+ "Not selected": "未选择",+ "Choose indexing models": "选择索引模型",+ "Indexing models (optional override)": "索引模型(可选覆盖)",+ "Engine model settings are used by default. The resolved models are pinned when this index is created.": "默认使用 LightRAG 引擎的索引模型设置;创建时会将实际模型固定到这个索引版本。",+ "After creation, changing EXTRACT or enabling, disabling, or replacing VLM requires a full rebuild.": "创建后,更换 EXTRACT 模型或启用、禁用、更换 VLM 均需完整重建索引。",+ "Configure valid LightRAG defaults in Settings before creating a knowledge base.": "请先在设置中配置有效的 LightRAG 默认模型,再创建知识库。",+ "Rebuild with current defaults. The previous index version is preserved until the rebuild succeeds.": "使用当前默认配置重建。重建成功前保留原索引版本。",+ "Rebuild index with current defaults": "使用当前默认配置重建索引",+ "Confirm rebuild": "确认重建",+ "This rebuild uses the selected embedding and the role defaults shown below. Change role models in Settings. The configuration is fixed when you confirm; the previous version is preserved if rebuilding fails.": "本次重建将采用所选嵌入模型和下列角色默认配置。请在设置中修改角色模型。确认提交后固定本次配置;重建失败时保留原索引版本。",+ "Rebuild configuration": "本次重建配置",+ "Index configuration": "索引配置",+ "The pinned EXTRACT or VLM configuration is unavailable. Restore model access in Settings, or update defaults and rebuild to replace the model. Existing text retrieval does not require these indexing models.": "此索引固定的 EXTRACT 或 VLM 配置不可用。请在设置中恢复模型访问;如需更换模型,请修改默认配置后重建。已有文本检索不依赖这些索引模型。",+ "Restore access to the pinned indexing models in Settings before adding documents.": "请先在设置中恢复此索引固定模型的访问权限,再添加文档。",+ "Default configuration changed. Review the updated configuration and confirm again.": "默认配置已更改。请查看更新后的配置并重新确认。",+ "Index embedding": "索引使用的嵌入模型",+ "Current embedding": "当前嵌入模型",+ "The current embedding configuration does not match this index. Restore the original configuration or rebuild with the current embedding before querying or adding documents.": "当前嵌入配置与此索引不匹配。请恢复原配置,或使用当前嵌入模型重建后再查询或添加文档。","Could not copy": "复制失败","The clipboard is not available in this browser.": "当前浏览器环境无法使用剪贴板。","attachments": "附件",diff --cc web/tests/lightrag-embedding-compatibility.spec.tsxindex 000000000,39fa03ece..f3b2669f8mode 000000,100644..100644--- a/web/tests/lightrag-embedding-compatibility.spec.tsx+++ b/web/tests/lightrag-embedding-compatibility.spec.tsx@@@ -1,0 -1,193 +1,192 @@@+ import React from "react";+ import { act, fireEvent, render, screen } from "@testing-library/react";+ import { expect, it, vi } from "vitest";+ import KnowledgeBaseDetail from "@/components/knowledge/KnowledgeBaseDetail";+ import KbIndexVersionsSection from "@/components/knowledge/KbIndexVersionsSection";+ import KnowledgeHome from "@/components/knowledge/KnowledgeHome";+ import {+ DEFAULT_UPLOAD_POLICY,+ kbCanUploadDocuments,+ type KnowledgeBase,+ } from "@/lib/knowledge-helpers";++ const fixture = vi.hoisted(() => ({+ t: (key: string) => key,+ refresh: vi.fn(async () => {}),+ }));+ vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: fixture.t }) }));+ vi.mock("next/dynamic", () => ({ default: () => () => null }));+ vi.mock("@/features/knowledge/api/engines", async (original) => ({+ ...(await original<typeof import("@/features/knowledge/api/engines")>()),+ getLightRagConfig: async () => ({ llm_profile_id: "", llm_model_id: "" }),+ }));+ vi.mock("@/hooks/useLLMOptions", () => ({+ useLLMOptions: () => ({+ options: [],+ activeDefault: null,+ loading: false,+ error: false,+ refresh: fixture.refresh,+ }),+ }));+ vi.mock("@/features/knowledge/api/files", async (original) => ({+ ...(await original<typeof import("@/features/knowledge/api/files")>()),+ listKnowledgeBaseFiles: async () => [+ { name: "paper.txt", type: "file", size: 12, mime_type: "text/plain" },+ ],+ }));++ const kb: KnowledgeBase = {+ name: "papers",+ status: "ready",+ metadata: {+ indexing_policy: { policy: "pinned" },+ embedding_mismatch: true,+ indexed_embedding_model: "original-model",+ indexed_embedding_dim: 3,+ current_embedding_model: "current-model",+ current_embedding_dim: 3,+ },+ statistics: {+ rag_provider: "lightrag",+ raw_documents: 1,+ index_versions: [+ { version: "version-1", provider: "lightrag", ready: true },+ ],+ },+ };++ it("omits mismatch warnings from list cards", () => {+ render(+ <KnowledgeHome+ kbs={[kb]}+ providers={[]}+ onOpenKb={vi.fn()}+ onOpenEngine={vi.fn()}+ onOpenSource={vi.fn()}+ onCreate={vi.fn()}+ activeSection="knowledge-bases"+ onSectionChange={vi.fn()}+ />,+ );+ expect(+ screen.queryByText(/Restore the original configuration/),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByText(/Index embedding.*original-model/),+ ).not.toBeInTheDocument();+ });++ it("shows detail guidance while files and downloads remain accessible", async () => {+ render(+ <KnowledgeBaseDetail+ kb={kb}+ uploadPolicy={DEFAULT_UPLOAD_POLICY}+ history={[]}+ onCreate={vi.fn()}+ onUpload={vi.fn()}+ onReindex={vi.fn()}- onUpdatePendingIndexingPolicy={vi.fn()}+ onRetry={vi.fn()}+ onSetDefault={vi.fn()}+ onDelete={vi.fn()}+ onClearHistory={vi.fn()}+ />,+ );+ expect(+ screen.getByText(/Restore the original configuration/),+ ).toBeInTheDocument();+ expect(+ screen.getByText(/Index embedding.*original-model/),+ ).toBeInTheDocument();+ expect(+ screen.getByText(/Current embedding.*current-model/),+ ).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Files" }));+ fireEvent.click(await screen.findByText("paper.txt"));+ expect(screen.getByRole("link", { name: "Download" })).toHaveAttribute(+ "href",+ expect.stringContaining("/knowledge-bases/papers/files/paper.txt"),+ );+ });++ it("keeps version guidance visible alongside a failed rebuild", async () => {+ await act(async () => {+ render(+ <KbIndexVersionsSection+ kb={{ ...kb, status: "error" }}+ onReindex={vi.fn()}- onUpdatePendingIndexingPolicy={vi.fn()}+ />,+ );+ });+ expect(+ screen.getByText(/Restore the original configuration/),+ ).toBeInTheDocument();+ expect(+ screen.getByText(/Index embedding.*original-model/),+ ).toBeInTheDocument();+ expect(+ screen.getByText(/Current embedding.*current-model/),+ ).toBeInTheDocument();+ });++ it("shows the recorded bound version rather than a newer unbound publication", async () => {+ await act(async () => {+ render(+ <KbIndexVersionsSection+ kb={{+ ...kb,+ metadata: {+ ...kb.metadata,+ embedding_selection: { profile_id: "p", model_id: "a" },+ indexed_version: "version-1",+ },+ statistics: {+ ...kb.statistics,+ index_versions: [+ {+ version: "version-2",+ provider: "lightrag",+ ready: true,+ indexing_policy: {+ policy: "pinned",+ descriptor: { model: "Newer model" },+ },+ },+ {+ version: "version-1",+ provider: "lightrag",+ ready: true,+ indexing_policy: {+ policy: "pinned",+ descriptor: { model: "Bound model" },+ },+ },+ ],+ },+ }}+ onReindex={vi.fn()}- onUpdatePendingIndexingPolicy={vi.fn()}+ />,+ );+ });- const source = screen.getByText("Version source").nextElementSibling;- expect(source).toHaveTextContent("version-1");++ const boundRow = screen.getByText("version-1").closest("li");++ const newerRow = screen.getByText("version-2").closest("li");++ expect(boundRow?.querySelector('[title="Active version"]')).not.toBeNull();++ expect(newerRow?.querySelector('[title="Inactive version"]')).not.toBeNull();+ });++ it.each(["ready", "error"])(+ "blocks incompatible appends in %s state and restores them",+ (status) => {+ expect(kbCanUploadDocuments({ ...kb, status }, false)).toBe(false);+ expect(+ kbCanUploadDocuments(+ {+ ...kb,+ status,+ metadata: { ...kb.metadata, embedding_mismatch: false },+ },+ false,+ ),+ ).toBe(true);+ },+ );