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.

fix(logs): exclude HEAD preflight from export quota (#5369)

Ziyang Guo5d872f872532
diff --git a/changelog.d/+log-export-head-rate-limit.bugfix.md b/changelog.d/+log-export-head-rate-limit.bugfix.md
new file mode 100644
index 0000000000..c7151786f5
--- /dev/null
+++ b/changelog.d/+log-export-head-rate-limit.bugfix.md
@@ -0,0 +1 @@
+Exclude log-export HEAD pre-flight checks from the per-user GET download quota.
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index e001934205..b6c9c1d220 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -1790,11 +1790,16 @@ def get_research_logs(research_id):
return jsonify({"error": "An internal error has occurred"}), 500
+def _is_log_export_rate_limit_exempt():
+ """Keep HEAD pre-flights outside the GET export quota."""
+ return request.method == "HEAD" or _is_api_rate_limit_exempt()
+
+
_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,
+ exempt_when=_is_log_export_rate_limit_exempt,
)
diff --git a/tests/js/components/logpanel.test.js b/tests/js/components/logpanel.test.js
index 58c4cbf82a..6ecb7ac7e4 100644
--- a/tests/js/components/logpanel.test.js
+++ b/tests/js/components/logpanel.test.js
@@ -33,6 +33,7 @@ beforeAll(async () => {
researchLogs: (id, limit) =>
`/api/research/${id}/logs${limit ? `?limit=${limit}` : ''}`,
historyLogCount: (id) => `/api/research/${id}/log_count`,
+ researchLogsExport: (id) => `/api/research/${id}/logs/export`,
};
// Pretend we're on a research page so the auto-initialize path runs.
@@ -120,6 +121,7 @@ function setupPanelDom({ page = 'progress', researchId } = {}) {
</div>
</div>
<button id="log-autoscroll-button" class="ldr-selected"></button>
+ <button id="log-download-button"></button>
</div>
<div class="ldr-console-log" id="console-log-container"></div>
</div>
@@ -2436,6 +2438,73 @@ describe('pruneToCap — per-category ordered prune', () => {
});
});
+describe('downloadLogs — HEAD pre-flight', () => {
+ const researchId = 'download-rid';
+ const exportUrl = `/api/research/${researchId}/logs/export`;
+
+ beforeEach(() => {
+ window.ui = { showAlert: vi.fn() };
+ setupPanelDom({ page: 'progress', researchId });
+ });
+
+ afterEach(() => {
+ delete window.ui;
+ vi.restoreAllMocks();
+ });
+
+ it.each([
+ [404, 'Research logs not found.'],
+ [429, 'Log export rate limit exceeded. Please wait a moment.'],
+ [500, 'Failed to export logs (HTTP 500).'],
+ ])(
+ 'shows an error and skips the download for HTTP %i',
+ async (status, message) => {
+ globalThis.fetch = vi.fn().mockResolvedValue({
+ ok: false,
+ status,
+ });
+ const anchorClick = vi
+ .spyOn(window.HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(() => {});
+
+ document.getElementById('log-download-button').click();
+
+ await vi.waitFor(() => {
+ expect(window.ui.showAlert).toHaveBeenCalledWith(
+ message,
+ 'error'
+ );
+ });
+ expect(globalThis.fetch).toHaveBeenCalledWith(exportUrl, {
+ method: 'HEAD',
+ });
+ expect(anchorClick).not.toHaveBeenCalled();
+ }
+ );
+
+ it('continues with the native download when the pre-flight request fails', async () => {
+ globalThis.fetch = vi.fn().mockRejectedValue(new Error('network down'));
+ const anchorClick = vi
+ .spyOn(window.HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(() => {});
+
+ document.getElementById('log-download-button').click();
+
+ await vi.waitFor(() => {
+ expect(anchorClick).toHaveBeenCalledOnce();
+ });
+ expect(globalThis.fetch).toHaveBeenCalledWith(exportUrl, {
+ method: 'HEAD',
+ });
+ expect(window.ui.showAlert).not.toHaveBeenCalled();
+ expect(
+ document.querySelector(
+ `a[download="research_logs_${researchId}.jsonl"]`
+ )
+ ).toBeNull();
+ });
+});
+
describe('addLog — live pruning integration', () => {
function setupLivePanel(renderedLimit) {
setupPanelDom({ page: 'progress', researchId: null });
diff --git a/tests/web/routes/test_research_log_export_rate_limit.py b/tests/web/routes/test_research_log_export_rate_limit.py
new file mode 100644
index 0000000000..4bffe028cd
--- /dev/null
+++ b/tests/web/routes/test_research_log_export_rate_limit.py
@@ -0,0 +1,114 @@
+"""Rate-limit contract tests for research log exports."""
+
+from contextlib import contextmanager
+from unittest.mock import MagicMock, patch
+
+import pytest
+from flask import Flask
+
+from local_deep_research.database.models import ResearchHistory, ResearchLog
+from local_deep_research.security.rate_limiter import limiter
+from local_deep_research.web.routes.research_routes import (
+ _is_log_export_rate_limit_exempt,
+ research_bp,
+)
+
+
+_RR = "local_deep_research.web.routes.research_routes"
+
+
+def rate_limited_app():
+ """Register the real route with Flask-Limiter enabled."""
+ original_enabled = limiter.enabled
+ app = Flask(__name__)
+ app.config.update(
+ SECRET_KEY="test-secret",
+ TESTING=True,
+ RATELIMIT_ENABLED=True,
+ RATELIMIT_STRATEGY="moving-window",
+ )
+ app.register_blueprint(research_bp)
+ limiter.enabled = True
+ limiter.init_app(app)
+ with app.app_context():
+ limiter.reset()
+
+ yield app
+
+ with app.app_context():
+ limiter.reset()
+ limiter.enabled = original_enabled
+
+
+ ("method", "base_exempt", "expected", "base_calls"),
+ [
+ ("HEAD", False, True, 0),
+ ("GET", False, False, 1),
+ ("GET", True, True, 1),
+ ],
+)
+def test_log_export_exemption_preserves_api_rules(
+ rate_limited_app, method, base_exempt, expected, base_calls
+):
+ """Only HEAD bypasses the existing API exemption decision."""
+ with rate_limited_app.test_request_context(method=method):
+ with patch(
+ f"{_RR}._is_api_rate_limit_exempt",
+ return_value=base_exempt,
+ ) as base_check:
+ assert _is_log_export_rate_limit_exempt() is expected
+ assert base_check.call_count == base_calls
+
+
+def test_head_preflights_do_not_consume_get_export_quota(rate_limited_app):
+ """Ten HEAD checks leave all ten per-minute GET slots available."""
+ db_session = MagicMock()
+ history_query = MagicMock()
+ history_query.filter_by.return_value.first.return_value = object()
+ log_query = MagicMock()
+ log_query.filter_by.return_value.order_by.return_value.yield_per.return_value = []
+
+ def query(model):
+ if model is ResearchHistory:
+ return history_query
+ assert model is ResearchLog
+ return log_query
+
+ db_session.query.side_effect = query
+
+ @contextmanager
+ def user_db_session(*_args, **_kwargs):
+ yield db_session
+
+ client = rate_limited_app.test_client()
+ with client.session_transaction() as flask_session:
+ flask_session["username"] = "rate-limit-user"
+
+ url = "/api/research/test-rid/logs/export"
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager.is_user_connected",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.security.rate_limiter._get_user_api_rate_limit",
+ return_value=60,
+ ),
+ patch(
+ f"{_RR}.get_user_db_session",
+ side_effect=user_db_session,
+ ),
+ ):
+ for request_number in range(1, 11):
+ response = client.head(url)
+ assert response.status_code == 200, request_number
+ response.close()
+
+ for request_number in range(1, 11):
+ response = client.get(url)
+ assert response.status_code == 200, request_number
+ response.close()
+
+ assert client.get(url).status_code == 429