DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(lightrag): publish embedding binding under write ownership
NoxsMedia18642ae3e926
diff --git a/deeptutor/services/rag/embedding_binding.py b/deeptutor/services/rag/embedding_binding.pyindex 0433a7cb2..fe337beb9 100644--- a/deeptutor/services/rag/embedding_binding.py+++ b/deeptutor/services/rag/embedding_binding.py@@ -301,9 +301,30 @@ def with_kb_embedding(method):}from deeptutor.services.embedding.config import embedding_config_scope+ locked_publication = entry["rag_provider"] == "lightrag" and method.__name__ != "search"+ if locked_publication:+ expected_binding = (entry.get("embedding_selection"), entry.get("embedding_signature"))++ def validate_binding():+ current = service.get_kb_config(kb_name)+ if (+ current.get("embedding_selection"),+ current.get("embedding_signature"),+ ) != expected_binding:+ raise ValueError(+ "The knowledge-base embedding binding changed before indexing started; resubmit the operation."+ )++ def publish_binding():+ persist_binding(self.kb_base_dir, kb_name, selection, config)++ # LightRAG invokes both callbacks under its existing write ownership.+ kwargs["validate_embedding_binding"] = validate_binding+ kwargs["publish_embedding_binding"] = publish_binding+with embedding_config_scope(config):result = await method(self, *args, **kwargs)- if result and method.__name__ != "search" and selection:+ if result and method.__name__ != "search" and selection and not locked_publication:persist_binding(self.kb_base_dir, kb_name, selection, config)return resultdiff --git a/deeptutor/services/rag/pipelines/lightrag/README.md b/deeptutor/services/rag/pipelines/lightrag/README.mdindex 15da0e824..74cad233a 100644--- a/deeptutor/services/rag/pipelines/lightrag/README.md+++ b/deeptutor/services/rag/pipelines/lightrag/README.md@@ -35,12 +35,14 @@ even when LightRAG requests its COT output format.## Creating, appending and rebuilding-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.+Configure role models in Settings. Creation and full rebuild do not offer per-index+role overrides, but retain per-knowledge-base embedding selection. An idle,+unpublished empty knowledge base follows current valid role defaults until its+first accepted indexing task freezes the configuration, retaining its embedding binding.-Before rebuilding, review the current default embedding model/dimension and-EXTRACT/VLM models and reasoning. If defaults change before submission, review+Before rebuilding, review the selected embedding model/dimension and current default+EXTRACT/VLM models and reasoning. The existing embedding binding is retained unless+another model is selected. If the selected configuration changes before submission, reviewand confirm the refreshed configuration. Accepted tasks retain the same embeddingand role settings through execution and version publication. Failed-task retryactions also use this confirmation flow.diff --git a/deeptutor/services/rag/pipelines/lightrag/pipeline.py b/deeptutor/services/rag/pipelines/lightrag/pipeline.pyindex e69c078ed..6726f5525 100644--- a/deeptutor/services/rag/pipelines/lightrag/pipeline.py+++ b/deeptutor/services/rag/pipelines/lightrag/pipeline.py@@ -373,6 +373,9 @@ class LightRagPipeline:kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)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)@@ -383,7 +386,10 @@ class LightRagPipeline:else "accepted_indexing_snapshot")kwargs[key] = fresh- return await self._initialize_owned(kb_name, file_paths, **kwargs)+ result = await self._initialize_owned(kb_name, file_paths, **kwargs)+ if result and publish_binding is not None:+ publish_binding()+ return resultasync def _initialize_owned(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()@@ -426,6 +432,9 @@ class LightRagPipeline:kb_dir = resolve_kb_dir(self.kb_base_dir, kb_name)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)):@@ -443,7 +452,10 @@ class LightRagPipeline:else "accepted_indexing_snapshot")kwargs[key] = fresh- return await self._add_documents_owned(kb_name, file_paths, **kwargs)+ result = await self._add_documents_owned(kb_name, file_paths, **kwargs)+ if result and publish_binding is not None:+ publish_binding()+ return resultasync def _add_documents_owned(self, kb_name: str, file_paths: List[str], **kwargs) -> bool:self._ensure_available()diff --git a/tests/services/rag/test_embedding_binding.py b/tests/services/rag/test_embedding_binding.pyindex fa34e042c..481331202 100644--- a/tests/services/rag/test_embedding_binding.py+++ b/tests/services/rag/test_embedding_binding.py@@ -77,6 +77,107 @@ def read_entry(root, name="kb"):return json.loads((root / "kb_config.json").read_text())["knowledge_bases"][name][email protected]("fail_publication", [False, True])+async def test_lightrag_rebuild_persists_binding_after_meta_under_write_ownership(+ catalog, tmp_path, monkeypatch, fail_publication+):+ 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++ write_entry(tmp_path, rag_provider="lightrag")+ service = RAGService(kb_base_dir=str(tmp_path))+ pipeline = pipeline_module.LightRagPipeline(str(tmp_path))+ service._pipelines["lightrag"] = pipeline+ monkeypatch.setattr(pipeline, "_ensure_available", lambda: None)+ monkeypatch.setattr(+ pipeline_module,+ "freeze_default_snapshot",+ lambda: SimpleNamespace(embedding_config=get_embedding_config()),+ )++ async def finish_index(root, *_args):+ (root / "kv_store_doc_status.json").write_text(+ json.dumps({"doc": {"status": "processed", "chunks_list": ["chunk"]}})+ )+ return pipeline_module.BatchOutcome(+ requested=1,+ accepted=1,+ processed=("doc",),+ indexing_policy={"policy": "legacy_unpinned"},+ )++ monkeypatch.setattr(pipeline, "_run_indexing", finish_index)+ original_persist = binding.persist_binding+ calls = []++ 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"+ 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)+ original_persist(*args)++ monkeypatch.setattr(binding, "persist_binding", persist)+ if fail_publication:++ def fail_meta(*args, **kwargs):+ raise OSError("publication failed")++ monkeypatch.setattr(storage, "write_meta", fail_meta)+ with pytest.raises(OSError, match="publication failed"):+ await service.initialize("kb", ["doc"], embedding_selection=selection("b"))+ assert calls == []+ assert read_entry(tmp_path)["embedding_selection"] == selection("a")+ else:+ assert await service.initialize("kb", ["doc"], embedding_selection=selection("b"))+ assert calls == [True]+ assert read_entry(tmp_path)["embedding_selection"] == selection("b")+ with write_ownership(tmp_path / "kb"):+ pass # Ownership is released on success and failure.++[email protected]("operation", ["initialize", "add_documents"])+async def test_lightrag_rejects_binding_changed_between_resolution_and_write_lock(+ catalog, tmp_path, monkeypatch, operation+):+ from contextlib import contextmanager++ from deeptutor.services.rag.pipelines.lightrag import write_lock+ from deeptutor.services.rag.pipelines.lightrag.pipeline import LightRagPipeline++ write_entry(tmp_path, rag_provider="lightrag")+ service = RAGService(kb_base_dir=str(tmp_path))+ pipeline = LightRagPipeline(str(tmp_path))+ service._pipelines["lightrag"] = pipeline+ original_lock = write_lock.write_ownership++ @contextmanager+ def changed_before_lock(kb_dir):+ # Another worker completed its rebuild after decorator resolution.+ binding.persist_binding(+ tmp_path, "kb", selection("b"), get_embedding_config(selection("b"))+ )+ with original_lock(kb_dir):+ yield++ async def unexpected(*args, **kwargs):+ pytest.fail("Stale binding must be rejected before any index write")++ monkeypatch.setattr(write_lock, "write_ownership", changed_before_lock)+ monkeypatch.setattr(pipeline, "_initialize_owned", unexpected)+ monkeypatch.setattr(pipeline, "_add_documents_owned", unexpected)+ with pytest.raises(ValueError, match="binding changed before indexing started"):+ await getattr(service, operation)("kb", ["doc"])+ assert read_entry(tmp_path)["embedding_selection"] == selection("b")++def test_default_change_and_key_rotation_do_not_invalidate_binding(catalog, tmp_path):entry = write_entry(tmp_path)catalog["services"]["embedding"]["active_model_id"] = "b"