Skip to content

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

fix: harden post-merge cleanup and image loading (#872)

Bingxi Zhaoed6e552f953f
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index 27bba1720..360abd056 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -1402,7 +1402,14 @@ class KnowledgeBaseManager:
# leaving the KB stuck in the list is worse than orphan files on
# disk (issue #370).
try:
- os.chmod(path, stat.S_IWRITE)
+ current_mode = os.stat(path).st_mode
+ writable_mode = current_mode | stat.S_IWRITE
+ if stat.S_ISDIR(current_mode):
+ # POSIX directories need execute permission to remain
+ # traversable. Replacing the whole mode with S_IWRITE
+ # leaves an orphan that even later cleanup cannot enter.
+ writable_mode |= stat.S_IXUSR
+ os.chmod(path, writable_mode)
func(path)
except Exception as retry_exc:
logger.warning(
diff --git a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
index eb690b644..d4809900b 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/document_loader.py
@@ -150,29 +150,34 @@ class LlamaIndexDocumentLoader:
return images
async def _load_image_nodes(self, sources: list[_ImageSource]) -> list[ImageNode]:
- embedding_client = get_embedding_client()
- llm_client = get_llm_client()
-
- unsupported_reasons = []
+ try:
+ embedding_client = get_embedding_client()
+ except Exception as exc:
+ self._log_skipped_images(sources, f"embedding client is unavailable ({exc})")
+ return []
if not embedding_client.supports_multimodal_contents():
- unsupported_reasons.append(
+ self._log_skipped_images(
+ sources,
"embedding provider/model does not support multimodal contents "
f"(binding={embedding_client.config.binding}, "
- f"model={embedding_client.config.model})"
+ f"model={embedding_client.config.model})",
)
+ return []
+
+ # Resolve the LLM only after the embedding prerequisite passes. This
+ # keeps text-only embedding setups independent of LLM configuration and
+ # reuses one client for the whole image batch.
+ try:
+ llm_client = get_llm_client()
+ except Exception as exc:
+ self._log_skipped_images(sources, f"LLM client is unavailable ({exc})")
+ return []
if not llm_client.supports_multimodal_images():
- unsupported_reasons.append(
+ self._log_skipped_images(
+ sources,
"LLM provider/model does not support multimodal image input "
- f"(binding={llm_client.config.binding}, model={llm_client.config.model})"
+ f"(binding={llm_client.config.binding}, model={llm_client.config.model})",
)
- if unsupported_reasons:
- reason_text = "; ".join(unsupported_reasons)
- for source in sources:
- self.logger.warning(
- "Skipped image because image indexing requires both "
- f"multimodal embedding and multimodal LLM support; {reason_text}: "
- f"{source.path.name}"
- )
return []
embedded: list[_ImageSource] = []
@@ -182,6 +187,7 @@ class LlamaIndexDocumentLoader:
try:
image_payload = self._load_image_payload(source.path)
description = await self._describe_image(
+ llm_client,
source.path,
image_payload["base64"],
image_payload["mimetype"],
@@ -241,8 +247,16 @@ class LlamaIndexDocumentLoader:
self.logger.info(f"Loaded image: {source.path.name} ({len(embedding)}D vector)")
return nodes
- async def _describe_image(self, file_path: Path, image_base64: str, mimetype: str) -> str:
- llm_client = get_llm_client()
+ def _log_skipped_images(self, sources: list[_ImageSource], reason: str) -> None:
+ for source in sources:
+ self.logger.warning(
+ "Skipped image because image indexing requires both multimodal "
+ f"embedding and multimodal LLM support; {reason}: {source.path.name}"
+ )
+
+ async def _describe_image(
+ self, llm_client: Any, file_path: Path, image_base64: str, mimetype: str
+ ) -> str:
response = await llm_client.complete(
IMAGE_DESCRIPTION_PROMPT,
system_prompt=IMAGE_DESCRIPTION_SYSTEM_PROMPT,
diff --git a/tests/knowledge/test_manager_delete.py b/tests/knowledge/test_manager_delete.py
index d98d7eeca..0dfa5b0d7 100644
--- a/tests/knowledge/test_manager_delete.py
+++ b/tests/knowledge/test_manager_delete.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import json
from pathlib import Path
+import stat
import pytest
@@ -59,6 +60,8 @@ def test_delete_knowledge_base_clears_config_when_rmtree_fails(
str(path),
(OSError, OSError("busy"), None),
)
+ else:
+ raise OSError("busy")
# manager_module.shutil is the global stdlib module object. Restore it
# immediately after the behavior under test so pytest's tmp cleanup keeps
@@ -67,6 +70,9 @@ def test_delete_knowledge_base_clears_config_when_rmtree_fails(
scoped_patch.setattr(manager_module.shutil, "rmtree", _rmtree_always_errors)
assert manager.delete_knowledge_base("broken", confirm=True) is True
assert "broken" not in _read_config(manager.config_file).get("knowledge_bases", {})
+ # A failed POSIX directory retry must preserve traversal permission so a
+ # later cleanup pass can remove the orphan.
+ assert (manager.base_dir / "broken").stat().st_mode & stat.S_IXUSR
def test_delete_knowledge_base_removes_orphan_config_when_directory_missing(
diff --git a/tests/services/rag/test_llamaindex_document_loader.py b/tests/services/rag/test_llamaindex_document_loader.py
index 6ec1d6e7e..237217ade 100644
--- a/tests/services/rag/test_llamaindex_document_loader.py
+++ b/tests/services/rag/test_llamaindex_document_loader.py
@@ -211,6 +211,11 @@ def test_loader_skips_images_when_embedding_provider_is_text_only(
monkeypatch.setattr(loader_module, "get_embedding_client", lambda: _TextOnlyClient())
+ def _unexpected_llm_client():
+ pytest.fail("text-only embedding must not initialize the LLM client")
+
+ monkeypatch.setattr(loader_module, "get_llm_client", _unexpected_llm_client)
+
documents = asyncio.run(loader_module.LlamaIndexDocumentLoader().load([str(image_path)]))
assert documents == []
@@ -300,7 +305,7 @@ def test_loader_skips_images_when_llm_is_text_only(
assert documents == []
-def test_loader_logs_all_missing_multimodal_image_requirements(
+def test_loader_skips_images_when_llm_client_is_unavailable(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
) -> None:
pytest.importorskip("llama_index.core")
@@ -309,27 +314,22 @@ def test_loader_logs_all_missing_multimodal_image_requirements(
image_path = tmp_path / "photo.png"
image_path.write_bytes(b"\x89PNG\r\n")
- class _TextOnlyEmbeddingClient:
- config = type("Config", (), {"binding": "openai", "model": "text-embedding-3-small"})()
+ class _MultimodalEmbeddingClient:
+ config = type("Config", (), {"binding": "siliconflow", "model": "qwen3-vl"})()
def supports_multimodal_contents(self) -> bool:
- return False
-
- class _TextOnlyLLMClient:
- config = type("Config", (), {"binding": "openai", "model": "gpt-3.5-turbo"})()
+ return True
- def supports_multimodal_images(self) -> bool:
- return False
+ def _unavailable_llm_client():
+ raise RuntimeError("no LLM configured")
- monkeypatch.setattr(loader_module, "get_embedding_client", lambda: _TextOnlyEmbeddingClient())
- monkeypatch.setattr(loader_module, "get_llm_client", lambda: _TextOnlyLLMClient())
+ monkeypatch.setattr(loader_module, "get_embedding_client", lambda: _MultimodalEmbeddingClient())
+ monkeypatch.setattr(loader_module, "get_llm_client", _unavailable_llm_client)
with caplog.at_level("WARNING"):
documents = asyncio.run(loader_module.LlamaIndexDocumentLoader().load([str(image_path)]))
assert documents == []
assert "requires both multimodal embedding and multimodal LLM support" in caplog.text
- assert "embedding provider/model does not support multimodal contents" in caplog.text
- assert "LLM provider/model does not support multimodal image input" in caplog.text
- assert "text-embedding-3-small" in caplog.text
- assert "gpt-3.5-turbo" in caplog.text
+ assert "LLM client is unavailable" in caplog.text
+ assert "no LLM configured" in caplog.text