DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(lightrag): preserve native write revisions and explicit role semantics
NoxsMedia8ef011b88a65
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.pyindex 2ec8a6dca..19ff72ebe 100644--- a/deeptutor/services/config/runtime_settings.py+++ b/deeptutor/services/config/runtime_settings.py@@ -342,7 +342,7 @@ DEFAULT_GRAPHRAG_SETTINGS: dict[str, Any] = {# Stable catalog references let LightRAG use a dedicated LLM while the global# active chat model remains unchanged for ordinary chat.DEFAULT_LIGHTRAG_SETTINGS: dict[str, Any] = {- "version": 1,+ "version": 2,"top_k": 60,"response_type": "Multiple Paragraphs","max_concurrent_files": 1,@@ -620,7 +620,10 @@ class RuntimeSettingsService:loaded = json.load(handle)if not isinstance(loaded, dict):raise ValueError("LightRAG settings must be an object.")- normalized = self._normalize_lightrag({**DEFAULT_LIGHTRAG_SETTINGS, **loaded})+ # Existing files without a version predate independent roles.+ normalized = self._normalize_lightrag(+ {**DEFAULT_LIGHTRAG_SETTINGS, "version": 1, **loaded}+ )if normalized != loaded:_atomic_write_json(path, normalized)return normalized@@ -977,7 +980,7 @@ class RuntimeSettingsService:else None)result = {- "version": 1,+ "version": 2 if roles is not None or settings.get("version") == 2 else 1,"top_k": _coerce_clamped_int(settings.get("top_k"), 60, 1, 200),"response_type": self._normalize_response_type(settings.get("response_type")),"max_concurrent_files": _coerce_clamped_int(diff --git a/deeptutor/services/model_selection/reasoning.py b/deeptutor/services/model_selection/reasoning.pyindex d7afae050..e0d058f9d 100644--- a/deeptutor/services/model_selection/reasoning.py+++ b/deeptutor/services/model_selection/reasoning.py@@ -9,7 +9,8 @@ from __future__ import annotationsfrom typing import Any-from .llm import VALID_REASONING_EFFORTS+from deeptutor.services.llm.reasoning_params import build_openai_compatible_reasoning_kwargs+from deeptutor.services.provider_registry import find_by_namedef supported_reasoning_efforts(@@ -17,11 +18,7 @@ def supported_reasoning_efforts() -> list[str]:metadata = metadata or {}declared = metadata.get("codex_supported_reasoning_levels")- if isinstance(declared, list):- return [level for level in (*VALID_REASONING_EFFORTS, "adaptive") if level in declared]capabilities = metadata.get("capabilities") or {}- if capabilities.get("reasoning") is False:- return []provider = binding.lower().replace("-", "_")provider = {"azure": "azure_openai",@@ -32,6 +29,28 @@ def supported_reasoning_efforts("openai_compatible": "custom","anthropic_compatible": "custom_anthropic",}.get(provider, provider)+ spec = find_by_name(provider)+ binary_choices = None+ if spec is None or spec.backend in {"openai_compat", "azure_openai"}:+ # Use the actual wire mapper, including custom model-family inference.+ # Its binary controls express off as minimal and on as high; it cannot+ # preserve none or distinct low/medium choices on these paths.+ mapped = build_openai_compatible_reasoning_kwargs(+ spec=spec, binding=provider, model=model, reasoning_effort="minimal"+ )+ if mapped.get("extra_body"):+ binary_choices = ["minimal", "high"]+ if isinstance(declared, list):+ ordered = ("none", "minimal", "low", "medium", "high", "xhigh", "max", "adaptive")+ return [+ level+ for level in ordered+ if level in declared and (binary_choices is None or level in binary_choices)+ ]+ if capabilities.get("reasoning") is False:+ return []+ if binary_choices is not None:+ return binary_choicesname = model.lower()levels: list[str] = []if provider == "gemini" or "gemini" in name:diff --git a/deeptutor/services/rag/pipelines/lightrag/README.md b/deeptutor/services/rag/pipelines/lightrag/README.mdindex 7454750fe..4a5ea5606 100644--- a/deeptutor/services/rag/pipelines/lightrag/README.md+++ b/deeptutor/services/rag/pipelines/lightrag/README.md@@ -11,6 +11,8 @@ Shared engine settings require administrator access when authentication is enabl| QUERY | Answer generation | Base or explicit model || 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.New role configurations disable VLM by default. Inheriting the base for VLMrequires a model that supports image inputs. Disabling VLM preserves text,table and equation processing. An explicit image-analysis request on a disableddiff --git a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.pyindex 5c2ae1815..de2554ef5 100644--- a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py+++ b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py@@ -301,6 +301,8 @@ def freeze_roles(settings = load_lightrag_settings()models = settings_models(settings)limits = runtime_limits(settings)+ if selection_value is None and models is None and settings.get("version") == 2:+ raise IndexingPolicyError("Choose a LightRAG base model or explicit indexing models first.")if selection_value is None and models is not None:extract_selection = models.selection_for("extract").model_dump()vlm_selection = models.selection_for("vlm")@@ -330,7 +332,7 @@ def freeze_roles(value = {"extract": selected,"vlm": {"mode": "enabled", "selection": selected}- if single.vision_available+ if single.vision_available and settings.get("version") != 2else {"mode": "disabled"},}parsed = LightRagIndexingSelection.model_validate(value)@@ -426,11 +428,17 @@ def _target_policy_key(kb_dir: Path) -> str | None:def _content_revision(root: Path | None) -> str:# Native document-status flushes are atomic. Track inode and nanosecond# timestamps as well as size so a same-version append invalidates a queued rebuild.+ from .storage import _store_root+revisions = {}if root is not None:- for name in ("meta.json", "kv_store_doc_status.json"):+ paths = {+ "meta.json": root / "meta.json",+ "kv_store_doc_status.json": _store_root(root) / "kv_store_doc_status.json",+ }+ for name, path in paths.items():try:- stat = (root / name).stat()+ stat = path.stat()revisions[name] = [stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns]except FileNotFoundError:revisions[name] = Nonediff --git a/deeptutor/services/rag/pipelines/lightrag/roles.py b/deeptutor/services/rag/pipelines/lightrag/roles.pyindex 7b312cfed..a2e641197 100644--- a/deeptutor/services/rag/pipelines/lightrag/roles.py+++ b/deeptutor/services/rag/pipelines/lightrag/roles.py@@ -101,6 +101,8 @@ def resolve_query_roles() -> dict[str, RoleCall]:settings = load_lightrag_settings()models = settings_models(settings)+ if models is None and settings.get("version") == 2:+ raise ValueError("Choose and save a LightRAG base model before querying.")limits = runtime_limits(settings)owner = get_current_user()result = {}diff --git a/tests/services/rag/test_lightrag_roles.py b/tests/services/rag/test_lightrag_roles.pyindex ea7aa0b92..bc5f16859 100644--- a/tests/services/rag/test_lightrag_roles.py+++ b/tests/services/rag/test_lightrag_roles.py@@ -639,3 +639,126 @@ async def test_github_sync_freezes_policy_before_download(role_environment, tmp_assert accepted[0].vlm.fingerprint == pinned.vlm.fingerprintassert accepted[0].target_boundassert recorded[0]["last_synced_sha"] == "new-sha"++[email protected]("outcome_kind", ["partial_append", "metadata_refresh_failure"])+def test_native_workspace_append_invalidates_queued_rebuild_without_meta_change(+ role_environment, tmp_path, monkeypatch, outcome_kind+):+ from deeptutor.services.rag.pipelines.lightrag.pipeline import LightRagBatchError++ kb = tmp_path / "kb"+ root = kb / "version-1"+ snapshot = policy.freeze_roles()+ _published(root, snapshot.persisted_policy())+ workspace = root / engine.workspace_for(root)+ workspace.mkdir()+ status = workspace / "kv_store_doc_status.json"+ (root / status.name).rename(status)+ before_meta = (root / "meta.json").read_bytes()+ rebuild = policy.bind_target(snapshot, kb, protect_contents=True)+ append = policy.bind_target(snapshot, kb)+ pipeline = LightRagPipeline(str(tmp_path))+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)++ async def append_native(*args):+ status.write_text('{"doc":{"status":"processed"},"later":{"status":"processed"}}')+ result = BatchOutcome(+ requested=2 if outcome_kind == "partial_append" else 1,+ accepted=2 if outcome_kind == "partial_append" else 1,+ processed=("later.md",),+ failed={"bad.md": "provider rejected"} if outcome_kind == "partial_append" else {},+ indexing_policy=snapshot.persisted_policy(),+ )+ if outcome_kind == "partial_append":+ raise LightRagBatchError(result)+ return result++ def fail_metadata(*args, **kwargs):+ raise OSError("metadata refresh failed")++ monkeypatch.setattr(pipeline, "_run_indexing", append_native)+ monkeypatch.setattr(storage, "write_meta", fail_metadata)+ if outcome_kind == "partial_append":+ with pytest.raises(LightRagBatchError):+ asyncio.run(+ pipeline.add_documents(+ "kb", ["later.md", "bad.md"], accepted_indexing_snapshot=append+ )+ )+ else:+ assert asyncio.run(+ pipeline.add_documents("kb", ["later.md"], accepted_indexing_snapshot=append)+ )+ assert (root / "meta.json").read_bytes() == before_meta+ assert storage.latest_published_root(kb) == root+ with pytest.raises(policy.IndexingPolicyError, match="target index"):+ policy.validate_target(rebuild, kb)+ policy.validate_target(append, kb)++[email protected]("model", ["qwen3-32b", "deepseek-r1"])+def test_custom_binary_reasoning_choices_match_actual_request(model):+ from deeptutor.services.llm.provider_core.openai_compat_provider import OpenAICompatProvider+ from deeptutor.services.model_selection.reasoning import supported_reasoning_efforts+ from deeptutor.services.provider_registry import find_by_name++ assert supported_reasoning_efforts("custom", model) == ["minimal", "high"]+ assert supported_reasoning_efforts(+ "custom", model, metadata={"codex_supported_reasoning_levels": ["none", "low", "high"]}+ ) == ["high"]+ provider = OpenAICompatProvider(+ api_key="synthetic", default_model=model, spec=find_by_name("custom"), configure_env=False+ )+ disabled = provider._build_kwargs(+ [{"role": "user", "content": "test"}], None, model, 100, 0, "minimal", None+ )+ enabled = provider._build_kwargs(+ [{"role": "user", "content": "test"}], None, model, 100, 0, "high", None+ )+ if "qwen" in model:+ assert disabled["extra_body"]["enable_thinking"] is False+ assert enabled["extra_body"]["enable_thinking"] is True+ else:+ assert disabled["extra_body"]["thinking"]["type"] == "disabled"+ assert enabled["extra_body"]["thinking"]["type"] == "enabled"+++def test_binary_provider_none_is_rejected_before_snapshot(role_environment):+ role_environment["configs"]["p0"].model = "qwen3-32b"+ # Use the real capability mapper with the same catalog model name.+ options = roles.allowed_llm_options++ def catalog():+ value = options()+ value["options"][0]["model"] = "qwen3-32b"+ return value++ from unittest.mock import patch++ with patch.object(roles, "allowed_llm_options", catalog):+ with pytest.raises(policy.IndexingPolicyError, match="reasoning effort"):+ policy.freeze_roles()+++def test_fresh_defaults_do_not_enter_legacy_model_or_vision_fallback(role_environment, tmp_path):+ from deeptutor.services.config.runtime_settings import RuntimeSettingsService++ service = RuntimeSettingsService(tmp_path / "settings", process_env={})+ fresh = service.load_lightrag()+ assert fresh["version"] == 2+ role_environment["settings"] = fresh+ with pytest.raises(policy.IndexingPolicyError, match="base model"):+ policy.freeze_roles()+ with pytest.raises(ValueError, match="base model"):+ roles.resolve_query_roles()+ # An old-form explicit model input on a fresh configuration still defaults VLM off.+ created = policy.freeze_roles(choice(3))+ assert created.vlm is None+ legacy_path = service.path_for("lightrag")+ legacy_path.write_text('{"llm_profile_id":"p3","llm_model_id":"m3"}')+ legacy = service.load_lightrag()+ assert legacy["version"] == 1+ role_environment["settings"] = legacy+ # The compatibility path retains historical vision semantics.+ assert policy.freeze_roles(choice(3)).vlm is not Nonediff --git a/web/components/knowledge/IndexingModelSelector.tsx b/web/components/knowledge/IndexingModelSelector.tsxindex 4e5ce880b..c73ec0ec6 100644--- a/web/components/knowledge/IndexingModelSelector.tsx+++ b/web/components/knowledge/IndexingModelSelector.tsx@@ -61,6 +61,7 @@ export function selectionFromLightRagDefault(interface IndexingModelSelectorProps {label?: string;lockModel?: boolean;+ inheritBaseReasoning?: string | null;options: LLMOption[];selection: IndexingLLMSelection | null;loading: boolean;@@ -74,6 +75,7 @@ interface IndexingModelSelectorProps {export default function IndexingModelSelector({label = "Indexing model",lockModel = false,+ inheritBaseReasoning,options,selection,loading,@@ -194,7 +196,11 @@ export default function IndexingModelSelector({}className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] text-[var(--foreground)] disabled:opacity-50">- <option value="">{t("Model default / unspecified")}</option>+ <option value="">+ {inheritBaseReasoning !== undefined+ ? t("Inherit base reasoning")+ : t("Model default / unspecified")}+ </option>{selection?.reasoning_effort &&!reasoningOptions.some((option) => option.value === selection.reasoning_effort,@@ -215,10 +221,17 @@ export default function IndexingModelSelector({<p className="mt-1 text-[11px] text-[var(--muted-foreground)]">{t("Effective reasoning")}:{" "}{selection?.reasoning_effort ||+ inheritBaseReasoning ||selected.reasoning_effort ||t("Model default")}.{" "}- {t("Auto inherits the selected model's saved reasoning effort.")}+ {inheritBaseReasoning !== undefined+ ? t(+ "With no role override, reasoning follows the LightRAG base.",+ )+ : t(+ "Auto inherits the selected model's saved reasoning effort.",+ )}</p></label>)}diff --git a/web/components/knowledge/LightRagIndexingSelector.tsx b/web/components/knowledge/LightRagIndexingSelector.tsxindex 61a34505e..c2d9d26a6 100644--- a/web/components/knowledge/LightRagIndexingSelector.tsx+++ b/web/components/knowledge/LightRagIndexingSelector.tsx@@ -17,7 +17,7 @@ export function indexingSelectionFromDefaults(config: Pick<LightRagConfig,"llm_profile_id" | "llm_model_id" | "role_models"- >,+ > & { version?: number },active?: LLMOptionsResponse["active"],): LightRagIndexingSelection | null {if (config.role_models) {@@ -33,6 +33,7 @@ export function indexingSelectionFromDefaults(const selected = selectionFromLightRagDefault(options, config, active);if (!selected) return null;const vision =+ config.version !== 2 &&options.find((option) =>option.profile_id === selected.profile_id &&diff --git a/web/components/knowledge/LightRagRoleModelsEditor.tsx b/web/components/knowledge/LightRagRoleModelsEditor.tsxindex b2fe00f22..ad154535d 100644--- a/web/components/knowledge/LightRagRoleModelsEditor.tsx+++ b/web/components/knowledge/LightRagRoleModelsEditor.tsx@@ -127,7 +127,19 @@ export default function LightRagRoleModelsEditor({? options.filter((option) => option.supports_vision): options}- selection={effective}+ selection={+ effective+ ? {+ ...effective,+ reasoning_effort: value.reasoning_effort ?? undefined,+ }+ : null+ }+ inheritBaseReasoning={+ value.mode === "inherit"+ ? (models.base.reasoning_effort ?? null)+ : undefined+ }loading={loading}error={error}lockModel={value.mode === "inherit"}diff --git a/web/features/knowledge/components/engines/EngineDetail.tsx b/web/features/knowledge/components/engines/EngineDetail.tsxindex 0867092b0..eef119ce1 100644--- a/web/features/knowledge/components/engines/EngineDetail.tsx+++ b/web/features/knowledge/components/engines/EngineDetail.tsx@@ -1081,7 +1081,10 @@ export function LightRagForm({const roleModels =form.role_models ??(legacyBase- ? newRoleModels(legacyBase, legacyOption?.supports_vision === true)+ ? newRoleModels(+ legacyBase,+ form.version !== 2 && legacyOption?.supports_vision === true,+ ): null);const save = async () => {@@ -1133,7 +1136,7 @@ export function LightRagForm({/></div>- {!form.role_models && (+ {!form.role_models && form.version !== 2 && (<p className="text-xs text-[var(--muted-foreground)]">{t("Legacy model settings are shown below. Saving fixes the LightRAG base selection independently of chat.",diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 700ce948f..e0c90ac72 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -4015,5 +4015,7 @@"VLM image analysis": "VLM image analysis","VLM model": "VLM model","effective model": "effective model",- "Finalizing index publication": "Finalizing index publication"+ "Finalizing index publication": "Finalizing index publication",+ "Inherit base reasoning": "Inherit base reasoning",+ "With no role override, reasoning follows the LightRAG base.": "With no role override, reasoning follows the LightRAG base."}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 8614f4abf..e8c6a479d 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -4015,5 +4015,7 @@"VLM image analysis": "VLM 图片分析","VLM model": "VLM 模型","effective model": "实际模型",- "Finalizing index publication": "正在完成索引发布"+ "Finalizing index publication": "正在完成索引发布",+ "Inherit base reasoning": "继承基础模型推理设置",+ "With no role override, reasoning follows the LightRAG base.": "未设置角色覆盖值时,推理强度继承 LightRAG 基础模型。"}diff --git a/web/tests/lightrag-form.spec.tsx b/web/tests/lightrag-form.spec.tsxnew file mode 100644index 000000000..382337973--- /dev/null+++ b/web/tests/lightrag-form.spec.tsx@@ -0,0 +1,81 @@+import React from "react";+import {+ fireEvent,+ render,+ screen,+ waitFor,+ within,+} from "@testing-library/react";+import { beforeEach, expect, it, vi } from "vitest";+import { LightRagForm } from "@/features/knowledge/components/engines/EngineDetail";++const fixture = vi.hoisted(() => ({ version: 2, save: vi.fn() }));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));+vi.mock("@/hooks/useAuthStatus", () => ({+ useAuthStatus: () => ({+ statusAvailable: true,+ enabled: false,+ isAdmin: true,+ loading: false,+ }),+}));+vi.mock("@/hooks/useLLMOptions", () => ({+ useLLMOptions: () => ({+ loading: false,+ error: false,+ activeDefault: { profile_id: "vision", model_id: "large" },+ options: [+ {+ profile_id: "vision",+ model_id: "large",+ profile_name: "Vision",+ model_name: "Large",+ model: "vision-large",+ provider: "custom",+ supports_vision: true,+ supported_reasoning_efforts: ["none", "high"],+ },+ ],+ }),+}));+vi.mock("@/features/knowledge/api/engines", async (original) => ({+ ...(await original<typeof import("@/features/knowledge/api/engines")>()),+ getLightRagConfig: async () => ({+ version: fixture.version,+ llm_profile_id: "",+ llm_model_id: "",+ top_k: 60,+ response_type: "Multiple Paragraphs",+ max_concurrent_files: 1,+ llm_model_max_async: 4,+ entity_extract_max_gleaning: 1,+ }),+ updateLightRagConfig: async (value: unknown) => {+ fixture.save(value);+ return value;+ },+}));+beforeEach(() => fixture.save.mockClear());++it.each([+ [2, "disabled"],+ [1, "inherit"],+] as const)(+ "saves version %s prefilled vision as %s",+ async (version, mode) => {+ fixture.version = version;+ render(<LightRagForm onChanged={vi.fn()} onError={vi.fn()} />);+ const vlm = within(await screen.findByRole("group", { name: "VLM" }));+ expect(vlm.getByRole("combobox", { name: "VLM Model source" })).toHaveValue(+ mode,+ );+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));+ await waitFor(() => expect(fixture.save).toHaveBeenCalledOnce());+ expect(fixture.save.mock.calls[0][0].role_models).toMatchObject({+ base: { profile_id: "vision", model_id: "large" },+ vlm: { mode },+ });+ },+);diff --git a/web/tests/lightrag-role-models.spec.tsx b/web/tests/lightrag-role-models.spec.tsxindex 4ce599b5f..87c3afb0c 100644--- a/web/tests/lightrag-role-models.spec.tsx+++ b/web/tests/lightrag-role-models.spec.tsx@@ -214,3 +214,50 @@ it("requires an explicit vision selection when enabling it in a rebuild draft",});expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();});++it("distinguishes inherited reasoning from an explicit override with the same value", () => {+ render(+ <Editor+ initial={newRoleModels({ ...visionModel, reasoning_effort: "high" })}+ />,+ );+ const extract = within(screen.getByRole("group", { name: "EXTRACT" }));+ const reasoning = extract.getByRole("combobox", { name: "Reasoning effort" });+ expect(reasoning).toHaveValue("");+ expect(+ within(reasoning).getByRole("option", {+ name: "Inherit base reasoning",+ selected: true,+ }),+ ).toBeInTheDocument();+ expect(resolvedRole(state(), "extract")?.reasoning_effort).toBe("high");+ fireEvent.change(reasoning, { target: { value: "high" } });+ expect(reasoning).toHaveValue("high");+ fireEvent.change(+ screen.getAllByRole("combobox", { name: "Reasoning effort" })[0],+ { target: { value: "none" } },+ );+ expect(resolvedRole(state(), "extract")?.reasoning_effort).toBe("high");+ fireEvent.change(reasoning, { target: { value: "" } });+ expect(reasoning).toHaveValue("");+ expect(state().extract.reasoning_effort).toBeNull();+ expect(resolvedRole(state(), "extract")?.reasoning_effort).toBe("none");+});++it("prefills fresh indexing defaults with VLM disabled while preserving legacy vision defaults", () => {+ const defaults = { llm_profile_id: "", llm_model_id: "" };+ expect(+ indexingSelectionFromDefaults(+ options,+ { ...defaults, version: 2 },+ visionModel,+ )?.vlm,+ ).toEqual({ mode: "disabled" });+ expect(+ indexingSelectionFromDefaults(+ options,+ { ...defaults, version: 1 },+ visionModel,+ )?.vlm,+ ).toEqual({ mode: "enabled", selection: visionModel });+});