Skip to content

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

fix: retain bound index provenance and embedding-only controls

NoxsMedia1c8a29d257b5
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index cf25c8400..a30682b1a 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -1407,11 +1407,16 @@ class KnowledgeBaseManager:
if rag_provider == LIGHTRAG_PROVIDER:
from deeptutor.services.rag.pipelines.lightrag.storage import (
- latest_published_root,
+ published_root_for_embedding,
read_published_policy,
)
- published_root = latest_published_root(kb_dir) if dir_exists else None
+ signature = (
+ kb_config.get("embedding_signature")
+ if kb_config.get("embedding_selection")
+ else None
+ )
+ published_root = published_root_for_embedding(kb_dir, signature) if dir_exists else None
indexing_policy = read_published_policy(published_root)
if indexing_policy is None:
pending = kb_config.get("pending_indexing_policy")
diff --git a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py
index 5206a9eca..352834a2b 100644
--- a/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py
+++ b/deeptutor/services/rag/pipelines/lightrag/indexing_policy.py
@@ -434,23 +434,12 @@ def revalidate_snapshot(snapshot: IndexingPolicySnapshot) -> IndexingPolicySnaps
def _bound_published_root(kb_dir: Path) -> Path | None:
"""Use the published version selected by the KB's existing embedding binding."""
from deeptutor.services.config.knowledge_base_config import KnowledgeBaseConfigService
- from deeptutor.services.embedding.config import embedding_config_scope
- from deeptutor.services.rag.embedding_binding import binding_status, bound_graph_storage_root
- from .storage import latest_published_root
+ from .storage import published_root_for_embedding
- latest = latest_published_root(kb_dir)
entry = KnowledgeBaseConfigService(kb_dir.parent / "kb_config.json").get_kb_config(kb_dir.name)
- _, config = binding_status(entry)
- if config is not None:
- with embedding_config_scope(config):
- try:
- return bound_graph_storage_root(kb_dir, "lightrag", latest)
- except ValueError:
- # A rebuild must still be able to replace an incompatible index.
- # Query/append binding checks independently reject this identity.
- pass
- return latest
+ signature = entry.get("embedding_signature") if entry.get("embedding_selection") else None
+ return published_root_for_embedding(kb_dir, signature)
def _target_policy_key(kb_dir: Path) -> str | None:
diff --git a/deeptutor/services/rag/pipelines/lightrag/storage.py b/deeptutor/services/rag/pipelines/lightrag/storage.py
index babb1d461..60f96e271 100644
--- a/deeptutor/services/rag/pipelines/lightrag/storage.py
+++ b/deeptutor/services/rag/pipelines/lightrag/storage.py
@@ -232,6 +232,19 @@ def latest_published_root(kb_dir: Path) -> Path | None:
return None
+def published_root_for_embedding(kb_dir: Path, signature: str | None) -> Path | None:
+ """Find provenance for the recorded binding, even after catalog identity drift."""
+ if signature is None:
+ return latest_published_root(kb_dir)
+ from deeptutor.services.rag.index_versioning import list_kb_versions
+
+ for entry in list_kb_versions(kb_dir):
+ root = Path(entry["storage_path"])
+ if entry.get("embedding_signature") == signature and meta_is_native_published(root):
+ return root
+ return None
+
+
def write_meta(
root_dir: Path,
*,
diff --git a/tests/services/rag/test_lightrag_roles.py b/tests/services/rag/test_lightrag_roles.py
index d2c218547..b004f6938 100644
--- a/tests/services/rag/test_lightrag_roles.py
+++ b/tests/services/rag/test_lightrag_roles.py
@@ -1046,6 +1046,20 @@ def test_append_policy_and_target_follow_older_bound_version(
workspace.mkdir()
(workspace / "kv_store_doc_status.json").write_text('{"doc":{"status":"processed"}}')
second_before = (second / "meta.json").read_bytes()
+ (tmp_path / "kb_config.json").write_text(
+ json.dumps(
+ {
+ "knowledge_bases": {
+ "kb": {
+ "rag_provider": "lightrag",
+ **embedding_binding.binding_fields(
+ {"profile_id": "embedding", "model_id": "a"}, original
+ ),
+ }
+ }
+ }
+ )
+ )
monkeypatch.setattr(embedding_binding, "binding_status", lambda _entry: ("ready", original))
accepted = policy.bind_target(
policy.resolve_write_snapshot(kb, base_dir=str(tmp_path), kb_name="kb"), kb
diff --git a/web/components/knowledge/KbIndexVersionsSection.tsx b/web/components/knowledge/KbIndexVersionsSection.tsx
index b2c5dbd02..e64b86d5a 100644
--- a/web/components/knowledge/KbIndexVersionsSection.tsx
+++ b/web/components/knowledge/KbIndexVersionsSection.tsx
@@ -69,6 +69,10 @@ export default function KbIndexVersionsSection({
const pageIndexProvider = !providerUsesEmbeddingMetadata(provider);
const modelInsensitiveProvider = pageIndexProvider || isLightRag;
const versions = kb.statistics?.index_versions ?? [];
+ const isEmptyEmbeddingKb =
+ needsEmbedding &&
+ kb.statistics?.raw_documents === 0 &&
+ !versions.some((version) => version.ready);
const activeSig = modelInsensitiveProvider
? null
: (kb.statistics?.active_signature ?? null);
@@ -235,7 +239,9 @@ export default function KbIndexVersionsSection({
: t("Re-indexing…")
: isError
? t("Retry indexing")
- : t("Re-index")}
+ : isEmptyEmbeddingKb
+ ? t("Change model")
+ : t("Re-index")}
</button>
)}
</div>
@@ -372,7 +378,13 @@ export default function KbIndexVersionsSection({
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" />}
- {t("Confirm rebuild")}
+ {t(
+ isEmptyEmbeddingKb
+ ? "Save model"
+ : isLightRag
+ ? "Confirm rebuild"
+ : "Start full re-index",
+ )}
</button>
</div>
}
diff --git a/web/tests/kb-embedding-binding.spec.tsx b/web/tests/kb-embedding-binding.spec.tsx
index e6c9b4ddc..48345bba9 100644
--- a/web/tests/kb-embedding-binding.spec.tsx
+++ b/web/tests/kb-embedding-binding.spec.tsx
@@ -56,7 +56,15 @@ beforeEach(() => {
});
fixtures.fetch
.mockReset()
- .mockResolvedValue({ ok: true, json: async () => ({ task_id: "task" }) });
+ .mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ task_id: "task",
+ fingerprint: "confirmed",
+ embedding: { model: "b", dimension: 2 },
+ indexing_policy: { policy: "defaults" },
+ }),
+ });
fixtures.usage.mockReset();
fixtures.lightRagConfig.mockReset().mockResolvedValue({});
fixtures.llmOptions.mockReset().mockReturnValue({
@@ -94,13 +102,7 @@ it("lets a healthy KB explicitly re-index with another configured embedding mode
index_versions: [],
},
} as unknown as KnowledgeBase;
- render(
- <KbIndexVersionsSection
- kb={kb}
- onReindex={onReindex}
- onUpdatePendingIndexingPolicy={vi.fn()}
- />,
- );
+ render(<KbIndexVersionsSection kb={kb} onReindex={onReindex} />);
fireEvent.click(screen.getByRole("button", { name: "Re-index" }));
await waitFor(() =>
expect(
@@ -132,7 +134,6 @@ it("lists affected knowledge bases and explains that deletion preserves their da
it("lets an empty LightRAG KB replace a deleted embedding model before its first upload", async () => {
const onReindex = vi.fn().mockResolvedValue(undefined);
- const onUpdatePendingIndexingPolicy = vi.fn().mockResolvedValue(undefined);
const llm = { profile_id: "chat", model_id: "chat-model" };
fixtures.llmOptions.mockReturnValue({
options: [
@@ -161,13 +162,7 @@ it("lets an empty LightRAG KB replace a deleted embedding model before its first
index_versions: [],
},
} as unknown as KnowledgeBase;
- render(
- <KbIndexVersionsSection
- kb={kb}
- onReindex={onReindex}
- onUpdatePendingIndexingPolicy={onUpdatePendingIndexingPolicy}
- />,
- );
+ render(<KbIndexVersionsSection kb={kb} onReindex={onReindex} />);
fireEvent.click(screen.getByRole("button", { name: "Change model" }));
const picker = await screen.findByRole("combobox", {
name: "Embedding model",
@@ -181,14 +176,7 @@ it("lets an empty LightRAG KB replace a deleted embedding model before its first
expect(screen.getByRole("button", { name: "Save model" })).toBeEnabled(),
);
fireEvent.click(screen.getByRole("button", { name: "Save model" }));
- await waitFor(() =>
- expect(onReindex).toHaveBeenCalledWith(expect.objectContaining(llm), b),
- );
- await waitFor(() =>
- expect(onUpdatePendingIndexingPolicy).toHaveBeenCalledWith(
- expect.objectContaining(llm),
- ),
- );
+ await waitFor(() => expect(onReindex).toHaveBeenCalledWith("confirmed", b));
});
it("sends model IDs on create and re-index without activating a global model", async () => {
@@ -207,7 +195,9 @@ it("sends model IDs on create and re-index without activating a global model", a
});
it("recovers usage after retry and clears the previous model's error", async () => {
- fixtures.usage.mockRejectedValueOnce(new Error("unavailable")).mockResolvedValue([]);
+ fixtures.usage
+ .mockRejectedValueOnce(new Error("unavailable"))
+ .mockResolvedValue([]);
const view = render(<EmbeddingModelUsage profileId="p" modelId="a" />);
await screen.findByRole("alert");
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
diff --git a/web/tests/lightrag-lifecycle.spec.tsx b/web/tests/lightrag-lifecycle.spec.tsx
index 135e77462..82fc0d355 100644
--- a/web/tests/lightrag-lifecycle.spec.tsx
+++ b/web/tests/lightrag-lifecycle.spec.tsx
@@ -190,13 +190,26 @@ it("refreshes confirmation when the selected embedding changes", async () => {
const dialog = screen.getByRole("dialog");
await within(dialog).findByText("embedding-current · 3d");
fixture.preview.mockResolvedValue(preview("selected-b", "embedding-b"));
- fireEvent.change(within(dialog).getByRole("combobox", { name: "Embedding model" }), {
- target: { value: JSON.stringify(["embedding", "b"]) },
- });
+ fireEvent.change(
+ within(dialog).getByRole("combobox", { name: "Embedding model" }),
+ {
+ target: { value: JSON.stringify(["embedding", "b"]) },
+ },
+ );
await within(dialog).findByText("embedding-b · 3d");
- expect(fixture.preview).toHaveBeenLastCalledWith("papers", { profile_id: "embedding", model_id: "b" });
- fireEvent.click(within(dialog).getByRole("button", { name: "Confirm rebuild" }));
- await waitFor(() => expect(submit).toHaveBeenCalledWith("selected-b", { profile_id: "embedding", model_id: "b" }));
+ expect(fixture.preview).toHaveBeenLastCalledWith("papers", {
+ profile_id: "embedding",
+ model_id: "b",
+ });
+ fireEvent.click(
+ within(dialog).getByRole("button", { name: "Confirm rebuild" }),
+ );
+ await waitFor(() =>
+ expect(submit).toHaveBeenCalledWith("selected-b", {
+ profile_id: "embedding",
+ model_id: "b",
+ }),
+ );
});
it("retains upstream embedding action but no role overrides for an empty knowledge base", () => {
@@ -213,7 +226,9 @@ it("retains upstream embedding action but no role overrides for an empty knowled
onReindex={vi.fn()}
/>,
);
- expect(screen.getByRole("button", { name: "Re-index" })).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Change model" }),
+ ).toBeInTheDocument();
expect(screen.queryByText("Index configuration")).not.toBeInTheDocument();
});