DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: preserve selected embeddings in confirmed LightRAG rebuilds
NoxsMediaac8cc4a97d34
diff --cc deeptutor/api/routers/knowledge.pyindex d0879ca64,3d45b6cb5..95368267b--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@@ -2981,10 -3042,19 +3110,22 @@@ async def upload_files"A knowledge base is locked to the engine it was created with."),)- _assert_provider_ready(kb_provider)- accepted_snapshot = _freeze_append_indexing(- kb_name, kb_base_dir, kb_provider, image_analysis- )+ from contextlib import nullcontext++ from deeptutor.services.embedding.config import embedding_config_scope+ from deeptutor.services.rag.embedding_binding import binding_status++ binding_state, bound_config = binding_status(kb_entry)+ if binding_state in {"missing", "changed", "unconfigured"}:+ raise HTTPException(+ status_code=409,+ detail="The bound embedding model is unavailable or changed. Check the model settings or select a model to re-index this knowledge base.",+ )+ with embedding_config_scope(bound_config) if bound_config else nullcontext():+ _assert_provider_ready(kb_provider)++ accepted_snapshot = _freeze_append_indexing(++ kb_name, kb_base_dir, kb_provider, image_analysis++ )_enforce_provider_formats(kb_provider, files)allowed_extensions = (set()@@@ -3051,47 -3120,8 +3192,50 @@@ async def create_knowledge_basesearch_mode: str = Form(""),rel_paths: list[str] = Form(None),indexing_llm: str = Form(""),+ embedding_model: str = Form(""),):+ from contextlib import nullcontext++ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import IndexingPolicyError+ from deeptutor.services.rag.pipelines.lightrag.write_lock import write_ownership++ try:+ valid_name = validate_knowledge_base_name(name)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ ownership = (+ write_ownership(_current_kb_base_dir() / valid_name)+ if rag_provider == LIGHTRAG_PROVIDER+ else nullcontext()+ )+ try:+ with ownership:+ return await _create_knowledge_base_owned(+ background_tasks,+ name,+ files,+ rag_provider,+ pageindex_mode,+ search_mode,+ rel_paths,+ indexing_llm,++ embedding_model,+ )+ except IndexingPolicyError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+++async def _create_knowledge_base_owned(+ background_tasks: BackgroundTasks,+ name: str = Form(...),+ files: list[UploadFile] = File(default=[]),+ rag_provider: str = Form(DEFAULT_PROVIDER),+ pageindex_mode: str = Form(""),+ search_mode: str = Form(""),+ rel_paths: list[str] = Form(None),+ indexing_llm: str = Form(""),++ embedding_model: str = Form(""),+) -> dict[str, Any]:"""Create a new knowledge base and initialize it with files."""try:try:@@@ -3105,14 -3135,20 +3249,20 @@@raise HTTPException(status_code=400, detail=f"Knowledge base '{name}' already exists")rag_provider = _validate_registered_provider(rag_provider)+ embedding_selection, embedding_config = _resolve_embedding_form(+ embedding_model, rag_provider+ )indexing_snapshot = None- if rag_provider == LIGHTRAG_PROVIDER:- if indexing_llm:- _, indexing_snapshot = _freeze_indexing_llm_form(indexing_llm)- else:- indexing_snapshot = _freeze_default_indexing_llm()- elif indexing_llm:+ if indexing_llm:raise HTTPException(status_code=400,- detail="indexing_llm is supported only for built-in LightRAG.",+ detail="Configure LightRAG models in Settings; per-knowledge-base overrides are no longer supported.",)+ if rag_provider == LIGHTRAG_PROVIDER:- indexing_snapshot = _freeze_default_indexing_llm()++ from deeptutor.services.embedding.config import embedding_config_scope++++ with embedding_config_scope(embedding_config):++ indexing_snapshot = _freeze_default_indexing_llm()pageindex_mode = str(pageindex_mode or "").strip().lower()if rag_provider == PAGEINDEX_OSS_PROVIDER and pageindex_mode not in {"",@@@ -3434,9 -3401,14 +3598,17 @@@ async def run_reindex_taskfile_paths=file_paths,progress_callback=_on_progress,indexing_snapshot=indexing_snapshot,+ before_publish=persist_terminal_state+ if signature_hash == LIGHTRAG_PROVIDER+ else None,+ **(+ {+ "embedding_selection": embedding_selection,+ "embedding_config": embedding_config,+ }+ if embedding_selection+ else {}+ ),)if not success:raise RuntimeError(f"Re-index found no valid documents to index in '{kb_name}'.")@@@ -3478,29 -3520,16 +3650,33 @@@task_stream_manager.emit_failed(task_id, error_msg, **failure_metadata)[email protected]("/knowledge-bases/{kb_name}/reindex-config")- async def get_reindex_config(kb_name: str) -> dict[str, Any]:- """Read the exact current default configuration for rebuild confirmation."""++async def get_reindex_config(kb_name: str, embedding_model: str = "") -> dict[str, Any]:++ """Read selected embedding and current role defaults for rebuild confirmation."""+ manager, kb_name, _ = _writable_kb(kb_name)+ entry = _load_kb_entry_or_404(manager, kb_name)+ _assert_not_connected_kb(kb_name, entry)+ if _validate_registered_provider(entry.get("rag_provider")) != LIGHTRAG_PROVIDER:+ raise HTTPException(status_code=400, detail="Rebuild configuration is only for LightRAG.")++ from deeptutor.services.embedding.config import embedding_config_scope+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import public_rebuild_config+- return public_rebuild_config(_freeze_default_indexing_llm())++ selection, config = _resolve_embedding_form(embedding_model, LIGHTRAG_PROVIDER, entry)++ with embedding_config_scope(config):++ return public_rebuild_config(_freeze_default_indexing_llm(), selection)++@router.post("/knowledge-bases/{kb_name}/reindex")async def reindex_knowledge_base(kb_name: str,background_tasks: BackgroundTasks,indexing_llm: str = Form(""),- embedding_model: str = Form(""),-):+ config_fingerprint: Annotated[str, Form()] = "",++ embedding_model: Annotated[str, Form()] = "",+) -> dict[str, Any]:"""Re-index ``kb_name`` through its bound RAG provider.- LlamaIndex still keys versions by the active embedding model. The other+ LlamaIndex keys versions by the selected embedding model. The otherproviders keep synthetic provider-keyed versions, so they should rebuildwithout requiring an embedding-signature precheck."""@@@ -3512,39 -3541,56 +3688,76 @@@kb_provider = _validate_registered_provider(kb_entry.get("rag_provider") or DEFAULT_PROVIDER)- _assert_provider_ready(kb_provider)+ embedding_selection, embedding_config = _resolve_embedding_form(+ embedding_model, kb_provider, kb_entry+ )+ if isinstance(embedding_model, str) and embedding_model:+ force_reindex = True+ from contextlib import nullcontext++ from deeptutor.services.embedding.config import embedding_config_scope++ with embedding_config_scope(embedding_config) if embedding_config else nullcontext():+ _assert_provider_ready(kb_provider)indexing_snapshot = None- if kb_provider == LIGHTRAG_PROVIDER:- if indexing_llm:- _, indexing_snapshot = _freeze_indexing_llm_form(indexing_llm)- else:- indexing_snapshot = _freeze_default_indexing_llm()- elif indexing_llm:+ if indexing_llm:raise HTTPException(status_code=400,- detail="indexing_llm is supported only for built-in LightRAG.",+ detail="Configure LightRAG models in Settings; per-knowledge-base overrides are no longer supported.",+ )+ if kb_provider == LIGHTRAG_PROVIDER:+ if not config_fingerprint:+ raise HTTPException(+ status_code=409,+ detail="Review the current rebuild configuration and confirm before rebuilding.",+ )- indexing_snapshot = _freeze_default_indexing_llm()++ with embedding_config_scope(embedding_config):++ indexing_snapshot = _freeze_default_indexing_llm()++ if indexing_snapshot is not None:+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (+ public_rebuild_config,)- if public_rebuild_config(indexing_snapshot)["fingerprint"] != config_fingerprint:++ if (++ public_rebuild_config(indexing_snapshot, embedding_selection)["fingerprint"]++ != config_fingerprint++ ):+ raise HTTPException(+ status_code=409,- detail="Default configuration changed. Review the updated configuration and confirm again.",++ detail="Rebuild configuration changed. Review the updated configuration and confirm again.",+ )kb_dir = kb_base_dir / kb_name+ if indexing_snapshot is not None:+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import bind_target++ indexing_snapshot = bind_target(indexing_snapshot, kb_dir, protect_contents=True)signature_hash = kb_provider+ from deeptutor.services.rag.index_probe import has_ready_provider_index++ if (+ isinstance(embedding_model, str)+ and embedding_model+ and embedding_selection+ and not has_ready_provider_index(kb_dir, kb_provider)+ and not FileTypeRouter.collect_supported_files(kb_dir / "raw", recursive=True)+ ):+ from deeptutor.services.rag.embedding_binding import binding_fields++ kb_entry.update(binding_fields(embedding_selection, embedding_config))+ kb_entry["needs_reindex"] = False+ kb_entry["status"] = "ready"+ manager._save_config()+ return {+ "message": "Embedding model updated for the empty knowledge base.",+ "task_id": None,+ "noop": True,+ }if provider_uses_embedding_versions(kb_provider):- from deeptutor.services.rag.embedding_signature import signature_from_embedding_config+ from deeptutor.services.rag.embedding_signature import (+ signature_from_config,+ signature_from_embedding_config,+ )from deeptutor.services.rag.index_versioning import (find_matching_version,)@@@ -3642,14 -3769,7 +3864,14 @@@ async def retry_knowledge_base"Use re-index when you want to rebuild a healthy knowledge base."),)- return await reindex_knowledge_base(kb_name, background_tasks, indexing_llm="")+ if normalize_provider_name(kb_entry.get("rag_provider")) == LIGHTRAG_PROVIDER:+ raise HTTPException(+ status_code=409,+ detail="Review current defaults in Index versions and confirm the LightRAG rebuild.",+ )+ return await reindex_knowledge_base(- resolved_name, background_tasks, indexing_llm="", config_fingerprint=""++ kb_name, background_tasks, indexing_llm="", config_fingerprint="", embedding_model=""+ )except HTTPException:raiseexcept Exception as e:diff --cc deeptutor/knowledge/add_documents.pyindex d4554bb97,2d1197f10..ea7e78ca4--- a/deeptutor/knowledge/add_documents.py+++ b/deeptutor/knowledge/add_documents.py@@@ -191,26 -190,15 +191,29 @@@ class DocumentAdderf"Knowledge base '{kb_name}' uses legacy index format and requires reindex before incremental add")- allows_lightrag_bootstrap = self.rag_provider == LIGHTRAG_PROVIDER and not list_kb_versions(- self.kb_dir- )- if not has_provider_index and not allows_lightrag_bootstrap:+ # Both pipelines create their first index on add; existing broken versions+ # still require reindex instead of being silently replaced (#1458).+ allows_bootstrap = self.rag_provider in {+ DEFAULT_PROVIDER,+ LIGHTRAG_PROVIDER,+ } and not list_kb_versions(self.kb_dir)+ if not has_provider_index and not allows_bootstrap:raise ValueError(f"Knowledge base not initialized ({self.rag_provider}): {kb_name}")+ self.accepted_indexing_snapshot = accepted_indexing_snapshot+ if self.rag_provider == LIGHTRAG_PROVIDER and self.accepted_indexing_snapshot is None:+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (+ bind_target,+ resolve_write_snapshot,+ )++ self.accepted_indexing_snapshot = bind_target(+ resolve_write_snapshot(+ self.kb_dir, base_dir=str(self.base_dir), kb_name=self.kb_name+ ),+ self.kb_dir,+ )+self.api_key = api_keyself.base_url = base_urlself.progress_tracker = progress_trackerdiff --cc deeptutor/services/rag/embedding_binding.pyindex 000000000,ca9b3fc4b..0433a7cb2mode 000000,100644..100644--- a/deeptutor/services/rag/embedding_binding.py+++ b/deeptutor/services/rag/embedding_binding.py@@@ -1,0 -1,306 +1,310 @@@+ """Per-knowledge-base embedding references and compatible legacy migration.++ Persist catalog IDs and index identity only. Credentials are always resolved+ from the current catalog; changing the global default never changes a binding.+ """++ from __future__ import annotations++ from functools import wraps+ from pathlib import Path+ from typing import TYPE_CHECKING++ if TYPE_CHECKING:+ from deeptutor.services.embedding.config import EmbeddingConfig++ from .embedding_signature import signature_from_config++ EMBEDDING_PROVIDERS = {"llamaindex", "graphrag", "lightrag"}+++ def get_embedding_config(selection=None, *, catalog=None):+ # Config imports the RAG factory during package initialization.+ from deeptutor.services.embedding.config import get_embedding_config as resolve++ return resolve(selection, catalog=catalog)+++ def uses_bound_embedding(entry: dict) -> bool:+ from deeptutor.knowledge.kb_types import is_connected_kb++ return (+ not is_connected_kb(entry)+ and entry.get("rag_provider", "llamaindex") in EMBEDDING_PROVIDERS+ )+++ def load_catalog() -> dict:+ from deeptutor.services.config import get_model_catalog_service++ return get_model_catalog_service().load()+++ def default_selection(catalog: dict | None = None) -> dict | None:+ service = (+ (catalog if catalog is not None else load_catalog())+ .get("services", {})+ .get("embedding", {})+ )+ if service.get("active_profile_id") and service.get("active_model_id"):+ return {"profile_id": service["active_profile_id"], "model_id": service["active_model_id"]}+ return None+++ def binding_fields(selection: dict, config) -> dict:+ return {+ "embedding_selection": {+ "profile_id": selection["profile_id"],+ "model_id": selection["model_id"],+ },+ "embedding_model": config.model,+ "embedding_dim": config.dim,+ "embedding_signature": signature_from_config(config).hash(),+ "embedding_status": "ready",+ "embedding_mismatch": False,+ }+++ def migrate_binding(entry: dict, kb_dir: Path, catalog: dict | None = None) -> bool:+ """Pin only when existing evidence identifies a compatible catalog model.++ Older indexes without enough evidence retain their legacy read path. A+ successful full rebuild will pin the model that produced the new vectors.+ """+ if entry.get("embedding_selection") or not uses_bound_embedding(entry):+ return False+ from .index_versioning import list_kb_versions++ catalog = catalog if catalog is not None else load_catalog()+ versions = list_kb_versions(kb_dir)+ signatures = {v.get("embedding_signature") or v.get("signature") for v in versions}+ stored_signature = entry.get("embedding_signature")+ if stored_signature in EMBEDDING_PROVIDERS | {"legacy"}:+ stored_signature = None+ matches = []+ for profile in catalog.get("services", {}).get("embedding", {}).get("profiles", []):+ for model in profile.get("models", []):+ selection = {"profile_id": profile.get("id"), "model_id": model.get("id")}+ try:+ config = get_embedding_config(selection, catalog=catalog)+ except ValueError:+ continue+ signature = signature_from_config(config).hash()+ # Prefer the recorded index identity, not whichever version happens+ # to match today's global default.+ if stored_signature:+ matches_index = signature == stored_signature+ elif entry.get("embedding_model"):+ matches_index = (+ config.model == entry["embedding_model"]+ and (not entry.get("embedding_dim") or config.dim == entry["embedding_dim"])+ and (+ not signatures+ or signature in signatures+ or all(s in EMBEDDING_PROVIDERS | {"legacy"} or not s for s in signatures)+ )+ )+ else:+ matches_index = signature in signatures+ if matches_index:+ matches.append((selection, config))+ if not matches:+ return False+ # Duplicate catalog entries for the same vector space are equivalent. If+ # there are different identities, leave the legacy binding unresolved.+ if len({signature_from_config(config).hash() for _, config in matches}) != 1:+ return False+ active = default_selection(catalog)+ selection, config = next((item for item in matches if item[0] == active), matches[0])+ entry.update(binding_fields(selection, config))+ return True+++ def binding_status(+ entry: dict, *, catalog: dict | None = None+ ) -> tuple[str, EmbeddingConfig | None]:+ selection = entry.get("embedding_selection")+ if not selection:+ return "legacy", None+ if not isinstance(selection, dict):+ return "missing", None+ catalog = catalog if catalog is not None else load_catalog()+ service = catalog.get("services", {}).get("embedding", {})+ profile = next(+ (p for p in service.get("profiles", []) if p.get("id") == selection.get("profile_id")), None+ )+ if not any(m.get("id") == selection.get("model_id") for m in (profile or {}).get("models", [])):+ return "missing", None+ try:+ config = get_embedding_config(selection, catalog=catalog)+ except ValueError:+ return "unconfigured", None+ if (+ entry.get("embedding_signature")+ and entry["embedding_signature"] != signature_from_config(config).hash()+ ):+ return "changed", config+ return "ready", config+++ def entry_signature(entry: dict):+ """Resolve a bound signature, falling back only for unbound legacy KBs."""+ from .embedding_signature import signature_from_embedding_config++ if not entry.get("embedding_selection"):+ return signature_from_embedding_config()+ status, config = binding_status(entry)+ return signature_from_config(config) if config is not None else None+++ def bound_graph_storage_root(kb_dir: Path, provider: str, fallback: Path | None) -> Path | None:+ """Keep graph reads on a compatible version if publishing a new binding failed."""+ from deeptutor.services.embedding.config import scoped_embedding_config++ from .index_probe import inspect_provider_version+ from .index_versioning import list_kb_versions++ config = scoped_embedding_config()+ if config is None or fallback is None:+ return fallback+ expected = signature_from_config(config).hash()+ versions = list_kb_versions(kb_dir)+ for version in versions:+ if version.get("embedding_signature") != expected or not version.get("ready"):+ continue+ root = Path(version["storage_path"])+ if provider == "lightrag":+ from .pipelines.lightrag.storage import meta_is_native_published++ if not meta_is_native_published(root):+ continue+ if inspect_provider_version(version, provider).ready:+ return root+ fallback_entry = next((v for v in versions if Path(v["storage_path"]) == fallback), {})+ if not fallback_entry.get("embedding_signature"):+ return fallback # Older graph indexes did not record embedding identity.+ raise ValueError(+ "No index version matches the bound embedding model. Re-index this knowledge base."+ )+++ def reconcile_bindings(entries: dict, base_dir: Path) -> bool:+ """Refresh binding health without touching files or changing index identity."""+ changed = False+ try:+ catalog = load_catalog()+ except (ValueError, OSError):+ return False+ for name, entry in entries.items():+ if not isinstance(entry, dict) or not uses_bound_embedding(entry):+ continue+ before = dict(entry)+ migrate_binding(entry, base_dir / name, catalog)+ if entry.get("embedding_selection"):+ state, _ = binding_status(entry, catalog=catalog)+ entry["embedding_status"] = state+ had_mismatch = bool(before.get("embedding_mismatch"))+ if state == "changed":+ entry["embedding_mismatch"] = True+ entry["needs_reindex"] = True+ elif state == "ready":+ entry.pop("embedding_mismatch", None)+ if had_mismatch:+ entry["needs_reindex"] = False+ # Keep the legacy index picker supplied with the same version list.+ from .index_probe import inspect_kb_versions++ entry["index_versions"] = inspect_kb_versions(+ base_dir / name, entry.get("rag_provider")+ )+ changed = changed or before != entry+ return changed+++ def _service(base_dir):+ from deeptutor.services.config.knowledge_base_config import KnowledgeBaseConfigService++ return KnowledgeBaseConfigService(Path(base_dir) / "kb_config.json")+++ def persist_binding(base_dir, kb_name: str, selection: dict, config) -> None:+ _service(base_dir).set_kb_config(+ kb_name, {**binding_fields(selection, config), "needs_reindex": False}+ )+++ def with_kb_embedding(method):+ """Resolve and isolate the model for the entire async RAG operation."""++ @wraps(method)+ async def wrapped(self, *args, **kwargs):+ # search(query, kb_name); initialize/add_documents(kb_name, files).+ kb_name = kwargs.get("kb_name") or args[1 if method.__name__ == "search" else 0]+ service = _service(self.kb_base_dir)+ entry = service.get_kb_config(kb_name)+ entry["rag_provider"] = self._resolve_provider(kb_name)+ if not uses_bound_embedding(entry):+ return await method(self, *args, **kwargs)+ selection = kwargs.pop("embedding_selection", None)+ frozen_config = kwargs.pop("embedding_config", None)++ if frozen_config is None and entry["rag_provider"] == "lightrag":++ snapshot = kwargs.get("indexing_snapshot") or kwargs.get("accepted_indexing_snapshot")++ if snapshot is not None:++ frozen_config = snapshot.embedding_config+ explicit = selection is not None+ if not explicit:+ if migrate_binding(entry, Path(self.kb_base_dir) / kb_name):+ service.set_kb_config(+ kb_name, {k: v for k, v in entry.items() if k.startswith("embedding_")}+ )+ selection = entry.get("embedding_selection")+ if not selection and method.__name__ != "initialize":+ from .index_versioning import list_kb_versions++ if list_kb_versions(Path(self.kb_base_dir) / kb_name):+ # In particular, old GraphRAG indexes use the model in+ # their saved settings.yaml. Do not overwrite that runtime+ # with today's default when migration could not identify it.+ return await method(self, *args, **kwargs)+ try:+ if selection:+ status, config = binding_status({**entry, "embedding_selection": selection})+ if status == "missing":+ raise ValueError(+ "The embedding model bound to this knowledge base was deleted. Select another embedding model to re-index it."+ )+ if status == "unconfigured":+ raise ValueError(+ "The bound embedding model is not configured. Check its provider settings."+ )+ if status == "changed" and not explicit:+ raise ValueError(+ "The bound embedding model configuration changed. Re-index this knowledge base before using it."+ )+ if frozen_config is not None:+ config = frozen_config+ else:+ selection = default_selection()+ if selection is None:+ # Preserve legacy callers and installations without a+ # configured catalog. The pipeline retains its own checks.+ return await method(self, *args, **kwargs)+ config = get_embedding_config(selection)+ except ValueError as exc:+ if method.__name__ != "search":+ raise+ return {+ "query": kwargs.get("query", args[0] if args else ""),+ "answer": str(exc),+ "content": "",+ "error_type": "embedding_binding_unavailable",+ }+ from deeptutor.services.embedding.config import embedding_config_scope++ with embedding_config_scope(config):+ result = await method(self, *args, **kwargs)+ if result and method.__name__ != "search" and selection:+ persist_binding(self.kb_base_dir, kb_name, selection, config)+ return result++ return wrappeddiff --cc deeptutor/services/rag/pipelines/lightrag/indexing_policy.pyindex a185a7c6b,bbfa81284..5206a9eca--- a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py+++ b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py@@@ -205,314 -201,11 +205,332 @@@ def _single_snapshot_from_persisted(polreturn snapshot+@dataclass(frozen=True, slots=True)+class IndexingPolicySnapshot:+ """Freeze role identities, runtime limits, and accepted indexing target state."""++ extract: IndexingLLMSnapshot+ vlm: IndexingLLMSnapshot | None+ policy: str = POLICY_PINNED+ limits: dict[str, dict[str, int]] = field(default_factory=dict)+ legacy_policy: dict[str, Any] | None = None+ target_version: str | None = None+ target_bound: bool = False+ target_policy: str | None = None+ image_analysis: bool | None = None+ target_revision: str | None = None+ embedding_config: Any | None = field(default=None, repr=False, compare=False)++ @property+ def vision_available(self) -> bool:+ """Return whether the pinned vision model supports image inputs."""+ return self.vlm is not None and self.vlm.vision_available++ def persisted_policy(self) -> dict[str, Any]:+ """Serialize role identities while preserving an existing legacy policy."""+ if self.legacy_policy is not None:+ # Appending must not rewrite the old fingerprint as a v2 identity.+ return dict(self.legacy_policy)+ return {+ "schema_version": 2,+ "policy": self.policy,+ "extract": self.extract.persisted_policy(),+ "vlm": {+ "mode": "enabled" if self.vlm else "disabled",+ **({"snapshot": self.vlm.persisted_policy()} if self.vlm else {}),+ },+ }+++def _role_identity(snapshot: IndexingLLMSnapshot, *, vision: bool) -> dict[str, Any]:+ config = snapshot.config+ return {+ **_canonical_identity(+ snapshot.selection,+ config,+ vision_available=snapshot.vision_available if vision else None,+ ),+ "wire_api": config.wire_api,+ "api_format": config.api_format,+ "context_window": config.context_window,+ }+++def _with_role_identity(snapshot: IndexingLLMSnapshot, *, vision: bool) -> IndexingLLMSnapshot:+ snapshot = replace(+ snapshot,+ selection=replace(snapshot.selection, reasoning_effort=snapshot.config.reasoning_effort),+ )+ identity = _role_identity(snapshot, vision=vision)+ return replace(snapshot, descriptor=identity, fingerprint=_fingerprint(identity))+++def _freeze_role(+ selection_value: Any, *, vision: bool = False, provider_default: bool = True+) -> IndexingLLMSnapshot:+ from deeptutor.services.config.lightrag_roles import LightRagModelSelection++ from .roles import resolve_selection++ if isinstance(selection_value, LLMSelection):+ selection_value = selection_value.to_dict()+ selected = LightRagModelSelection.model_validate(selection_value)+ selection = LLMSelection(**selected.model_dump())+ try:+ config = resolve_selection(selection, vision=vision, provider_default=provider_default)+ except (ValueError, PermissionError, LLMConfigError) as exc:+ raise IndexingPolicyError(str(exc)) from exc+ explicit_user = get_current_user_or_none()+ if config.binding in OWNER_BOUND_BINDINGS and explicit_user is None:+ raise IndexingPolicyError(+ "Owner-bound indexing models require an explicit initiating user scope."+ )+ snapshot = IndexingLLMSnapshot(+ config=config,+ owner=explicit_user or get_current_user(),+ policy=POLICY_PINNED,+ selection=replace(selection, reasoning_effort=config.reasoning_effort),+ descriptor={},+ fingerprint=None,+ vision_available=supports_vision(config.binding, config.model),+ )+ return _with_role_identity(snapshot, vision=vision)+++def freeze_roles(+ selection_value: Any = None, *, policy: str = POLICY_PINNED+) -> IndexingPolicySnapshot:+ """Freeze create/rebuild choices; old request bodies still mean one model."""+ from deeptutor.services.config import load_lightrag_settings+ from deeptutor.services.config.lightrag_roles import LightRagIndexingSelection++ from .roles import runtime_limits, settings_models++ settings = load_lightrag_settings()+ models = settings_models(settings)+ limits = runtime_limits(settings)+ if selection_value is None and models is None and settings.get("version") == 2:+ raise IndexingPolicyError("Choose a LightRAG base model or explicit indexing models first.")+ if selection_value is None and models is not None:+ extract_selection = models.selection_for("extract").model_dump()+ vlm_selection = models.selection_for("vlm")+ value = {+ "extract": extract_selection,+ "vlm": {"mode": "enabled", "selection": vlm_selection.model_dump()}+ if vlm_selection+ else {"mode": "disabled"},+ }+ elif (+ selection_value is not None+ and isinstance(selection_value, dict)+ and "extract" in selection_value+ ):+ value = selection_value+ else:+ # Supported v1 settings and form producer: freeze the one known model,+ # including its known vision capability, before constructing v2 roles.+ single = (+ freeze_snapshot(selection_value, policy=POLICY_PINNED)+ if selection_value is not None+ else _freeze_legacy_default_snapshot()+ )+ if single.selection is None:+ raise IndexingPolicyError("Choose a catalog model before creating a LightRAG index.")+ selected = single.selection.to_dict()+ value = {+ "extract": selected,+ "vlm": {"mode": "enabled", "selection": selected}+ if single.vision_available and settings.get("version") != 2+ else {"mode": "disabled"},+ }+ parsed = LightRagIndexingSelection.model_validate(value)+ extract = _freeze_role(parsed.extract.model_dump())+ vlm = (+ _freeze_role(parsed.vlm.selection.model_dump(), vision=True)+ if parsed.vlm.selection+ else None+ )+ return IndexingPolicySnapshot(extract, vlm, policy=policy, limits=limits)+++def freeze_default_snapshot() -> IndexingPolicySnapshot:+ return freeze_roles()+++def snapshot_from_persisted(policy: dict[str, Any]) -> IndexingPolicySnapshot:+ from deeptutor.services.config import load_lightrag_settings++ from .roles import runtime_limits++ if not isinstance(policy, dict) or policy.get("policy") not in {POLICY_PINNED, POLICY_PENDING}:+ raise IndexingModelChangedError(+ "The index has no verified model policy; run a full re-index."+ )+ limits = runtime_limits(load_lightrag_settings())+ if "schema_version" not in policy:+ single = _single_snapshot_from_persisted(policy)+ if policy["policy"] == POLICY_PENDING:+ return IndexingPolicySnapshot(+ _with_role_identity(single, vision=False),+ _with_role_identity(single, vision=True) if single.vision_available else None,+ policy=POLICY_PENDING,+ limits=limits,+ )+ return IndexingPolicySnapshot(+ single,+ single if single.vision_available else None,+ policy=policy["policy"],+ limits=limits,+ legacy_policy=dict(policy),+ )+ if type(policy["schema_version"]) is not int or policy["schema_version"] != 2:+ raise IndexingPolicyError("Unsupported LightRAG indexing-policy version.")+ vision = policy.get("vlm")+ if not isinstance(vision, dict) or vision.get("mode") not in {"disabled", "enabled"}:+ raise IndexingPolicyError("Invalid LightRAG vision policy.")+ if vision["mode"] == "disabled" and "snapshot" in vision:+ raise IndexingPolicyError("A disabled VLM cannot have an indexing snapshot.")++ def restore(value: Any, *, vision: bool = False) -> IndexingLLMSnapshot:+ if not isinstance(value, dict) or not isinstance(value.get("selection"), dict):+ raise IndexingPolicyError("Invalid LightRAG role snapshot.")+ descriptor = value.get("descriptor")+ result = _freeze_role(+ value["selection"],+ vision=vision,+ provider_default=isinstance(descriptor, dict)+ and descriptor.get("reasoning_effort") == "",+ )+ if not value.get("fingerprint") or result.fingerprint != value["fingerprint"]:+ raise IndexingModelChangedError("The pinned role model changed; run a full re-index.")+ return result++ return IndexingPolicySnapshot(+ restore(policy.get("extract")),+ restore(vision.get("snapshot"), vision=True) if vision["mode"] == "enabled" else None,+ policy=policy["policy"],+ limits=limits,+ )+++def revalidate_snapshot(snapshot: IndexingPolicySnapshot) -> IndexingPolicySnapshot:+ """Refresh credentials and permissions without changing frozen task settings."""+ from deeptutor.multi_user.paths import user_context++ with user_context(snapshot.extract.owner):+ fresh = snapshot_from_persisted(snapshot.persisted_policy())+ return replace(+ fresh,+ limits=snapshot.limits,+ target_version=snapshot.target_version,+ target_bound=snapshot.target_bound,+ target_policy=snapshot.target_policy,+ image_analysis=snapshot.image_analysis,+ target_revision=snapshot.target_revision,+ embedding_config=snapshot.embedding_config,+ )++++def _bound_published_root(kb_dir: Path) -> Path | None:++ """Use the published version selected by the KB's existing embedding binding."""++ from deeptutor.services.config.knowledge_base_config import KnowledgeBaseConfigService++ from deeptutor.services.embedding.config import embedding_config_scope++ from deeptutor.services.rag.embedding_binding import binding_status, bound_graph_storage_root++++ from .storage import latest_published_root++++ latest = latest_published_root(kb_dir)++ entry = KnowledgeBaseConfigService(kb_dir.parent / "kb_config.json").get_kb_config(kb_dir.name)++ _, config = binding_status(entry)++ if config is not None:++ with embedding_config_scope(config):++ try:++ return bound_graph_storage_root(kb_dir, "lightrag", latest)++ except ValueError:++ # A rebuild must still be able to replace an incompatible index.++ # Query/append binding checks independently reject this identity.++ pass++ return latest+++++def _target_policy_key(kb_dir: Path) -> str | None:+ policy = effective_policy(kb_dir, base_dir=str(kb_dir.parent), kb_name=kb_dir.name)+ return (+ _fingerprint({key: value for key, value in policy.items() if key != "vlm_used"})+ if policy is not None+ else None+ )+++def _content_revision(root: Path | None) -> str:+ # Native document-status flushes are atomic. Track inode and nanosecond+ # timestamps as well as size so a same-version append invalidates a queued rebuild.+ from .storage import _store_root++ revisions = {}+ if root is not None:+ paths = {+ "meta.json": root / "meta.json",+ "kv_store_doc_status.json": _store_root(root) / "kv_store_doc_status.json",+ }+ for name, path in paths.items():+ try:+ stat = path.stat()+ revisions[name] = [stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns]+ except FileNotFoundError:+ revisions[name] = None+ return _fingerprint(revisions)+++def bind_target(+ snapshot: IndexingPolicySnapshot, kb_dir: Path, *, protect_contents: bool = False+) -> IndexingPolicySnapshot:+ """Bind a snapshot to the current index and optionally its content revision."""- from .storage import latest_published_root-- target = latest_published_root(kb_dir)- snapshot = with_embedding(snapshot)++ target = _bound_published_root(kb_dir)++ snapshot = with_embedding(snapshot, kb_dir=kb_dir)+ return replace(+ snapshot,+ target_version=str(target) if target else None,+ target_bound=True,+ target_policy=_target_policy_key(kb_dir),+ target_revision=_content_revision(target) if protect_contents else None,+ )+++def validate_target(snapshot: IndexingPolicySnapshot, kb_dir: Path) -> None:+ """Reject a queued write if its bound index, policy, or revision changed."""- from .storage import latest_published_root-+ if not snapshot.target_bound:+ return- target = latest_published_root(kb_dir)++ target = _bound_published_root(kb_dir)+ if (+ snapshot.target_version != (str(target) if target else None)+ or snapshot.target_policy != _target_policy_key(kb_dir)+ or (+ snapshot.target_revision is not None+ and snapshot.target_revision != _content_revision(target)+ )+ ):+ raise IndexingPolicyError(+ "The target index or pending policy changed while queued; resubmit this operation."+ )+++def with_image_analysis(+ snapshot: IndexingPolicySnapshot, requested: bool | None+) -> IndexingPolicySnapshot:+ """Record the requested image mode, rejecting unavailable pinned vision."""+ if requested is True and not snapshot.vision_available:+ raise IndexingModelChangedError(+ "Image analysis is disabled for this index; run a full re-index with a VLM."+ )+ return replace(snapshot, image_analysis=requested)++def effective_policy(kb_dir: Path, *, base_dir: str, kb_name: str) -> dict[str, Any] | None:"""Return published policy first, then pre-publication pending policy."""-- from .storage import latest_published_root, read_published_policy++ from .storage import read_published_policy-- root = latest_published_root(kb_dir)++ root = _bound_published_root(kb_dir)published = read_published_policy(root)if published is not None:return published@@@ -553,34 -238,6 +571,58 @@@ def resolve_write_snapshotreturn snapshot_from_persisted(policy)- def with_embedding(snapshot: IndexingPolicySnapshot) -> IndexingPolicySnapshot:++def with_embedding(++ snapshot: IndexingPolicySnapshot, *, kb_dir: Path | None = None++) -> IndexingPolicySnapshot:+ """Freeze embedding configuration once, before accepting an indexing task."""+ if snapshot.embedding_config is not None:+ return snapshot+ from deeptutor.services.embedding import get_embedding_config+- config = deepcopy(get_embedding_config())++ config = None++ if kb_dir is not None:++ from deeptutor.services.config.knowledge_base_config import KnowledgeBaseConfigService++ from deeptutor.services.rag.embedding_binding import binding_status++++ entry = KnowledgeBaseConfigService(kb_dir.parent / "kb_config.json").get_kb_config(++ kb_dir.name++ )++ state, config = binding_status(entry)++ if state in {"missing", "unconfigured", "changed"}:++ raise IndexingPolicyError(++ "The bound embedding model is unavailable or changed. Restore its configuration or rebuild."++ )++ config = deepcopy(config if config is not None else get_embedding_config())+ if not config.dim:+ raise IndexingPolicyError(+ "Configure an embedding model with a known dimension in Settings."+ )+ return replace(snapshot, embedding_config=config)++- def public_rebuild_config(snapshot: IndexingPolicySnapshot) -> dict[str, Any]:++def public_rebuild_config(++ snapshot: IndexingPolicySnapshot, embedding_selection: dict | None = None++) -> dict[str, Any]:+ """Bind the confirmation to resolved identities without exposing credentials."""+ from deeptutor.services.rag.embedding_signature import signature_from_config++ snapshot = with_embedding(snapshot)+ signature = signature_from_config(snapshot.embedding_config)+ policy = snapshot.persisted_policy()+ return {- "fingerprint": _fingerprint({"indexing_policy": policy, "embedding": signature.hash()}),++ "fingerprint": _fingerprint(++ {++ "indexing_policy": policy,++ "embedding": signature.hash(),++ "embedding_selection": embedding_selection,++ }++ ),+ "indexing_policy": public_policy(policy),+ "embedding": {"model": signature.model, "dimension": signature.dimension},++ "embedding_selection": embedding_selection,+ }++def cache_identity(snapshot: IndexingLLMSnapshot) -> str:if snapshot.fingerprint:return snapshot.fingerprintdiff --cc deeptutor/services/rag/pipelines/lightrag/pipeline.pyindex 58898dedd,53a7f73f5..e69c078ed--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py@@@ -449,8 -406,16 +449,11 @@@ class LightRagPipelineself._ensure_available()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++ existing = bound_graph_storage_root(kb_dir, storage.PROVIDER, existing)versions = list_kb_versions(kb_dir)explicit = kwargs.get("indexing_snapshot")- if explicit is not None and (existing is not None or versions):- raise IndexingPolicyError(- "An explicit LightRAG indexing model cannot override an existing index; "- "run a full re-index."- )if existing is None and versions:raise LightRagNeedsReindexError("This LightRAG index is legacy, unpublished, or corrupt and must be rebuilt "diff --cc tests/api/test_knowledge_router.pyindex 208b4bf0b,7aa578538..7168663c9--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@@ -2450,14 -2446,10 +2450,16 @@@ def test_reindex_passes_frozen_lightragmonkeypatch.setattr(knowledge_router_module, "_assert_provider_ready", lambda _provider: None)monkeypatch.setattr(knowledge_router_module,- "_freeze_indexing_llm_form",- lambda _raw: ({"profile_id": "profile-1", "model_id": "model-1"}, snapshot),+ "_freeze_default_indexing_llm",+ lambda: snapshot,)monkeypatch.setattr(knowledge_router_module, "run_reindex_task", capture_task)+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.indexing_policy.public_rebuild_config",- lambda accepted: {"fingerprint": "confirmed"} if accepted is snapshot else {},++ lambda accepted, selection=None: (++ {"fingerprint": "confirmed"} if accepted is snapshot else {}++ ),+ )with TestClient(_build_app()) as client:response = client.post(diff --cc tests/knowledge/test_document_adder_provider.pyindex ed8fab710,5e78be8c5..f0fae7a33--- a/tests/knowledge/test_document_adder_provider.py+++ b/tests/knowledge/test_document_adder_provider.py@@@ -78,46 -80,18 +80,48 @@@ def test_document_adder_preserves_expliassert adder.rag_provider == "graphrag"- def test_document_adder_allows_empty_lightrag_kb_to_bootstrap(monkeypatch, tmp_path: Path) -> None:+ @pytest.mark.parametrize("provider", ["llamaindex", "lightrag"])-def test_document_adder_allows_empty_kb_to_bootstrap(tmp_path: Path, provider: str) -> None:++def test_document_adder_allows_empty_kb_to_bootstrap(monkeypatch, tmp_path: Path, provider) -> None:+ from deeptutor.services import config+ from deeptutor.services.llm.config import LLMConfig+ from deeptutor.services.rag.pipelines.lightrag import roles++ monkeypatch.setattr(+ config,+ "load_lightrag_settings",+ lambda: {+ "version": 2,+ "role_models": {"base": {"profile_id": "fixture", "model_id": "fixture"}},+ },+ )+ monkeypatch.setattr(+ roles,+ "resolve_selection",+ lambda *_args, **_kwargs: LLMConfig(+ model="fixture", binding="openai", api_key="offline-fixture"+ ),+ )+ from deeptutor.services.embedding.config import EmbeddingConfig++ monkeypatch.setattr(+ "deeptutor.services.embedding.get_embedding_config",+ lambda: EmbeddingConfig(+ model="embed-fixture", api_key="fake", dim=3, base_url="https://embed.test"+ ),+ )(tmp_path / "empty-kb").mkdir()adder = DocumentAdder(kb_name="empty-kb",base_dir=str(tmp_path),- rag_provider="lightrag",+ rag_provider=provider,)- assert adder.rag_provider == "lightrag"+ assert adder.rag_provider == providerassert adder.raw_dir.is_dir()- assert adder.accepted_indexing_snapshot.extract.config.model == "fixture"- assert adder.accepted_indexing_snapshot.vlm is None++ if provider == "lightrag":++ assert adder.accepted_indexing_snapshot.extract.config.model == "fixture"++ assert adder.accepted_indexing_snapshot.vlm is Nonedef test_process_new_documents_returns_failures_without_marking_processed(diff --cc tests/services/rag/test_lightrag_roles.pyindex e1c12c7fe,000000000..d2c218547mode 100644,000000..100644--- a/tests/services/rag/test_lightrag_roles.py+++ b/tests/services/rag/test_lightrag_roles.py@@@ -1,1004 -1,0 +1,1120 @@@+"""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: state["embedding"]++ "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_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):+ (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):+ (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):+ 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):+ 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()++ 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):++ 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/CreateKbModal.tsxindex e3cbbf39c,0a3c0221e..e0471e039--- a/web/components/knowledge/CreateKbModal.tsx+++ b/web/components/knowledge/CreateKbModal.tsx@@@ -75,6 -77,8 +79,7 @@@ interface CreateKbModalPropsfiles: File[];pageindexMode?: "flash" | "standard";searchMode?: string;- indexingLLM?: IndexingLLMSelection;+ embeddingModel?: EmbeddingModelSelection;}) => Promise<void>;/** Link a pre-built engine index folder in place (no copy, no re-index). */onConnectLinkedFolder: (params: {@@@ -424,18 -410,14 +437,25 @@@ export default function CreateKbModal(!!weKnoraProbe?.ok);}+ if (+ provider === "lightrag" &&+ (!lightRagConfigLoaded ||+ lightRagConfigError ||+ llmCatalog.loading ||+ llmCatalog.error ||+ !isCompleteIndexingSelection(+ lightRagIndexingDefaults,+ llmCatalog.options,+ ))+ )+ return false;+ if (+ needsEmbedding &&+ (!embeddingCatalog.selection ||+ embeddingCatalog.loading ||+ embeddingCatalog.error)+ )+ return false;- if (provider === "lightrag" && !indexingLLM) return false;return !providerUnavailable;}if (linkIsIma) return imaConnection.canSubmit;@@@ -537,6 -519,11 +557,9 @@@pageindexMode:isPageIndexOSS && pageIndexMode ? pageIndexMode : undefined,searchMode: retrievalMode || undefined,+ embeddingModel: needsEmbedding+ ? embeddingCatalog.selection || undefined+ : undefined,- indexingLLM:- provider === "lightrag" ? indexingLLM || undefined : undefined,});}} else if (linkIsIma) {@@@ -667,21 -654,33 +690,29 @@@setFiles={setFiles}policyForProvider={policyForProvider}indexingModelField={- provider === "lightrag" &&- (lightRagConfigError ||- llmCatalog.error ||- (lightRagConfigLoaded &&- !llmCatalog.loading &&- !isCompleteIndexingSelection(- lightRagIndexingDefaults,- llmCatalog.options,- ))) ? (- <p role="alert" className="text-[12px] text-red-600">- {t(- "Configure valid LightRAG defaults in Settings before creating a knowledge base.",- )}- </p>- ) : null+ <div className="space-y-4">+ {needsEmbedding && (+ <EmbeddingModelSelector+ catalog={embeddingCatalog}+ disabled={submitting}+ />+ )}- {provider === "lightrag" ? (- <IndexingModelSelector- options={llmCatalog.options}- selection={indexingLLM}- loading={llmCatalog.loading}- error={llmCatalog.error}- defaultUnavailable={- lightRagConfigLoaded &&- !!(- lightRagConfig?.llm_profile_id ||- lightRagConfig?.llm_model_id- ) &&- !indexingLLM- }- defaultLoadError={lightRagConfigError}- disabled={submitting}- onChange={setIndexingLLM}- />++ {provider === "lightrag" &&++ (lightRagConfigError ||++ llmCatalog.error ||++ (lightRagConfigLoaded &&++ !llmCatalog.loading &&++ !isCompleteIndexingSelection(++ lightRagIndexingDefaults,++ llmCatalog.options,++ ))) ? (++ <p role="alert" className="text-[12px] text-red-600">++ {t(++ "Configure valid LightRAG defaults in Settings before creating a knowledge base.",++ )}++ </p>+ ) : null}+ </div>}connectionForm={isLightRagServer ? (diff --cc web/components/knowledge/KbIndexVersionsSection.tsxindex aa952fe6b,06b9e568a..b2c5dbd02--- a/web/components/knowledge/KbIndexVersionsSection.tsx+++ b/web/components/knowledge/KbIndexVersionsSection.tsx@@@ -1,6 -1,9 +1,9 @@@"use client";- import { useState } from "react";+ import { useEffect, useState } from "react";+ import { useEmbeddingModels } from "@/hooks/useEmbeddingModels";-import EmbeddingModelSelector from "./EmbeddingModelSelector";+ import type { EmbeddingModelSelection } from "@/features/knowledge/model/types";++import EmbeddingModelSelector from "./EmbeddingModelSelector";import { useTranslation } from "react-i18next";import {AlertTriangle,@@@ -24,19 -27,53 +27,22 @@@ importtype KnowledgeBase,} from "@/lib/knowledge-helpers";import type { TaskState } from "@/hooks/useKnowledgeProgress";- import ProcessLogs from "@/components/common/ProcessLogs";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";--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);-}++import { knowledgeBaseRef } from "@/lib/knowledge-helpers";interface KbIndexVersionsSectionProps {kb: KnowledgeBase;task?: TaskState;- onReindex: (configFingerprint?: string) => Promise<void>;+ onReindex: (- indexingLLM?: IndexingLLMSelection,++ configFingerprint?: string,+ embeddingModel?: EmbeddingModelSelection,+ ) => Promise<void>;- onUpdatePendingIndexingPolicy: (- indexingLLM: IndexingLLMSelection,- ) => Promise<void>;}export default function KbIndexVersionsSection({@@@ -47,12 -85,25 +53,19 @@@const { t } = useTranslation();const [submitting, setSubmitting] = useState(false);const [modelDialogOpen, setModelDialogOpen] = useState(false);- const [indexingLLM, setIndexingLLM] = useState<IndexingLLMSelection | null>(- null,- );+ const [rebuildConfig, setRebuildConfig] =+ useState<LightRagRebuildConfig | null>(null);const [dialogError, setDialogError] = useState<string | null>(null);- const [lightRagConfig, setLightRagConfig] = useState<LightRagConfig | null>(- null,- );- const [lightRagConfigLoaded, setLightRagConfigLoaded] = useState(false);- const [lightRagConfigError, setLightRagConfigError] = useState(false);- const llmCatalog = useLLMOptions();+ const [configLoading, setConfigLoading] = useState(false);const provider = kb.statistics?.rag_provider || "llamaindex";const isLightRag = provider === "lightrag";+ const needsEmbedding = ["llamaindex", "lightrag", "graphrag"].includes(+ provider,+ );+ const embeddingCatalog = useEmbeddingModels(+ kb.metadata?.embedding_selection,+ modelDialogOpen && needsEmbedding,+ );const pageIndexProvider = !providerUsesEmbeddingMetadata(provider);const modelInsensitiveProvider = pageIndexProvider || isLightRag;const versions = kb.statistics?.index_versions ?? [];@@@ -76,23 -126,68 +88,58 @@@const buildingLightRagVersion = isLightRag? currentLightRagBuildCandidate(versions, Boolean(isReindexingHere)): undefined;- const emptyPendingEligible =- isLightRag &&- !kb.read_only &&- kb.statistics?.raw_documents === 0 &&- !publishedLightRagVersion &&- !kbHasLiveProgress(kb) &&- !task?.executing;+ const loadRebuildConfig = async () => {+ setRebuildConfig(null);+ setConfigLoading(true);+ try {- setRebuildConfig(await getReindexConfig(kb.name));++ setRebuildConfig(++ await getReindexConfig(++ knowledgeBaseRef(kb),++ embeddingCatalog.selection || undefined,++ ),++ );+ } catch (error) {+ setDialogError(error instanceof Error ? error.message : String(error));+ } finally {+ setConfigLoading(false);+ }+ };++ const selectedProfile = embeddingCatalog.selection?.profile_id;++ const selectedModel = embeddingCatalog.selection?.model_id;++ const kbRef = knowledgeBaseRef(kb);+ useEffect(() => {- if (!isLightRag) return;++ if (!modelDialogOpen || !isLightRag || !selectedProfile || !selectedModel)++ return;+ let cancelled = false;- void getLightRagConfig()++ setRebuildConfig(null);++ setConfigLoading(true);++ setDialogError(null);++ void getReindexConfig(kbRef, {++ profile_id: selectedProfile,++ model_id: selectedModel,++ })+ .then((config) => {- if (!cancelled) {- setLightRagConfig(config);- setLightRagConfigError(false);- }++ if (!cancelled) setRebuildConfig(config);+ })- .catch(() => {- if (!cancelled) setLightRagConfigError(true);++ .catch((error) => {++ if (!cancelled)++ setDialogError(++ error instanceof Error ? error.message : String(error),++ );+ })+ .finally(() => {- if (!cancelled) setLightRagConfigLoaded(true);++ if (!cancelled) setConfigLoading(false);+ });+ return () => {+ cancelled = true;+ };- }, [isLightRag, t]);-- useEffect(() => {- if (!modelDialogOpen || indexingLLM || llmCatalog.options.length === 0)- return;- if (!lightRagConfigLoaded || !lightRagConfig) return;- setIndexingLLM(- selectionForLightRagModelDialog(- llmCatalog.options,- lightRagConfig,- llmCatalog.activeDefault,- kb.metadata?.indexing_policy?.selection,- emptyPendingEligible,- ),- );- }, [- emptyPendingEligible,- indexingLLM,- kb.metadata?.indexing_policy?.selection,- llmCatalog.activeDefault,- llmCatalog.options,- lightRagConfig,- lightRagConfigLoaded,- modelDialogOpen,- ]);-- const openModelDialog = () => {- setIndexingLLM(null);- setDialogError(null);- setModelDialogOpen(true);- };++ }, [modelDialogOpen, isLightRag, selectedProfile, selectedModel, kbRef]);+const handleReindex = async () => {- if (isLightRag) {- if (needsEmbedding) {- openModelDialog();++ if (isLightRag || needsEmbedding) {+ setDialogError(null);+ setModelDialogOpen(true);- await loadRebuildConfig();return;}setSubmitting(true);@@@ -104,15 -199,32 +151,18 @@@};const handleModelSubmit = async () => {- if (!rebuildConfig) return;- if (isLightRag && !indexingLLM) return;- if (needsEmbedding && !embeddingCatalog.selection) return;++ if (isLightRag && !rebuildConfig) return;setSubmitting(true);setDialogError(null);try {- await onReindex(rebuildConfig.fingerprint);- if (emptyPendingEligible) {- const saved = kb.metadata?.embedding_selection;- const selected = embeddingCatalog.selection;- if (- selected &&- (selected.profile_id !== saved?.profile_id ||- selected.model_id !== saved?.model_id ||- kb.metadata?.embedding_status !== "ready")- ) {- await onReindex(indexingLLM || undefined, selected);- }- if (indexingLLM) await onUpdatePendingIndexingPolicy(indexingLLM);- } else {- await onReindex(- isLightRag ? indexingLLM || undefined : undefined,- embeddingCatalog.selection || undefined,- );- }++ await onReindex(++ rebuildConfig?.fingerprint,++ embeddingCatalog.selection || undefined,++ );setModelDialogOpen(false);} catch (error) {setDialogError(error instanceof Error ? error.message : String(error));- await loadRebuildConfig();++ if (isLightRag) await loadRebuildConfig();} finally {setSubmitting(false);}@@@ -156,10 -274,10 +212,10 @@@): t(isLightRag- ? "Choose a model and publish a new LightRAG index version. The current published version remains available until the rebuild succeeds."+ ? "Rebuild with current defaults. The previous index version is preserved until the rebuild succeeds.": pageIndexProvider? "Rebuild this PageIndex knowledge base. Existing index versions are preserved."- : "Click Re-index to rebuild this knowledge base with the active embedding model. Existing index versions are preserved.",+ : "Choose an embedding model to rebuild this knowledge base. Existing index versions are preserved.",)}className={`inline-flex shrink-0 items-center gap-1.5 rounded-md border px-2.5 py-1 text-[12px] font-medium transition-colors disabled:opacity-50 ${@@@ -185,19 -305,28 +241,39 @@@</div>{isError && <KbIndexFailureBanner kb={kb} />}+ {kb.metadata?.embedding_status === "missing" && (+ <p+ role="alert"+ className="rounded-lg border border-amber-300 p-3 text-xs text-amber-700"+ >+ {t(+ "The bound embedding model was deleted. Your documents and indexes are preserved. Select another model to re-index this knowledge base.",+ )}+ </p>+ )}+ {kb.metadata?.embedding_status === "unconfigured" && (+ <p+ role="alert"+ className="rounded-lg border border-amber-300 p-3 text-xs text-amber-700"+ >+ {t(+ "The bound embedding model is not configured. Check its provider settings.",+ )}+ </p>+ )}- {isLightRag && (+ {isLightRag && kb.metadata?.indexing_model_unavailable && (+ <p+ role="alert"+ className="rounded-lg border border-amber-200 bg-amber-50/80 px-3 py-2 text-[12px] text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/20 dark:text-amber-300"+ >+ {t(+ "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.",+ )}+ </p>+ )}++ {isLightRag && publishedLightRagVersion && (<LightRagIndexingProvenancepolicy={kb.metadata?.indexing_policy}version={publishedLightRagVersion}@@@ -322,7 -415,14 +361,14 @@@<buttontype="button"onClick={() => void handleModelSubmit()}- disabled={submitting || configLoading || !rebuildConfig}+ disabled={+ submitting ||- (isLightRag && !indexingLLM) ||++ (isLightRag && (configLoading || !rebuildConfig)) ||+ (needsEmbedding &&+ (!embeddingCatalog.selection ||+ embeddingCatalog.loading ||+ !!embeddingCatalog.error))+ }className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] disabled:opacity-50">{submitting && <Loader2 className="h-3 w-3 animate-spin" />}@@@ -332,22 -434,37 +378,28 @@@}><div className="space-y-3 p-4">- <p className="text-[12px] text-[var(--muted-foreground)]">- {emptyPendingEligible- ? t(- "This selection will take effect when the empty knowledge base is indexed for the first time.",- )- : t(- "A full re-index publishes a new version and then makes this model the pinned identity for future incremental uploads.",- )}- </p>+ {needsEmbedding && (+ <EmbeddingModelSelector+ catalog={embeddingCatalog}+ disabled={submitting}+ />+ )}- {isLightRag && (- <IndexingModelSelector- options={llmCatalog.options}- selection={indexingLLM}- loading={llmCatalog.loading}- error={llmCatalog.error}- defaultUnavailable={- lightRagConfigLoaded &&- !!(- lightRagConfig?.llm_profile_id || lightRagConfig?.llm_model_id- ) &&- !indexingLLM- }- defaultLoadError={lightRagConfigError}- disabled={submitting}- onChange={setIndexingLLM}+ <p className="text-[12px] text-[var(--muted-foreground)]">+ {t(- "This rebuild uses the defaults shown below for the full index. Change 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.",+ )}+ </p>+ {configLoading && (+ <Loader2+ aria-label={t("Loading")}+ className="h-4 w-4 animate-spin"+ />+ )}+ {rebuildConfig && (+ <LightRagIndexingProvenance+ policy={rebuildConfig.indexing_policy}+ embedding={rebuildConfig.embedding}+ title={t("Rebuild configuration")}/>)}{dialogError && (diff --cc web/components/knowledge/KnowledgeBaseDetail.tsxindex e6e68bf3c,e5bedb1cc..b124fc426--- a/web/components/knowledge/KnowledgeBaseDetail.tsx+++ b/web/components/knowledge/KnowledgeBaseDetail.tsx@@@ -52,7 -59,15 +56,11 @@@ interface KnowledgeBaseDetailPropsfiles: File[],destSubdir?: string,) => Promise<void>;- onReindex: (kbName: string, configFingerprint?: string) => Promise<void>;+ onReindex: (+ kbName: string,- indexingLLM?: IndexingLLMSelection,++ configFingerprint?: string,+ embeddingModel?: EmbeddingModelSelection,+ ) => Promise<void>;- onUpdatePendingIndexingPolicy: (- kbName: string,- indexingLLM: IndexingLLMSelection,- ) => Promise<void>;onRetry: (kbName: string) => Promise<void>;onSetDefault: (kbName: string) => Promise<void>;onDelete: (kbName: string) => Promise<void>;@@@ -148,13 -164,9 +156,13 @@@ export default function KnowledgeBaseDeconst handleRetry = async () => {if (!canRetry || retrySubmitting || isReindexingLocally) return;+ if (kbProvider(kb) === "lightrag") {+ setSection("versions");+ return;+ }setRetrySubmitting(true);try {- await onRetry(kb.name);+ await onRetry(knowledgeBaseRef(kb));} finally {setRetrySubmitting(false);}@@@ -297,32 -306,39 +306,45 @@@<KbIndexVersionsSectionkb={kb}task={task}- onReindex={(configFingerprint) =>- onReindex={(indexingLLM, embeddingModel) =>++ onReindex={(configFingerprint, embeddingModel) =>kb.read_only? Promise.resolve()- : status === "error" && kbProvider(kb) !== "lightrag"+ : status === "error" &&+ kbProvider(kb) !== "lightrag" &&+ !embeddingModel? handleRetry()- : onReindex(kb.name, configFingerprint)- : onReindex(knowledgeBaseRef(kb), indexingLLM, embeddingModel)- }- onUpdatePendingIndexingPolicy={(indexingLLM) =>- kb.read_only- ? Promise.resolve()- : onUpdatePendingIndexingPolicy(knowledgeBaseRef(kb), indexingLLM)++ : onReindex(++ knowledgeBaseRef(kb),++ configFingerprint,++ embeddingModel,++ )}/>)}{activeSection === "github" && (- <KbGitHubSourcesSection kbName={kb.name} />+ <KbGitHubSourcesSection kbName={knowledgeBaseRef(kb)} />)}{activeSection === "web" && (- <KbWebSourcesSection kbName={kb.name} />+ <KbWebSourcesSection kbName={knowledgeBaseRef(kb)} />)}{activeSection === "devices" && (- <KbMarginNoteDevicesSection key={kb.name} kb={kb} />- <KbMarginNoteDevicesSection key={knowledgeBaseRef(kb)} kb={kb} />++ <KbMarginNoteDevicesSection++ key={knowledgeBaseRef(kb)}++ kb={kb}++ />)}{activeSection === "settings" && (<KbSettingsSectionkb={kb}onSetDefault={() =>- kb.read_only ? Promise.resolve() : onSetDefault(kb.name)- kb.read_only ? Promise.resolve() : onSetDefault(knowledgeBaseRef(kb))++ kb.read_only++ ? Promise.resolve()++ : onSetDefault(knowledgeBaseRef(kb))}onDelete={() =>- kb.read_only ? Promise.resolve() : onDelete(kb.name)- kb.read_only ? Promise.resolve() : onDelete(knowledgeBaseRef(kb))++ kb.read_only++ ? Promise.resolve()++ : onDelete(knowledgeBaseRef(kb))}/>)}diff --cc web/components/knowledge/KnowledgePage.tsxindex c184aa4fb,ba06b25d6..b4b104b64--- a/web/components/knowledge/KnowledgePage.tsx+++ b/web/components/knowledge/KnowledgePage.tsx@@@ -143,11 -149,13 +147,13 @@@ export default function KnowledgePage(// request is still in flight. Once loading finishes, the normal existence// check below may repair an actually stale name to the default KB.if (loading && explicitSelection) return explicitSelection;- if (explicitSelection && kbs.some((kb) => kb.name === explicitSelection)) {- return explicitSelection;- }- const exact = kbs.find(kb => knowledgeBaseRef(kb) === explicitSelection);++ const exact = kbs.find((kb) => knowledgeBaseRef(kb) === explicitSelection);+ if (exact) return knowledgeBaseRef(exact);- const legacy = kbs.filter(kb => kb.name === explicitSelection);++ const legacy = kbs.filter((kb) => kb.name === explicitSelection);+ if (legacy.length === 1) return knowledgeBaseRef(legacy[0]);+ if (explicitSelection) return explicitSelection;if (!kbs.length) return null;- return kbs.find((kb) => kb.is_default)?.name ?? kbs[0].name;- return knowledgeBaseRef(kbs.find(kb => kb.is_default) ?? kbs[0]);++ return knowledgeBaseRef(kbs.find((kb) => kb.is_default) ?? kbs[0]);}, [explicitSelection, kbs, loading]);const selectedKb = useMemo(@@@ -221,10 -229,10 +227,18 @@@const handleDelete = useCallback(async (name: string) => {- if (!window.confirm(t('Delete knowledge base "{{name}}"?', { name }))) {- return;- }try {+ const workspaces = await resourceUsage("knowledge_bases", name);- const impact = workspaces.length ? "\n\n" + t("Used by workspaces: {{names}}", { names: workspaces.join(", ") }) : "";- if (!window.confirm(t('Delete knowledge base "{{name}}"?', { name }) + impact)) return;++ const impact = workspaces.length++ ? "\n\n" +++ t("Used by workspaces: {{names}}", { names: workspaces.join(", ") })++ : "";++ if (++ !window.confirm(++ t('Delete knowledge base "{{name}}"?', { name }) + impact,++ )++ )++ return;await deleteKb(name);if (explicitSelection === name) {setExplicitSelection(null);@@@ -250,9 -258,13 +264,13 @@@);const handleReindex = useCallback(- async (kbName: string, configFingerprint?: string) => {+ async (+ kbName: string,- indexingLLM?: IndexingLLMSelection,++ configFingerprint?: string,+ embeddingModel?: EmbeddingModelSelection,+ ) => {try {- await reindex(kbName, configFingerprint);- await reindex(kbName, indexingLLM, embeddingModel);++ await reindex(kbName, configFingerprint, embeddingModel);} catch (err) {setError(err instanceof Error ? err.message : String(err));throw err;@@@ -354,8 -378,8 +372,14 @@@<KnowledgeBaseDetailkb={selectedKb}uploadPolicy={uploadPolicy}- task={selectedKb ? tasksByKb[selectedKb.name] : undefined}- history={selectedKb ? (historyByKb[selectedKb.name] ?? []) : []}- task={selectedKb ? tasksByKb[knowledgeBaseRef(selectedKb)] : undefined}- history={selectedKb ? (historyByKb[knowledgeBaseRef(selectedKb)] ?? []) : []}++ task={++ selectedKb ? tasksByKb[knowledgeBaseRef(selectedKb)] : undefined++ }++ history={++ selectedKb++ ? (historyByKb[knowledgeBaseRef(selectedKb)] ?? [])++ : []++ }onCreate={openCreate}onUpload={handleUpload}onReindex={handleReindex}diff --cc web/contracts/generated/api.tsindex 083c133d3,edff22318..00d037a86--- a/web/contracts/generated/api.ts+++ b/web/contracts/generated/api.ts@@@ -1916,26 -1979,6 +1976,26 @@@ export interface pathsreadonly patch?: never;readonly trace?: never;};+ readonly "/api/knowledge-bases/{kb_name}/reindex-config": {+ readonly parameters: {+ readonly query?: never;+ readonly header?: never;+ readonly path?: never;+ readonly cookie?: never;+ };+ /**+ * Get Reindex Config- * @description Read the exact current default configuration for rebuild confirmation.++ * @description Read selected embedding and current role defaults for rebuild confirmation.+ */+ readonly get: operations["get_reindex_config_api_knowledge_bases__kb_name__reindex_config_get"];+ readonly put?: never;+ readonly post?: never;+ readonly delete?: never;+ readonly options?: never;+ readonly head?: never;+ readonly patch?: never;+ readonly trace?: never;+ };readonly "/api/knowledge-bases/{kb_name}/retry": {readonly parameters: {readonly query?: never;@@@ -9411,21 -10151,65 +10188,60 @@@ export interface components};/** Body_import_docx_api_documents_import_docx_post */readonly Body_import_docx_api_documents_import_docx_post: {- /**- * File- * Format: binary- */+ /** File */readonly file: string;};+ /** Body_import_preview_api_question_notebook_practice_import_preview_post */+ readonly Body_import_preview_api_question_notebook_practice_import_preview_post: {+ /**+ * Course Id+ * @default+ */+ readonly course_id: string;- /**- * File- * Format: binary- */++ /** File */+ readonly file: string;+ /**+ * Target+ * @default bank+ * @enum {string}+ */+ readonly target: "bank" | "mistakes";+ };/** Body_import_visualizer_api_visualizers_import_post */readonly Body_import_visualizer_api_visualizers_import_post: {- /**- * File- * Format: binary- */+ /** File */readonly file: string;};+ /** Body_library_add */+ readonly Body_library_add: {+ /**+ * File- * Format: binary+ * @description Raw file bytes+ */+ readonly file: string;+ /**+ * Filename+ * @description Original filename+ */+ readonly filename: string;+ /**+ * Mime Type+ * @default+ */+ readonly mime_type: string;+ };/** Body_reindex_knowledge_base_api_knowledge_bases__kb_name__reindex_post */readonly Body_reindex_knowledge_base_api_knowledge_bases__kb_name__reindex_post: {+ /**+ * Config Fingerprint+ * @default+ */+ readonly config_fingerprint: string;+ /**+ * Embedding Model+ * @default+ */+ readonly embedding_model: string;/*** Indexing Llm* @default@@@ -18438,46 -19852,7 +20027,48 @@@ export interface operationsreadonly [name: string]: unknown;};content: {- readonly "application/json": unknown;+ readonly "application/json": {+ readonly [key: string]: unknown;+ };+ };+ };+ /** @description Validation Error */+ readonly 422: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };+ readonly get_reindex_config_api_knowledge_bases__kb_name__reindex_config_get: {+ readonly parameters: {- readonly query?: never;++ readonly query?: {++ readonly embedding_model?: string;++ };+ readonly header?: {+ readonly Authorization?: string | null;+ };+ readonly path: {+ readonly kb_name: string;+ };+ readonly cookie?: {+ readonly dt_token?: string | null;+ };+ };+ readonly requestBody?: never;+ readonly responses: {+ /** @description Successful Response */+ readonly 200: {+ headers: {+ readonly [name: string]: unknown;+ };+ content: {+ readonly "application/json": {+ readonly [key: string]: unknown;+ };};};/** @description Validation Error */diff --cc web/contracts/schema/openapi.jsonindex 16a82bc9f,3fc5cc8a5..6367b61c9--- a/web/contracts/schema/openapi.json+++ b/web/contracts/schema/openapi.json@@@ -736,6 -753,35 +753,35 @@@"title": "Body_import_docx_api_documents_import_docx_post","type": "object"},+ "Body_import_preview_api_question_notebook_practice_import_preview_post": {+ "properties": {+ "course_id": {+ "default": "",+ "maxLength": 200,+ "title": "Course Id",+ "type": "string"+ },+ "file": {- "format": "binary",++ "contentMediaType": "application/octet-stream",+ "title": "File",+ "type": "string"+ },+ "target": {+ "default": "bank",+ "enum": [+ "bank",+ "mistakes"+ ],+ "title": "Target",+ "type": "string"+ }+ },+ "required": [+ "file"+ ],+ "title": "Body_import_preview_api_question_notebook_practice_import_preview_post",+ "type": "object"+ },"Body_import_visualizer_api_visualizers_import_post": {"properties": {"file": {@@@ -750,13 -796,39 +796,44 @@@"title": "Body_import_visualizer_api_visualizers_import_post","type": "object"},+ "Body_library_add": {+ "properties": {+ "file": {++ "contentMediaType": "application/octet-stream",+ "description": "Raw file bytes",- "format": "binary",+ "title": "File",+ "type": "string"+ },+ "filename": {+ "description": "Original filename",+ "title": "Filename",+ "type": "string"+ },+ "mime_type": {+ "default": "",+ "title": "Mime Type",+ "type": "string"+ }+ },+ "required": [+ "filename",+ "file"+ ],+ "title": "Body_library_add",+ "type": "object"+ },"Body_reindex_knowledge_base_api_knowledge_bases__kb_name__reindex_post": {"properties": {+ "config_fingerprint": {+ "default": "",+ "title": "Config Fingerprint",+ "type": "string"+ },+ "embedding_model": {+ "default": "",+ "title": "Embedding Model",+ "type": "string"+ },"indexing_llm": {"default": "","title": "Indexing Llm",@@@ -17629,12 -18648,10 +18915,9 @@@"tags": ["knowledge-bases"]- }- },- "/api/knowledge-bases/connect-lightrag-server": {+ },"post": {- "description": "Connect an external LightRAG server as a retrieval-only knowledge base.\n\nRe-probes server-side (never trusts the client's verdict), then registers a\npointer (``type: lightrag_server``). Retrieval is offloaded to the server's\n``/query`` endpoint — no copy, no local index.",- "operationId": "connect_lightrag_server_route_api_knowledge_bases_connect_lightrag_server_post",- "description": "Create a new knowledge base and initialize it with files.",+ "operationId": "create_knowledge_base_api_knowledge_bases_post","parameters": [{"in": "header",@@@ -19540,72 -20697,10 +20963,74 @@@]}},- "/api/knowledge-bases/rag-pipelines/pageindex/config": {++ "/api/knowledge-bases/rag-pipelines/lightrag/model-options": {+ "get": {- "description": "Read the PageIndex credential state (key redacted to a boolean).",- "operationId": "get_pageindex_pipeline_config_api_knowledge_bases_rag_pipelines_pageindex_config_get",++ "description": "Return accessible catalog models with supported role capabilities.",++ "operationId": "get_lightrag_model_options_api_knowledge_bases_rag_pipelines_lightrag_model_options_get",+ "parameters": [+ {+ "in": "header",+ "name": "Authorization",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Authorization"+ }+ },+ {+ "in": "cookie",+ "name": "dt_token",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Dt Token"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {}+ }+ },+ "description": "Successful Response"+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ },+ "description": "Validation Error"+ }+ },- "summary": "Get Pageindex Pipeline Config",++ "summary": "Get Lightrag Model Options",+ "tags": [+ "knowledge-bases"+ ]- },- "put": {- "description": "Persist the deployment-level PageIndex Cloud credential.",- "operationId": "update_pageindex_pipeline_config_api_knowledge_bases_rag_pipelines_pageindex_config_put",++ }++ },+ "/api/knowledge-bases/rag-pipelines/llamaindex/config": {+ "get": {+ "description": "Read the LlamaIndex engine's retrieval + chunking knobs.",+ "operationId": "get_llamaindex_pipeline_config_api_knowledge_bases_rag_pipelines_llamaindex_config_get","parameters": [{"in": "header",@@@ -21402,10 -22428,10 +22758,10 @@@]}},- "/api/knowledge-bases/{kb_name}/progress": {- "get": {- "description": "Get initialization progress for a knowledge base",- "operationId": "get_progress_api_knowledge_bases__kb_name__progress_get",+ "/api/knowledge-bases/{kb_name}/indexing-policy": {+ "put": {- "description": "Change the pending model of an empty, unpublished LightRAG KB.",++ "description": "Reject obsolete model edits instead of saving a policy that will not apply.",+ "operationId": "update_pending_indexing_policy_api_knowledge_bases__kb_name__indexing_policy_put","parameters": [{"in": "path",@@@ -21449,11 -22475,21 +22805,33 @@@}}],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {- "$ref": "#/components/schemas/IndexingLLMSelectionRequest"++ "anyOf": [++ {++ "$ref": "#/components/schemas/LightRagIndexingSelection"++ },++ {++ "$ref": "#/components/schemas/IndexingLLMSelectionRequest"++ }++ ],++ "title": "Payload"+ }+ }+ },+ "required": true+ },"responses": {"200": {"content": {"application/json": {-- "schema": {}++ "schema": {++ "additionalProperties": true,++ "title": "Response Update Pending Indexing Policy Api Knowledge Bases Kb Name Indexing Policy Put",++ "type": "object"++ }}},"description": "Successful Response"@@@ -21920,7 -22963,7 +23305,11 @@@"200": {"content": {"application/json": {-- "schema": {}++ "schema": {++ "additionalProperties": true,++ "title": "Response Reindex Knowledge Base Api Knowledge Bases Kb Name Reindex Post",++ "type": "object"++ }}},"description": "Successful Response"@@@ -21942,83 -22985,10 +23331,97 @@@]}},- "/api/knowledge-bases/{kb_name}/sync-web": {- "post": {- "description": "Run one bounded crawl-and-sync pass for every enabled web source.",- "operationId": "sync_web_sources_api_knowledge_bases__kb_name__sync_web_post",++ "/api/knowledge-bases/{kb_name}/reindex-config": {++ "get": {++ "description": "Read selected embedding and current role defaults for rebuild confirmation.",++ "operationId": "get_reindex_config_api_knowledge_bases__kb_name__reindex_config_get",+ "parameters": [+ {+ "in": "path",+ "name": "kb_name",+ "required": true,+ "schema": {+ "title": "Kb Name",+ "type": "string"+ }+ },++ {++ "in": "query",++ "name": "embedding_model",++ "required": false,++ "schema": {++ "default": "",++ "title": "Embedding Model",++ "type": "string"++ }++ },+ {+ "in": "header",+ "name": "Authorization",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Authorization"+ }+ },+ {+ "in": "cookie",+ "name": "dt_token",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Dt Token"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {- "schema": {}++ "schema": {++ "additionalProperties": true,++ "title": "Response Get Reindex Config Api Knowledge Bases Kb Name Reindex Config Get",++ "type": "object"++ }+ }+ },+ "description": "Successful Response"+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HTTPValidationError"+ }+ }+ },+ "description": "Validation Error"+ }+ },- "summary": "Sync Web Sources",++ "summary": "Get Reindex Config",+ "tags": [+ "knowledge-bases"+ ]+ }+ },- "/api/knowledge-bases/{kb_name}/upload": {+ "/api/knowledge-bases/{kb_name}/retry": {"post": {- "description": "Upload files to a knowledge base and process them in background.\n\n``dest_subdir`` places the whole batch under that folder inside the KB.\nA browser folder pick reports each file's path relative to the chosen\ndirectory, so the directory's own ancestors never reach the server; this\nis how a caller adding one subtree at a time re-attaches it where it\nbelongs instead of piling every batch at the root (#866).",- "operationId": "upload_files_api_knowledge_bases__kb_name__upload_post",+ "description": "Retry a failed KB initialization/indexing run from its stored raw files.",+ "operationId": "retry_knowledge_base_api_knowledge_bases__kb_name__retry_post","parameters": [{"in": "path",@@@ -22076,7 -23036,7 +23469,11 @@@"200": {"content": {"application/json": {-- "schema": {}++ "schema": {++ "additionalProperties": true,++ "title": "Response Retry Knowledge Base Api Knowledge Bases Kb Name Retry Post",++ "type": "object"++ }}},"description": "Successful Response"diff --cc web/features/knowledge/api/client.tsindex cf5e1889b,3f899bdbb..05a9213cb--- a/web/features/knowledge/api/client.ts+++ b/web/features/knowledge/api/client.ts@@@ -2,8 -2,36 +2,41 @@@ import { apiFetch, apiUrl as baseApiUrimport { invalidateClientCache, withClientCache } from "@/lib/client-cache";import type { ImaKnowledgeBaseOption } from "@/lib/ima-connection";+ function inKnowledgeLibrary(): boolean {- return typeof window !== "undefined" && /^\/knowledge-bases(?:\/|$)/.test(window.location.pathname);++ return (++ typeof window !== "undefined" &&++ /^\/knowledge-bases(?:\/|$)/.test(window.location.pathname)++ );+ }++ function apiUrl(path: string): string {+ const url = baseApiUrl(path);- return inKnowledgeLibrary() && path.startsWith("/api/knowledge-bases") && !path.includes("resource_library=")++ return inKnowledgeLibrary() &&++ path.startsWith("/api/knowledge-bases") &&++ !path.includes("resource_library=")+ ? `${url}${url.includes("?") ? "&" : "?"}resource_library=true`+ : url;+ }+const KNOWLEDGE_CACHE_PREFIX = "knowledge:";+ export type EmbeddingModelSelection = { profile_id: string; model_id: string };+ export type EmbeddingUsage = EmbeddingModelSelection & {+ name: string;+ workspace_name: string;+ };++ export async function getEmbeddingUsage(): Promise<EmbeddingUsage[]> {+ const res = await apiFetch(apiUrl("/api/knowledge-bases/embedding-usage"), {+ cache: "no-store",+ });+ if (!res.ok)+ throw new Error(+ await readErrorDetail(res, "Failed to load embedding model usage"),+ );+ return (await res.json()).knowledge_bases;+ }+export interface IndexingLLMSelection {profile_id: string;model_id: string;@@@ -248,13 -254,13 +281,23 @@@ function normalizeUploadPolicy(data: un};}- export async function listKnowledgeBases(options?: { force?: boolean }) {-export async function listKnowledgeBases(options?: { force?: boolean; library?: boolean }) {++export async function listKnowledgeBases(options?: {++ force?: boolean;++ library?: boolean;++}) {return withClientCache<KnowledgeBaseSummary[]>(- `${KNOWLEDGE_CACHE_PREFIX}list`,+ `${KNOWLEDGE_CACHE_PREFIX}list:${options?.library || inKnowledgeLibrary() ? "library" : "workspace"}`,async () => {- const response = await apiFetch(apiUrl("/api/knowledge-bases"), {- const response = await apiFetch(apiUrl(options?.library ? "/api/knowledge-bases?resource_library=true" : "/api/knowledge-bases"), {-- cache: "no-store",-- });++ const response = await apiFetch(++ apiUrl(++ options?.library++ ? "/api/knowledge-bases?resource_library=true"++ : "/api/knowledge-bases",++ ),++ {++ cache: "no-store",++ },++ );if (!response.ok) {throw new Error(await readErrorDetail(response, "Failed to list knowledge bases"),@@@ -727,6 -717,8 +770,7 @@@ export async function createKnowledgeBafiles: File[];pageindexMode?: "flash" | "standard";searchMode?: string;- indexingLLM?: IndexingLLMSelection;+ embeddingModel?: EmbeddingModelSelection;}): Promise<KnowledgeTaskResponse> {const form = new FormData();form.append("name", payload.name);@@@ -735,6 -727,11 +779,8 @@@form.append("pageindex_mode", payload.pageindexMode);}if (payload.searchMode) form.append("search_mode", payload.searchMode);+ if (payload.embeddingModel)+ form.append("embedding_model", JSON.stringify(payload.embeddingModel));- if (payload.indexingLLM) {- form.append("indexing_llm", JSON.stringify(payload.indexingLLM));- }appendFilesWithPaths(form, payload.files);const res = await apiFetch(apiUrl("/api/knowledge-bases"), {@@@ -1215,34 -1212,17 +1261,44 @@@ export async function setDefaultKnowledinvalidateKnowledgeCaches();}+export interface LightRagRebuildConfig {+ fingerprint: string;+ indexing_policy: import("@/lib/knowledge-helpers").LightRagIndexingPolicy;+ embedding: { model: string; dimension: number };++ embedding_selection?: EmbeddingModelSelection | null;+}++export async function getReindexConfig(+ name: string,++ embeddingModel?: EmbeddingModelSelection,+): Promise<LightRagRebuildConfig> {++ const query = embeddingModel++ ? `?${new URLSearchParams({ embedding_model: JSON.stringify(embeddingModel) })}`++ : "";+ const res = await apiFetch(- apiUrl(`/api/knowledge-bases/${encodeURIComponent(name)}/reindex-config`),++ apiUrl(++ `/api/knowledge-bases/${encodeURIComponent(name)}/reindex-config${query}`,++ ),+ { cache: "no-store" },+ );+ if (!res.ok)+ throw new Error(+ await readErrorDetail(res, "Failed to load rebuild configuration"),+ );+ return (await res.json()) as LightRagRebuildConfig;+}+export async function reindexKnowledgeBase(name: string,- indexingLLM?: IndexingLLMSelection,+ configFingerprint?: string,+ embeddingModel?: EmbeddingModelSelection,): Promise<KnowledgeTaskResponse> {const request: RequestInit = { method: "POST" };- if (configFingerprint) {- if (indexingLLM || embeddingModel) {++ if (configFingerprint || embeddingModel) {const form = new FormData();- form.append("config_fingerprint", configFingerprint);- if (indexingLLM) form.append("indexing_llm", JSON.stringify(indexingLLM));++ if (configFingerprint) form.append("config_fingerprint", configFingerprint);+ if (embeddingModel)+ form.append("embedding_model", JSON.stringify(embeddingModel));request.body = form;}const res = await apiFetch(diff --cc web/hooks/useKnowledgeBases.tsindex 322fde356,c68754246..5a3399e82--- a/web/hooks/useKnowledgeBases.ts+++ b/web/hooks/useKnowledgeBases.ts@@@ -111,7 -116,7 +114,10 @@@ export function useKnowledgeBases()const status = kb.status ?? kb.statistics?.status;const kbProgress = kb.progress ?? kb.statistics?.progress;if (status === "error" && kbProgress) {- progress.setProgress(kb.name, kbProgress as ProgressInfo);- progress.setProgress(knowledgeBaseRef(kb), kbProgress as ProgressInfo);++ progress.setProgress(++ knowledgeBaseRef(kb),++ kbProgress as ProgressInfo,++ );continue;}if (@@@ -180,7 -187,9 +188,8 @@@files: File[];pageindexMode?: "flash" | "standard";searchMode?: string;- }): Promise<KnowledgeTaskResponse> => {- indexingLLM?: IndexingLLMSelection;+ embeddingModel?: EmbeddingModelSelection;+ }): Promise<KnowledgeTaskResponse> => {const result = await createKbApi(params);invalidateKnowledgeCaches();const fileCount = params.files.length;@@@ -257,9 -266,10 +266,14 @@@const reindex = useCallback(async (kbName: string,- indexingLLM?: IndexingLLMSelection,+ configFingerprint?: string,+ embeddingModel?: EmbeddingModelSelection,): Promise<KnowledgeTaskResponse> => {- const result = await reindexKbApi(kbName, configFingerprint);- const result = await reindexKbApi(kbName, indexingLLM, embeddingModel);++ const result = await reindexKbApi(++ kbName,++ configFingerprint,++ embeddingModel,++ );if (result.noop) {await load({ force: true, showSpinner: false });return result;diff --cc web/lib/knowledge-helpers.tsindex 43d36bd9f,e8faa6e62..813892849--- a/web/lib/knowledge-helpers.ts+++ b/web/lib/knowledge-helpers.ts@@@ -429,8 -427,8 +431,9 @@@ export const kbRequiresLightRagRebuildBexport const kbIsUploadable = (kb: KnowledgeBase): boolean =>resolveKbStatus(kb) === "ready" &&+ !kbEmbeddingUnavailable(kb) &&!kbNeedsReindex(kb) &&+ !kb.metadata?.indexing_model_unavailable &&!kbRequiresLightRagRebuildBeforeAppend(kb);export const kbCanUploadDocuments = (@@@ -439,8 -437,8 +442,9 @@@): boolean =>kbIsUploadable(kb) ||(resolveKbStatus(kb) === "error" &&+ !kbEmbeddingUnavailable(kb) &&!indexingActive &&+ !kb.metadata?.indexing_model_unavailable &&!kbRequiresLightRagRebuildBeforeAppend(kb));export const kbCanReindex = (kb: KnowledgeBase): boolean => {diff --cc web/locales/en/app.jsonindex f1a7f2a44,b9fdaa84d..e1b43a66e--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@@ -4011,59 -4015,6 +4016,59 @@@"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 defaults shown below for the full index. Change models in Settings. The configuration is fixed when you confirm; the previous version is preserved if rebuilding fails.": "This rebuild uses the defaults shown below for the full index. Change 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.": "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.","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 ce50920dd,3e68611ad..84db86b88--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@@ -4011,59 -4015,6 +4016,59 @@@"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 defaults shown below for the full index. Change 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": "本次重建配置",+ "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.": "默认配置已更改。请查看更新后的配置并重新确认。","Could not copy": "复制失败","The clipboard is not available in this browser.": "当前浏览器环境无法使用剪贴板。","attachments": "附件",diff --cc web/tests/lightrag-indexing-model.test.tsindex b16973015,7c4eaae11..5cf55282e--- a/web/tests/lightrag-indexing-model.test.ts+++ b/web/tests/lightrag-indexing-model.test.ts@@@ -54,14 -62,47 +54,20 @@@ test("create uses defaults and re-inderestore();}- assert.equal(requests[0].url, "/api/knowledge-bases");+ assert.equal(+ new URL(requests[0].url, "http://localhost").pathname,+ "/api/knowledge-bases",+ );- assert.deepEqual(- JSON.parse(String(requests[0].form.get("indexing_llm"))),- selection,- );+ assert.equal(requests[0].form.has("indexing_llm"), false);- assert.equal(requests[1].url, "/api/knowledge-bases/papers/reindex");+ assert.equal(+ new URL(requests[1].url, "http://localhost").pathname,+ "/api/knowledge-bases/papers/reindex",+ );- assert.deepEqual(- JSON.parse(String(requests[1].form.get("indexing_llm"))),- selection,- );-});--test("pending-policy update is JSON-only and creates no indexing request", async () => {- let captured: { url: string; init?: RequestInit } | undefined;- const restore = stubFetch(async (input, init) => {- captured = { url: String(input), init };- return jsonResponse(200, { indexing_policy: { policy: "pending_pinned" } });- });- try {- await updatePendingIndexingPolicy("empty", {- profile_id: "p",- model_id: "m",- });- } finally {- restore();- }assert.equal(- new URL(captured!.url, "http://localhost").pathname,- "/api/knowledge-bases/empty/indexing-policy",+ requests[1].form.get("config_fingerprint"),+ "confirmed-fingerprint",);- assert.equal(captured?.init?.method, "PUT");- assert.deepEqual(JSON.parse(String(captured?.init?.body)), {- profile_id: "p",- model_id: "m",- });+ assert.equal(requests[1].form.has("indexing_llm"), false);});test("non-LightRAG re-index keeps the established bodyless request", async () => {diff --cc web/tests/lightrag-lifecycle.spec.tsxindex 161bcffe3,000000000..135e77462mode 100644,000000..100644--- a/web/tests/lightrag-lifecycle.spec.tsx+++ b/web/tests/lightrag-lifecycle.spec.tsx@@@ -1,264 -1,0 +1,305 @@@+import React from "react";+import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vitest";+import KbIndexVersionsSection from "@/components/knowledge/KbIndexVersionsSection";+import KnowledgeBaseDetail from "@/components/knowledge/KnowledgeBaseDetail";+import CreateKbModal from "@/components/knowledge/CreateKbModal";+import {+ DEFAULT_UPLOAD_POLICY,+ type KnowledgeBase,+} from "@/lib/knowledge-helpers";++vi.mock("@/components/knowledge/KbFilesTab", () => ({ default: () => null }));+vi.mock("@/features/knowledge/api/files", async (original) => ({+ ...(await original<typeof import("@/features/knowledge/api/files")>()),+ listKnowledgeBaseFiles: async () => [],+}));++const fixture = vi.hoisted(() => {+ const selection = {+ profile_id: "p",+ model_id: "model",+ reasoning_effort: "none",+ };+ return {+ t: (key: string) => key,+ selection,+ refresh: vi.fn(async () => {}),+ config: {+ version: 2,+ llm_profile_id: "",+ llm_model_id: "",+ top_k: 20,+ max_concurrent_files: 1,+ entity_extract_max_gleaning: 1,+ role_models: {+ base: selection,+ query: {+ mode: "model",+ selection: { profile_id: "p", model_id: "model" },+ max_async: 1,+ timeout: 60,+ },+ keyword: { mode: "inherit", max_async: 1, timeout: 60 },+ extract: { mode: "inherit", max_async: 1, timeout: 60 },+ vlm: { mode: "disabled", max_async: 1, timeout: 60 },+ },+ },+ preview: vi.fn(),+ create: vi.fn(async () => ({ task_id: null, files: [] })),+ options: [+ {+ ...selection,+ model_name: "Model one",+ model: "one",+ profile_name: "Provider",+ provider: "custom",+ is_active_default: true,+ supports_vision: true,+ },+ ],+ };+});+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: fixture.t }) }));+vi.mock("@/hooks/useLLMOptions", () => ({+ useLLMOptions: () => ({+ options: fixture.options,+ activeDefault: fixture.selection,+ loading: false,+ error: false,+ refresh: fixture.refresh,+ }),+}));+vi.mock("@/features/knowledge/api/engines", async (original) => ({+ ...(await original<typeof import("@/features/knowledge/api/engines")>()),+ getLightRagConfig: async () => structuredClone(fixture.config),++ getEngineModelOptions: async () => ({++ embedding: {++ active: { profile_id: "embedding", model_id: "a" },++ options: ["a", "b"].map((model_id) => ({++ profile_id: "embedding",++ model_id,++ label: `Embedding ${model_id}`,++ profile_name: "Provider",++ })),++ },++ }),+}));+vi.mock("@/features/knowledge/api/catalog", async (original) => ({+ ...(await original<typeof import("@/features/knowledge/api/catalog")>()),+ getReindexConfig: fixture.preview,+ createKnowledgeBase: fixture.create,+ listKnowledgeBases: async () => [],+ listRagProviders: async () => [],+ getKnowledgeUploadPolicy: async () => {+ throw new Error("use default upload policy");+ },+}));++const policy = {+ policy: "pinned",+ schema_version: 2,+ extract: {+ policy: "pinned",+ descriptor: {+ model: "Extract model",+ binding: "custom",+ reasoning_effort: "none",+ },+ },+ vlm: { mode: "disabled" as const },+};+const kb: KnowledgeBase = {+ name: "papers",+ status: "ready",+ metadata: { indexing_policy: policy },+ statistics: {+ rag_provider: "lightrag",+ raw_documents: 2,+ index_versions: [+ {+ version: "version-3",+ signature: "lightrag",+ provider: "lightrag",+ ready: true,+ embedding_model: "embedding-old",+ embedding_dim: 3,+ indexing_policy: policy,+ },+ ],+ },+};+const preview = (fingerprint: string, model = "embedding-current") => ({+ fingerprint,+ embedding: { model, dimension: 3 },+ indexing_policy: policy,+});++beforeEach(() => {+ fixture.preview.mockReset().mockResolvedValue(preview("first"));+ fixture.config.role_models.base = { ...fixture.selection };+});+- it("shows version identifiers and a read-only rebuild confirmation, then requires reconfirmation after drift", async () => {++it("shows version identifiers and embedding selection with read-only role confirmation, then requires reconfirmation after drift", async () => {+ const submit = vi+ .fn()+ .mockRejectedValueOnce(new Error("Default configuration changed"));+ render(<KbIndexVersionsSection kb={kb} onReindex={submit} />);+ expect(screen.getByText("version-3")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Re-index" }));+ const dialog = screen.getByRole("dialog");+ await within(dialog).findByText("embedding-current · 3d");- expect(within(dialog).queryByRole("combobox")).not.toBeInTheDocument();++ expect(++ within(dialog).getByRole("combobox", { name: "Embedding model" }),++ ).toBeInTheDocument();+ fixture.preview.mockResolvedValue(preview("second", "embedding-new"));+ fireEvent.click(+ within(dialog).getByRole("button", { name: "Confirm rebuild" }),+ );+ await within(dialog).findByText("embedding-new · 3d");- expect(submit).toHaveBeenCalledExactlyOnceWith("first");++ expect(submit).toHaveBeenCalledExactlyOnceWith("first", {++ profile_id: "embedding",++ model_id: "a",++ });+ expect(+ within(dialog).getByText("Default configuration changed"),+ ).toBeInTheDocument();+ submit.mockResolvedValue(undefined);+ fireEvent.click(+ within(dialog).getByRole("button", { name: "Confirm rebuild" }),+ );+ await waitFor(() =>+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),+ );- expect(submit).toHaveBeenLastCalledWith("second");++ expect(submit).toHaveBeenLastCalledWith("second", {++ profile_id: "embedding",++ model_id: "a",++ });++});++++it("refreshes confirmation when the selected embedding changes", async () => {++ const submit = vi.fn(async () => {});++ render(<KbIndexVersionsSection kb={kb} onReindex={submit} />);++ fireEvent.click(screen.getByRole("button", { name: "Re-index" }));++ const dialog = screen.getByRole("dialog");++ await within(dialog).findByText("embedding-current · 3d");++ fixture.preview.mockResolvedValue(preview("selected-b", "embedding-b"));++ fireEvent.change(within(dialog).getByRole("combobox", { name: "Embedding model" }), {++ target: { value: JSON.stringify(["embedding", "b"]) },++ });++ await within(dialog).findByText("embedding-b · 3d");++ expect(fixture.preview).toHaveBeenLastCalledWith("papers", { profile_id: "embedding", model_id: "b" });++ fireEvent.click(within(dialog).getByRole("button", { name: "Confirm rebuild" }));++ await waitFor(() => expect(submit).toHaveBeenCalledWith("selected-b", { profile_id: "embedding", model_id: "b" }));+});+- it("has no model or rebuild action for an empty knowledge base", () => {++it("retains upstream embedding action but no role overrides for an empty knowledge base", () => {+ render(+ <KbIndexVersionsSection+ kb={{+ ...kb,+ statistics: {+ rag_provider: "lightrag",+ raw_documents: 0,+ index_versions: [],+ },+ }}+ onReindex={vi.fn()}+ />,+ );- expect(screen.queryByRole("button")).not.toBeInTheDocument();++ expect(screen.getByRole("button", { name: "Re-index" })).toBeInTheDocument();+ expect(screen.queryByText("Index configuration")).not.toBeInTheDocument();+});++it("refreshes all four default roles on return from settings and creates without overrides", async () => {+ const create = vi.fn(async (_params: unknown) => {});+ render(+ <CreateKbModal+ isOpen+ onClose={vi.fn()}+ providers={[{ id: "lightrag", name: "LightRAG", description: "Graph" }]}+ uploadPolicy={DEFAULT_UPLOAD_POLICY}+ onCreate={create}+ onConnectLinkedFolder={vi.fn()}+ onConnectObsidian={vi.fn()}+ onConnectLightRagServer={vi.fn()}+ onConnectWeKnora={vi.fn()}+ onConnectMarginNote4={vi.fn()}+ onConnectIma={vi.fn()}+ />,+ );+ await screen.findByText("QUERY: Model one · Auto");+ expect(screen.getByText("KEYWORD: Model one · none")).toBeInTheDocument();+ expect(screen.getByText("EXTRACT: Model one · none")).toBeInTheDocument();+ expect(screen.getByText("VLM: Disabled")).toBeInTheDocument();+ expect(+ screen.queryByText("Customize indexing models"),+ ).not.toBeInTheDocument();+ fixture.config.role_models.base.reasoning_effort = "high";+ fireEvent(window, new Event("focus"));+ await screen.findByText("EXTRACT: Model one · high");+ const name = screen.getByPlaceholderText("e.g. project-papers");+ fireEvent.change(name, { target: { value: "empty" } });+ fireEvent.click(screen.getByRole("button", { name: "Create" }));+ await waitFor(() => expect(create).toHaveBeenCalledTimes(1));+ expect(create.mock.calls[0][0]).not.toHaveProperty("indexingLLM");+});++it.each(["header", "documents"])(+ "routes the %s LightRAG retry through refreshed rebuild confirmation",+ async (entry) => {+ const retry = vi.fn();+ const reindex = vi+ .fn()+ .mockRejectedValueOnce(new Error("Default configuration changed"));+ render(+ <KnowledgeBaseDetail+ kb={{ ...kb, status: "error" }}+ uploadPolicy={DEFAULT_UPLOAD_POLICY}+ history={[]}+ onCreate={vi.fn()}+ onUpload={vi.fn()}+ onReindex={reindex}+ onRetry={retry}+ onSetDefault={vi.fn()}+ onDelete={vi.fn()}+ onClearHistory={vi.fn()}+ />,+ );+ if (entry === "documents")+ fireEvent.click(screen.getByRole("button", { name: "Add documents" }));+ const buttons = screen.getAllByRole("button", { name: "Review rebuild" });+ fireEvent.click(buttons[entry === "header" ? 0 : buttons.length - 1]);+ expect(retry).not.toHaveBeenCalled();+ expect(reindex).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Retry indexing" }));+ const dialog = screen.getByRole("dialog");+ await within(dialog).findByText("embedding-current · 3d");+ fixture.preview.mockResolvedValue(preview("retry-new", "embedding-new"));+ fireEvent.click(+ within(dialog).getByRole("button", { name: "Confirm rebuild" }),+ );+ await within(dialog).findByText("embedding-new · 3d");- expect(reindex).toHaveBeenCalledExactlyOnceWith("papers", "first");++ expect(reindex).toHaveBeenCalledExactlyOnceWith("papers", "first", {++ profile_id: "embedding",++ model_id: "a",++ });+ reindex.mockResolvedValue(undefined);+ fireEvent.click(+ within(dialog).getByRole("button", { name: "Confirm rebuild" }),+ );+ await waitFor(() =>- expect(reindex).toHaveBeenLastCalledWith("papers", "retry-new"),++ expect(reindex).toHaveBeenLastCalledWith("papers", "retry-new", {++ profile_id: "embedding",++ model_id: "a",++ }),+ );+ expect(retry).not.toHaveBeenCalled();+ },+);