Skip to content

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

fix(llm): recover from stale CA bundle paths (#920)

LamXwah738ad6d604d5
diff --git a/deeptutor/core/agentic/client.py b/deeptutor/core/agentic/client.py
index 83fb14bb3..6b3236303 100644
--- a/deeptutor/core/agentic/client.py
+++ b/deeptutor/core/agentic/client.py
@@ -81,6 +81,12 @@ def _client_cache_key(
def _build_openai_client(config: LLMClientConfig, *, disable_ssl_verify: bool) -> Any:
+ # A stale SSL_CERT_FILE (common with cloned conda envs) makes httpx's
+ # create_ssl_context raise FileNotFoundError mid-__init__, aborting client
+ # construction. Drop broken CA paths first so TLS uses its default CA config.
+ from deeptutor.services.llm.openai_http_client import sanitize_invalid_ssl_env
+
+ sanitize_invalid_ssl_env()
default_headers = config.extra_headers or None
spec = find_by_name(config.binding)
if spec:
diff --git a/deeptutor/services/llm/openai_http_client.py b/deeptutor/services/llm/openai_http_client.py
index 5a2d18b4c..0ea881e28 100644
--- a/deeptutor/services/llm/openai_http_client.py
+++ b/deeptutor/services/llm/openai_http_client.py
@@ -35,8 +35,57 @@ def disable_ssl_verify_enabled() -> bool:
return True
+_sanitized_lock = threading.Lock()
+_sanitized_warned: set[str] = set()
+
+# httpx passes these OpenSSL paths to ssl.create_default_context, which raises
+# FileNotFoundError when a path has gone stale after a conda env is cloned or
+# moved without ca-certificates.
+_SSL_CA_ENV_PATHS: tuple[tuple[str, str], ...] = (
+ ("SSL_CERT_FILE", "file"),
+ ("SSL_CERT_DIR", "directory"),
+)
+
+
+def sanitize_invalid_ssl_env() -> list[str]:
+ """Remove CA-bundle env vars that point at non-existent paths.
+
+ Returns the names of removed variables. The operation is idempotent and
+ thread-safe, and each stale variable is warned about at most once.
+ """
+ removed: list[str] = []
+ warnings: list[tuple[str, str]] = []
+ with _sanitized_lock:
+ for name, kind in _SSL_CA_ENV_PATHS:
+ value = os.environ.get(name)
+ if not value:
+ continue
+ path_exists = os.path.isfile(value) if kind == "file" else os.path.isdir(value)
+ if path_exists:
+ continue
+ os.environ.pop(name, None)
+ removed.append(name)
+ if name not in _sanitized_warned:
+ _sanitized_warned.add(name)
+ warnings.append((name, kind))
+ for name, kind in warnings:
+ _warn_stale_ca_var(name, kind=kind)
+ return removed
+
+
+def _warn_stale_ca_var(name: str, *, kind: str) -> None:
+ logger.warning(
+ "%s points to a missing %s; clearing it so TLS falls back to the "
+ "default CA bundle. If this is a conda environment, reinstalling "
+ "ca-certificates regenerates the bundle.",
+ name,
+ kind,
+ )
+
+
def build_openai_http_client(**kwargs: Any) -> httpx.AsyncClient | None:
"""Build a custom SDK httpx client when DISABLE_SSL_VERIFY is enabled."""
+ sanitize_invalid_ssl_env()
if not disable_ssl_verify_enabled():
return None
return httpx.AsyncClient(verify=False, **kwargs) # nosec B501
@@ -52,4 +101,5 @@ __all__ = [
"build_openai_http_client",
"disable_ssl_verify_enabled",
"openai_client_kwargs",
+ "sanitize_invalid_ssl_env",
]
diff --git a/tests/services/llm/test_ssl_env_sanitizer.py b/tests/services/llm/test_ssl_env_sanitizer.py
new file mode 100644
index 000000000..240a7be50
--- /dev/null
+++ b/tests/services/llm/test_ssl_env_sanitizer.py
@@ -0,0 +1,97 @@
+"""sanitize_invalid_ssl_env drops CA-bundle env vars that point nowhere.
+
+Reproduces the chat crash where a conda env's SSL_CERT_FILE goes stale after
+the env is cloned/moved without ca-certificates: httpx hands the path to
+ssl.create_default_context, which raises FileNotFoundError mid client
+``__init__`` and aborts the whole chat turn.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+from pathlib import Path
+
+import pytest
+
+from deeptutor.services.llm import openai_http_client
+from deeptutor.services.llm.openai_http_client import sanitize_invalid_ssl_env
+
+
[email protected](autouse=True)
+def _reset_sanitizer_state(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The warning-dedup set is module-level and would leak between tests.
+ monkeypatch.setattr(openai_http_client, "_sanitized_warned", set())
+ for name, _kind in openai_http_client._SSL_CA_ENV_PATHS:
+ monkeypatch.delenv(name, raising=False)
+
+
+def test_stale_ssl_cert_file_is_popped(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SSL_CERT_FILE", "/definitely/not/here/cacert.pem")
+ removed = sanitize_invalid_ssl_env()
+ assert "SSL_CERT_FILE" in removed
+ assert "SSL_CERT_FILE" not in os.environ
+
+
+def test_valid_ssl_cert_file_is_kept(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ bundle = tmp_path / "cacert.pem"
+ bundle.write_text("dummy")
+ monkeypatch.setenv("SSL_CERT_FILE", str(bundle))
+ removed = sanitize_invalid_ssl_env()
+ assert removed == []
+ assert os.environ["SSL_CERT_FILE"] == str(bundle)
+
+
+def test_stale_ssl_cert_dir_is_popped(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SSL_CERT_DIR", "/definitely/not/a/dir")
+ removed = sanitize_invalid_ssl_env()
+ assert "SSL_CERT_DIR" in removed
+
+
+def test_valid_ssl_cert_dir_is_kept(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("SSL_CERT_DIR", str(tmp_path))
+ removed = sanitize_invalid_ssl_env()
+ assert removed == []
+
+
+def test_idempotent(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SSL_CERT_FILE", "/missing/cacert.pem")
+ assert sanitize_invalid_ssl_env() == ["SSL_CERT_FILE"]
+ # Already popped on the first pass — the second finds nothing.
+ assert sanitize_invalid_ssl_env() == []
+
+
+def test_warning_deduped(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None:
+ missing_path = "/missing/private-user/cacert.pem"
+ monkeypatch.setenv("SSL_CERT_FILE", missing_path)
+ sanitize_invalid_ssl_env()
+ monkeypatch.setenv("SSL_CERT_FILE", missing_path)
+ sanitize_invalid_ssl_env()
+ warns = [
+ record
+ for record in caplog.records
+ if record.levelname == "WARNING" and record.name == openai_http_client.__name__
+ ]
+ assert len(warns) == 1
+ assert missing_path not in caplog.text
+
+
+def test_build_openai_client_survives_stale_ssl_cert_file(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The chat client factory must not crash when SSL_CERT_FILE is stale."""
+ from deeptutor.core.agentic.client import LLMClientConfig, build_openai_client
+
+ monkeypatch.setenv("SSL_CERT_FILE", "/definitely/not/here/cacert.pem")
+ config = LLMClientConfig(
+ binding="custom",
+ model="m",
+ api_key="sk-test",
+ base_url="https://example.test/v1",
+ )
+ client = build_openai_client(config) # raised FileNotFoundError before the fix
+ try:
+ # The underlying httpx transport initialised successfully.
+ assert getattr(client._client, "_transport", None) is not None
+ finally:
+ asyncio.run(client.close())