~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
fix(news): start subscription research in-process (loopback POST failed CSRF) (#4834)
LearningCircuite51be7593f27
diff --git a/changelog.d/4834.bugfix.md b/changelog.d/4834.bugfix.mdnew file mode 100644index 0000000000..a9a1918235--- /dev/null+++ b/changelog.d/4834.bugfix.md@@ -0,0 +1 @@+The manual **Run now** button and the manual overdue-subscription sweep now actually start research. Both previously made a server-internal loopback HTTP POST to `/research/api/start`, which sits on a CSRF-protected blueprint and so always failed with HTTP 400 ("CSRF token is missing") — the "Run now" button reported `Failed to start research: 400`. They now invoke the research handler in-process, bypassing the HTTP/CSRF layer while still resolving the user's encrypted-database credentials. (Scheduled subscription runs were unaffected.)diff --git a/src/local_deep_research/news/flask_api.py b/src/local_deep_research/news/flask_api.pyindex 4babcc63d4..82297833f9 100644--- a/src/local_deep_research/news/flask_api.py+++ b/src/local_deep_research/news/flask_api.py@@ -15,7 +15,6 @@ from ..web.auth.decorators import login_requiredfrom ..database.session_context import get_user_db_sessionfrom ..settings.env_registry import get_env_settingfrom ..utilities.db_utils import get_settings_manager-from ..security import safe_postfrom ..llm.providers.base import normalize_providerfrom ..security.decorators import require_json_body@@ -104,6 +103,71 @@ def _is_job_owned_by_user(job, username, scheduler):return False+def _call_start_research_internal(request_data: dict) -> dict:+ """Start a research run by invoking the research route handler in-process.++ Both manual subscription runs (``run_subscription_now``) and the overdue+ sweep (``check_overdue_subscriptions``) previously issued a loopback HTTP+ POST to ``/research/api/start`` via ``safe_post``. That endpoint lives on a+ CSRF-protected blueprint (only ``api_v1`` is exempt — see+ ``web/app_factory.py``), and a server-to-server request cannot carry a CSRF+ token, so every loopback failed with HTTP 400 ("The CSRF token is+ missing"). Forwarding the user's session cookie did not help — CSRF is+ checked before authentication. The result: both the "run now" button and+ the overdue endpoint were broken (only the scheduler path, which calls the+ programmatic API directly, still worked).++ Calling the view function directly skips the HTTP layer (and therefore the+ CSRF ``before_request`` hook) entirely, and removes any need to relay the+ session cookie. Must be called from within the authenticated request+ context of the caller; that context's session and DB session are+ propagated into the nested request context so ``start_research`` can resolve+ the user's DB password (it reads ``session["session_id"]`` -> password+ store, or ``g.user_password``) and reuse the open connection.++ Returns the route's JSON body as a dict (with at least a ``status`` key).+ """+ from flask import current_app, g, session+ from ..web.routes.research_routes import start_research+ from ..database.session_context import get_g_db_session++ host_url = request.host_url.rstrip("/")+ # Snapshot the caller's auth context. Copying only session["username"]+ # would make start_research() -> resolve_user_password() fail with+ # "session expired" on encrypted databases, because the DB password is+ # keyed by session["session_id"] in the password store.+ outer_session = dict(session)+ outer_user_password = getattr(g, "user_password", None)+ db_session = get_g_db_session()++ # Pushing a request context for the same app reuses the existing app+ # context, so ``g`` is shared with the caller and ``session`` is fresh.+ # session.update() is therefore required; the g.* assignments below are+ # usually no-ops but kept so this stays correct if a fresh app context is+ # ever pushed (e.g. a different invocation path or a future Flask change).+ with current_app.test_request_context(+ "/research/api/start",+ method="POST",+ json=request_data,+ base_url=host_url,+ ):+ session.update(outer_session)+ if outer_user_password is not None:+ g.user_password = outer_user_password # gitleaks:allow+ if db_session is not None:+ g.db_session = db_session++ result = start_research()++ # start_research returns either a Response or (Response, status_code).+ # The target path is under /api/, so @login_required returns a JSON 401+ # (never an HTML redirect) and every other return is jsonify(...), so+ # get_json() always yields a dict — keep this route under /api/.+ resp_obj = result[0] if isinstance(result, tuple) else result+ data: dict = resp_obj.get_json()+ return data++# Create Blueprint - no url_prefix here since parent blueprint already has /newsnews_api_bp = Blueprint("news_api", __name__, url_prefix="/api")# NOTE: Routes use session["username"] (not .get()) intentionally.@@ -611,56 +675,48 @@ def run_subscription_now(subscription_id: str) -> Any:# request-cached and not closed on exit).db.rollback()- # Call the research API endpoint (api_bp at /research/api), now with no- # DB transaction held open. Use request.host_url to get the actual URL- # the server responds on.- base_url = request.host_url.rstrip("/")-- response = safe_post(- f"{base_url}/research/api/start",- json=request_data,- headers={"Content-Type": "application/json"},- allow_localhost=True,- allow_private_ips=True,- )-- if response.ok:- data = response.json()- if data.get("status") in ("success", "queued"):- # Advance the schedule so a subscription that was also overdue- # is not immediately re-run by the scheduler while this run is- # in flight. If the run later fails, the research failure- # handler resets next_refresh so the scheduler retries it.- # Compare-and-set: only advance if next_refresh is unchanged- # since we read it pre-spawn. A fast-failing run can reset it- # (worker thread) before we get here; in that case leave the- # reset in place rather than clobbering it and re-hiding the- # failed subscription for a full interval.- with get_user_db_session(username) as db:- sub = (- db.query(NewsSubscription)- .filter(NewsSubscription.id == subscription_pk)- .first()- )- if sub and sub.next_refresh == prev_next_refresh:- advance_refresh_schedule(- sub, datetime.now(timezone.utc)- )- db.commit()- return jsonify(- {- "status": "success",- "message": "Research started",- "research_id": data.get("research_id"),- "url": f"/progress/{data.get('research_id')}",- }+ # Start the research in-process. A loopback HTTP POST to+ # /research/api/start cannot pass CSRF validation (see+ # _call_start_research_internal), so call the route handler directly.+ # The read transaction was already released above so the research+ # route can reuse the connection without contending for the lock.+ data = _call_start_research_internal(request_data)++ if data.get("status") in ("success", "queued"):+ # Advance the schedule so a subscription that was also overdue+ # is not immediately re-run by the scheduler while this run is+ # in flight. If the run later fails, the research failure+ # handler resets next_refresh so the scheduler retries it.+ # Compare-and-set: only advance if next_refresh is unchanged+ # since we read it pre-spawn. A fast-failing run can reset it+ # (worker thread) before we get here; in that case leave the+ # reset in place rather than clobbering it and re-hiding the+ # failed subscription for a full interval.+ with get_user_db_session(username) as db:+ sub = (+ db.query(NewsSubscription)+ .filter(NewsSubscription.id == subscription_pk)+ .first())+ if sub and sub.next_refresh == prev_next_refresh:+ advance_refresh_schedule(sub, datetime.now(timezone.utc))+ db.commit()return jsonify(- {"error": data.get("message", "Failed to start research")}- ), 500+ {+ "status": "success",+ "message": "Research started",+ "research_id": data.get("research_id"),+ "url": f"/progress/{data.get('research_id')}",+ }+ )return jsonify(- {"error": f"Failed to start research: {response.status_code}"}- ), response.status_code+ {+ "error": data.get(+ "message",+ data.get("error", "Failed to start research"),+ )+ }+ ), 500except Exception as e:return jsonify(@@ -1130,13 +1186,22 @@ def check_overdue_subscriptions():current_date = get_local_date_string(settings_manager)for sub in overdue_subs:+ # Capture identity up front as plain strings. This loop shares+ # one DB session across every start_research call, and+ # start_research's error path does not roll back — so a failed+ # run can leave the session in a PendingRollbackError state.+ # Reading sub.* again in an error branch would then raise (the+ # row was expired by an earlier commit), collapsing the whole+ # sweep. Snapshotting here keeps the error branches session-free.+ sub_id = str(sub.id)+ sub_label = sub.name or sub.query_or_topic[:50]try:# Run the subscription using the same pattern as run_subscription_nowlogger.info(- f"Running overdue subscription: {sub.name or sub.query_or_topic[:30]}"+ f"Running overdue subscription: {sub_label[:30]}")- # Snapshot for the post-POST compare-and-set (see below).+ # Snapshot for the post-run compare-and-set (see below).prev_next_refresh = sub.next_refreshrequest_data = build_subscription_request_data(@@ -1152,36 +1217,12 @@ def check_overdue_subscriptions():title=sub.name,)- # Make HTTP request to research API- from flask import request-- # Use request.host_url to get the actual URL the server is responding on- base_url = request.host_url.rstrip("/")-- # Use the session from the current request to maintain authentication- session_cookie = request.cookies.get("session")-- response = safe_post(- f"{base_url}/research/api/start",- json=request_data,- headers={- "Content-Type": "application/json",- "Cookie": f"session={session_cookie}"- if session_cookie- else "",- },- timeout=30,- allow_localhost=True,- allow_private_ips=True,- )-- if response.ok:- result = response.json()- else:- result = {- "status": "error",- "error": f"HTTP {response.status_code}: {response.text}",- }+ # Start the research in-process. A loopback HTTP POST to+ # /research/api/start cannot pass CSRF validation (see+ # _call_start_research_internal), so call the route handler+ # directly — this also removes the session-cookie relay+ # that the loopback used to attempt authentication.+ result = _call_start_research_internal(request_data)if result.get("status") in ("success", "queued"):overdue_count += 1@@ -1197,27 +1238,40 @@ def check_overdue_subscriptions():results.append({- "id": str(sub.id),- "name": sub.name or sub.query_or_topic[:50],+ "id": sub_id,+ "name": sub_label,"research_id": result.get("research_id"),})else:+ # start_research failed and may have left the shared+ # session dirty; reset it so the next subscription runs.+ db.rollback()results.append({- "id": str(sub.id),- "name": sub.name or sub.query_or_topic[:50],+ "id": sub_id,+ "name": sub_label,+ # start_research reports failures under+ # "message"; keep "error" as a fallback for+ # any other shape."error": result.get(- "error", "Failed to start research"+ "message",+ result.get(+ "error", "Failed to start research"+ ),),})except Exception as e:- logger.exception(f"Error running subscription {sub.id}")+ # Recover the shared session (a failed start_research commit+ # can leave it in a PendingRollbackError state) so the+ # remaining overdue subscriptions in the sweep still run.+ db.rollback()+ logger.exception(f"Error running subscription {sub_id}")results.append({- "id": str(sub.id),- "name": sub.name or sub.query_or_topic[:50],+ "id": sub_id,+ "name": sub_label,"error": safe_error_message(e, "running subscription"),diff --git a/src/local_deep_research/news/subscription_runner.py b/src/local_deep_research/news/subscription_runner.pyindex 146491cef4..9f1b890b5f 100644--- a/src/local_deep_research/news/subscription_runner.py+++ b/src/local_deep_research/news/subscription_runner.py@@ -4,8 +4,10 @@ These centralize logic that was previously copy-pasted across the three placesthat run a subscription:* ``run_subscription_now`` (manual "run now" button) and- ``check_overdue_subscriptions`` (the overdue sweep) -- both POST to- ``/research/api/start`` and share the request payload built here.+ ``check_overdue_subscriptions`` (the overdue sweep) -- both start research+ in-process via ``flask_api._call_start_research_internal`` and share the+ request payload built here. (They previously issued a loopback HTTP POST to+ ``/research/api/start``, which always failed CSRF validation.)* ``BackgroundJobScheduler`` -- triggers research programmatically, but sharesthe refresh-schedule arithmetic.diff --git a/tests/news/test_flask_api_coverage_gaps.py b/tests/news/test_flask_api_coverage_gaps.pyindex 757aabbc46..6ce537b39d 100644--- a/tests/news/test_flask_api_coverage_gaps.py+++ b/tests/news/test_flask_api_coverage_gaps.py@@ -57,6 +57,97 @@ def _session_ctx_returning(sub):return ctx+class TestCallStartResearchInternal:+ """Cover _call_start_research_internal: the in-process replacement for the+ old loopback HTTP POST to /research/api/start.++ The loopback could never pass CSRF (only the api_v1 blueprint is exempt),+ so both run_subscription_now and check_overdue_subscriptions were broken.+ Calling the route handler directly fixes that, but the nested request+ context MUST carry the caller's full auth context: start_research() resolves+ the user's DB password from session["session_id"] (-> password store) or+ g.user_password. Propagating only session["username"] makes research fail+ with "session expired" on encrypted databases — this test guards that+ regression.+ """++ def test_propagates_session_and_db_to_research_handler(self, app):+ from local_deep_research.news.flask_api import (+ _call_start_research_internal,+ )++ captured = {}++ def _spy_start_research():+ from flask import g as gg, request as rq+ from flask import session as ss++ captured["session"] = dict(ss)+ captured["db_session"] = getattr(gg, "db_session", None)+ captured["user_password"] = getattr(gg, "user_password", None)+ captured["payload"] = rq.get_json()+ return jsonify({"status": "success", "research_id": "spy_res"})++ sentinel_db = object()++ with app.test_request_context():+ from flask import g, session++ # Authenticated caller context: username AND session_id (the key+ # the DB-password store is keyed by) plus g state.+ session["username"] = "alice"+ session["session_id"] = "sid-abc123"+ g.db_session = sentinel_db+ g.user_password = "hunter2" # gitleaks:allow++ with patch(+ "local_deep_research.web.routes.research_routes.start_research",+ _spy_start_research,+ ):+ result = _call_start_research_internal({"query": "hello"})++ # Returns the handler's JSON body as a dict.+ assert result == {"status": "success", "research_id": "spy_res"}+ # The request payload reached the handler.+ assert captured["payload"] == {"query": "hello"}+ # Critically: session_id is propagated (not just username), so+ # resolve_user_password() can find the password. The PR this supersedes+ # copied only username and would fail this assertion.+ assert captured["session"]["username"] == "alice"+ assert captured["session"]["session_id"] == "sid-abc123"+ # The handler sees the caller's db session and password. Note these+ # arrive via the shared app-context ``g`` (the nested request context+ # reuses it), so these two assertions document the contract rather than+ # exercise the helper's explicit (defensive) g-copying. The session_id+ # assertion above is the one that fails against the username-only bug.+ assert captured["db_session"] is sentinel_db+ assert captured["user_password"] == "hunter2" # gitleaks:allow++ def test_handles_tuple_response_with_status_code(self, app):+ """start_research may return (Response, status_code); the helper must+ unwrap the body either way."""+ from local_deep_research.news.flask_api import (+ _call_start_research_internal,+ )++ def _spy_start_research():+ return jsonify({"status": "error", "message": "boom"}), 400++ with app.test_request_context():+ from flask import session++ session["username"] = "alice"+ session["session_id"] = "sid-xyz"++ with patch(+ "local_deep_research.web.routes.research_routes.start_research",+ _spy_start_research,+ ):+ result = _call_start_research_internal({"query": "q"})++ assert result == {"status": "error", "message": "boom"}++class TestSchedulerControlRequiredLogging:"""Cover the 403 branch that reads session username and remote_addr."""@@ -165,9 +256,7 @@ class TestRunSubscriptionNow:from local_deep_research.database.models.news import NewsSubscription- mock_response = MagicMock()- mock_response.ok = True- mock_response.json.return_value = {+ mock_response = {"status": "success","research_id": "res_42",}@@ -192,7 +281,7 @@ class TestRunSubscriptionNow:return_value=_session_ctx_returning(sub),),patch(- "local_deep_research.news.flask_api.safe_post",+ "local_deep_research.news.flask_api._call_start_research_internal",return_value=mock_response,),patch(@@ -223,9 +312,7 @@ class TestRunSubscriptionNow:from local_deep_research.database.models.news import NewsSubscription- mock_response = MagicMock()- mock_response.ok = True- mock_response.json.return_value = {+ mock_response = {"status": "success","research_id": "res_99",}@@ -248,7 +335,7 @@ class TestRunSubscriptionNow:return_value=_session_ctx_returning(sub),),patch(- "local_deep_research.news.flask_api.safe_post",+ "local_deep_research.news.flask_api._call_start_research_internal",return_value=mock_response,) as mock_post,patch(@@ -264,7 +351,7 @@ class TestRunSubscriptionNow:resp = client.post("/news/api/subscriptions/sub_1/run")assert resp.status_code == 200- sent = mock_post.call_args.kwargs["json"]+ sent = mock_post.call_args.args[0]# Unset → falsy, so the backend resolves from user settings.assert not sent["model_provider"]assert not sent["model"]@@ -278,9 +365,7 @@ class TestRunSubscriptionNow:from local_deep_research.database.models.news import NewsSubscription- mock_response = MagicMock()- mock_response.ok = True- mock_response.json.return_value = {+ mock_response = {"status": "success","research_id": "res_100",}@@ -304,7 +389,7 @@ class TestRunSubscriptionNow:return_value=_session_ctx_returning(sub),),patch(- "local_deep_research.news.flask_api.safe_post",+ "local_deep_research.news.flask_api._call_start_research_internal",return_value=mock_response,) as mock_post,patch(@@ -320,19 +405,21 @@ class TestRunSubscriptionNow:resp = client.post("/news/api/subscriptions/sub_1/run")assert resp.status_code == 200- sent = mock_post.call_args.kwargs["json"]+ sent = mock_post.call_args.args[0]assert sent["model_provider"] == "openai"assert sent["model"] == "gpt-4o"def test_failed_response_returns_error(self, client):- """Non-ok response from research API returns the status code."""+ """An error status from start_research surfaces as a 500 with the+ error message (the in-process call has no HTTP status code to relay)."""self._setup_auth(client)from local_deep_research.database.models.news import NewsSubscription- mock_response = MagicMock()- mock_response.ok = False- mock_response.status_code = 503+ mock_response = {+ "status": "error",+ "message": "Service unavailable",+ }sub = NewsSubscription(id="sub_1",@@ -350,7 +437,7 @@ class TestRunSubscriptionNow:return_value=_session_ctx_returning(sub),),patch(- "local_deep_research.news.flask_api.safe_post",+ "local_deep_research.news.flask_api._call_start_research_internal",return_value=mock_response,),patch(@@ -364,7 +451,50 @@ class TestRunSubscriptionNow:mock_db.is_user_connected.return_value = Trueresp = client.post("/news/api/subscriptions/sub_1/run")- assert resp.status_code == 503+ assert resp.status_code == 500+ # The actual start_research message must surface (it reports failures+ # under "message"), not a generic fallback — guards the+ # message-over-error extraction.+ assert resp.get_json()["error"] == "Service unavailable"++ def test_helper_exception_propagates_as_500(self, client):+ """If _call_start_research_internal raises (e.g. start_research blows+ up), run_subscription_now's outer handler returns a 500 rather than+ leaking the traceback. The old safe_post path converted HTTP failures+ to error dicts; the in-process call can raise, so this path matters."""+ self._setup_auth(client)++ from local_deep_research.database.models.news import NewsSubscription++ sub = NewsSubscription(+ id="sub_1",+ query_or_topic="test",+ subscription_type="topic",+ refresh_interval_minutes=60,+ )++ with (+ patch(+ "local_deep_research.web.auth.decorators.db_manager",+ ) as mock_db,+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ return_value=_session_ctx_returning(sub),+ ),+ patch(+ "local_deep_research.news.flask_api._call_start_research_internal",+ side_effect=RuntimeError("boom"),+ ),+ patch(+ "local_deep_research.news.core.utils.get_local_date_string",+ return_value="2026-03-20",+ ),+ patch("local_deep_research.settings.manager.SettingsManager"),+ ):+ mock_db.is_user_connected.return_value = True++ resp = client.post("/news/api/subscriptions/sub_1/run")+ assert resp.status_code == 500assert "error" in resp.get_json()def test_successful_run_advances_refresh_schedule(self, client):@@ -381,9 +511,7 @@ class TestRunSubscriptionNow:self._setup_auth(client)- mock_response = MagicMock()- mock_response.ok = True- mock_response.json.return_value = {+ mock_response = {"status": "success","research_id": "res_adv",}@@ -406,7 +534,7 @@ class TestRunSubscriptionNow:return_value=_session_ctx_returning(sub),),patch(- "local_deep_research.news.flask_api.safe_post",+ "local_deep_research.news.flask_api._call_start_research_internal",return_value=mock_response,),patch(@@ -467,9 +595,7 @@ class TestRunSubscriptionNow:ctx.__enter__ = MagicMock(return_value=session)ctx.__exit__ = MagicMock(return_value=False)- mock_response = MagicMock()- mock_response.ok = True- mock_response.json.return_value = {+ mock_response = {"status": "success","research_id": "res_x",}@@ -483,7 +609,7 @@ class TestRunSubscriptionNow:return_value=ctx,),patch(- "local_deep_research.news.flask_api.safe_post",+ "local_deep_research.news.flask_api._call_start_research_internal",return_value=mock_response,),patch(@@ -527,9 +653,7 @@ class TestCheckOverdueSubscriptions:def _run(self, client, sub):"""POST /check-overdue with the DB query returning [sub]; return therequest_data dict sent to the research backend."""- mock_response = MagicMock()- mock_response.ok = True- mock_response.json.return_value = {+ mock_response = {"status": "success","research_id": "res_overdue",}@@ -550,7 +674,7 @@ class TestCheckOverdueSubscriptions:return_value=mock_ctx_mgr,),patch(- "local_deep_research.news.flask_api.safe_post",+ "local_deep_research.news.flask_api._call_start_research_internal",return_value=mock_response,) as mock_post,patch(@@ -564,7 +688,7 @@ class TestCheckOverdueSubscriptions:mock_db.is_user_connected.return_value = Trueresp = client.post("/news/api/check-overdue")assert resp.status_code == 200, resp.get_json()- return mock_post.call_args.kwargs["json"]+ return mock_post.call_args.args[0]def test_unset_model_config_falls_back_to_user_settings(self, client):"""Overdue sub without provider/model must not force ollama/llama3."""@@ -613,9 +737,7 @@ class TestCheckOverdueSubscriptions:t1 = datetime(2026, 6, 10, 12, 5, tzinfo=timezone.utc) # worker resetsub = self._make_sub(next_refresh=t0, last_refresh=None)- mock_response = MagicMock()- mock_response.ok = True- mock_response.json.return_value = {+ mock_response = {"status": "success","research_id": "res_overdue",}@@ -642,7 +764,7 @@ class TestCheckOverdueSubscriptions:return_value=mock_ctx_mgr,),patch(- "local_deep_research.news.flask_api.safe_post",+ "local_deep_research.news.flask_api._call_start_research_internal",return_value=mock_response,),patch(@@ -659,6 +781,69 @@ class TestCheckOverdueSubscriptions:assert sub.last_refresh is None, "advance clobbered the reset"assert sub.next_refresh == t1+ def test_failed_sub_rolls_back_and_sweep_continues(self, client):+ """A failing subscription (error result OR raised exception) must roll+ back the shared session and let the remaining overdue subs run.++ Regression guard: the loop shares one DB session with start_research,+ whose error path does not roll back. Without the per-iteration+ db.rollback() recovery, a PendingRollbackError would propagate while+ re-reading the expired sub and collapse the entire sweep into a 500,+ discarding all partial results.+ """+ _auth_session(client)++ sub_err = self._make_sub(id="sub_err", name="Returns error")+ sub_raise = self._make_sub(id="sub_raise", name="Raises")+ sub_ok = self._make_sub(id="sub_ok", name="Succeeds")++ db_mock = MagicMock()+ db_mock.query.return_value.filter.return_value.all.return_value = [+ sub_err,+ sub_raise,+ sub_ok,+ ]++ mock_ctx_mgr = MagicMock()+ mock_ctx_mgr.__enter__ = MagicMock(return_value=db_mock)+ mock_ctx_mgr.__exit__ = MagicMock(return_value=False)++ with (+ patch(+ "local_deep_research.web.auth.decorators.db_manager",+ ) as mock_db,+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ return_value=mock_ctx_mgr,+ ),+ patch(+ "local_deep_research.news.flask_api._call_start_research_internal",+ side_effect=[+ {"status": "error", "message": "kaboom"},+ RuntimeError("explode"),+ {"status": "success", "research_id": "rid-ok"},+ ],+ ),+ patch(+ "local_deep_research.news.core.utils.get_local_date_string",+ return_value="2026-03-20",+ ),+ patch("local_deep_research.settings.manager.SettingsManager"),+ ):+ mock_db.is_user_connected.return_value = True+ resp = client.post("/news/api/check-overdue")++ assert resp.status_code == 200, resp.get_json()+ data = resp.get_json()+ assert data["overdue_found"] == 3+ assert data["started"] == 1+ # Both failure branches recovered the session via rollback (>= 2 calls).+ assert db_mock.rollback.call_count >= 2+ by_id = {r["id"]: r for r in data["results"]}+ assert by_id["sub_err"]["error"] == "kaboom"+ assert "error" in by_id["sub_raise"]+ assert by_id["sub_ok"]["research_id"] == "rid-ok"+class TestUpdateSubscriptionFolderStatus:"""Cover update_subscription_folder: the is_active->status translationdiff --git a/tests/news/test_flask_api_scheduler_coverage.py b/tests/news/test_flask_api_scheduler_coverage.pyindex 193d0ed5a4..14ba92296d 100644--- a/tests/news/test_flask_api_scheduler_coverage.py+++ b/tests/news/test_flask_api_scheduler_coverage.py@@ -667,20 +667,16 @@ class TestCheckOverdueSuccessAndFailureMix:def fake_session(*a, **kw):yield mock_db- # HTTP response for sub_ok: research started successfully- ok_http = MagicMock()- ok_http.ok = True- ok_http.json.return_value = {+ # start_research result for sub_ok: research started successfully+ ok_result = {"status": "success","research_id": "rid-ok",}- # HTTP response for sub_fail: research returned an error body- fail_http = MagicMock()- fail_http.ok = True- fail_http.json.return_value = {+ # start_research result for sub_fail: research returned an error body+ fail_result = {"status": "error",- "error": "model not found",+ "message": "model not found",}mock_settings_cls = MagicMock()@@ -693,8 +689,8 @@ class TestCheckOverdueSuccessAndFailureMix:side_effect=fake_session,),patch(- "local_deep_research.news.flask_api.safe_post",- side_effect=[ok_http, fail_http],+ "local_deep_research.news.flask_api._call_start_research_internal",+ side_effect=[ok_result, fail_result],),patch("local_deep_research.settings.manager.SettingsManager",@@ -713,9 +709,13 @@ class TestCheckOverdueSuccessAndFailureMix:assert data["overdue_found"] == 2assert data["started"] == 1 # only sub_ok succeeded- result_ids = [r["id"] for r in data["results"]]- assert "uuid-ok" in result_ids- assert "uuid-fail" in result_ids+ by_id = {r["id"]: r for r in data["results"]}+ assert "uuid-ok" in by_id+ assert "uuid-fail" in by_id+ # The failed sub surfaces start_research's "message" text, not a generic+ # fallback — guards the message-over-error extraction.+ assert by_id["uuid-fail"]["error"] == "model not found"+ assert by_id["uuid-ok"]["research_id"] == "rid-ok"ok_result = next(r for r in data["results"] if r["id"] == "uuid-ok")fail_result = next(r for r in data["results"] if r["id"] == "uuid-fail")