~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
"""Reconstruct the legacy "full report" view from structured storage.
`research.report_content` stores only the synthesized answer (with inline
`[N](url)` hyperlinks). Sources live in the `research_resources` table;
metrics live in `research.research_meta`. This module rebuilds the
combined `answer + ## Sources + ## Research Metrics` view on demand for
display and export — chat reads `research.report_content` directly and
never goes through this module.
The legacy Sources guard expects the first non-blank entry to use the
bracketed bibliography shape (`[N]`, grouped `[N, M]`, or historical `[]`)
and to carry an indented `URL:` continuation line. Indexed entries mirror
`text_optimization.citation_formatter._BIB_SOURCES_PATTERN`; the empty-index
variant covers rows emitted before every source had an index. The currently
dormant `advanced_search_system.findings.repository.format_links` instead
emits `1. Title` entries, so it must not become a persisted Sources emitter
without extending this guard and its round-trip tests.
DO NOT write the assembled output back to `research.report_content` —
that column must stay answer-only. Writing assembled output back would
silently re-introduce the regex over-strip class of bugs that
answer-only storage avoids.
"""
import json
import re
from typing import Any, Dict, List, Optional
from loguru import logger
from sqlalchemy.orm import Session
from ...database.models.research import ResearchHistory, ResearchResource
from ...text_optimization.citation_formatter import (
strip_appended_sources_sentinel,
)
from ...utilities.search_utilities import (
UNCITED_SOURCES_MODE_KEY,
UNCITED_SOURCES_MODES,
format_links_to_markdown,
resolve_uncited_sources_mode,
)
from ...utilities.url_utils import FETCHED_TITLE_KEY, canonical_url_key
# Line-anchored regexes for the legacy-row guard. See `assemble_full_report`
# for why a substring `in body` check is too loose. A Sources heading alone is
# not enough: LLMs sometimes emit one followed by placeholder prose. Require
# the first non-blank line to be a bracket-shaped legacy bibliography entry,
# including grouped indices and the historical empty-index shape, and require
# its URL continuation line so bracket-led prose cannot trip the guard.
_LEGACY_SOURCES_RE = re.compile(
r"^## Sources\b[^\r\n]*\r?\n"
r"(?:[ \t]*\r?\n)*[ \t]*\[(?:\d+(?:[ \t]*,[ \t]*\d+)*)?\]"
r"[^\r\n]*\r?\n[ \t]+URL:[ \t]*\S",
re.MULTILINE,
)
_LEGACY_METRICS_RE = re.compile(r"^## Research Metrics\b", re.MULTILINE)
def _current_user_uncited_mode(db_session: Session) -> Optional[str]:
"""Read the requesting user's CURRENT saved uncited-sources mode.
Covers legacy rows that completed before snapshots were persisted
(chat/follow-up research created and finished before #6747): those
rows carry only ``{"submission": ...}`` forever, so the row snapshot
cannot decide the render. The requesting user's current preference is
the best available signal — it is what a re-run would generate with.
Returns the validated mode, or ``None`` when the setting is missing,
malformed, or unreadable (caller falls through to the thread context
and then ``"fallback"``). Never raises: rendering a report must not
crash on a preference read.
"""
try:
from ...settings.manager import SettingsManager
raw = SettingsManager(db_session).get_setting(
UNCITED_SOURCES_MODE_KEY, None
)
except Exception:
logger.debug(
"report assembly: current uncited-sources mode unreadable; "
"falling back",
exc_info=True,
)
return None
if isinstance(raw, dict):
raw = raw.get("value")
if isinstance(raw, str) and raw.strip() in UNCITED_SOURCES_MODES:
return raw.strip()
return None
def _research_metadata(research) -> Dict[str, Any]:
"""Read metadata from current rows and legacy JSON-string rows."""
try:
meta = getattr(research, "research_meta", None)
if isinstance(meta, str):
meta = json.loads(meta)
return meta if isinstance(meta, dict) else {}
except (json.JSONDecodeError, TypeError):
return {}
def _research_settings_snapshot(research) -> Optional[Dict[str, Any]]:
"""Return the saved ``settings_snapshot`` for a research row, if any.
Report/history routes run without a research-worker settings context,
so resolving ``report.uncited_sources_mode`` from the thread context
alone always yields ``fallback`` — even when the user saved
``disabled`` or ``strict``. The snapshot captured at research start
(``research_meta["settings_snapshot"]``) is the applicable saved
preference and must be passed explicitly.
"""
try:
snap = _research_metadata(research).get("settings_snapshot")
return snap if isinstance(snap, dict) else None
except Exception:
return None
def assemble_full_report(
research: Optional[ResearchHistory],
db_session: Session,
uncited_mode: Optional[str] = None,
settings_snapshot: Optional[Dict[str, Any]] = None,
) -> Optional[str]:
"""Reconstruct the legacy report shape from structured storage.
Args:
research: The ResearchHistory ORM row. Must be loaded inside
the supplied ``db_session`` to avoid DetachedInstanceError
when accessing ``research.research_meta`` lazily.
db_session: Active SQLAlchemy session bound to the user DB.
Used to query ``research_resources`` for the sources block.
uncited_mode: Explicit ``report.uncited_sources_mode`` override.
When ``None`` (default), a saved value in the research row's
snapshot is honored. Legacy snapshots without this setting use
the requesting user's current preference.
settings_snapshot: Explicit settings snapshot override. It takes
precedence over the row only when it contains this setting.
Returns:
``None`` when ``research`` is ``None`` (caller should map to
404). Otherwise assembled markdown: answer + optional
``## Sources`` block + optional ``## Research Metrics`` block.
An existing row with no body / sources / metrics returns an
empty string ``""`` (a valid empty-but-found response).
"""
if research is None:
return None
# Detailed reports saved in NO_HYPERLINKS mode, or after the citation
# formatter raised, before the save site removed it, still carry the
# report generator's appended-sources sentinel. It is an HTML comment,
# which renderMarkdown() shows as literal text, so it is removed before
# the body is displayed or exported.
body = strip_appended_sources_sentinel(research.report_content or "")
# Legacy-row guard: older rows already contain inline
# `## Sources` / `## Research Metrics` blocks in report_content. If
# we appended freshly-assembled sections to those rows we'd render
# the blocks twice. Match only at line-start to avoid false positives
# from prose that happens to contain the substring `## Sources` inline
# (e.g. an answer that quotes another markdown document).
has_legacy_sources = bool(_LEGACY_SOURCES_RE.search(body))
has_legacy_metrics = bool(_LEGACY_METRICS_RE.search(body))
parts = [body]
if not has_legacy_sources:
# Let any failure propagate: the callers already wrap this in a
# try/except that returns HTTP 500. Swallowing it here would emit a
# report that looks complete but is silently missing all sources.
sources_md = _build_sources_markdown(
research,
db_session,
body=body,
uncited_mode=uncited_mode,
settings_snapshot=settings_snapshot,
)
if sources_md:
parts.append("## Sources\n\n" + sources_md)
if not has_legacy_metrics:
metrics_md = _build_metrics_markdown(research)
if metrics_md:
parts.append("## Research Metrics\n" + metrics_md)
return "\n\n".join(parts)
def _build_metrics_markdown(research: ResearchHistory) -> str:
"""Render the Research Metrics block from persisted metadata.
Today the inline metrics block (research_service.py quick-summary
path) used ``results["iterations"]`` and a fresh save-time
timestamp. Both end up in ``research.research_meta`` (the save site
persists ``metadata["iterations"]`` and ``metadata["generated_at"]``)
so this read recovers the same values. Falls back to
``research.completed_at`` for the timestamp when ``generated_at`` is
missing (legacy rows or scheduler-saved research).
Returns an empty string when nothing meaningful can be rendered.
"""
meta = _research_metadata(research)
iterations = meta.get("iterations")
generated_at = meta.get("generated_at") or research.completed_at
lines = []
if iterations is not None:
lines.append(f"- Search Iterations: {iterations}")
if generated_at:
lines.append(f"- Generated at: {generated_at}")
return "\n".join(lines)
def _build_sources_markdown(
research: ResearchHistory,
db_session: Session,
body: str = "",
uncited_mode: Optional[str] = None,
settings_snapshot: Optional[Dict[str, Any]] = None,
) -> str:
"""Render the Sources block from the ``research_resources`` table.
Maps each ResearchResource row back to the dict shape
``format_links_to_markdown`` expects, preferring the original
citation index from ``resource_metadata['original_data']['index']``
(assigned by the search system at search time, and the number the
inline ``[N]`` references in the saved answer point to). Falls
back to row order when the original index was lost on save.
Only resources cited in ``body`` (the saved answer) are listed,
honoring ``report.uncited_sources_mode``. The saved snapshot on
the research row wins over the thread-local worker context (which
report/history routes never install): an explicit ``uncited_mode``
wins first, then an explicit snapshot containing this setting, then
the row's own snapshot containing it, then — for older rows that
lack this setting — the requesting user's current saved setting,
then the thread context.
"""
resources = (
db_session.query(ResearchResource)
.filter_by(research_id=research.id)
.order_by(ResearchResource.id.asc())
.all()
)
all_links: List[Dict[str, Any]] = []
missing_index_count = 0
for fallback_idx, r in enumerate(resources, start=1):
# Defensive: legacy rows may have stored metadata as a string.
meta = (
r.resource_metadata if isinstance(r.resource_metadata, dict) else {}
)
original = (
meta.get("original_data")
if isinstance(meta.get("original_data"), dict)
else {}
)
# ``is None`` (not ``not``) so 0 isn't treated as missing.
index = original.get("index")
if index is None or index == "":
missing_index_count += 1
index = str(fallback_idx)
all_links.append(
{
"url": str(r.url) if r.url else "",
"title": str(r.title) if r.title else "Untitled",
"index": index,
"journal_quality": original.get("journal_quality"),
# A fetched title can predate an archive upgrade. Retain
# the capture metadata so the renderer still adds its date.
"source_type": original.get("source_type", r.source_type),
"original_url": original.get("original_url"),
"requested_url": original.get("requested_url"),
"timestamp": original.get("timestamp"),
"formatted_date": original.get("formatted_date"),
# ``title`` above is the column, which the search hit wrote.
# Rows saved before this key existed return None, which the
# renderer ignores.
FETCHED_TITLE_KEY: original.get(FETCHED_TITLE_KEY),
}
)
if missing_index_count:
# DEBUG (not WARNING): expected for legacy rows / URL-less
# entries skipped at save time. Render correctness is preserved
# via row-order fallback. Bind research_id so the message
# routes through the per-research log table.
logger.bind(research_id=research.id).debug(
"_build_sources_markdown: {} of {} rows missing original "
"citation index; using row order. Common cause: URL-less "
"entries were skipped at save time.",
missing_index_count,
len(resources),
)
return format_links_to_markdown(
all_links,
prose=body,
uncited_mode=_resolve_saved_uncited_mode(
research,
uncited_mode=uncited_mode,
settings_snapshot=settings_snapshot,
db_session=db_session,
),
)
def _resolve_saved_uncited_mode(
research,
uncited_mode: Optional[str] = None,
settings_snapshot: Optional[Dict[str, Any]] = None,
db_session: Optional[Session] = None,
) -> str:
"""Resolve the effective uncited-sources mode for a saved research row.
Precedence: explicit ``uncited_mode`` > explicit snapshot value >
the row's own saved snapshot value > the requesting user's current
saved setting > thread context (which report routes never install) >
``"fallback"``. A snapshot without this key is not an override.
"""
if uncited_mode is not None:
return resolve_uncited_sources_mode(uncited_mode)
if (
isinstance(settings_snapshot, dict)
and UNCITED_SOURCES_MODE_KEY in settings_snapshot
):
return resolve_uncited_sources_mode(
None, settings_snapshot=settings_snapshot
)
row_snapshot = _research_settings_snapshot(research)
if row_snapshot is not None and UNCITED_SOURCES_MODE_KEY in row_snapshot:
return resolve_uncited_sources_mode(
None, settings_snapshot=row_snapshot
)
if db_session is not None:
current = _current_user_uncited_mode(db_session)
if current is not None:
return current
return resolve_uncited_sources_mode(None, settings_snapshot=None)
def _format_source_link(row: ResearchResource) -> Optional[Dict[str, str]]:
"""Map one ``research_resources`` row to the news feed's link shape.
Shared by :func:`get_research_source_links` and its batched variant so
the two cannot drift. Returns ``None`` for a row the feed cannot link
to: a non-``http`` URL, or a ``url`` that is not a string at all.
Titles fall back to the bare domain when missing and are truncated to
50 chars, matching the existing list-card rendering in the news UI.
A non-``str`` ``url`` is skipped, not coerced — the same rule
``count_distinct_sources`` and ``format_links_to_markdown`` already
apply, and for the same reason: the caller passes this result to
:func:`_dedup_key`, and ``canonical_url_key`` raises on a non-str
(it unpacks ``str.partition``). Coercing with ``str()`` instead would
render a Python repr as a clickable link. ``title`` gets the same
treatment, so a malformed row degrades to the domain fallback rather
than printing a repr onto a news card.
"""
if not isinstance(row.url, str):
return None
url = row.url.strip()
if not url.startswith("http"):
return None
title = (row.title if isinstance(row.title, str) else "").strip()
if not title:
domain = url.split("//")[-1].split("/")[0]
title = domain.replace("www.", "")
if len(title) > 50:
title = title[:50] + "..."
return {"url": url, "title": title}
def _dedup_key(url: str) -> str:
"""Canonical grouping key for a source link.
The SAME key ``format_links_to_markdown`` groups the bibliography by
and ``count_distinct_sources`` counts with, so a "top 3 sources" card,
the rendered ``## Sources`` block and the reported source count cannot
disagree about what counts as one source. Falls back to the raw URL if
canonicalization yields nothing, so an unrecognizable URL stays its
own source rather than merging with every other unrecognizable one.
"""
return canonical_url_key(url) or url
def get_research_source_links(
research_id: str, db_session: Session, limit: int = 3
) -> List[Dict[str, str]]:
"""Top-N DISTINCT source links for a research, in row-insertion order.
Returns dicts shaped ``{"url": str, "title": str}`` matching the
news feed's ``links`` contract (``news/api.py`` consumers). Titles
are domain-fallback when missing, truncated to 50 chars to match
the existing list-card rendering in the news UI.
Deduplicated on :func:`_dedup_key`, first occurrence winning, so
``limit=N`` yields N *distinct* sources rather than N rows. One row
per source is not something the caller can assume: a search strategy
stores one ``research_resources`` row per piece of evidence, so the
same URL legitimately appears several times with different snippets
(see #5894), and without this a "top 3 sources" card could render one
URL three times. Because dedup happens in Python the row cap cannot
be pushed into SQL: the query fetches every matching row, but
formatting stops as soon as ``limit`` distinct sources are in hand.
Args:
research_id: The ResearchHistory id.
db_session: Active SQLAlchemy session bound to the user DB.
limit: Maximum number of DISTINCT links to return.
"""
rows = (
db_session.query(ResearchResource)
.filter_by(research_id=research_id)
.filter(ResearchResource.url.isnot(None))
.order_by(ResearchResource.id.asc())
)
out: List[Dict[str, str]] = []
seen: set[str] = set()
for r in rows:
if len(out) >= limit:
break
link = _format_source_link(r)
if link is None:
continue
key = _dedup_key(link["url"])
if key in seen:
continue
seen.add(key)
out.append(link)
return out
def get_research_source_links_batch(
research_ids: List[str], db_session: Session, limit: Optional[int] = 3
) -> Dict[str, List[Dict[str, str]]]:
"""Batched variant of :func:`get_research_source_links`.
For news-feed list views that would otherwise fire one query per
research item (N+1). One ``WHERE research_id IN (...)`` query plus
Python-side grouping. Returned dict maps each research_id to its
top-N links (same shape as :func:`get_research_source_links`, and
deduplicated the same way — ``limit`` counts DISTINCT sources, not
rows). Research ids with zero rows map to ``[]``.
``limit=None`` returns every link for each research (no cap) — used by
the report API, which exposes the full source list rather than a top-N.
"""
result: Dict[str, List[Dict[str, str]]] = {rid: [] for rid in research_ids}
if not research_ids:
return result
rows = (
db_session.query(ResearchResource)
.filter(ResearchResource.research_id.in_(research_ids))
.filter(ResearchResource.url.isnot(None))
.order_by(ResearchResource.research_id, ResearchResource.id.asc())
.all()
)
seen_by_research: Dict[str, set[str]] = {}
for r in rows:
bucket = result.setdefault(r.research_id, [])
if limit is not None and len(bucket) >= limit:
continue
link = _format_source_link(r)
if link is None:
continue
seen = seen_by_research.setdefault(r.research_id, set())
key = _dedup_key(link["url"])
if key in seen:
continue
seen.add(key)
bucket.append(link)
return result