~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat(api): add FD and thread diagnostics to /api/v1/health (#4915)
LearningCircuitbbd7284ffad9
diff --git a/changelog.d/4915.feature.md b/changelog.d/4915.feature.mdnew file mode 100644index 0000000000..6e0e0ac2b5--- /dev/null+++ b/changelog.d/4915.feature.md@@ -0,0 +1 @@+**`/api/v1/health` now reports file-descriptor and thread diagnostics.** Authenticated callers receive a `resources` block (`fd_count`, `fd_soft_limit`, `fd_hard_limit`, `fd_usage_percent`, `thread_count`), and `status` flips to `"warning"` above 70% FD usage — making FD growth observable over HTTP for dashboards and alerting. Anonymous callers still get the basic `status`/`message`/`timestamp`, so the Docker healthcheck is unaffected. FD metrics report `null` on non-Linux platforms.diff --git a/src/local_deep_research/web/api.py b/src/local_deep_research/web/api.pyindex 45491f9fa6..45166a9e2b 100644--- a/src/local_deep_research/web/api.py+++ b/src/local_deep_research/web/api.py@@ -4,10 +4,17 @@ Provides HTTP access to programmatic search and research capabilities."""import inspect+import os+import threadingimport timefrom functools import wrapsfrom typing import Dict, Any, Optional, Tuple+try:+ import resource as _resource_mod+except ImportError:+ _resource_mod = None # Windows: no POSIX resource limits+from flask import Blueprint, jsonify, request, Responsefrom loguru import logger@@ -234,10 +241,68 @@ def api_documentation():@api_blueprint.route("/health", methods=["GET"])def health_check():- """Simple health check endpoint."""- return jsonify(- {"status": "ok", "message": "API is running", "timestamp": time.time()}- )+ """Health check endpoint with resource usage diagnostics.++ The basic ``status``/``message``/``timestamp`` fields are public so the+ Docker healthcheck (which only inspects the HTTP status code) keeps+ working. File-descriptor and thread diagnostics are only included for+ authenticated users, to avoid leaking process internals to anonymous+ callers.+ """+ diagnostics = {+ "status": "ok",+ "message": "API is running",+ "timestamp": time.time(),+ }++ # Only expose resource diagnostics to authenticated users+ username = get_current_username()+ if username:+ # File descriptor count (Linux only; /proc not available on macOS)+ try:+ fd_count = len(os.listdir("/proc/self/fd"))+ except OSError:+ fd_count = None++ # FD soft/hard limits (POSIX)+ soft_limit = hard_limit = None+ if _resource_mod is not None:+ try:+ soft_limit, hard_limit = _resource_mod.getrlimit(+ _resource_mod.RLIMIT_NOFILE+ )+ if soft_limit == _resource_mod.RLIM_INFINITY:+ soft_limit = None+ if hard_limit == _resource_mod.RLIM_INFINITY:+ hard_limit = None+ except (AttributeError, ValueError, OSError):+ pass++ thread_count = threading.active_count()++ fd_usage_percent = (+ round(fd_count / soft_limit * 100, 1)+ if fd_count is not None+ and soft_limit is not None+ and soft_limit > 0+ else None+ )++ diagnostics["resources"] = {+ "fd_count": fd_count,+ "fd_soft_limit": soft_limit,+ "fd_hard_limit": hard_limit,+ "fd_usage_percent": fd_usage_percent,+ "thread_count": thread_count,+ }++ if fd_usage_percent is not None and fd_usage_percent > 70:+ diagnostics["status"] = "warning"+ diagnostics["message"] = (+ f"High FD usage: {fd_count}/{soft_limit} ({fd_usage_percent}%)"+ )++ return jsonify(diagnostics)def _serialize_results(results: Dict[str, Any]) -> Response:diff --git a/tests/web/test_api_coverage.py b/tests/web/test_api_coverage.pyindex 77c173e054..3116ad61e4 100644--- a/tests/web/test_api_coverage.py+++ b/tests/web/test_api_coverage.py@@ -5,6 +5,7 @@ Covers all blueprint routes, the api_access_control decorator (auth, API-disablerate-limiting), and the _serialize_results helper."""+import sysimport timefrom contextlib import contextmanagerfrom unittest.mock import MagicMock, patch@@ -139,6 +140,154 @@ class TestHealthCheck:resp = client.get("/api/v1/health")assert resp.status_code == 200+ def test_no_resources_when_unauthenticated(self, client):+ """Unauthenticated requests do not get resource diagnostics."""+ resp = client.get("/api/v1/health")+ data = resp.get_json()+ assert data["status"] == "ok"+ assert "resources" not in data++ @patch(+ "local_deep_research.web.api.get_current_username",+ return_value="testuser",+ )+ def test_resources_structure(self, _mock_user, client):+ """Authenticated response contains resources dict with expected keys."""+ resp = client.get("/api/v1/health")+ data = resp.get_json()+ assert "resources" in data+ res = data["resources"]+ expected_keys = {+ "fd_count",+ "fd_soft_limit",+ "fd_hard_limit",+ "fd_usage_percent",+ "thread_count",+ }+ assert set(res.keys()) == expected_keys++ @patch(+ "local_deep_research.web.api.get_current_username",+ return_value="testuser",+ )+ def test_thread_count_positive(self, _mock_user, client):+ """thread_count is always >= 1 (main thread)."""+ resp = client.get("/api/v1/health")+ tc = resp.get_json()["resources"]["thread_count"]+ assert isinstance(tc, int)+ assert tc >= 1++ @pytest.mark.skipif(+ sys.platform != "linux", reason="/proc/self/fd only on Linux"+ )+ @patch(+ "local_deep_research.web.api.get_current_username",+ return_value="testuser",+ )+ def test_fd_count_on_linux(self, _mock_user, client):+ """On Linux, fd_count is a non-negative integer."""+ resp = client.get("/api/v1/health")+ fd = resp.get_json()["resources"]["fd_count"]+ assert isinstance(fd, int)+ assert fd >= 0++ @patch(+ "local_deep_research.web.api.get_current_username",+ return_value="testuser",+ )+ def test_no_resource_module(self, _mock_user, client):+ """When resource module is unavailable, FD limits are None."""+ with patch("local_deep_research.web.api._resource_mod", None):+ resp = client.get("/api/v1/health")+ data = resp.get_json()+ assert data["status"] == "ok"+ assert data["resources"]["fd_soft_limit"] is None+ assert data["resources"]["fd_hard_limit"] is None++ @patch(+ "local_deep_research.web.api.get_current_username",+ return_value="testuser",+ )+ def test_no_proc_fs(self, _mock_user, client):+ """When /proc/self/fd is unavailable, fd_count and percent are None."""+ with patch("os.listdir", side_effect=OSError("no /proc")):+ resp = client.get("/api/v1/health")+ res = resp.get_json()["resources"]+ assert res["fd_count"] is None+ assert res["fd_usage_percent"] is None++ @patch(+ "local_deep_research.web.api.get_current_username",+ return_value="testuser",+ )+ def test_warning_status_high_fd(self, _mock_user, client):+ """Status becomes 'warning' when FD usage exceeds 70%."""+ fake_fds = [str(i) for i in range(80)]+ with (+ patch("os.listdir", return_value=fake_fds),+ patch("local_deep_research.web.api._resource_mod") as mock_res,+ ):+ mock_res.RLIM_INFINITY = -1+ mock_res.RLIMIT_NOFILE = 7+ mock_res.getrlimit.return_value = (100, 100)+ resp = client.get("/api/v1/health")+ data = resp.get_json()+ assert data["status"] == "warning"+ assert "High FD usage" in data["message"]+ assert data["resources"]["fd_usage_percent"] == 80.0++ @patch(+ "local_deep_research.web.api.get_current_username",+ return_value="testuser",+ )+ def test_ok_status_normal_fd(self, _mock_user, client):+ """Status stays 'ok' when FD usage is low."""+ fake_fds = [str(i) for i in range(10)]+ with (+ patch("os.listdir", return_value=fake_fds),+ patch("local_deep_research.web.api._resource_mod") as mock_res,+ ):+ mock_res.RLIM_INFINITY = -1+ mock_res.RLIMIT_NOFILE = 7+ mock_res.getrlimit.return_value = (1000, 1000)+ resp = client.get("/api/v1/health")+ data = resp.get_json()+ assert data["status"] == "ok"+ assert data["resources"]["fd_usage_percent"] == 1.0++ @patch(+ "local_deep_research.web.api.get_current_username",+ return_value="testuser",+ )+ def test_getrlimit_oserror_does_not_500(self, _mock_user, client):+ """A getrlimit OSError must not break the health endpoint."""+ with patch("local_deep_research.web.api._resource_mod") as mock_res:+ mock_res.RLIM_INFINITY = -1+ mock_res.RLIMIT_NOFILE = 7+ mock_res.getrlimit.side_effect = OSError("getrlimit failed")+ resp = client.get("/api/v1/health")+ assert resp.status_code == 200+ res = resp.get_json()["resources"]+ assert res["fd_soft_limit"] is None+ assert res["fd_hard_limit"] is None+ assert res["fd_usage_percent"] is None++ @patch(+ "local_deep_research.web.api.get_current_username",+ return_value="testuser",+ )+ def test_rlim_infinity_becomes_none(self, _mock_user, client):+ """RLIM_INFINITY limits are reported as None."""+ with patch("local_deep_research.web.api._resource_mod") as mock_res:+ mock_res.RLIM_INFINITY = -1+ mock_res.RLIMIT_NOFILE = 7+ mock_res.getrlimit.return_value = (-1, -1)+ resp = client.get("/api/v1/health")+ res = resp.get_json()["resources"]+ assert res["fd_soft_limit"] is None+ assert res["fd_hard_limit"] is None+ assert res["fd_usage_percent"] is None+# ===================================================================# /api/v1/ (api_documentation)