Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(news): correct subscription run-now schedule + repair broken folder PUT route (#4492 follow-up) (#4587)

LearningCircuit7da1fefbf29b
diff --git a/changelog.d/4587.bugfix.md b/changelog.d/4587.bugfix.md
new file mode 100644
index 0000000000..179dfad886
--- /dev/null
+++ b/changelog.d/4587.bugfix.md
@@ -0,0 +1 @@
+Fixed news subscription scheduling regressions from #4492: a manual "Run Now" whose research later failed no longer pushes the subscription out a full refresh interval (it is reset to due so the scheduler retries), the run-now request no longer holds the encrypted-DB session open across the research-start HTTP call, and the subscription folder-update PUT route now keeps `status` authoritative (an `is_active` toggle pauses correctly instead of being ignored by the scheduler). The same folder-update route was also repaired — it previously failed on every call due to a bad relative import and a missing serializer.
diff --git a/src/local_deep_research/news/flask_api.py b/src/local_deep_research/news/flask_api.py
index d8942634a6..0002402e5b 100644
--- a/src/local_deep_research/news/flask_api.py
+++ b/src/local_deep_research/news/flask_api.py
@@ -562,6 +562,13 @@ def run_subscription_now(subscription_id: str) -> Any:
# drops model_provider/model/search_strategy/search_engine) ensures the
# manual run honors the subscription's saved model config, matching the
# overdue sweep and the scheduler.
+ # Read the subscription + build the payload, then release the read
+ # transaction before the blocking POST below. The per-user encrypted DB
+ # uses deferred isolation, so a SELECT holds a SHARED lock on the
+ # SQLCipher file until the transaction ends — and the session is
+ # request-cached, so it is NOT closed on `with` exit. We therefore
+ # rollback() explicitly to drop the read lock before the (up to 30s)
+ # HTTP call, then reopen a short session to advance.
with get_user_db_session(username) as db:
sub = (
db.query(NewsSubscription)
@@ -571,6 +578,11 @@ def run_subscription_now(subscription_id: str) -> Any:
if not sub:
return jsonify({"error": "Subscription not found"}), 404
+ subscription_pk = sub.id
+ # Snapshot next_refresh for the post-POST compare-and-set (below):
+ # a fast-failing run's failure handler may reset next_refresh on the
+ # worker thread, and the advance must not clobber that.
+ prev_next_refresh = sub.next_refresh
settings_manager = SettingsManager(db)
current_date = get_local_date_string(settings_manager)
@@ -586,40 +598,61 @@ def run_subscription_now(subscription_id: str) -> Any:
custom_endpoint=sub.custom_endpoint,
title=sub.name,
)
+ # End the read transaction so the SHARED lock is released before the
+ # blocking POST (exiting the `with` does not — the session is
+ # 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,
+ )
- # Call the research API endpoint (api_bp at /research/api).
- # 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.
- 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')}",
- }
+ 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(
- {"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", "Failed to start research")}
+ ), 500
+ return jsonify(
+ {"error": f"Failed to start research: {response.status_code}"}
+ ), response.status_code
except Exception as e:
return jsonify(
@@ -1094,6 +1127,9 @@ def check_overdue_subscriptions():
f"Running overdue subscription: {sub.name or sub.query_or_topic[:30]}"
)
+ # Snapshot for the post-POST compare-and-set (see below).
+ prev_next_refresh = sub.next_refresh
+
request_data = build_subscription_request_data(
query_template=sub.query_or_topic,
current_date=current_date,
@@ -1141,9 +1177,14 @@ def check_overdue_subscriptions():
if result.get("status") in ("success", "queued"):
overdue_count += 1
- # Update subscription's last/next refresh times
- advance_refresh_schedule(sub, datetime.now(UTC))
- db.commit()
+ # Update subscription's last/next refresh times.
+ # Compare-and-set: re-read and skip the advance if a
+ # fast-failing run already reset next_refresh (worker
+ # thread), so we don't clobber the reset and re-hide it.
+ db.refresh(sub)
+ if sub.next_refresh == prev_next_refresh:
+ advance_refresh_schedule(sub, datetime.now(UTC))
+ db.commit()
results.append(
{
@@ -1319,7 +1360,9 @@ def update_subscription_folder(subscription_id):
with get_user_db_session() as session:
# Manually handle the update to ensure next_refresh is recalculated
- from ...database.models import NewsSubscription as BaseSubscription
+ from ..database.models.news import (
+ NewsSubscription as BaseSubscription,
+ )
from datetime import datetime, timedelta, timezone
sub = (
@@ -1330,12 +1373,26 @@ def update_subscription_folder(subscription_id):
if not sub:
return jsonify({"error": "Subscription not found"}), 404
- # Update fields
+ # `status` is the single source of truth for active/paused (the
+ # scheduler keys on it, not the legacy is_active column). Translate
+ # an is_active toggle into status and keep both out of the blind
+ # setattr loop below -- otherwise a body like {"is_active": false}
+ # would flip only the legacy column while status stayed "active"
+ # and the scheduler would keep running the subscription. Mirrors
+ # api.update_subscription's translation.
+ if "is_active" in data:
+ sub.status = "active" if data["is_active"] else "paused"
+ if "status" in data:
+ sub.status = data["status"]
+
+ # Update remaining fields
for key, value in data.items():
if hasattr(sub, key) and key not in [
"id",
"user_id",
"created_at",
+ "is_active",
+ "status",
]:
setattr(sub, key, value)
@@ -1355,12 +1412,27 @@ def update_subscription_folder(subscription_id):
sub.updated_at = datetime.now(timezone.utc)
session.commit()
- result = sub.to_dict()
+ # NewsSubscription has no to_dict(); serialize the fields the UI
+ # needs explicitly. is_active is derived from status (the source of
+ # truth) so the response stays consistent with the toggle above.
+ result = {
+ "id": sub.id,
+ "name": sub.name,
+ "status": sub.status,
+ "is_active": sub.status == "active",
+ "folder_id": sub.folder_id,
+ "refresh_interval_minutes": sub.refresh_interval_minutes,
+ "next_refresh": sub.next_refresh.isoformat()
+ if sub.next_refresh
+ else None,
+ "last_refresh": sub.last_refresh.isoformat()
+ if sub.last_refresh
+ else None,
+ }
logger.info(
f"Updated subscription result: refresh_interval_minutes={result.get('refresh_interval_minutes')}, next_refresh={result.get('next_refresh')}"
)
return jsonify(result)
- # Force reload: v2
except Exception as e:
return jsonify(
diff --git a/src/local_deep_research/news/subscription_runner.py b/src/local_deep_research/news/subscription_runner.py
index b22faf17b3..146491cef4 100644
--- a/src/local_deep_research/news/subscription_runner.py
+++ b/src/local_deep_research/news/subscription_runner.py
@@ -118,3 +118,31 @@ def advance_refresh_schedule_by_id(db_session, subscription_id) -> bool:
return False
advance_refresh_schedule(subscription, datetime.now(timezone.utc))
return True
+
+
+def mark_subscription_due_by_id(db_session, subscription_id) -> bool:
+ """Reset a subscription to "due" after a FAILED run.
+
+ ``run_subscription_now`` (and the overdue sweep) advance ``next_refresh``
+ at spawn time so the scheduler will not double-run a subscription whose
+ research is still in flight. If that research then FAILS, the success-only
+ completion advance never fires, leaving ``next_refresh`` pushed a full
+ interval into the future and the subscription silently skipped until then.
+ The research failure handler calls this to reset ``next_refresh`` to now so
+ the scheduler picks the subscription up again on its next cycle -- matching
+ the pre-consolidation behavior where a failed manual run left the
+ subscription due. ``last_refresh`` is intentionally left untouched (it
+ records the last *successful* refresh). Returns True if the subscription
+ was found. Does not commit -- the caller owns the transaction.
+ """
+ from ..database.models.news import NewsSubscription
+
+ subscription = (
+ db_session.query(NewsSubscription)
+ .filter(NewsSubscription.id == str(subscription_id))
+ .first()
+ )
+ if not subscription:
+ return False
+ subscription.next_refresh = datetime.now(timezone.utc)
+ return True
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 65e3ee8c7d..554dd7cfd9 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -2537,6 +2537,38 @@ def run_research_process(research_id, query, mode, **kwargs):
else user_friendly_error
)
+ # A subscription-triggered run that FAILED must be made due again.
+ # run_subscription_now / the overdue sweep advance next_refresh at
+ # spawn time (to avoid the scheduler double-running an in-flight
+ # subscription), but the completion-time advance only runs on
+ # success. Without this reset a failed run would leave next_refresh
+ # pushed a full interval out, silently hiding the subscription from
+ # the scheduler. Skipped for SUSPENDED (user-terminated) runs.
+ if (
+ status == ResearchStatus.FAILED
+ and username
+ and metadata.get("subscription_id")
+ ):
+ try:
+ from ...news.subscription_runner import (
+ mark_subscription_due_by_id,
+ )
+
+ with get_user_db_session(username) as sub_db:
+ if mark_subscription_due_by_id(
+ sub_db, metadata["subscription_id"]
+ ):
+ sub_db.commit()
+ logger.info(
+ f"Reset subscription {metadata['subscription_id']} "
+ "to due after failed run"
+ )
+ except Exception:
+ logger.warning(
+ "Could not reset subscription refresh time after "
+ "failed run"
+ )
+
# Calculate duration up to termination point - using UTC consistently
now = datetime.now(UTC)
completed_at = now.isoformat()
diff --git a/tests/news/test_flask_api_coverage_gaps.py b/tests/news/test_flask_api_coverage_gaps.py
index 29ef9d582b..757aabbc46 100644
--- a/tests/news/test_flask_api_coverage_gaps.py
+++ b/tests/news/test_flask_api_coverage_gaps.py
@@ -367,6 +367,139 @@ class TestRunSubscriptionNow:
assert resp.status_code == 503
assert "error" in resp.get_json()
+ def test_successful_run_advances_refresh_schedule(self, client):
+ """A successful run advances the subscription's refresh schedule.
+
+ Regression guard for the PR's headline behavior: without the
+ advance_refresh_schedule() call, a manually-run subscription that was
+ also overdue would be immediately re-run by the scheduler. Deleting the
+ advance must fail this test.
+ """
+ from datetime import datetime, timedelta, timezone
+
+ from local_deep_research.database.models.news import NewsSubscription
+
+ self._setup_auth(client)
+
+ mock_response = MagicMock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "status": "success",
+ "research_id": "res_adv",
+ }
+
+ sub = NewsSubscription(
+ id="sub_1",
+ query_or_topic="AI news",
+ subscription_type="topic",
+ refresh_interval_minutes=60,
+ last_refresh=None,
+ next_refresh=None,
+ )
+
+ 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.safe_post",
+ return_value=mock_response,
+ ),
+ 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
+
+ before = datetime.now(timezone.utc)
+ resp = client.post("/news/api/subscriptions/sub_1/run")
+ after = datetime.now(timezone.utc)
+ assert resp.status_code == 200
+
+ assert sub.last_refresh is not None, "schedule was not advanced"
+ assert before <= sub.last_refresh <= after
+ assert sub.next_refresh == sub.last_refresh + timedelta(minutes=60)
+
+ def test_advance_skipped_when_failure_already_reset(self, client):
+ """Compare-and-set guard: if a fast-failing run already reset
+ next_refresh (worker thread) between the pre-spawn read and the
+ post-POST advance, the advance must NOT clobber it and re-hide the
+ failed subscription. Regression guard for the race in fix #1.
+ """
+ from datetime import datetime, timezone
+
+ from local_deep_research.database.models.news import NewsSubscription
+
+ self._setup_auth(client)
+
+ t0 = datetime(2026, 6, 10, 12, 0, tzinfo=timezone.utc)
+ # Worker's failure handler reset next_refresh to a different value
+ # before we reopen to advance.
+ t1 = datetime(2026, 6, 10, 12, 5, tzinfo=timezone.utc)
+ sub_read = NewsSubscription(
+ id="sub_1",
+ query_or_topic="q",
+ subscription_type="topic",
+ refresh_interval_minutes=60,
+ next_refresh=t0,
+ )
+ sub_after = NewsSubscription(
+ id="sub_1",
+ query_or_topic="q",
+ subscription_type="topic",
+ refresh_interval_minutes=60,
+ next_refresh=t1,
+ last_refresh=None,
+ )
+
+ session = MagicMock()
+ session.query.return_value.filter.return_value.first.side_effect = [
+ sub_read,
+ sub_after,
+ ]
+ ctx = MagicMock()
+ ctx.__enter__ = MagicMock(return_value=session)
+ ctx.__exit__ = MagicMock(return_value=False)
+
+ mock_response = MagicMock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "status": "success",
+ "research_id": "res_x",
+ }
+
+ 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=ctx,
+ ),
+ patch(
+ "local_deep_research.news.flask_api.safe_post",
+ return_value=mock_response,
+ ),
+ patch(
+ "local_deep_research.news.core.utils.get_local_date_string",
+ return_value="2026-06-10",
+ ),
+ 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 == 200
+
+ # CAS skipped the advance: the worker's reset (t1) is preserved.
+ assert sub_after.last_refresh is None, "advance clobbered the reset"
+ assert sub_after.next_refresh == t1
+
class TestCheckOverdueSubscriptions:
"""Cover check_overdue_subscriptions: the per-overdue-sub run path
@@ -452,6 +585,175 @@ class TestCheckOverdueSubscriptions:
assert sent["model_provider"] == "anthropic"
assert sent["model"] == "claude-3"
+ def test_successful_overdue_run_advances_schedule(self, client):
+ """The overdue sweep advances each run subscription's schedule.
+
+ Regression guard: without advance_refresh_schedule() the same overdue
+ subscription would be picked up and re-run on every sweep.
+ """
+ from datetime import timedelta
+
+ _auth_session(client)
+ sub = self._make_sub(refresh_interval_minutes=60)
+ self._run(client, sub)
+
+ assert sub.last_refresh is not None, "schedule was not advanced"
+ assert sub.next_refresh == sub.last_refresh + timedelta(minutes=60)
+
+ def test_overdue_run_skips_advance_when_reset_during_run(self, client):
+ """Compare-and-set in the sweep: if a fast-failing run already reset
+ next_refresh (worker thread, observed via db.refresh), the advance is
+ skipped so the reset is not clobbered. Mirrors the run-now CAS guard.
+ """
+ from datetime import datetime, timezone
+
+ _auth_session(client)
+
+ t0 = datetime(2026, 6, 10, 12, 0, tzinfo=timezone.utc)
+ t1 = datetime(2026, 6, 10, 12, 5, tzinfo=timezone.utc) # worker reset
+ sub = self._make_sub(next_refresh=t0, last_refresh=None)
+
+ mock_response = MagicMock()
+ mock_response.ok = True
+ mock_response.json.return_value = {
+ "status": "success",
+ "research_id": "res_overdue",
+ }
+
+ db_mock = MagicMock()
+ db_mock.query.return_value.filter.return_value.all.return_value = [sub]
+
+ # Simulate the worker's failure reset becoming visible on db.refresh().
+ def _refresh(obj):
+ obj.next_refresh = t1
+
+ db_mock.refresh.side_effect = _refresh
+
+ 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.safe_post",
+ return_value=mock_response,
+ ),
+ 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()
+
+ # CAS skipped the advance: the worker's reset (t1) is preserved.
+ assert sub.last_refresh is None, "advance clobbered the reset"
+ assert sub.next_refresh == t1
+
+
+class TestUpdateSubscriptionFolderStatus:
+ """Cover update_subscription_folder: the is_active->status translation
+ (so the PUT route keeps status authoritative) and the response
+ serialization (NewsSubscription has no to_dict)."""
+
+ def _ctx_for(self, sub):
+ """get_user_db_session() context whose query(...).filter_by(...).first()
+ yields ``sub`` (this route looks the row up via filter_by)."""
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ sub
+ )
+ ctx = MagicMock()
+ ctx.__enter__ = MagicMock(return_value=session)
+ ctx.__exit__ = MagicMock(return_value=False)
+ return ctx
+
+ def _put(self, client, sub, body):
+ with (
+ patch(
+ "local_deep_research.web.auth.decorators.db_manager",
+ ) as mock_db,
+ patch(
+ "local_deep_research.news.flask_api.get_user_db_session",
+ return_value=self._ctx_for(sub),
+ ),
+ ):
+ mock_db.is_user_connected.return_value = True
+ return client.put(
+ "/news/api/subscription/subscriptions/sub_1", json=body
+ )
+
+ def test_is_active_false_translates_to_paused_status(self, client):
+ """A {"is_active": false} body must pause via status, not just flip the
+ legacy column -- otherwise the status-keyed scheduler keeps running it.
+ """
+ from local_deep_research.database.models.news import NewsSubscription
+
+ _auth_session(client)
+ sub = NewsSubscription(
+ id="sub_1",
+ query_or_topic="q",
+ subscription_type="topic",
+ status="active",
+ refresh_interval_minutes=60,
+ )
+
+ resp = self._put(client, sub, {"is_active": False})
+
+ assert resp.status_code == 200, resp.get_json()
+ assert sub.status == "paused"
+ body = resp.get_json()
+ assert body["status"] == "paused"
+ assert body["is_active"] is False
+
+ def test_is_active_true_translates_to_active_status(self, client):
+ from local_deep_research.database.models.news import NewsSubscription
+
+ _auth_session(client)
+ sub = NewsSubscription(
+ id="sub_1",
+ query_or_topic="q",
+ subscription_type="topic",
+ status="paused",
+ refresh_interval_minutes=60,
+ )
+
+ resp = self._put(client, sub, {"is_active": True})
+
+ assert resp.status_code == 200, resp.get_json()
+ assert sub.status == "active"
+ assert resp.get_json()["is_active"] is True
+
+ def test_plain_field_update_returns_200_not_500(self, client):
+ """A non-status field update must serialize a response without raising
+ (NewsSubscription has no to_dict; the route builds the dict explicitly).
+ """
+ from local_deep_research.database.models.news import NewsSubscription
+
+ _auth_session(client)
+ sub = NewsSubscription(
+ id="sub_1",
+ query_or_topic="q",
+ subscription_type="topic",
+ status="active",
+ refresh_interval_minutes=60,
+ )
+
+ resp = self._put(client, sub, {"folder_id": "folder_9"})
+
+ assert resp.status_code == 200, resp.get_json()
+ assert sub.folder_id == "folder_9"
+ assert resp.get_json()["id"] == "sub_1"
+
class TestCheckSubscriptionsNow:
"""Cover check_subscriptions_now: DB query for overdue subs + threading."""
diff --git a/tests/news/test_subscription_runner.py b/tests/news/test_subscription_runner.py
index 96c6626455..7439ccb1eb 100644
--- a/tests/news/test_subscription_runner.py
+++ b/tests/news/test_subscription_runner.py
@@ -25,6 +25,7 @@ from local_deep_research.news.subscription_runner import (
advance_refresh_schedule,
advance_refresh_schedule_by_id,
build_subscription_request_data,
+ mark_subscription_due_by_id,
)
@@ -255,3 +256,63 @@ class TestAdvanceRefreshScheduleById:
_make_sub(db_session, "42", next_refresh=None)
# Callers pass ids from metadata dicts, which may be ints.
assert advance_refresh_schedule_by_id(db_session, 42) is True
+
+
+class TestMarkSubscriptionDueById:
+ """The failure-path reset that undoes the spawn-time schedule advance.
+
+ run_subscription_now advances next_refresh at spawn time so the scheduler
+ will not double-run an in-flight subscription. If that run fails, the
+ success-only completion advance never fires; without this reset the
+ subscription would be hidden from the scheduler for a full interval.
+ """
+
+ def test_resets_next_refresh_to_now(self, db_session):
+ # Simulate the spawn-time advance: next_refresh pushed far out.
+ future = datetime.now(timezone.utc) + timedelta(hours=24)
+ last = datetime.now(timezone.utc) - timedelta(minutes=1)
+ _make_sub(db_session, "s1", next_refresh=future, last_refresh=last)
+
+ before = datetime.now(timezone.utc)
+ assert mark_subscription_due_by_id(db_session, "s1") is True
+ after = datetime.now(timezone.utc)
+
+ sub = (
+ db_session.query(NewsSubscription)
+ .filter(NewsSubscription.id == "s1")
+ .first()
+ )
+ # next_refresh reset to ~now so due_filter(now) selects it again.
+ assert before <= sub.next_refresh <= after
+ # last_refresh is the last *successful* refresh and must be untouched.
+ assert sub.last_refresh == last
+
+ def test_missing_subscription_returns_false(self, db_session):
+ assert mark_subscription_due_by_id(db_session, "nope") is False
+
+ def test_reset_makes_subscription_due_again(self, db_session):
+ """End-to-end: a spawn-advanced sub is not due, then is after reset."""
+ future = datetime.now(timezone.utc) + timedelta(hours=24)
+ _make_sub(db_session, "s1", next_refresh=future)
+ now = datetime.now(timezone.utc)
+
+ not_due = (
+ db_session.query(NewsSubscription)
+ .filter(NewsSubscription.due_filter(now))
+ .all()
+ )
+ assert not_due == []
+
+ mark_subscription_due_by_id(db_session, "s1")
+ db_session.commit()
+
+ due = (
+ db_session.query(NewsSubscription)
+ .filter(NewsSubscription.due_filter(datetime.now(timezone.utc)))
+ .all()
+ )
+ assert [s.id for s in due] == ["s1"]
+
+ def test_non_string_id_is_stringified(self, db_session):
+ _make_sub(db_session, "7", next_refresh=None)
+ assert mark_subscription_due_by_id(db_session, 7) is True
diff --git a/tests/web/services/test_research_service_coverage.py b/tests/web/services/test_research_service_coverage.py
index fdabc57234..b592891f55 100644
--- a/tests/web/services/test_research_service_coverage.py
+++ b/tests/web/services/test_research_service_coverage.py
@@ -650,10 +650,12 @@ class TestRunResearchProcessTerminatedBeforeStart:
class TestRunResearchProcessQuickMode:
"""Quick mode research process end-to-end."""
- def _run_quick(self, results, search_error=None, **extra_kwargs):
+ def _run_quick(
+ self, results, search_error=None, research_meta=None, **extra_kwargs
+ ):
"""Helper to run quick mode with mocked dependencies."""
mock_session = MagicMock()
- research = _make_research_mock()
+ research = _make_research_mock(research_meta=research_meta)
mock_session.query.return_value.filter_by.return_value.first.return_value = research
mock_system = MagicMock()
@@ -750,6 +752,45 @@ class TestRunResearchProcessQuickMode:
assert research.status == "completed"
mock_storage.save_report.assert_called_once()
+ def test_failed_subscription_run_is_reset_to_due(self):
+ """A FAILED subscription-triggered run resets next_refresh to due.
+
+ Integration guard for the headline fix #1: the failure handler in
+ run_research_process must call mark_subscription_due_by_id so a failed
+ run is retried by the scheduler instead of being hidden a full interval.
+ """
+ with patch(
+ "local_deep_research.news.subscription_runner.mark_subscription_due_by_id",
+ return_value=True,
+ ) as mock_reset:
+ self._run_quick(
+ results=None,
+ search_error=RuntimeError("provider unavailable"),
+ research_meta={
+ "subscription_id": "sub_x",
+ "is_news_search": True,
+ },
+ )
+
+ mock_reset.assert_called_once()
+ # called as mark_subscription_due_by_id(db_session, subscription_id)
+ assert mock_reset.call_args.args[1] == "sub_x"
+
+ def test_failed_non_subscription_run_does_not_reset(self):
+ """A FAILED run that is NOT subscription-triggered never calls the
+ reset (the guard must require a subscription_id)."""
+ with patch(
+ "local_deep_research.news.subscription_runner.mark_subscription_due_by_id",
+ return_value=True,
+ ) as mock_reset:
+ self._run_quick(
+ results=None,
+ search_error=RuntimeError("boom"),
+ research_meta={}, # no subscription_id
+ )
+
+ mock_reset.assert_not_called()
+
def test_quick_mode_no_findings_queues_error(self):
results = {
"findings": [],