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(research): detailed reports bypass report.enable_file_backup (H2) (#4684)

LearningCircuitbd08f686d5ec
diff --git a/changelog.d/+detailed-report-file-backup.bugfix.md b/changelog.d/+detailed-report-file-backup.bugfix.md
new file mode 100644
index 0000000000..e859c7a597
--- /dev/null
+++ b/changelog.d/+detailed-report-file-backup.bugfix.md
@@ -0,0 +1 @@
+Detailed-mode research reports now honor the ``report.enable_file_backup`` setting. The detailed completion path saved ``report_content`` via a raw ORM write that bypassed the report-storage abstraction, so a user who enabled file backup got on-disk ``.md``/``_metadata.json`` files for quick-mode research but silently never for detailed-mode research. Route the detailed save through ``get_report_storage().save_report()`` exactly like the quick and error paths already do (DRY-review finding H2).
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 9cdeba4939..40a1e3a4bb 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -1949,8 +1949,10 @@ def run_research_process(research_id, query, mode, **kwargs):
research.status = ResearchStatus.COMPLETED
research.completed_at = completed_at
research.duration_seconds = duration_seconds
- # Note: report_content is saved by CachedResearchService
- # report_path is not used in encrypted database version
+ # report_content was already saved above via the report
+ # storage abstraction; this block only updates
+ # status/metadata. report_path is not used in the
+ # encrypted-database version.
# Generate headline and topics only for news searches
if (
@@ -2158,37 +2160,30 @@ def run_research_process(research_id, query, mode, **kwargs):
# Save report FIRST, sources after.
# See quick-summary path for rationale.
+ from ...storage import get_report_storage
+
with get_user_db_session(username) as db_session:
- # Update metadata
+ storage = get_report_storage(session=db_session)
+
+ # Update metadata. Include generated_at like the quick path so
+ # the detailed file backup's _metadata.json has parity with
+ # quick-mode (the detailed path previously omitted it).
metadata = final_report["metadata"]
metadata["iterations"] = results["iterations"]
-
- # Save report to database
- try:
- research = (
- db_session.query(ResearchHistory)
- .filter_by(id=research_id)
- .first()
- )
-
- if not research:
- logger.error(f"Research {research_id} not found")
- success = False
- else:
- research.report_content = formatted_content
- if research.research_meta:
- research.research_meta.update(metadata)
- else:
- research.research_meta = metadata
- db_session.commit()
- success = True
- logger.info(
- f"Saved report for research {research_id} to database"
- )
- except Exception:
- logger.exception("Error saving report to database")
- db_session.rollback()
- success = False
+ metadata["generated_at"] = datetime.now(UTC).isoformat()
+
+ # Save the report through the storage abstraction, exactly as
+ # the quick-summary branch does, so detailed reports also honor
+ # the report.enable_file_backup setting. This previously did a
+ # raw ORM write of report_content that silently skipped the
+ # file backup, so a user who enabled file backup got it for
+ # quick research but never for detailed research.
+ success = storage.save_report(
+ research_id=research_id,
+ content=formatted_content,
+ metadata=metadata,
+ username=username,
+ )
if not success:
raise RuntimeError("Failed to save research report") # noqa: TRY301 — triggers research failure handling in outer except
@@ -2242,8 +2237,9 @@ def run_research_process(research_id, query, mode, **kwargs):
research.status = ResearchStatus.COMPLETED
research.completed_at = completed_at
research.duration_seconds = duration_seconds
- # Note: report_content is saved by CachedResearchService
- # report_path is not used in encrypted database version
+ # report_content was already saved above via the report storage
+ # abstraction; this block only updates status/metadata.
+ # report_path is not used in the encrypted-database version.
# Generate headline and topics only for news searches
if (
diff --git a/tests/web/services/test_research_service_coverage.py b/tests/web/services/test_research_service_coverage.py
index b592891f55..aa49a6434f 100644
--- a/tests/web/services/test_research_service_coverage.py
+++ b/tests/web/services/test_research_service_coverage.py
@@ -978,6 +978,14 @@ class TestRunResearchProcessDetailedMode:
"""Detailed/full report mode."""
def test_detailed_mode_success(self):
+ """Detailed completion saves the report through the storage
+ abstraction (get_report_storage), exactly like the quick path.
+
+ Guards the H2 fix: the detailed path previously did a raw ORM write
+ of report_content that bypassed get_report_storage and therefore the
+ report.enable_file_backup feature. If that regresses, save_report
+ stops being called and this fails.
+ """
mock_session = MagicMock()
research = _make_research_mock()
mock_session.query.return_value.filter_by.return_value.first.return_value = research
@@ -996,7 +1004,15 @@ class TestRunResearchProcessDetailedMode:
mock_system.analyze_topic.return_value = results
mock_formatter = MagicMock()
- mock_formatter.format_document.return_value = "formatted report"
+ # Exercise the normal citation path: format_document_split returns the
+ # answer body plus non-empty sources, so apply_inline_hyperlinks is
+ # skipped and the over-strip safety check is not triggered for this
+ # short content. (Without this stub the test passes only via the
+ # formatter's exception fallback, which is fragile.)
+ mock_formatter.format_document_split.return_value = (
+ "# Full Report",
+ [{"url": "u"}],
+ )
mock_report_gen = MagicMock()
mock_report_gen.generate_report.return_value = {
@@ -1004,6 +1020,9 @@ class TestRunResearchProcessDetailedMode:
"metadata": {"sections": 3},
}
+ mock_storage = MagicMock()
+ mock_storage.save_report.return_value = True
+
mock_sources_service = MagicMock()
mock_sources_service.save_research_sources.return_value = 1
mock_qp = MagicMock()
@@ -1036,6 +1055,10 @@ class TestRunResearchProcessDetailedMode:
patch(
f"{RS}.IntegratedReportGenerator", return_value=mock_report_gen
),
+ patch(
+ "local_deep_research.storage.get_report_storage",
+ return_value=mock_storage,
+ ),
patch(
f"{RS}.extract_links_from_search_results",
return_value=[],
@@ -1064,6 +1087,142 @@ class TestRunResearchProcessDetailedMode:
search_engine="s",
)
assert research.status == "completed"
+ # Detailed routes report-save through the storage abstraction (the
+ # H2 fix), passing the DETAILED report content.
+ mock_storage.save_report.assert_called_once()
+ assert (
+ mock_storage.save_report.call_args.kwargs["content"]
+ == "# Full Report"
+ )
+
+ def test_detailed_mode_writes_file_backup_when_enabled(self):
+ """Detailed completion writes the on-disk file backup when the
+ report.enable_file_backup setting is on.
+
+ The user-visible half of the H2 fix: because the detailed path now
+ routes through get_report_storage -> DatabaseWithFileBackupStorage, a
+ user who enabled file backup gets files for detailed research, not
+ only quick research. On the old raw ORM write get_report_storage was
+ never called for detailed, so FileReportStorage was never invoked and
+ this would fail.
+ """
+ from local_deep_research.storage.database_with_file_backup import (
+ DatabaseWithFileBackupStorage,
+ )
+
+ mock_session = MagicMock()
+ research = _make_research_mock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = research
+
+ mock_system = MagicMock()
+ mock_search_system = MagicMock()
+ mock_search_system.all_links_of_system = [
+ {"url": "http://a.com", "title": "A"}
+ ]
+ results = {
+ "findings": [{"content": "data"}],
+ "formatted_findings": "# Report",
+ "iterations": 5,
+ "search_system": mock_search_system,
+ }
+ mock_system.analyze_topic.return_value = results
+
+ mock_report_gen = MagicMock()
+ mock_report_gen.generate_report.return_value = {
+ "content": "# Full Report",
+ "metadata": {"sections": 3},
+ }
+
+ # Exercise the normal citation path (see test_detailed_mode_success)
+ # rather than the formatter's exception fallback.
+ mock_formatter = MagicMock()
+ mock_formatter.format_document_split.return_value = (
+ "# Full Report",
+ [{"url": "u"}],
+ )
+
+ mock_file_storage = MagicMock()
+ mock_file_storage.save_report.return_value = True
+
+ mock_sources_service = MagicMock()
+ mock_sources_service.save_research_sources.return_value = 1
+ mock_qp = MagicMock()
+
+ with (
+ patch(
+ "local_deep_research.web.routes.globals.is_termination_requested",
+ return_value=False,
+ ),
+ patch(
+ "local_deep_research.web.routes.globals.is_research_active",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.web.routes.globals.update_progress_and_check_active",
+ return_value=(50, True),
+ ),
+ patch(f"{RS}.get_llm", return_value=MagicMock()),
+ patch(f"{RS}.get_search", return_value=MagicMock()),
+ patch(f"{RS}.AdvancedSearchSystem", return_value=mock_system),
+ patch(f"{RS}.get_citation_formatter", return_value=mock_formatter),
+ patch(
+ f"{RS}.get_user_db_session",
+ side_effect=_fake_session_ctx(mock_session),
+ ),
+ patch(f"{RS}.cleanup_research_resources"),
+ patch(f"{RS}.SocketIOService"),
+ patch(f"{RS}.set_search_context"),
+ patch(f"{RS}.calculate_duration", return_value=20.0),
+ patch(
+ f"{RS}.IntegratedReportGenerator", return_value=mock_report_gen
+ ),
+ # The on-disk writer is mocked so the test touches no filesystem.
+ patch(
+ "local_deep_research.storage.database_with_file_backup.FileReportStorage",
+ return_value=mock_file_storage,
+ ),
+ # Construct the real backup-aware storage lazily (at call time, so
+ # the FileReportStorage patch above is active) with backup ENABLED.
+ patch(
+ "local_deep_research.storage.get_report_storage",
+ side_effect=lambda *a, **kw: DatabaseWithFileBackupStorage(
+ session=mock_session, enable_file_storage=True
+ ),
+ ),
+ patch(
+ f"{RS}.extract_links_from_search_results",
+ return_value=[],
+ ),
+ patch(
+ "local_deep_research.web.services.research_sources_service.ResearchSourcesService",
+ return_value=mock_sources_service,
+ ),
+ patch(
+ "local_deep_research.web.queue.processor_v2.queue_processor",
+ mock_qp,
+ ),
+ patch("local_deep_research.settings.logger.log_settings"),
+ patch(
+ "local_deep_research.config.thread_settings.set_settings_context"
+ ),
+ ):
+ raw_fn = _get_raw_run_research_process()
+ raw_fn(
+ "r1",
+ "query",
+ "detailed",
+ username="alice",
+ settings_snapshot={},
+ model="m",
+ search_engine="s",
+ )
+
+ # The file backup was written exactly once, with the detailed report
+ # content (positional: research_id, content, metadata, username).
+ mock_file_storage.save_report.assert_called_once()
+ assert (
+ mock_file_storage.save_report.call_args.args[1] == "# Full Report"
+ )
def test_detailed_mode_report_not_found_raises(self):
mock_session = MagicMock()