Files
MoviePilot/tests/test_subscription_search_governance.py

972 lines
38 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""订阅搜索队列接入、锁隔离和批次失败治理测试。"""
import threading
from dataclasses import replace
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from unittest.mock import Mock, patch
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.application.site.observation import report_site_search_outcome
from app.application.subscription.contract import SubscriptionSnapshot
from app.application.subscription.execution import (
SubscriptionExecutionAdmission,
raise_subscription_site_budget_failures,
)
from app.application.subscription.sitebudget import (
SubscriptionSearchCancelled,
SubscriptionSearchDeferred,
)
from app.chain.search.facade import SearchChain
from app.chain.search.provider import SearchProviderOwner
from app.chain.subscribe import search as subscribe_search
from app.chain.subscribe.facade import SubscribeChain
from app.chain.subscribe.search import _search_task_available_at
from app.db.adapters.subscriptionsearch import TransactionalSubscriptionSearchRepository
from app.db.base import Base
from app.db.models.subscriptionsearch import SubscriptionSearchTask
from app.modules.indexer import IndexerModule
from app.schemas.types import MediaType
class _ForbiddenLock:
"""正式队列路径若仍访问 Match 全局锁则立即失败。"""
def acquire(self, **_kwargs):
"""禁止搜索队列取得历史长锁。"""
raise AssertionError("持久搜索队列不应取得 Match 全局锁")
def release(self):
"""禁止搜索队列释放从未取得的历史长锁。"""
raise AssertionError("持久搜索队列不应释放 Match 全局锁")
class _SubscriptionRepository:
"""为搜索队列返回稳定的多订阅快照。"""
def __init__(self, subscribes: list[SubscriptionSnapshot]) -> None:
"""保存各订阅的不可变测试快照。"""
self._subscribes = {subscribe.id: subscribe for subscribe in subscribes}
def list(self, _state: str = None) -> list[SubscriptionSnapshot]:
"""返回全部测试订阅。"""
return list(self._subscribes.values())
def get(self, subscribe_id: int) -> SubscriptionSnapshot | None:
"""按 ID 返回任务执行时重新读取的订阅。"""
return self._subscribes.get(subscribe_id)
def _subscribe(subscribe_id: int) -> SubscriptionSnapshot:
"""构造越过新增保护期的活动电影订阅。"""
return SubscriptionSnapshot(
id=subscribe_id,
name=f"治理电影 {subscribe_id}",
year="2026",
type=MediaType.MOVIE.value,
media_source="themoviedb",
media_id=str(1000 + subscribe_id),
state="R",
date=(datetime.now() - timedelta(minutes=2)).strftime("%Y-%m-%d %H:%M:%S"),
)
def _chain(tmp_path, subscribes: list[SubscriptionSnapshot]):
"""构造注入持久队列且不初始化其他 Chain 依赖的搜索实例。"""
engine = create_engine(f"sqlite:///{tmp_path / 'search-governance.db'}")
Base.metadata.create_all(engine)
chain = object.__new__(SubscribeChain)
chain.subscription_repository = _SubscriptionRepository(subscribes)
chain.subscription_search_repository = TransactionalSubscriptionSearchRepository(
sessionmaker(bind=engine)
)
chain.get_states_for_search = lambda state: state
chain._match_lock = _ForbiddenLock()
chain._search_queue_lock = threading.Lock()
chain._subscription_execution_admission = SubscriptionExecutionAdmission()
chain.messagehelper = Mock()
return chain
def _make_tasks_ready(monkeypatch) -> None:
"""让治理测试中的持久任务立即到期,避免依赖真实随机时钟。"""
ready_at = "1970-01-01T00:00:00+00:00"
monkeypatch.setattr(
"app.chain.subscribe.search._search_task_available_at",
lambda _source, subscription_ids: {
subscription_id: ready_at for subscription_id in subscription_ids
},
)
def test_fallback_task_schedule_jitters_once_for_large_batch(monkeypatch):
"""千条订阅共享一次启动抖动,不能再累计成数日空等。"""
now = datetime(2026, 9, 3, 1, 2, 3, tzinfo=timezone.utc)
jitter = Mock(return_value=12)
monkeypatch.setattr("app.chain.subscribe.search.random.randint", jitter)
schedule = _search_task_available_at("fallback", tuple(range(1000)), now=now)
assert len(schedule) == 1000
assert set(schedule.values()) == {(now + timedelta(seconds=12)).isoformat(timespec="seconds")}
jitter.assert_called_once_with(0, 60)
def test_inline_fallback_search_preserves_site_pressure_stagger(tmp_path, monkeypatch):
"""无持久队列的兼容宿主仍须在每条自动兜底订阅前错峰。"""
subscribes = [_subscribe(20), _subscribe(21)]
chain = _chain(tmp_path, subscribes)
del chain.subscription_search_repository
waits = []
delays = iter((60, 300))
monkeypatch.setattr(
"app.chain.subscribe.search.random.randint",
lambda _low, _high: next(delays),
)
monkeypatch.setattr("app.chain.subscribe.search.time.sleep", waits.append)
monkeypatch.setattr(
chain,
"_process_search_subscription",
lambda item, _searchchain, **_kwargs: item,
)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
chain.search(state="R")
assert waits == [60, 300]
def test_successful_sites_remain_available_to_next_due_subscription(tmp_path, monkeypatch):
"""正常站点请求不能让同批下一条到期订阅漏掉目标站点。"""
subscribes = [_subscribe(40), _subscribe(41)]
chain = _chain(tmp_path, subscribes)
_make_tasks_ready(monkeypatch)
searchchain = object.__new__(SearchChain)
searchchain.configure_subscription_site_budget(None)
current_subscription_id = 0
calls = []
def search_site_torrents(*, site, **_kwargs):
"""记录真实发出的站点请求并发布正常完成观察结果。"""
calls.append((current_subscription_id, site["id"]))
report_site_search_outcome(attempted=True, outcome="success")
return [f"torrent-{current_subscription_id}-{site['id']}"]
def process(subscribe, current_searchchain, **_kwargs):
"""让每条到期订阅访问同一组完整目标站点。"""
nonlocal current_subscription_id
current_subscription_id = subscribe.id
for site_id in (11, 12):
current_searchchain._search_site_torrents_with_budget( # pylint: disable=protected-access
site={"id": site_id, "name": f"Site {site_id}"},
keyword=subscribe.name,
mtype=MediaType.MOVIE,
page=0,
)
return subscribe
searchchain.search_site_torrents = search_site_torrents
monkeypatch.setattr(chain, "_process_search_subscription", process)
info_logs = []
monkeypatch.setattr(subscribe_search.logger, "info", info_logs.append)
with patch("app.chain.subscribe.search.SearchChain", return_value=searchchain):
batch_id = chain.search(state="R")
assert calls == [(40, 11), (40, 12), (41, 11), (41, 12)]
assert chain.get_search_batch(batch_id).state == "completed"
assert "访问 2 个站点" in info_logs[-1]
assert "发出 4 次请求" in info_logs[-1]
assert "找到 4 个资源" in info_logs[-1]
def test_fallback_queue_executes_without_match_global_lock(tmp_path, monkeypatch):
"""R/P 兜底搜索在持久队列中执行,不受日常 Match 长锁阻塞。"""
subscribes = [_subscribe(1), _subscribe(2)]
chain = _chain(tmp_path, subscribes)
_make_tasks_ready(monkeypatch)
processed = []
def process(subscribe, _searchchain, *, execution_context):
"""记录每条任务独立的订阅执行上下文。"""
processed.append((subscribe.id, execution_context))
return subscribe
monkeypatch.setattr(
chain,
"_process_search_subscription",
process,
)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
assert [subscribe_id for subscribe_id, _context in processed] == [1, 2]
assert [context.lease.subscription_id for _subscribe_id, context in processed] == [1, 2]
assert len({context.task_id for _subscribe_id, context in processed}) == 2
assert len({id(context) for _subscribe_id, context in processed}) == 2
assert batch.state == "completed"
assert batch.finished_count == 2
assert batch.failed_count == 0
@pytest.mark.parametrize("scheduled_interval", [None, 24])
def test_due_search_restores_healthy_sites_while_ordinary_resume_keeps_scope(
tmp_path, monkeypatch, scheduled_interval,
):
"""到期轮次恢复完整站点和插件源,普通合并仍只补查未完成的站点。"""
subscribe = replace(
_subscribe(91),
last_search=(datetime.now(timezone.utc) - timedelta(hours=25)).isoformat(timespec="seconds"),
)
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
queue = chain.subscription_search_repository
original = queue.enqueue(subscription_ids=(subscribe.id,), source="fallback", priority=10)
first = queue.claim_next(owner="initial")
assert queue.defer_task(
task_id=first.task_id, lease_token=first.lease_token,
available_at=(datetime.now(timezone.utc) + timedelta(hours=6)).isoformat(timespec="seconds"),
pending_site_ids=(9,),
)
searchchain = object.__new__(SearchChain)
searchchain._sync_indexers = lambda _sites: [{"id": 1}, {"id": 9}]
searchchain._torrent_type = lambda *_args: None
searchchain._torrent_keyword = lambda *_args: subscribe.name
searchchain._build_search_pages = lambda _page: [0]
searchchain.search_plugin_torrents = Mock(return_value=[])
scopes = []
searched_sites = []
def collect(_self, **kwargs):
"""记录实际 provider 选择的站点,同时隔离外部请求。"""
searched_sites.extend(site["id"] for site in kwargs["indexer_sites"])
return {}
monkeypatch.setattr(SearchProviderOwner, "_collect_sync_site_results", collect)
monkeypatch.setattr("app.chain.search.provider.ProgressHelper", Mock())
def process(item, current_searchchain, *, execution_context):
"""记录真实消费者为本轮 provider 注入的范围,禁止外部搜索。"""
scopes.append((
execution_context.resuming_sites,
execution_context.task_id,
))
SearchProviderOwner._search_all_sites(current_searchchain, keyword=item.name, sites=[1, 9])
return item
monkeypatch.setattr(chain, "_process_search_subscription", process)
with patch("app.chain.subscribe.search.SearchChain", return_value=searchchain):
chain.search(state="R", scheduled_interval=scheduled_interval)
assert scopes == [(scheduled_interval is None, first.task_id)]
assert searched_sites == ([1, 9] if scheduled_interval else [9])
assert searchchain.search_plugin_torrents.call_count == (1 if scheduled_interval else 0)
assert queue.get_batch(original.batch.batch_id).state == "completed"
def test_fallback_queue_continues_after_one_subscription_failure(tmp_path, monkeypatch):
"""单订阅异常不得中止批次后续任务,聚合终态必须暴露失败。"""
subscribes = [_subscribe(3), _subscribe(4)]
chain = _chain(tmp_path, subscribes)
_make_tasks_ready(monkeypatch)
processed = []
def process(subscribe, _searchchain, **_kwargs):
"""让首条失败并保持第二条正常完成。"""
processed.append(subscribe.id)
if subscribe.id == 3:
raise RuntimeError("provider timeout")
return replace(subscribe)
monkeypatch.setattr(chain, "_process_search_subscription", process)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
assert processed == [3, 4]
assert batch.state == "failed"
assert batch.finished_count == 1
assert batch.failed_count == 1
assert batch.last_error == "provider timeout"
for subscribe_id in (3, 4):
lease = chain._subscription_execution_admission.try_acquire(
subscription_id=subscribe_id,
operation="match",
ttl_seconds=60,
)
assert lease is not None
assert chain._subscription_execution_admission.release(lease) is True
def test_site_search_failure_logs_without_internal_traceback(tmp_path, monkeypatch):
"""可预期的站点聚合失败仍标记任务失败,但不输出误导性的内部堆栈。"""
chain = _chain(tmp_path, [_subscribe(15)])
_make_tasks_ready(monkeypatch)
def process(*_args, **_kwargs):
"""通过正式聚合助手制造站点失败。"""
raise_subscription_site_budget_failures(
("站点 Generic 搜索失败:站点请求或页面解析失败",)
)
monkeypatch.setattr(
chain,
"_process_search_subscription",
process,
)
error_logs = []
monkeypatch.setattr(
"app.chain.subscribe.searchtask.logger.error",
lambda message, **kwargs: error_logs.append((message, kwargs)),
)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
assert batch.state == "failed"
assert batch.failed_count == 1
assert error_logs == [
(
"订阅《治理电影 15》搜索失败:站点 Generic 搜索失败:站点请求或页面解析失败",
{"exc_info": False},
)
]
def test_inline_site_search_failure_logs_without_internal_traceback(tmp_path, monkeypatch):
"""兼容内联搜索遇到站点聚合失败时也不得输出内部堆栈。"""
chain = _chain(tmp_path, [_subscribe(16)])
del chain.subscription_search_repository
monkeypatch.setattr(chain, "_wait_before_scheduled_search", lambda *_args: None)
def process(*_args, **_kwargs):
"""通过正式聚合助手制造内联站点失败。"""
raise_subscription_site_budget_failures(
("站点 Generic 搜索失败:站点请求或页面解析失败",)
)
monkeypatch.setattr(chain, "_process_search_subscription", process)
error_logs = []
monkeypatch.setattr(
subscribe_search.logger,
"error",
lambda message, **kwargs: error_logs.append((message, kwargs)),
)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
chain.search(state="R")
assert error_logs == [
(
"订阅 治理电影 16 搜索失败:站点 Generic 搜索失败:站点请求或页面解析失败",
{"exc_info": False},
)
]
def test_site_budget_conflict_requeues_task_without_batch_failure(tmp_path, monkeypatch):
"""站点预算冲突应自动排队重试,不能把订阅批次置为失败。"""
subscribe = _subscribe(5)
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
retry_at = (datetime.now(timezone.utc) + timedelta(minutes=5)).isoformat(timespec="seconds")
monkeypatch.setattr(
chain,
"_process_search_subscription",
Mock(side_effect=SubscriptionSearchDeferred(retry_at=retry_at, site_ids=(31,))),
)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
assert batch.state == "queued"
assert batch.finished_count == 0
assert batch.failed_count == 0
assert batch.last_error is None
with chain.subscription_search_repository._session_factory() as session:
task = session.query(SubscriptionSearchTask).filter_by(
subscription_id=subscribe.id,
).one()
assert task.state == "queued"
assert task.phase == "waiting_site_budget"
assert task.available_at == retry_at
assert task.last_error == "等待站点"
assert task.pending_site_ids == [31]
assert chain.subscription_search_repository.claim_next(owner="worker-after-retry") is None
def test_search_logs_one_readable_start_and_finish_summary(tmp_path, monkeypatch):
"""Search INFO 只保留用户能直接读懂的开始和结束摘要。"""
subscribes = [_subscribe(50), _subscribe(51)]
chain = _chain(tmp_path, subscribes)
_make_tasks_ready(monkeypatch)
def process(subscribe, _searchchain, **_kwargs):
"""让一条任务失败并保持下一条正常收口。"""
if subscribe.id == 50:
raise RuntimeError("provider timeout")
return subscribe
monkeypatch.setattr(chain, "_process_search_subscription", process)
info_logs = []
monkeypatch.setattr(subscribe_search.logger, "info", info_logs.append)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
assert batch_id
assert len(info_logs) == 2
assert info_logs[0] == "开始订阅定时检查,共 2 个订阅。"
assert info_logs[1].startswith("订阅定时检查结束:部分订阅没有完成。")
assert "本次处理 2/2 个" in info_logs[1]
assert "完成 1 个" in info_logs[1]
assert "失败 1 个" in info_logs[1]
assert "发出 0 次请求" in info_logs[1]
assert "用时 " in info_logs[1]
assert "operation=" not in "\n".join(info_logs)
def test_search_logs_subscription_admission_release_failure(tmp_path, monkeypatch):
"""Search 无法释放订阅 owner 时必须即时告警并写入轮次摘要。"""
subscribe = _subscribe(52)
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
monkeypatch.setattr(
chain,
"_process_search_subscription",
lambda item, _searchchain, **_kwargs: item,
)
monkeypatch.setattr(chain._subscription_execution_admission, "release", lambda _lease: False)
info_logs = []
error_logs = []
monkeypatch.setattr(subscribe_search.logger, "info", info_logs.append)
monkeypatch.setattr(
subscribe_search.logger,
"error",
lambda message, **_kwargs: error_logs.append(message),
)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
chain.search(state="R")
assert any("订阅《治理电影 52》的搜索状态没有正常恢复" in item for item in error_logs)
assert "另有 1 个搜索状态没有正常恢复" in info_logs[-1]
def test_queued_search_logs_failed_finish_summary_when_callback_raises(tmp_path, monkeypatch):
"""排队搜索开始后的外围异常仍须输出失败结束摘要。"""
chain = _chain(tmp_path, [_subscribe(53)])
_make_tasks_ready(monkeypatch)
info_logs = []
monkeypatch.setattr(subscribe_search.logger, "info", info_logs.append)
with pytest.raises(RuntimeError, match="callback failed"):
chain.search(
state="R",
progress_callback=Mock(side_effect=RuntimeError("callback failed")),
)
assert len(info_logs) == 2
assert info_logs[-1].startswith("订阅定时检查结束:部分订阅没有完成。")
def test_resume_search_logs_failed_finish_summary_when_drain_raises(tmp_path, monkeypatch):
"""恢复消费开始后的外围异常仍须输出失败结束摘要。"""
chain = _chain(tmp_path, [_subscribe(54)])
info_logs = []
monkeypatch.setattr(subscribe_search.logger, "info", info_logs.append)
monkeypatch.setattr(
chain,
"_drain_search_queue",
Mock(side_effect=RuntimeError("claim failed")),
)
with pytest.raises(RuntimeError, match="claim failed"):
chain.resume_search_queue()
assert len(info_logs) == 1
assert info_logs[-1].startswith("等待中的订阅搜索结束:部分订阅没有完成。")
def test_swallowed_indexer_failure_marks_task_and_batch_failed_but_continues(tmp_path, monkeypatch):
"""索引器吞错后仍须失败收口当前任务,并继续处理后续订阅。"""
subscribes = [_subscribe(13), _subscribe(14)]
chain = _chain(tmp_path, subscribes)
_make_tasks_ready(monkeypatch)
searchchain = object.__new__(SearchChain)
attempts = 0
processed = []
def execute_search(_site, _request):
"""首条站点请求模拟被 IndexerModule 吞掉的 HTTP 429。"""
nonlocal attempts
attempts += 1
if attempts == 1:
raise RuntimeError("HTTP 429")
return False, []
monkeypatch.setattr(
IndexerModule,
"_IndexerModule__search_check",
staticmethod(lambda _site, _keyword=None: True),
)
monkeypatch.setattr(
IndexerModule,
"_IndexerModule__execute_search",
staticmethod(execute_search),
)
monkeypatch.setattr(
IndexerModule,
"_IndexerModule__indexer_statistic",
staticmethod(lambda **_kwargs: None),
)
monkeypatch.setattr(
IndexerModule,
"_IndexerModule__parse_result",
staticmethod(lambda **_kwargs: []),
)
searchchain.search_site_torrents = object.__new__(IndexerModule).search_torrents
def process(subscribe, current_searchchain, **_kwargs):
"""让每条任务经过同一预算包装,并把观察到的站点失败抛给队列。"""
processed.append(subscribe.id)
current_searchchain._search_site_torrents_with_budget( # pylint: disable=protected-access
site={
"id": 31 if subscribe.id == 13 else 32,
"name": "Flaky" if subscribe.id == 13 else "Healthy",
},
keyword=subscribe.name,
mtype=MediaType.MOVIE,
page=0,
)
failures = current_searchchain.consume_subscription_site_budget_failures()
if failures:
raise RuntimeError(";".join(failures))
return subscribe
monkeypatch.setattr(chain, "_process_search_subscription", process)
info_logs = []
monkeypatch.setattr(subscribe_search.logger, "info", info_logs.append)
with patch("app.chain.subscribe.search.SearchChain", return_value=searchchain):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
assert processed == [13, 14]
assert batch.state == "failed"
assert batch.finished_count == 1
assert batch.failed_count == 1
assert "Flaky" in batch.last_error
assert "HTTP 429" in batch.last_error
assert "失败 1 个" in info_logs[-1]
assert "访问 2 个站点" in info_logs[-1]
assert "发出 2 次请求" in info_logs[-1]
def test_same_subscription_conflict_is_skipped_without_waiting(tmp_path, monkeypatch):
"""Match 已持有同一订阅时,Search 本轮完成为跳过且不进入业务处理。"""
subscribe = _subscribe(6)
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
process = Mock(side_effect=AssertionError("冲突订阅不应进入 Search"))
monkeypatch.setattr(chain, "_process_search_subscription", process)
match_lease = chain._subscription_execution_admission.try_acquire(
subscription_id=subscribe.id,
operation="match",
ttl_seconds=60,
)
assert match_lease is not None
info_logs = []
monkeypatch.setattr(subscribe_search.logger, "info", info_logs.append)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
process.assert_not_called()
assert batch.state == "skipped"
assert batch.finished_count == 0
assert batch.skipped_count == 1
assert batch.last_error == "这个订阅正在处理,本次自动检查无需重复执行"
assert "这次未搜索 1 个" in info_logs[-1]
assert chain._subscription_execution_admission.release(match_lease) is True
def test_manual_search_waits_for_same_subscription_then_continues(tmp_path, monkeypatch):
"""手动搜索遇到同一订阅正在处理时应稍后自动继续,而不是结束为跳过。"""
subscribe = _subscribe(61)
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
process = Mock(return_value=subscribe)
monkeypatch.setattr(chain, "_process_search_subscription", process)
match_lease = chain._subscription_execution_admission.try_acquire(
subscription_id=subscribe.id,
operation="match",
ttl_seconds=60,
)
assert match_lease is not None
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(sid=subscribe.id, state=None, manual=True)
batch = chain.get_search_batch(batch_id)
assert batch.state == "queued"
process.assert_not_called()
with chain.subscription_search_repository._session_factory() as session:
task = session.query(SubscriptionSearchTask).filter_by(
subscription_id=subscribe.id,
).one()
assert task.phase == "waiting_subscription"
assert task.last_error == "这个订阅正在处理,结束后会自动继续搜索"
task.available_at = "1970-01-01T00:00:00+00:00"
session.commit()
assert chain._subscription_execution_admission.release(match_lease) is True
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
chain.resume_search_queue(limit=1)
process.assert_called_once()
assert chain.get_search_batch(batch_id).state == "completed"
def test_recent_new_subscription_is_scheduled_instead_of_skipped(tmp_path, monkeypatch):
"""新订阅的一分钟编辑窗口应保留任务并在到时后自动继续。"""
subscribe = replace(
_subscribe(62),
state="N",
date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
)
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
process = Mock(side_effect=AssertionError("编辑等待期内不应开始搜索"))
monkeypatch.setattr(chain, "_process_search_subscription", process)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="N")
batch = chain.get_search_batch(batch_id)
assert batch.state == "queued"
assert batch.skipped_count == 0
with chain.subscription_search_repository._session_factory() as session:
task = session.query(SubscriptionSearchTask).filter_by(
subscription_id=subscribe.id,
).one()
assert task.phase == "scheduled"
assert task.last_error == "订阅刚刚创建,保存好设置后会自动开始搜索"
assert task.available_at > datetime.now(timezone.utc).isoformat(timespec="seconds")
process.assert_not_called()
def test_new_subscription_post_commit_creates_scheduled_search(tmp_path):
"""订阅保存后应立即写入自动搜索计划,无需等待五分钟扫描。"""
subscribe = replace(
_subscribe(64),
state="N",
date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
)
chain = _chain(tmp_path, [subscribe])
batch_id = chain._SubscribeChain__queue_new_subscription_search(subscribe.id)
assert batch_id
assert chain.get_search_batch(batch_id).state == "queued"
with chain.subscription_search_repository._session_factory() as session:
task = session.query(SubscriptionSearchTask).filter_by(
subscription_id=subscribe.id,
).one()
assert task.source == "new"
assert task.phase == "scheduled"
assert task.available_at > datetime.now(timezone.utc).isoformat(timespec="seconds")
def test_manual_search_bypasses_new_subscription_edit_wait(tmp_path, monkeypatch):
"""用户主动点击搜索时不受新订阅编辑等待时间限制。"""
subscribe = replace(
_subscribe(63),
date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
)
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
process = Mock(return_value=subscribe)
monkeypatch.setattr(chain, "_process_search_subscription", process)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(sid=subscribe.id, state=None, manual=True)
process.assert_called_once()
assert chain.get_search_batch(batch_id).state == "completed"
def test_paused_subscription_is_skipped_after_admission_refresh(tmp_path, monkeypatch):
"""准入后重新读取到暂停订阅时不得开始搜索或伪造完成。"""
subscribe = _subscribe(9)
paused = replace(subscribe, state="S")
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
chain.subscription_repository.get = Mock(side_effect=(subscribe, paused))
process = Mock(side_effect=AssertionError("暂停订阅不应进入 Search"))
monkeypatch.setattr(chain, "_process_search_subscription", process)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
process.assert_not_called()
assert batch.state == "skipped"
assert batch.finished_count == 0
assert batch.skipped_count == 1
assert batch.last_error == "订阅已暂停,这次没有搜索"
def test_cleanup_failures_cannot_leak_subscription_admission(tmp_path, monkeypatch):
"""站点预算和状态清理都失败时仍必须释放当前订阅 owner。"""
subscribe = replace(_subscribe(7), state="N")
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
monkeypatch.setattr(
chain,
"_process_search_subscription",
lambda item, _searchchain, **_kwargs: item,
)
monkeypatch.setattr(
chain,
"_SubscribeChain__apply_subscribe_update",
Mock(side_effect=RuntimeError("state cleanup failed")),
)
searchchain = Mock()
def configure_site_budget(budget):
"""仅让释放站点预算的清理步骤失败。"""
if budget is None:
raise RuntimeError("budget cleanup failed")
searchchain.configure_subscription_site_budget.side_effect = configure_site_budget
with patch("app.chain.subscribe.search.SearchChain", return_value=searchchain):
batch_id = chain.search(state="N")
assert chain.get_search_batch(batch_id).state == "completed"
replacement = chain._subscription_execution_admission.try_acquire(
subscription_id=subscribe.id,
operation="match",
ttl_seconds=60,
)
assert replacement is not None
assert chain._subscription_execution_admission.release(replacement) is True
def test_search_state_reset_stays_inside_subscription_admission(tmp_path, monkeypatch):
"""N 到 R 的本地状态写回完成前不能让 Match 接管同一订阅。"""
subscribe = replace(_subscribe(8), state="N")
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
monkeypatch.setattr(
chain,
"_process_search_subscription",
lambda item, _searchchain, **_kwargs: item,
)
competing_leases = []
def apply_update(*_args, **_kwargs):
"""在状态写回时探测同一订阅仍由 Search 持有。"""
competing_leases.append(
chain._subscription_execution_admission.try_acquire(
subscription_id=subscribe.id,
operation="match",
ttl_seconds=60,
)
)
monkeypatch.setattr(chain, "_SubscribeChain__apply_subscribe_update", apply_update)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
chain.search(state="N")
assert competing_leases == [None]
replacement = chain._subscription_execution_admission.try_acquire(
subscription_id=subscribe.id,
operation="match",
ttl_seconds=60,
)
assert replacement is not None
assert chain._subscription_execution_admission.release(replacement) is True
def test_late_cancel_completes_when_download_side_effect_already_started(tmp_path, monkeypatch):
"""取消晚于下载器副作用边界时按真实结果完成,不能伪装成未执行取消。"""
subscribe = _subscribe(5)
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
queue = chain.subscription_search_repository
cancel_checks = iter((False, True))
monkeypatch.setattr(queue, "is_cancel_requested", lambda _task_id: next(cancel_checks))
def process(item, _searchchain, *, execution_context):
"""模拟当前任务复用或完成下载后才收到取消。"""
execution_context.mark_download_started()
return item
monkeypatch.setattr(chain, "_process_search_subscription", process)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
assert batch.state == "completed"
assert batch.finished_count == 1
assert batch.cancelled_count == 0
def test_system_stop_requeues_task_after_search_returns(tmp_path, monkeypatch):
"""系统停机应阻止后续副作用,并把未完成任务退回可恢复队列。"""
subscribe = _subscribe(10)
chain = _chain(tmp_path, [subscribe])
stop_state = SimpleNamespace(is_system_stopped=False)
chain.stop_state = stop_state
_make_tasks_ready(monkeypatch)
def process(item, _searchchain, *, execution_context):
"""模拟站点搜索返回部分候选时进程进入停止阶段。"""
stop_state.is_system_stopped = True
assert execution_context.should_stop() is True
return item
monkeypatch.setattr(chain, "_process_search_subscription", process)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
assert batch.state == "queued"
assert batch.finished_count == 0
assert batch.failed_count == 0
assert batch.cancelled_count == 0
assert batch.skipped_count == 0
stop_state.is_system_stopped = False
recovered = chain.subscription_search_repository.claim_next(owner="worker-after-restart")
assert recovered is not None
assert recovered.subscription_id == subscribe.id
assert recovered.attempt_count == 2
def test_system_stop_completes_when_download_side_effect_already_started(tmp_path, monkeypatch):
"""停机晚于下载器副作用边界时必须终结任务,避免重启后重复提交。"""
subscribe = _subscribe(11)
chain = _chain(tmp_path, [subscribe])
stop_state = SimpleNamespace(is_system_stopped=False)
chain.stop_state = stop_state
_make_tasks_ready(monkeypatch)
def process(item, _searchchain, *, execution_context):
"""模拟下载器已接收任务后进程进入停止阶段。"""
execution_context.mark_download_started()
stop_state.is_system_stopped = True
return item
monkeypatch.setattr(chain, "_process_search_subscription", process)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
assert batch.state == "completed"
assert batch.finished_count == 1
assert batch.failed_count == 0
assert batch.cancelled_count == 0
assert batch.skipped_count == 0
assert chain.subscription_search_repository.claim_next(owner="worker-after-restart") is None
def test_ttl_expiry_after_normal_return_marks_task_and_batch_failed(tmp_path, monkeypatch):
"""正常返回也必须检查执行 TTL,未提交下载时按失败收口。"""
subscribe = _subscribe(15)
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
monkeypatch.setattr(
chain._subscription_execution_admission,
"is_expired",
lambda _lease: True,
)
monkeypatch.setattr(
chain,
"_process_search_subscription",
lambda item, _searchchain, **_kwargs: item,
)
info_logs = []
monkeypatch.setattr(subscribe_search.logger, "info", info_logs.append)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
assert batch.state == "failed"
assert batch.finished_count == 0
assert batch.failed_count == 1
assert batch.cancelled_count == 0
assert batch.last_error == "这次搜索用时过长,已停止,可稍后重试"
assert "失败 1 个" in info_logs[-1]
def test_ttl_expiry_after_download_started_completes_with_actual_result(tmp_path, monkeypatch):
"""TTL 晚于下载器副作用边界时按实际结果完成,避免下轮重复提交。"""
subscribe = _subscribe(16)
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
monkeypatch.setattr(
chain._subscription_execution_admission,
"is_expired",
lambda _lease: True,
)
def process(item, _searchchain, *, execution_context):
"""模拟下载器已接收任务后搜索链正常返回。"""
execution_context.mark_download_started()
return item
monkeypatch.setattr(chain, "_process_search_subscription", process)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
assert batch.state == "completed"
assert batch.finished_count == 1
assert batch.failed_count == 0
assert batch.cancelled_count == 0
def test_site_budget_ttl_expiry_marks_task_and_batch_failed(tmp_path, monkeypatch):
"""站点预算观察到执行 TTL 到期时必须失败收口,不能伪装成用户取消。"""
subscribe = _subscribe(12)
chain = _chain(tmp_path, [subscribe])
_make_tasks_ready(monkeypatch)
monkeypatch.setattr(
chain._subscription_execution_admission,
"is_expired",
lambda _lease: True,
)
def process(_item, _searchchain, *, execution_context):
"""模拟站点预算将协作超时传播为搜索取消异常。"""
assert execution_context.should_stop() is True
raise SubscriptionSearchCancelled("订阅搜索已取消")
monkeypatch.setattr(chain, "_process_search_subscription", process)
with patch("app.chain.subscribe.search.SearchChain", return_value=Mock()):
batch_id = chain.search(state="R")
batch = chain.get_search_batch(batch_id)
assert batch.state == "failed"
assert batch.finished_count == 0
assert batch.failed_count == 1
assert batch.cancelled_count == 0
assert batch.last_error == "这次搜索用时过长,已停止,可稍后重试"