diff --git a/app/application/rules.py b/app/application/rules.py index 23b93656e..d4f259f01 100644 --- a/app/application/rules.py +++ b/app/application/rules.py @@ -4,6 +4,7 @@ """ import copy +import re import threading from collections.abc import Awaitable, Callable, Iterable, Mapping from dataclasses import dataclass @@ -14,6 +15,7 @@ from pyparsing import ( Combine, Forward, Literal, + ParseBaseException, ParseResults, Word, alphanums, @@ -40,7 +42,7 @@ from app.schemas.rule import CustomRule, FilterRuleGroup from app.schemas.types import SystemConfigKey if TYPE_CHECKING: - from app.schemas.search import SearchDiagnosticRuleGroup + from app.schemas.search import SearchDiagnosticRuleGroup, SearchDiagnosticWarning _RULE_GROUP_LIST_CONFIG_KEYS = ( SystemConfigKey.SearchFilterRuleGroups, @@ -102,6 +104,29 @@ class RuleGroupMutationConflictError(RuntimeError): """ +class RuleStringValidationError(ValueError): + """ + 不包含解析器输入摘要的规则配置定位信息。 + + :ivar code: 区分无效 ID、悬空引用和表达式语法错误的稳定代码 + :ivar rule_ids: 完整的相关 ID,保留旧 ID 中的空白,语法错误时为空 + """ + + def __init__(self, code: str, rule_ids: Iterable[str] = ()) -> None: + """ + 构造可写入日志的中文说明,完整 ID 不依赖解析器截断的异常文本。 + """ + self.code = code + self.rule_ids = tuple(dict.fromkeys(rule_ids)) + labels = ", ".join(repr(rule_id) for rule_id in self.rule_ids) + messages = { + "rule_id_invalid": f"引用了无效的规则 ID:{labels};ID 仅支持英文字母和数字,且至少包含一个字母", + "rule_id_missing": f"引用了不存在的规则 ID:{labels}", + "rule_syntax_invalid": "规则表达式语法错误,请检查运算符、括号和优先级层级", + } + super().__init__(messages[code]) + + @dataclass(frozen=True, slots=True) class RuleGroupSubscriptionChange: """ @@ -587,6 +612,29 @@ class RuleHelper: )) return result + def diagnose_rule_groups( + self, *, media: Optional[MediaInfo], group_names: list[str], + ) -> list["SearchDiagnosticWarning"]: + """ + 检查本次所选且适用的规则组配置,不将配置告警推测为资源拒绝。 + + :param media: 本次过滤使用的媒体上下文,标题搜索传 None + :param group_names: 本次选择的规则组名称;空列表不检查其它组 + :return: 完整 ID 与规则组定位组成的安全告警,不含原始解析异常 + """ + if not group_names: + return [] + from app.schemas.search import SearchDiagnosticWarning + + available_ids = [*BUILTIN_RULE_SET, *(rule.id for rule in self.get_custom_rules() if rule.id is not None)] + warnings = [] + for group in self.get_rule_group_by_media(media=media, group_names=group_names): + issue = describe_rule_string_error(group.rule_string or "", available_ids) + if issue is not None: + warnings.append(SearchDiagnosticWarning(code=issue.code, rule_group=group.name, + rule_ids=list(issue.rule_ids))) + return warnings + @staticmethod def get_custom_rules() -> List[CustomRule]: """ @@ -850,6 +898,48 @@ class _RustParseResults(list[Any]): return self.as_list() +def describe_rule_string_error( + rule_string: str, available_rule_ids: Iterable[str], +) -> Optional[RuleStringValidationError]: + """ + 按完整操作数诊断规则表达式,避免将含空格的旧 ID 拆成多个错误片段。 + + 本检查只诊断配置;运行时仍按实际需要延迟解析层级,不能因未执行的坏层级 + 改变高优先级命中或后续规则组的短路语义。 + + :param rule_string: 需要检查的完整规则表达式 + :param available_rule_ids: 当前内置和自定义 ID,旧 ID 保留原始空白 + :return: 首类配置错误;全部语法和引用有效时返回 None + """ + available = set(available_rule_ids) + aliases: dict[str, list[str]] = {} + for rule_id in sorted(available): + aliases.setdefault(rule_id.strip(), []).append(rule_id) + operands = [span.strip() for span in re.findall(r"[^!&|()>]+", rule_string) if span.strip()] + invalid_ids = [] + missing_ids = [] + for operand in operands: + originals = [operand] if operand in available else aliases.get(operand, [operand]) + invalid = [rule_id for rule_id in originals if not re.fullmatch(r"[A-Za-z0-9]*[A-Za-z][A-Za-z0-9]*", rule_id)] + if invalid: + invalid_ids.extend(invalid) + elif operand not in available: + missing_ids.append(operand) + if invalid_ids: + return RuleStringValidationError("rule_id_invalid", invalid_ids) + if missing_ids: + return RuleStringValidationError("rule_id_missing", missing_ids) + parser = RuleParser() + for level in rule_string.split(">"): + if not level.strip(): + return RuleStringValidationError("rule_syntax_invalid") + try: + parser.parse(level.strip()) + except ParseBaseException: + return RuleStringValidationError("rule_syntax_invalid") + return None + + if __name__ == '__main__': expression_str = """ SPECSUB & CNVOI & 4K & !BLU & !REMUX & !WEBDL & 60FPS & !DOLBY & !SDR & !3D > CNSUB & CNVOI & 4K & !BLU & !REMUX & !WEBDL & 60FPS & !DOLBY & !SDR & !3D > SPECSUB & 4K & !BLU & !REMUX & !WEBDL & 60FPS & !DOLBY & !SDR & !3D > CNSUB & 4K & !BLU & !REMUX & !WEBDL & 60FPS & !DOLBY & !SDR & !3D > SPECSUB & CNVOI & 4K & !BLU & !REMUX & !WEBDL & !DOLBY & HDR & !3D > CNSUB & CNVOI & 4K & !BLU & !REMUX & !WEBDL & !DOLBY & HDR & !3D > SPECSUB & CNVOI & 4K & !BLU & !REMUX & !WEBDL & !DOLBY & !3D > CNSUB & CNVOI & 4K & !BLU & !REMUX & !WEBDL & !DOLBY & !3D > SPECSUB & 4K & !BLU & !REMUX & !WEBDL & !DOLBY & HDR & !3D > CNSUB & 4K & !BLU & !REMUX & !WEBDL & !DOLBY & HDR & !3D > SPECSUB & 4K & !BLU & !REMUX & !WEBDL & !DOLBY & !3D > CNSUB & 4K & !BLU & !REMUX & !WEBDL & !DOLBY & !3D > SPECSUB & CNVOI & 4K & WEBDL & 60FPS & !DOLBY & !SDR & !3D > CNSUB & CNVOI & 4K & WEBDL & 60FPS & !DOLBY & !SDR & !3D > SPECSUB & 4K & WEBDL & 60FPS & !DOLBY & !SDR & !3D > CNSUB & 4K & WEBDL & 60FPS & !DOLBY & !SDR & !3D > SPECSUB & CNVOI & 4K & WEBDL & !DOLBY & HDR & !3D > CNSUB & CNVOI & 4K & WEBDL & !DOLBY & HDR & !3D > SPECSUB & CNVOI & 4K & WEBDL & !DOLBY & !3D > CNSUB & CNVOI & 4K & WEBDL & !DOLBY & !3D > SPECSUB & 4K & WEBDL & !DOLBY & HDR & !3D > CNSUB & 4K & WEBDL & !DOLBY & HDR & !3D > SPECSUB & 4K & WEBDL & !DOLBY & !3D > CNSUB & 4K & WEBDL & !DOLBY & !3D > SPECSUB & CNVOI & 4K & !BLU & !WEBDL & !DOLBY & HDR & !3D > CNSUB & CNVOI & 4K & !BLU & !WEBDL & !DOLBY & HDR & !3D > SPECSUB & CNVOI & 4K & !BLU & !WEBDL & !DOLBY & !3D > CNSUB & CNVOI & 4K & !BLU & !WEBDL & !DOLBY & !3D > SPECSUB & 4K & !BLU & !WEBDL & !DOLBY & HDR & !3D > CNSUB & 4K & !BLU & !WEBDL & !DOLBY & HDR & !3D > SPECSUB & 4K & !BLU & !WEBDL & !DOLBY & !SDR & !3D > CNSUB & 4K & !BLU & !WEBDL & !DOLBY & !SDR & !3D > 4K & !BLU & !REMUX & !DOLBY & HDR & !3D > 4K & !BLURAY & !REMUX & !DOLBY & !3D > SPECSUB & 1080P & !BLU & !REMUX & !WEBDL & !DOLBY & HDR & !3D > CNSUB & 1080P & !BLU & !REMUX & !WEBDL & !DOLBY & HDR & !3D > SPECSUB & 1080P & !BLU & !REMUX & !WEBDL & !DOLBY & !3D > CNSUB & 1080P & !BLU & !REMUX & !WEBDL & !DOLBY & !3D > SPECSUB & 1080P & !BLU & !WEBDL & !DOLBY & HDR & !3D > CNSUB & 1080P & !BLU & !WEBDL & !DOLBY & HDR & !3D > SPECSUB & 1080P & !BLU & !WEBDL & !DOLBY & !3D > CNSUB & 1080P & !BLU & !WEBDL & !DOLBY & !3D > SPECSUB & 1080P & WEBDL & !DOLBY & HDR & !3D > CNSUB & 1080P & WEBDL & !DOLBY & HDR & !3D > SPECSUB & 1080P & WEBDL & !DOLBY & !3D > CNSUB & 1080P & WEBDL & !DOLBY & !3D > 1080P & !BLU & !REMUX & !DOLBY & HDR & !3D > 1080P & !BLU & !REMUX & !DOLBY & !3D diff --git a/app/chain/search/manual.py b/app/chain/search/manual.py index a2b1ceef1..d0ceb576c 100644 --- a/app/chain/search/manual.py +++ b/app/chain/search/manual.py @@ -184,10 +184,12 @@ class _ManualPage: SearchDiagnosticWarning, ) - rules = RuleHelper().explain_rule_groups( - media=None if self.raw_title else self.media, group_names=self.plan.rule_groups or [], - ) + helper = RuleHelper() + media = None if self.raw_title else self.media + group_names = self.plan.rule_groups or [] + rules = helper.explain_rule_groups(media=media, group_names=group_names) warnings = [SearchDiagnosticWarning(code=rule.reason, rule_group=rule.name) for rule in rules if rule.reason] + warnings.extend(helper.diagnose_rule_groups(media=media, group_names=group_names)) sites: dict[Optional[int], SearchDiagnosticSite] = {} warning_codes: set[str] = set() for observation in self.observations: diff --git a/app/modules/filter/__init__.py b/app/modules/filter/__init__.py index 89c3823b8..ca8b4b346 100644 --- a/app/modules/filter/__init__.py +++ b/app/modules/filter/__init__.py @@ -7,8 +7,10 @@ from copy import deepcopy from functools import lru_cache from typing import Any, Dict, List, Optional, Tuple, Union, cast +from pyparsing import ParseBaseException + from app.adapters.system import rust as rust_accel -from app.application.rules import BUILTIN_RULE_SET, RuleHelper, RuleParser +from app.application.rules import BUILTIN_RULE_SET, RuleHelper, RuleParser, describe_rule_string_error from app.domain.context import MediaInfo, TorrentInfo from app.domain.metainfo import MetaInfo, _rust_parse_options, clear_rust_parse_options_cache from app.foundation import size as size_tools @@ -291,18 +293,26 @@ class FilterModule(_ModuleBase): 筛选命中任一优先级层级的种子,并保留输入顺序。 每个种子的优先级由第一个命中的层级决定;解析结果复用调用方提供的缓存。 + + :raises ValueError: 实际执行的层级无法解析,说明中保留规则组及完整无效 ID """ if not torrent_list: return [] # 只拆分一次规则层级;具体层级仍延迟到真正需要匹配时解析。 rule_groups = [rule_group.strip() for rule_group in rule_string.split('>')] ret_torrents = [] - for torrent in torrent_list: - if not self.__get_order(torrent, rule_groups, mediainfo, parser, parsed_rule_cache): - logger.debug(f"种子 {torrent.site_name} - {torrent.title} {torrent.description or ''} " - f"不匹配 {rule_name} 过滤规则") - continue - ret_torrents.append(torrent) + try: + for torrent in torrent_list: + if not self.__get_order(torrent, rule_groups, mediainfo, parser, parsed_rule_cache): + logger.debug(f"种子 {torrent.site_name} - {torrent.title} {torrent.description or ''} " + f"不匹配 {rule_name} 过滤规则") + continue + ret_torrents.append(torrent) + except ParseBaseException as error: + # 只在实际解析失败后补充定位,不能预解析未执行的低优先级层级。 + issue = describe_rule_string_error(error.pstr, self.rule_set) + detail = str(issue) if issue is not None else "规则表达式语法错误" + raise ValueError(f"过滤规则组 {rule_name!r} 配置错误:{detail}") from error return ret_torrents diff --git a/app/schemas/search.py b/app/schemas/search.py index 350f7a48c..995bfe96e 100644 --- a/app/schemas/search.py +++ b/app/schemas/search.py @@ -73,6 +73,8 @@ class SearchDiagnosticWarning(BaseModel): code: str = Field(description="稳定警告代码;客户端应兼容未知代码") rule_group: Optional[str] = Field(default=None, description="相关规则组名称;来源警告为 None") + rule_ids: list[str] = Field(default_factory=list, exclude_if=lambda value: not value, + description="规则配置错误涉及的完整 ID;保留旧 ID 空白,没有相关 ID 时省略") class SearchDiagnostics(BaseModel): diff --git a/database/versions/a7383c1d9e20_filter_rule_ids.py b/database/versions/a7383c1d9e20_filter_rule_ids.py new file mode 100644 index 000000000..522a48a09 --- /dev/null +++ b/database/versions/a7383c1d9e20_filter_rule_ids.py @@ -0,0 +1,137 @@ +""" +迁移旧版允许保存、但现有 Python/Rust 规则语法无法解析的自定义 ID。 + +规则定义与完整操作数引用在同一 Alembic 事务内更新;不重新序列化业务字段, +不清理规则组、订阅或全局配置。历史迁移固定使用此时的语法与内置 ID 集合。 +""" + +import copy +import re +from collections import Counter +from typing import Any + +import sqlalchemy as sa +from alembic import op + +from app.runtime.log import logger +from app.schemas.types import SystemConfigKey + +revision = "a7383c1d9e20" +down_revision = "b849e613a72f" +branch_labels = None +depends_on = None + +# 两套解析器的 ID 都只能包含 ASCII 字母、数字,且必须至少包含一个字母。 +_RULE_ID = re.compile(r"[A-Za-z0-9]*[A-Za-z][A-Za-z0-9]*\Z") +_OPERAND = re.compile(r"[^!&|()>]+") +# 固定迁移时的内置 ID,避免历史迁移随运行代码变化而覆盖内置规则。 +_BUILTIN_IDS = frozenset({ + "BLU", "4K", "1080P", "720P", "CNSUB", "GZ", "SPECSUB", "BLURAY", "UHD", + "H265", "H264", "DOLBY", "ATMOS", "HDR", "SDR", "REMUX", "WEBDL", "FREE", + "CNVOI", "HKVOI", "60FPS", "3D", "HIRES", "LOSSLESS", "FLAC", "ALAC", "APE", + "WAV", "DSD", "MP3", "AAC", "OPUS", "BITRATE320", "BITRATE256", "BITRATE192", +}) + + +def _rename_rules(custom_rules: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, str]]: + """ + 保留规则顺序和全部业务字段,为无效 ID 分配不冲突的稳定新 ID。 + """ + ids = [rule.get("id") for rule in custom_rules] + if any(not isinstance(rule_id, str) for rule_id in ids) or len(set(ids)) != len(ids): + raise RuntimeError("自定义过滤规则存在缺失或重复 ID,无法安全迁移") + occupied = _BUILTIN_IDS | set(ids) + renames = {} + updated = copy.deepcopy(custom_rules) + for rule in updated: + old_id = rule["id"] + if _RULE_ID.fullmatch(old_id): + continue + base = re.sub(r"[^A-Za-z0-9]", "", old_id) + if not _RULE_ID.fullmatch(base): + base = f"Rule{base}" + new_id = base + suffix = 1 + while new_id in occupied: + new_id = f"{base}{suffix}" + suffix += 1 + occupied = occupied | {new_id} + renames[old_id] = new_id + rule["id"] = new_id + return updated, renames + + +def _rewrite_groups( + groups: list[dict[str, Any]], custom_rules: list[dict[str, Any]], renames: dict[str, str], +) -> list[dict[str, Any]]: + """ + 一次性改写完整操作数,保留外围空白,避免片段误替换及连续改名的串扰。 + + 外围空白属于表达式排版,去除后存在多个候选 ID 时拒绝猜测引用归属。 + """ + aliases = {old_id.strip(): new_id for old_id, new_id in renames.items() if old_id.strip()} + counts = Counter([*_BUILTIN_IDS, *(rule["id"].strip() for rule in custom_rules)]) + updated = copy.deepcopy(groups) + for group in updated: + expression = group.get("rule_string") + if expression is None: + continue + if not isinstance(expression, str): + raise RuntimeError(f"过滤规则组 {group.get('name')!r} 的表达式不是字符串,无法安全迁移") + + def replace(match: re.Match[str]) -> str: + """ + 只替换完整旧 ID,无法唯一定位时在任何数据库写入前中止迁移。 + """ + span = match.group() + operand = span.strip() + if operand not in aliases: + return span + if counts[operand] > 1: + raise RuntimeError(f"过滤规则组 {group.get('name')!r} 的旧规则 ID {operand!r} 无法唯一定位,请先手动改名") + start = len(span) - len(span.lstrip()) + end = len(span.rstrip()) + return f"{span[:start]}{aliases[operand]}{span[end:]}" + + group["rule_string"] = _OPERAND.sub(replace, expression) + return updated + + +def upgrade() -> None: + """ + 在调用方迁移事务中同步更新 ID 和引用,异常时由 Alembic 整体回滚。 + """ + connection = op.get_bind() + if "systemconfig" not in sa.inspect(connection).get_table_names(): + return + table = sa.table("systemconfig", sa.column("key", sa.String()), sa.column("value", sa.JSON())) + keys = (SystemConfigKey.CustomFilterRules, SystemConfigKey.UserFilterRuleGroups) + values = dict(connection.execute( + sa.select(table.c.key, table.c.value).where(table.c.key.in_([key.value for key in keys])) + .order_by(table.c.key).with_for_update() + ).tuples().all()) + custom = values.get(SystemConfigKey.CustomFilterRules.value) + if custom is None or custom == []: + return + if not isinstance(custom, list) or any(not isinstance(rule, dict) for rule in custom): + raise RuntimeError("自定义过滤规则格式无效,无法安全迁移") + updated_custom, renames = _rename_rules(custom) + if not renames: + return + groups = values.get(SystemConfigKey.UserFilterRuleGroups.value) + if groups is not None and (not isinstance(groups, list) or any(not isinstance(group, dict) for group in groups)): + raise RuntimeError("过滤规则组格式无效,无法安全迁移") + updated_groups = _rewrite_groups(groups or [], custom, renames) + connection.execute(table.update().where(table.c.key == SystemConfigKey.CustomFilterRules.value) + .values(value=updated_custom)) + if updated_groups != (groups or []): + connection.execute(table.update().where(table.c.key == SystemConfigKey.UserFilterRuleGroups.value) + .values(value=updated_groups)) + for old_id, new_id in renames.items(): + logger.info(f"自定义过滤规则 ID 迁移:{old_id!r} -> {new_id!r}") + + +def downgrade() -> None: + """ + 保留迁移后的合法 ID;不能无依据恢复已失效的旧引用,回退数据需使用升级前备份。 + """ diff --git a/docs/mcp-api.md b/docs/mcp-api.md index fd89f748f..247fa1eb3 100644 --- a/docs/mcp-api.md +++ b/docs/mcp-api.md @@ -130,9 +130,20 @@ Web 影视精确与标题 SSE 的 `manual_paging=true` 模式在最终 `done` 索引器内部未报告的丢弃原因不作推测。 - `rule_groups` 包含 `name`、`status`、`reason`、`media_type` 和 `categories`。 `effective` 表示规则适用,`skipped` 不增加拒绝数。标题搜索沿用过滤器的空媒体上下文。 -- `warnings` 使用 `{code,rule_group?}`,代码包括 `rule_group_not_applicable`、 +- `warnings` 使用 `{code,rule_group?,rule_ids?}`,代码包括 `rule_group_not_applicable`、 `rule_group_missing`、`provider_error`、`provider_cooldown`、`provider_outcome_unknown`。 - 原始异常、下载地址和凭据不进入诊断。 + 所选且适用的规则组还会检查配置:`rule_id_invalid` 表示 ID 不符合解析语法, + `rule_id_missing` 表示引用的 ID 不存在,`rule_syntax_invalid` 表示运算符、括号或层级 + 语法无效。前两者通过可选 `rule_ids` 保留完整 ID,包括旧 ID 的外围空白;没有相关 + ID 时省略该字段。配置告警不增加资源拒绝计数,也不意味着所有优先级层级都已执行。 + 原始解析异常、下载地址和凭据不进入诊断。 + +升级时数据库迁移会将存量不符合 Python/Rust 语法的自定义 ID 转为英文字母和数字, +并同步改写规则组中的完整操作数引用。保留规则名称、匹配内容、顺序、媒体范围和其它 +字段;与内置或已有 ID 冲突时追加数字后缀。仅包含数字或清理后为空的 ID 添加 `Rule` +前缀。去除外围空白后无法唯一定位引用时中止迁移,需先通过自定义规则改名 API 修复, +不会猜测引用归属或保存半套变更。新 ID 保持两套解析器的“至少包含一个字母”约束。 +升级前备份沿用数据库自动备份开关;数据降级不自动恢复失效 ID。 `GET /api/v1/search/last/context` 按认证用户返回完整的 `params`、`results` 和可选 `diagnostics`。同一用户并发搜索按完成顺序保存,异常或取消保留上次完整记录。普通 diff --git a/scripts/generate_agent_skill_docs.py b/scripts/generate_agent_skill_docs.py index c1a35a90e..7c0f54474 100644 --- a/scripts/generate_agent_skill_docs.py +++ b/scripts/generate_agent_skill_docs.py @@ -17,7 +17,8 @@ PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) -MOVIEPILOT_API_SKILL_VERSION = "72" +# 与对应 SKILL.md 同步维护,重新生成不能回退用户同步所需的版本。 +MOVIEPILOT_API_SKILL_VERSION = "73" DATABASE_OPERATION_SKILL_VERSION = "18" diff --git a/skills/moviepilot-api/SKILL.md b/skills/moviepilot-api/SKILL.md index 62c2d591d..4143c09e6 100644 --- a/skills/moviepilot-api/SKILL.md +++ b/skills/moviepilot-api/SKILL.md @@ -1,6 +1,6 @@ --- name: moviepilot-api -version: 72 +version: 73 description: >- Use this skill for MoviePilot product operations such as media search, torrent search, downloads, subscriptions, library checks, sites, storage, workflows, @@ -420,6 +420,12 @@ token exchange downloads retain their existing credential rules. - Recent `search.results` snapshots belong to the authenticated user; search again after upgrading to populate them. Optional Web `done.diagnostics` uses `scope=page` for the current page. Skipped rule groups do not increase the resource rejection count. +- Page diagnostics `rule_id_invalid`, `rule_id_missing`, and `rule_syntax_invalid` + describe configuration errors in selected applicable rule groups, not ordinary + resource mismatches. Optional `warnings.rule_ids` preserves complete IDs and + surrounding whitespace. Use rule APIs to rename IDs and references together; + do not edit the database. Upgrade migration handles unambiguous legacy IDs; + confirm ambiguous references manually instead of relaxing parsing or skipping rules. - For list inspection, explicitly send the operation's documented pagination fields instead of requesting an unbounded legacy result. For optional legacy pagination, start with `query={"page":1,"count":20}`. diff --git a/tests/test_builtin_skill_boundaries.py b/tests/test_builtin_skill_boundaries.py index bf3594694..59cbaad4f 100644 --- a/tests/test_builtin_skill_boundaries.py +++ b/tests/test_builtin_skill_boundaries.py @@ -130,7 +130,7 @@ def test_modified_builtin_skills_have_incremented_versions() -> None: "database-operation": "18", "feedback-issue": "12", "anysearch": "3", - "moviepilot-api": "72", + "moviepilot-api": "73", "moviepilot-update": "7", "organize-files": "6", "transfer-failed-retry": "6", diff --git a/tests/test_filter_rule_diagnostics.py b/tests/test_filter_rule_diagnostics.py new file mode 100644 index 000000000..2d2aa8a6b --- /dev/null +++ b/tests/test_filter_rule_diagnostics.py @@ -0,0 +1,113 @@ +""" +验证旧规则 ID 的完整定位、规则配置诊断与过滤器的延迟解析合同。 +""" + +from collections import Counter +from types import SimpleNamespace + +import pytest + +from app.application import rules +from app.chain.search.manual import _ManualPage +from app.domain.context import MediaInfo, TorrentInfo +from app.modules.filter import FilterModule +from app.schemas.rule import CustomRule, FilterRuleGroup +from app.schemas.types import MediaType + + +@pytest.mark.parametrize("accelerated", [False, True]) +def test_runtime_reports_full_legacy_id_and_rule_group(monkeypatch, accelerated) -> None: + """ + Python 解析及 Rust 失败后的回退都应定位完整旧 ID,而不是只报告 Candidate。 + """ + group = FilterRuleGroup(name="国产剧", rule_string="1080P & Pre Candidate") + module = FilterModule() + module.rulehelper = SimpleNamespace(get_rule_group_by_media=lambda **_kwargs: [group]) + module.rule_set = {**rules.BUILTIN_RULE_SET, " Pre Candidate": {"include": "QHstudIo"}} + monkeypatch.setattr("app.modules.filter.rust_accel.is_enabled", lambda: accelerated) + with pytest.raises(Exception) as caught: + module.filter_torrents( + rule_groups=["国产剧"], + torrent_list=[TorrentInfo(title="Show S01E01 1080p QHstudIo", description="")], + ) + message = str(caught.value) + assert "国产剧" in message + assert "' Pre Candidate'" in message + assert "无效的规则 ID" in message + assert "found 'Candidate'" not in message + + +@pytest.mark.parametrize( + ("expression", "ids", "code", "invalid_ids"), + [ + ("1080P & Pre Candidate", [" Pre Candidate"], "rule_id_invalid", [" Pre Candidate"]), + ("!M-Team & 1080P", ["M-Team"], "rule_id_invalid", ["M-Team"]), + ("!Missing & 1080P", [], "rule_id_missing", ["Missing"]), + ("1080P >", [], "rule_syntax_invalid", []), + ("(1080P", [], "rule_syntax_invalid", []), + ("1080P & 123", ["123"], "rule_id_invalid", ["123"]), + ], +) +def test_rule_expression_diagnosis_keeps_complete_operands(expression, ids, code, invalid_ids) -> None: + """ + 配置诊断保留完整 ID,区分无效 ID、悬空引用和真正的表达式语法错误。 + """ + issue = rules.describe_rule_string_error(expression, [*rules.BUILTIN_RULE_SET, *ids]) + assert issue is not None + assert issue.code == code + assert list(issue.rule_ids) == invalid_ids + + +def test_valid_rule_expression_has_no_configuration_warning() -> None: + """ + 括号、否定、多层优先级和数字开头的合法 ID 都不产生配置告警。 + """ + assert rules.describe_rule_string_error("(1080P | 4K) & !BLU > 60FPS", rules.BUILTIN_RULE_SET) is None + + +def test_diagnostics_only_checks_selected_applicable_rule_groups(monkeypatch) -> None: + """ + 无效电影规则不污染电视剧搜索,未选择的组也不进入当前页诊断。 + """ + helper = rules.RuleHelper() + groups = [ + FilterRuleGroup(name="国产剧", media_type="电视剧", rule_string="1080P & Pre Candidate"), + FilterRuleGroup(name="电影", media_type="电影", rule_string="!Missing"), + FilterRuleGroup(name="未选择", rule_string="!OtherMissing"), + ] + monkeypatch.setattr(helper, "get_rule_groups", lambda: groups) + monkeypatch.setattr(helper, "get_custom_rules", lambda: [CustomRule(id=" Pre Candidate", name="候补组")]) + warnings = helper.diagnose_rule_groups( + media=MediaInfo(type=MediaType.TV), group_names=["国产剧", "电影", "已删除", "国产剧"], + ) + assert [warning.model_dump() for warning in warnings] == [{ + "code": "rule_id_invalid", "rule_group": "国产剧", "rule_ids": [" Pre Candidate"], + }] + assert helper.diagnose_rule_groups(media=None, group_names=[]) == [] + + +def test_terminal_page_diagnostics_contains_rule_configuration_warning(monkeypatch) -> None: + """ + 页完成事件携带可供前端显示的完整规则定位,不复制 pyparsing 的原始报错。 + """ + monkeypatch.setattr(rules.RuleHelper, "get_rule_groups", staticmethod(lambda: [ + FilterRuleGroup(name="国产剧", media_type="电视剧", rule_string="1080P & Pre Candidate"), + ])) + monkeypatch.setattr(rules.RuleHelper, "get_custom_rules", staticmethod(lambda: [ + CustomRule(id=" Pre Candidate", name="候补组"), + ])) + page = object.__new__(_ManualPage) + page.plan = SimpleNamespace(rule_groups=["国产剧"]) + page.raw_title = False + page.media = MediaInfo(type=MediaType.TV) + page.search_id = "legacy-rule-search" + page.torrents = [TorrentInfo(title="Show S01E01 1080p")] + page.counts = Counter() + page.observations = [] + diagnostics = page.diagnostics([]).model_dump(mode="json") + assert diagnostics["warnings"] == [{ + "code": "rule_id_invalid", "rule_group": "国产剧", "rule_ids": [" Pre Candidate"], + }] + assert diagnostics["stage_counts"] == {"candidates": 1, "retained": 0} + assert diagnostics["rejection_reasons"] == [] + assert "Expected end of text" not in str(diagnostics) diff --git a/tests/test_filter_rule_ids_migration.py b/tests/test_filter_rule_ids_migration.py new file mode 100644 index 000000000..42035d068 --- /dev/null +++ b/tests/test_filter_rule_ids_migration.py @@ -0,0 +1,259 @@ +""" +用隔离 SQLite 验证旧过滤规则 ID 与规则组引用的原子、保真迁移。 +""" + +import copy +import importlib +from types import SimpleNamespace + +import pytest +import sqlalchemy as sa +from alembic.config import Config +from alembic.migration import MigrationContext +from alembic.operations import Operations +from alembic.script import ScriptDirectory + +from app.adapters.system import rust as rust_accel +from app.application import rules +from app.application.rules import RuleParser +from app.domain.context import TorrentInfo +from app.modules.filter import FilterModule +from app.schemas.types import SystemConfigKey + +_MIGRATION = "database.versions.a7383c1d9e20_filter_rule_ids" + + +@pytest.fixture +def migration_database(monkeypatch): + """ + 创建只含系统配置的临时数据库,并把新迁移绑定到调用方事务。 + """ + engine = sa.create_engine("sqlite://") + metadata = sa.MetaData() + table = sa.Table( + "systemconfig", metadata, + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("key", sa.String(), nullable=False, unique=True), + sa.Column("value", sa.JSON()), + ) + metadata.create_all(engine) + migration = importlib.import_module(_MIGRATION) + try: + with engine.begin() as connection: + monkeypatch.setattr(migration, "op", Operations(MigrationContext.configure(connection))) + yield migration, table, connection + finally: + engine.dispose() + + +def _save(connection, table, key, value) -> None: + connection.execute(table.insert().values(key=key.value, value=value)) + + +def _read(connection, table, key): + return connection.execute(sa.select(table.c.value).where(table.c.key == key.value)).scalar_one() + + +def test_upgrade_preserves_reported_rule_and_group_counts_and_all_other_fields(migration_database) -> None: + """ + 模拟 Issue 的 30 条规则、27 个组和 13 处引用,只改变两个 ID 及相关引用。 + """ + migration, table, connection = migration_database + custom = [ + {"id": " Pre Candidate", "name": "优先候补组", "include": "QHstudIo|OurTV", "exclude": None}, + {"id": "M-Team", "name": "馒头", "include": "M-Team", "size_range": ">100", "extra": {"keep": True}}, + *[{"id": f"Rule{index}", "name": f"规则{index}"} for index in range(28)], + ] + groups = [ + {"name": f"组{index}", "media_type": "电视剧", "category": "国产剧", + "rule_string": "1080P & Pre Candidate > 4K" if index < 13 else "1080P", + "extra": [index]} + for index in range(27) + ] + _save(connection, table, SystemConfigKey.CustomFilterRules, custom) + _save(connection, table, SystemConfigKey.UserFilterRuleGroups, groups) + _save(connection, table, SystemConfigKey.SearchFilterRuleGroups, ["组0", "组26"]) + migration.upgrade() + updated = _read(connection, table, SystemConfigKey.CustomFilterRules) + updated_groups = _read(connection, table, SystemConfigKey.UserFilterRuleGroups) + expected = copy.deepcopy(custom) + expected[0]["id"], expected[1]["id"] = "PreCandidate", "MTeam" + assert updated == expected + expected_groups = copy.deepcopy(groups) + for group in expected_groups[:13]: + group["rule_string"] = "1080P & PreCandidate > 4K" + assert updated_groups == expected_groups + assert _read(connection, table, SystemConfigKey.SearchFilterRuleGroups) == ["组0", "组26"] + migration.upgrade() + migration.downgrade() + assert _read(connection, table, SystemConfigKey.CustomFilterRules) == expected + assert _read(connection, table, SystemConfigKey.UserFilterRuleGroups) == expected_groups + + +def test_migration_avoids_builtin_custom_and_generated_id_collisions(migration_database) -> None: + """ + 清理后的 ID 冲突时追加稳定数字后缀,不覆盖已有规则或另一条迁移结果。 + """ + migration, table, connection = migration_database + custom = [{"id": value, "name": value} for value in [ + "PreCandidate", "PreCandidate1", "Pre Candidate", "Pre-Candidate", "4-K", "中文", "123", + ]] + _save(connection, table, SystemConfigKey.CustomFilterRules, custom) + _save(connection, table, SystemConfigKey.UserFilterRuleGroups, [{ + "name": "优先级", "rule_string": "Pre Candidate > Pre-Candidate > 4-K > 中文 > 123", + }]) + migration.upgrade() + updated = _read(connection, table, SystemConfigKey.CustomFilterRules) + assert [rule["id"] for rule in updated] == [ + "PreCandidate", "PreCandidate1", "PreCandidate2", "PreCandidate3", "4K1", "Rule", "Rule123", + ] + expression = _read(connection, table, SystemConfigKey.UserFilterRuleGroups)[0]["rule_string"] + assert expression == "PreCandidate2 > PreCandidate3 > 4K1 > Rule > Rule123" + for level in expression.split(">"): + assert RuleParser().parse(level).as_list() + + +def test_reference_rewrite_only_replaces_complete_operands(migration_database) -> None: + """ + 同名片段不能被改写,括号和否定中的完整引用则同步迁移并保留排版。 + """ + migration, table, connection = migration_database + _save(connection, table, SystemConfigKey.CustomFilterRules, [ + {"id": "M-Team", "name": "馒头"}, {"id": "Prefix-M-Team", "name": "前缀组"}, + ]) + _save(connection, table, SystemConfigKey.UserFilterRuleGroups, [ + {"name": "完整引用", "rule_string": "!(M-Team | Prefix-M-Team) & 1080P"}, + {"name": "相似片段", "rule_string": "Unknown-M-Team > M-Teams"}, + {"name": "空草稿", "rule_string": None}, + ]) + migration.upgrade() + assert _read(connection, table, SystemConfigKey.UserFilterRuleGroups) == [ + {"name": "完整引用", "rule_string": "!(MTeam | PrefixMTeam) & 1080P"}, + {"name": "相似片段", "rule_string": "Unknown-M-Team > M-Teams"}, + {"name": "空草稿", "rule_string": None}, + ] + + +@pytest.mark.parametrize("value", [None, []]) +def test_empty_custom_rules_do_not_create_or_rewrite_configuration(migration_database, value) -> None: + """ + 新安装及没有自定义规则的配置保持原值,不创建额外规则组。 + """ + migration, table, connection = migration_database + _save(connection, table, SystemConfigKey.CustomFilterRules, value) + migration.upgrade() + assert _read(connection, table, SystemConfigKey.CustomFilterRules) == value + assert connection.execute(sa.select(sa.func.count()).select_from(table)).scalar_one() == 1 + + +def test_ambiguous_whitespace_ids_fail_without_partial_changes(migration_database) -> None: + """ + 去除外围空白后无法唯一定位引用时明确失败,不能猜测后覆盖用户规则。 + """ + migration, table, connection = migration_database + custom = [{"id": " Rule", "name": "旧规则"}, {"id": "Rule", "name": "合法规则"}] + groups = [{"name": "组", "rule_string": "Rule"}] + _save(connection, table, SystemConfigKey.CustomFilterRules, custom) + _save(connection, table, SystemConfigKey.UserFilterRuleGroups, groups) + with pytest.raises(RuntimeError, match="无法唯一定位"): + migration.upgrade() + assert _read(connection, table, SystemConfigKey.CustomFilterRules) == custom + assert _read(connection, table, SystemConfigKey.UserFilterRuleGroups) == groups + + +def test_whitespace_id_cannot_take_over_builtin_references(migration_database) -> None: + """ + 带外围空白的旧 ID 与内置 ID 相同也必须拒绝猜测,不能改写原本有效的内置引用。 + """ + migration, table, connection = migration_database + custom = [{"id": " 4K", "name": "旧规则"}] + _save(connection, table, SystemConfigKey.CustomFilterRules, custom) + _save(connection, table, SystemConfigKey.UserFilterRuleGroups, [{"name": "组", "rule_string": "4K"}]) + with pytest.raises(RuntimeError, match="无法唯一定位"): + migration.upgrade() + assert _read(connection, table, SystemConfigKey.CustomFilterRules) == custom + + +@pytest.mark.parametrize("accelerated", [False, True]) +def test_migrated_ids_restore_filtering_without_changing_rule_content(migration_database, monkeypatch, accelerated) -> None: + """ + 迁移后相同规则内容在真实 Python/Rust 过滤入口重新生效,而不是跳过坏规则。 + """ + migration, table, connection = migration_database + _save(connection, table, SystemConfigKey.CustomFilterRules, [{"id": "M-Team", "name": "馒头", "include": "M-Team"}]) + _save(connection, table, SystemConfigKey.UserFilterRuleGroups, [{"name": "组", "rule_string": "1080P & M-Team"}]) + configuration = SimpleNamespace(get=lambda key: _read(connection, table, key)) + monkeypatch.setattr(rules, "get_configured_system_config", lambda: configuration) + monkeypatch.setattr("app.modules.filter.rust_accel.is_enabled", lambda: accelerated) + module = FilterModule() + module.init_module() + keep = TorrentInfo(title="Show S01E01 1080p M-Team", description="") + drop = TorrentInfo(title="Show S01E01 1080p OtherGroup", description="") + with pytest.raises(ValueError, match="无效的规则 ID"): + module.filter_torrents(["组"], [keep, drop]) + migration.upgrade() + module.init_module() + assert module.filter_torrents(["组"], [keep, drop]) == [keep] + assert keep.pri_order == 100 + assert module.rule_set["MTeam"]["include"] == "M-Team" + native = rust_accel.filter_torrents( + groups=[{"name": "组", "rule_string": "1080P & MTeam"}], + torrent_list=[keep, drop], rule_set=module.rule_set, + ) + if accelerated: + assert native is not None + assert native[0] == [(0, 100)] + else: + assert native is None + + +def test_data_migration_belongs_to_single_startup_lineage() -> None: + """ + 新迁移连接现有 head,启动更新能够自动发现它,不依赖用户调用改名接口。 + """ + config = Config() + config.set_main_option("script_location", "database") + script = ScriptDirectory.from_config(config) + assert len(script.get_heads()) == 1 + assert "a7383c1d9e20" in {item.revision for item in script.walk_revisions()} + assert script.get_revision("a7383c1d9e20").down_revision == "b849e613a72f" + + +def test_failure_between_config_writes_rolls_back_both_rows(monkeypatch) -> None: + """ + 两个配置更新之间的数据库错误回滚整个迁移,不留下只改 ID 而未改引用的状态。 + """ + migration = importlib.import_module(_MIGRATION) + engine = sa.create_engine("sqlite://") + metadata = sa.MetaData() + table = sa.Table("systemconfig", metadata, sa.Column("key", sa.String(), primary_key=True), + sa.Column("value", sa.JSON())) + custom = [{"id": "M-Team", "name": "馒头"}] + groups = [{"name": "组", "rule_string": "M-Team"}] + metadata.create_all(engine) + with engine.begin() as connection: + _save(connection, table, SystemConfigKey.CustomFilterRules, custom) + _save(connection, table, SystemConfigKey.UserFilterRuleGroups, groups) + writes = [] + + def fail_second_write(_connection, _cursor, statement, _parameters, _context, _executemany): + """ + 在第二个配置写入前注入故障,验证第一个写入也没有独立提交。 + """ + if statement.startswith("UPDATE"): + writes.append(statement) + if len(writes) == 2: + raise RuntimeError("模拟第二次配置写入失败") + + sa.event.listen(engine, "before_cursor_execute", fail_second_write) + try: + with pytest.raises(RuntimeError, match="第二次配置写入失败"): + with engine.begin() as connection: + monkeypatch.setattr(migration, "op", Operations(MigrationContext.configure(connection))) + migration.upgrade() + with engine.connect() as connection: + assert _read(connection, table, SystemConfigKey.CustomFilterRules) == custom + assert _read(connection, table, SystemConfigKey.UserFilterRuleGroups) == groups + finally: + sa.event.remove(engine, "before_cursor_execute", fail_second_write) + engine.dispose() diff --git a/tests/test_subscription_identity_review_migration.py b/tests/test_subscription_identity_review_migration.py index b27d32003..5de132251 100644 --- a/tests/test_subscription_identity_review_migration.py +++ b/tests/test_subscription_identity_review_migration.py @@ -87,7 +87,8 @@ def test_identity_upgrade_chain_preserves_plugin_installation_snapshot(monkeypat config = Config() config.set_main_option("script_location", "database") script = ScriptDirectory.from_config(config) - assert script.get_heads() == ["b849e613a72f"] + assert script.get_heads() == ["a7383c1d9e20"] + assert script.get_revision("a7383c1d9e20").down_revision == "b849e613a72f" assert script.get_revision("b849e613a72f").down_revision == "97ad7239c1e0" assert script.get_revision("97ad7239c1e0").down_revision == "4f62a73e81c9" assert script.get_revision("4f62a73e81c9").down_revision == "e4a8c7b29016"