Skip to content

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

fix(lightrag): withdraw failed rebuild publication and align provenance

NoxsMedia26a63c76bce0
diff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.py
index 6726f5525..c80620d50 100644
--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py
+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py
@@ -375,7 +375,6 @@ class LightRagPipeline:
with write_ownership(kb_dir):
if validate_binding := kwargs.pop("validate_embedding_binding", None):
validate_binding()
- publish_binding = kwargs.pop("publish_embedding_binding", None)
snapshot = kwargs.get("indexing_snapshot") or kwargs.get("accepted_indexing_snapshot")
if snapshot is not None:
indexing_policy.validate_target(snapshot, kb_dir)
@@ -386,10 +385,26 @@ class LightRagPipeline:
else "accepted_indexing_snapshot"
)
kwargs[key] = fresh
- result = await self._initialize_owned(kb_name, file_paths, **kwargs)
- if result and publish_binding is not None:
+ return await self._initialize_owned(kb_name, file_paths, **kwargs)
+
+ def _publish_new_version(
+ self,
+ root_dir: Path,
+ policy: dict[str, Any],
+ embedding_config: Any,
+ publish_binding: Callable[[], None] | None,
+ ) -> None:
+ storage.write_meta(root_dir, indexing_policy=policy, embedding_config=embedding_config)
+ try:
+ if publish_binding is not None:
publish_binding()
- return result
+ except BaseException:
+ # A same-embedding rebuild would otherwise become the newest
+ # compatible version even though its binding publication failed.
+ # Withdraw only this new candidate's publication marker; retain
+ # its data and the previous version for recovery.
+ (root_dir / "meta.json").unlink()
+ raise
async def _initialize_owned(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
self._ensure_available()
@@ -412,8 +427,11 @@ 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, embedding_config=snapshot.embedding_config
+ self._publish_new_version(
+ root_dir,
+ policy,
+ snapshot.embedding_config,
+ kwargs.get("publish_embedding_binding") if outcome.complete else None,
)
self._clear_pending_policy(kb_name)
return outcome.complete
@@ -434,7 +452,6 @@ class LightRagPipeline:
with write_ownership(kb_dir):
if validate_binding := kwargs.pop("validate_embedding_binding", None):
validate_binding()
- publish_binding = kwargs.pop("publish_embedding_binding", None)
if kwargs.get("indexing_snapshot") is not None and (
storage.latest_published_root(kb_dir) is not None or list_kb_versions(kb_dir)
):
@@ -452,10 +469,7 @@ class LightRagPipeline:
else "accepted_indexing_snapshot"
)
kwargs[key] = fresh
- result = await self._add_documents_owned(kb_name, file_paths, **kwargs)
- if result and publish_binding is not None:
- publish_binding()
- return result
+ return await self._add_documents_owned(kb_name, file_paths, **kwargs)
async def _add_documents_owned(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:
self._ensure_available()
@@ -499,8 +513,11 @@ 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, embedding_config=snapshot.embedding_config
+ self._publish_new_version(
+ root_dir,
+ policy,
+ snapshot.embedding_config,
+ kwargs.get("publish_embedding_binding") if outcome.complete else None,
)
self._clear_pending_policy(kb_name)
else:
@@ -515,6 +532,10 @@ class LightRagPipeline:
"existing published policy",
exc_info=True,
)
+ if outcome.complete and (
+ publish_binding := kwargs.get("publish_embedding_binding")
+ ):
+ publish_binding()
return outcome.complete
except LightRagBatchError as exc:
if not is_update and exc.outcome.accepted == 0:
diff --git a/tests/services/rag/test_embedding_binding.py b/tests/services/rag/test_embedding_binding.py
index 481331202..e1c622130 100644
--- a/tests/services/rag/test_embedding_binding.py
+++ b/tests/services/rag/test_embedding_binding.py
@@ -78,16 +78,23 @@ def read_entry(root, name="kb"):
@pytest.mark.asyncio
[email protected]("fail_publication", [False, True])
[email protected]("failure", [None, "metadata", "binding"])
[email protected]("target_model", ["a", "b"])
async def test_lightrag_rebuild_persists_binding_after_meta_under_write_ownership(
- catalog, tmp_path, monkeypatch, fail_publication
+ catalog, tmp_path, monkeypatch, failure, target_model
):
+ from deeptutor.services.rag.pipelines.lightrag import engine, storage
from deeptutor.services.rag.pipelines.lightrag import pipeline as pipeline_module
- from deeptutor.services.rag.pipelines.lightrag import storage
from deeptutor.services.rag.pipelines.lightrag.indexing_policy import IndexingPolicyError
from deeptutor.services.rag.pipelines.lightrag.write_lock import write_ownership
+ monkeypatch.setattr(engine, "installed_version", lambda: "synthetic-test-version")
write_entry(tmp_path, rag_provider="lightrag")
+ old = tmp_path / "kb" / "version-1"
+ old.mkdir()
+ (old / "kv_store_doc_status.json").write_text('{"old":{"status":"processed"}}')
+ storage.write_meta(old, embedding_config=get_embedding_config(selection("a")))
+ old_meta = (old / "meta.json").read_bytes()
service = RAGService(kb_base_dir=str(tmp_path))
pipeline = pipeline_module.LightRagPipeline(str(tmp_path))
service._pipelines["lightrag"] = pipeline
@@ -116,28 +123,44 @@ async def test_lightrag_rebuild_persists_binding_after_meta_under_write_ownershi
def persist(*args):
root = storage.latest_published_root(tmp_path / "kb")
assert root is not None
- assert json.loads((root / "meta.json").read_text())["embedding_model"] == "embed-b"
+ assert (
+ json.loads((root / "meta.json").read_text())["embedding_model"]
+ == f"embed-{target_model}"
+ )
with pytest.raises(IndexingPolicyError, match="Another indexing operation"):
with write_ownership(tmp_path / "kb"):
pytest.fail("Binding publication must retain indexing ownership")
calls.append(True)
+ if failure == "binding":
+ raise OSError("binding publication failed")
original_persist(*args)
monkeypatch.setattr(binding, "persist_binding", persist)
- if fail_publication:
+ if failure == "metadata":
def fail_meta(*args, **kwargs):
raise OSError("publication failed")
monkeypatch.setattr(storage, "write_meta", fail_meta)
+ if failure:
with pytest.raises(OSError, match="publication failed"):
- await service.initialize("kb", ["doc"], embedding_selection=selection("b"))
- assert calls == []
+ await service.initialize("kb", ["doc"], embedding_selection=selection(target_model))
+ assert calls == ([True] if failure == "binding" else [])
assert read_entry(tmp_path)["embedding_selection"] == selection("a")
+ assert storage.latest_published_root(tmp_path / "kb") == old
+ assert (
+ storage.published_root_for_embedding(
+ tmp_path / "kb", read_entry(tmp_path)["embedding_signature"]
+ )
+ == old
+ )
+ assert not (tmp_path / "kb" / "version-2" / "meta.json").exists()
+ assert (old / "meta.json").read_bytes() == old_meta
else:
- assert await service.initialize("kb", ["doc"], embedding_selection=selection("b"))
+ assert await service.initialize("kb", ["doc"], embedding_selection=selection(target_model))
assert calls == [True]
- assert read_entry(tmp_path)["embedding_selection"] == selection("b")
+ assert read_entry(tmp_path)["embedding_selection"] == selection(target_model)
+ assert storage.latest_published_root(tmp_path / "kb").name == "version-2"
with write_ownership(tmp_path / "kb"):
pass # Ownership is released on success and failure.
diff --git a/web/components/knowledge/KbDocumentsSection.tsx b/web/components/knowledge/KbDocumentsSection.tsx
index 6a6880164..c7ec96e48 100644
--- a/web/components/knowledge/KbDocumentsSection.tsx
+++ b/web/components/knowledge/KbDocumentsSection.tsx
@@ -1,12 +1,9 @@
-"use client";
+'use client'
-import { useEffect, useState } from "react";
-import { useTranslation } from "react-i18next";
-import { FolderInput, Loader2, RefreshCw, Upload } from "lucide-react";
-import {
- listKnowledgeBaseFiles,
- type KnowledgeUploadPolicy,
-} from "@/features/knowledge/api/files";
+import { useEffect, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { FolderInput, Loader2, RefreshCw, Upload } from 'lucide-react'
+import { listKnowledgeBaseFiles, type KnowledgeUploadPolicy } from '@/features/knowledge/api/files'
import {
kbCanUploadDocuments,
kbNeedsReindex,
@@ -16,22 +13,22 @@ import {
uploadPolicyForProvider,
validateFiles,
type KnowledgeBase,
-} from "@/lib/knowledge-helpers";
-import type { TaskState } from "@/hooks/useKnowledgeProgress";
-import type { HistoryEntry } from "@/hooks/useKnowledgeHistory";
-import FileDropZone from "./FileDropZone";
-import KbIndexFailureBanner from "./KbIndexFailureBanner";
-import KbUpdateHistory from "./KbUpdateHistory";
-import LightRagIndexingProvenance from "./LightRagIndexingProvenance";
+} from '@/lib/knowledge-helpers'
+import type { TaskState } from '@/hooks/useKnowledgeProgress'
+import type { HistoryEntry } from '@/hooks/useKnowledgeHistory'
+import FileDropZone from './FileDropZone'
+import KbIndexFailureBanner from './KbIndexFailureBanner'
+import KbUpdateHistory from './KbUpdateHistory'
+import LightRagIndexingProvenance from './LightRagIndexingProvenance'
interface KbDocumentsSectionProps {
- kb: KnowledgeBase;
- uploadPolicy: KnowledgeUploadPolicy;
- task?: TaskState;
- history: HistoryEntry[];
- onClearHistory: () => void;
- onRetry?: () => Promise<void>;
- onUpload: (files: File[], destSubdir?: string) => Promise<void>;
+ kb: KnowledgeBase
+ uploadPolicy: KnowledgeUploadPolicy
+ task?: TaskState
+ history: HistoryEntry[]
+ onClearHistory: () => void
+ onRetry?: () => Promise<void>
+ onUpload: (files: File[], destSubdir?: string) => Promise<void>
}
/**
@@ -49,131 +46,119 @@ export default function KbDocumentsSection({
onRetry,
onUpload,
}: KbDocumentsSectionProps) {
- const { t } = useTranslation();
- const [files, setFiles] = useState<File[]>([]);
- const [submitting, setSubmitting] = useState(false);
- const [retrySubmitting, setRetrySubmitting] = useState(false);
+ const { t } = useTranslation()
+ const [files, setFiles] = useState<File[]>([])
+ const [submitting, setSubmitting] = useState(false)
+ const [retrySubmitting, setRetrySubmitting] = useState(false)
// Existing folders in this KB, offered as a destination for the batch.
- const [folders, setFolders] = useState<string[]>([]);
- const [destSubdir, setDestSubdir] = useState("");
+ const [folders, setFolders] = useState<string[]>([])
+ const [destSubdir, setDestSubdir] = useState('')
useEffect(() => {
- let cancelled = false;
+ let cancelled = false
void listKnowledgeBaseFiles(kb.name)
- .then((entries) => {
- if (cancelled) return;
+ .then(entries => {
+ if (cancelled) return
setFolders(
entries
- .filter((entry) => entry.type === "folder")
- .map((entry) => entry.name)
- .sort((a, b) => a.localeCompare(b)),
- );
+ .filter(entry => entry.type === 'folder')
+ .map(entry => entry.name)
+ .sort((a, b) => a.localeCompare(b))
+ )
})
.catch(() => {
// A destination picker is an optional convenience; failing to list
// folders just means the batch goes to the root as it always did.
- if (!cancelled) setFolders([]);
- });
+ if (!cancelled) setFolders([])
+ })
return () => {
- cancelled = true;
- };
- }, [kb.name]);
-
- const needsReindex = kbNeedsReindex(kb);
- const requiresLightRagRebuild = kbRequiresLightRagRebuildBeforeAppend(kb);
- const status = resolveKbStatus(kb);
- const isError = status === "error";
- const provider =
- kb.statistics?.rag_provider || kb.metadata?.rag_provider || "llamaindex";
- const policyForProvider = uploadPolicyForProvider(uploadPolicy, provider);
+ cancelled = true
+ }
+ }, [kb.name])
+
+ const needsReindex = kbNeedsReindex(kb)
+ const requiresLightRagRebuild = kbRequiresLightRagRebuildBeforeAppend(kb)
+ const status = resolveKbStatus(kb)
+ const isError = status === 'error'
+ const provider = kb.statistics?.rag_provider || kb.metadata?.rag_provider || 'llamaindex'
+ const policyForProvider = uploadPolicyForProvider(uploadPolicy, provider)
const publishedLightRagVersion =
- provider === "lightrag"
+ provider === 'lightrag'
? kb.statistics?.index_versions?.find(
- (version) => version.provider === "lightrag" && version.ready,
+ version =>
+ version.provider === 'lightrag' &&
+ version.ready &&
+ (!kb.metadata?.embedding_selection || version.version === kb.metadata.indexed_version)
)
- : undefined;
+ : undefined
- const isUploadingHere = task?.kind === "upload" && task.executing;
- const isIndexingHere =
- (task?.kind === "reindex" || task?.kind === "retry") && task.executing;
- const isRetryingHere = task?.kind === "retry" && task.executing;
+ const isUploadingHere = task?.kind === 'upload' && task.executing
+ const isIndexingHere = (task?.kind === 'reindex' || task?.kind === 'retry') && task.executing
+ const isRetryingHere = task?.kind === 'retry' && task.executing
// An error-state KB is not locked: the user can drop the file(s) that failed
// (Files tab) and upload replacements here, instead of being forced to
// delete and rebuild the whole base. Uploads stay open unless a rebuild is
// actively running; legacy/transition states remain genuinely blocked.
- const canUpload = kbCanUploadDocuments(kb, isIndexingHere);
+ const canUpload = kbCanUploadDocuments(kb, isIndexingHere)
const blockedReason = canUpload
? null
: kb.metadata?.indexing_model_unavailable
+ ? t('Restore access to the pinned indexing models in Settings before adding documents.')
+ : requiresLightRagRebuild
? t(
- "Restore access to the pinned indexing models in Settings before adding documents.",
+ 'This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.'
)
- : requiresLightRagRebuild
- ? t(
- "This legacy LightRAG index remains queryable, but it must be fully rebuilt before incremental uploads.",
- )
- : 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;
+ : 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
// Unsupported files are skipped (shown in the drop zone), not blocking, so a
// picked folder with mixed content still uploads its supported members.
- const canSubmit =
- canUpload &&
- selection.validFiles.length > 0 &&
- !submitting &&
- !isUploadingHere;
+ const canSubmit = canUpload && selection.validFiles.length > 0 && !submitting && !isUploadingHere
const handleSubmit = async () => {
- if (!canSubmit) return;
- setSubmitting(true);
+ if (!canSubmit) return
+ setSubmitting(true)
try {
- await onUpload(selection.validFiles, destSubdir || undefined);
- setFiles([]);
+ await onUpload(selection.validFiles, destSubdir || undefined)
+ setFiles([])
} finally {
- setSubmitting(false);
+ setSubmitting(false)
}
- };
+ }
const handleRetry = async () => {
- if (!onRetry || !canRetry || retrySubmitting) return;
- setRetrySubmitting(true);
+ if (!onRetry || !canRetry || retrySubmitting) return
+ setRetrySubmitting(true)
try {
- await onRetry();
+ await onRetry()
} finally {
- setRetrySubmitting(false);
+ setRetrySubmitting(false)
}
- };
+ }
return (
<div className="space-y-5">
<div>
- <div className="text-[13px] font-medium text-[var(--foreground)]">
- {t("Add documents")}
- </div>
+ <div className="text-[13px] font-medium text-[var(--foreground)]">{t('Add documents')}</div>
<p className="mt-0.5 text-[11.5px] text-[var(--muted-foreground)]">
{t(
providerUsesEmbeddingMetadata(provider)
- ? "Drop files here to add them to this knowledge base. New files use its bound embedding model."
- : "Drop files here",
+ ? 'Drop files here to add them to this knowledge base. New files use its bound embedding model.'
+ : 'Drop files here'
)}
</p>
</div>
- {provider === "lightrag" && publishedLightRagVersion && (
+ {provider === 'lightrag' && publishedLightRagVersion && (
<LightRagIndexingProvenance
policy={kb.metadata?.indexing_policy}
version={publishedLightRagVersion}
@@ -204,12 +189,8 @@ export default function KbDocumentsSection({
<RefreshCw className="h-3 w-3" />
)}
{retrySubmitting || isRetryingHere
- ? t("Retrying…")
- : t(
- provider === "lightrag"
- ? "Review rebuild"
- : "Retry indexing",
- )}
+ ? t('Retrying…')
+ : t(provider === 'lightrag' ? 'Review rebuild' : 'Retry indexing')}
</button>
) : undefined
}
@@ -226,15 +207,15 @@ export default function KbDocumentsSection({
{folders.length > 0 && files.length > 0 && (
<label className="flex items-center gap-2 text-[12px] text-[var(--muted-foreground)]">
<FolderInput size={13} strokeWidth={1.7} />
- <span>{t("Add to folder")}</span>
+ <span>{t('Add to folder')}</span>
<select
value={destSubdir}
- onChange={(event) => setDestSubdir(event.target.value)}
+ onChange={event => setDestSubdir(event.target.value)}
disabled={!canUpload || isUploadingHere}
className="min-w-0 flex-1 rounded-md border border-[var(--border)] bg-[var(--background)] px-2 py-1 text-[12px] text-[var(--foreground)] disabled:opacity-40"
>
- <option value="">{t("Knowledge base root")}</option>
- {folders.map((folder) => (
+ <option value="">{t('Knowledge base root')}</option>
+ {folders.map(folder => (
<option key={folder} value={folder}>
{folder}
</option>
@@ -255,11 +236,11 @@ export default function KbDocumentsSection({
) : (
<Upload size={14} />
)}
- {t("Upload")}
+ {t('Upload')}
</button>
</div>
<KbUpdateHistory entries={history} onClear={onClearHistory} />
</div>
- );
+ )
}
diff --git a/web/tests/lightrag-lifecycle.spec.tsx b/web/tests/lightrag-lifecycle.spec.tsx
index 82fc0d355..4078df61d 100644
--- a/web/tests/lightrag-lifecycle.spec.tsx
+++ b/web/tests/lightrag-lifecycle.spec.tsx
@@ -1,54 +1,46 @@
-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";
+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 KbDocumentsSection from '@/components/knowledge/KbDocumentsSection'
+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")>()),
+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",
- };
+ 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: "",
+ 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" },
+ 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 },
+ 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(),
@@ -56,18 +48,18 @@ const fixture = vi.hoisted(() => {
options: [
{
...selection,
- model_name: "Model one",
- model: "one",
- profile_name: "Provider",
- provider: "custom",
+ 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", () => ({
+ }
+})
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: fixture.t }) }))
+vi.mock('@/hooks/useLLMOptions', () => ({
useLLMOptions: () => ({
options: fixture.options,
activeDefault: fixture.selection,
@@ -75,170 +67,185 @@ vi.mock("@/hooks/useLLMOptions", () => ({
error: false,
refresh: fixture.refresh,
}),
-}));
-vi.mock("@/features/knowledge/api/engines", async (original) => ({
- ...(await original<typeof import("@/features/knowledge/api/engines")>()),
+}))
+vi.mock('@/features/knowledge/api/engines', async original => ({
+ ...(await original<typeof import('@/features/knowledge/api/engines')>()),
getLightRagConfig: async () => structuredClone(fixture.config),
getEngineModelOptions: async () => ({
embedding: {
- active: { profile_id: "embedding", model_id: "a" },
- options: ["a", "b"].map((model_id) => ({
- profile_id: "embedding",
+ active: { profile_id: 'embedding', model_id: 'a' },
+ options: ['a', 'b'].map(model_id => ({
+ profile_id: 'embedding',
model_id,
label: `Embedding ${model_id}`,
- profile_name: "Provider",
+ profile_name: 'Provider',
})),
},
}),
-}));
-vi.mock("@/features/knowledge/api/catalog", async (original) => ({
- ...(await original<typeof import("@/features/knowledge/api/catalog")>()),
+}))
+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");
+ throw new Error('use default upload policy')
},
-}));
+}))
const policy = {
- policy: "pinned",
+ policy: 'pinned',
schema_version: 2,
extract: {
- policy: "pinned",
+ policy: 'pinned',
descriptor: {
- model: "Extract model",
- binding: "custom",
- reasoning_effort: "none",
+ model: 'Extract model',
+ binding: 'custom',
+ reasoning_effort: 'none',
},
},
- vlm: { mode: "disabled" as const },
-};
+ vlm: { mode: 'disabled' as const },
+}
const kb: KnowledgeBase = {
- name: "papers",
- status: "ready",
+ name: 'papers',
+ status: 'ready',
metadata: { indexing_policy: policy },
statistics: {
- rag_provider: "lightrag",
+ rag_provider: 'lightrag',
raw_documents: 2,
index_versions: [
{
- version: "version-3",
- signature: "lightrag",
- provider: "lightrag",
+ version: 'version-3',
+ signature: 'lightrag',
+ provider: 'lightrag',
ready: true,
- embedding_model: "embedding-old",
+ embedding_model: 'embedding-old',
embedding_dim: 3,
indexing_policy: policy,
},
],
},
-};
-const preview = (fingerprint: string, model = "embedding-current") => ({
+}
+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 };
-});
+ fixture.preview.mockReset().mockResolvedValue(preview('first'))
+ fixture.config.role_models.base = { ...fixture.selection }
+})
-it("shows version identifiers and embedding selection with read-only role confirmation, then requires reconfirmation after drift", async () => {
- const submit = vi
- .fn()
- .mockRejectedValueOnce(new Error("Default configuration changed"));
- render(<KbIndexVersionsSection kb={kb} onReindex={submit} />);
- expect(screen.getByText("version-3")).toBeInTheDocument();
- fireEvent.click(screen.getByRole("button", { name: "Re-index" }));
- const dialog = screen.getByRole("dialog");
- await within(dialog).findByText("embedding-current · 3d");
- expect(
- within(dialog).getByRole("combobox", { name: "Embedding model" }),
- ).toBeInTheDocument();
- fixture.preview.mockResolvedValue(preview("second", "embedding-new"));
- fireEvent.click(
- within(dialog).getByRole("button", { name: "Confirm rebuild" }),
- );
- await within(dialog).findByText("embedding-new · 3d");
- expect(submit).toHaveBeenCalledExactlyOnceWith("first", {
- profile_id: "embedding",
- model_id: "a",
- });
- expect(
- within(dialog).getByText("Default configuration changed"),
- ).toBeInTheDocument();
- submit.mockResolvedValue(undefined);
- fireEvent.click(
- within(dialog).getByRole("button", { name: "Confirm rebuild" }),
- );
- await waitFor(() =>
- expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
- );
- expect(submit).toHaveBeenLastCalledWith("second", {
- profile_id: "embedding",
- model_id: "a",
- });
-});
-
-it("refreshes confirmation when the selected embedding changes", async () => {
- const submit = vi.fn(async () => {});
- render(<KbIndexVersionsSection kb={kb} onReindex={submit} />);
- fireEvent.click(screen.getByRole("button", { name: "Re-index" }));
- const dialog = screen.getByRole("dialog");
- await within(dialog).findByText("embedding-current · 3d");
- fixture.preview.mockResolvedValue(preview("selected-b", "embedding-b"));
- fireEvent.change(
- within(dialog).getByRole("combobox", { name: "Embedding model" }),
- {
- target: { value: JSON.stringify(["embedding", "b"]) },
+it('keeps Documents embedding and role provenance on the same bound historical version', async () => {
+ const bound: KnowledgeBase = {
+ ...kb,
+ metadata: {
+ ...kb.metadata,
+ embedding_selection: { profile_id: 'embedding', model_id: 'a' },
+ indexed_version: 'version-3',
},
- );
- 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" }),
- );
+ statistics: {
+ ...kb.statistics,
+ index_versions: [
+ {
+ ...kb.statistics!.index_versions![0],
+ version: 'version-4',
+ embedding_model: 'unrelated-newer',
+ },
+ ...kb.statistics!.index_versions!,
+ ],
+ },
+ }
+ render(
+ <KbDocumentsSection
+ kb={bound}
+ uploadPolicy={DEFAULT_UPLOAD_POLICY}
+ history={[]}
+ onClearHistory={() => {}}
+ onUpload={async () => {}}
+ />
+ )
+ expect(await screen.findByText('embedding-old · 3d')).toBeInTheDocument()
+ expect(screen.getByText(/Extract model/)).toBeInTheDocument()
+ expect(screen.queryByText(/unrelated-newer/)).not.toBeInTheDocument()
+})
+
+it('shows version identifiers and embedding selection with read-only role confirmation, then requires reconfirmation after drift', async () => {
+ const submit = vi.fn().mockRejectedValueOnce(new Error('Default configuration changed'))
+ render(<KbIndexVersionsSection kb={kb} onReindex={submit} />)
+ expect(screen.getByText('version-3')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'Re-index' }))
+ const dialog = screen.getByRole('dialog')
+ await within(dialog).findByText('embedding-current · 3d')
+ expect(within(dialog).getByRole('combobox', { name: 'Embedding model' })).toBeInTheDocument()
+ fixture.preview.mockResolvedValue(preview('second', 'embedding-new'))
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Confirm rebuild' }))
+ await within(dialog).findByText('embedding-new · 3d')
+ expect(submit).toHaveBeenCalledExactlyOnceWith('first', {
+ profile_id: 'embedding',
+ model_id: 'a',
+ })
+ expect(within(dialog).getByText('Default configuration changed')).toBeInTheDocument()
+ submit.mockResolvedValue(undefined)
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Confirm rebuild' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(submit).toHaveBeenLastCalledWith('second', {
+ profile_id: 'embedding',
+ model_id: 'a',
+ })
+})
+
+it('refreshes confirmation when the selected embedding changes', async () => {
+ const submit = vi.fn(async () => {})
+ render(<KbIndexVersionsSection kb={kb} onReindex={submit} />)
+ fireEvent.click(screen.getByRole('button', { name: 'Re-index' }))
+ const dialog = screen.getByRole('dialog')
+ await within(dialog).findByText('embedding-current · 3d')
+ fixture.preview.mockResolvedValue(preview('selected-b', 'embedding-b'))
+ fireEvent.change(within(dialog).getByRole('combobox', { name: 'Embedding model' }), {
+ target: { value: JSON.stringify(['embedding', 'b']) },
+ })
+ await within(dialog).findByText('embedding-b · 3d')
+ expect(fixture.preview).toHaveBeenLastCalledWith('papers', {
+ profile_id: 'embedding',
+ model_id: 'b',
+ })
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Confirm rebuild' }))
await waitFor(() =>
- expect(submit).toHaveBeenCalledWith("selected-b", {
- profile_id: "embedding",
- model_id: "b",
- }),
- );
-});
+ 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", () => {
+it('retains upstream embedding action but no role overrides for an empty knowledge base', () => {
render(
<KbIndexVersionsSection
kb={{
...kb,
statistics: {
- rag_provider: "lightrag",
+ rag_provider: 'lightrag',
raw_documents: 0,
index_versions: [],
},
}}
onReindex={vi.fn()}
- />,
- );
- expect(
- screen.getByRole("button", { name: "Change model" }),
- ).toBeInTheDocument();
- expect(screen.queryByText("Index configuration")).not.toBeInTheDocument();
-});
+ />
+ )
+ expect(screen.getByRole('button', { name: 'Change model' })).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) => {});
+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" }]}
+ providers={[{ id: 'lightrag', name: 'LightRAG', description: 'Graph' }]}
uploadPolicy={DEFAULT_UPLOAD_POLICY}
onCreate={create}
onConnectLinkedFolder={vi.fn()}
@@ -247,35 +254,31 @@ it("refreshes all four default roles on return from settings and creates without
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");
-});
+ />
+ )
+ 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"));
+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" }}
+ kb={{ ...kb, status: 'error' }}
uploadPolicy={DEFAULT_UPLOAD_POLICY}
history={[]}
onCreate={vi.fn()}
@@ -285,36 +288,32 @@ it.each(["header", "documents"])(
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", {
- profile_id: "embedding",
- model_id: "a",
- });
- reindex.mockResolvedValue(undefined);
- fireEvent.click(
- within(dialog).getByRole("button", { name: "Confirm rebuild" }),
- );
+ />
+ )
+ 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', {
+ profile_id: 'embedding',
+ model_id: 'a',
+ })
+ reindex.mockResolvedValue(undefined)
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Confirm rebuild' }))
await waitFor(() =>
- expect(reindex).toHaveBeenLastCalledWith("papers", "retry-new", {
- profile_id: "embedding",
- model_id: "a",
- }),
- );
- expect(retry).not.toHaveBeenCalled();
- },
-);
+ expect(reindex).toHaveBeenLastCalledWith('papers', 'retry-new', {
+ profile_id: 'embedding',
+ model_id: 'a',
+ })
+ )
+ expect(retry).not.toHaveBeenCalled()
+ }
+)