~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(memory): paginate /history/logs/<id> endpoint (#4037)
LearningCircuit635bdc4b6a49
diff --git a/changelog.d/+memory-history-logs-pagination.bugfix.md b/changelog.d/+memory-history-logs-pagination.bugfix.mdnew file mode 100644index 0000000000..ae28b56460--- /dev/null+++ b/changelog.d/+memory-history-logs-pagination.bugfix.md@@ -0,0 +1 @@+Paginate the ``/history/logs/<id>`` endpoint (default 500, clamped to 5000) so loading a long research's history no longer materialises every ResearchLog row server-side or pushes a 50+ MB JSON response that the browser ultimately prunes to 500 entries anyway. Complements the live-socket truncation in PR #4004.diff --git a/src/local_deep_research/web/models/database.py b/src/local_deep_research/web/models/database.pyindex 77e601c9f0..c1261e6efd 100644--- a/src/local_deep_research/web/models/database.py+++ b/src/local_deep_research/web/models/database.py@@ -127,24 +127,39 @@ def calculate_duration(created_at_str, completed_at_str=None):return None-def get_logs_for_research(research_id):+def get_logs_for_research(research_id, limit: int | None = None):"""- Retrieve all logs for a specific research ID+ Retrieve logs for a specific research ID, oldest-first.Args:research_id: ID of the research+ limit: If set, return only the most recent ``limit`` entries+ (still oldest-first in the returned list). Used to bound the+ response size of ``/history/logs/<id>`` — long langgraph+ researches can produce thousands of 10 KB rows that the+ frontend prunes to 500 anyway.Returns:List of log entries as dictionaries"""try:with get_user_db_session() as session:- log_results = (- session.query(ResearchLog)- .filter(ResearchLog.research_id == research_id)- .order_by(ResearchLog.timestamp.asc())- .all()+ query = session.query(ResearchLog).filter(+ ResearchLog.research_id == research_id)+ if limit is not None:+ # Take the newest ``limit`` rows from the DB, then flip back+ # to oldest-first ordering for the caller. Avoids loading+ # the entire table when only the tail is wanted.+ log_results = list(+ reversed(+ query.order_by(ResearchLog.timestamp.desc())+ .limit(limit)+ .all()+ )+ )+ else:+ log_results = query.order_by(ResearchLog.timestamp.asc()).all()logs = []for result in log_results:diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.pyindex 570d5d2829..a7c4c26b31 100644--- a/src/local_deep_research/web/routes/history_routes.py+++ b/src/local_deep_research/web/routes/history_routes.py@@ -378,9 +378,22 @@ def get_markdown(research_id):@history_bp.route("/logs/<string:research_id>")@login_requireddef get_research_logs(research_id):- """Get logs for a specific research ID"""+ """Get logs for a specific research ID.++ Accepts ``?limit=N`` to bound the response size; default 500 matches+ the frontend's ``MAX_LOG_ENTRIES`` DOM cap. Clamped to ``[1, 5000]``+ so a client cannot force an unbounded load (a long langgraph run can+ persist thousands of 10 KB rows; pre-cap the route allocated ~150 MB+ transient on the server and Firefox parsed a ~50 MB JSON response).+ """username = session["username"]+ # Per-request cap. 500 matches MAX_LOG_ENTRIES in logpanel.js; the+ # 5000 ceiling lets explicit log-download flows still get more rows+ # but stops accidental unbounded loads.+ limit = request.args.get("limit", default=500, type=int)+ limit = max(1, min(limit, 5000))+# First check if the research existswith get_user_db_session(username) as db_session:research = (@@ -392,20 +405,20 @@ def get_research_logs(research_id):{"status": "error", "message": "Research not found"}), 404- # Retrieve logs from the database- logs = get_logs_for_research(research_id)+ logs = get_logs_for_research(research_id, limit=limit)- # Format logs correctly if needed- formatted_logs = []+ # Defensive backfill for any row missing the three frontend-required+ # fields. `get_logs_for_research` always sets these from ResearchLog+ # columns, but the defensive layer is covered by+ # test_logs_with_missing_fields_get_defaults (extra keys must be+ # preserved, missing keys must take a default). In-place mutation is+ # safe — the formatter returned a fresh list of fresh dicts.for log in logs:- log_entry = log.copy()- # Ensure each log has time, message, and type fields- log_entry["time"] = log.get("time", "")- log_entry["message"] = log.get("message", "No message")- log_entry["type"] = log.get("type", "info")- formatted_logs.append(log_entry)-- return jsonify({"status": "success", "logs": formatted_logs})+ log.setdefault("time", "")+ log.setdefault("message", "No message")+ log.setdefault("type", "info")++ return jsonify({"status": "success", "logs": logs})@history_bp.route("/log_count/<string:research_id>")diff --git a/src/local_deep_research/web/static/js/components/logpanel.js b/src/local_deep_research/web/static/js/components/logpanel.jsindex 3770da7c79..9ec54b392d 100644--- a/src/local_deep_research/web/static/js/components/logpanel.js+++ b/src/local_deep_research/web/static/js/components/logpanel.js@@ -400,9 +400,12 @@* @param researchId The ID of the research instance.* @returns {Promise<any>} The logs.*/- async function fetchLogsForResearch(researchId) {- // Fetch logs from API- const response = await fetch(URLBuilder.researchLogs(researchId));+ async function fetchLogsForResearch(researchId, limit) {+ // Pass an explicit limit to the API so the server doesn't return+ // (and we don't have to parse) more rows than the panel will keep.+ // Live load uses MAX_LOG_ENTRIES; download uses the server-side+ // hard cap (5000) so users still get the full tail.+ const response = await fetch(URLBuilder.researchLogs(researchId, limit));return await response.json();}@@ -434,7 +437,7 @@SafeLogger.log('Loading logs for research ID:', researchId);- const data = await fetchLogsForResearch(researchId);+ const data = await fetchLogsForResearch(researchId, MAX_LOG_ENTRIES);SafeLogger.log('Logs API response:', data);// Initialize array to hold all logs from different sources@@ -1026,7 +1029,9 @@*/function downloadLogs() {const researchId = window._logPanelState.connectedResearchId;- fetchLogsForResearch(researchId).then((logData) => {+ // Download path requests the server-side hard cap so users still+ // get the full tail (server enforces a 5000-row clamp).+ fetchLogsForResearch(researchId, 5000).then((logData) => {// Create a blob with the logs dataconst blob = new Blob([JSON.stringify(logData, null, 2)], { type: 'application/json' });diff --git a/src/local_deep_research/web/static/js/config/urls.js b/src/local_deep_research/web/static/js/config/urls.jsindex 9b1bea5596..91e6fc00cb 100644--- a/src/local_deep_research/web/static/js/config/urls.js+++ b/src/local_deep_research/web/static/js/config/urls.js@@ -192,8 +192,10 @@ const URLBuilder = {return this.build(URLS.API.RESEARCH_DETAILS, researchId);},- researchLogs(researchId) {- return this.build(URLS.API.RESEARCH_LOGS, researchId);+ researchLogs(researchId, limit) {+ const base = this.build(URLS.API.RESEARCH_LOGS, researchId);+ if (limit === undefined || limit === null) return base;+ return `${base}?limit=${encodeURIComponent(limit)}`;},researchReport(researchId) {diff --git a/tests/js/config/urls.test.js b/tests/js/config/urls.test.jsindex c56994fd4f..6ea7bdfa1f 100644--- a/tests/js/config/urls.test.js+++ b/tests/js/config/urls.test.js@@ -75,6 +75,24 @@ describe('URLBuilder', () => {expect(URLBuilder.historyStatus(42)).toBe(URLS.HISTORY_API.STATUS.replace('{id}', '42'));});+ it('researchLogs returns the bare URL when no limit passed', () => {+ const url = URLBuilder.researchLogs(42);+ expect(url).toBe(URLS.API.RESEARCH_LOGS.replace('{id}', '42'));+ expect(url).not.toContain('?');+ });++ it('researchLogs appends ?limit=N when limit passed', () => {+ const url = URLBuilder.researchLogs(42, 500);+ expect(url).toContain('limit=500');+ });++ it('researchLogs encodes the limit value', () => {+ // Sanity: limit should be safe to pass directly, but encodeURIComponent+ // means anything unexpected stays escaped.+ const url = URLBuilder.researchLogs('abc-123', 5000);+ expect(url).toBe(`${URLS.API.RESEARCH_LOGS.replace('{id}', 'abc-123')}?limit=5000`);+ });+it('getSetting substitutes key into SETTINGS_API.GET_SETTING', () => {const url = URLBuilder.getSetting('llm.model');expect(url).toContain('llm.model');diff --git a/tests/web/models/test_database.py b/tests/web/models/test_database.pyindex 80ef0a57da..b7e9877f2e 100644--- a/tests/web/models/test_database.py+++ b/tests/web/models/test_database.py@@ -189,6 +189,80 @@ class TestGetLogsForResearch:assert result == []+ def test_get_logs_with_limit_uses_desc_order_and_reverses(self):+ """When limit is set, the query takes the newest N rows (desc) and+ the result is reversed so the caller still sees oldest-first.+ """+ # Three rows ordered newest-first as the DB would return them.+ rows = []+ for i, msg in enumerate(["newest", "middle", "oldest"]):+ row = Mock()+ row.timestamp = f"2025-01-01T10:0{2 - i}:00"+ row.message = msg+ row.level = "INFO"+ row.module = "m"+ row.line_no = i+ rows.append(row)++ mock_session = Mock()+ mock_query = Mock()+ mock_query.filter.return_value = mock_query+ mock_query.order_by.return_value = mock_query+ mock_query.limit.return_value = mock_query+ mock_query.all.return_value = rows+ mock_session.query.return_value = mock_query++ with patch(+ "local_deep_research.web.models.database.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__ = Mock(+ return_value=mock_session+ )+ mock_get_session.return_value.__exit__ = Mock(return_value=False)++ from local_deep_research.web.models.database import (+ get_logs_for_research,+ )++ result = get_logs_for_research("rid", limit=3)++ # limit() was called with the requested cap.+ mock_query.limit.assert_called_once_with(3)+ # Caller sees oldest-first ordering.+ assert [r["message"] for r in result] == [+ "oldest",+ "middle",+ "newest",+ ]++ def test_get_logs_without_limit_does_not_call_limit(self):+ """When limit is None, the function preserves legacy behaviour and+ does not invoke .limit() on the query (returns every row, asc)."""+ mock_session = Mock()+ mock_query = Mock()+ mock_query.filter.return_value = mock_query+ mock_query.order_by.return_value = mock_query+ mock_query.all.return_value = []+ # Track whether limit() is invoked — it should NOT be.+ mock_query.limit = Mock(side_effect=AssertionError("limit() called"))+ mock_session.query.return_value = mock_query++ with patch(+ "local_deep_research.web.models.database.get_user_db_session"+ ) as mock_get_session:+ mock_get_session.return_value.__enter__ = Mock(+ return_value=mock_session+ )+ mock_get_session.return_value.__exit__ = Mock(return_value=False)++ from local_deep_research.web.models.database import (+ get_logs_for_research,+ )++ # Should complete without triggering the AssertionError side-effect.+ result = get_logs_for_research("rid")+ assert result == []+class TestGetTotalLogsForResearch:"""Tests for get_total_logs_for_research function."""diff --git a/tests/web/routes/test_history_routes.py b/tests/web/routes/test_history_routes.pyindex c13bae18e1..2c53362833 100644--- a/tests/web/routes/test_history_routes.py+++ b/tests/web/routes/test_history_routes.py@@ -598,6 +598,88 @@ class TestGetResearchLogs:assert data["status"] == "success"assert len(data["logs"]) == 2+ def _patch_existing_research(self):+ """Return a context manager that mocks the existence check + returns+ a session whose query.filter_by().first() yields a research row."""+ from contextlib import contextmanager++ @contextmanager+ def _ctx():+ with patch(+ "local_deep_research.web.routes.history_routes.get_user_db_session"+ ) as mock_session_ctx:+ mock_session = MagicMock()+ mock_session_ctx.return_value.__enter__ = MagicMock(+ return_value=mock_session+ )+ mock_session_ctx.return_value.__exit__ = MagicMock(+ return_value=None+ )+ mock_research = MagicMock()+ mock_research.id = "test-id"+ mock_query = MagicMock()+ mock_query.filter_by.return_value.first.return_value = (+ mock_research+ )+ mock_session.query.return_value = mock_query+ yield++ return _ctx()++ def test_default_limit_is_500(self, authenticated_client):+ """When no ?limit= is passed, the route should request 500 rows."""+ with self._patch_existing_research():+ with patch(+ "local_deep_research.web.routes.history_routes.get_logs_for_research"+ ) as mock_logs:+ mock_logs.return_value = []+ response = authenticated_client.get(+ f"{HISTORY_PREFIX}/logs/test-id"+ )+ assert response.status_code == 200+ # Route MUST pass an explicit limit so the DB can't dump+ # every row into the session identity map.+ assert mock_logs.call_args.kwargs.get("limit") == 500++ def test_explicit_limit_is_forwarded(self, authenticated_client):+ """An explicit ?limit=N below the cap is forwarded verbatim."""+ with self._patch_existing_research():+ with patch(+ "local_deep_research.web.routes.history_routes.get_logs_for_research"+ ) as mock_logs:+ mock_logs.return_value = []+ response = authenticated_client.get(+ f"{HISTORY_PREFIX}/logs/test-id?limit=42"+ )+ assert response.status_code == 200+ assert mock_logs.call_args.kwargs.get("limit") == 42++ def test_limit_is_clamped_to_5000(self, authenticated_client):+ """A ?limit= above the server-side ceiling is clamped to 5000."""+ with self._patch_existing_research():+ with patch(+ "local_deep_research.web.routes.history_routes.get_logs_for_research"+ ) as mock_logs:+ mock_logs.return_value = []+ response = authenticated_client.get(+ f"{HISTORY_PREFIX}/logs/test-id?limit=99999"+ )+ assert response.status_code == 200+ assert mock_logs.call_args.kwargs.get("limit") == 5000++ def test_limit_floor_is_1(self, authenticated_client):+ """A ?limit= of 0 or negative is floored to 1."""+ with self._patch_existing_research():+ with patch(+ "local_deep_research.web.routes.history_routes.get_logs_for_research"+ ) as mock_logs:+ mock_logs.return_value = []+ response = authenticated_client.get(+ f"{HISTORY_PREFIX}/logs/test-id?limit=0"+ )+ assert response.status_code == 200+ assert mock_logs.call_args.kwargs.get("limit") == 1+class TestGetLogCount:"""Tests for /history/log_count/<research_id> endpoint."""