Skip to content

~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.

feat(logs): add streaming NDJSON export endpoint for full research logs (#5259)

Sc969b141883c
diff --git a/changelog.d/5259.feature.md b/changelog.d/5259.feature.md
new file mode 100644
index 0000000000..4d546f75a0
--- /dev/null
+++ b/changelog.d/5259.feature.md
@@ -0,0 +1 @@
+Add streaming NDJSON research log export endpoint (`/api/research/<id>/logs/export`) and log download action.
diff --git a/src/local_deep_research/database/models/logs.py b/src/local_deep_research/database/models/logs.py
index 1fda8a9c1d..ecd9d796db 100644
--- a/src/local_deep_research/database/models/logs.py
+++ b/src/local_deep_research/database/models/logs.py
@@ -11,6 +11,7 @@ re-export below.
from sqlalchemy import (
Column,
ForeignKey,
+ Index,
Integer,
Sequence,
String,
@@ -31,6 +32,14 @@ class ResearchLog(Base):
"""
__tablename__ = "app_logs"
+ __table_args__ = (
+ Index(
+ "ix_app_logs_research_id_timestamp_id",
+ "research_id",
+ "timestamp",
+ "id",
+ ),
+ )
id = Column(Integer, Sequence("reseach_log_id_seq"), primary_key=True)
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 3789f63d49..202dbd0e3d 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -1,15 +1,18 @@
import io
import json
+import re
from datetime import datetime, UTC
from pathlib import Path
from flask import (
Blueprint,
+ Response,
jsonify,
redirect,
request,
send_file,
session,
+ stream_with_context,
url_for,
)
from loguru import logger
@@ -31,6 +34,8 @@ from ...security import (
)
from ...utilities.url_utils import is_safe_custom_llm_endpoint
from ...security.rate_limiter import (
+ _get_api_user_key,
+ _is_api_rate_limit_exempt,
api_rate_limit,
upload_rate_limit_ip,
upload_rate_limit_user,
@@ -1780,6 +1785,125 @@ def get_research_logs(research_id):
return jsonify({"error": "An internal error has occurred"}), 500
+_log_export_limit = limiter.shared_limit(
+ "10 per minute",
+ scope="log_export",
+ key_func=_get_api_user_key,
+ exempt_when=_is_api_rate_limit_exempt,
+)
+
+
+@research_bp.route("/api/research/<string:research_id>/logs/export")
+@_log_export_limit
+@login_required
+def export_research_logs(research_id):
+ """Stream every persisted log row for a research as newline-delimited JSON.
+
+ This endpoint deliberately bypasses ``HISTORY_LOGS_HARD_CAP``: a long
+ langgraph run can persist tens of thousands of rows and the on-screen
+ log panel rightly caps at ``?limit=5000`` to bound DOM and parsing
+ memory. A *download*, by contrast, is short-lived — the browser's
+ download manager streams the response body straight to disk — so the
+ cap does not protect anything here and only hides data.
+
+ Memory layout for very large exports:
+
+ * **Server**: ``get_user_db_session`` opens a fresh session inside
+ the generator so it survives until the response finishes flushing;
+ ``.yield_per(500)`` pulls rows in 500-row batches from the SQLite
+ cursor so the full set is never resident in process memory.
+ * **Wire**: each yielded row is a single ``\\n``-terminated JSON
+ line, so the server flushes incrementally and the browser receives
+ chunks as they arrive.
+ * **Client**: ``Content-Disposition: attachment`` plus the
+ ``log-download-button`` JS trigger a native browser download, so
+ the response body streams to disk without first being buffered
+ into a JS Blob.
+
+ The NDJSON format is the standard streaming interchange for
+ line-oriented records. Each line emits ``id``, ``timestamp``, ``message``,
+ ``level`` (log level), ``log_type`` (aligned with ``/logs`` endpoint),
+ ``module``, and ``line_no``. Consumers can ``for line in file: json.loads(line)``
+ without parsing a wrapper array.
+ """
+ username = session["username"]
+
+ # Verify the research exists (and belongs to this user, since
+ # ``get_user_db_session(username)`` scopes queries to the user's
+ # encrypted DB). Failing fast here avoids opening a streaming session
+ # for a 404.
+ try:
+ with get_user_db_session(username) as db_session:
+ research = (
+ db_session.query(ResearchHistory)
+ .filter_by(id=research_id)
+ .first()
+ )
+ if not research:
+ return _research_not_found(research_id)
+ except Exception:
+ logger.exception("Error verifying research for log export")
+ return jsonify({"error": "An internal error has occurred"}), 500
+
+ def generate():
+ # Open a fresh session inside the generator so it stays open for
+ # the entire streaming duration. ``stream_with_context`` keeps the
+ # request context alive across yields, so ``session``, ``g``,
+ # etc. remain valid until the response flushes.
+ yielded_count = 0
+ try:
+ with get_user_db_session(username) as db_session:
+ log_query = (
+ db_session.query(ResearchLog)
+ .filter_by(research_id=research_id)
+ .order_by(ResearchLog.timestamp.asc(), ResearchLog.id.asc())
+ .yield_per(500)
+ )
+ for row in log_query:
+ yielded_count += 1
+ yield (
+ json.dumps(
+ {
+ "id": row.id,
+ "timestamp": row.timestamp.isoformat()
+ if row.timestamp is not None
+ else None,
+ "message": row.message,
+ "level": row.level,
+ "log_type": row.level,
+ "module": row.module,
+ "line_no": row.line_no,
+ },
+ default=str,
+ )
+ + "\n"
+ )
+ except Exception:
+ # If the DB blows up mid-stream we have already sent a 200 +
+ # partial body, so we can't recover with a JSON error here.
+ # Log and let the iterator end; the client will see a
+ # truncated file, which is the best we can do without
+ # buffering the whole result.
+ logger.exception(
+ f"Error streaming logs for export (research_id={research_id}, yielded={yielded_count})"
+ )
+
+ safe_id = re.sub(r"[^a-zA-Z0-9_-]", "", research_id)
+ filename = f"research_logs_{safe_id or 'export'}.jsonl"
+ return Response(
+ stream_with_context(generate()),
+ mimetype="application/x-ndjson",
+ headers={
+ "Content-Disposition": f'attachment; filename="{filename}"',
+ # Disable caching: this is a one-shot download, and a stale
+ # partial body from a previous run could otherwise confuse a
+ # retry after a mid-stream failure.
+ "Cache-Control": "no-store",
+ "X-Content-Type-Options": "nosniff",
+ },
+ )
+
+
@research_bp.route("/api/report/<string:research_id>")
@login_required
def get_research_report(research_id):
diff --git a/src/local_deep_research/web/routes/route_registry.py b/src/local_deep_research/web/routes/route_registry.py
index fe403e0ffb..ecdcc39214 100644
--- a/src/local_deep_research/web/routes/route_registry.py
+++ b/src/local_deep_research/web/routes/route_registry.py
@@ -37,6 +37,12 @@ ROUTE_REGISTRY: dict[str, Any] = {
"get_research_logs",
"Get research logs",
),
+ (
+ "GET",
+ "/api/research/<string:research_id>/logs/export",
+ "export_research_logs",
+ "Stream all research logs as NDJSON download",
+ ),
(
"GET",
"/api/research/<research_id>/status",
diff --git a/src/local_deep_research/web/static/js/components/logpanel.js b/src/local_deep_research/web/static/js/components/logpanel.js
index 8ebd7fe23a..7f5c089529 100644
--- a/src/local_deep_research/web/static/js/components/logpanel.js
+++ b/src/local_deep_research/web/static/js/components/logpanel.js
@@ -1766,39 +1766,70 @@
* @brief Handler for the log download button which downloads all the
* saved logs to the user's computer.
*/
- function downloadLogs() {
+ async function downloadLogs() {
const researchId = window._logPanelState.connectedResearchId;
if (!researchId) {
// No active research yet (e.g. on a freshly-loaded /chat/ page).
- // Without this guard, fetchLogsForResearch(null) would request
- // /api/research/null/logs and fail silently.
+ // Without this guard, a fetchLogsForResearch(null) call would
+ // request /api/research/null/logs and fail silently.
SafeLogger.warn('downloadLogs called without researchId; skipping');
return;
}
- // Download path requests the shared hard cap (window.LDR_LOG_LIMITS,
- // 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 data
- const blob = new Blob([JSON.stringify(logData, null, 2)], { type: 'application/json' });
-
- // Create a link element and trigger download
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- if (typeof URLValidator !== 'undefined' && URLValidator.safeAssign) {
- URLValidator.safeAssign(a, 'href', url);
- } else {
- a.href = url;
+ // Stream the full export rather than the capped in-page API:
+ // * /api/research/<id>/logs is bounded by HISTORY_LOGS_HARD_CAP
+ // (5 000) on the server so the on-screen panel's DOM and
+ // JSON-parsing budget stays sane. That cap is wrong for a
+ // download — the only memory touched is the browser's
+ // download manager writing the response to disk.
+ // * /api/research/<id>/logs/export streams NDJSON
+ // (Content-Disposition: attachment) so the browser pulls
+ // chunks straight to disk without buffering the full body in
+ // a JS Blob, and the server uses yield_per(500) so it never
+ // holds the full result either.
+ //
+ // We trigger the download with a direct anchor click rather than
+ // fetch()+Blob: the latter would materialise the whole response
+ // in JS memory before handing it to the download manager, which
+ // is exactly what the streaming endpoint exists to avoid.
+ const exportUrl = URLBuilder.researchLogsExport(researchId);
+
+ try {
+ // Perform a fast HEAD pre-flight to verify endpoint status (e.g. catch 404/429/500)
+ // before creating the download anchor, preventing the browser from saving JSON errors as .jsonl files.
+ const res = await fetch(exportUrl, { method: 'HEAD' });
+ if (!res.ok) {
+ const errorMsg = res.status === 404
+ ? 'Research logs not found.'
+ : res.status === 429
+ ? 'Log export rate limit exceeded. Please wait a moment.'
+ : `Failed to export logs (HTTP ${res.status}).`;
+ if (window.ui?.showAlert) {
+ window.ui.showAlert(errorMsg, 'error');
+ } else if (window.ui?.showError) {
+ window.ui.showError(errorMsg);
+ } else {
+ SafeLogger.error(errorMsg);
+ }
+ return;
}
- a.download = `research_logs_${researchId}.json`;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
- });
+ } catch (err) {
+ SafeLogger.warn('Export pre-flight check failed, proceeding with download', err);
+ }
+
+ const a = document.createElement('a');
+ a.style.display = 'none';
+ if (typeof URLValidator !== 'undefined' && URLValidator.safeAssign) {
+ URLValidator.safeAssign(a, 'href', exportUrl);
+ } else {
+ a.href = exportUrl;
+ }
+ // ``download`` is a hint to the browser to save rather than
+ // navigate; the server's Content-Disposition header is the
+ // authoritative filename, so they match either way.
+ a.download = `research_logs_${researchId}.jsonl`;
+ document.body.appendChild(a);
+ a.click();
+ document.body.removeChild(a);
}
// Expose public API
diff --git a/src/local_deep_research/web/static/js/config/urls.js b/src/local_deep_research/web/static/js/config/urls.js
index 677e7116fb..a727233da6 100644
--- a/src/local_deep_research/web/static/js/config/urls.js
+++ b/src/local_deep_research/web/static/js/config/urls.js
@@ -14,6 +14,7 @@ if (typeof URLS !== 'undefined') {
RESEARCH_STATUS: '/api/research/{id}/status',
RESEARCH_DETAILS: '/api/research/{id}',
RESEARCH_LOGS: '/api/research/{id}/logs',
+ RESEARCH_LOGS_EXPORT: '/api/research/{id}/logs/export',
RESEARCH_REPORT: '/api/report/{id}',
TERMINATE_RESEARCH: '/api/terminate/{id}',
DELETE_RESEARCH: '/api/delete/{id}',
@@ -194,6 +195,10 @@ const URLBuilder = {
return `${base}?limit=${encodeURIComponent(limit)}`;
},
+ researchLogsExport(researchId) {
+ return this.build(URLS.API.RESEARCH_LOGS_EXPORT, researchId);
+ },
+
researchReport(researchId) {
return this.build(URLS.API.RESEARCH_REPORT, researchId);
},
diff --git a/tests/api_tests/test_all_endpoints.py b/tests/api_tests/test_all_endpoints.py
index c565e3eefb..9a0c6df323 100644
--- a/tests/api_tests/test_all_endpoints.py
+++ b/tests/api_tests/test_all_endpoints.py
@@ -175,6 +175,9 @@ class TestAllEndpoints:
("GET", f"/history/status/{research_id}", None, 200),
("GET", f"/history/details/{research_id}", None, 200),
("GET", f"/history/log_count/{research_id}", None, 200),
+ # Streaming log export — returns 200 with streamed NDJSON body
+ # (or 404 if research is still initializing).
+ ("GET", f"/api/research/{research_id}/logs/export", None, 200),
]
for method, endpoint, req_data, expected_status in research_endpoints:
diff --git a/tests/infrastructure_tests/test_urls_js.py b/tests/infrastructure_tests/test_urls_js.py
index 04cde98a4f..036e072757 100644
--- a/tests/infrastructure_tests/test_urls_js.py
+++ b/tests/infrastructure_tests/test_urls_js.py
@@ -99,6 +99,10 @@ class TestJavaScriptURLConfiguration:
("API.RESEARCH_STATUS", "/api/research/<research_id>/status"),
("API.RESEARCH_DETAILS", "/api/research/<string:research_id>"),
("API.RESEARCH_LOGS", "/api/research/<string:research_id>/logs"),
+ (
+ "API.RESEARCH_LOGS_EXPORT",
+ "/api/research/<string:research_id>/logs/export",
+ ),
("API.RESEARCH_REPORT", "/api/report/<string:research_id>"),
("API.TERMINATE_RESEARCH", "/api/terminate/<string:research_id>"),
("API.DELETE_RESEARCH", "/api/delete/<string:research_id>"),
diff --git a/tests/web/routes/test_research_routes.py b/tests/web/routes/test_research_routes.py
index b843c9bd72..e74dce6921 100644
--- a/tests/web/routes/test_research_routes.py
+++ b/tests/web/routes/test_research_routes.py
@@ -701,6 +701,212 @@ class TestGetResearchLogsApi:
self._close_session(session)
+class TestExportResearchLogsApi:
+ """Tests for /api/research/<id>/logs/export streaming endpoint."""
+
+ def test_requires_authentication(self, client):
+ """Should require authentication."""
+ response = client.get(
+ f"{RESEARCH_PREFIX}/api/research/test-id/logs/export"
+ )
+ assert response.status_code == 401, response.status_code
+
+ @staticmethod
+ def _build_engine_with_seed(num_logs, rid="test-rid"):
+ """Build an in-memory SQLite engine, create the schema, seed one
+ research + ``num_logs`` log rows, and return ``(engine, session)``
+ bound to that engine. Returning the engine (not just the session)
+ lets the test ``.dispose()`` it to release the underlying
+ sqlite connection — otherwise pytest reports a ResourceWarning.
+
+ ``export_research_logs`` opens ``get_user_db_session`` *twice*
+ (existence check + streaming generator). Both calls must see the
+ same committed rows, so the test patches the factory to hand out
+ a single shared session against this engine rather than building
+ two separate in-memory DBs.
+ """
+ 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=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=rid,
+ timestamp=base_time + timedelta(minutes=i),
+ message=f"Log {i}",
+ module="test",
+ function="test",
+ line_no=i,
+ level="INFO",
+ )
+ )
+ session.commit()
+ return engine, session
+
+ @staticmethod
+ def _patch_session(session):
+ """Patch ``get_user_db_session`` so every call returns a context
+ manager yielding the same ``session``. ``export_research_logs``
+ calls the factory twice (existence check + streaming); reusing one
+ session keeps the in-memory DB contract simple.
+ """
+ cm = MagicMock()
+ cm.__enter__ = lambda self: session
+ cm.__exit__ = MagicMock(return_value=False)
+ return patch(f"{_RR}.get_user_db_session", return_value=cm)
+
+ @staticmethod
+ def _teardown(engine, session):
+ """Close the session AND dispose the engine so the underlying
+ sqlite connection is released; otherwise pytest reports a
+ ResourceWarning."""
+ session.close()
+ engine.dispose()
+
+ def test_returns_404_when_research_missing(self, authenticated_client):
+ """A non-existent research must short-circuit before any streaming
+ session is opened — otherwise the user pays for a generator that
+ always emits zero rows."""
+ from sqlalchemy import create_engine
+ from sqlalchemy.orm import sessionmaker
+
+ from local_deep_research.database.models import Base
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ empty_session = sessionmaker(bind=engine)()
+
+ try:
+ with self._patch_session(empty_session):
+ resp = authenticated_client.get(
+ f"{RESEARCH_PREFIX}/api/research/test-rid/logs/export"
+ )
+ assert resp.status_code == 404, resp.status_code
+ assert resp.get_json()["error"] == "Research not found"
+ finally:
+ empty_session.close()
+ engine.dispose()
+
+ def test_streams_all_logs_as_ndjson(self, authenticated_client):
+ """Every persisted row must appear in the response body, oldest
+ first, one JSON object per line.
+ """
+ import json
+
+ num_logs = 7 # multiple log rows to verify streaming NDJSON structure
+ engine, seed = self._build_engine_with_seed(num_logs)
+ try:
+ with self._patch_session(seed):
+ resp = authenticated_client.get(
+ f"{RESEARCH_PREFIX}/api/research/test-rid/logs/export"
+ )
+
+ assert resp.status_code == 200, resp.status_code
+ # NDJSON is one JSON object per line, terminated by '\n'.
+ # The last line is allowed to lack a trailing newline depending
+ # on the writer, so rstrip is required before splitting.
+ lines = resp.get_data(as_text=True).rstrip("\n").split("\n")
+ assert len(lines) == num_logs, len(lines)
+
+ parsed = [json.loads(line) for line in lines]
+ messages = [entry["message"] for entry in parsed]
+ assert messages == [f"Log {i}" for i in range(num_logs)]
+ # Oldest-first: Log 0 precedes Log N-1.
+ assert messages[0] == "Log 0"
+ assert messages[-1] == f"Log {num_logs - 1}"
+
+ # All required fields (including log_type aligned with /logs) are present on every row.
+ for entry in parsed:
+ assert set(entry.keys()) == {
+ "id",
+ "timestamp",
+ "message",
+ "level",
+ "log_type",
+ "module",
+ "line_no",
+ }
+ finally:
+ self._teardown(engine, seed)
+
+ def test_response_is_streamed(self, authenticated_client):
+ """``Response.is_streamed`` must be true so Flask returns the
+ generator to the WSGI server as an iterator rather than
+ materialising it. This is the property that makes the export
+ memory-bounded on the server."""
+ engine, seed = self._build_engine_with_seed(3)
+ try:
+ with self._patch_session(seed):
+ resp = authenticated_client.get(
+ f"{RESEARCH_PREFIX}/api/research/test-rid/logs/export"
+ )
+ assert resp.status_code == 200, resp.status_code
+ assert resp.is_streamed is True, resp.is_streamed
+ assert resp.headers["Content-Disposition"].startswith(
+ "attachment; filename="
+ )
+ assert resp.headers["Content-Disposition"].endswith('.jsonl"')
+ assert resp.mimetype == "application/x-ndjson"
+ finally:
+ self._teardown(engine, seed)
+
+ def test_zero_logs_returns_empty_body(self, authenticated_client):
+ """A research with zero logs is a valid state (e.g. still running).
+ The endpoint must return 200 + an empty body rather than erroring
+ on the empty generator — otherwise users would see a 500 for a
+ perfectly normal research."""
+ engine, seed = self._build_engine_with_seed(0)
+ try:
+ with self._patch_session(seed):
+ resp = authenticated_client.get(
+ f"{RESEARCH_PREFIX}/api/research/test-rid/logs/export"
+ )
+ assert resp.status_code == 200, resp.status_code
+ assert resp.get_data() == b""
+ finally:
+ self._teardown(engine, seed)
+
+ def test_filename_sanitization_prevents_header_breakout(
+ self, authenticated_client
+ ):
+ """Research IDs containing quotes or special characters must have those
+ stripped in Content-Disposition header so header breakout is impossible.
+ """
+ engine, seed = self._build_engine_with_seed(0, rid='test-rid"extra')
+ try:
+ with self._patch_session(seed):
+ resp = authenticated_client.get(
+ f"{RESEARCH_PREFIX}/api/research/test-rid%22extra/logs/export"
+ )
+ assert resp.status_code == 200, resp.status_code
+ cd = resp.headers["Content-Disposition"]
+ assert 'filename="research_logs_test-ridextra.jsonl"' in cd
+ finally:
+ self._teardown(engine, seed)
+
+
class TestGetResearchStatusApi:
"""Tests for /api/research/<id>/status endpoint."""