~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
"""
Routes for Research Library and Download Manager
Provides web endpoints for:
- Library browsing and management
- Download manager interface
- API endpoints for downloads and queries
"""
from fastapi import APIRouter, Depends, Request
from fastapi.responses import (
HTMLResponse,
JSONResponse,
Response,
)
from ..dependencies.auth import require_auth
from ..dependencies.threadpool import (
WorkerCleanupStreamingResponse,
run_db_sync,
)
from ..utils.range_response import in_memory_range_response
from ..template_config import templates
from ..utils.download_headers import build_content_disposition
from ..utils.pagination import OFFSET_LIMIT_ERROR, parse_bounded_offset
import os
import json
from datetime import UTC, datetime
from pathlib import Path
from loguru import logger
from sqlalchemy import or_
from ...database.session_context import get_user_db_session
from ...database.models.research import ResearchResource
from ...database.models.library import (
Document as Document,
DocumentStatus,
DownloadQueue as LibraryDownloadQueue,
Collection,
)
from ...library.download_management import ResourceFilter
from ...security.url_validator import URLValidator
from ...research_library.services.download_service import DownloadService
from ...research_library.services.library_service import LibraryService
from ...research_library.services.pdf_storage_manager import (
PDFStorageManager,
resolve_pdf_storage_mode,
)
from ...security import failure_reason_for_log, redact_url_for_log
from ...security.client_safe_errors import (
CLIENT_SAFE_DOWNLOAD_USER_MESSAGES,
download_reason_for_user,
)
from ...research_library.utils import (
apply_user_subdir,
document_awaits_pdf_clause,
document_counts_as_downloaded,
download_claim_is_live,
get_document_for_resource,
resource_document_clause,
handle_api_error,
is_downloadable_domain,
is_downloadable_url,
)
from ...utilities.db_utils import get_settings_manager
from ...config.paths import get_library_directory
from ...security.log_sanitizer import redact_and_bound_for_log
from ...settings.exceptions import SettingsValueError
from ...web.exceptions import AuthenticationRequiredError
from ..dependencies.json_body import read_json_dict
from .notes import _log_value_preview
from typing import Annotated
# Create the router
router = APIRouter(prefix="/library", tags=["library"])
#: Upper bound for user-supplied id/url lists on the manual-selection
#: routes (check-downloads, mark-redownload). Far above any real bulk
#: selection and a safe margin under SQLite's 250,000 bind-parameter
#: ceiling, so an oversized list can never reach the .in_() filters.
_MAX_STRING_LIST_ITEMS = 1000
#: Higher bound for download-bulk only: the locked download-all
#: contract (test_library_api_response_shapes) requires lists above
#: one thousand to stream, so the functional floor sits above the
#: manual cap. download_bulk never binds these ids into a SQL query —
#: it loops per id, opening a session and queueing downloads for each
#: — so the real cost axis is per-item work, not a bind-parameter
#: ceiling. 100,000 bounds that per-item work to a size the "queue
#: everything undownloaded" flow (queue-all-undownloaded's
#: research_ids) can legitimately reach.
_MAX_BULK_LIST_ITEMS = 100_000
#: Upper bound per item; 2048 characters covers any URL or id the
#: UI ever sends while bounding per-request memory.
_MAX_STRING_LIST_ITEM_LENGTH = 2048
def _string_list_error(
value, field_name: str, max_items: int = _MAX_STRING_LIST_ITEMS
) -> JSONResponse | None:
"""Return a 400 response unless *value* is a bounded non-empty-string list.
Caps both the item count and per-item length. Only
``check-downloads`` feeds the list into a SQLAlchemy ``.in_()``
filter, whose bind-parameter ceiling this helper's default
``max_items`` stays a safe margin under; ``download-bulk`` and
``mark-redownload`` loop over the list per item instead, so their
exposure is unbounded per-item work rather than a bind-parameter
crash. Routes that must preserve larger lists (download-all) pass
a higher ``max_items`` sized to that per-item cost instead of the
bind ceiling.
The count check runs before the per-item type/length sweeps so an
oversized list 400s in O(1) instead of paying an O(n) scan first.
"""
if not isinstance(value, list):
return JSONResponse(
{"error": f"{field_name} must be a list of non-empty strings"},
status_code=400,
)
if len(value) > max_items:
return JSONResponse(
{"error": (f"{field_name} must contain at most {max_items} items")},
status_code=400,
)
if any(not isinstance(item, str) or not item.strip() for item in value):
return JSONResponse(
{"error": f"{field_name} must be a list of non-empty strings"},
status_code=400,
)
if any(len(item) > _MAX_STRING_LIST_ITEM_LENGTH for item in value):
return JSONResponse(
{
"error": (
f"{field_name} items must be at most"
f" {_MAX_STRING_LIST_ITEM_LENGTH} characters"
)
},
status_code=400,
)
return None
# NOTE: Routes use username (not .get()) intentionally.
# Depends(require_auth) guarantees the key exists; direct access fails
# fast if the dependency is ever removed.
# Error handler for authentication errors
def handle_web_api_exception(error):
"""Handle WebAPIException and its subclasses."""
from ...web.exceptions import WebAPIException
if isinstance(error, WebAPIException):
return error.to_dict(), error.status_code
# Re-raise other exceptions
raise error
def get_authenticated_user_password(
username: str, session_id: str | None = None
) -> str:
"""
Get authenticated user password from session store.
Args:
username: The username to get password for
session_id: Optional session ID for direct lookup.
Returns:
str: The user's password
Raises:
AuthenticationRequiredError: If no password is available for the user
"""
from ...database.session_passwords import session_password_store
# Try specific session first
if session_id:
try:
user_password = session_password_store.get_session_password(
username, session_id
)
if user_password:
return user_password
except Exception:
logger.exception("Failed to get user password from session store")
# Try any session for this user (works without Flask)
user_password = session_password_store.get_any_session_password(username)
if user_password:
return user_password
# No password available
logger.error(f"No user password available for user {username}")
raise AuthenticationRequiredError(
message="Authentication required: Please refresh the page and log in again to access encrypted database features.",
)
# ============= Page Routes =============
@router.get("/")
def library_page(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
"""Main library page showing downloaded documents."""
import math
try:
with get_user_db_session(username) as db_session:
settings = get_settings_manager(db_session, username)
pdf_storage_mode = resolve_pdf_storage_mode(
settings.get_setting(
"research_library.pdf_storage_mode", "database"
)
)
shared_library = settings.get_setting(
"research_library.shared_library", False
)
except SettingsValueError:
# An invalid configured value must not render the page as if the
# defaults were configured. The app's handler shows the diagnostic.
raise
except Exception:
pdf_storage_mode = "database"
shared_library = False
enable_pdf_storage = pdf_storage_mode != "none"
# Filters
domain_filter = request.query_params.get("domain")
research_filter = request.query_params.get("research")
collection_filter = request.query_params.get("collection")
date_filter = request.query_params.get("date")
# Build context with graceful degradation
stats = {}
documents = []
unique_domains = []
research_list = []
collections = []
page = 1
total_pages = 1
# Degrading gracefully is deliberate here (main let the exception
# reach Flask's 500 handler), but an empty `documents` list is
# ambiguous: the template's empty state would tell a user whose
# library failed to load that they have no documents yet, and invite
# them to go download some. Track *why* the list is empty so the page
# can say "we could not load this" instead of asserting something
# false about their data.
load_error = False
try:
service = LibraryService(username)
stats = service.get_library_stats()
from ...database.library_init import get_default_library_id
resolved_collection = collection_filter or get_default_library_id(
username
)
# Pagination
per_page = 100
total_docs = service.count_documents(
research_id=research_filter,
domain=domain_filter,
collection_id=resolved_collection,
date_filter=date_filter,
)
total_pages = max(1, math.ceil(total_docs / per_page))
try:
page = int(request.query_params.get("page", "1"))
except ValueError:
page = 1
page = max(1, min(page, total_pages))
offset = (page - 1) * per_page
documents = service.get_documents(
research_id=research_filter,
domain=domain_filter,
collection_id=resolved_collection,
date_filter=date_filter,
limit=per_page,
offset=offset,
)
unique_domains = service.get_unique_domains()
research_list = service.get_research_list_for_dropdown()
collections = service.get_all_collections()
except Exception:
logger.exception("Error loading library data")
load_error = True
default_collection_id = next(
(c["id"] for c in collections if c.get("is_default")), None
)
return templates.TemplateResponse(
request=request,
name="pages/library.html",
context={
"stats": stats,
"documents": documents,
"load_error": load_error,
"unique_domains": unique_domains,
"research_list": research_list,
"collections": collections,
"selected_collection": collection_filter,
"default_collection_id": default_collection_id,
"storage_path": stats.get("storage_path", ""),
"enable_pdf_storage": enable_pdf_storage,
"pdf_storage_mode": pdf_storage_mode,
"shared_library": shared_library,
"page": page,
"total_pages": total_pages,
"selected_date": date_filter,
"selected_research": research_filter,
"selected_domain": domain_filter,
},
)
@router.get("/document/{document_id}")
def document_details_page(
request: Request,
document_id,
username: Annotated[str, Depends(require_auth)],
):
"""Document details page showing all metadata and links."""
service = LibraryService(username)
# Get document details
document = service.get_document_by_id(document_id)
if not document:
# Browser navigation: return text/html, not JSON. These four page
# routes are reached from library.html as ordinary <a href> links, so a
# stale link showed the user a raw {"error": ...} body in the browser's
# JSON viewer. main returned `"Document not found", 404` (text/html)
# here; the sibling /api/ routes keep JSON.
return HTMLResponse("Document not found", status_code=404)
# HTML escaping does not make a stored javascript:/data: URL safe to
# navigate. Keep rejected values visible as text, but never as links.
original_url = document.get("original_url")
original_source_url = (
original_url if URLValidator.is_safe_http_link(original_url) else None
)
return templates.TemplateResponse(
request=request,
name="pages/document_details.html",
context={
"request": request,
"document": document,
"original_source_url": original_source_url,
},
)
@router.get("/download-manager")
def download_manager_page(
request: Request,
username: Annotated[str, Depends(require_auth)],
):
"""Download manager page for selecting and downloading research PDFs."""
import math
service = LibraryService(username)
with get_user_db_session(username) as db_session:
settings = get_settings_manager(db_session, username)
pdf_storage_mode = resolve_pdf_storage_mode(
settings.get_setting(
"research_library.pdf_storage_mode", "database"
)
)
shared_library = settings.get_setting(
"research_library.shared_library", False
)
enable_pdf_storage = pdf_storage_mode != "none"
# Summary stats over ALL sessions (also used for page count)
per_page = 50
summary = service.get_download_manager_summary_stats()
total_pages = max(1, math.ceil(summary["total_researches"] / per_page))
# Pagination with upper-bound clamp
try:
page = int(request.query_params.get("page", "1"))
except ValueError:
page = 1
page = max(1, min(page, total_pages))
offset = (page - 1) * per_page
# Get paginated research sessions
research_list = service.get_research_list_with_stats(
limit=per_page, offset=offset
)
# Batch-fetch PDF previews and domain breakdowns (single query)
research_ids = [r["id"] for r in research_list]
previews = service.get_pdf_previews_batch(research_ids)
for research in research_list:
rid = research["id"]
data = previews.get(rid, {"pdf_sources": [], "domains": {}})
research["pdf_sources"] = data["pdf_sources"]
research["domains"] = data["domains"]
return templates.TemplateResponse(
request=request,
name="pages/download_manager.html",
context={
"request": request,
"research_list": research_list,
"total_researches": summary["total_researches"],
"total_resources": summary["total_resources"],
"already_downloaded": summary["already_downloaded"],
"available_to_download": summary["available_to_download"],
"enable_pdf_storage": enable_pdf_storage,
"pdf_storage_mode": pdf_storage_mode,
"shared_library": shared_library,
"page": page,
"total_pages": total_pages,
},
)
# ============= API Routes =============
@router.get("/api/stats")
def get_library_stats(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get library statistics."""
service = LibraryService(username)
return service.get_library_stats()
@router.get("/api/collections/list")
def get_collections_list(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get list of all collections for dropdown selection."""
with get_user_db_session(username) as db_session:
collections = (
db_session.query(Collection).order_by(Collection.name).all()
)
return {
"success": True,
"collections": [
{
"id": col.id,
"name": col.name,
"description": col.description,
}
for col in collections
],
}
@router.get("/api/documents")
def get_documents(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get documents with filtering."""
service = LibraryService(username)
# Get filter parameters
research_id = request.query_params.get("research_id")
domain = request.query_params.get("domain")
file_type = request.query_params.get("file_type")
favorites_only = request.query_params.get("favorites") == "true"
search_query = request.query_params.get("search")
# Clamp pagination. SQLite treats LIMIT -1 as "no limit", so an
# unclamped negative limit (e.g. ?limit=-1) would bypass pagination and
# load the whole collection — including large Document.text_content
# bodies — into memory (#4560). Mirrors the clamp in history_routes.
try:
limit = max(1, min(int(request.query_params.get("limit", 100)), 1000))
except (TypeError, ValueError):
limit = 100
try:
offset = parse_bounded_offset(request.query_params.get("offset"))
except ValueError:
return JSONResponse({"error": OFFSET_LIMIT_ERROR}, status_code=400)
documents = service.get_documents(
research_id=research_id,
domain=domain,
file_type=file_type,
favorites_only=favorites_only,
search_query=search_query,
limit=limit,
offset=offset,
)
return {"documents": documents}
@router.post("/api/document/{document_id}/favorite")
def toggle_favorite(
request: Request,
document_id,
username: Annotated[str, Depends(require_auth)],
):
"""Toggle favorite status of a document."""
service = LibraryService(username)
is_favorite = service.toggle_favorite(document_id)
return {"favorite": is_favorite}
@router.get("/api/document/{document_id}/pdf-url")
def get_pdf_url(
request: Request,
document_id,
username: Annotated[str, Depends(require_auth)],
):
"""Get URL for viewing PDF."""
# Return URL that will serve the PDF
return {
"url": f"/library/api/document/{document_id}/pdf",
"title": "Document", # Could fetch actual title
}
def _serve_pdf(
request: Request, document_id, username: str, *, html_errors: bool
):
"""Shared PDF-loading core for the page route and its /api/ sibling.
``html_errors`` picks the not-found/not-available error shape: the
browser-navigation page route wants text/html (a stale <a href> link
should not show a raw JSON body), while the /api/ sibling keeps the
JSON contract every other /api/ route has -- same rule its /text
sibling (serve_text_api) already follows.
"""
def _error(message: str) -> Response:
if html_errors:
return HTMLResponse(message, status_code=404)
return JSONResponse({"error": message}, status_code=404)
with get_user_db_session(username) as db_session:
# Get document from database
document = db_session.query(Document).filter_by(id=document_id).first()
if not document:
logger.warning(
f"Document ID {_log_value_preview(document_id)} not found in database for user {username}"
)
# Browser navigation: return text/html, not JSON. These four page
# routes are reached from library.html as ordinary <a href> links, so a
# stale link showed the user a raw {"error": ...} body in the browser's
# JSON viewer. main returned `"Document not found", 404` (text/html)
# here; the sibling /api/ routes keep JSON.
return _error("Document not found")
logger.info(
f"Document {document_id}: title='{document.title}', "
f"file_path={document.file_path}"
)
# Get settings for PDF storage manager
settings = get_settings_manager(db_session)
storage_mode = settings.get_setting(
"research_library.pdf_storage_mode", "none"
)
# Expand configured environment variables before choosing the user's
# library directory, matching the download/storage path resolution.
base_root = (
Path(
os.path.expandvars(
settings.get_setting(
"research_library.storage_path",
str(get_library_directory()),
)
)
)
.expanduser()
.resolve()
)
shared_library = settings.get_setting(
"research_library.shared_library", False
)
# Serve only from the requesting user's root. A matching relative
# filename in the shared legacy directory does not prove ownership.
library_root = apply_user_subdir(base_root, username, shared_library)
# Use PDFStorageManager to load PDF (handles database and filesystem)
pdf_manager = PDFStorageManager(library_root, storage_mode)
pdf_bytes = pdf_manager.load_pdf(document, db_session)
if pdf_bytes:
logger.info(
f"Serving PDF for document {document_id} ({len(pdf_bytes)} bytes)"
)
filename = document.filename or "document.pdf"
# Plain Response, not StreamingResponse: the bytes are already
# fully in memory, and iterating a BytesIO yields *lines* — it
# splits on every 0x0A, which in binary PDF data occurs roughly
# every 256 bytes, so a single view became tens of thousands of
# threadpool dispatches and sent no Content-Length.
return in_memory_range_response(
content=pdf_bytes,
request=request,
media_type="application/pdf",
headers={
"Content-Disposition": build_content_disposition(
filename, inline=True
)
},
)
# No PDF found anywhere
logger.warning(f"No PDF available for document {document_id}")
# Browser navigation, same rule as the not-found branch above: main
# returned `"PDF not available", 404` (text/html) here. Reached
# routinely, not just via stale links -- "Remove the PDF file to save
# space" deletes the blob while leaving the row, so an open tab or a
# bookmark lands here. The /api/ sibling keeps JSON.
return _error("PDF not available")
@router.get("/document/{document_id}/pdf")
def view_pdf_page(
request: Request,
document_id,
username: Annotated[str, Depends(require_auth)],
):
"""Page for viewing PDF file - uses PDFStorageManager for retrieval."""
return _serve_pdf(request, document_id, username, html_errors=True)
@router.get("/api/document/{document_id}/pdf")
def serve_pdf_api(
request: Request,
document_id,
username: Annotated[str, Depends(require_auth)],
):
"""API endpoint for serving PDF file (kept for backward compatibility).
Unlike the page route above, a missing document or missing PDF blob
here answers JSON, not text/html -- this is an /api/ route, and its
/api/document/{id}/text sibling (serve_text_api) already keeps that
contract on the same two error branches.
"""
return _serve_pdf(request, document_id, username, html_errors=False)
@router.get("/document/{document_id}/txt")
def view_text_page(
request: Request,
document_id,
username: Annotated[str, Depends(require_auth)],
):
"""Page for viewing text content."""
with get_user_db_session(username) as db_session:
# Get document by ID (text now stored in Document.text_content)
document = db_session.query(Document).filter_by(id=document_id).first()
if not document:
logger.warning(
f"Document not found for document ID {_log_value_preview(document_id)}"
)
# Browser navigation: return text/html, not JSON. These four page
# routes are reached from library.html as ordinary <a href> links, so a
# stale link showed the user a raw {"error": ...} body in the browser's
# JSON viewer. main returned `"Document not found", 404` (text/html)
# here; the sibling /api/ routes keep JSON.
return HTMLResponse("Document not found", status_code=404)
if not document.text_content:
logger.warning(f"Document {document_id} has no text content")
# Browser navigation, same rule as the not-found branch above:
# main returned `"Text content not available", 404` (text/html)
# here. serve_text_api below keeps main's jsonify() shape.
return HTMLResponse("Text content not available", status_code=404)
logger.info(
f"Serving text content for document {document_id}: {len(document.text_content)} characters"
)
# Render as HTML page
return templates.TemplateResponse(
request=request,
name="pages/document_text.html",
context={
"document_id": document_id,
"title": document.title or "Document Text",
"text_content": document.text_content,
"extraction_method": document.extraction_method,
"word_count": document.word_count,
},
)
@router.get("/api/document/{document_id}/text")
def serve_text_api(
request: Request,
document_id,
username: Annotated[str, Depends(require_auth)],
):
"""API endpoint for serving text content (kept for backward compatibility)."""
with get_user_db_session(username) as db_session:
# Get document by ID (text now stored in Document.text_content)
document = db_session.query(Document).filter_by(id=document_id).first()
if not document:
logger.warning(
f"Document not found for document ID {_log_value_preview(document_id)}"
)
return JSONResponse(
{"error": "Document not found"}, status_code=404
)
if not document.text_content:
logger.warning(f"Document {document_id} has no text content")
return JSONResponse(
{"error": "Text content not available"}, status_code=404
)
logger.info(
f"Serving text content for document {document_id}: {len(document.text_content)} characters"
)
return {
"text_content": document.text_content,
"title": document.title or "Document",
"extraction_method": document.extraction_method,
"word_count": document.word_count,
}
@router.post("/api/open-folder")
def open_folder(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Open folder containing a document.
Security: This endpoint is disabled for server deployments.
It only makes sense for desktop usage where the server and client are on the same machine.
"""
return JSONResponse(
{
"status": "error",
"message": "This feature is disabled. It is only available in desktop mode.",
},
status_code=403,
)
@router.post("/api/download/{resource_id}")
def download_single_resource(
request: Request,
# Typed int, matching Flask's <int:resource_id> converter: without it a
# non-numeric segment is passed straight through to the service layer
# instead of being rejected as a 422 by the router.
resource_id: int,
username: Annotated[str, Depends(require_auth)],
):
"""Download a single resource."""
user_password = get_authenticated_user_password(username)
with DownloadService(username, user_password) as service:
success, error = service.download_resource(resource_id)
if success:
return {"success": True}
if error == "Resource not found":
# download_resource() returns this exact string (never raises)
# when resource_id doesn't exist — that's a 404, not a generic
# download failure. Without this branch every nonexistent
# resource_id collapsed to the 500 below.
return JSONResponse(
{"success": False, "error": "Resource not found"},
status_code=404,
)
if error in CLIENT_SAFE_DOWNLOAD_USER_MESSAGES:
# A refusal the operator can lift (the PDF storage size limit):
# say how, rather than suggest trying again.
return JSONResponse(
{"success": False, "error": download_reason_for_user(error)},
status_code=409,
)
# The reason may be exception text that keeps the URL's path and
# query; download_service logs the cause itself where it is caught.
logger.warning(
f"Download failed for resource {resource_id}: "
f"{failure_reason_for_log(error)}"
)
return JSONResponse(
{
"success": False,
"error": "Download failed. Please try again or contact support.",
},
status_code=500,
)
@router.post("/api/download-text/{resource_id}")
def download_text_single(
request: Request,
# Typed int, matching Flask's <int:resource_id> converter: without it a
# non-numeric segment is passed straight through to the service layer
# instead of being rejected as a 422 by the router.
resource_id: int,
username: Annotated[str, Depends(require_auth)],
):
"""Download a single resource as text file."""
try:
user_password = get_authenticated_user_password(username)
with DownloadService(username, user_password) as service:
success, error = service.download_as_text(resource_id)
# Sanitize error message - don't expose internal details
if not success:
if error:
logger.warning(
f"Download as text failed for resource {resource_id}: "
f"{failure_reason_for_log(error)}"
)
return {
"success": False,
"error": "Failed to download resource",
}
return {"success": True, "error": None}
except AuthenticationRequiredError:
raise # Let the global WebAPIException handler return 401
except Exception as e:
return handle_api_error(
f"downloading resource {resource_id} as text", e
)
@router.post("/api/download-all-text")
def download_all_text(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Download all undownloaded resources as text files."""
# Capture Flask session ID to avoid scoping issues in nested function
session_id = request.session.get("session_id")
def generate():
# Get user password for database operations
try:
user_password = get_authenticated_user_password(
username, session_id
)
except AuthenticationRequiredError:
logger.warning(
f"Authentication unavailable for user {username} - password not in session store"
)
yield f"data: {json.dumps({'progress': 0, 'current': 0, 'total': 0, 'error': 'Authentication required', 'complete': True})}\n\n"
return
# This DownloadService (and the SettingsManager session inside
# download_service.settings) is built ONCE, before the loop, and
# lives across every ``yield`` below. That crosses a cleanup
# boundary the wrapper's per-chunk cleanup does NOT know about:
# ``WorkerCleanupStreamingResponse`` wraps this generator in
# ``iterate_sync_with_cleanup``, whose ``thread_cleanup()`` runs
# after EVERY ``next()`` (i.e. after every chunk, not just at the
# end) and closes every session cached or tracked on this thread
# (``utilities/db_utils.py``). The first chunk that touches
# ``download_service.settings`` therefore gets its underlying
# SQLAlchemy session closed by that per-chunk cleanup the moment the
# chunk's ``yield`` returns -- but the ``SettingsManager``/``Session``
# OBJECTS themselves are untouched, only their pooled connection is
# released, so the next chunk's use of ``download_service.settings``
# transparently reopens a fresh connection (ordinary SQLAlchemy
# session behavior after ``close()``). That connection then sits in
# neither the LRU cache nor the owner-thread registry until stream
# end, when ``safe_close(download_service, ...)`` below closes it
# via ``SettingsManager.close()`` -- exactly where it was released
# pre-#6095, so this is NOT a leak, just a "cleanup at every
# boundary" invariant violated for the longest-lived object in this
# stream. Documented rather than restructured: giving this loop its
# own re-created-per-chunk settings manager would fix the invariant
# but changes this route's session lifetime shape for no behavioral
# gain, and isn't warranted without a demonstrated leak.
download_service = DownloadService(username, user_password)
try:
# Fetch the resource rows in a SHORT-LIVED session, snapshotting
# only the columns the loop uses into plain tuples. The download
# loop below holds NO session while it yields — the held session is
# only needed for this query, and keeping a get_user_db_session
# scope open across a yield risks the Starlette/anyio thread-
# affinity corruption fixed in download_bulk (its __enter__ and
# __exit__ can land on different pooled threads). Project only
# id/url/title so the content_preview Text column doesn't
# materialize on this whole-table scan (#4560).
with get_user_db_session(username) as session:
all_resources = [
(r.id, r.url, r.title)
for r in session.query(
ResearchResource.id,
ResearchResource.url,
ResearchResource.title,
).all()
]
# Filter to only downloadable resources (academic/PDF)
resources = [
(rid, url, title)
for (rid, url, title) in all_resources
if is_downloadable_url(url)
]
# Pre-scan directory once to get all existing resource IDs
txt_path = Path(download_service.library_root) / "txt"
existing_resource_ids = set()
if txt_path.exists():
# nosemgrep: semgrep.rules.path-traversal-risk, reason: Only enumerate fixed txt names under this authenticated user's resolved library directory
for txt_file in txt_path.glob("*.txt"):
# Extract resource ID from filename pattern *_{id}.txt
parts = txt_file.stem.rsplit("_", 1)
if len(parts) == 2:
try:
existing_resource_ids.add(int(parts[1]))
except ValueError:
pass
# Filter resources that need text extraction
resources_to_process = [
(rid, url, title)
for (rid, url, title) in resources
if rid not in existing_resource_ids
]
total = len(resources_to_process)
current = 0
logger.info(f"Found {total} resources needing text extraction")
for rid, url, title in resources_to_process:
current += 1
progress = int((current / total) * 100) if total > 0 else 100
file_name = title[:50] if title else f"document_{current}.txt"
try:
# download_as_text opens its own session internally.
# Its every error-return path (see download_service.py
# download_as_text/_try_api_text_extraction/
# _fallback_pdf_extraction) is either a static string or
# a fixed token from _client_safe_download_message()
# (never str(e) — sanitize_error_for_client() scrubs
# credentials only and leaves SQL text intact) — no raw
# exception text reaches `error` here.
success, error = download_service.download_as_text(rid)
if success:
status = "success"
error_msg = None
else:
status = "failed"
error_msg = error or "Text extraction failed"
except Exception as e:
# Type name only, no traceback: an exception escaping
# the fetch can embed the raw resource URL in its text.
logger.warning(
f"Error extracting text for resource {rid} "
f"({type(e).__name__})"
)
status = "failed"
# CWE-209: only the exception CLASS NAME is surfaced,
# never str(e) — same "class name only" mitigation as
# journal_quality/downloader.py (CodeQL alerts 7650/7684).
error_msg = f"Text extraction failed - {type(e).__name__}"
# Send update
update = {
"progress": progress,
"current": current,
"total": total,
"file": file_name,
"url": url, # Add the URL for UI display
"status": status,
"error": error_msg,
}
yield f"data: {json.dumps(update)}\n\n"
# Send completion
yield f"data: {json.dumps({'complete': True, 'total': total})}\n\n"
finally:
from ...utilities.resource_utils import safe_close
safe_close(download_service, "download service")
# CWE-209 (CodeQL "Information exposure through an exception"): the SSE
# body streamed here never carries a raw exception message — see the
# `except Exception as e:` block in generate() above, which only ever
# surfaces `type(e).__name__` or a fixed token from
# download_service._client_safe_download_message (sanitize_error_for_client
# alone would not suffice — it scrubs credentials only, not SQL/paths).
return WorkerCleanupStreamingResponse(
generate(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
},
)
@router.post("/api/download-research/{research_id}")
async def download_research_pdfs(
request: Request,
research_id,
username: Annotated[str, Depends(require_auth)],
):
"""Queue all PDFs from a research session for download."""
user_password = get_authenticated_user_password(username)
data, body_error = await read_json_dict(
request, "simple", "Request body must be valid JSON"
)
if body_error is not None:
return body_error
collection_id = data.get("collection_id")
# `queue_research_downloads` does sync SQLAlchemy work. Keep it off
# the uvicorn event loop.
def _queue_sync():
with DownloadService(username, user_password) as service:
return service.queue_research_downloads(research_id, collection_id)
queued = await run_db_sync(_queue_sync)
return {"success": True, "queued": queued}
def _claim_download_queue_item(db_session, queue_item_id):
"""Atomically claim a PENDING download-queue row before processing it.
Flip the row from PENDING to PROCESSING in a single conditional UPDATE and
return True only when this caller won the claim. Two concurrent
``download_bulk`` streams for the same user (the user clicks Download
twice, or a second bulk run starts before the first finishes) both read
the same PENDING rows and, with no claim, both call ``download_resource``
for every row (issue #4691). The row-count guard makes the
PENDING -> PROCESSING transition the single point where exactly one stream
wins each row; the loser sees 0 updated rows and skips it.
The claim also records its time in ``last_attempt_at``. Nothing reclaims
a row left PROCESSING, e.g. by a restart during the download, and the
queueing of a document that awaits its PDF (see ``document_awaits_pdf``)
lets another resource refill it only while no download holds one of its
resources. ``download_claim_is_live`` tells a held row from one a restart
left behind by this time.
"""
claimed = (
db_session.query(LibraryDownloadQueue)
.filter_by(id=queue_item_id, status=DocumentStatus.PENDING)
.update(
{
LibraryDownloadQueue.status: DocumentStatus.PROCESSING,
LibraryDownloadQueue.last_attempt_at: datetime.now(UTC),
},
synchronize_session=False,
)
)
db_session.commit()
return claimed == 1
def _release_download_queue_item(db_session, queue_item_id):
"""Return a claimed row from PROCESSING back to PENDING so it stays
retryable when the download raised before a terminal COMPLETED/FAILED
status was recorded (issue #4691), matching the pre-fix behaviour where an
errored row was left PENDING. Scoped to PROCESSING so it only ever undoes
this stream's own claim.
"""
db_session.query(LibraryDownloadQueue).filter_by(
id=queue_item_id, status=DocumentStatus.PROCESSING
).update(
{LibraryDownloadQueue.status: DocumentStatus.PENDING},
synchronize_session=False,
)
db_session.commit()
def _finalize_download_queue_item(db_session, queue_item_id, success):
"""Record the outcome of a claimed row that returned without raising.
``download_resource`` writes a terminal COMPLETED/FAILED status itself for
the rows it actually downloads, and this is a no-op for those: the row is
no longer PROCESSING, so the guard matches nothing and pdf-mode behaviour
is unchanged. It fires only on the paths that otherwise strand a claim
(issue #4691):
- ``mode="text_only"``: ``download_as_text`` and its call tree never touch
``LibraryDownloadQueue``, so a successful extraction would leave the row
PROCESSING forever. Nothing in ``src/`` reaps PROCESSING rows, and a
successful extraction also writes a COMPLETED Document, which blocks both
the pre-pass reset and ``queue_all_undownloaded``'s outer-join filter.
- ``download_resource``'s already-downloaded early return, which reports
success before reaching its own queue update.
Pre-fix, both paths left the row PENDING and merely re-scanned it, so
failure returns to PENDING rather than FAILED to keep that retryability.
"""
db_session.query(LibraryDownloadQueue).filter_by(
id=queue_item_id, status=DocumentStatus.PROCESSING
).update(
{
LibraryDownloadQueue.status: (
DocumentStatus.COMPLETED if success else DocumentStatus.PENDING
),
LibraryDownloadQueue.completed_at: (
datetime.now(UTC) if success else None
),
},
synchronize_session=False,
)
db_session.commit()
@router.post("/api/download-bulk")
async def download_bulk(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Download PDFs or extract text from multiple research sessions."""
data, body_error = await read_json_dict(
request, "simple", "Request body must be valid JSON"
)
if body_error is not None:
return body_error
research_ids = data.get("research_ids", [])
mode = data.get("mode", "pdf") # pdf or text_only
collection_id = data.get(
"collection_id"
) # Optional: target collection for downloads
if not research_ids:
return JSONResponse(
{"error": "No research IDs provided"}, status_code=400
)
# Download-all selections legitimately exceed the manual-selection
# cap (locked contract: lists above one thousand must stream), so
# this route uses the higher bulk ceiling — bounded to a size the
# "queue everything undownloaded" flow can legitimately reach, not
# to a SQL bind-parameter limit (this route loops per id rather
# than binding the list into a query).
if error := _string_list_error(
research_ids, "research_ids", max_items=_MAX_BULK_LIST_ITEMS
):
return error
if not isinstance(mode, str) or mode not in {"pdf", "text_only"}:
return JSONResponse(
{"error": "mode must be either 'pdf' or 'text_only'"},
status_code=400,
)
# Capture Flask session ID to avoid scoping issues in nested function
session_id = request.session.get("session_id")
def generate():
"""Generate progress updates as Server-Sent Events."""
# Get user password for database operations
try:
user_password = get_authenticated_user_password(
username, session_id
)
except AuthenticationRequiredError:
logger.warning(
f"Authentication unavailable for user {username} - password not in session store"
)
yield f"data: {json.dumps({'progress': 0, 'current': 0, 'total': 0, 'error': 'Authentication required', 'complete': True})}\n\n"
return
# Same per-chunk-cleanup caveat as download_all_text() above:
# download_service.settings' session gets closed (connection
# released, object untouched) by iterate_sync_with_cleanup's
# per-chunk thread_cleanup() after the first chunk that uses it, and
# transparently reopens a fresh connection on later chunks. Not a
# leak -- safe_close(download_service, ...) below releases it at
# stream end exactly as pre-#6095 -- just documented here rather
# than restructured; see the fuller note there.
download_service = DownloadService(username, user_password)
try:
total = 0
current = 0
queue_failures = 0
# Pre-queue and count in one merged loop. queue_research_downloads
# opens its own session, commits, and handles dedup internally:
# it skips resources that are already PENDING or already backed by
# a COMPLETED Document, and re-queues any remaining row (e.g. a
# prior FAILED attempt) back to PENDING. Calling it BEFORE counting
# ensures the total reflects what will actually be processed
# (issue #4660). In PDF mode it also queues a COMPLETED Document
# that still needs its PDF (see document_awaits_pdf), through
# one resource per such document across all the research
# sessions of this run (run_research_ids); a text extraction
# already has that document's text, so text_only mode skips it.
# The set is built once for the run: each call only looks it up.
run_research_ids = frozenset(research_ids)
for research_id in research_ids:
try:
download_service.queue_research_downloads(
research_id,
collection_id,
text_only=mode == "text_only",
run_research_ids=run_research_ids,
)
except Exception:
queue_failures += 1
logger.exception(
"Error queueing downloads for "
"user={} research={} collection={}",
username,
research_id,
_log_value_preview(collection_id),
)
with get_user_db_session(username) as session:
count = (
session.query(LibraryDownloadQueue)
.filter_by(
research_id=research_id,
status=DocumentStatus.PENDING,
)
.count()
)
total += count
logger.debug(
f"Research {research_id}: {count} pending items in queue"
)
logger.info(f"Total pending downloads across all research: {total}")
yield f"data: {json.dumps({'progress': 0, 'current': 0, 'total': total})}\n\n"
# If the pre-pass yielded nothing to process, surface it as an
# error so the UI alerts instead of silently completing with
# "0 / 0 files" success. Distinguish queue failure from a
# legitimate "nothing left to download" state.
if total == 0:
if queue_failures > 0:
error_msg = (
f"Download failed to start: queueing failed for "
f"{queue_failures} of {len(research_ids)} "
f"research session(s). Check server logs."
)
else:
error_msg = (
"No new papers to download for the selected "
"research session(s)."
)
yield f"data: {json.dumps({'progress': 100, 'current': 0, 'total': 0, 'complete': True, 'error': error_msg})}\n\n"
return
# Process each research
for research_id in research_ids:
# Get queued downloads for this research in a SHORT-LIVED
# session, snapshotting only the ids we need. The per-item work
# below opens its own short-lived sessions so that NO
# get_user_db_session scope is ever held across a ``yield``:
# generate() is a sync generator that Starlette drives via
# iterate_in_threadpool (one anyio dispatch per next()), so a
# session whose __enter__/__exit__ straddled a yield could run
# on two different pooled OS threads and leave the thread-local
# scope_depth counter permanently corrupted.
with get_user_db_session(username) as session:
queue_items = [
(qi.id, qi.resource_id)
for qi in (
session.query(LibraryDownloadQueue)
.filter_by(
research_id=research_id,
status=DocumentStatus.PENDING,
)
.all()
)
]
# Process each queued item
for queue_item_id, resource_id in queue_items:
# Atomically claim this row before downloading so a
# second concurrent download_bulk stream can't also
# process it (issue #4691). A row already claimed by
# another stream returns 0 updated rows; skip it.
with get_user_db_session(username) as session:
claimed = _claim_download_queue_item(
session, queue_item_id
)
if not claimed:
continue
current += 1
progress = (
int((current / total) * 100) if total > 0 else 100
)
# Attempt actual download with error handling
skip_reason = None
status = "skipped" # Default to skipped
success = False
error_msg = None
error_type = None
# Everything from the resource lookup onward runs
# inside the try below, so file_name needs a value
# even if that block raises before setting one.
file_name = f"document_{current}.pdf"
try:
# Get resource info in its own short-lived session.
# This sits INSIDE the try because the claim above is
# already committed as PROCESSING: any raise between
# the claim and this handler would leave the row that
# way forever, since nothing in src/ reaps PROCESSING
# rows and every reset path now refuses to touch them
# (issue #4691). ResearchResource.title is nullable, so
# resource.title[:50] raises TypeError on a resource
# whose title was never populated.
with get_user_db_session(username) as session:
resource = session.get(
ResearchResource, resource_id
)
if resource and resource.title:
file_name = resource.title[:50]
logger.debug(
f"Attempting {'PDF download' if mode == 'pdf' else 'text extraction'} for resource {resource_id}"
)
# Call appropriate service method based on mode.
# DownloadService opens its own session internally; no
# session is held here across the blocking download.
if mode == "pdf":
result = download_service.download_resource(
resource_id
)
else: # text_only
result = download_service.download_as_text(
resource_id
)
# Handle new tuple return format
if isinstance(result, tuple):
success, skip_reason = result
else:
success = result
skip_reason = None
# Finalize the claim for the paths that don't
# record a terminal status themselves (text_only,
# and download_resource's already-downloaded early
# return); a no-op when they already did (#4691).
with get_user_db_session(username) as session:
_finalize_download_queue_item(
session, queue_item_id, success
)
status = "success" if success else "skipped"
if skip_reason and not success:
error_msg = skip_reason
logger.info(
f"{'Download' if mode == 'pdf' else 'Text extraction'} skipped for resource {resource_id}: {failure_reason_for_log(skip_reason)}"
)
logger.debug(
f"{'Download' if mode == 'pdf' else 'Text extraction'} result: success={success}, status={status}, skip_reason={failure_reason_for_log(skip_reason)}"
)
except Exception as e:
# Release the claim so a later run can retry this row:
# the download raised before download_resource recorded
# a terminal status (issue #4691). A fresh short-lived
# session — the download's own session is unrelated and
# each op above already closed its scope, so there is no
# held session to roll back.
try:
with get_user_db_session(username) as session:
_release_download_queue_item(
session, queue_item_id
)
except Exception:
logger.exception(
"Failed to release download-queue claim"
)
# Log error but continue processing. `error_msg`
# (str(e)) is used ONLY for the keyword classification
# below (`.lower()` checks) — it is never logged
# (an exception escaping download_resource /
# download_as_text can embed the raw resource URL:
# urllib3 "with url: ...", SQLAlchemy
# "[parameters: ...]") and never written into
# `skip_reason`, which the yield below sends to the
# client. Only `error_type` (the exception CLASS NAME)
# reaches the log and skip_reason, same "class name
# only" mitigation as journal_quality/downloader.py
# (CodeQL alerts 7650/7684) — CWE-209.
error_msg = str(e)
error_type = type(e).__name__
logger.warning(
f"CAUGHT Download exception for resource {resource_id}: {error_type}"
)
# Check if this is a skip reason (not a real error)
# Use error category + categorized message for user display
if any(
phrase in error_msg.lower()
for phrase in [
"paywall",
"subscription",
"not available",
"not found",
"no free",
"embargoed",
"forbidden",
"not accessible",
]
):
status = "skipped"
skip_reason = f"Document not accessible (paywall or access restriction) - {error_type}"
elif any(
phrase in error_msg.lower()
for phrase in [
"failed to download",
"could not",
"invalid",
"server",
]
):
status = "failed"
skip_reason = f"Download failed - {error_type}"
else:
status = "failed"
skip_reason = f"Processing failed - {error_type}"
success = False
# Ensure skip_reason is set if we have an error message
if error_msg and not skip_reason:
skip_reason = f"Processing failed - {error_type}"
logger.debug(
f"Setting skip_reason from error type: {error_type}"
)
# Send progress update
update_data = {
"progress": progress,
"current": current,
"total": total,
"file": file_name,
"status": status,
}
# Add skip reason if available
if skip_reason:
# A token the operator can act on (the PDF storage
# size limit) is shown as the message that says how.
update_data["error"] = download_reason_for_user(
skip_reason
)
logger.info(
"Sending skip reason to UI: "
f"{failure_reason_for_log(skip_reason)}"
)
yield f"data: {json.dumps(update_data)}\n\n"
yield f"data: {json.dumps({'progress': 100, 'current': current, 'total': total, 'complete': True})}\n\n"
finally:
from ...utilities.resource_utils import safe_close
safe_close(download_service, "download service")
# CWE-209 (CodeQL "Information exposure through an exception"): the SSE
# body streamed here never carries a raw exception message. `skip_reason`
# either comes straight from download_service (already a static string or
# a fixed token from _client_safe_download_message() — see
# download_resource / download_as_text and their helpers in
# download_service.py; sanitize_error_for_client() alone would not
# suffice since it scrubs credentials only, not SQL/paths) or, on the
# `except Exception as e:` path above, is built from `type(e).__name__`
# only — never the raw `error_msg = str(e)`.
return WorkerCleanupStreamingResponse(
generate(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
},
)
@router.get("/api/research-list")
def get_research_list(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Get the lightweight research list used to populate a dropdown.
Deliberately NOT ``get_research_list_with_stats``: that runs a 3-table
GROUP BY aggregate plus follow-up ratings and domain-breakdown queries,
which a <select> needing only id/title/query does not use. Main replaced
this call for exactly that reason.
"""
service = LibraryService(username)
research_list = service.get_research_list_for_dropdown()
return {"research": research_list}
@router.post("/api/sync-library")
def sync_library(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Sync library database with filesystem."""
service = LibraryService(username)
return service.sync_library_with_filesystem()
@router.post("/api/mark-redownload")
async def mark_for_redownload(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Mark documents for re-download."""
data, body_error = await read_json_dict(
request, "simple", "Request body must be valid JSON"
)
if body_error is not None:
return body_error
document_ids = data.get("document_ids", [])
if not document_ids:
return JSONResponse(
{"error": "No document IDs provided"}, status_code=400
)
if error := _string_list_error(document_ids, "document_ids"):
return error
def _mark_sync():
service = LibraryService(username)
return service.mark_for_redownload(document_ids)
count = await run_db_sync(_mark_sync)
return {"success": True, "marked": count}
def _one_resource_per_awaiting_document(
db_session, resources, username, password
):
"""Keep one of the resources that would refill the same document.
A document that awaits its PDF (see ``document_awaits_pdf``) does not
count as a download, so "Download All New" finds its own resource
(``Document.resource_id``) and every resource linked to it by content
(``ResearchResource.document_id``). Each of them downloads into that
document (``get_document_for_resource``), and one download refills it.
So of the ``resources`` that would refill the same document only one is
kept, the one ``queue_research_downloads`` would leave the document to
(see ``DownloadService._refilled_by_another_resource``): one that a
download holds (a PROCESSING queue entry, see
``download_claim_is_live``), else a viable one that is already PENDING
in the download queue, else the one that ranks first in
``DownloadService.refill_rank``. So a resource that cannot succeed (its
URL cannot be queued, the retry manager holds it back, or its latest
attempt failed) is kept only when it is being downloaded or no viable
one is there. A resource whose PROCESSING entry a restart left behind
comes last during this selection; the queueing step can then reset its
stale claim. The others count as skipped. (Once the document holds its PDF
again, ``DownloadService.download_resource`` reports the document's own
resource as already downloaded, and for a linked one whose URL the
egress policy allows, ``DownloadService._download_pdf`` reuses that
stored PDF instead of fetching it.)
``resources`` have passed the route's retry-policy and downloadability
checks. The ranking also asks the egress policy and the resources'
retry records, through a ``DownloadService`` for ``username``, which is
built only when some document has more than one of them.
Returns the kept resources in their order, and how many were left out.
"""
awaiting = {
resource_id: (document_id, owner_id)
for resource_id, document_id, owner_id in (
db_session.query(
ResearchResource.id, Document.id, Document.resource_id
)
.join(
Document,
resource_document_clause(),
)
.filter(document_awaits_pdf_clause())
.all()
)
}
candidates = {}
for resource in resources:
if resource.id in awaiting:
document_id = awaiting[resource.id][0]
candidates.setdefault(document_id, []).append(resource)
shared = [rows for rows in candidates.values() if len(rows) > 1]
if not shared:
return resources, 0
entries = {
entry.resource_id: entry
for entry in db_session.query(
LibraryDownloadQueue.resource_id,
LibraryDownloadQueue.status,
LibraryDownloadQueue.last_attempt_at,
)
.filter(
LibraryDownloadQueue.resource_id.in_(
[row.id for rows in shared for row in rows]
),
LibraryDownloadQueue.status.in_(
(DocumentStatus.PENDING, DocumentStatus.PROCESSING)
),
)
.all()
}
left_out = set()
with DownloadService(username, password) as download_service:
for rows in shared:
owner_id = awaiting[rows[0].id][1]
choices = []
for row in rows:
rank = download_service.refill_rank(row.id, row.url, owner_id)
entry = entries.get(row.id)
if entry is None:
tier = 2
elif entry.status == DocumentStatus.PROCESSING:
tier = (
0
if download_claim_is_live(entry.last_attempt_at)
else 3
)
else:
tier = 1 if rank.viable else 2
choices.append(((tier, rank), row.id))
kept_id = min(choices)[1]
left_out.update(row.id for row in rows if row.id != kept_id)
for resource_id in sorted(left_out):
logger.debug(
f"Skipping resource {resource_id}: another resource of its "
"document is queued to download its PDF"
)
kept = [resource for resource in resources if resource.id not in left_out]
return kept, len(left_out)
def _resettable_download_queue_status(queue_entry):
"""Allow a stale PROCESSING row only while its observed claim is unchanged."""
resettable = LibraryDownloadQueue.status != DocumentStatus.PROCESSING
if queue_entry.status == DocumentStatus.PROCESSING and not (
download_claim_is_live(queue_entry.last_attempt_at)
):
same_claim = (
LibraryDownloadQueue.last_attempt_at.is_(None)
if queue_entry.last_attempt_at is None
else LibraryDownloadQueue.last_attempt_at
== queue_entry.last_attempt_at
)
resettable = or_(resettable, same_claim)
return resettable
@router.post("/api/queue-all-undownloaded")
def queue_all_undownloaded(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Queue all articles that haven't been downloaded yet."""
logger.info(f"queue_all_undownloaded called for user {username}")
with get_user_db_session(username) as db_session:
# Find all resources that don't have a completed download. Project only
# the columns the filter/loop use (id/url/research_id) instead of full
# ``ResearchResource`` entities so the ``content_preview`` Text column
# isn't materialized for every row on this whole-table scan (#4560).
# A completed document that still needs its PDF (the library sync
# kept its text after its PDF file went missing) is not counted as
# a download, see document_awaits_pdf. Only one of the resources
# that would refill such a document is queued, see
# _one_resource_per_awaiting_document.
undownloaded = (
db_session.query(
ResearchResource.id,
ResearchResource.url,
ResearchResource.research_id,
)
.outerjoin(
Document,
resource_document_clause()
& (Document.status == "completed")
& ~document_awaits_pdf_clause(),
)
.filter(Document.id.is_(None))
.all()
)
logger.info(f"Found {len(undownloaded)} total undownloaded resources")
# Get user password for encrypted database access
user_password = get_authenticated_user_password(username)
resource_filter = ResourceFilter(username, user_password)
filter_results = resource_filter.filter_downloadable_resources(
undownloaded
)
# Get detailed filtering summary
filter_summary = resource_filter.get_filter_summary(undownloaded)
skipped_info = resource_filter.get_skipped_resources_info(undownloaded)
logger.info(f"Filter results: {filter_summary.to_dict()}")
queued_count = 0
research_ids = set()
skipped_count = 0
# Convert filter_results to dict for O(1) lookup instead of O(n²)
filter_results_by_id = {r.resource_id: r for r in filter_results}
# The resources that pass every check below, in scan order.
eligible = []
for resource in undownloaded:
# Check if resource passed the smart filter
filter_result = filter_results_by_id.get(resource.id)
if not filter_result or not filter_result.can_retry:
skipped_count += 1
if filter_result:
# A permanently failed row's reason embeds its stored
# failure_message, which rows written before the
# domain fix may hold with URL userinfo.
logger.debug(
f"Skipping resource {resource.id} due to retry policy: "
f"{failure_reason_for_log(filter_result.reason)}"
)
else:
logger.debug(
f"Skipping resource {resource.id} - no filter result available"
)
continue
# Check if it's downloadable using proper URL parsing
if not resource.url:
skipped_count += 1
continue
is_downloadable = is_downloadable_domain(resource.url)
# Log what we're checking
if resource.url and "pubmed" in resource.url.lower():
logger.info(
"Found PubMed URL: {}",
# (#6938: redacted before it is cut.)
redact_and_bound_for_log(
redact_url_for_log(resource.url), 100
),
)
if not is_downloadable:
skipped_count += 1
logger.opt(lazy=True).debug(
"Skipping non-downloadable URL: {}",
lambda: redact_and_bound_for_log(
redact_url_for_log(resource.url), 100
),
)
continue
eligible.append(resource)
# One download refills a document that awaits its PDF, so only one
# of the resources that would refill the same document is queued.
eligible, covered = _one_resource_per_awaiting_document(
db_session, eligible, username, user_password
)
skipped_count += covered
for resource in eligible:
# Check if already in queue (any status)
existing_queue = (
db_session.query(LibraryDownloadQueue)
.filter_by(resource_id=resource.id)
.first()
)
if existing_queue:
# Reset finished rows and claims stranded by a restart, but
# preserve a download claimed by this running server. Match
# the observed claim time inside the UPDATE so a new claim
# cannot be reset between the read and the write.
reset = (
db_session.query(LibraryDownloadQueue)
.filter(
LibraryDownloadQueue.id == existing_queue.id,
LibraryDownloadQueue.status != DocumentStatus.PENDING,
_resettable_download_queue_status(existing_queue),
)
.update(
{
LibraryDownloadQueue.status: DocumentStatus.PENDING,
LibraryDownloadQueue.completed_at: None,
},
synchronize_session=False,
)
)
# Counted either way, matching the pre-fix behaviour: a row
# already PENDING, a row just reset, and a row another stream
# is downloading are all "queued" to the caller.
queued_count += 1
research_ids.add(resource.research_id)
if reset:
logger.debug(
f"Reset queue entry for resource {resource.id} to pending"
)
else:
logger.debug(
f"Resource {resource.id} already pending or in flight"
)
else:
# Add new entry to queue
queue_entry = LibraryDownloadQueue(
resource_id=resource.id,
research_id=resource.research_id,
priority=0,
status=DocumentStatus.PENDING,
)
db_session.add(queue_entry)
queued_count += 1
research_ids.add(resource.research_id)
logger.debug(
f"Added new queue entry for resource {resource.id}"
)
db_session.commit()
logger.info(
f"Queued {queued_count} articles for download, skipped {skipped_count} resources (including {filter_summary.permanently_failed_count} permanently failed and {filter_summary.temporarily_failed_count} temporarily failed)"
)
# Note: Removed synchronous download processing here to avoid blocking the HTTP request
# Downloads will be processed via the SSE streaming endpoint or background tasks
return {
"success": True,
"queued": queued_count,
"research_ids": list(research_ids),
"total_undownloaded": len(undownloaded),
"skipped": skipped_count,
"filter_summary": filter_summary.to_dict(),
"skipped_details": skipped_info,
}
@router.get("/api/get-research-sources/{research_id}")
def get_research_sources(
request: Request,
research_id,
username: Annotated[str, Depends(require_auth)],
):
"""Get all sources for a research with snippets."""
sources = []
with get_user_db_session(username) as db_session:
# Get all resources for this research
resources = (
db_session.query(ResearchResource)
.filter_by(research_id=research_id)
.order_by(ResearchResource.created_at)
.all()
)
for idx, resource in enumerate(resources, 1):
# Check if document exists
document = get_document_for_resource(db_session, resource)
# Get domain from URL
domain = ""
if resource.url:
try:
from urllib.parse import urlparse
domain = urlparse(resource.url).hostname or ""
except (ValueError, AttributeError):
# urlparse can raise ValueError for malformed URLs
pass
source_data = {
"number": idx,
"resource_id": resource.id,
"url": resource.url,
"title": resource.title or f"Source {idx}",
"snippet": resource.content_preview or "",
"domain": domain,
"relevance_score": getattr(resource, "relevance_score", None),
"downloaded": False,
"document_id": None,
"file_type": None,
}
# The Download Manager's rule: a completed document, unless it
# awaits its PDF (see document_counts_as_downloaded). A loaded
# status never equals the string "completed".
if document and document_counts_as_downloaded(document):
source_data.update(
{
"downloaded": True,
"document_id": document.id,
"file_type": document.file_type,
"download_date": document.created_at.isoformat()
if document.created_at
else None,
}
)
sources.append(source_data)
return {"success": True, "sources": sources, "total": len(sources)}
@router.post("/api/check-downloads")
async def check_downloads(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Check download status for a list of URLs."""
data, body_error = await read_json_dict(
request, "simple", "Request body must be valid JSON"
)
if body_error is not None:
return body_error
research_id = data.get("research_id")
urls = data.get("urls", [])
if not isinstance(research_id, str) or not research_id.strip() or not urls:
return JSONResponse(
{"error": "Missing research_id or urls"}, status_code=400
)
if error := _string_list_error(urls, "urls"):
return error
def _query_sync():
download_status = {}
with get_user_db_session(username) as db_session:
resources = (
db_session.query(ResearchResource)
.filter_by(research_id=research_id)
.filter(ResearchResource.url.in_(urls))
.all()
)
for resource in resources:
document = get_document_for_resource(db_session, resource)
# A document that awaits its PDF is reported not downloaded,
# with the resource_id to download it by (see
# document_counts_as_downloaded).
if document and document_counts_as_downloaded(document):
# Do NOT return document.file_path — it's the absolute
# server path, which leaks directory layout to any
# authenticated user. The client fetches via
# `/document/{id}/pdf` or `/document/{id}/text` using
# document_id, so the path is never needed client-side.
download_status[resource.url] = {
"downloaded": True,
"document_id": document.id,
"file_type": document.file_type,
"title": document.title or resource.title,
}
else:
download_status[resource.url] = {
"downloaded": False,
"resource_id": resource.id,
}
return download_status
download_status = await run_db_sync(_query_sync)
return {"download_status": download_status}
@router.post("/api/download-source")
async def download_source(
request: Request, username: Annotated[str, Depends(require_auth)]
):
"""Download a single source from a research."""
user_password = get_authenticated_user_password(username)
data, body_error = await read_json_dict(
request, "simple", "Request body must be valid JSON"
)
if body_error is not None:
return body_error
research_id = data.get("research_id")
url = data.get("url")
if not research_id or not url:
return JSONResponse(
{"error": "Missing research_id or url"}, status_code=400
)
# Check if URL is downloadable
if not is_downloadable_domain(url):
return JSONResponse(
{"error": "URL is not from a downloadable domain"}, status_code=400
)
def _download_sync():
"""The DB + network work — all blocking, run in a threadpool."""
with get_user_db_session(username) as db_session:
# Find the resource
resource = (
db_session.query(ResearchResource)
.filter_by(research_id=research_id, url=url)
.first()
)
if not resource:
return JSONResponse(
{"error": "Resource not found"}, status_code=404
)
# Check if already downloaded, by the Download Manager's rule
# (see document_counts_as_downloaded). A document that awaits
# its PDF is downloaded again, into the same document.
existing = get_document_for_resource(db_session, resource)
if existing and document_counts_as_downloaded(existing):
return {
"success": True,
"message": "Already downloaded",
"document_id": existing.id,
}
# Add to download queue
queue_entry = (
db_session.query(LibraryDownloadQueue)
.filter_by(resource_id=resource.id)
.first()
)
if not queue_entry:
queue_entry = LibraryDownloadQueue(
resource_id=resource.id,
research_id=resource.research_id,
priority=1, # Higher priority for manual downloads
status=DocumentStatus.PENDING,
)
db_session.add(queue_entry)
db_session.commit()
else:
# Reclaim a row stranded by a restart, while preserving an
# in-flight download and any claim refreshed after our read.
reset = (
db_session.query(LibraryDownloadQueue)
.filter(
LibraryDownloadQueue.id == queue_entry.id,
_resettable_download_queue_status(queue_entry),
)
.update(
{
LibraryDownloadQueue.status: DocumentStatus.PENDING,
LibraryDownloadQueue.priority: 1,
},
synchronize_session=False,
)
)
db_session.commit()
if not reset:
return JSONResponse(
{
"success": False,
"message": "Download already in progress",
},
status_code=409,
)
queue_item_id = queue_entry.id
# The claim commits and expires ORM rows. Snapshot the resource
# ID first so no attribute access can fail between claiming and
# the download. Base re-read resource.id after claiming, inside
# the try: that refresh raised, and although the handler caught
# it and released the claim, the download itself never ran.
resource_id = resource.id
# Claim the row before downloading, exactly as download_bulk does,
# so a bulk stream that reaches this row between the reset above and
# the download below cannot also process it (issue #4691).
if not _claim_download_queue_item(db_session, queue_item_id):
return JSONResponse(
{
"success": False,
"message": "Download already in progress",
},
status_code=409,
)
# The claim above is committed. Leave the thread-local read scope
# before the remote download, which may occupy this worker for minutes.
try:
with DownloadService(username, user_password) as service:
success, message = service.download_resource(resource_id)
except Exception:
# A fresh short-lived session — the download ran outside the read
# scope above, so there is no held session to roll back. Pass the
# password captured at request start: by the time a multi-minute
# transfer ends, logout / password change / the idle sweep may
# have cleared the session password store, and the store-less
# lookup would raise DatabaseSessionError before the release,
# stranding the row in PROCESSING (issue #4691). Guard the
# release so a failure here cannot mask the original exception.
try:
with get_user_db_session(username, user_password) as db_session:
# Release the claim so a later run can retry this row:
# the download raised before download_resource recorded a
# terminal status (issue #4691).
_release_download_queue_item(db_session, queue_item_id)
except Exception:
logger.exception("Failed to release download-queue claim")
raise
# download_resource writes a terminal status for the rows it actually
# downloads, so this is a no-op for those; it fires on early returns,
# which would otherwise strand the claim in PROCESSING. The password
# must be passed for the same reason as the release above.
with get_user_db_session(username, user_password) as db_session:
_finalize_download_queue_item(db_session, queue_item_id, success)
if success:
return {"success": True, "message": "Download completed"}
if message in CLIENT_SAFE_DOWNLOAD_USER_MESSAGES:
# A refusal the operator can lift: say how.
return {
"success": False,
"message": download_reason_for_user(message),
}
# Log internal message, but show only generic message to user
return {"success": False, "message": "Download failed"}
# Offload the blocking DB + HTTP work so we don't stall the event loop.
return await run_db_sync(_download_sync)