From cc00ce6b79699414a6bff5b4677a2a9273510ddf Mon Sep 17 00:00:00 2001 From: LIN student <86354789+MiCat-S@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:14:47 +0800 Subject: [PATCH] fix(download): avoid blacklisting one-shot episode probes --- app/chain/download/batch.py | 10 +++++-- app/chain/download/failure.py | 6 ++-- app/chain/download/submission.py | 8 ++++-- tests/test_download_batch_phases.py | 1 + tests/test_download_resource_cache.py | 3 +- tests/test_torrent_download_retry.py | 41 +++++++++++++++++++++++++++ 6 files changed, 61 insertions(+), 8 deletions(-) diff --git a/app/chain/download/batch.py b/app/chain/download/batch.py index 9676d9ad6..5c0903955 100644 --- a/app/chain/download/batch.py +++ b/app/chain/download/batch.py @@ -393,7 +393,11 @@ class _BatchDownloadRun: self, context: Context, *, partial: bool = False, ) -> Optional[Tuple[bytes, List[int]]]: """ - 读取真实文件集数;保留站点失败原因用于冷却,磁力链只跳过当前阶段。 + 读取真实文件集数;保留站点失败原因,单次无效内容使用瞬时冷却,磁力链只跳过当前阶段。 + + :param context: 包含种子与识别信息的候选 + :param partial: 是否处于拆包阶段,用于选择日志级别和说明 + :return: 种子内容和识别出的集数;无法读取或核对文件时返回 None """ assert context.torrent_info is not None torrent = context.torrent_info @@ -407,9 +411,11 @@ class _BatchDownloadRun: if not content: log_failure = logger.info if partial else logger.warn log_failure(f"{torrent.title} 种子下载失败!") + error_msg = errors[-1] if errors else "下载种子内容为空" self.owner._record_download_failure( - context=context, error_msg=errors[-1] if errors else "下载种子内容为空", + context=context, error_msg=error_msg, downloader=self.options["downloader"], source=self.options["source"], + ttl_seconds=self.owner._download_failure_ttl(error_msg, episode_probe=True), ) self._remember_failure(context) governance = self.options["governance"] diff --git a/app/chain/download/failure.py b/app/chain/download/failure.py index 792267c6c..e1965024d 100644 --- a/app/chain/download/failure.py +++ b/app/chain/download/failure.py @@ -236,12 +236,13 @@ class DownloadFailureOwner(_DownloadOwnerBase): return hashlib.sha256(raw_text.encode("utf-8")).hexdigest() @staticmethod - def _download_failure_ttl(error_msg: Optional[str]) -> int: + def _download_failure_ttl(error_msg: Optional[str], *, episode_probe: bool = False) -> int: """ 限流按站点窗口冷却;已有任务的拒绝按原因区分资源级与瞬时冷却;换票、临时地址和泛化空内容 失败使用瞬时冷却。 :param error_msg: 准备或下载器提交阶段保留的具体失败原因 + :param episode_probe: 是否为仅核对集数的读取;一次无效响应只按瞬时失败处理 :return: 冷却秒数;换票诊断中的 404 等关键字不能升级为资源失效 """ rate_limit_ttl = torrent_rules.rate_limit_cooldown(error_msg) @@ -255,7 +256,8 @@ class DownloadFailureOwner(_DownloadOwnerBase): return DOWNLOAD_FAILURE_RESOURCE_TTL_SECONDS return DOWNLOAD_FAILURE_TRANSIENT_TTL_SECONDS error_text = str(error_msg or "").lower() - if error_text.startswith(("换票失败:", "临时下载地址失效:")): + if (error_text.startswith(("换票失败:", "临时下载地址失效:")) + or (episode_probe and error_text.startswith("种子数据有误"))): return DOWNLOAD_FAILURE_TRANSIENT_TTL_SECONDS if any(keyword in error_text for keyword in DOWNLOAD_FAILURE_RESOURCE_ERROR_KEYWORDS): return DOWNLOAD_FAILURE_RESOURCE_TTL_SECONDS diff --git a/app/chain/download/submission.py b/app/chain/download/submission.py index e591f5d59..0aa13a241 100644 --- a/app/chain/download/submission.py +++ b/app/chain/download/submission.py @@ -761,8 +761,12 @@ class _DownloadResourceOwner(_DownloadOwnerBase): 下载种子文件,如果是磁力链,会返回磁力链接本身 换票种子按站点资源和原始换票凭据复用本地内容,命中后不再请求临时链接。 + :param torrent: 包含站点身份和种子地址的候选 + :param channel: 下载失败通知的渠道 + :param source: 下载请求来源,指定通知渠道时用于路由通知 + :param userid: 接收下载失败通知的用户 :param on_failure: 将本次具体失败原因交还准备流程,保持返回元组与并发调用隔离 - :param retry: 是否对普通 GET 瞬时失败退避重试;仅核对集数的读取应关闭 + :param retry: 是否对普通 GET 失败退避重试并缓存无效地址;仅核对集数时关闭 :param notify: 失败时是否推送下载失败告警;仅核对集数的读取应关闭 :return: 种子内容,种子目录名,种子文件清单 """ @@ -790,7 +794,7 @@ class _DownloadResourceOwner(_DownloadOwnerBase): if not content: if on_failure: on_failure(error_msg or "下载种子内容为空") - if not enclosure.startswith("[") and error_msg and "种子数据有误" in error_msg: + if retry and not enclosure.startswith("[") and "种子数据有误" in (error_msg or ""): helper.add_invalid(enclosure) logger.error(f"下载种子文件失败:{torrent.title},{error_msg}") if notify: diff --git a/tests/test_download_batch_phases.py b/tests/test_download_batch_phases.py index 09a56f3ee..2e1acd699 100644 --- a/tests/test_download_batch_phases.py +++ b/tests/test_download_batch_phases.py @@ -229,6 +229,7 @@ def test_empty_torrent_is_recorded_once_and_not_retried_in_later_phases(batch): batch.chain.download_torrent.assert_called_once() batch.chain._record_download_failure.assert_called_once_with( context=whole, error_msg="下载种子内容为空", downloader="test", source="Subscribe|42", + ttl_seconds=3600, ) diff --git a/tests/test_download_resource_cache.py b/tests/test_download_resource_cache.py index 0632ee890..277c2acb9 100644 --- a/tests/test_download_resource_cache.py +++ b/tests/test_download_resource_cache.py @@ -15,7 +15,6 @@ import app.chain.download.submission as submission from app.adapters.cache.backends import FileBackend from app.chain.download import DownloadChain from app.chain.download.batch import _BatchDownloadRun -from app.chain.download.failure import DownloadFailureOwner from app.domain.context import Context, MediaInfo, TorrentInfo from app.domain.metainfo import MetaInfo from app.schemas.types import MediaType @@ -161,7 +160,7 @@ def test_batch_keeps_daily_limit_reason_and_cooldown(boundary, partial): assert recorded["error_msg"] == f"站点限流:{reason}" assert recorded["context"] is context assert recorded["source"] == "Subscribe|48" - assert DownloadFailureOwner._download_failure_ttl(recorded["error_msg"]) == 86400 + assert recorded["ttl_seconds"] == 86400 boundary.port.request.assert_called_once() key = boundary.chain._indirect_torrent_cache_key(context.torrent_info) assert boundary.cache.get(key, region="torrents") is None diff --git a/tests/test_torrent_download_retry.py b/tests/test_torrent_download_retry.py index f0553ffe7..d6310a9a0 100644 --- a/tests/test_torrent_download_retry.py +++ b/tests/test_torrent_download_retry.py @@ -17,6 +17,7 @@ import app.chain.download.failure as failure_owner import app.chain.download.submission as submission from app.application.download.failures import DownloadFailureWrite from app.chain.download import DownloadChain +from app.chain.download.batch import _BatchDownloadRun from app.chain.download.failure import ( DOWNLOAD_FAILURE_DUPLICATE_MESSAGE, DOWNLOAD_FAILURE_DUPLICATE_TTL_SECONDS, @@ -504,6 +505,46 @@ def test_invalid_torrent_data_has_resource_cooldown(error): assert DownloadFailureOwner._download_failure_ttl(error) == 86400 +@pytest.mark.parametrize("partial", [False, True]) +def test_episode_probe_invalid_content_allows_recovered_download(boundary, monkeypatch, partial): + """ + 核对集数遇到站点维护页时本批去重,记录短冷却,站点恢复后可立即正式下载。 + + :param boundary: 隔离种子请求、缓存和等待的边界夹具 + :param monkeypatch: 恢复共享种子助手替身的测试夹具 + :param partial: 是否走拆包核对集数路径 + """ + helper, port, _, sleep = boundary + monkeypatch.setattr(submission, "TorrentHelper", Mock(return_value=helper)) + port.request.side_effect = [_response(content=b"Site maintenance"), _response()] + chain = object.__new__(DownloadChain) + chain.post_message = Mock() + chain.download_failure_repository = Mock() + torrent = TorrentInfo(site=1, site_name="test", title="Series S01", enclosure=URL, site_cookie="session=test") + context = Context( + torrent_info=torrent, media_info=MediaInfo(title="Series", type=MediaType.TV), + meta_info=MetaInfo("Series S01"), + ) + options = dict(save_path=None, channel=None, source="Subscribe|39", userid=None, + username=None, downloader=None, custom_words=None, governance=None) + batch = _BatchDownloadRun(chain, [], {}, options, None) + + assert batch._read_torrent(context, partial=partial) is None + assert batch._in_failure_cooldown(context) + port.request.assert_called_once() + sleep.assert_not_called() + chain.post_message.assert_not_called() + + assert chain.download_torrent(torrent) == (CONTENT, "", ["Series.mkv"]) + assert port.request.call_count == 2 + helper.add_invalid.assert_not_called() + chain.download_failure_repository.record_failure.assert_called_once() + failure = chain.download_failure_repository.record_failure.call_args.args[0] + assert failure.error_message == "种子数据有误,请确认链接是否正确" + assert (datetime.fromisoformat(failure.next_retry_at) + - datetime.fromisoformat(failure.failed_at)).total_seconds() == 3600 + + def test_invalid_content_preparation_preserves_persisted_resource_cooldown(boundary, monkeypatch): """ 单任务准备保留无效种子原因,持久化冷却不能再被统一空内容错误覆盖。