DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: enforce native LightRAG embedding compatibility
NoxsMediafd5f7d2347fc
diff --git a/README.md b/README.mdindex 83cb76932..4da770c29 100644--- a/README.md+++ b/README.md@@ -748,6 +748,8 @@ Creating a KB, you either **create new** (upload documents and build a fresh indThe built-in LightRAG engine is installed with `pip install 'deeptutor[rag-lightrag]'`. That extra contains the supported LightRAG SDK but does not install MinerU. Choose MinerU independently in Document Parsing and either configure its cloud mode or install its current local CLI when structured parsing is wanted. MinerU accepts PDF, common raster images, DOCX, PPTX, and XLSX; the legacy `magic-pdf` command remains PDF-only. Text-only and the other parsing engines do not require MinerU.+Native LightRAG queries and incremental indexing require the embedding configuration recorded by the published index, including the model, dimension, and endpoint identity. If it changes, restore the original configuration or rebuild with the current embedding; indexes without a recorded embedding identity require a rebuild. The knowledge-base detail and index-version views show recovery guidance, while files remain available for viewing and download.+</details><details>diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 63d74924c..1be1840b3 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -3272,16 +3272,17 @@ async def run_reindex_task(# this cached instance before clearing flags so stale processing# state cannot overwrite the completed status it just wrote.manager.config = manager._load_config()- # Clear the legacy mismatch / needs_reindex flags now that an- # index version matching the active config exists on disk.+ # LightRAG's loader reconciles its published embedding against current+ # defaults, which may have changed during this accepted operation.+ # Other providers retain their existing completion flag cleanup.kb_entry = manager.config.get("knowledge_bases", {}).get(kb_name) or {}if kb_entry.get("status") != "ready":raise RuntimeError(f"Re-index terminal state was not persisted for '{kb_name}'.")mutated = False- if kb_entry.get("needs_reindex"):+ if signature_hash != LIGHTRAG_PROVIDER and kb_entry.get("needs_reindex"):kb_entry["needs_reindex"] = Falsemutated = True- if kb_entry.get("embedding_mismatch"):+ if signature_hash != LIGHTRAG_PROVIDER and kb_entry.get("embedding_mismatch"):kb_entry.pop("embedding_mismatch", None)mutated = Trueif mutated:diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.pyindex a5e2c5cfe..87dd59515 100644--- a/deeptutor/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -156,9 +156,6 @@ def _reconcile_embedding_flags(knowledge_bases: dict, base_dir: Path | None = Nosignature = signature_from_embedding_config()changed = False- if signature is None and not fp:- return False-for kb_name, kb_entry in knowledge_bases.items():if not isinstance(kb_entry, dict):continue@@ -170,6 +167,34 @@ def _reconcile_embedding_flags(knowledge_bases: dict, base_dir: Path | None = Nocontinueprovider = normalize_provider_name(kb_entry.get("rag_provider"))+ if provider == LIGHTRAG_PROVIDER and base_dir is not None:+ from deeptutor.services.rag.pipelines.lightrag.storage import (+ embedding_matches,+ latest_published_root,+ )++ kb_dir = base_dir / kb_name+ kb_entry["index_versions"] = inspect_kb_versions(kb_dir, provider)+ published = latest_published_root(kb_dir)+ lightrag_mismatch = published is not None and not embedding_matches(+ published, signature+ )+ if lightrag_mismatch and not kb_entry.get("embedding_mismatch"):+ kb_entry["embedding_mismatch"] = True+ kb_entry["needs_reindex"] = True+ changed = True+ elif (+ published is not None+ and not lightrag_mismatch+ and kb_entry.pop("embedding_mismatch", None)+ ):+ kb_entry["needs_reindex"] = False+ changed = True+ continue++ if signature is None and not fp:+ continue+if not provider_uses_embedding_versions(provider):kb_dir = (base_dir / kb_name) if base_dir is not None else Noneif kb_dir is not None:@@ -1405,6 +1430,21 @@ class KnowledgeBaseManager:pending if isinstance(pending, dict) else {"policy": "legacy_unpinned"})metadata["indexing_policy"] = indexing_policy+ if published_root is not None:+ from deeptutor.services.rag.embedding_signature import (+ signature_from_embedding_config,+ )++ published = next(+ (v for v in index_versions if v.get("version") == published_root.name),+ {},+ )+ metadata["indexed_embedding_model"] = published.get("embedding_model")+ metadata["indexed_embedding_dim"] = published.get("embedding_dim")+ current_embedding = signature_from_embedding_config()+ if current_embedding is not None:+ metadata["current_embedding_model"] = current_embedding.model+ metadata["current_embedding_dim"] = current_embedding.dimensionmetadata.update(self._embedding_fields(kb_config))diff --git a/deeptutor/services/rag/pipelines/lightrag/config.py b/deeptutor/services/rag/pipelines/lightrag/config.pyindex 6f45e3365..2e6d45a19 100644--- a/deeptutor/services/rag/pipelines/lightrag/config.py+++ b/deeptutor/services/rag/pipelines/lightrag/config.py@@ -17,14 +17,18 @@ from __future__ import annotationsimport asynciofrom collections.abc import Awaitable, Callable+from copy import deepcopyimport importlib.utilimport inspectimport loggingimport re-from typing import TYPE_CHECKING, TypeVar+from typing import TYPE_CHECKING, Any, TypeVarif TYPE_CHECKING:+ from lightrag.utils import EmbeddingFunc+from deeptutor.multi_user.models import CurrentUser+ from deeptutor.services.embedding.config import EmbeddingConfigfrom deeptutor.services.llm.config import LLMConfigfrom .worker import OwnerLoopBridge@@ -357,13 +361,18 @@ def vision_model_available() -> bool:return False-def build_embedding_func(*, io_bridge: OwnerLoopBridge | None = None):- """Wrap DeepTutor's embedding client in LightRAG's ``EmbeddingFunc``."""+def build_embedding_func(+ *,+ io_bridge: OwnerLoopBridge | None = None,+ embedding_config: EmbeddingConfig | None = None,+) -> EmbeddingFunc:+ """Wrap one captured embedding configuration in LightRAG's adapter."""from lightrag.utils import EmbeddingFunc- from deeptutor.services.embedding import get_embedding_client, get_embedding_config+ from deeptutor.services.embedding import get_embedding_config+ from deeptutor.services.embedding.client import EmbeddingClient- cfg = get_embedding_config()+ cfg = deepcopy(embedding_config if embedding_config is not None else get_embedding_config())dim = int(getattr(cfg, "dim", 0) or 0)if not dim:raise LightRagNotConfiguredError(@@ -371,9 +380,9 @@ def build_embedding_func(*, io_bridge: OwnerLoopBridge | None = None):"Settings → Catalog before using a LightRAG knowledge base.")- client = get_embedding_client()+ client = EmbeddingClient(config=cfg)- async def embedding_func(texts, context=None, **_ignored):+ async def embedding_func(texts: list[str], context: str | None = None, **_ignored: Any) -> Any:import numpy as np# No context means no role. Defaulting to "document" would label@@ -383,7 +392,7 @@ def build_embedding_func(*, io_bridge: OwnerLoopBridge | None = None):"document": "search_document",}.get(str(context or "").strip().lower())- async def request():+ async def request() -> Any:return await client.embed(texts, input_type=input_type)vectors = await io_bridge.run(request) if io_bridge is not None else await request()diff --git a/deeptutor/services/rag/pipelines/lightrag/engine.py b/deeptutor/services/rag/pipelines/lightrag/engine.pyindex 3b5f2cb85..24b7ec3ad 100644--- a/deeptutor/services/rag/pipelines/lightrag/engine.py+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py@@ -8,7 +8,10 @@ import hashlibfrom importlib.metadata import PackageNotFoundError, versionimport inspectfrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from deeptutor.services.embedding.config import EmbeddingConfigfrom .config import (DEFAULT_MODE,@@ -189,6 +192,7 @@ def build_rag(io_bridge: OwnerLoopBridge | None = None,enable_vlm: bool = False,indexing_snapshot: Any | None = None,+ embedding_config: EmbeddingConfig | None = None,) -> Any:"""Construct one exact-version, version-isolated LightRAG instance."""_require_exact_version()@@ -197,6 +201,8 @@ def build_rag(llm_adapter_kwargs: dict[str, Any] = {}embedding_adapter_kwargs: dict[str, Any] = {}+ if embedding_config is not None:+ embedding_adapter_kwargs["embedding_config"] = embedding_configif io_bridge is not None:llm_adapter_kwargs["io_bridge"] = io_bridgeembedding_adapter_kwargs["io_bridge"] = io_bridgediff --git a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.pyindex bbfa81284..439c80b3f 100644--- a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py+++ b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py@@ -39,6 +39,12 @@ class IndexingModelChangedError(IndexingPolicyError):code = "reindex_required"+class EmbeddingMismatchError(IndexingPolicyError):+ """The selected embedding does not match the published vector space."""++ code = "lightrag_embedding_incompatible"++def _endpoint_identity(value: str | None) -> str:if not value:return ""diff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.pyindex 5818ce487..3dd76765c 100644--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py@@ -3,12 +3,16 @@from __future__ import annotationsimport asyncio+from copy import deepcopyfrom dataclasses import dataclass, field, replaceimport loggingfrom pathlib import Pathimport shutilimport traceback-from typing import Any, Callable, Dict, List, Optional+from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional++if TYPE_CHECKING:+ from deeptutor.services.embedding.config import EmbeddingConfigfrom deeptutor.runtime.home import get_runtime_data_rootfrom deeptutor.services.rag.index_versioning import (@@ -280,9 +284,15 @@ class LightRagPipeline:file_paths: List[str],progress_callback: Callable[[int, int], Any] | None,snapshot: IndexingLLMSnapshot | None = None,+ *,+ embedding_config: EmbeddingConfig | None = None,) -> BatchOutcome:if snapshot is None:snapshot = freeze_default_snapshot()+ if embedding_config is None:+ from deeptutor.services.embedding import get_embedding_config++ embedding_config = deepcopy(get_embedding_config())async def job(io_bridge: OwnerLoopBridge) -> BatchOutcome:io_bridge.raise_if_cancelled()@@ -301,6 +311,7 @@ class LightRagPipeline:io_bridge=io_bridge,enable_vlm=any("i" in item.process_options for item in staged),indexing_snapshot=snapshot,+ embedding_config=embedding_config,)except BaseException:for item in staged:@@ -368,6 +379,9 @@ class LightRagPipeline:async def initialize(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()+ from deeptutor.services.embedding import get_embedding_config++ embedding_config = deepcopy(get_embedding_config())kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)snapshot = kwargs.get("indexing_snapshot")if snapshot is None:@@ -383,13 +397,17 @@ class LightRagPipeline:root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)try:outcome = await self._run_indexing(- root_dir, file_paths, kwargs.get("progress_callback"), snapshot+ root_dir,+ file_paths,+ kwargs.get("progress_callback"),+ snapshot,+ embedding_config=embedding_config,)if not storage.has_output(root_dir):raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")policy = dict(outcome.indexing_policy)policy["vlm_used"] = outcome.vlm_used- storage.write_meta(root_dir, indexing_policy=policy)+ storage.write_meta(root_dir, indexing_policy=policy, embedding_config=embedding_config)self._clear_pending_policy(kb_name)return outcome.completeexcept asyncio.CancelledError:@@ -404,6 +422,9 @@ class LightRagPipeline:async def add_documents(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()+ from deeptutor.services.embedding import get_embedding_config++ embedding_config = deepcopy(get_embedding_config())kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)existing = storage.latest_published_root(kb_dir)versions = list_kb_versions(kb_dir)@@ -418,6 +439,8 @@ class LightRagPipeline:"This LightRAG index is legacy, unpublished, or corrupt and must be rebuilt ""before appending.")+ if existing is not None:+ storage.require_compatible_embedding(existing, embedding_config)snapshot = resolve_write_snapshot(kb_dir,base_dir=self.kb_base_dir,@@ -432,18 +455,26 @@ class LightRagPipeline:is_update = Falsetry:outcome = await self._run_indexing(- root_dir, file_paths, kwargs.get("progress_callback"), snapshot+ root_dir,+ file_paths,+ kwargs.get("progress_callback"),+ snapshot,+ embedding_config=embedding_config,)if not storage.has_output(root_dir):raise RuntimeError(f"LightRAG did not produce a ready index for {kb_name!r}")policy = dict(outcome.indexing_policy)policy["vlm_used"] = outcome.vlm_usedif not is_update:- storage.write_meta(root_dir, indexing_policy=policy)+ storage.write_meta(+ root_dir, indexing_policy=policy, embedding_config=embedding_config+ )self._clear_pending_policy(kb_name)else:try:- storage.write_meta(root_dir, indexing_policy=policy)+ storage.write_meta(+ root_dir, indexing_policy=policy, embedding_config=embedding_config+ )self._clear_pending_policy(kb_name)except Exception:self.logger.warning(@@ -493,9 +524,15 @@ class LightRagPipeline:mode = self._resolve_mode(kb_name, kwargs)try:self._ensure_available()+ from deeptutor.services.embedding import get_embedding_config- async def job(io_bridge: OwnerLoopBridge):- rag = engine.build_rag(root_dir, io_bridge=io_bridge)+ embedding_config = deepcopy(get_embedding_config())+ storage.require_compatible_embedding(root_dir, embedding_config)++ async def job(io_bridge: OwnerLoopBridge) -> Any:+ rag = engine.build_rag(+ root_dir, io_bridge=io_bridge, embedding_config=embedding_config+ )failed = Truetry:await engine.initialize(rag)@@ -508,6 +545,8 @@ class LightRagPipeline:answer, sources = await run_in_worker_loop(job)except lr_config.LightRagNotAvailableError as exc:return self._error_result(query, exc, error_type="not_configured")+ except indexing_policy.EmbeddingMismatchError as exc:+ return self._error_result(query, exc, error_type=exc.code)except Exception as exc:self.logger.error("LightRAG search failed: %s", exc)self.logger.error(traceback.format_exc())diff --git a/deeptutor/services/rag/pipelines/lightrag/storage.py b/deeptutor/services/rag/pipelines/lightrag/storage.pyindex a79a9e392..15d3ad559 100644--- a/deeptutor/services/rag/pipelines/lightrag/storage.py+++ b/deeptutor/services/rag/pipelines/lightrag/storage.py@@ -23,7 +23,11 @@ from datetime import datetime, timezoneimport jsonimport loggingfrom pathlib import Path-from typing import Any+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from deeptutor.services.embedding.config import EmbeddingConfig+ from deeptutor.services.rag.index_versioning import EmbeddingSignaturefrom deeptutor.services.file_io import atomic_write_json@@ -232,7 +236,32 @@ def latest_published_root(kb_dir: Path) -> Path | None:return None-def write_meta(root_dir: Path, *, indexing_policy: dict[str, Any] | None = None) -> None:+def embedding_matches(root_dir: Path, signature: EmbeddingSignature | None) -> bool:+ """Compare the published vector identity, never just its dimension."""+ meta = _read_meta(root_dir) or {}+ return signature is not None and meta.get("embedding_signature") == signature.hash()+++def require_compatible_embedding(root_dir: Path, config: EmbeddingConfig) -> None:+ """Reject reads and appends when the published embedding identity differs."""+ from deeptutor.services.rag.embedding_signature import signature_from_config++ from .indexing_policy import EmbeddingMismatchError++ if not embedding_matches(root_dir, signature_from_config(config)):+ raise EmbeddingMismatchError(+ "The current embedding configuration does not match this LightRAG index. "+ "Restore the original embedding configuration or rebuild with the current embedding "+ "before querying or adding documents."+ )+++def write_meta(+ root_dir: Path,+ *,+ indexing_policy: dict[str, Any] | None = None,+ embedding_config: EmbeddingConfig | None = None,+) -> None:"""Write a flat-layout ``meta.json`` so the version lists as ready.Mirrors ``index_versioning.write_version_meta`` but carries a synthetic@@ -241,13 +270,25 @@ def write_meta(root_dir: Path, *, indexing_policy: dict[str, Any] | None = None)embedding compatibility at connect time (LightRAG otherwise fails retrievalsilently on a dimension mismatch)."""- from deeptutor.services.rag.embedding_signature import embedding_meta_fields+ from deeptutor.services.rag.embedding_signature import (+ embedding_meta_fields,+ signature_from_config,+ )from .engine import installed_version, workspace_fortarget = Path(root_dir)previous = _read_meta(target) or {}now = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z"+ if embedding_config is None:+ embedding_fields = embedding_meta_fields()+ else:+ signature = signature_from_config(embedding_config)+ embedding_fields = {+ "embedding_signature": signature.hash(),+ "embedding_model": signature.model,+ "embedding_dim": signature.dimension,+ }payload = {"version": target.name,"signature": PROVIDER,@@ -264,7 +305,7 @@ def write_meta(root_dir: Path, *, indexing_policy: dict[str, Any] | None = None)"indexing_policy": indexing_policyor previous.get("indexing_policy")or {"policy": "legacy_unpinned"},- **embedding_meta_fields(),+ **embedding_fields,}atomic_write_json(target / META_FILENAME, payload)diff --git a/tests/api/test_knowledge_router.py b/tests/api/test_knowledge_router.pyindex 518a017bb..cf8d2932d 100644--- a/tests/api/test_knowledge_router.py+++ b/tests/api/test_knowledge_router.py@@ -1552,7 +1552,18 @@ def test_reindex_error_status_bypasses_existing_match_noop(monkeypatch, tmp_pathassert manager.config["knowledge_bases"]["failed-kb"]["status"] == "initializing"-def test_reindex_task_persists_completed_progress(monkeypatch, tmp_path: Path) -> None:[email protected]("embedding_changed", [False, True])+def test_reindex_task_persists_completed_progress(+ monkeypatch, tmp_path: Path, embedding_changed: bool+) -> None:+ from deeptutor.services.embedding.config import EmbeddingConfig+ from deeptutor.services.rag.pipelines.lightrag import storage++ embedding = EmbeddingConfig(model="original", dim=3, api_key="test-key")+ monkeypatch.setattr("deeptutor.services.embedding.get_embedding_config", lambda: embedding)+ monkeypatch.setattr(+ "deeptutor.services.rag.pipelines.lightrag.engine.installed_version", lambda: "1.5.7rc2"+ )base_dir = tmp_path / "knowledge_bases"raw_dir = base_dir / "kb" / "raw"raw_dir.mkdir(parents=True)@@ -1580,6 +1591,14 @@ def test_reindex_task_persists_completed_progress(monkeypatch, tmp_path: Path) -async def initialize(self, *_args, **kwargs) -> bool:kwargs["progress_callback"](1, 1)+ version = base_dir / "kb" / "version-1"+ version.mkdir()+ (version / "kv_store_doc_status.json").write_text(+ json.dumps({"fixture": {"status": "processed"}}), encoding="utf-8"+ )+ storage.write_meta(version)+ if embedding_changed:+ embedding.model = "later-default"return Truerag_service_module = importlib.import_module("deeptutor.services.rag.service")@@ -1632,8 +1651,8 @@ def test_reindex_task_persists_completed_progress(monkeypatch, tmp_path: Path) -assert "progress" not in entryassert entry["last_indexed_count"] == 1assert entry["last_indexed_action"] == "reindex"- assert entry["needs_reindex"] is False- assert "embedding_mismatch" not in entry+ assert bool(entry.get("needs_reindex")) is embedding_changed+ assert bool(entry.get("embedding_mismatch")) is embedding_changeddef test_reindex_task_preserves_prepublication_failure(monkeypatch, tmp_path: Path) -> None:diff --git a/tests/services/rag/test_lightrag_embedding_compatibility.py b/tests/services/rag/test_lightrag_embedding_compatibility.pynew file mode 100644index 000000000..c8d0e3a0a--- /dev/null+++ b/tests/services/rag/test_lightrag_embedding_compatibility.py@@ -0,0 +1,253 @@+"""Published vector identity and operation-local embedding consistency."""++from __future__ import annotations++import asyncio+from copy import deepcopy+import importlib.util+import json+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import pytest++from deeptutor.knowledge.manager import KnowledgeBaseManager, _reconcile_embedding_flags+from deeptutor.services.embedding.config import EmbeddingConfig+from deeptutor.services.rag.embedding_signature import signature_from_config+from deeptutor.services.rag.pipelines.lightrag import config, engine, indexing_policy, storage+from deeptutor.services.rag.pipelines.lightrag import pipeline as pipeline_module+from deeptutor.services.rag.pipelines.lightrag.pipeline import BatchOutcome, LightRagPipeline+++def embedding(monkeypatch: pytest.MonkeyPatch) -> EmbeddingConfig:+ cfg = EmbeddingConfig(+ model="embed-original", dim=3, base_url="https://embedding.test/v1", api_key="test-key"+ )+ monkeypatch.setattr("deeptutor.services.embedding.get_embedding_config", lambda: cfg)+ monkeypatch.setattr(engine, "installed_version", lambda: "1.5.7rc2")+ return cfg+++def _snapshot() -> SimpleNamespace:+ return SimpleNamespace(+ vision_available=False,+ persisted_policy=lambda: {"policy": "pinned", "fingerprint": "a" * 64},+ )+++def _published(root: Path) -> None:+ root.mkdir(parents=True)+ (root / "kv_store_doc_status.json").write_text(+ json.dumps({"doc": {"status": "processed"}}), encoding="utf-8"+ )+ storage.write_meta(root, indexing_policy=_snapshot().persisted_policy())+++def _pipeline(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> LightRagPipeline:+ pipeline = LightRagPipeline(str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)+ monkeypatch.setattr(pipeline, "_resolve_mode", lambda *_args: "hybrid")+ monkeypatch.setattr(pipeline_module, "resolve_write_snapshot", lambda *_a, **_k: _snapshot())+ monkeypatch.setattr(pipeline, "_clear_pending_policy", lambda *_args: None)+ return pipeline+++ "field,value",+ [("model", "embed-other"), ("dim", 4), ("base_url", "https://other.test/v1")],+)+def test_changed_identity_blocks_query_and_append_before_vectors_open(+ embedding: EmbeddingConfig,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ field: str,+ value: Any,+) -> None:+ root = tmp_path / "kb" / "version-1"+ _published(root)+ before = (root / "meta.json").read_bytes()+ setattr(embedding, field, value)+ pipeline = _pipeline(tmp_path, monkeypatch)+ monkeypatch.setattr(engine, "build_rag", lambda *_a, **_k: pytest.fail("opened vectors"))++ result = asyncio.run(pipeline.search("question", "kb"))+ assert result["sources"] == []+ assert result["error_type"] == "lightrag_embedding_incompatible"+ assert "Restore the original" in result["answer"]+ with pytest.raises(indexing_policy.IndexingPolicyError, match="Restore the original"):+ asyncio.run(pipeline.add_documents("kb", ["new.md"]))+ assert (root / "meta.json").read_bytes() == before+++def test_missing_identity_requires_rebuild(+ embedding: EmbeddingConfig, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ root = tmp_path / "kb" / "version-1"+ _published(root)+ meta_path = root / "meta.json"+ meta = json.loads(meta_path.read_text())+ del meta["embedding_signature"]+ meta_path.write_text(json.dumps(meta))+ entries = {"kb": {"rag_provider": "lightrag", "status": "ready"}}+ assert _reconcile_embedding_flags(entries, tmp_path)+ assert entries["kb"]["embedding_mismatch"] is True+ pipeline = _pipeline(tmp_path, monkeypatch)+ monkeypatch.setattr(engine, "build_rag", lambda *_a, **_k: pytest.fail("opened vectors"))+ assert asyncio.run(pipeline.search("question", "kb"))["error_type"] == (+ "lightrag_embedding_incompatible"+ )+ with pytest.raises(indexing_policy.IndexingPolicyError):+ asyncio.run(pipeline.add_documents("kb", ["new.md"]))+++def test_restoring_identity_recovers_query_and_incremental_append(+ embedding: EmbeddingConfig, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ root = tmp_path / "kb" / "version-1"+ _published(root)+ index_before = (root / "kv_store_doc_status.json").read_bytes()+ original = embedding.model+ embedding.model = "other"+ entries = {"kb": {"rag_provider": "lightrag", "status": "ready"}}+ assert _reconcile_embedding_flags(entries, tmp_path)+ embedding.model = original+ assert _reconcile_embedding_flags(entries, tmp_path)+ assert not entries["kb"].get("embedding_mismatch")+ assert entries["kb"]["needs_reindex"] is False+ assert (root / "kv_store_doc_status.json").read_bytes() == index_before++ pipeline = _pipeline(tmp_path, monkeypatch)+ monkeypatch.setattr(engine, "build_rag", lambda *_a, **_k: object())++ async def noop(*_a: Any, **_k: Any) -> None:+ return None++ async def query(*_a: Any, **_k: Any) -> tuple[str, list]:+ return "retrieved", []++ roots = []++ async def append(path: Path, *_a: Any, **_k: Any) -> BatchOutcome:+ roots.append(path)+ return BatchOutcome(requested=1, accepted=1, processed=("new.md",))++ monkeypatch.setattr(engine, "initialize", noop)+ monkeypatch.setattr(engine, "finalize", noop)+ monkeypatch.setattr(engine, "query_with_sources", query)+ monkeypatch.setattr(pipeline, "_run_indexing", append)+ assert asyncio.run(pipeline.search("question", "kb"))["answer"] == "retrieved"+ assert asyncio.run(pipeline.add_documents("kb", ["new.md"]))+ assert roots == [root]+ assert not (root.parent / "version-2").exists()++[email protected]("operation", ["initialize", "add_documents"])+def test_index_operation_metadata_uses_captured_embedding_after_default_change(+ embedding: EmbeddingConfig,+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ operation: str,+) -> None:+ original = deepcopy(embedding)+ if operation == "add_documents":+ _published(tmp_path / "kb" / "version-1")+ pipeline = _pipeline(tmp_path, monkeypatch)+ captured = []++ async def index(root: Path, *_a: Any, embedding_config: EmbeddingConfig) -> BatchOutcome:+ captured.append(embedding_config)+ embedding.model = "later-default"+ assert embedding_config.model == original.model+ root.mkdir(parents=True, exist_ok=True)+ (root / "kv_store_doc_status.json").write_text('{"doc":{"status":"processed"}}')+ return BatchOutcome(requested=1, accepted=1, processed=("doc.md",))++ monkeypatch.setattr(pipeline, "_run_indexing", index)+ kwargs = {"indexing_snapshot": _snapshot()} if operation == "initialize" else {}+ assert asyncio.run(getattr(pipeline, operation)("kb", ["doc.md"], **kwargs))+ root = storage.latest_published_root(tmp_path / "kb")+ assert root is not None+ meta = json.loads((root / "meta.json").read_text())+ assert len(captured) == 1+ assert meta["embedding_signature"] == signature_from_config(original).hash()+ assert meta["embedding_model"] == original.model+ assert meta["embedding_dim"] == original.dim+ assert "test-key" not in json.dumps(meta)+++def test_query_keeps_captured_embedding_while_worker_waits(+ embedding: EmbeddingConfig, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ _published(tmp_path / "kb" / "version-1")+ original = embedding.model+ pipeline = _pipeline(tmp_path, monkeypatch)+ captured = []++ async def worker(job: Any) -> Any:+ embedding.model = "later-default"+ return await job(None)++ def build(*_a: Any, embedding_config: EmbeddingConfig, **_k: Any) -> object:+ captured.append(embedding_config.model)+ return object()++ async def noop(*_a: Any, **_k: Any) -> None:+ return None++ async def query(*_a: Any, **_k: Any) -> tuple[str, list]:+ return "retrieved", []++ monkeypatch.setattr(pipeline_module, "run_in_worker_loop", worker)+ monkeypatch.setattr(engine, "build_rag", build)+ monkeypatch.setattr(engine, "initialize", noop)+ monkeypatch.setattr(engine, "finalize", noop)+ monkeypatch.setattr(engine, "query_with_sources", query)+ assert asyncio.run(pipeline.search("question", "kb"))["answer"] == "retrieved"+ assert captured == [original]++[email protected](importlib.util.find_spec("lightrag") is None, reason="optional LightRAG SDK")+def test_adapter_calls_captured_config_and_preserves_query_role(+ embedding: EmbeddingConfig, monkeypatch: pytest.MonkeyPatch+) -> None:+ original = deepcopy(embedding)+ embedding.model = "later-default"+ calls = []++ class Client:+ def __init__(self, *, config: EmbeddingConfig) -> None:+ self.config = config++ async def embed(self, texts: list[str], *, input_type: str | None) -> list[list[float]]:+ calls.append((self.config.model, texts, input_type))+ return [[1.0, 2.0, 3.0]]++ monkeypatch.setattr("deeptutor.services.embedding.client.EmbeddingClient", Client)+ adapter = config.build_embedding_func(embedding_config=original)+ original.model = "mutated-input"+ asyncio.run(adapter(["question"], context="query"))+ assert calls == [("embed-original", ["question"], "search_query")]+ assert adapter.embedding_dim == 3+++def test_manager_surfaces_old_current_identity_and_ignores_llm_default(+ embedding: EmbeddingConfig, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ root = tmp_path / "kb" / "version-1"+ _published(root)+ manager = KnowledgeBaseManager(base_dir=str(tmp_path))+ manager.config["knowledge_bases"]["kb"] = {"rag_provider": "lightrag", "status": "ready"}+ monkeypatch.setattr(+ "deeptutor.services.config.load_lightrag_settings",+ lambda: {"llm_profile_id": "different", "llm_model_id": "different"},+ )+ assert not _reconcile_embedding_flags(manager.config["knowledge_bases"], tmp_path)+ embedding.model = "current-model"+ assert _reconcile_embedding_flags(manager.config["knowledge_bases"], tmp_path)+ info = manager.get_info("kb")+ assert info["metadata"]["indexed_embedding_model"] == "embed-original"+ assert info["metadata"]["current_embedding_model"] == "current-model"+ assert info["metadata"]["indexed_embedding_dim"] == 3+ assert info["metadata"]["current_embedding_dim"] == 3diff --git a/tests/services/rag/test_lightrag_pipeline.py b/tests/services/rag/test_lightrag_pipeline.pyindex a1dc03be0..061c84b12 100644--- a/tests/services/rag/test_lightrag_pipeline.py+++ b/tests/services/rag/test_lightrag_pipeline.py@@ -41,6 +41,14 @@ REQUIRES_LIGHTRAG = pytest.mark.skipif()[email protected](autouse=True)+def _active_embedding(monkeypatch: pytest.MonkeyPatch) -> None:+ from deeptutor.services.embedding.config import EmbeddingConfig++ cfg = EmbeddingConfig(model="test-embedding", dim=3, api_key="test-key")+ monkeypatch.setattr("deeptutor.services.embedding.get_embedding_config", lambda: cfg)++class _Bridge:def __init__(self) -> None:self.calls = 0@@ -403,12 +411,15 @@ def test_embedding_adapter_preserves_query_and_document_roles(monkeypatch) -> Nomax_tokens = 99class Client:+ def __init__(self, *, config):+ self.config = config+async def embed(self, texts, *, input_type=None):calls.append((list(texts), input_type))return [[1, 2, 3] for _ in texts]monkeypatch.setattr("deeptutor.services.embedding.get_embedding_config", EmbeddingConfig)- monkeypatch.setattr("deeptutor.services.embedding.get_embedding_client", Client)+ monkeypatch.setattr("deeptutor.services.embedding.client.EmbeddingClient", Client)adapter = config.build_embedding_func()query = asyncio.run(adapter(["question"], context="query"))document = asyncio.run(adapter(["passage"], context="document"))@@ -626,6 +637,8 @@ def test_flat_schema_two_candidate_fails_closed_until_published(tmp_path: Path)def _write_published_version(root: Path, *, indexing_policy_value: dict | None = None) -> None:+ from deeptutor.services.rag.embedding_signature import embedding_meta_fields+root.mkdir(parents=True)(root / "kv_store_doc_status.json").write_text(json.dumps({"doc": {"status": "processed", "chunks_list": ["chunk"]}}),@@ -640,6 +653,7 @@ def _write_published_version(root: Path, *, indexing_policy_value: dict | None ="parser_bridge_schema": 1,"state": "published","indexing_policy": indexing_policy_value or {"policy": "legacy_unpinned"},+ **embedding_meta_fields(),}),encoding="utf-8",@@ -1287,7 +1301,7 @@ def test_append_rejects_corrupt_or_unpublished_existing_version(def test_search_failure_is_not_reported_as_empty_success(tmp_path: Path, monkeypatch) -> None:root = tmp_path / "version-1"- root.mkdir()+ _write_published_version(root)pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))monkeypatch.setattr(storage, "latest_published_root", lambda _kb_dir: root)monkeypatch.setattr(pipeline, "_resolve_mode", lambda *_args: "hybrid")diff --git a/tests/services/rag/test_lightrag_settings_wiring.py b/tests/services/rag/test_lightrag_settings_wiring.pyindex 4b9f7ad0d..a5c91f667 100644--- a/tests/services/rag/test_lightrag_settings_wiring.py+++ b/tests/services/rag/test_lightrag_settings_wiring.py@@ -89,6 +89,22 @@ def test_global_dedicated_selection_drives_query_roles_not_embedding(assert embedding_calls == [{}]+def test_constructor_forwards_captured_embedding_config(monkeypatch, tmp_path: Path) -> None:+ from deeptutor.services.embedding.config import EmbeddingConfig++ _stub_build(monkeypatch)+ captured = []+ embedding = EmbeddingConfig(model="accepted", dim=3, api_key="test-key")++ def build_embedding(**kwargs):+ captured.append(kwargs)+ return "embedding"++ monkeypatch.setattr(engine, "build_embedding_func", build_embedding)+ engine.build_rag(tmp_path, embedding_config=embedding)+ assert captured == [{"embedding_config": embedding}]++def test_vlm_role_is_only_configured_when_enabled(monkeypatch, tmp_path: Path) -> None:_stub_build(monkeypatch)monkeypatch.setattr(engine, "build_vision_model_func", lambda **_kwargs: "vision")diff --git a/web/components/knowledge/KbDocumentsSection.tsx b/web/components/knowledge/KbDocumentsSection.tsxindex 516061135..591204f9e 100644--- a/web/components/knowledge/KbDocumentsSection.tsx+++ b/web/components/knowledge/KbDocumentsSection.tsx@@ -109,7 +109,11 @@ export default function KbDocumentsSection({const blockedReason = canUpload? null: requiresLightRagRebuild- ? t(+ ? kb.metadata?.embedding_mismatch+ ? t(+ "The current embedding configuration does not match this index. Restore the original configuration or rebuild with the current embedding before querying or adding documents.",+ )+ : t("This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.",): needsReindexdiff --git a/web/components/knowledge/KbIndexVersionsSection.tsx b/web/components/knowledge/KbIndexVersionsSection.tsxindex c4d9a33b9..d90ad9adc 100644--- a/web/components/knowledge/KbIndexVersionsSection.tsx+++ b/web/components/knowledge/KbIndexVersionsSection.tsx@@ -40,6 +40,7 @@ import IndexingModelSelector, {selectionFromLLMOption,} from "./IndexingModelSelector";import LightRagIndexingProvenance from "./LightRagIndexingProvenance";+import LightRagEmbeddingWarning from "./LightRagEmbeddingWarning";export function selectionForLightRagModelDialog(options: LLMOption[],@@ -278,6 +279,7 @@ export default function KbIndexVersionsSection({</div>{isError && <KbIndexFailureBanner kb={kb} />}+ <LightRagEmbeddingWarning kb={kb} />{isLightRag && (<LightRagIndexingProvenancediff --git a/web/components/knowledge/KnowledgeBaseDetail.tsx b/web/components/knowledge/KnowledgeBaseDetail.tsxindex 2390c7c43..39c2a4494 100644--- a/web/components/knowledge/KnowledgeBaseDetail.tsx+++ b/web/components/knowledge/KnowledgeBaseDetail.tsx@@ -2,6 +2,7 @@import { useState } from "react";import { useTranslation } from "react-i18next";+import LightRagEmbeddingWarning from "./LightRagEmbeddingWarning";import {ArrowLeft,Database,@@ -226,6 +227,7 @@ export default function KnowledgeBaseDetail({? ` · ${t("Last indexed")} ${lastIndexedLabel}`: ""}</p>+ <LightRagEmbeddingWarning kb={kb} /></div></div>{canRetry && (diff --git a/web/components/knowledge/LightRagEmbeddingWarning.tsx b/web/components/knowledge/LightRagEmbeddingWarning.tsxnew file mode 100644index 000000000..2b35c4ceb--- /dev/null+++ b/web/components/knowledge/LightRagEmbeddingWarning.tsx@@ -0,0 +1,32 @@+"use client";++import { useTranslation } from "react-i18next";+import { kbProvider, type KnowledgeBase } from "@/lib/knowledge-helpers";++export default function LightRagEmbeddingWarning({+ kb,+}: {+ kb: KnowledgeBase;+}) {+ const { t } = useTranslation();+ if (kbProvider(kb) !== "lightrag" || !kb.metadata?.embedding_mismatch)+ return null;+ const meta = kb.metadata;+ return (+ <span className="mt-2 block 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 current embedding configuration does not match this index. Restore the original configuration or rebuild with the current embedding before querying or adding documents.",+ )}+ <span className="mt-2 block">+ {t("Index embedding")}: {meta.indexed_embedding_model || t("Unknown")} ·{" "}+ {meta.indexed_embedding_dim ?? "?"}+ {t("d")}+ </span>+ <span className="block">+ {t("Current embedding")}: {meta.current_embedding_model || t("Unknown")}{" "}+ · {meta.current_embedding_dim ?? "?"}+ {t("d")}+ </span>+ </span>+ );+}diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.tsindex 121e0475f..fe94f146d 100644--- a/web/lib/knowledge-helpers.ts+++ b/web/lib/knowledge-helpers.ts@@ -172,6 +172,10 @@ export interface KnowledgeBase {embedding_model?: string;embedding_dim?: number;embedding_mismatch?: boolean;+ indexed_embedding_model?: string;+ indexed_embedding_dim?: number;+ current_embedding_model?: string;+ current_embedding_dim?: number;/** Connected-source kind (e.g. "obsidian", "subagent"); absent for ordinary indexed KBs. */type?: string;/** Absolute path of a connected Obsidian vault (when type === "obsidian"). */@@ -421,7 +425,8 @@ export const kbRequiresLightRagRebuildBeforeAppend = (kb: KnowledgeBase,): boolean =>kbProvider(kb) === "lightrag" &&- kb.metadata?.indexing_policy?.policy === "legacy_unpinned";+ (kb.metadata?.indexing_policy?.policy === "legacy_unpinned" ||+ Boolean(kb.metadata?.embedding_mismatch));export const kbIsUploadable = (kb: KnowledgeBase): boolean =>resolveKbStatus(kb) === "ready" &&diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex ee807061f..5e05ea230 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -3993,5 +3993,8 @@"readiness.detail.redis_unreachable": "Redis is unreachable","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"+ "readiness.detail.redis_available_but_memory_selected": "Redis is reachable — coordination could be switched to it",+ "Index embedding": "Index embedding",+ "Current embedding": "Current embedding",+ "The current embedding configuration does not match this index. Restore the original configuration or rebuild with the current embedding before querying or adding documents.": "The current embedding configuration does not match this index. Restore the original configuration or rebuild with the current embedding before querying or adding documents."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 974de84b9..ed6cdc7ec 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -3993,5 +3993,8 @@"readiness.detail.redis_unreachable": "Redis 连不上","readiness.detail.redis_not_configured": "未配置","readiness.detail.multiple_workers_require_redis": "多进程后端必须用 Redis 协调",- "readiness.detail.redis_available_but_memory_selected": "Redis 可用,可以把轮次协调切到它"+ "readiness.detail.redis_available_but_memory_selected": "Redis 可用,可以把轮次协调切到它",+ "Index embedding": "索引使用的嵌入模型",+ "Current embedding": "当前嵌入模型",+ "The current embedding configuration does not match this index. Restore the original configuration or rebuild with the current embedding before querying or adding documents.": "当前嵌入配置与此索引不匹配。请恢复原配置,或使用当前嵌入模型重建后再查询或添加文档。"}diff --git a/web/tests/lightrag-embedding-compatibility.spec.tsx b/web/tests/lightrag-embedding-compatibility.spec.tsxnew file mode 100644index 000000000..b2417307d--- /dev/null+++ b/web/tests/lightrag-embedding-compatibility.spec.tsx@@ -0,0 +1,122 @@+import React from "react";+import { act, fireEvent, render, screen } from "@testing-library/react";+import { expect, it, vi } from "vitest";+import KnowledgeBaseDetail from "@/components/knowledge/KnowledgeBaseDetail";+import KbIndexVersionsSection from "@/components/knowledge/KbIndexVersionsSection";+import KnowledgeHome from "@/components/knowledge/KnowledgeHome";+import {+ DEFAULT_UPLOAD_POLICY,+ kbCanUploadDocuments,+ type KnowledgeBase,+} from "@/lib/knowledge-helpers";++const fixture = vi.hoisted(() => ({+ t: (key: string) => key,+ refresh: vi.fn(async () => {}),+}));+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: fixture.t }) }));+vi.mock("next/dynamic", () => ({ default: () => () => null }));+vi.mock("@/features/knowledge/api/engines", async (original) => ({+ ...(await original<typeof import("@/features/knowledge/api/engines")>()),+ getLightRagConfig: async () => ({ llm_profile_id: "", llm_model_id: "" }),+}));+vi.mock("@/hooks/useLLMOptions", () => ({+ useLLMOptions: () => ({+ options: [],+ activeDefault: null,+ loading: false,+ error: false,+ refresh: fixture.refresh,+ }),+}));+vi.mock("@/features/knowledge/api/files", async (original) => ({+ ...(await original<typeof import("@/features/knowledge/api/files")>()),+ listKnowledgeBaseFiles: async () => [+ { name: "paper.txt", type: "file", size: 12, mime_type: "text/plain" },+ ],+}));++const kb: KnowledgeBase = {+ name: "papers",+ status: "ready",+ metadata: {+ indexing_policy: { policy: "pinned" },+ embedding_mismatch: true,+ indexed_embedding_model: "original-model",+ indexed_embedding_dim: 3,+ current_embedding_model: "current-model",+ current_embedding_dim: 3,+ },+ statistics: {+ rag_provider: "lightrag",+ raw_documents: 1,+ index_versions: [{ version: "version-1", provider: "lightrag", ready: true }],+ },+};++it("omits mismatch warnings from list cards", () => {+ render(+ <KnowledgeHome+ kbs={[kb]}+ providers={[]}+ onOpenKb={vi.fn()}+ onOpenEngine={vi.fn()}+ onOpenSource={vi.fn()}+ onCreate={vi.fn()}+ activeSection="knowledge-bases"+ onSectionChange={vi.fn()}+ />,+ );+ expect(screen.queryByText(/Restore the original configuration/)).not.toBeInTheDocument();+ expect(screen.queryByText(/Index embedding.*original-model/)).not.toBeInTheDocument();+});++it("shows detail guidance while files and downloads remain accessible", async () => {+ render(+ <KnowledgeBaseDetail+ kb={kb}+ uploadPolicy={DEFAULT_UPLOAD_POLICY}+ history={[]}+ onCreate={vi.fn()}+ onUpload={vi.fn()}+ onReindex={vi.fn()}+ onUpdatePendingIndexingPolicy={vi.fn()}+ onRetry={vi.fn()}+ onSetDefault={vi.fn()}+ onDelete={vi.fn()}+ onClearHistory={vi.fn()}+ />,+ );+ expect(screen.getByText(/Restore the original configuration/)).toBeInTheDocument();+ expect(screen.getByText(/Index embedding.*original-model/)).toBeInTheDocument();+ expect(screen.getByText(/Current embedding.*current-model/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Files" }));+ fireEvent.click(await screen.findByText("paper.txt"));+ expect(screen.getByRole("link", { name: "Download" })).toHaveAttribute(+ "href",+ expect.stringContaining("/knowledge-bases/papers/files/paper.txt"),+ );+});++it("keeps version guidance visible alongside a failed rebuild", async () => {+ await act(async () => { render(+ <KbIndexVersionsSection+ kb={{ ...kb, status: "error" }}+ onReindex={vi.fn()}+ onUpdatePendingIndexingPolicy={vi.fn()}+ />,+ ); });+ expect(screen.getByText(/Restore the original configuration/)).toBeInTheDocument();+ expect(screen.getByText(/Index embedding.*original-model/)).toBeInTheDocument();+ expect(screen.getByText(/Current embedding.*current-model/)).toBeInTheDocument();+});++it.each(["ready", "error"])("blocks incompatible appends in %s state and restores them", (status) => {+ expect(kbCanUploadDocuments({ ...kb, status }, false)).toBe(false);+ expect(+ kbCanUploadDocuments(+ { ...kb, status, metadata: { ...kb.metadata, embedding_mismatch: false } },+ false,+ ),+ ).toBe(true);+});