~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
fix(logs): honor ?limit on /api/research/<id>/logs (#4645)
LearningCircuitd668158360cb
diff --git a/changelog.d/+research-logs-honor-limit.bugfix.md b/changelog.d/+research-logs-honor-limit.bugfix.mdnew file mode 100644index 0000000000..4d8f7e0954--- /dev/null+++ b/changelog.d/+research-logs-honor-limit.bugfix.md@@ -0,0 +1 @@+Honor ``?limit`` on ``/api/research/<id>/logs`` (the route the log panel actually fetches). It previously ignored the parameter and returned every row, so a long langgraph run could still ship thousands of rows to the browser despite the panel requesting a bounded tail. The limit now returns the newest N rows (oldest-first, unchanged ordering) clamped to ``HISTORY_LOGS_HARD_CAP``; omitting ``?limit`` preserves the existing return-all contract for direct API callers.diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 8271efd0ed..aec60b9944 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -21,7 +21,7 @@ from sqlalchemy.orm import Sessionfrom ...config.constants import DEFAULT_OLLAMA_URLfrom ...exceptions import DuplicateResearchError, SystemAtCapacityErrorfrom ...llm.providers.base import normalize_provider-from ...constants import ResearchStatus+from ...constants import HISTORY_LOGS_HARD_CAP, ResearchStatusfrom ...security import (FileUploadValidator,UnsafeFilenameError,@@ -1448,9 +1448,23 @@ def get_research_details(research_id):@research_bp.route("/api/research/<string:research_id>/logs")@login_requireddef get_research_logs(research_id):- """Get logs for a specific research"""+ """Get logs for a specific research.++ Accepts an optional ``?limit=N`` that bounds the response to the newest+ ``N`` rows (returned oldest-first, matching the default ordering) and is+ clamped to ``[1, HISTORY_LOGS_HARD_CAP]`` so a client cannot force an+ unbounded load — a long langgraph run can persist thousands of rows. When+ ``?limit`` is absent or not a valid integer (Flask ``type=int`` yields+ ``None``) the historical contract is preserved: every row is returned. The+ frontend log panel always sends a valid limit; this only affects direct+ API callers that omit or malform one.+ """username = session["username"]+ limit = request.args.get("limit", type=int)+ if limit is not None:+ limit = max(1, min(limit, HISTORY_LOGS_HARD_CAP))+try:# First check if the research existswith get_user_db_session(username) as db_session:@@ -1463,12 +1477,21 @@ def get_research_logs(research_id):return jsonify({"error": "Research not found"}), 404# Get logs from research_logs table- log_results = (- db_session.query(ResearchLog)- .filter_by(research_id=research_id)- .order_by(ResearchLog.timestamp)- .all()+ log_query = db_session.query(ResearchLog).filter_by(+ research_id=research_id)+ if limit is None:+ log_results = log_query.order_by(ResearchLog.timestamp).all()+ else:+ # Take the newest ``limit`` rows at the SQL layer, then flip+ # back to oldest-first so the response ordering is unchanged.+ log_results = list(+ reversed(+ log_query.order_by(ResearchLog.timestamp.desc())+ .limit(limit)+ .all()+ )+ )# Extract log attributes while session is active# to avoid DetachedInstanceError on ORM attribute accessdiff --git a/src/local_deep_research/web/static/js/components/logpanel.js b/src/local_deep_research/web/static/js/components/logpanel.jsindex 6b78d80088..a848bcfe7b 100644--- a/src/local_deep_research/web/static/js/components/logpanel.js+++ b/src/local_deep_research/web/static/js/components/logpanel.js@@ -1094,10 +1094,10 @@return;}// Download path requests the shared hard cap (window.LDR_LOG_LIMITS,- // Python's HISTORY_LOGS_HARD_CAP) so users get the full tail. NOTE:- // the route this fetch hits (/api/research/<id>/logs) does not yet- // honor ?limit server-side, so this value is currently advisory; the- // /history/logs route clamps to the same ceiling when used.+ // Python's HISTORY_LOGS_HARD_CAP) so users get the full tail. The+ // route this fetch hits (/api/research/<id>/logs) clamps ?limit to+ // the same ceiling server-side, so the download is bounded to the+ // newest hard-cap rows.const hardCap = window.LDR_LOG_LIMITS?.hard_cap ?? 5000;fetchLogsForResearch(researchId, hardCap).then((logData) => {// Create a blob with the logs datadiff --git a/tests/web/routes/test_research_routes.py b/tests/web/routes/test_research_routes.pyindex 14627628fa..9d96da0d87 100644--- a/tests/web/routes/test_research_routes.py+++ b/tests/web/routes/test_research_routes.py@@ -419,6 +419,147 @@ class TestGetResearchLogsApi:)assert response.status_code == 404, response.status_code+ @staticmethod+ def _seed_real_session(num_logs):+ """Build an in-memory SQLite session with one ResearchHistory row+ (id ``test-rid``) and ``num_logs`` ResearchLog rows at 1-minute+ intervals (messages ``Log 0``..``Log N-1``, oldest first). Returns the+ live session so the route is driven through real SQL — a mocked query+ chain returns a fixed list regardless of ``desc()``/``limit()`` and so+ cannot prove the newest-N ordering.+ """+ from datetime import datetime, timedelta, timezone++ from sqlalchemy import create_engine+ from sqlalchemy.orm import sessionmaker++ from local_deep_research.database.models import (+ Base,+ ResearchHistory,+ ResearchLog,+ )++ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()++ session.add(+ ResearchHistory(+ id="test-rid",+ query="q",+ mode="quick",+ status="completed",+ created_at="2025-01-01T00:00:00+00:00",+ )+ )+ base_time = datetime(2025, 1, 1, tzinfo=timezone.utc)+ for i in range(num_logs):+ session.add(+ ResearchLog(+ research_id="test-rid",+ timestamp=base_time + timedelta(minutes=i),+ message=f"Log {i}",+ module="test",+ function="test",+ line_no=i,+ level="INFO",+ )+ )+ session.commit()+ return session++ @staticmethod+ def _close_session(session):+ """Close the session AND dispose its in-memory engine, so the+ underlying sqlite connection is released (otherwise the pool keeps+ it open and pytest reports a ResourceWarning)."""+ engine = session.get_bind()+ session.close()+ if engine is not None:+ engine.dispose()++ def _get_logs(self, authenticated_client, session, query):+ with patch(f"{_RR}.get_user_db_session") as mock_db:+ mock_db.return_value.__enter__ = lambda s: session+ mock_db.return_value.__exit__ = MagicMock(return_value=False)+ return authenticated_client.get(+ f"{RESEARCH_PREFIX}/api/research/test-rid/logs{query}"+ )++ def test_no_limit_returns_all_logs_oldest_first(self, authenticated_client):+ """Omitting ?limit preserves the public contract: every row, asc."""+ session = self._seed_real_session(10)+ try:+ resp = self._get_logs(authenticated_client, session, "")+ assert resp.status_code == 200, resp.status_code+ messages = [r["message"] for r in resp.get_json()]+ assert messages == [f"Log {i}" for i in range(10)]+ finally:+ self._close_session(session)++ def test_limit_returns_newest_n_oldest_first(self, authenticated_client):+ """?limit=N returns the newest N rows, still oldest-first."""+ session = self._seed_real_session(10)+ try:+ resp = self._get_logs(authenticated_client, session, "?limit=3")+ assert resp.status_code == 200, resp.status_code+ messages = [r["message"] for r in resp.get_json()]+ assert messages == ["Log 7", "Log 8", "Log 9"]+ finally:+ self._close_session(session)++ def test_limit_is_clamped_to_at_least_one(self, authenticated_client):+ """?limit=0 clamps up to 1 -> just the single newest row."""+ session = self._seed_real_session(10)+ try:+ resp = self._get_logs(authenticated_client, session, "?limit=0")+ assert resp.status_code == 200, resp.status_code+ messages = [r["message"] for r in resp.get_json()]+ assert messages == ["Log 9"]+ finally:+ self._close_session(session)++ def test_malformed_limit_falls_back_to_all_logs(self, authenticated_client):+ """A non-integer ?limit (Flask ``type=int`` yields None) is treated as+ absent, preserving the return-all contract rather than erroring."""+ session = self._seed_real_session(10)+ try:+ resp = self._get_logs(authenticated_client, session, "?limit=abc")+ assert resp.status_code == 200, resp.status_code+ messages = [r["message"] for r in resp.get_json()]+ assert messages == [f"Log {i}" for i in range(10)]+ finally:+ self._close_session(session)++ def test_negative_limit_clamps_to_one(self, authenticated_client):+ """?limit=-5 clamps to 1 — NOT SQLite's ``LIMIT -1`` (= unbounded).+ The clamp runs before ``.limit()``, so a negative value can never+ reach SQL as a no-op limit."""+ session = self._seed_real_session(10)+ try:+ resp = self._get_logs(authenticated_client, session, "?limit=-5")+ assert resp.status_code == 200, resp.status_code+ messages = [r["message"] for r in resp.get_json()]+ assert messages == ["Log 9"]+ finally:+ self._close_session(session)++ def test_limit_above_hard_cap_is_clamped(self, authenticated_client):+ """?limit above HISTORY_LOGS_HARD_CAP is clamped to the cap. The cap+ is patched to a small value so the clamp is observable without seeding+ thousands of rows."""+ session = self._seed_real_session(10)+ try:+ with patch(f"{_RR}.HISTORY_LOGS_HARD_CAP", 2):+ resp = self._get_logs(+ authenticated_client, session, "?limit=999999"+ )+ assert resp.status_code == 200, resp.status_code+ messages = [r["message"] for r in resp.get_json()]+ assert messages == ["Log 8", "Log 9"]+ finally:+ self._close_session(session)+class TestGetResearchStatusApi:"""Tests for /api/research/<id>/status endpoint."""