Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

refactor: unify LightRAG defaults and confirmed rebuilds

NoxsMedia80d257d55e56
diff --git a/README.md b/README.md
index f8a9e5b4b..e055dd7bc 100644
--- a/README.md
+++ b/README.md
@@ -224,7 +224,7 @@ DeepTutor is an agent-native learning workspace that connects tutoring, problem
- **Connected learning context** — Knowledge bases, books, Co-Writer drafts, notebooks, question banks, personas, and Memory can be reused across the workflows that support them, subject to account grants and learning policies.
- **Immersive video learning** — paste a YouTube link for privacy-enhanced native playback, synchronized captions, timestamp-grounded tutoring, and resumable progress; administrators can switch playback to a self-hosted Invidious instance without rebuilding materials.
- **Subagents and Partners** — from Chat, consult a live agent harness (Claude Code, Codex, Antigravity, Kimi, opencode, MiMo, Hermes, OpenClaw, or DeepSeek) or a Partner, import past conversations, and run persistent IM companions on the same brain.
-- **Multi-engine knowledge** — versioned RAG libraries across LlamaIndex, PageIndex, GraphRAG, LightRAG, a remote LightRAG Server, a self-hosted WeKnora knowledge base, a Tencent IMA or MarginNote 4 library, or a linked Obsidian vault, with pluggable document parsing. See [native LightRAG role models](deeptutor/services/rag/pipelines/lightrag/README.md) for independent extraction, query and vision settings.
+- **Multi-engine knowledge** — versioned RAG libraries across LlamaIndex, PageIndex, GraphRAG, LightRAG, a remote LightRAG Server, a self-hosted WeKnora knowledge base, a Tencent IMA or MarginNote 4 library, or a linked Obsidian vault, with pluggable document parsing. See [native LightRAG role models](deeptutor/services/rag/pipelines/lightrag/README.md) for independent extraction, query and vision settings, default-only creation and confirmed rebuilds.
- **Extensible tools and skills** — built-in tools, MCP servers, CLI apps, image / video / voice generation models, and installable community skills from EduHub.
- **Inspectable memory** — L1 traces, L2 surface summaries, and L3 synthesis make personalization visible and editable; the Memory Graph links L2 facts to L1 evidence and L3 synthesis to contributing surfaces.
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index cfc9c0276..8a5a646b7 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -16,7 +16,7 @@ from pathlib import Path
import re
import shutil
import traceback
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Annotated, Any
from uuid import uuid4
if TYPE_CHECKING:
@@ -689,22 +689,6 @@ def _validate_registered_provider(raw_provider: str | None) -> str:
return normalize_provider_name(raw_provider)
-def _freeze_indexing_llm_form(raw: str):
- """Parse and resolve the optional LightRAG selection exactly once."""
- from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (
- IndexingPolicyError,
- freeze_roles,
- )
-
- try:
- selection = json.loads(raw)
- if not isinstance(selection, dict) or not selection:
- raise ValueError("indexing_llm must be a non-empty JSON object.")
- return selection, freeze_roles(selection)
- except (json.JSONDecodeError, ValueError, PermissionError, IndexingPolicyError) as exc:
- raise HTTPException(status_code=400, detail=str(exc)) from exc
-
-
def _freeze_append_indexing(
kb_name: str, base_dir: str | Path, provider: str, image_analysis: bool | None = None
) -> "IndexingPolicySnapshot | None":
@@ -729,15 +713,16 @@ def _freeze_append_indexing(
raise HTTPException(status_code=409, detail=str(exc)) from exc
-def _freeze_default_indexing_llm():
+def _freeze_default_indexing_llm() -> "IndexingPolicySnapshot":
"""Freeze the released LightRAG model default for one create or rebuild."""
from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (
IndexingPolicyError,
freeze_default_snapshot,
+ with_embedding,
)
try:
- return freeze_default_snapshot()
+ return with_embedding(freeze_default_snapshot())
except (ValueError, PermissionError, IndexingPolicyError) as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -3089,16 +3074,13 @@ async def _create_knowledge_base_owned(
rag_provider = _validate_registered_provider(rag_provider)
indexing_snapshot = None
- if rag_provider == LIGHTRAG_PROVIDER:
- if indexing_llm:
- _, indexing_snapshot = _freeze_indexing_llm_form(indexing_llm)
- else:
- indexing_snapshot = _freeze_default_indexing_llm()
- elif indexing_llm:
+ 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()
pageindex_mode = str(pageindex_mode or "").strip().lower()
if rag_provider == PAGEINDEX_OSS_PROVIDER and pageindex_mode not in {
"",
@@ -3162,7 +3144,7 @@ async def _create_knowledge_base_owned(
manager.config["knowledge_bases"][name]["pageindex_mode"] = pageindex_mode
if search_mode:
manager.config["knowledge_bases"][name]["search_mode"] = search_mode
- if indexing_snapshot is not None:
+ if indexing_snapshot is not None and files:
pending_policy = indexing_snapshot.persisted_policy()
pending_policy["policy"] = "pending_pinned"
manager.config["knowledge_bases"][name]["pending_indexing_policy"] = pending_policy
@@ -3464,12 +3446,26 @@ async def run_reindex_task(
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."""
+ 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.rag.pipelines.lightrag.indexing_policy import public_rebuild_config
+
+ return public_rebuild_config(_freeze_default_indexing_llm())
+
+
@router.post("/knowledge-bases/{kb_name}/reindex")
async def reindex_knowledge_base(
kb_name: str,
background_tasks: BackgroundTasks,
indexing_llm: str = Form(""),
-):
+ config_fingerprint: 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
@@ -3486,17 +3482,24 @@ async def reindex_knowledge_base(
)
_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:
+ indexing_snapshot = _freeze_default_indexing_llm()
+
+ if indexing_snapshot is not None and config_fingerprint:
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (
+ public_rebuild_config,
)
+ if public_rebuild_config(indexing_snapshot)["fingerprint"] != config_fingerprint:
+ raise HTTPException(
+ status_code=409,
+ detail="Default 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
@@ -3572,110 +3575,21 @@ async def reindex_knowledge_base(
async def update_pending_indexing_policy(
kb_name: str,
payload: LightRagIndexingSelection | IndexingLLMSelectionRequest,
-):
- from deeptutor.services.rag.pipelines.lightrag.indexing_policy import IndexingPolicyError
- from deeptutor.services.rag.pipelines.lightrag.write_lock import write_ownership
-
- _, resolved_name, base_dir = _writable_kb(kb_name)
- try:
- with write_ownership(base_dir / resolved_name):
- return await _update_pending_indexing_policy_owned(kb_name, payload)
- except IndexingPolicyError as exc:
- raise HTTPException(status_code=409, detail=str(exc)) from exc
-
-
-async def _update_pending_indexing_policy_owned(
- kb_name: str,
- payload: LightRagIndexingSelection | IndexingLLMSelectionRequest,
) -> dict[str, Any]:
- """Change the pending model of an empty, unpublished LightRAG KB."""
- manager, kb_name, kb_base_dir = _writable_kb(kb_name)
- kb_entry = _load_kb_entry_or_404(manager, kb_name)
- _assert_not_connected_kb(kb_name, kb_entry)
- provider = _validate_registered_provider(kb_entry.get("rag_provider"))
- if provider != LIGHTRAG_PROVIDER:
- raise HTTPException(
- status_code=400,
- detail="Indexing-model policy is supported only for built-in LightRAG.",
- )
-
- def assert_no_active_task(entry: dict) -> None:
- status = str(entry.get("status") or "").lower()
- progress = entry.get("progress")
- stage = str(progress.get("stage") or "").lower() if isinstance(progress, dict) else ""
- if status in {"initializing", "processing"} and stage not in {
- "completed",
- "error",
- }:
- raise HTTPException(
- status_code=409,
- detail=(
- "The pending indexing model cannot change while an indexing task is active."
- ),
- )
-
- assert_no_active_task(kb_entry)
- kb_dir = kb_base_dir / kb_name
- from deeptutor.services.rag.pipelines.lightrag.storage import latest_published_root
-
- if latest_published_root(kb_dir) is not None:
- raise HTTPException(
- status_code=409,
- detail=(
- "This knowledge base already has a published index; run a full re-index "
- "to change its model."
- ),
- )
- raw_dir = kb_dir / "raw"
- if raw_dir.is_dir() and any(path.is_file() for path in raw_dir.rglob("*")):
- raise HTTPException(
- status_code=409,
- detail=(
- "The pending indexing model can change only while the knowledge base is empty."
- ),
- )
-
- from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (
- IndexingPolicyError,
- pending_policy_for_selection,
+ """Reject obsolete model edits instead of saving a policy that will not apply."""
+ manager, kb_name, _ = _writable_kb(kb_name)
+ _load_kb_entry_or_404(manager, kb_name)
+ raise HTTPException(
+ status_code=409,
+ detail="Empty LightRAG knowledge bases follow defaults. Configure models in Settings.",
)
- try:
- policy = pending_policy_for_selection(payload.model_dump(exclude_none=True))
- except (ValueError, PermissionError, IndexingPolicyError) as exc:
- raise HTTPException(status_code=400, detail=str(exc)) from exc
-
- # Re-read immediately before saving so a task queued during model
- # resolution cannot be overwritten through a stale entry reference.
- kb_entry = _load_kb_entry_or_404(manager, kb_name)
- assert_no_active_task(kb_entry)
- if latest_published_root(kb_dir) is not None:
- raise HTTPException(
- status_code=409,
- detail=(
- "This knowledge base already has a published index; run a full re-index "
- "to change its model."
- ),
- )
- if raw_dir.is_dir() and any(path.is_file() for path in raw_dir.rglob("*")):
- raise HTTPException(
- status_code=409,
- detail=(
- "The pending indexing model can change only while the knowledge base is empty."
- ),
- )
- kb_entry["pending_indexing_policy"] = policy
- manager._save_config()
- from deeptutor.services.rag.pipelines.lightrag.indexing_policy import public_policy
-
- return {"indexing_policy": public_policy(policy)}
-
@router.post("/knowledge-bases/{kb_name}/retry")
async def retry_knowledge_base(
kb_name: str,
background_tasks: BackgroundTasks,
-):
+) -> dict[str, Any]:
"""Retry a failed KB initialization/indexing run from its stored raw files."""
try:
manager, resolved_name, _ = _writable_kb(kb_name)
@@ -3691,7 +3605,14 @@ async def retry_knowledge_base(
"Use re-index when you want to rebuild a healthy knowledge base."
),
)
- return await reindex_knowledge_base(resolved_name, background_tasks, 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=""
+ )
except HTTPException:
raise
except Exception as e:
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index 57ba9fc77..b49da48a0 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -596,9 +596,9 @@ class KnowledgeBaseManager:
continue
# Check if this is a valid KB directory (flat versions or legacy stores)
+ rag_storage = item / "rag_storage"
from deeptutor.services.rag.index_versioning import list_kb_versions
- rag_storage = item / "rag_storage"
versions = list_kb_versions(item)
detected_provider = _detect_provider_from_versions(versions)
is_valid_kb = has_ready_provider_index(item, detected_provider) or (
@@ -1402,11 +1402,27 @@ class KnowledgeBaseManager:
if indexing_policy is None:
pending = kb_config.get("pending_indexing_policy")
indexing_policy = (
- pending if isinstance(pending, dict) else {"policy": "legacy_unpinned"}
+ {"policy": "defaults"}
+ if not index_versions
+ else pending
+ if isinstance(pending, dict)
+ else {"policy": "legacy_unpinned"}
)
from deeptutor.services.rag.pipelines.lightrag.indexing_policy import public_policy
metadata["indexing_policy"] = public_policy(indexing_policy)
+ if published_root is not None and indexing_policy.get("policy") == "pinned":
+ from deeptutor.services.rag.pipelines.lightrag.indexing_policy import (
+ IndexingPolicyError,
+ snapshot_from_persisted,
+ )
+
+ try:
+ snapshot_from_persisted(indexing_policy)
+ except (IndexingPolicyError, ValueError, PermissionError):
+ # This is local catalog/access validation, not a model health probe.
+ # Keep credential/provider exception details out of public metadata.
+ metadata["indexing_model_unavailable"] = True
for version in index_versions:
if isinstance(version.get("indexing_policy"), dict):
version["indexing_policy"] = public_policy(version["indexing_policy"])
diff --git a/deeptutor/services/rag/pipelines/lightrag/README.md b/deeptutor/services/rag/pipelines/lightrag/README.md
index 909723469..15da0e824 100644
--- a/deeptutor/services/rag/pipelines/lightrag/README.md
+++ b/deeptutor/services/rag/pipelines/lightrag/README.md
@@ -12,16 +12,18 @@ Shared engine settings require administrator access when authentication is enabl
| VLM | Requested image analysis | Disabled, base or explicit vision model |
Fresh settings are distinguished from historical settings. Choose and save a
-LightRAG base before querying; creation can also use explicit indexing selections.
+LightRAG base in Settings before querying or creating a knowledge base.
New role configurations disable VLM by default. Inheriting the base for VLM
requires a model that supports image inputs. Disabling VLM preserves text,
table and equation processing. An explicit image-analysis request on a disabled
index fails with full-rebuild guidance.
-Each enabled role can override supported reasoning effort. An unspecified value
-inherits the selected model's saved default; `none` explicitly disables reasoning
-where supported. Unsupported choices are rejected without substituting another
-model or reasoning level. Concurrency and timeout limits apply per role to
+Each enabled role can override supported reasoning effort. `Auto` leaves reasoning
+controls to the provider; `none` explicitly disables reasoning where supported.
+An inherited role follows the base reasoning unless it has its own override.
+Restoring an older pinned index retains its recorded reasoning semantics.
+Unsupported choices are rejected without substituting another model or reasoning
+level. Concurrency and timeout limits apply per role to
subsequent tasks and do not require rebuilding. Accepted tasks keep their effective
models, reasoning and limits while queued and running.
@@ -33,9 +35,15 @@ even when LightRAG requests its COT output format.
## Creating, appending and rebuilding
-Creation and full rebuild dialogs prefill EXTRACT and VLM from engine settings.
-You may change both for that index. An empty, idle knowledge base also allows
-editing its pending selection before first publication.
+Configure models in Settings. Creation and full rebuild do not offer per-index
+model overrides. An idle, unpublished empty knowledge base follows current valid
+defaults until its first accepted indexing task freezes the configuration.
+
+Before rebuilding, review the current default embedding model/dimension and
+EXTRACT/VLM models and reasoning. If defaults change before submission, review
+and confirm the refreshed configuration. Accepted tasks retain the same embedding
+and role settings through execution and version publication. Failed-task retry
+actions also use this confirmation flow.
After publication, uploads and folder/GitHub sync use the index's pinned EXTRACT
and VLM identities. Changing engine defaults does not change an existing index.
@@ -43,9 +51,13 @@ Enabling, disabling or replacing VLM, or replacing EXTRACT or their reasoning
configuration, requires a full rebuild. If a valid VLM was pinned before the first
image, later image uploads can use it without another rebuild.
-The index details show pending or published model provenance, effective vision
-state and whether VLM was used. A failed or cancelled rebuild keeps the previous
-published index. A queued operation whose target changed fails before writing;
+Index versions show their version identifier, state, timestamp and actual embedding,
+EXTRACT and VLM configuration. The display distinguishes provider-default reasoning,
+explicit `none` and disabled VLM. Returning from Settings refreshes default-role
+summaries. Unavailable pinned indexing models require restoring access or rebuilding
+with new defaults, but do not unconditionally block existing text retrieval.
+A failed or cancelled rebuild keeps the previous published index. A queued
+operation whose target changed fails before writing;
resubmit it against the current index. Concurrent writers for one knowledge base
are rejected, so wait for the active operation to finish before resubmitting.
diff --git a/deeptutor/services/rag/pipelines/lightrag/config.py b/deeptutor/services/rag/pipelines/lightrag/config.py
index d7fd19ccf..9041da503 100644
--- a/deeptutor/services/rag/pipelines/lightrag/config.py
+++ b/deeptutor/services/rag/pipelines/lightrag/config.py
@@ -21,10 +21,13 @@ import importlib.util
import inspect
import logging
import re
-from typing import TYPE_CHECKING, TypeVar
+from typing import TYPE_CHECKING, Any, TypeVar
if TYPE_CHECKING:
+ from lightrag.utils import EmbeddingFunc
+
from deeptutor.multi_user.models import CurrentUser
+ from deeptutor.services.embedding.config import EmbeddingConfig
from deeptutor.services.llm.config import LLMConfig
from .worker import OwnerLoopBridge
@@ -283,8 +286,8 @@ def build_llm_model_func(
):
del enable_cot
- async def request():
- async def complete():
+ async def request() -> Any:
+ async def complete() -> Any:
provider_kwargs = {}
if response_format is not None:
provider_kwargs["response_format"] = response_format
@@ -344,8 +347,8 @@ def build_vision_model_func(
if not isinstance(image_data, str) or not image_data.strip():
raise ValueError("LightRAG vision image input requires a non-empty base64 value")
- async def request():
- async def complete():
+ async def request() -> Any:
+ async def complete() -> Any:
provider_kwargs = {}
if response_format is not None:
provider_kwargs["response_format"] = response_format
@@ -382,13 +385,17 @@ def vision_model_available() -> bool:
return False
-def build_embedding_func(*, io_bridge: OwnerLoopBridge | None = None):
+def build_embedding_func(
+ *,
+ io_bridge: OwnerLoopBridge | None = None,
+ embedding_config: EmbeddingConfig | None = None,
+) -> EmbeddingFunc:
"""Wrap DeepTutor's embedding client in LightRAG's ``EmbeddingFunc``."""
from lightrag.utils import EmbeddingFunc
from deeptutor.services.embedding import get_embedding_client, get_embedding_config
- cfg = get_embedding_config()
+ cfg = 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(
@@ -396,9 +403,14 @@ def build_embedding_func(*, io_bridge: OwnerLoopBridge | None = None):
"Settings → Catalog before using a LightRAG knowledge base."
)
- client = get_embedding_client()
+ if embedding_config is None:
+ client = get_embedding_client()
+ else:
+ from deeptutor.services.embedding.client import EmbeddingClient
+
+ 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
@@ -408,7 +420,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.py
index 0d4a7b0b6..310985acf 100644
--- a/deeptutor/services/rag/pipelines/lightrag/engine.py
+++ b/deeptutor/services/rag/pipelines/lightrag/engine.py
@@ -189,6 +189,7 @@ def build_rag(
enable_vlm: bool = False,
indexing_snapshot: Any | None = None,
query_roles: dict[str, Any] | None = None,
+ embedding_config: Any | None = None,
) -> Any:
"""Construct one exact-version, version-isolated LightRAG instance."""
_require_exact_version()
@@ -200,6 +201,10 @@ def build_rag(
if io_bridge is not None:
llm_adapter_kwargs["io_bridge"] = io_bridge
embedding_adapter_kwargs["io_bridge"] = io_bridge
+ if indexing_snapshot is not None:
+ embedding_config = indexing_snapshot.embedding_config
+ if embedding_config is not None:
+ embedding_adapter_kwargs["embedding_config"] = embedding_config
from .indexing_policy import cache_identity, cache_identity_for_config
from .roles import resolve_query_roles
diff --git a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py
index 731c8f6ed..a185a7c6b 100644
--- a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py
+++ b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from copy import deepcopy
from dataclasses import dataclass, field, replace
import hashlib
import json
@@ -218,6 +219,7 @@ class IndexingPolicySnapshot:
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:
@@ -425,6 +427,7 @@ def revalidate_snapshot(snapshot: IndexingPolicySnapshot) -> IndexingPolicySnaps
target_policy=snapshot.target_policy,
image_analysis=snapshot.image_analysis,
target_revision=snapshot.target_revision,
+ embedding_config=snapshot.embedding_config,
)
@@ -464,6 +467,7 @@ def bind_target(
from .storage import latest_published_root
target = latest_published_root(kb_dir)
+ snapshot = with_embedding(snapshot)
return replace(
snapshot,
target_version=str(target) if target else None,
@@ -532,10 +536,16 @@ def resolve_write_snapshot(
) -> IndexingPolicySnapshot:
if explicit is not None:
return explicit
- policy = effective_policy(kb_dir, base_dir=base_dir, kb_name=kb_name)
- if policy is None:
+ # Empty KBs (including old creation-time pending policies) follow defaults.
+ # Published/partial versions still require verified historical identities.
+ from deeptutor.services.rag.index_versioning import list_kb_versions
+
+ from .storage import latest_published_root
+
+ if latest_published_root(kb_dir) is None and not list_kb_versions(kb_dir):
return freeze_default_snapshot()
- if policy.get("policy") == POLICY_LEGACY:
+ policy = effective_policy(kb_dir, base_dir=base_dir, kb_name=kb_name)
+ if policy is None or policy.get("policy") == POLICY_LEGACY:
raise IndexingModelChangedError(
"This LightRAG index has no verified indexing model; run a full re-index "
"before appending documents."
@@ -543,6 +553,34 @@ def resolve_write_snapshot(
return snapshot_from_persisted(policy)
+def with_embedding(snapshot: IndexingPolicySnapshot) -> 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())
+ 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]:
+ """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()}),
+ "indexing_policy": public_policy(policy),
+ "embedding": {"model": signature.model, "dimension": signature.dimension},
+ }
+
+
def cache_identity(snapshot: IndexingLLMSnapshot) -> str:
if snapshot.fingerprint:
return snapshot.fingerprint
diff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.py
index b9d0b525f..58898dedd 100644
--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py
+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py
@@ -22,7 +22,6 @@ from . import config as lr_config
from .indexing_policy import (
IndexingPolicyError,
IndexingPolicySnapshot,
- effective_policy,
freeze_default_snapshot,
resolve_write_snapshot,
)
@@ -391,15 +390,8 @@ class LightRagPipeline:
kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)
snapshot = kwargs.get("indexing_snapshot") or kwargs.get("accepted_indexing_snapshot")
if snapshot is None:
- policy = effective_policy(
- kb_dir,
- base_dir=self.kb_base_dir,
- kb_name=kb_name,
- )
- if policy is not None and policy.get("policy") == "pending_pinned":
- snapshot = indexing_policy.snapshot_from_persisted(policy)
- else:
- snapshot = freeze_default_snapshot()
+ snapshot = freeze_default_snapshot()
+ snapshot = indexing_policy.with_embedding(snapshot)
if "image_analysis" in kwargs:
snapshot = indexing_policy.with_image_analysis(snapshot, kwargs["image_analysis"])
root_dir = resolve_storage_dir_for_rebuild(kb_dir, None)
@@ -414,7 +406,9 @@ class LightRagPipeline:
before_publish = kwargs.get("before_publish")
if before_publish is not None:
before_publish(root_dir)
- storage.write_meta(root_dir, indexing_policy=policy)
+ storage.write_meta(
+ root_dir, indexing_policy=policy, embedding_config=snapshot.embedding_config
+ )
self._clear_pending_policy(kb_name)
return outcome.complete
except asyncio.CancelledError:
@@ -468,6 +462,7 @@ class LightRagPipeline:
kb_name=kb_name,
explicit=explicit,
)
+ snapshot = indexing_policy.with_embedding(snapshot)
if "image_analysis" in kwargs:
snapshot = indexing_policy.with_image_analysis(snapshot, kwargs["image_analysis"])
if existing is not None:
@@ -489,11 +484,15 @@ class LightRagPipeline:
before_publish = kwargs.get("before_publish")
if before_publish is not None:
before_publish(root_dir)
- storage.write_meta(root_dir, indexing_policy=policy)
+ storage.write_meta(
+ root_dir, indexing_policy=policy, embedding_config=snapshot.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=snapshot.embedding_config
+ )
self._clear_pending_policy(kb_name)
except Exception:
self.logger.warning(
@@ -544,12 +543,22 @@ class LightRagPipeline:
try:
self._ensure_available()
+ from copy import deepcopy
+
+ from deeptutor.services.embedding import get_embedding_config
+
from .roles import resolve_query_roles
+ embedding_config = deepcopy(get_embedding_config())
query_roles = resolve_query_roles()
- async def job(io_bridge: OwnerLoopBridge):
- rag = engine.build_rag(root_dir, io_bridge=io_bridge, query_roles=query_roles)
+ async def job(io_bridge: OwnerLoopBridge) -> Any:
+ rag = engine.build_rag(
+ root_dir,
+ io_bridge=io_bridge,
+ query_roles=query_roles,
+ embedding_config=embedding_config,
+ )
failed = True
try:
await engine.initialize(rag)
diff --git a/deeptutor/services/rag/pipelines/lightrag/storage.py b/deeptutor/services/rag/pipelines/lightrag/storage.py
index a79a9e392..babb1d461 100644
--- a/deeptutor/services/rag/pipelines/lightrag/storage.py
+++ b/deeptutor/services/rag/pipelines/lightrag/storage.py
@@ -232,7 +232,12 @@ 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 write_meta(
+ root_dir: Path,
+ *,
+ indexing_policy: dict[str, Any] | None = None,
+ embedding_config: Any | None = None,
+) -> None:
"""Write a flat-layout ``meta.json`` so the version lists as ready.
Mirrors ``index_versioning.write_version_meta`` but carries a synthetic
@@ -241,13 +246,25 @@ def write_meta(root_dir: Path, *, indexing_policy: dict[str, Any] | None = None)
embedding compatibility at connect time (LightRAG otherwise fails retrieval
silently 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_for
target = Path(root_dir)
previous = _read_meta(target) or {}
now = datetime.now(timezone.utc).replace(tzinfo=None).isoformat() + "Z"
+ if embedding_config is not None:
+ signature = signature_from_config(embedding_config)
+ embedding_fields = {
+ "embedding_signature": signature.hash(),
+ "embedding_model": signature.model,
+ "embedding_dim": signature.dimension,
+ }
+ else:
+ embedding_fields = embedding_meta_fields()
payload = {
"version": target.name,
"signature": PROVIDER,
@@ -264,7 +281,7 @@ def write_meta(root_dir: Path, *, indexing_policy: dict[str, Any] | None = None)
"indexing_policy": indexing_policy
or 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.py
index 890681a53..e01ad8962 100644
--- a/tests/api/test_knowledge_router.py
+++ b/tests/api/test_knowledge_router.py
@@ -2290,7 +2290,7 @@ def test_create_mode_aware_kb_persists_per_kb_search_mode(monkeypatch, tmp_path:
assert manager.config["knowledge_bases"]["kb-light"]["search_mode"] == "hybrid"
-def test_create_empty_lightrag_kb_persists_redacted_pending_policy(
+def test_create_empty_lightrag_kb_does_not_persist_creation_time_policy(
monkeypatch, tmp_path: Path
) -> None:
monkeypatch.setattr(
@@ -2307,17 +2307,11 @@ def test_create_empty_lightrag_kb_persists_redacted_pending_policy(
"vision_available": True,
}
)
- seen: list[str] = []
-
- def freeze_form(raw: str):
- seen.append(raw)
- return {"profile_id": "profile-1", "model_id": "model-1"}, snapshot
-
monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)
monkeypatch.setattr(knowledge_router_module, "KnowledgeBaseInitializer", _FakeInitializer)
monkeypatch.setattr(knowledge_router_module, "_kb_base_dir", manager.base_dir)
monkeypatch.setattr(knowledge_router_module, "_assert_provider_ready", lambda _provider: None)
- monkeypatch.setattr(knowledge_router_module, "_freeze_indexing_llm_form", freeze_form)
+ monkeypatch.setattr(knowledge_router_module, "_freeze_default_indexing_llm", lambda: snapshot)
with TestClient(_build_app()) as client:
response = client.post(
@@ -2325,16 +2319,12 @@ def test_create_empty_lightrag_kb_persists_redacted_pending_policy(
data={
"name": "kb-pending",
"rag_provider": "lightrag",
- "indexing_llm": json.dumps({"profile_id": "profile-1", "model_id": "model-1"}),
},
)
assert response.status_code == 200
- assert len(seen) == 1
- pending = manager.config["knowledge_bases"]["kb-pending"]["pending_indexing_policy"]
- assert pending["policy"] == "pending_pinned"
- assert pending["fingerprint"] == "a" * 64
- assert pending["selection"] == {"profile_id": "profile-1", "model_id": "model-1"}
+ assert response.json()["task_id"] is None
+ assert "pending_indexing_policy" not in manager.config["knowledge_bases"]["kb-pending"]
assert not list((manager.base_dir / "kb-pending").glob("version-*"))
@@ -2359,7 +2349,9 @@ def test_create_rejects_indexing_selection_for_other_provider_before_registratio
assert manager.config["knowledge_bases"] == {}
-def test_empty_lightrag_kb_can_update_pending_indexing_policy(monkeypatch, tmp_path: Path) -> None:
+def test_empty_lightrag_kb_rejects_obsolete_pending_model_edits(
+ monkeypatch, tmp_path: Path
+) -> None:
manager = _FakeKBManager(tmp_path / "knowledge_bases")
manager.config["knowledge_bases"]["empty"] = {
"rag_provider": "lightrag",
@@ -2398,9 +2390,9 @@ def test_empty_lightrag_kb_can_update_pending_indexing_policy(monkeypatch, tmp_p
},
)
- assert response.status_code == 200
- assert response.json()["indexing_policy"] == policy
- assert manager.config["knowledge_bases"]["empty"]["pending_indexing_policy"] == policy
+ assert response.status_code == 409
+ assert "Settings" in response.json()["detail"]
+ assert "pending_indexing_policy" not in manager.config["knowledge_bases"]["empty"]
@pytest.mark.parametrize("reason", ["published", "documents", "active"])
@@ -2457,15 +2449,14 @@ def test_reindex_passes_frozen_lightrag_snapshot_to_background_task(
monkeypatch.setattr(knowledge_router_module, "_assert_provider_ready", lambda _provider: None)
monkeypatch.setattr(
knowledge_router_module,
- "_freeze_indexing_llm_form",
- lambda _raw: ({"profile_id": "profile-1", "model_id": "model-1"}, snapshot),
+ "_freeze_default_indexing_llm",
+ lambda: snapshot,
)
monkeypatch.setattr(knowledge_router_module, "run_reindex_task", capture_task)
with TestClient(_build_app()) as client:
response = client.post(
"/api/knowledge-bases/kb/reindex",
- data={"indexing_llm": json.dumps({"profile_id": "profile-1", "model_id": "model-1"})},
)
assert response.status_code == 200
@@ -2834,3 +2825,25 @@ def test_lightrag_role_settings_validate_before_save(monkeypatch, tmp_path):
):
assert client.put(url, json=invalid).status_code == 422
assert client.get(url).json() == before
+
+
+def test_lightrag_retry_requires_confirmed_rebuild(monkeypatch, tmp_path: Path) -> None:
+ manager = _FakeKBManager(tmp_path / "knowledge_bases")
+ manager.config["knowledge_bases"]["failed-kb"] = {
+ "path": "failed-kb",
+ "status": "error",
+ "rag_provider": "lightrag",
+ }
+ monkeypatch.setattr(knowledge_router_module, "get_kb_manager", lambda: manager)
+ calls = []
+
+ async def reindex(*args, **kwargs):
+ calls.append((args, kwargs))
+
+ monkeypatch.setattr(knowledge_router_module, "reindex_knowledge_base", reindex)
+ with TestClient(_build_app()) as client:
+ response = client.post("/api/knowledge-bases/failed-kb/retry")
+ assert response.status_code == 409
+ assert "confirm" in response.json()["detail"]
+ assert calls == []
+ assert manager.config["knowledge_bases"]["failed-kb"]["status"] == "error"
diff --git a/tests/knowledge/test_document_adder_provider.py b/tests/knowledge/test_document_adder_provider.py
index f16e5e4b2..ed8fab710 100644
--- a/tests/knowledge/test_document_adder_provider.py
+++ b/tests/knowledge/test_document_adder_provider.py
@@ -98,6 +98,14 @@ def test_document_adder_allows_empty_lightrag_kb_to_bootstrap(monkeypatch, tmp_p
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(
diff --git a/tests/services/rag/test_lightrag_pipeline.py b/tests/services/rag/test_lightrag_pipeline.py
index aa1a3f210..496992c37 100644
--- a/tests/services/rag/test_lightrag_pipeline.py
+++ b/tests/services/rag/test_lightrag_pipeline.py
@@ -16,8 +16,10 @@ from deeptutor.multi_user.context import (
set_current_user,
)
from deeptutor.multi_user.models import CurrentUser, UserScope
+from deeptutor.services.embedding.config import EmbeddingConfig
from deeptutor.services.llm.exceptions import LLMAPIError, LLMAuthenticationError
from deeptutor.services.parsing.types import ParsedDocument
+from deeptutor.services.rag.embedding_signature import signature_from_config
from deeptutor.services.rag.factory import get_pipeline, list_pipelines, normalize_provider_name
from deeptutor.services.rag.index_versioning import list_kb_versions
from deeptutor.services.rag.pipelines.lightrag import config, engine, indexing_policy, storage
@@ -67,6 +69,9 @@ def _isolate_role_revalidation(monkeypatch):
def _indexing_snapshot():
return types.SimpleNamespace(
+ embedding_config=EmbeddingConfig(
+ model="embed-one", api_key="fake", dim=3, base_url="https://embed.test/v1"
+ ),
vision_available=True,
image_analysis=None,
target_bound=False,
@@ -141,6 +146,8 @@ def test_query_model_resolver_falls_back_only_when_selected_entry_is_missing(
fallback = object()
calls: list[object] = []
monkeypatch.setattr(config, "lightrag_llm_selection_from_settings", lambda: selection)
+ active = {"profile_id": "active-profile", "model_id": "active-model"}
+ monkeypatch.setattr(indexing_policy, "_active_catalog_selection", lambda: active)
def resolve(value):
calls.append(value)
@@ -154,7 +161,7 @@ def test_query_model_resolver_falls_back_only_when_selected_entry_is_missing(
)
assert config.resolve_lightrag_query_llm_config() is fallback
- assert calls == [selection, indexing_policy._active_catalog_selection()]
+ assert calls == [selection, active]
def test_lightrag_llm_adapter_uses_explicit_snapshot_config(monkeypatch) -> None:
@@ -694,6 +701,9 @@ 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_signature": signature_from_config(
+ _indexing_snapshot().embedding_config
+ ).hash(),
}
),
encoding="utf-8",
@@ -846,7 +856,7 @@ def test_append_rejects_explicit_indexing_snapshot_before_mutation(
)
-def test_pending_policy_drift_fails_before_creating_a_version(tmp_path: Path, monkeypatch) -> None:
+def test_first_index_uses_defaults_instead_of_creation_time_pending_policy(tmp_path, monkeypatch):
kb_dir = tmp_path / "kb"
kb_dir.mkdir()
(tmp_path / "kb_config.json").write_text(
@@ -854,29 +864,35 @@ def test_pending_policy_drift_fails_before_creating_a_version(tmp_path: Path, mo
{
"knowledge_bases": {
"kb": {
- "path": "kb",
"pending_indexing_policy": {
"policy": "pending_pinned",
- "selection": {"profile_id": "profile", "model_id": "model"},
- "fingerprint": "a" * 64,
+ "fingerprint": "stale",
},
}
}
}
- ),
- encoding="utf-8",
+ )
)
pipeline = LightRagPipeline(kb_base_dir=str(tmp_path))
monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)
+ snapshot = _indexing_snapshot()
+ monkeypatch.setattr(
+ "deeptutor.services.rag.pipelines.lightrag.pipeline.freeze_default_snapshot",
+ lambda: snapshot,
+ )
+ monkeypatch.setattr(
+ indexing_policy,
+ "snapshot_from_persisted",
+ lambda _: pytest.fail("restored old empty policy"),
+ )
- def changed(_policy):
- raise indexing_policy.IndexingModelChangedError("reindex required")
-
- monkeypatch.setattr(indexing_policy, "snapshot_from_persisted", changed)
+ async def check_defaults(_root, _files, _progress, accepted):
+ assert accepted is snapshot
+ raise RuntimeError("checked defaults before provider call")
- with pytest.raises(indexing_policy.IndexingModelChangedError):
+ monkeypatch.setattr(pipeline, "_run_indexing", check_defaults)
+ with pytest.raises(RuntimeError, match="checked defaults"):
asyncio.run(pipeline.initialize("kb", [str(tmp_path / "doc.md")]))
-
assert not any(kb_dir.glob("version-*"))
@@ -1271,6 +1287,7 @@ def test_public_initial_ingestion_retains_uncertain_ingress(
"kb",
[str(source)],
indexing_snapshot=types.SimpleNamespace(
+ embedding_config=_indexing_snapshot().embedding_config,
vision_available=True,
image_analysis=None,
target_bound=False,
diff --git a/tests/services/rag/test_lightrag_roles.py b/tests/services/rag/test_lightrag_roles.py
index 64a266d64..56f0d8218 100644
--- a/tests/services/rag/test_lightrag_roles.py
+++ b/tests/services/rag/test_lightrag_roles.py
@@ -15,8 +15,10 @@ 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
@@ -72,6 +74,9 @@ def role_environment(tmp_path, monkeypatch):
}
)
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": {
@@ -133,6 +138,9 @@ def role_environment(tmp_path, monkeypatch):
policy, "supports_vision", lambda _binding, model: state["vision"].get(model, False)
)
monkeypatch.setattr(policy, "_active_catalog_selection", lambda: choice(0))
+ monkeypatch.setattr(
+ "deeptutor.services.embedding.get_embedding_config", lambda: state["embedding"]
+ )
yield state
reset_current_user(token)
@@ -331,6 +339,7 @@ def _published(path: Path, value: dict):
"parser_bridge_schema": 1,
"state": "published",
"indexing_policy": value,
+ **embedding_meta_fields(),
}
)
)
@@ -491,7 +500,9 @@ def test_concurrent_first_writers_do_not_publish_different_policies(
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: _published(root, indexing_policy)
+ storage,
+ "write_meta",
+ lambda root, *, indexing_policy, embedding_config: _published(root, indexing_policy),
)
async def exercise():
@@ -838,3 +849,148 @@ def test_provider_auto_omits_actual_reasoning_request_fields(role_environment, b
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
+):
+ 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)
+
+
+def test_rebuild_confirmation_rejects_changed_defaults_without_queueing(
+ role_environment, tmp_path, monkeypatch
+):
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from deeptutor.api.routers import knowledge
+
+ entry = {"rag_provider": "lightrag", "status": "ready"}
+ 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:
+ 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_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
+):
+ 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 --git a/tests/services/rag/test_lightrag_settings_wiring.py b/tests/services/rag/test_lightrag_settings_wiring.py
index 22c011ce8..2230bc5df 100644
--- a/tests/services/rag/test_lightrag_settings_wiring.py
+++ b/tests/services/rag/test_lightrag_settings_wiring.py
@@ -113,7 +113,7 @@ def test_vlm_role_is_only_configured_when_enabled(monkeypatch, tmp_path: Path) -
lambda _snapshot: "snapshot-fingerprint",
)
- pair = types.SimpleNamespace(extract=snapshot, vlm=snapshot, limits={})
+ pair = types.SimpleNamespace(extract=snapshot, vlm=snapshot, limits={}, embedding_config=None)
rag = engine.build_rag(tmp_path, enable_vlm=True, indexing_snapshot=pair)
role = rag.kwargs["role_llm_configs"]["vlm"]
@@ -150,7 +150,7 @@ def test_indexing_uses_frozen_roles_without_resolving_query_models(
lambda _snapshot: "snapshot-fingerprint",
)
- pair = types.SimpleNamespace(extract=snapshot, vlm=snapshot, limits={})
+ pair = types.SimpleNamespace(extract=snapshot, vlm=snapshot, limits={}, embedding_config=None)
rag = engine.build_rag(tmp_path, enable_vlm=True, indexing_snapshot=pair)
assert "llm_config" in llm_calls[0]
diff --git a/web/components/knowledge/CreateKbModal.tsx b/web/components/knowledge/CreateKbModal.tsx
index c5855bf24..f0d088dd3 100644
--- a/web/components/knowledge/CreateKbModal.tsx
+++ b/web/components/knowledge/CreateKbModal.tsx
@@ -31,7 +31,6 @@ import {
probeLinkedFolder,
probeWeKnora,
type KnowledgeUploadPolicy,
- type LightRagIndexingSelection,
type LinkedFolderProbe,
type RagProviderSummary,
type WeKnoraProbe,
@@ -48,10 +47,11 @@ import {
import FileDropZone from "./FileDropZone";
import ImaConnectionFields from "./ImaConnectionFields";
import KnowledgeEngineIcon from "./KnowledgeEngineIcon";
-import LightRagIndexingSelector, {
+import {
indexingSelectionFromDefaults,
isCompleteIndexingSelection,
} from "./LightRagIndexingSelector";
+import { resolvedRole } from "./LightRagRoleModelsEditor";
const OBSIDIAN_SOURCE = "obsidian";
const MARGINNOTE4_SOURCE = "marginnote4";
@@ -74,7 +74,6 @@ interface CreateKbModalProps {
files: File[];
pageindexMode?: "flash" | "standard";
searchMode?: string;
- indexingLLM?: LightRagIndexingSelection;
}) => Promise<void>;
/** Link a pre-built engine index folder in place (no copy, no re-index). */
onConnectLinkedFolder: (params: {
@@ -166,8 +165,6 @@ export default function CreateKbModal({
const [weKnoraProbe, setWeKnoraProbe] = useState<WeKnoraProbe | null>(null);
const [weKnoraProbing, setWeKnoraProbing] = useState(false);
const [submitting, setSubmitting] = useState(false);
- const [indexingLLM, setIndexingLLM] =
- useState<LightRagIndexingSelection | null>(null);
const [lightRagConfig, setLightRagConfig] = useState<Awaited<
ReturnType<typeof getLightRagConfig>
> | null>(null);
@@ -191,27 +188,53 @@ export default function CreateKbModal({
llmCatalog.activeDefault,
)
: null;
- const lightRagModelName = (value?: {
- profile_id: string;
- model_id: string;
- }) =>
- llmCatalog.options.find(
- (option) =>
- option.profile_id === value?.profile_id &&
- option.model_id === value?.model_id,
- )?.model_name ?? value?.model_id;
+ const lightRagModelLabel = (
+ value?: {
+ profile_id: string;
+ model_id: string;
+ reasoning_effort?: string;
+ } | null,
+ ) => {
+ if (!value) return t("Disabled");
+ const option = llmCatalog.options.find(
+ (item) =>
+ item.profile_id === value.profile_id &&
+ item.model_id === value.model_id,
+ );
+ return `${option?.model_name ?? value.model_id} · ${value.reasoning_effort || t("Auto")}`;
+ };
const visibleEngineDefaultSummary =
provider === "lightrag" && lightRagIndexingDefaults
? [
...engineDefaultSummary,
- `EXTRACT: ${lightRagModelName(lightRagIndexingDefaults.extract)}`,
- `VLM: ${
- lightRagIndexingDefaults.vlm.mode === "enabled"
- ? lightRagModelName(lightRagIndexingDefaults.vlm.selection)
- : t("Image analysis disabled")
- }`,
+ ...(["query", "keyword", "extract", "vlm"] as const).map((role) => {
+ const value = lightRagConfig?.role_models
+ ? resolvedRole(lightRagConfig.role_models, role)
+ : role === "vlm"
+ ? lightRagIndexingDefaults.vlm.selection
+ : lightRagIndexingDefaults.extract;
+ return `${role.toUpperCase()}: ${lightRagModelLabel(value)}`;
+ }),
]
: engineDefaultSummary;
+ const [defaultsRevision, setDefaultsRevision] = useState(0);
+ const refreshCatalog = llmCatalog.refresh;
+
+ useEffect(() => {
+ if (!isOpen) return;
+ const refresh = () => setDefaultsRevision((value) => value + 1);
+ const onVisible = () => {
+ if (document.visibilityState === "visible") refresh();
+ };
+ window.addEventListener("focus", refresh);
+ window.addEventListener("pageshow", refresh);
+ document.addEventListener("visibilitychange", onVisible);
+ return () => {
+ window.removeEventListener("focus", refresh);
+ window.removeEventListener("pageshow", refresh);
+ document.removeEventListener("visibilitychange", onVisible);
+ };
+ }, [isOpen]);
const firstLinkable = providers.find((p) => p.linkable)?.id;
@@ -262,44 +285,19 @@ export default function CreateKbModal({
setWeKnoraKnowledgeBaseId("");
setWeKnoraProbe(null);
setWeKnoraProbing(false);
- setIndexingLLM(null);
setLightRagConfig(null);
setLightRagConfigLoaded(false);
setLightRagConfigError(false);
}, [isOpen, providers, firstLinkable, initialMode, initialSource]);
- useEffect(() => {
- if (
- !isOpen ||
- mode !== "new" ||
- provider !== "lightrag" ||
- indexingLLM ||
- !lightRagConfigLoaded ||
- !lightRagConfig
- ) {
- return;
- }
- setIndexingLLM(
- indexingSelectionFromDefaults(
- llmCatalog.options,
- lightRagConfig,
- llmCatalog.activeDefault,
- ),
- );
- }, [
- indexingLLM,
- isOpen,
- llmCatalog.activeDefault,
- llmCatalog.options,
- lightRagConfig,
- lightRagConfigLoaded,
- mode,
- provider,
- ]);
-
useEffect(() => {
if (!isOpen || mode !== "new") return;
let cancelled = false;
+ if (provider === "lightrag") {
+ setLightRagConfig(null);
+ setLightRagConfigLoaded(false);
+ void refreshCatalog({ force: true });
+ }
const load = async () => {
try {
@@ -318,7 +316,7 @@ export default function CreateKbModal({
`${t("Community level")}: ${config.community_level}`,
];
} else if (provider === "lightrag") {
- const config = await getLightRagConfig();
+ const config = await getLightRagConfig({ force: true });
if (!cancelled) {
setLightRagConfig(config);
setLightRagConfigLoaded(true);
@@ -365,7 +363,7 @@ export default function CreateKbModal({
return () => {
cancelled = true;
};
- }, [isOpen, mode, provider, t]);
+ }, [isOpen, mode, provider, t, defaultsRevision, refreshCatalog]);
// A fresh path / source invalidates a stale probe verdict.
useEffect(() => {
@@ -421,7 +419,14 @@ export default function CreateKbModal({
}
if (
provider === "lightrag" &&
- !isCompleteIndexingSelection(indexingLLM, llmCatalog.options)
+ (!lightRagConfigLoaded ||
+ lightRagConfigError ||
+ llmCatalog.loading ||
+ llmCatalog.error ||
+ !isCompleteIndexingSelection(
+ lightRagIndexingDefaults,
+ llmCatalog.options,
+ ))
)
return false;
return !providerUnavailable;
@@ -525,8 +530,6 @@ export default function CreateKbModal({
pageindexMode:
isPageIndexOSS && pageIndexMode ? pageIndexMode : undefined,
searchMode: retrievalMode || undefined,
- indexingLLM:
- provider === "lightrag" ? indexingLLM || undefined : undefined,
});
}
} else if (linkIsIma) {
@@ -648,26 +651,20 @@ export default function CreateKbModal({
setFiles={setFiles}
policyForProvider={policyForProvider}
indexingModelField={
- provider === "lightrag" ? (
- <LightRagIndexingSelector
- options={llmCatalog.options}
- selection={indexingLLM}
- defaults={lightRagIndexingDefaults}
- collapsible
- 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
}
connectionForm={
@@ -988,9 +985,7 @@ function NewModeFields({
</div>
)}
- {indexingModelField && (
- <div>{indexingModelField}</div>
- )}
+ {indexingModelField && <div>{indexingModelField}</div>}
{modeOptions.length > 0 && (
<div>
diff --git a/web/components/knowledge/KbDocumentsSection.tsx b/web/components/knowledge/KbDocumentsSection.tsx
index 516061135..3a6be1373 100644
--- a/web/components/knowledge/KbDocumentsSection.tsx
+++ b/web/components/knowledge/KbDocumentsSection.tsx
@@ -108,22 +108,26 @@ export default function KbDocumentsSection({
const blockedReason = canUpload
? null
- : requiresLightRagRebuild
- ? t(
- "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.",
- )
- : needsReindex
+ : kb.metadata?.indexing_model_unavailable
? t(
- "This knowledge base is in legacy index format and needs reindex before upload.",
+ "Restore access to the pinned indexing models in Settings before adding documents.",
)
- : status !== "ready"
+ : requiresLightRagRebuild
? t(
- "This knowledge base is currently {{status}} and cannot accept uploads yet.",
- {
- status: status.replaceAll("_", " "),
- },
+ "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.",
)
- : null;
+ : needsReindex
+ ? t(
+ "This knowledge base is in legacy index format and needs reindex before upload.",
+ )
+ : status !== "ready"
+ ? t(
+ "This knowledge base is currently {{status}} and cannot accept uploads yet.",
+ {
+ status: status.replaceAll("_", " "),
+ },
+ )
+ : null;
const selection = validateFiles(files, policyForProvider, t);
const canRetry = Boolean(onRetry) && isError && !isIndexingHere;
@@ -186,7 +190,7 @@ export default function KbDocumentsSection({
</p>
</div>
- {provider === "lightrag" && (
+ {provider === "lightrag" && publishedLightRagVersion && (
<LightRagIndexingProvenance
policy={kb.metadata?.indexing_policy}
version={publishedLightRagVersion}
@@ -218,7 +222,11 @@ export default function KbDocumentsSection({
)}
{retrySubmitting || isRetryingHere
? t("Retrying…")
- : t("Retry indexing")}
+ : t(
+ provider === "lightrag"
+ ? "Review rebuild"
+ : "Retry indexing",
+ )}
</button>
) : undefined
}
diff --git a/web/components/knowledge/KbIndexVersionsSection.tsx b/web/components/knowledge/KbIndexVersionsSection.tsx
index 9bd7ea41e..aa952fe6b 100644
--- a/web/components/knowledge/KbIndexVersionsSection.tsx
+++ b/web/components/knowledge/KbIndexVersionsSection.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useState } from "react";
+import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
AlertTriangle,
@@ -15,80 +15,42 @@ import {
currentLightRagBuildCandidate,
formatKnowledgeTimestamp,
kbCanReindex,
- kbHasLiveProgress,
kbNeedsReindex,
lightRagVersionDisplayState,
providerUsesEmbeddingMetadata,
resolveKbStatus,
resolveProgressPercent,
type IndexVersion,
- type LightRagIndexingPolicy,
type 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,
- getLightRagModelOptions,
-} from "@/features/knowledge/api/engines";
-import type { LLMOption } from "@/lib/llm-options";
-import type {
- LightRagIndexingSelection,
- LightRagConfig,
-} from "@/features/knowledge/model/types";
+ getReindexConfig,
+ type LightRagRebuildConfig,
+} from "@/features/knowledge/api/catalog";
import KbIndexFailureBanner from "./KbIndexFailureBanner";
-import LightRagIndexingSelector, {
- indexingSelectionFromDefaults,
- isCompleteIndexingSelection,
- indexingSelectionFromPolicy,
-} from "./LightRagIndexingSelector";
import LightRagIndexingProvenance from "./LightRagIndexingProvenance";
-export function selectionForLightRagModelDialog(
- options: LLMOption[],
- config: Pick<
- LightRagConfig,
- "llm_profile_id" | "llm_model_id" | "role_models"
- >,
- activeDefault: import("@/lib/llm-options").LLMOptionsResponse["active"],
- savedPending: LightRagIndexingPolicy | undefined,
- preserveSavedPending: boolean,
-): LightRagIndexingSelection | null {
- return (
- (preserveSavedPending ? indexingSelectionFromPolicy(savedPending) : null) ??
- indexingSelectionFromDefaults(options, config, activeDefault)
- );
-}
-
interface KbIndexVersionsSectionProps {
kb: KnowledgeBase;
task?: TaskState;
- onReindex: (indexingLLM?: LightRagIndexingSelection) => Promise<void>;
- onUpdatePendingIndexingPolicy: (
- indexingLLM: LightRagIndexingSelection,
- ) => Promise<void>;
+ onReindex: (configFingerprint?: string) => Promise<void>;
}
export default function KbIndexVersionsSection({
kb,
task,
onReindex,
- onUpdatePendingIndexingPolicy,
}: KbIndexVersionsSectionProps) {
const { t } = useTranslation();
const [submitting, setSubmitting] = useState(false);
const [modelDialogOpen, setModelDialogOpen] = useState(false);
- const [indexingLLM, setIndexingLLM] =
- useState<LightRagIndexingSelection | 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(getLightRagModelOptions);
+ const [configLoading, setConfigLoading] = useState(false);
const provider = kb.statistics?.rag_provider || "llamaindex";
const isLightRag = provider === "lightrag";
const pageIndexProvider = !providerUsesEmbeddingMetadata(provider);
@@ -114,68 +76,23 @@ export default function KbIndexVersionsSection({
const buildingLightRagVersion = isLightRag
? currentLightRagBuildCandidate(versions, Boolean(isReindexingHere))
: undefined;
- const emptyPendingEligible =
- isLightRag &&
- !kb.read_only &&
- kb.statistics?.raw_documents === 0 &&
- !publishedLightRagVersion &&
- !kbHasLiveProgress(kb) &&
- !task?.executing;
-
- useEffect(() => {
- if (!isLightRag) return;
- let cancelled = false;
- void getLightRagConfig()
- .then((config) => {
- if (!cancelled) {
- setLightRagConfig(config);
- setLightRagConfigError(false);
- }
- })
- .catch(() => {
- if (!cancelled) setLightRagConfigError(true);
- })
- .finally(() => {
- if (!cancelled) setLightRagConfigLoaded(true);
- });
- 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,
- emptyPendingEligible,
- ),
- );
- }, [
- emptyPendingEligible,
- indexingLLM,
- kb.metadata?.indexing_policy,
- llmCatalog.activeDefault,
- llmCatalog.options,
- lightRagConfig,
- lightRagConfigLoaded,
- modelDialogOpen,
- ]);
-
- const openModelDialog = () => {
- setIndexingLLM(null);
- setDialogError(null);
- setModelDialogOpen(true);
+ const loadRebuildConfig = async () => {
+ setRebuildConfig(null);
+ setConfigLoading(true);
+ try {
+ setRebuildConfig(await getReindexConfig(kb.name));
+ } catch (error) {
+ setDialogError(error instanceof Error ? error.message : String(error));
+ } finally {
+ setConfigLoading(false);
+ }
};
const handleReindex = async () => {
if (isLightRag) {
- openModelDialog();
+ setDialogError(null);
+ setModelDialogOpen(true);
+ await loadRebuildConfig();
return;
}
setSubmitting(true);
@@ -187,18 +104,15 @@ export default function KbIndexVersionsSection({
};
const handleModelSubmit = async () => {
- if (!isCompleteIndexingSelection(indexingLLM, llmCatalog.options)) return;
+ if (!rebuildConfig) return;
setSubmitting(true);
setDialogError(null);
try {
- if (emptyPendingEligible) {
- await onUpdatePendingIndexingPolicy(indexingLLM);
- } else {
- await onReindex(indexingLLM);
- }
+ await onReindex(rebuildConfig.fingerprint);
setModelDialogOpen(false);
} catch (error) {
setDialogError(error instanceof Error ? error.message : String(error));
+ await loadRebuildConfig();
} finally {
setSubmitting(false);
}
@@ -230,7 +144,7 @@ export default function KbIndexVersionsSection({
</div>
</div>
- {(showReindexCta || emptyPendingEligible) && (
+ {showReindexCta && (
<button
type="button"
onClick={handleReindex}
@@ -242,7 +156,7 @@ export default function KbIndexVersionsSection({
)
: 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.",
@@ -259,35 +173,47 @@ export default function KbIndexVersionsSection({
) : (
<RefreshCw className="h-3 w-3" />
)}
- {emptyPendingEligible
- ? t("Change model")
- : isReindexingHere
- ? isError
- ? t("Retrying…")
- : t("Re-indexing…")
- : isError
- ? t("Retry indexing")
- : t("Re-index")}
+ {isReindexingHere
+ ? isError
+ ? t("Retrying…")
+ : t("Re-indexing…")
+ : isError
+ ? t("Retry indexing")
+ : t("Re-index")}
</button>
)}
</div>
{isError && <KbIndexFailureBanner kb={kb} />}
- {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 && (
<LightRagIndexingProvenance
policy={kb.metadata?.indexing_policy}
version={publishedLightRagVersion}
/>
)}
- {!modelInsensitiveProvider && !isError && (needsReindex || mismatch) && (
- <div 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 active embedding configuration doesn't match any ready index version. Re-index to rebuild against the current embedding model.",
- )}
- </div>
- )}
+ {!pageIndexProvider &&
+ !isLightRag &&
+ !isError &&
+ (needsReindex || mismatch) && (
+ <div 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 active embedding configuration doesn't match any ready index version. Re-index to rebuild against the current embedding model.",
+ )}
+ </div>
+ )}
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 rounded-lg border border-[var(--border)] bg-[var(--muted)]/30 px-3 py-2 text-[11.5px] text-[var(--muted-foreground)]">
<Clock className="h-3.5 w-3.5 shrink-0" />
@@ -317,6 +243,7 @@ export default function KbIndexVersionsSection({
{versions.map((version) => (
<IndexVersionRow
key={
+ version.version ??
version.signature ??
`${version.model}-${version.dimension}-${version.created_at}`
}
@@ -380,11 +307,7 @@ export default function KbIndexVersionsSection({
<Modal
isOpen={modelDialogOpen}
onClose={() => !submitting && setModelDialogOpen(false)}
- title={
- emptyPendingEligible
- ? t("Change pending indexing model")
- : t("Re-index with a pinned model")
- }
+ title={t("Rebuild index with current defaults")}
width="sm"
footer={
<div className="flex justify-end gap-2">
@@ -399,49 +322,37 @@ export default function KbIndexVersionsSection({
<button
type="button"
onClick={() => void handleModelSubmit()}
- disabled={
- submitting ||
- !isCompleteIndexingSelection(indexingLLM, llmCatalog.options)
- }
+ disabled={submitting || configLoading || !rebuildConfig}
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" />}
- {emptyPendingEligible
- ? t("Save model")
- : t("Start full re-index")}
+ {t("Confirm rebuild")}
</button>
</div>
}
>
<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.",
- )}
+ {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.",
+ )}
</p>
- <LightRagIndexingSelector
- 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}
- />
+ {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 && (
<div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">
- {dialogError}
+ {t(dialogError)}
</div>
)}
</div>
@@ -486,15 +397,8 @@ function IndexVersionRow({
const isFailedLightRagCandidate = lightRagState === "failed";
const isBuildingLightRagCandidate = lightRagState === "building";
- const title = isFailedLightRagCandidate
- ? t("Failed rebuild candidate")
- : isBuildingLightRagCandidate
- ? t("Rebuild candidate in progress")
- : isLegacy
- ? t("Legacy index")
- : version.model
- ? version.model
- : (version.signature ?? t("Unknown"));
+ const title =
+ version.version || (isLegacy ? t("Legacy index") : t("Unknown"));
const created = formatKnowledgeTimestamp(version.created_at);
@@ -586,6 +490,19 @@ function IndexVersionRow({
</span>
)}
</div>
+ {isLightRagVersion &&
+ !isPublishedLightRag &&
+ version.indexing_policy && (
+ <details className="mt-2 text-[11px]">
+ <summary className="cursor-pointer text-[var(--muted-foreground)]">
+ {t("Index configuration")}
+ </summary>
+ <LightRagIndexingProvenance
+ policy={version.indexing_policy}
+ version={version}
+ />
+ </details>
+ )}
</div>
</li>
);
diff --git a/web/components/knowledge/KbSettingsSection.tsx b/web/components/knowledge/KbSettingsSection.tsx
index 659073c2f..c1b191fce 100644
--- a/web/components/knowledge/KbSettingsSection.tsx
+++ b/web/components/knowledge/KbSettingsSection.tsx
@@ -8,7 +8,6 @@ import {
providerUsesEmbeddingMetadata,
type KnowledgeBase,
} from "@/lib/knowledge-helpers";
-import LightRagIndexingProvenance from "./LightRagIndexingProvenance";
interface KbSettingsSectionProps {
kb: KnowledgeBase;
@@ -40,12 +39,6 @@ export default function KbSettingsSection({
const created = formatKnowledgeTimestamp(meta.created_at);
const updated = formatKnowledgeTimestamp(meta.last_updated);
const lastIndexed = formatKnowledgeTimestamp(meta.last_indexed_at);
- const publishedLightRagVersion =
- provider === "lightrag"
- ? kb.statistics?.index_versions?.find(
- (version) => version.provider === "lightrag" && version.ready,
- )
- : undefined;
return (
<div className="space-y-6">
@@ -87,18 +80,6 @@ export default function KbSettingsSection({
</dl>
</section>
- {provider === "lightrag" && (
- <section className="space-y-3">
- <div className="text-[13px] font-medium text-[var(--foreground)]">
- {t("Indexing model provenance")}
- </div>
- <LightRagIndexingProvenance
- policy={meta.indexing_policy}
- version={publishedLightRagVersion}
- />
- </section>
- )}
-
<section className="space-y-3 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">
<div>
<div className="text-[12.5px] font-medium text-[var(--foreground)]">
diff --git a/web/components/knowledge/KnowledgeBaseDetail.tsx b/web/components/knowledge/KnowledgeBaseDetail.tsx
index ff091c3dd..e6e68bf3c 100644
--- a/web/components/knowledge/KnowledgeBaseDetail.tsx
+++ b/web/components/knowledge/KnowledgeBaseDetail.tsx
@@ -16,10 +16,7 @@ import {
Star,
Upload,
} from "lucide-react";
-import type {
- LightRagIndexingSelection,
- KnowledgeUploadPolicy,
-} from "@/features/knowledge/model/types";
+import type { KnowledgeUploadPolicy } from "@/features/knowledge/model/types";
import {
formatKnowledgeTimestamp,
isMarginNoteKb,
@@ -55,14 +52,7 @@ interface KnowledgeBaseDetailProps {
files: File[],
destSubdir?: string,
) => Promise<void>;
- onReindex: (
- kbName: string,
- indexingLLM?: LightRagIndexingSelection,
- ) => Promise<void>;
- onUpdatePendingIndexingPolicy: (
- kbName: string,
- indexingLLM: LightRagIndexingSelection,
- ) => Promise<void>;
+ onReindex: (kbName: string, configFingerprint?: string) => Promise<void>;
onRetry: (kbName: string) => Promise<void>;
onSetDefault: (kbName: string) => Promise<void>;
onDelete: (kbName: string) => Promise<void>;
@@ -94,7 +84,6 @@ export default function KnowledgeBaseDetail({
onCreate,
onUpload,
onReindex,
- onUpdatePendingIndexingPolicy,
onRetry,
onSetDefault,
onDelete,
@@ -159,6 +148,10 @@ export default function KnowledgeBaseDetail({
const handleRetry = async () => {
if (!canRetry || retrySubmitting || isReindexingLocally) return;
+ if (kbProvider(kb) === "lightrag") {
+ setSection("versions");
+ return;
+ }
setRetrySubmitting(true);
try {
await onRetry(kb.name);
@@ -245,7 +238,11 @@ export default function KnowledgeBaseDetail({
)}
{retrySubmitting || isReindexingLocally
? t("Retrying…")
- : t("Retry indexing")}
+ : t(
+ kbProvider(kb) === "lightrag"
+ ? "Review rebuild"
+ : "Retry indexing",
+ )}
</button>
)}
</div>
@@ -300,17 +297,12 @@ export default function KnowledgeBaseDetail({
<KbIndexVersionsSection
kb={kb}
task={task}
- onReindex={(indexingLLM) =>
+ onReindex={(configFingerprint) =>
kb.read_only
? Promise.resolve()
: status === "error" && kbProvider(kb) !== "lightrag"
? handleRetry()
- : onReindex(kb.name, indexingLLM)
- }
- onUpdatePendingIndexingPolicy={(indexingLLM) =>
- kb.read_only
- ? Promise.resolve()
- : onUpdatePendingIndexingPolicy(kb.name, indexingLLM)
+ : onReindex(kb.name, configFingerprint)
}
/>
)}
diff --git a/web/components/knowledge/KnowledgePage.tsx b/web/components/knowledge/KnowledgePage.tsx
index 029f16a9b..c184aa4fb 100644
--- a/web/components/knowledge/KnowledgePage.tsx
+++ b/web/components/knowledge/KnowledgePage.tsx
@@ -12,7 +12,6 @@ import {
decodeResourceSegment,
knowledgeBaseRoute,
} from "@/lib/resource-routes";
-import type { LightRagIndexingSelection } from "@/features/knowledge/model/types";
const panelLoading = () => (
<div
@@ -64,7 +63,6 @@ export default function KnowledgePage() {
uploadFiles,
setDefault,
reindex,
- updatePendingIndexingPolicy,
retry,
deleteKb,
connectObsidian,
@@ -252,9 +250,9 @@ export default function KnowledgePage() {
);
const handleReindex = useCallback(
- async (kbName: string, indexingLLM?: LightRagIndexingSelection) => {
+ async (kbName: string, configFingerprint?: string) => {
try {
- await reindex(kbName, indexingLLM);
+ await reindex(kbName, configFingerprint);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
throw err;
@@ -263,18 +261,6 @@ export default function KnowledgePage() {
[reindex, setError],
);
- const handleUpdatePendingIndexingPolicy = useCallback(
- async (kbName: string, indexingLLM: LightRagIndexingSelection) => {
- try {
- await updatePendingIndexingPolicy(kbName, indexingLLM);
- } catch (err) {
- setError(err instanceof Error ? err.message : String(err));
- throw err;
- }
- },
- [setError, updatePendingIndexingPolicy],
- );
-
const handleRetry = useCallback(
async (kbName: string) => {
try {
@@ -373,7 +359,6 @@ export default function KnowledgePage() {
onCreate={openCreate}
onUpload={handleUpload}
onReindex={handleReindex}
- onUpdatePendingIndexingPolicy={handleUpdatePendingIndexingPolicy}
onRetry={handleRetry}
onSetDefault={handleSetDefault}
onDelete={handleDelete}
diff --git a/web/components/knowledge/LightRagIndexingProvenance.tsx b/web/components/knowledge/LightRagIndexingProvenance.tsx
index a808db874..2de7d90a0 100644
--- a/web/components/knowledge/LightRagIndexingProvenance.tsx
+++ b/web/components/knowledge/LightRagIndexingProvenance.tsx
@@ -1,27 +1,28 @@
"use client";
import { useTranslation } from "react-i18next";
-import {
- formatKnowledgeTimestamp,
- type IndexVersion,
- type LightRagIndexingPolicy,
+import type {
+ IndexVersion,
+ LightRagIndexingPolicy,
} from "@/lib/knowledge-helpers";
interface LightRagIndexingProvenanceProps {
policy?: LightRagIndexingPolicy;
version?: IndexVersion;
+ embedding?: { model: string; dimension: number };
+ title?: string;
compact?: boolean;
}
export default function LightRagIndexingProvenance({
policy,
version,
+ embedding,
+ title,
compact = false,
}: LightRagIndexingProvenanceProps) {
const { t } = useTranslation();
const resolved = policy ?? { policy: "legacy_unpinned" };
- const pending = resolved.policy === "pending_pinned";
- const pinned = resolved.policy === "pinned" || pending;
const extract = resolved.schema_version === 2 ? resolved.extract : resolved;
const visionEnabled =
resolved.schema_version === 2
@@ -33,92 +34,58 @@ export default function LightRagIndexingProvenance({
: resolved.vision_available;
const vision =
resolved.schema_version === 2 ? resolved.vlm?.snapshot : resolved;
- const visionLabel = [vision?.descriptor?.binding, vision?.descriptor?.model]
- .filter(Boolean)
- .join(" · ");
- const model = extract?.descriptor?.model;
- const binding = extract?.descriptor?.binding;
- const modelLabel = [binding, model].filter(Boolean).join(" · ");
- const effort = extract?.descriptor?.reasoning_effort;
- const title = pending
- ? t("Pending pinned indexing model")
- : pinned
- ? t("Pinned indexing model")
- : t("Legacy unpinned indexing model");
- const summary = pending
- ? t(
- "Takes effect on the first index. No index version has been published yet.",
- )
- : pinned
- ? t("Incremental indexing continues with this pinned model.")
- : t(
- "The historical indexing model is unknown. Queries remain available, but incremental uploads require a full rebuild.",
- );
+ const modelLabel = (value?: LightRagIndexingPolicy) => {
+ const name = [value?.descriptor?.binding, value?.descriptor?.model]
+ .filter(Boolean)
+ .join(" · ");
+ return name
+ ? `${name} · ${value?.descriptor?.reasoning_effort || t("Auto")}`
+ : t("Unverified historical indexing model");
+ };
+ const embeddingModel = embedding?.model ?? version?.embedding_model;
+ const dimension = embedding?.dimension ?? version?.embedding_dim;
+ const rows = [
+ ...(embeddingModel
+ ? [
+ [
+ t("Embedding"),
+ `${embeddingModel}${dimension ? ` · ${dimension}${t("d")}` : ""}`,
+ ],
+ ]
+ : []),
+ [t("EXTRACT model"), modelLabel(extract)],
+ [
+ t("VLM model"),
+ visionEnabled === true
+ ? modelLabel(vision)
+ : visionEnabled === false
+ ? t("Disabled")
+ : t("Unknown"),
+ ],
+ ];
return (
<div className="rounded-lg border border-[var(--border)] bg-[var(--muted)]/25 px-3 py-2.5">
<div className="text-[12px] font-medium text-[var(--foreground)]">
- {title}
+ {title || t("Index configuration")}
</div>
- <p className="mt-0.5 text-[11px] text-[var(--muted-foreground)]">
- {summary}
- </p>
- {visionEnabled === false && (
+ {resolved.policy === "legacy_unpinned" && (
<p className="mt-1 text-[11px] text-[var(--muted-foreground)]">
{t(
- "Image analysis is disabled. Enable a VLM through a full rebuild.",
+ "The historical indexing model is unknown. Queries remain available, but incremental uploads require a full rebuild.",
)}
</p>
)}
- {compact && (
- <p className="mt-1 text-[11px] font-medium text-[var(--foreground)]">
- {"EXTRACT: "}
- {modelLabel || t("Unverified historical indexing model")}
- {` · ${t("Reasoning effort")}: ${effort || t("Model default")}`}
- {` · VLM: ${visionEnabled === true ? visionLabel || t("Unknown") : visionEnabled === false ? t("Image analysis disabled") : t("Unknown")}`}
- </p>
- )}
- {!compact && (
- <dl className="mt-2 grid gap-x-4 gap-y-1 text-[11px] sm:grid-cols-2">
- <ProvenanceField label={t("EXTRACT model")}>
- {modelLabel || t("Unverified historical indexing model")}
- </ProvenanceField>
- <ProvenanceField label={t("Reasoning effort")}>
- {effort || t("Model default")}
- </ProvenanceField>
- <ProvenanceField label={t("VLM model")}>
- {visionEnabled === true
- ? visionLabel || t("Unknown")
- : visionEnabled === false
- ? t("Image analysis disabled")
- : t("Unknown")}
- {visionEnabled === true &&
- ` · ${t("Reasoning effort")}: ${vision?.descriptor?.reasoning_effort || t("Model default")}`}
- </ProvenanceField>
- <ProvenanceField label={t("Version source")}>
- {version?.version ||
- (pending ? t("Pending configuration") : t("Legacy metadata"))}
- {version?.created_at
- ? ` · ${formatKnowledgeTimestamp(version.created_at)}`
- : ""}
- </ProvenanceField>
- </dl>
- )}
- </div>
- );
-}
-
-function ProvenanceField({
- label,
- children,
-}: {
- label: string;
- children: React.ReactNode;
-}) {
- return (
- <div>
- <dt className="text-[var(--muted-foreground)]">{label}</dt>
- <dd className="break-words text-[var(--foreground)]">{children}</dd>
+ <dl
+ className={`mt-2 gap-1 text-[11px] ${compact ? "flex flex-wrap gap-x-4" : "grid"}`}
+ >
+ {rows.map(([label, value]) => (
+ <div key={label} className="flex gap-2">
+ <dt className="shrink-0 text-[var(--muted-foreground)]">{label}</dt>
+ <dd className="break-words text-[var(--foreground)]">{value}</dd>
+ </div>
+ ))}
+ </dl>
</div>
);
}
diff --git a/web/components/knowledge/LightRagIndexingSelector.tsx b/web/components/knowledge/LightRagIndexingSelector.tsx
index 89768e9e4..a404808b0 100644
--- a/web/components/knowledge/LightRagIndexingSelector.tsx
+++ b/web/components/knowledge/LightRagIndexingSelector.tsx
@@ -1,15 +1,11 @@
"use client";
-import { useTranslation } from "react-i18next";
import type {
LightRagConfig,
LightRagIndexingSelection,
} from "@/features/knowledge/model/types";
import type { LLMOption, LLMOptionsResponse } from "@/lib/llm-options";
-import type { LightRagIndexingPolicy } from "@/lib/knowledge-helpers";
-import IndexingModelSelector, {
- selectionFromLightRagDefault,
-} from "./IndexingModelSelector";
+import { selectionFromLightRagDefault } from "./IndexingModelSelector";
import { resolvedRole } from "./LightRagRoleModelsEditor";
export function indexingSelectionFromDefaults(
@@ -47,31 +43,6 @@ export function indexingSelectionFromDefaults(
};
}
-export function indexingSelectionFromPolicy(
- policy?: LightRagIndexingPolicy,
-): LightRagIndexingSelection | null {
- if (policy?.schema_version === 2 && policy.extract?.selection && policy.vlm) {
- const extract = policy.extract.selection;
- if (policy.vlm.mode === "disabled")
- return { extract, vlm: { mode: "disabled" } };
- if (policy.vlm.mode === "enabled" && policy.vlm.snapshot?.selection)
- return {
- extract,
- vlm: { mode: "enabled", selection: policy.vlm.snapshot.selection },
- };
- return null;
- }
- if (policy?.selection && typeof policy.vision_available === "boolean") {
- return {
- extract: policy.selection,
- vlm: policy.vision_available
- ? { mode: "enabled", selection: policy.selection }
- : { mode: "disabled" },
- };
- }
- return null;
-}
-
export function isCompleteIndexingSelection(
value: LightRagIndexingSelection | null,
options?: LLMOption[],
@@ -99,228 +70,3 @@ export function isCompleteIndexingSelection(
)
);
}
-
-export default function LightRagIndexingSelector({
- options,
- selection,
- defaults,
- collapsible = false,
- onChange,
- ...state
-}: {
- options: LLMOption[];
- selection: LightRagIndexingSelection | null;
- defaults?: LightRagIndexingSelection | null;
- collapsible?: boolean;
- onChange: (value: LightRagIndexingSelection | null) => void;
- loading: boolean;
- error: boolean;
- defaultUnavailable?: boolean;
- defaultLoadError?: boolean;
- disabled?: boolean;
-}) {
- const { t } = useTranslation();
- const optionFor = (value?: { profile_id: string; model_id: string }) =>
- options.find(
- (option) =>
- option.profile_id === value?.profile_id &&
- option.model_id === value?.model_id,
- );
- const optionName = (value?: { profile_id: string; model_id: string }) => {
- const option = optionFor(value);
- return option?.model_name ?? value?.model_id ?? t("Not selected");
- };
- const optionLabel = (value?: { profile_id: string; model_id: string }) => {
- const option = optionFor(value);
- return option
- ? `${option.provider_label || option.profile_name} · ${option.model_name}`
- : (value?.model_id ?? t("Not selected"));
- };
- const sameSelection = (
- left?: { profile_id: string; model_id: string; reasoning_effort?: string },
- right?: { profile_id: string; model_id: string; reasoning_effort?: string },
- ) =>
- Boolean(
- left &&
- right &&
- left.profile_id === right.profile_id &&
- left.model_id === right.model_id &&
- (left.reasoning_effort ?? "") === (right.reasoning_effort ?? ""),
- );
- const usesDefaultVlm = Boolean(
- selection &&
- defaults &&
- selection.vlm.mode === defaults.vlm.mode &&
- (selection.vlm.mode === "disabled" ||
- (defaults.vlm.mode === "enabled" &&
- sameSelection(selection.vlm.selection, defaults.vlm.selection))),
- );
- const vlmValue = usesDefaultVlm
- ? "__engine_default__"
- : selection?.vlm.mode === "enabled" && selection.vlm.selection
- ? `${selection.vlm.selection.profile_id}:${selection.vlm.selection.model_id}`
- : "disabled";
- const defaultVlmLabel =
- defaults?.vlm.mode === "enabled"
- ? optionLabel(defaults.vlm.selection)
- : t("Image analysis disabled");
- const hasUnavailableSelection = Boolean(
- selection &&
- isCompleteIndexingSelection(selection) &&
- !isCompleteIndexingSelection(selection, options),
- );
-
- const fields = (
- <div className="space-y-4">
- <p className="text-xs text-[var(--muted-foreground)]">
- {t(
- defaults
- ? "Engine model settings are used by default. The resolved models are pinned when this index is created."
- : "Prefilled from the engine's EXTRACT and VLM settings. Changes here apply only to this new or rebuilt index.",
- )}
- </p>
- <p className="text-[11px] leading-relaxed text-[var(--muted-foreground)]">
- {t(
- "Used to extract entities and relationships during indexing. Choose a fast, economical model with reasoning disabled.",
- )}
- </p>
- {hasUnavailableSelection && (
- <p className="text-xs text-red-600">
- {t(
- "One or more selected indexing models are unavailable. Choose accessible models before continuing.",
- )}
- </p>
- )}
- <IndexingModelSelector
- {...state}
- label="EXTRACT model"
- defaultSelection={defaults?.extract}
- defaultLabel={
- defaults
- ? `${t("Use engine default")} · ${optionLabel(defaults.extract)}`
- : undefined
- }
- options={options}
- selection={selection?.extract ?? null}
- onChange={(extract) =>
- onChange(
- extract
- ? { extract, vlm: selection?.vlm ?? { mode: "disabled" } }
- : null,
- )
- }
- />
- {selection && (
- <>
- <div className="space-y-1">
- <p className="text-[11px] leading-relaxed text-[var(--muted-foreground)]">
- {t(
- "Used to analyze images during indexing. The model must support image input.",
- )}
- </p>
- </div>
- <label className="block text-xs font-medium">
- {t("VLM image analysis")}
- <select
- aria-label={t("VLM image analysis")}
- value={vlmValue}
- disabled={state.disabled}
- onChange={(event) => {
- if (event.target.value === "__engine_default__" && defaults) {
- onChange({ ...selection, vlm: defaults.vlm });
- return;
- }
- if (event.target.value === "disabled") {
- onChange({ ...selection, vlm: { mode: "disabled" } });
- return;
- }
- const option = options.find(
- (item) =>
- `${item.profile_id}:${item.model_id}` === event.target.value,
- );
- if (!option) return;
- onChange({
- ...selection,
- vlm: {
- mode: "enabled",
- selection: {
- profile_id: option.profile_id,
- model_id: option.model_id,
- },
- },
- });
- }}
- className="mt-1 w-full rounded-lg border border-[var(--border)] bg-[var(--background)] p-2"
- >
- {defaults && (
- <option value="__engine_default__">
- {t("Use engine default")} · {defaultVlmLabel}
- </option>
- )}
- <option value="disabled">{t("Image analysis disabled")}</option>
- {options
- .filter((option) => option.supports_vision)
- .map((option) => (
- <option
- key={`${option.profile_id}:${option.model_id}`}
- value={`${option.profile_id}:${option.model_id}`}
- >
- {option.provider_label || option.profile_name} ·{" "}
- {option.model_name}
- </option>
- ))}
- </select>
- </label>
- {selection.vlm.mode === "enabled" && selection.vlm.selection && (
- <IndexingModelSelector
- {...state}
- reasoningOnly
- options={options.filter((option) => option.supports_vision)}
- selection={selection.vlm.selection}
- onChange={(vlm) =>
- onChange({
- ...selection,
- vlm: { mode: "enabled", ...(vlm ? { selection: vlm } : {}) },
- })
- }
- />
- )}
- <p className="text-xs text-[var(--muted-foreground)]">
- {t(
- defaults
- ? "After creation, changing EXTRACT or enabling, disabling, or replacing VLM requires a full rebuild."
- : "After publication, enabling, disabling or replacing VLM requires a full rebuild. A VLM pinned now can process later image uploads.",
- )}
- </p>
- </>
- )}
- </div>
- );
-
- if (!collapsible) return fields;
- const summary = selection
- ? `EXTRACT: ${optionName(selection.extract)} · VLM: ${
- selection.vlm.mode === "enabled"
- ? optionName(selection.vlm.selection)
- : t("Image analysis disabled")
- }`
- : t("Choose indexing models");
- return (
- <details
- className="rounded-xl border border-[var(--border)] bg-[var(--muted)]/20 p-3"
- open={
- state.error || state.defaultLoadError || !selection ? true : undefined
- }
- >
- <summary className="cursor-pointer list-none">
- <span className="block text-[12px] font-medium text-[var(--foreground)]">
- {t("Indexing models (optional override)")}
- </span>
- <span className="mt-1 block text-[11px] text-[var(--muted-foreground)]">
- {summary}
- </span>
- </summary>
- <div className="mt-4 border-t border-[var(--border)] pt-4">{fields}</div>
- </details>
- );
-}
diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.ts
index 261c4d343..97527c46c 100644
--- a/web/contracts/generated/api.ts
+++ b/web/contracts/generated/api.ts
@@ -1772,7 +1772,10 @@ export interface paths {
readonly cookie?: never;
};
readonly get?: never;
- /** Update Pending Indexing Policy */
+ /**
+ * Update Pending Indexing Policy
+ * @description Reject obsolete model edits instead of saving a policy that will not apply.
+ */
readonly put: operations["update_pending_indexing_policy_api_knowledge_bases__kb_name__indexing_policy_put"];
readonly post?: never;
readonly delete?: never;
@@ -1913,6 +1916,26 @@ export interface paths {
readonly 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.
+ */
+ 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;
@@ -9302,6 +9325,11 @@ export interface components {
};
/** 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;
/**
* Indexing Llm
* @default
@@ -18079,7 +18107,9 @@ export interface operations {
readonly [name: string]: unknown;
};
content: {
- readonly "application/json": unknown;
+ readonly "application/json": {
+ readonly [key: string]: unknown;
+ };
};
};
/** @description Validation Error */
@@ -18298,7 +18328,46 @@ export interface operations {
readonly [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 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 */
@@ -18333,7 +18402,9 @@ export interface operations {
readonly [name: string]: unknown;
};
content: {
- readonly "application/json": unknown;
+ readonly "application/json": {
+ readonly [key: string]: unknown;
+ };
};
};
/** @description Validation Error */
diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.json
index 1d53cdf41..5e51a2fd5 100644
--- a/web/contracts/schema/openapi.json
+++ b/web/contracts/schema/openapi.json
@@ -752,6 +752,11 @@
},
"Body_reindex_knowledge_base_api_knowledge_bases__kb_name__reindex_post": {
"properties": {
+ "config_fingerprint": {
+ "default": "",
+ "title": "Config Fingerprint",
+ "type": "string"
+ },
"indexing_llm": {
"default": "",
"title": "Indexing Llm",
@@ -20958,6 +20963,7 @@
},
"/api/knowledge-bases/{kb_name}/indexing-policy": {
"put": {
+ "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": [
{
@@ -21024,7 +21030,11 @@
"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"
@@ -21498,7 +21508,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"
@@ -21520,6 +21534,83 @@
]
}
},
+ "/api/knowledge-bases/{kb_name}/reindex-config": {
+ "get": {
+ "description": "Read the exact current default configuration 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": "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": {
+ "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": "Get Reindex Config",
+ "tags": [
+ "knowledge-bases"
+ ]
+ }
+ },
"/api/knowledge-bases/{kb_name}/retry": {
"post": {
"description": "Retry a failed KB initialization/indexing run from its stored raw files.",
@@ -21571,7 +21662,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 --git a/web/features/knowledge/api/catalog.ts b/web/features/knowledge/api/catalog.ts
index 9e99933da..b6818cedd 100644
--- a/web/features/knowledge/api/catalog.ts
+++ b/web/features/knowledge/api/catalog.ts
@@ -16,9 +16,10 @@ export {
probeWeKnora,
readErrorDetail,
reindexKnowledgeBase,
+ getReindexConfig,
+ type LightRagRebuildConfig,
retryKnowledgeBase,
setDefaultKnowledgeBase,
- updatePendingIndexingPolicy,
} from "./client";
export type {
diff --git a/web/features/knowledge/api/client.ts b/web/features/knowledge/api/client.ts
index e4383f4ff..c962589dd 100644
--- a/web/features/knowledge/api/client.ts
+++ b/web/features/knowledge/api/client.ts
@@ -727,7 +727,6 @@ export async function createKnowledgeBase(payload: {
files: File[];
pageindexMode?: "flash" | "standard";
searchMode?: string;
- indexingLLM?: IndexingLLMSelection | LightRagIndexingSelection;
}): Promise<KnowledgeTaskResponse> {
const form = new FormData();
form.append("name", payload.name);
@@ -736,9 +735,6 @@ export async function createKnowledgeBase(payload: {
form.append("pageindex_mode", payload.pageindexMode);
}
if (payload.searchMode) form.append("search_mode", payload.searchMode);
- if (payload.indexingLLM) {
- form.append("indexing_llm", JSON.stringify(payload.indexingLLM));
- }
appendFilesWithPaths(form, payload.files);
const res = await apiFetch(apiUrl("/api/knowledge-bases"), {
@@ -1219,14 +1215,34 @@ export async function setDefaultKnowledgeBase(name: string): Promise<void> {
invalidateKnowledgeCaches();
}
+export interface LightRagRebuildConfig {
+ fingerprint: string;
+ indexing_policy: import("@/lib/knowledge-helpers").LightRagIndexingPolicy;
+ embedding: { model: string; dimension: number };
+}
+
+export async function getReindexConfig(
+ name: string,
+): Promise<LightRagRebuildConfig> {
+ const res = await apiFetch(
+ apiUrl(`/api/knowledge-bases/${encodeURIComponent(name)}/reindex-config`),
+ { 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 | LightRagIndexingSelection,
+ configFingerprint?: string,
): Promise<KnowledgeTaskResponse> {
const request: RequestInit = { method: "POST" };
- if (indexingLLM) {
+ if (configFingerprint) {
const form = new FormData();
- form.append("indexing_llm", JSON.stringify(indexingLLM));
+ form.append("config_fingerprint", configFingerprint);
request.body = form;
}
const res = await apiFetch(
@@ -1246,30 +1262,6 @@ export async function reindexKnowledgeBase(
return (await res.json()) as KnowledgeTaskResponse;
}
-export async function updatePendingIndexingPolicy(
- name: string,
- indexingLLM: IndexingLLMSelection | LightRagIndexingSelection,
-): Promise<{ indexing_policy: Record<string, unknown> }> {
- const res = await apiFetch(
- apiUrl(`/api/knowledge-bases/${encodeURIComponent(name)}/indexing-policy`),
- {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(indexingLLM),
- },
- );
- if (!res.ok) {
- throw new Error(
- await readErrorDetail(
- res,
- `Failed to update indexing model (${res.status})`,
- ),
- );
- }
- invalidateKnowledgeCaches();
- return (await res.json()) as { indexing_policy: Record<string, unknown> };
-}
-
export async function retryKnowledgeBase(
name: string,
): Promise<KnowledgeTaskResponse> {
diff --git a/web/hooks/useKnowledgeBases.ts b/web/hooks/useKnowledgeBases.ts
index 32065de5a..374c5d848 100644
--- a/web/hooks/useKnowledgeBases.ts
+++ b/web/hooks/useKnowledgeBases.ts
@@ -15,10 +15,8 @@ import {
listRagProviders,
reindexKnowledgeBase as reindexKbApi,
retryKnowledgeBase as retryKbApi,
- updatePendingIndexingPolicy as updatePendingIndexingPolicyApi,
setDefaultKnowledgeBase as setDefaultKbApi,
type KnowledgeTaskResponse,
- type LightRagIndexingSelection,
type KnowledgeUploadPolicy,
type RagProviderSummary,
} from "@/features/knowledge/api/catalog";
@@ -182,8 +180,7 @@ export function useKnowledgeBases() {
files: File[];
pageindexMode?: "flash" | "standard";
searchMode?: string;
- indexingLLM?: LightRagIndexingSelection;
- }): Promise<KnowledgeTaskResponse> => {
+ }): Promise<KnowledgeTaskResponse> => {
const result = await createKbApi(params);
invalidateKnowledgeCaches();
const fileCount = params.files.length;
@@ -262,9 +259,9 @@ export function useKnowledgeBases() {
const reindex = useCallback(
async (
kbName: string,
- indexingLLM?: LightRagIndexingSelection,
+ configFingerprint?: string,
): Promise<KnowledgeTaskResponse> => {
- const result = await reindexKbApi(kbName, indexingLLM);
+ const result = await reindexKbApi(kbName, configFingerprint);
if (result.noop) {
await load({ force: true, showSpinner: false });
return result;
@@ -287,14 +284,6 @@ export function useKnowledgeBases() {
[load, progress],
);
- const updatePendingIndexingPolicy = useCallback(
- async (kbName: string, indexingLLM: LightRagIndexingSelection) => {
- await updatePendingIndexingPolicyApi(kbName, indexingLLM);
- await load({ force: true, showSpinner: false });
- },
- [load],
- );
-
const retry = useCallback(
async (kbName: string): Promise<KnowledgeTaskResponse> => {
const result = await retryKbApi(kbName);
@@ -415,7 +404,6 @@ export function useKnowledgeBases() {
uploadFiles,
setDefault,
reindex,
- updatePendingIndexingPolicy,
retry,
deleteKb,
connectObsidian,
diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.ts
index 111bd796a..43d36bd9f 100644
--- a/web/lib/knowledge-helpers.ts
+++ b/web/lib/knowledge-helpers.ts
@@ -103,6 +103,8 @@ export interface IndexVersion {
legacy?: boolean;
failure_summary?: string;
indexing_policy?: LightRagIndexingPolicy;
+ embedding_model?: string;
+ embedding_dim?: number;
}
export interface LightRagIndexingPolicy {
@@ -182,6 +184,7 @@ export interface KnowledgeBase {
/** Bound partner id when agent_kind === "partner". */
partner_id?: string;
indexing_policy?: LightRagIndexingPolicy;
+ indexing_model_unavailable?: boolean;
};
progress?: ProgressInfo;
statistics?: {
@@ -387,6 +390,8 @@ export const resolveKnowledgeIndexFailure = (
]);
const completionConfigurationCodes = new Set([
"graphrag_model_incompatible",
+ "indexing_model_unavailable",
+ "reindex_required",
"graphrag_provider_unsupported",
"graphrag_model_authentication_failed",
"graphrag_model_endpoint_failed",
@@ -425,6 +430,7 @@ export const kbRequiresLightRagRebuildBeforeAppend = (
export const kbIsUploadable = (kb: KnowledgeBase): boolean =>
resolveKbStatus(kb) === "ready" &&
!kbNeedsReindex(kb) &&
+ !kb.metadata?.indexing_model_unavailable &&
!kbRequiresLightRagRebuildBeforeAppend(kb);
export const kbCanUploadDocuments = (
@@ -434,6 +440,7 @@ export const kbCanUploadDocuments = (
kbIsUploadable(kb) ||
(resolveKbStatus(kb) === "error" &&
!indexingActive &&
+ !kb.metadata?.indexing_model_unavailable &&
!kbRequiresLightRagRebuildBeforeAppend(kb));
export const kbCanReindex = (kb: KnowledgeBase): boolean => {
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index 4054ebe0b..2a76a0f5d 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -1,4 +1,5 @@
{
+ "Review rebuild": "Review rebuild",
"language.english": "English",
"language.chinese": "中文",
"Start": "Start",
@@ -4036,5 +4037,15 @@
"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."
+ "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.",
+ "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."
}
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 3d605d744..c840b747c 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -1,4 +1,5 @@
{
+ "Review rebuild": "查看重建配置",
"language.english": "English",
"language.chinese": "中文",
"Start": "开始",
@@ -4036,5 +4037,15 @@
"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 均需完整重建索引。"
+ "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.": "本次完整重建将采用下列默认配置。请在设置中修改模型。确认提交后固定本次配置;重建失败时保留原索引版本。",
+ "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.": "默认配置已更改。请查看更新后的配置并重新确认。"
}
diff --git a/web/tests/lightrag-indexing-model.test.ts b/web/tests/lightrag-indexing-model.test.ts
index f9dc8dda6..b16973015 100644
--- a/web/tests/lightrag-indexing-model.test.ts
+++ b/web/tests/lightrag-indexing-model.test.ts
@@ -6,13 +6,11 @@ import path from "node:path";
import {
createKnowledgeBase,
reindexKnowledgeBase,
- updatePendingIndexingPolicy,
} from "../features/knowledge/api/client";
import {
selectionFromLightRagDefault,
selectionFromLLMOption,
} from "../components/knowledge/IndexingModelSelector";
-import { selectionForLightRagModelDialog } from "../components/knowledge/KbIndexVersionsSection";
import {
currentLightRagBuildCandidate,
kbCanUploadDocuments,
@@ -39,61 +37,31 @@ function stubFetch(
};
}
-test("create and re-index send the exact pinned selection and preserve none", async () => {
+test("create uses defaults and re-index sends only the confirmed fingerprint", async () => {
const requests: Array<{ url: string; form: FormData }> = [];
const restore = stubFetch(async (input, init) => {
requests.push({ url: String(input), form: init?.body as FormData });
return jsonResponse(200, { task_id: "task-1", noop: false });
});
- const selection = {
- profile_id: "profile-1",
- model_id: "model-1",
- reasoning_effort: "none",
- };
try {
await createKnowledgeBase({
name: "papers",
provider: "lightrag",
files: [],
- indexingLLM: selection,
});
- await reindexKnowledgeBase("papers", selection);
+ await reindexKnowledgeBase("papers", "confirmed-fingerprint");
} finally {
restore();
}
assert.equal(requests[0].url, "/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.deepEqual(
- JSON.parse(String(requests[1].form.get("indexing_llm"))),
- selection,
+ assert.equal(
+ requests[1].form.get("config_fingerprint"),
+ "confirmed-fingerprint",
);
-});
-
-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(captured?.url, "/api/knowledge-bases/empty/indexing-policy");
- 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 () => {
@@ -178,43 +146,6 @@ test("indexing defaults prefer the released LightRAG query model", () => {
);
});
-test("late catalog loading preserves an empty knowledge base's saved pending model", () => {
- const option = {
- profile_id: "saved-profile",
- model_id: "saved-model",
- profile_name: "Saved",
- model_name: "Saved model",
- model: "saved",
- provider: "openai",
- is_active_default: false,
- };
- assert.deepEqual(
- selectionForLightRagModelDialog(
- [option],
- { llm_profile_id: "current-profile", llm_model_id: "current-model" },
- null,
- {
- policy: "pending_pinned",
- vision_available: false,
- selection: {
- profile_id: "saved-profile",
- model_id: "saved-model",
- reasoning_effort: "none",
- },
- },
- true,
- ),
- {
- extract: {
- profile_id: "saved-profile",
- model_id: "saved-model",
- reasoning_effort: "none",
- },
- vlm: { mode: "disabled" },
- },
- );
-});
-
test("healthy LightRAG knowledge bases retain a full re-index entry", () => {
const kb: KnowledgeBase = {
name: "graph",
@@ -288,39 +219,22 @@ test("LightRAG candidates distinguish active builds from failures", () => {
);
});
-test("model controls are scoped to built-in LightRAG create/rebuild surfaces", () => {
- const root = path.resolve(process.cwd());
- const createSource = readFileSync(
- path.join(root, "components/knowledge/CreateKbModal.tsx"),
- "utf8",
- );
- const uploadSource = readFileSync(
- path.join(root, "components/knowledge/KbDocumentsSection.tsx"),
- "utf8",
- );
- const detailSource = readFileSync(
- path.join(root, "components/knowledge/KnowledgeBaseDetail.tsx"),
- "utf8",
- );
- const provenanceSource = readFileSync(
- path.join(root, "components/knowledge/LightRagIndexingProvenance.tsx"),
+test("model selectors are absent from create/rebuild and duplicate settings surfaces", () => {
+ const root = process.cwd();
+ for (const name of [
+ "CreateKbModal",
+ "KbIndexVersionsSection",
+ "KbDocumentsSection",
+ ]) {
+ const source = readFileSync(
+ path.join(root, `components/knowledge/${name}.tsx`),
+ "utf8",
+ );
+ assert.doesNotMatch(source, /<LightRagIndexingSelector/);
+ }
+ const settings = readFileSync(
+ path.join(root, "components/knowledge/KbSettingsSection.tsx"),
"utf8",
);
- assert.match(createSource, /provider === ['"]lightrag['"] \? \(/);
- assert.match(createSource, /indexingLLM:\s*provider === ['"]lightrag['"]/);
- assert.doesNotMatch(uploadSource, /IndexingModelSelector/);
- assert.match(uploadSource, /LightRagIndexingProvenance/);
- assert.match(provenanceSource, /compact && \(/);
- assert.match(
- provenanceSource,
- /modelLabel \|\| t\(['"]Unverified historical indexing model['"]\)/,
- );
- assert.match(
- provenanceSource,
- /t\(['"]Reasoning effort['"]\).*effort \|\| t\(['"]Model default['"]\)/s,
- );
- assert.match(
- detailSource,
- /status === ['"]error['"] && kbProvider\(kb\) !== ['"]lightrag['"]/,
- );
+ assert.doesNotMatch(settings, /LightRagIndexingProvenance/);
});
diff --git a/web/tests/lightrag-lifecycle.spec.tsx b/web/tests/lightrag-lifecycle.spec.tsx
new file mode 100644
index 000000000..161bcffe3
--- /dev/null
+++ b/web/tests/lightrag-lifecycle.spec.tsx
@@ -0,0 +1,264 @@
+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),
+}));
+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 () => {
+ 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();
+ 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(
+ 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");
+});
+
+it("has no model or rebuild action 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.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");
+ reindex.mockResolvedValue(undefined);
+ fireEvent.click(
+ within(dialog).getByRole("button", { name: "Confirm rebuild" }),
+ );
+ await waitFor(() =>
+ expect(reindex).toHaveBeenLastCalledWith("papers", "retry-new"),
+ );
+ expect(retry).not.toHaveBeenCalled();
+ },
+);
diff --git a/web/tests/lightrag-role-models.spec.tsx b/web/tests/lightrag-role-models.spec.tsx
index acd9288e7..b87d747af 100644
--- a/web/tests/lightrag-role-models.spec.tsx
+++ b/web/tests/lightrag-role-models.spec.tsx
@@ -6,9 +6,8 @@ import LightRagRoleModelsEditor, {
resolvedRole,
roleModelsValidationError,
} from "@/components/knowledge/LightRagRoleModelsEditor";
-import LightRagIndexingSelector, {
+import {
indexingSelectionFromDefaults,
- indexingSelectionFromPolicy,
isCompleteIndexingSelection,
} from "@/components/knowledge/LightRagIndexingSelector";
import type {
@@ -180,7 +179,7 @@ describe("LightRAG role editor", () => {
).not.toBeInTheDocument();
});
});
-it("prefills independent indexing roles and preserves a saved disabled policy", () => {
+it("resolves independent indexing role defaults", () => {
const roles = newRoleModels(textModel);
roles.vlm = {
mode: "model",
@@ -202,109 +201,15 @@ it("prefills independent indexing roles and preserves a saved disabled policy",
selection: { ...visionModel, reasoning_effort: "none" },
},
});
- expect(
- indexingSelectionFromPolicy({
- schema_version: 2,
- policy: "pending_pinned",
- extract: { policy: "pinned", selection: textModel },
- vlm: { mode: "disabled" },
- }),
- ).toEqual({ extract: textModel, vlm: { mode: "disabled" } });
-});
-it("selects a vision model without a duplicate VLM control", () => {
- function Draft() {
- const [selection, setSelection] =
- useState<LightRagIndexingSelection | null>({
- extract: textModel,
- vlm: { mode: "disabled" },
- });
- return (
- <>
- <LightRagIndexingSelector
- options={options}
- selection={selection}
- onChange={setSelection}
- loading={false}
- error={false}
- />
- <output data-testid="draft">{JSON.stringify(selection)}</output>
- <button disabled={!isCompleteIndexingSelection(selection)}>
- Submit
- </button>
- </>
- );
- }
- render(<Draft />);
- fireEvent.change(
- screen.getByRole("combobox", { name: "VLM image analysis" }),
- {
- target: { value: "vision:large" },
- },
- );
- expect(
- JSON.parse(screen.getByTestId("draft").textContent ?? "{}").vlm,
- ).toEqual({
- mode: "enabled",
- selection: visionModel,
- });
- expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
- expect(
- screen.queryByRole("combobox", { name: "VLM model" }),
- ).not.toBeInTheDocument();
-});
+ });
-it("blocks structurally complete indexing selections whose models disappeared", () => {
+it("rejects default indexing models missing from the accessible catalog", () => {
const stale: LightRagIndexingSelection = {
extract: { profile_id: "gone", model_id: "gone" },
vlm: { mode: "disabled" },
};
expect(isCompleteIndexingSelection(stale)).toBe(true);
expect(isCompleteIndexingSelection(stale, options)).toBe(false);
- render(
- <LightRagIndexingSelector
- options={options}
- selection={stale}
- onChange={vi.fn()}
- loading={false}
- error={false}
- />,
- );
- expect(
- screen.getByText(
- "One or more selected indexing models are unavailable. Choose accessible models before continuing.",
- ),
- ).toBeInTheDocument();
- expect(
- screen.getByRole("option", { name: "Unavailable model · gone" }),
- ).toBeDisabled();
-});
-
-it("shows engine defaults in the collapsed create-index summary", () => {
- const defaults: LightRagIndexingSelection = {
- extract: textModel,
- vlm: { mode: "disabled" },
- };
- render(
- <LightRagIndexingSelector
- options={options}
- selection={defaults}
- defaults={defaults}
- collapsible
- onChange={vi.fn()}
- loading={false}
- error={false}
- />,
- );
- expect(
- screen.getByText("EXTRACT: Small · VLM: Image analysis disabled"),
- ).toBeInTheDocument();
- fireEvent.click(screen.getByText("Indexing models (optional override)"));
- expect(
- screen.getByRole("combobox", { name: "EXTRACT model" }),
- ).toHaveValue("__engine_default__");
- expect(
- screen.getByRole("combobox", { name: "VLM image analysis" }),
- ).toHaveValue("__engine_default__");
});
it("distinguishes inherited reasoning from an explicit override with the same value", () => {