From b6f9a61671f17c88f467c12be633e5106111fbec Mon Sep 17 00:00:00 2001 From: subaoyan16 Date: Fri, 4 Sep 2026 18:02:50 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E6=9C=80?= =?UTF-8?q?=E5=B0=8F=20Agent=20=E8=BD=A8=E8=BF=B9=E8=AF=84=E4=BC=B0?= =?UTF-8?q?=E5=85=A5=E5=8F=A3(Refs=20#1956)=20(#2325)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add minimal agent trajectory metrics with golden samples * feat: add runnable agent trajectory eval entry with JSON and text reports * fix: treat unsuccessful AgentResult as a run failure in trajectory eval * fix: reject multi-arch executor and validate golden tools against the real registry --- docs/CHANGELOG.md | 2 + docs/agent-trajectory-eval.md | 82 ++ evals/agent_trajectory/__init__.py | 6 + evals/agent_trajectory/golden_samples.json | 18 + evals/agent_trajectory/metrics.py | 421 ++++++++++ evals/agent_trajectory/run_eval.py | 211 ++++++ .../negative_600519_technical.json | 41 + .../positive_600519_technical.json | 41 + .../retry_000001_core_data_strict.json | 41 + tests/test_agent_trajectory_metrics.py | 716 ++++++++++++++++++ tests/test_agent_trajectory_run_eval.py | 436 +++++++++++ 11 files changed, 2015 insertions(+) create mode 100644 docs/agent-trajectory-eval.md create mode 100644 evals/agent_trajectory/__init__.py create mode 100644 evals/agent_trajectory/golden_samples.json create mode 100644 evals/agent_trajectory/metrics.py create mode 100644 evals/agent_trajectory/run_eval.py create mode 100644 tests/fixtures/agent_trajectory/negative_600519_technical.json create mode 100644 tests/fixtures/agent_trajectory/positive_600519_technical.json create mode 100644 tests/fixtures/agent_trajectory/retry_000001_core_data_strict.json create mode 100644 tests/test_agent_trajectory_metrics.py create mode 100644 tests/test_agent_trajectory_run_eval.py diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index f5ae6cb50cb..4b1183d19af 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/). > For user-friendly release highlights, see the [GitHub Releases](https://github.com/ZhuLinsen/daily_stock_analysis/releases) page. ## [Unreleased] +- [新功能] 新增最小 Agent 轨迹评估入口 `evals/agent_trajectory/`(Refs #1956):纯函数指标层只消费真实 `tool_calls_log + AgentResult`,冻结最小指标契约(工具命中、冗余/缓存、失败/重试、总步数/max_steps),`run_eval.py` 经 `build_agent_executor` 真实执行并输出文本摘要 + 结构化 JSON 报告;评估为 reporter 非 gate,零 `src/` 改动 + - [修复] 将 litellm 依赖窗口上界收敛到 `<1.99.0`:1.99.0 起把 `prompt_cache_key` 透传给 OpenAI provider,破坏 provider 缓存测试对不透传行为的既有断言(CI backend-tests 3/3 与 backend-gate 失败);保留历史最低版本与 `!=1.82.7`/`!=1.82.8` 事故排除,同时同步更新各 LLM 兼容文档中写死的依赖约束表述,避免文档与 requirements.txt 漂移 - [新功能] 新增 `SEARXNG_TIMEOUT_SECONDS` 配置自建 SearXNG 单次搜索超时(默认 10 秒),已接线全部 SearchService 构造入口(含题材搜索子进程重建)与默认 GitHub Actions 工作流 diff --git a/docs/agent-trajectory-eval.md b/docs/agent-trajectory-eval.md new file mode 100644 index 00000000000..8a322a83486 --- /dev/null +++ b/docs/agent-trajectory-eval.md @@ -0,0 +1,82 @@ +# Agent Trajectory 评估(最小版,Refs #1956) + +## 定位 + +`evals/agent_trajectory/` 提供一套**离线可运行的最小轨迹评估管线**:用真实 `tool_calls_log + AgentResult` 跑一个 golden 样例,输出结构化 JSON 报告与简短可读文本摘要。评估结果是 **reporter 而非 gate** —— 指标违规只反映在报告里,不会让进程失败,也不进入 CI 门禁。 + +- 指标层(`metrics.py`)是纯函数:只消费轨迹日志与 golden 样例,不 import `src/`,不触网、不调 LLM,可离线单测。 +- 入口(`run_eval.py`)通过 `build_agent_executor()` 构建真实执行器,与 `src/core/pipeline.py` 使用同一个执行捕获钩子,消费真实产物。 +- 入口只支持**单 agent 运行**(`AGENT_ARCH=single`,默认):`AGENT_ARCH=multi` 时 factory 返回 orchestrator,其轨迹是各 stage 局部步号的拼接、`total_steps` 为 stage 数,与单 runner 指标契约不兼容——入口在构建前明确报错并退出(退出码 1)。 +- 入口用真实工具注册表校验 golden:`expected_tools` 拼错或过期会被判为无效样例(退出码 1),而不是静默按低命中继续评分。 +- 本次冻结**最小指标契约**,股票 guard、Codex `arguments_summary` 等扩展语义明确留给后续 PR(见文末「不在范围」)。 + +## 快速开始 + +```bash +# 跑单个样例(真实 LLM,依赖本地已配置的模型) +python evals/agent_trajectory/run_eval.py --sample 600519_technical + +# 跑全部样例,并输出结构化 JSON(按样例 id 键控) +python evals/agent_trajectory/run_eval.py --all --json-out eval_report.json +``` + +参数: + +| 参数 | 说明 | +| --- | --- | +| `--sample ID` / `--all` | 二选一必填:跑单个 golden 样例或全部 | +| `--golden-path PATH` | 自定义 golden JSON 路径(默认模块旁 `golden_samples.json`) | +| `--json-out PATH` | 写结构化 JSON 报告(`--all` 时为键控对象) | + +退出码:`0` 运行成功(含违规);`1` golden 加载(含 `expected_tools` 不在真实工具注册表)/ 样例选择 / 工具注册表加载失败 / 执行器构建(含 `AGENT_ARCH=multi` 拒绝)/ 运行失败(含执行器返回 `success=false`,如 provider 未配置、LLM 错误、超时、max_steps 耗尽、dashboard 解析失败);`2` 用法错误。 + +## 冻结的最小指标契约 + +对每条 `tool_calls_log`(runner 契约:每项含 `step / tool / arguments / success / duration / result_length / cached`,可选 `timeout` / `guarded`),只统计: + +| 指标 | 定义 | +| --- | --- | +| `expected_hit_rate` / `missing_expected` | 期望工具按**工具名**命中(本版不做股票维度判定);`expected_total` 为去重后的期望数 | +| `optional_tools_used` | 期望集合之外实际调用的工具;`allow_optional_tools=false` 时记为违规 | +| `redundant_calls` | 同一 (tool, args-key) 对在首次出现之后的每一次出现(不论成败)。args-key = `json.dumps(arguments, sort_keys=True, default=str)`,与运行时缓存键同思路 | +| `retries` | 紧跟**失败**之后重试同一 (tool, args-key) 对;`retries ⊆ redundant_calls`。成功会清除该对的失败态:`fail → success → success` 只计 1 次 retry(后一次 success 仅计冗余) | +| `failed_calls` | `success=false` 的条目数 | +| `cached_calls` | `cached=true` 的条目数(runner 语义:复用不可重试的失败结果) | +| `distinct_steps` / `max_steps_touched` | 日志 step 与 `AgentResult.total_steps` 取较大者(最后纯回答轮不产生工具调用,日志会低估);`max_steps_touched` 为 `max(step) >= allowed_max_steps` 的启发式 | + +## Golden 样例 schema + +`golden_samples.json` 是一个数组,字段: + +| 字段 | 类型 | 说明 | +| --- | --- | --- | +| `id` | string | 唯一样例 id(必填) | +| `task_description` | string | 交给执行器的任务文本(必填) | +| `stock_code` | string | 原样传入 runner context(`{"stock_code": ...}`);空串 = 无 context;不参与打分 | +| `expected_tools` | string[] | 期望工具名(必填,非空、无重复) | +| `allowed_max_steps` | int | 步数预算启发式(默认 10,>= 1) | +| `allow_optional_tools` | bool | 是否容忍期望外工具(默认 true) | + +校验:加载路径(`load_golden_samples`)直接拒绝非法样例;直接构造路径(`compute_trajectory_metrics`)以 validator 完全相同的措辞逐条上报违规,两条路径的契约按构造保持一致。`known_tool_names` 可注入真实工具注册表做成员校验(metrics 层自身不 import `src/`);`run_eval.py` 入口会自动注入真实工具注册表。 + +## JSON 报告 schema + +单个样例: + +```json +{ + "sample_id": "600519_technical", + "task_description": "…", + "stock_code": "600519", + "metrics": { "expected_hit_rate": …, "expected_total": …, "…": "… 共 11 个字段" }, + "violations": ["…"] +} +``` + +`--all --json-out` 时外层为 `{sample_id: <上述对象>}` 键控对象。 + +## 不在范围(后续 PR) + +- 股票维度命中判定与 guard 拦截语义(`guarded` / 越界调用违规) +- Codex App Server 的 `arguments_summary` 方言识别 +- 任何 `.env` / 运行时配置与 CI 门禁(本 PR 零 `src/` 改动,不影响现有分析流程) diff --git a/evals/agent_trajectory/__init__.py b/evals/agent_trajectory/__init__.py new file mode 100644 index 00000000000..c362965c2e8 --- /dev/null +++ b/evals/agent_trajectory/__init__.py @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +"""Agent trajectory evaluation package (Issue #1956). + +Pure-function metrics layer that scores a real ``tool_calls_log`` against +golden samples; the runnable entry point lives in ``run_eval.py``. +""" diff --git a/evals/agent_trajectory/golden_samples.json b/evals/agent_trajectory/golden_samples.json new file mode 100644 index 00000000000..a6e2270ff4d --- /dev/null +++ b/evals/agent_trajectory/golden_samples.json @@ -0,0 +1,18 @@ +[ + { + "id": "600519_technical", + "task_description": "分析贵州茅台(600519)近期技术面走势,输出趋势判断", + "stock_code": "600519", + "expected_tools": ["get_realtime_quote", "get_daily_history", "analyze_trend"], + "allowed_max_steps": 8, + "allow_optional_tools": true + }, + { + "id": "000001_core_data_strict", + "task_description": "获取平安银行(000001)核心行情数据,不做扩展检索", + "stock_code": "000001", + "expected_tools": ["get_realtime_quote", "get_daily_history"], + "allowed_max_steps": 6, + "allow_optional_tools": false + } +] diff --git a/evals/agent_trajectory/metrics.py b/evals/agent_trajectory/metrics.py new file mode 100644 index 00000000000..b3365ca1784 --- /dev/null +++ b/evals/agent_trajectory/metrics.py @@ -0,0 +1,421 @@ +# -*- coding: utf-8 -*- +"""Pure-function trajectory metrics for agent evaluation (Issue #1956). + +This module computes quality metrics for an agent execution trajectory from its +``tool_calls_log`` (see ``src/agent/runner.py`` for the producer contract): + +* each entry carries ``step / tool / arguments / success / duration / + result_length / cached`` and optionally ``timeout`` or ``guarded`` fields; +* entries with missing optional fields are tolerated with defaults. + +The scoring functions in this module are pure: ``compute_trajectory_metrics``, +``format_text_report`` and ``validate_golden_sample`` consume plain data (a log +list and a ``GoldenSample``) and never touch the filesystem, network, or LLM. +The one exception is the loader ``load_golden_samples``, which reads the golden +JSON file from disk. This keeps the metrics layer deterministic, unit-testable +without an API key, and free of ``src/`` imports — it can score trajectories +from any source. The runnable entry point that produces real trajectories and +feeds them into this layer lives in ``run_eval.py``. + +Both entry paths enforce the same golden-sample structure contract: +``validate_golden_sample`` (the loader path) rejects malformed samples +outright, while ``compute_trajectory_metrics`` (the direct-construction path) +excludes the invalid parts from scoring, reports its own scoring-level +violations with the validator's wording, and finally appends *every* issue +``validate_golden_sample`` reports, verbatim and deduplicated — a caller who +builds a ``GoldenSample`` by hand can never get a silently relaxed result, +and a new validator check applies to direct scoring automatically (see the +compute docstring for the exact mapping). + +Idempotency key contract +------------------------ +Two log entries are considered "the same call" when their ``tool`` names are +equal and their serialized ``arguments`` are equal. Arguments may contain +unhashable values (dict / list), so the key is built with +``json.dumps(arguments, sort_keys=True, default=str)`` — a *stable string*, +not a hash. Do not replace this with ``tuple(arguments)`` or ``repr()``: +insertion order or collection type would then change call identity and corrupt +redundancy / retry counts. + +Metric semantics +---------------- +* ``redundant_calls``: every occurrence of a (tool, args-key) pair beyond its + first — regardless of success. +* ``retries``: occurrences that follow a *failed* occurrence of the same pair + (i.e. "tried again after a failure"). ``retries`` is a subset of + ``redundant_calls``; repeats after success count as redundant but not retry, + and a success clears the pair's failure state — so ``fail -> success -> + success`` counts exactly one retry, not two. +* ``failed_calls``: entries with ``success=False``. +* ``cached_calls``: entries with ``cached=True`` (runner semantics: reuse of a + non-retriable failure result). +* ``max_steps_touched``: the log does not carry ``max_steps`` itself, so this + is the conservative heuristic ``max(step) >= golden.allowed_max_steps`` — + a proxy for "the run reached the step budget", not proof of the loop + exhausting it. When ``total_steps`` is supplied (see + :func:`compute_trajectory_metrics`), the larger of ``total_steps`` and the + log-derived step is compared instead — the final answer round consumes a + step but produces no tool call, so the log alone understates consumption. + +Scope +----- +This is the frozen minimal contract requested for the close-and-rebuild PR +(Refs #1956): tool hit, redundancy / caching, failure / retry and total +steps / max_steps only. Stock guard and Codex ``arguments_summary`` +semantics are out of scope here and belong in follow-up PRs (see +``docs/agent-trajectory-eval.md``). +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, fields +from pathlib import Path +from typing import Any, Dict, Iterable, List, Optional + + +@dataclass +class GoldenSample: + """Expected trajectory for one evaluation task. + + ``expected_tools`` are the tool names the agent should call; tools outside + this set are tolerated only when ``allow_optional_tools`` is true. + ``stock_code`` is carried verbatim into the runner context by + ``run_eval.py`` (empty string = no stock context) and does not take part + in scoring. + """ + + id: str + task_description: str + expected_tools: List[str] + stock_code: str = "" + allowed_max_steps: int = 10 + allow_optional_tools: bool = True + + +@dataclass +class TrajectoryMetrics: + """All metrics computed for one trajectory against one golden sample.""" + + expected_hit_rate: float + expected_total: int + missing_expected: List[str] + optional_tools_used: List[str] + redundant_calls: int + cached_calls: int + failed_calls: int + retries: int + distinct_steps: int + max_steps_touched: bool + violations: List[str] + + +def _args_key(arguments: Any) -> str: + """Return a stable idempotency key for tool-call arguments (see module docstring). + + ``None`` (an entry without an ``arguments`` payload) is serialized as an + empty object, so arguments-less calls of one tool share a single identity. + Non-dict payloads are serialized as-is. + """ + if arguments is None: + arguments = {} + return json.dumps(arguments, ensure_ascii=False, sort_keys=True, default=str) + + +def _entry_arguments(entry: Dict[str, Any]) -> Any: + """Extract the idempotent argument payload from a log entry. + + Runner entries carry ``arguments`` (a dict); entries without the field + key as ``None``, which ``_args_key`` treats as an empty object. + """ + return entry.get("arguments") + + +def _coerce_step(value: Any) -> int: + """Coerce a log entry's ``step`` to a non-negative int (missing/odd -> 0).""" + try: + step = int(value) + except (TypeError, ValueError): + return 0 + return step if step > 0 else 0 + + +def compute_trajectory_metrics( + log: List[Dict[str, Any]], + golden: GoldenSample, + total_steps: Optional[int] = None, +) -> TrajectoryMetrics: + """Compute all trajectory metrics from a ``tool_calls_log`` and a golden sample. + + ``total_steps`` optionally carries the number of loop rounds the run + actually consumed (``AgentResult.total_steps``), which includes the + final plain-answer round that produces no tool call. When it is larger + than the log-derived step count it is used for ``distinct_steps`` and the + ``max_steps_touched`` heuristic; otherwise the log alone decides, and the + default ``None`` keeps the log-only behaviour. + + Direct construction of a hand-edited ``GoldenSample`` is held to the same + structure contract as :func:`validate_golden_sample` on the loader path: + malformed parts are excluded from scoring instead of silently reshaping + the result, scoring-level violations are reported with the validator's + wording, and every issue the validator reports is appended verbatim + (deduplicated) before returning. Malformed ``expected_tools`` elements — + non-strings, empty strings and whitespace-only strings, the validator's + exact predicate — are dropped with an explicit violation, and a + non-positive ``allowed_max_steps`` is reported with the validator's + wording (and the budget assertion stays disabled). + """ + used_tools: List[str] = [] + key_counts: Dict[tuple, int] = {} + key_failed_seen: Dict[tuple, bool] = {} + key_retries: Dict[tuple, int] = {} + # Extract the expected tool list before scanning entries. Malformed + # elements are not silently dropped: they are reported as a violation + # below (mirroring validate_golden_sample, which rejects them at load + # time) and only the valid names take part in scoring. + if isinstance(golden.expected_tools, list): + # Same element predicate as validate_golden_sample(): whitespace-only + # strings count as malformed too, not just falsy ones. + expected_tools_malformed = [t for t in golden.expected_tools if not isinstance(t, str) or not t.strip()] + expected = [t for t in golden.expected_tools if isinstance(t, str) and t.strip()] + else: + # Defend against hand-edited samples passing a bare string: + # validation rejects it at load time, but scoring must not misparse + # it into per-character tool names either. + expected_tools_malformed = [] + expected = [] + # A hand-edited sample may repeat a tool name; normalize to first + # occurrences before scoring so the hit rate cannot be inflated + # (["quote", "quote"] with one quote call must read 1/2, not 2/3). + expected_dupes = len(set(expected)) != len(expected) + if expected_dupes: + expected = list(dict.fromkeys(expected)) + failed_calls = 0 + cached_calls = 0 + redundant_calls = 0 + distinct_steps = 0 + max_step = 0 + seen_steps: set = set() + + for entry in log: + if not isinstance(entry, dict): + continue + tool = entry.get("tool") or "" + success = bool(entry.get("success", True)) + if tool and tool not in used_tools: + used_tools.append(tool) + step = _coerce_step(entry.get("step")) + if step and step not in seen_steps: + seen_steps.add(step) + distinct_steps += 1 + max_step = max(max_step, step) + if not success: + failed_calls += 1 + if entry.get("cached"): + cached_calls += 1 + + key = (tool, _args_key(_entry_arguments(entry))) + if key_counts.get(key, 0): + redundant_calls += 1 + key_counts[key] = key_counts.get(key, 0) + 1 + # An occurrence is a retry only when the same call already failed + # before it (see module docstring for the precise contract). + if key_failed_seen.get(key): + key_retries[key] = key_retries.get(key, 0) + 1 + # A success clears the failure state: repeats after a recovery count + # as redundant only, not as further retries. + key_failed_seen[key] = not success + + retries = sum(key_retries.values()) + violations: List[str] = [] + + if expected_dupes: + violations.append("expected_tools must not contain duplicate names") + if expected_tools_malformed: + violations.append("expected_tools must contain only non-empty strings") + missing_expected = [t for t in expected if t not in used_tools] + expected_hit_rate = (len(expected) - len(missing_expected)) / len(expected) if expected else 0.0 + optional_tools_used = [t for t in used_tools if t not in expected] + + if not isinstance(golden.expected_tools, list): + violations.append("expected_tools must be a list of tool names") + elif not golden.expected_tools: + violations.append("expected_tools must be a non-empty list") + + # Malformed golden samples must not crash scoring nor flip semantics: + # a truthy string like "false" must not silently turn a strict sample + # permissive, and a non-integer step limit must not crash the comparison. + optional_allowed = golden.allow_optional_tools + if not isinstance(optional_allowed, bool): + violations.append("allow_optional_tools must be a boolean") + optional_allowed = False + if optional_tools_used and not optional_allowed: + violations.append(f"optional tools used but not allowed: {', '.join(optional_tools_used)}") + + # The final answer round consumes a step but produces no tool call, so + # when the caller supplies the run's real total it may exceed the log. + total = 0 + if total_steps is not None: + try: + total = int(total_steps) + except (TypeError, ValueError): + total = 0 + total = total if total > 0 else 0 + distinct_steps = max(distinct_steps, total) + max_step = max(max_step, total) + + limit = golden.allowed_max_steps + if isinstance(limit, bool) or not isinstance(limit, int): + violations.append("allowed_max_steps must be an integer") + limit = 0 + elif limit < 1: + # Validator wording for the same field: a non-positive limit must + # not silently disable the budget assertion on the direct-score path. + violations.append("allowed_max_steps must be >= 1") + limit = 0 + max_steps_touched = bool(max_step and limit > 0 and max_step >= limit) + if max_steps_touched: + violations.append(f"trajectory reached allowed_max_steps ({golden.allowed_max_steps})") + + # The direct-score path surfaces the validator's complete structure + # contract, not only the checks scoring itself depends on: every issue + # validate_golden_sample() reports is appended verbatim (deduplicated + # against the inline violations above), so a hand-built malformed golden + # can never score as valid — and a new validator check applies to direct + # scoring automatically. The two entry paths stay aligned by + # construction instead of by convention. + for issue in validate_golden_sample(golden): + if issue not in violations: + violations.append(issue) + + return TrajectoryMetrics( + expected_hit_rate=expected_hit_rate, + expected_total=len(expected), + missing_expected=missing_expected, + optional_tools_used=optional_tools_used, + redundant_calls=redundant_calls, + cached_calls=cached_calls, + failed_calls=failed_calls, + retries=retries, + distinct_steps=distinct_steps, + max_steps_touched=max_steps_touched, + violations=violations, + ) + + +def format_text_report(m: TrajectoryMetrics) -> str: + """Render metrics as a deterministic, human-readable text report.""" + hit_count = max(0, m.expected_total - len(m.missing_expected)) + hit_percent = f"{m.expected_hit_rate * 100:.1f}%" + missing = ", ".join(m.missing_expected) if m.missing_expected else "无" + optional = ", ".join(m.optional_tools_used) if m.optional_tools_used else "无" + violations = "; ".join(m.violations) if m.violations else "无" + max_steps_label = "是" if m.max_steps_touched else "否" + return ( + "============================================\n" + "Agent Trajectory 评估报告\n" + "============================================\n" + f"- 期望工具命中: {hit_count}/{m.expected_total} ({hit_percent})\n" + f"- 缺失期望工具: {missing}\n" + f"- 期望外工具: {optional}\n" + f"- 冗余调用: {m.redundant_calls} | 缓存调用: {m.cached_calls} | " + f"失败调用: {m.failed_calls} | 重试: {m.retries}\n" + f"- 消耗步数: {m.distinct_steps} (触碰 max_steps: {max_steps_label})\n" + f"- 违规项: {violations}\n" + ) + + +def load_golden_samples( + path: Optional[str] = None, + known_tool_names: Optional[Iterable[str]] = None, +) -> List[GoldenSample]: + """Load golden samples from ``path`` (default: ``golden_samples.json`` next to this module). + + Raises ``FileNotFoundError`` when the file is missing and ``ValueError`` on + malformed JSON or structural issues (see :func:`validate_golden_sample`). + Unknown extra JSON keys are ignored so the file can carry forward-looking + metadata without breaking the loader. + """ + if path is None: + path = str(Path(__file__).with_name("golden_samples.json")) + data = json.loads(Path(path).read_text(encoding="utf-8")) + if not isinstance(data, list): + raise ValueError(f"golden samples file must contain a JSON list, got {type(data).__name__}") + + # Materialize once before the loop: a one-shot generator must survive the + # validation of every sample, not just the first. + known = set(known_tool_names) if known_tool_names is not None else None + golden_fields = {f.name for f in fields(GoldenSample)} + samples: List[GoldenSample] = [] + seen_ids: set = set() + for index, item in enumerate(data): + if not isinstance(item, dict): + raise ValueError(f"sample #{index} must be a JSON object, got {type(item).__name__}") + try: + sample = GoldenSample(**{k: v for k, v in item.items() if k in golden_fields}) + except TypeError as exc: + raise ValueError(f"sample #{index} has invalid fields: {exc}") from exc + # Structural validation runs before duplicate detection so that a + # mistyped (possibly unhashable) id is rejected as a ValueError here + # instead of crashing the membership check below. + issues = validate_golden_sample(sample, known) + if issues: + raise ValueError(f"sample '{sample.id}': " + "; ".join(issues)) + if sample.id in seen_ids: + raise ValueError(f"duplicate sample id: {sample.id}") + seen_ids.add(sample.id) + samples.append(sample) + return samples + + +def validate_golden_sample( + sample: GoldenSample, + known_tool_names: Optional[Iterable[str]] = None, +) -> List[str]: + """Return a list of structural issues for ``sample``; empty list means valid. + + When ``known_tool_names`` is provided, ``expected_tools`` must be a subset + of it; the caller supplies the authoritative registry names (this module + deliberately does not import ``src/``). Any ``Iterable[str]`` is accepted + — including one-shot generators — and materialized once internally, so + membership checks never consume the caller's iterable. + + Field *types* are part of the structural contract — hand-edited golden + JSON must fail with a clear message instead of crashing or silently + passing: text fields must be strings, ``expected_tools`` must be a list of + non-empty, duplicate-free names, ``allowed_max_steps`` an integer >= 1 and + ``allow_optional_tools`` a boolean. ``stock_code`` must be a string; the + empty string is the documented default ("no stock context", see + ``run_eval.py``) and passes, while whitespace-only values fail. + """ + issues: List[str] = [] + known = set(known_tool_names) if known_tool_names is not None else None + if not isinstance(sample.id, str) or not sample.id.strip(): + issues.append("id must be a non-empty string") + if not isinstance(sample.task_description, str) or not sample.task_description.strip(): + issues.append("task_description must be a non-empty string") + if not isinstance(sample.stock_code, str): + issues.append("stock_code must be a string") + elif sample.stock_code != sample.stock_code.strip(): + issues.append("stock_code must not contain leading or trailing whitespace") + if not isinstance(sample.expected_tools, list): + issues.append("expected_tools must be a list of tool names") + elif not sample.expected_tools: + issues.append("expected_tools must be a non-empty list") + elif any(not isinstance(t, str) or not t.strip() for t in sample.expected_tools): + issues.append("expected_tools must contain only non-empty strings") + elif len(set(sample.expected_tools)) != len(sample.expected_tools): + issues.append("expected_tools must not contain duplicate names") + elif known is not None: + # Only reachable when expected_tools is a non-empty list of non-empty + # strings, so malformed values can never crash the membership check. + unknown = [t for t in sample.expected_tools if t not in known] + if unknown: + issues.append(f"unknown expected_tools: {', '.join(unknown)}") + if isinstance(sample.allowed_max_steps, bool) or not isinstance(sample.allowed_max_steps, int): + issues.append("allowed_max_steps must be an integer") + elif sample.allowed_max_steps < 1: + issues.append("allowed_max_steps must be >= 1") + if not isinstance(sample.allow_optional_tools, bool): + issues.append("allow_optional_tools must be a boolean") + return issues diff --git a/evals/agent_trajectory/run_eval.py b/evals/agent_trajectory/run_eval.py new file mode 100644 index 00000000000..28dd9cfda6f --- /dev/null +++ b/evals/agent_trajectory/run_eval.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""Run one agent-trajectory eval sample against the real agent executor (Issue #1956). + +Consumes a real ``tool_calls_log + AgentResult`` produced by +``src.agent.factory.build_agent_executor`` (the same capture hook the +analysis pipeline uses in ``src/core/pipeline.py``), scores it with the +pure metrics layer and emits a short human-readable text summary plus an +optional structured JSON report. + +The eval is a *reporter*, not a gate: metric violations lower the report, +they never fail the process. Exit codes: 0 = ran (violations included), +1 = load (golden / tool registry) / build / run failure, 2 = usage error. + +The entry supports the single-agent runner only. When ``AGENT_ARCH=multi`` +the factory returns the orchestrator whose trajectories use per-stage local +step numbers, which breaks the single-runner metric contract, so the entry +rejects that arch up front with exit code 1. Golden samples are validated +against the real tool registry before running, so misspelled or stale +``expected_tools`` fail as invalid samples instead of scoring as low hit +rate. + +Usage: + python evals/agent_trajectory/run_eval.py --sample 600519_technical + python evals/agent_trajectory/run_eval.py --all --json-out eval_report.json +""" + +from __future__ import annotations + +import argparse +import json +import sys +from dataclasses import asdict +from pathlib import Path +from typing import Any, Dict, List, Optional + +# Add the project root to sys.path so the script also works as +# `python evals/agent_trajectory/run_eval.py` from anywhere. +REPO_ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(REPO_ROOT)) + +from evals.agent_trajectory.metrics import ( + GoldenSample, + TrajectoryMetrics, + compute_trajectory_metrics, + format_text_report, + load_golden_samples, +) + + +def _build_report(sample: GoldenSample, metrics: TrajectoryMetrics) -> Dict[str, Any]: + """Structured JSON report for one sample (schema in docs/agent-trajectory-eval.md).""" + return { + "sample_id": sample.id, + "task_description": sample.task_description, + "stock_code": sample.stock_code, + "metrics": asdict(metrics), + "violations": metrics.violations, + } + + +def _write_json(path: Optional[Path], payload: Any) -> None: + """Write ``payload`` as indented UTF-8 JSON (trailing newline).""" + if path is None: + return + Path(path).write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + + +_KNOWN_TOOL_NAMES: Optional[set] = None + + +def _check_agent_arch() -> None: + """Reject multi-agent arch up front (mirrors the factory's own decision). + + ``src.agent.factory.build_agent_executor`` returns the orchestrator when + ``config.agent_arch == "multi"``; its trajectories concatenate per-stage + logs with local step numbering and set ``total_steps`` to the stage count, + which the single-runner metric contract cannot interpret. Fail fast + instead of scoring a distorted trajectory. + """ + from src.config import get_config + + arch = getattr(get_config(), "agent_arch", "single") + if arch == "multi": + raise RuntimeError( + "AGENT_ARCH=multi is not supported by this minimal eval: " + "orchestrator trajectories use per-stage local step numbers, " + "which break the single-runner metric contract" + ) + + +def _known_tool_names(): + """Authoritative tool names from the real registry modules (lazy, cached). + + The metrics layer deliberately does not import ``src/``; the entry point + supplies these names so ``load_golden_samples`` rejects misspelled or + stale ``expected_tools`` instead of scoring them as low hit rate. + """ + global _KNOWN_TOOL_NAMES + if _KNOWN_TOOL_NAMES is None: + from src.agent.tools.analysis_tools import ALL_ANALYSIS_TOOLS + from src.agent.tools.backtest_tools import ALL_BACKTEST_TOOLS + from src.agent.tools.data_tools import ALL_DATA_TOOLS + from src.agent.tools.market_tools import ALL_MARKET_TOOLS + from src.agent.tools.search_tools import ALL_SEARCH_TOOLS + + all_tools = ALL_DATA_TOOLS + ALL_ANALYSIS_TOOLS + ALL_SEARCH_TOOLS + ALL_MARKET_TOOLS + ALL_BACKTEST_TOOLS + _KNOWN_TOOL_NAMES = {tool_def.name for tool_def in all_tools} + return _KNOWN_TOOL_NAMES + + +def _build_executor(): + """Build the real agent executor (lazy import so tests can monkeypatch this).""" + _check_agent_arch() + from src.agent.factory import build_agent_executor + + return build_agent_executor() + + +def run_sample(executor, sample: GoldenSample, *, json_out: Optional[Path] = None) -> TrajectoryMetrics: + """Run one golden sample against a duck-typed agent executor and score it. + + ``executor`` only needs ``run(task, context=None) -> result`` where + ``result`` carries ``tool_calls_log`` (and optionally ``total_steps``) — + the same shape as ``src.agent.executor.AgentResult``. The production + executor is built lazily by :func:`_build_executor`; tests may pass a + stub. A result carrying an explicit ``success=False`` is a run failure + (the executor reported a provider / timeout / budget error) and raises + ``RuntimeError`` before any scoring; duck-typed results without a + ``success`` attribute are treated as successful. The text summary is + always printed to stdout; ``json_out`` additionally writes the + structured report for this sample. + """ + context: Optional[Dict[str, Any]] = None + if sample.stock_code: + context = {"stock_code": sample.stock_code} + result = executor.run(sample.task_description, context=context) + if getattr(result, "success", None) is False: + error = getattr(result, "error", None) + raise RuntimeError(f"agent run failed (success=false): {error or 'no error detail'}") + log = getattr(result, "tool_calls_log", None) or [] + total_steps = getattr(result, "total_steps", None) + metrics = compute_trajectory_metrics(log, sample, total_steps=total_steps) + print(format_text_report(metrics)) + _write_json(json_out, _build_report(sample, metrics)) + return metrics + + +def main(argv=None) -> int: + """Run one golden sample (--sample ID) or every sample (--all).""" + parser = argparse.ArgumentParser( + description="Run one agent-trajectory eval sample against the real agent executor (Issue #1956).", + ) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("--sample", metavar="ID", help="run the golden sample with this id") + group.add_argument("--all", action="store_true", help="run every golden sample") + parser.add_argument( + "--golden-path", + default=None, + help="path to golden_samples.json (default: the checked-in file next to this module)", + ) + parser.add_argument( + "--json-out", + default=None, + help="write a structured JSON report to this path (--all writes a keyed object)", + ) + args = parser.parse_args(argv) + + try: + known = _known_tool_names() + except Exception as exc: + print(f"error: failed to load tool registry for golden validation: {exc}", file=sys.stderr) + return 1 + + try: + samples = load_golden_samples(path=args.golden_path, known_tool_names=known) + except (OSError, ValueError) as exc: + print(f"error: failed to load golden samples: {exc}", file=sys.stderr) + return 1 + + if args.sample: + selected = next((s for s in samples if s.id == args.sample), None) + if selected is None: + available = ", ".join(s.id for s in samples) if samples else "(none)" + print(f"error: unknown sample id '{args.sample}'; available: {available}", file=sys.stderr) + return 1 + samples = [selected] + + try: + executor = _build_executor() + except Exception as exc: # pragma: no cover - exercised via monkeypatched failure + print(f"error: failed to build agent executor: {exc}", file=sys.stderr) + return 1 + + reports: Dict[str, Dict[str, Any]] = {} + for sample in samples: + print(f"[eval] sample: {sample.id} | task: {sample.task_description}") + try: + metrics = run_sample(executor, sample) + except Exception as exc: + print(f"error: sample '{sample.id}' failed: {exc}", file=sys.stderr) + return 1 + reports[sample.id] = _build_report(sample, metrics) + + if args.json_out: + _write_json(Path(args.json_out), reports if args.all else reports[args.sample]) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/fixtures/agent_trajectory/negative_600519_technical.json b/tests/fixtures/agent_trajectory/negative_600519_technical.json new file mode 100644 index 00000000000..25fff4430ab --- /dev/null +++ b/tests/fixtures/agent_trajectory/negative_600519_technical.json @@ -0,0 +1,41 @@ +{ + "total_steps": 8, + "tool_calls_log": [ + { + "step": 1, + "tool": "get_realtime_quote", + "arguments": {"stock_code": "600519"}, + "success": true, + "duration": 0.5, + "result_length": 100, + "cached": false + }, + { + "step": 2, + "tool": "get_realtime_quote", + "arguments": {"stock_code": "600519"}, + "success": true, + "duration": 0.6, + "result_length": 110, + "cached": false + }, + { + "step": 3, + "tool": "get_daily_history", + "arguments": {"stock_code": "600519", "days": 30}, + "success": false, + "duration": 1.5, + "result_length": 0, + "cached": true + }, + { + "step": 4, + "tool": "search_stock_news", + "arguments": {"query": "贵州茅台"}, + "success": true, + "duration": 2.0, + "result_length": 300, + "cached": false + } + ] +} diff --git a/tests/fixtures/agent_trajectory/positive_600519_technical.json b/tests/fixtures/agent_trajectory/positive_600519_technical.json new file mode 100644 index 00000000000..852174142ae --- /dev/null +++ b/tests/fixtures/agent_trajectory/positive_600519_technical.json @@ -0,0 +1,41 @@ +{ + "total_steps": 5, + "tool_calls_log": [ + { + "step": 1, + "tool": "get_realtime_quote", + "arguments": {"stock_code": "600519"}, + "success": true, + "duration": 0.5, + "result_length": 100, + "cached": false + }, + { + "step": 2, + "tool": "get_daily_history", + "arguments": {"stock_code": "600519", "days": 30}, + "success": true, + "duration": 0.8, + "result_length": 200, + "cached": false + }, + { + "step": 3, + "tool": "analyze_trend", + "arguments": {"stock_code": "600519"}, + "success": true, + "duration": 1.2, + "result_length": 150, + "cached": false + }, + { + "step": 4, + "tool": "search_stock_news", + "arguments": {"query": "贵州茅台"}, + "success": true, + "duration": 2.0, + "result_length": 300, + "cached": false + } + ] +} diff --git a/tests/fixtures/agent_trajectory/retry_000001_core_data_strict.json b/tests/fixtures/agent_trajectory/retry_000001_core_data_strict.json new file mode 100644 index 00000000000..897b44f8a15 --- /dev/null +++ b/tests/fixtures/agent_trajectory/retry_000001_core_data_strict.json @@ -0,0 +1,41 @@ +{ + "total_steps": 5, + "tool_calls_log": [ + { + "step": 1, + "tool": "get_realtime_quote", + "arguments": {"stock_code": "000001"}, + "success": true, + "duration": 0.5, + "result_length": 100, + "cached": false + }, + { + "step": 2, + "tool": "get_daily_history", + "arguments": {"stock_code": "000001", "days": 60}, + "success": false, + "duration": 1.2, + "result_length": 0, + "cached": false + }, + { + "step": 3, + "tool": "get_daily_history", + "arguments": {"stock_code": "000001", "days": 60}, + "success": true, + "duration": 1.3, + "result_length": 250, + "cached": false + }, + { + "step": 4, + "tool": "get_daily_history", + "arguments": {"stock_code": "000001", "days": 60}, + "success": true, + "duration": 0.4, + "result_length": 250, + "cached": false + } + ] +} diff --git a/tests/test_agent_trajectory_metrics.py b/tests/test_agent_trajectory_metrics.py new file mode 100644 index 00000000000..9e1a7a31c77 --- /dev/null +++ b/tests/test_agent_trajectory_metrics.py @@ -0,0 +1,716 @@ +# -*- coding: utf-8 -*- +"""Unit tests for the agent trajectory evaluation metrics (Issue #1956). + +All trajectories are synthetic ``tool_calls_log`` lists — no LLM, no network. +The golden-samples-file tests verify that the checked-in ``golden_samples.json`` +stays structurally valid and that every ``expected_tools`` entry exists in the +repository's real tool registry (imported lazily so the metrics-only sections +run even without ``src/`` importable). +""" + +import json + +import pytest + +from evals.agent_trajectory.metrics import ( + GoldenSample, + TrajectoryMetrics, + _args_key, + compute_trajectory_metrics, + format_text_report, + load_golden_samples, + validate_golden_sample, +) + + +def _entry(tool="get_realtime_quote", arguments=None, step=1, success=True, **extra): + """Build a runner-shaped ``tool_calls_log`` entry with sensible defaults.""" + entry = { + "step": step, + "tool": tool, + "arguments": arguments if arguments is not None else {"stock_code": "600519"}, + "success": success, + "duration": 0.5, + "result_length": 100, + "cached": False, + } + entry.update(extra) + return entry + + +def _golden(**overrides): + values = dict( + id="600519_technical", + task_description="分析贵州茅台近期技术面走势", + stock_code="600519", + expected_tools=["get_realtime_quote", "get_daily_history", "analyze_trend"], + allowed_max_steps=8, + allow_optional_tools=True, + ) + values.update(overrides) + return GoldenSample(**values) + + +def _metrics(**overrides): + values = dict( + expected_hit_rate=2 / 3, + expected_total=3, + missing_expected=["analyze_trend"], + optional_tools_used=[], + redundant_calls=0, + cached_calls=0, + failed_calls=0, + retries=0, + distinct_steps=3, + max_steps_touched=False, + violations=[], + ) + values.update(overrides) + return TrajectoryMetrics(**values) + + +# --------------------------------------------------------------------------- +# 1. Args-key stability +# --------------------------------------------------------------------------- +class TestArgsKey: + def test_key_stable_across_key_order_and_nested_unhashable(self): + a = {"b": [1, 2], "a": {"x": {"y": 1}}} + b = {"a": {"x": {"y": 1}}, "b": [1, 2]} + assert _args_key(a) == _args_key(b) + + def test_key_differs_for_different_arguments(self): + assert _args_key({"stock_code": "600519"}) != _args_key({"stock_code": "000001"}) + + def test_none_arguments_use_empty_object(self): + assert _args_key(None) == json.dumps({}) + + def test_non_dict_arguments_serialized(self): + assert _args_key(["600519"]) == '["600519"]' + + +# --------------------------------------------------------------------------- +# 2. Hit rate / expected & optional tools +# --------------------------------------------------------------------------- +class TestComputeMetricsHitRate: + @staticmethod + def _two_of_three_log(): + return [ + _entry(tool="get_realtime_quote", step=1), + _entry(tool="get_daily_history", step=2), + _entry(tool="search_stock_news", step=3), + ] + + def test_hit_rate_missing_and_optional(self): + m = compute_trajectory_metrics(self._two_of_three_log(), _golden()) + assert m.expected_hit_rate == pytest.approx(2 / 3) + assert m.missing_expected == ["analyze_trend"] + assert m.optional_tools_used == ["search_stock_news"] + assert m.violations == [] + + def test_optional_tools_not_allowed_produces_violation(self): + m = compute_trajectory_metrics(self._two_of_three_log(), _golden(allow_optional_tools=False)) + assert m.violations == ["optional tools used but not allowed: search_stock_news"] + assert m.expected_hit_rate == pytest.approx(2 / 3) + + def test_duplicate_tool_calls_still_full_hit(self): + log = [ + _entry(tool="get_realtime_quote", arguments={"stock_code": "600519"}, step=1), + _entry(tool="get_realtime_quote", arguments={"stock_code": "000001"}, step=2), + ] + m = compute_trajectory_metrics(log, _golden(expected_tools=["get_realtime_quote"])) + assert m.expected_hit_rate == 1.0 + assert m.missing_expected == [] + + def test_empty_log_yields_zero_metrics(self): + m = compute_trajectory_metrics([], _golden()) + assert m.expected_hit_rate == 0.0 + assert m.expected_total == 3 + assert m.missing_expected == ["get_realtime_quote", "get_daily_history", "analyze_trend"] + assert m.redundant_calls == 0 and m.cached_calls == 0 and m.failed_calls == 0 + assert m.retries == 0 and m.distinct_steps == 0 + assert m.max_steps_touched is False + assert m.violations == [] + + def test_non_dict_entries_ignored(self): + log = ["garbage", None, _entry(tool="get_realtime_quote", step=1)] + m = compute_trajectory_metrics(log, _golden(expected_tools=["get_realtime_quote"])) + assert m.expected_hit_rate == 1.0 + assert m.distinct_steps == 1 + + def test_empty_expected_tools_yields_zero_hit_and_violation(self): + m = compute_trajectory_metrics([_entry()], _golden(expected_tools=[])) + assert m.expected_hit_rate == 0.0 + assert "expected_tools must be a non-empty list" in m.violations + + def test_string_expected_tools_scored_as_empty_not_as_characters(self): + m = compute_trajectory_metrics([_entry()], _golden(expected_tools="get_realtime_quote")) + assert m.expected_hit_rate == 0.0 + assert m.expected_total == 0 + assert "expected_tools must be a list of tool names" in m.violations + + def test_non_bool_allow_optional_tools_scores_strictly(self): + log = [ + _entry(tool="get_realtime_quote", step=1), + _entry(tool="search_stock_news", step=2), + ] + m = compute_trajectory_metrics( + log, + _golden(expected_tools=["get_realtime_quote"], allow_optional_tools="false"), + ) + assert "allow_optional_tools must be a boolean" in m.violations + assert "optional tools used but not allowed: search_stock_news" in m.violations + + def test_duplicate_expected_tools_scored_as_unique_names(self): + # Regression: ["quote", "quote", "history"] with a single quote call + # must read 1/2, not 2/3. + golden = _golden( + expected_tools=[ + "get_realtime_quote", + "get_realtime_quote", + "get_daily_history", + ], + ) + m = compute_trajectory_metrics([_entry(tool="get_realtime_quote")], golden) + assert m.expected_total == 2 + assert m.expected_hit_rate == pytest.approx(0.5) + assert m.missing_expected == ["get_daily_history"] + assert "expected_tools must not contain duplicate names" in m.violations + + +# --------------------------------------------------------------------------- +# 2b. Direct-construction path: same structure contract as the loader +# --------------------------------------------------------------------------- +class TestDirectConstructionContract: + def test_malformed_expected_tools_elements_are_reported(self): + # Review counter-example: ['get_realtime_quote', ''] must not + # silently collapse into a one-tool golden — the malformed element + # is reported, only valid names take part in scoring. Whitespace- + # only elements follow the validator's predicate (t.strip()). + log = [_entry(tool="get_realtime_quote", arguments={"stock_code": "600519"})] + for malformed in (["get_realtime_quote", ""], ["get_realtime_quote", 1]): + m = compute_trajectory_metrics(log, _golden(expected_tools=malformed)) + assert m.expected_hit_rate == 1.0 + assert "expected_tools must contain only non-empty strings" in m.violations + + def test_whitespace_only_expected_tool_does_not_pollute_scoring(self): + # Review counter-example: ' ' must not enter the hit-rate + # denominator nor show up as a missing tool — it is malformed. + log = [_entry(tool="get_realtime_quote", arguments={"stock_code": "600519"})] + m = compute_trajectory_metrics(log, _golden(expected_tools=["get_realtime_quote", " "])) + assert m.expected_total == 1 + assert m.expected_hit_rate == 1.0 + assert m.missing_expected == [] + assert "expected_tools must contain only non-empty strings" in m.violations + + def test_non_positive_allowed_max_steps_reported_in_direct_score(self): + # Review counter-example: allowed_max_steps=0 / -3 must report the + # validator's wording instead of silently disabling the budget + # assertion, no matter how many steps the trajectory takes. + log = [_entry(tool="get_realtime_quote", arguments={"stock_code": "600519"}, step=s) for s in range(1, 100)] + for limit in (0, -3): + m = compute_trajectory_metrics(log, _golden(allowed_max_steps=limit)) + assert "allowed_max_steps must be >= 1" in m.violations + assert m.max_steps_touched is False + + def test_direct_score_mirrors_validator_structure_contract(self): + # The owner-requested parity: for each malformed golden shape the + # validator rejects, the direct-score path must surface the same + # issue wording in its violations. + log = [_entry(tool="get_realtime_quote", arguments={"stock_code": "600519"})] + cases = [ + (dict(expected_tools=["get_realtime_quote", " "]), "expected_tools must contain only non-empty strings"), + (dict(expected_tools=["get_realtime_quote", ""]), "expected_tools must contain only non-empty strings"), + (dict(allowed_max_steps=0), "allowed_max_steps must be >= 1"), + (dict(allowed_max_steps=-3), "allowed_max_steps must be >= 1"), + (dict(allow_optional_tools="false"), "allow_optional_tools must be a boolean"), + (dict(id=[]), "id must be a non-empty string"), + (dict(task_description=None), "task_description must be a non-empty string"), + (dict(stock_code=None), "stock_code must be a string"), + (dict(stock_code=" "), "stock_code must not contain leading or trailing whitespace"), + ] + for overrides, issue in cases: + golden = _golden(**overrides) + validator_issues = validate_golden_sample(golden) + assert any(issue in i for i in validator_issues), (issue, overrides, validator_issues) + m = compute_trajectory_metrics(log, golden) + assert any(issue in v for v in m.violations), (issue, overrides, m.violations) + + def test_every_validator_issue_surfaces_in_direct_score(self): + # Structural lock: the direct-score path surfaces the validator's + # COMPLETE issue list verbatim (this is how id / task_description / + # stock_code and any future validator check apply to direct scoring + # automatically). A thoroughly malformed sample must yield every + # validator issue in compute violations, with no duplicates from the + # inline scoring checks. + log = [_entry(tool="get_realtime_quote", arguments={"stock_code": "600519"})] + golden = GoldenSample( + id=[], + task_description=None, + stock_code=" ", + expected_tools=["", " "], + allowed_max_steps=0, + allow_optional_tools="false", + ) + validator_issues = validate_golden_sample(golden) + assert validator_issues, "the sample is thoroughly malformed" + m = compute_trajectory_metrics(log, golden) + for issue in validator_issues: + assert any(issue in v for v in m.violations), (issue, m.violations) + assert m.violations.count(issue) == 1, (issue, m.violations) + + +# --------------------------------------------------------------------------- +# 3. Retries, caching, failure counting +# --------------------------------------------------------------------------- +class TestRetryAndCaching: + def test_fail_then_retry_success_counts_one_retry(self): + log = [ + _entry(step=1, success=False), + _entry(step=2, success=True), + ] + m = compute_trajectory_metrics(log, _golden()) + assert m.retries == 1 + assert m.redundant_calls == 1 + assert m.failed_calls == 1 + + def test_same_tool_different_args_not_redundant(self): + log = [ + _entry(arguments={"stock_code": "600519"}, step=1), + _entry(arguments={"stock_code": "000001"}, step=2), + ] + m = compute_trajectory_metrics(log, _golden()) + assert m.redundant_calls == 0 + assert m.retries == 0 + + def test_repeat_after_success_is_redundant_but_not_retry(self): + log = [_entry(step=1, success=True), _entry(step=2, success=True)] + m = compute_trajectory_metrics(log, _golden()) + assert m.redundant_calls == 1 + assert m.retries == 0 + assert m.failed_calls == 0 + + def test_fail_fail_success_counts_two_retries(self): + log = [ + _entry(step=1, success=False), + _entry(step=2, success=False), + _entry(step=3, success=True), + ] + m = compute_trajectory_metrics(log, _golden()) + assert m.retries == 2 + assert m.redundant_calls == 2 + assert m.failed_calls == 2 + + def test_recovery_clears_failure_state(self): + # fail -> success -> success: only the recovery attempt is a retry; + # the repeat after success counts as redundant only. + log = [ + _entry(step=1, success=False), + _entry(step=2, success=True), + _entry(step=3, success=True), + ] + m = compute_trajectory_metrics(log, _golden()) + assert m.retries == 1 + assert m.redundant_calls == 2 + assert m.failed_calls == 1 + + def test_cached_entry_counted(self): + m = compute_trajectory_metrics([_entry(cached=True, success=False)], _golden()) + assert m.cached_calls == 1 + assert m.failed_calls == 1 + + +# --------------------------------------------------------------------------- +# 4. max_steps touching +# --------------------------------------------------------------------------- +class TestMaxStepsTouched: + def test_steps_reaching_allowed_max_touched(self): + log = [_entry(step=i) for i in range(1, 6)] + m = compute_trajectory_metrics(log, _golden(allowed_max_steps=5)) + assert m.max_steps_touched is True + assert "trajectory reached allowed_max_steps (5)" in m.violations + + def test_steps_below_limit_not_touched(self): + log = [_entry(step=i) for i in range(1, 5)] + m = compute_trajectory_metrics(log, _golden(allowed_max_steps=5)) + assert m.max_steps_touched is False + assert m.violations == [] + + def test_empty_log_not_touched(self): + m = compute_trajectory_metrics([], _golden(allowed_max_steps=5)) + assert m.max_steps_touched is False + + def test_non_integer_limit_surfaces_violation_without_crash(self): + log = [_entry(step=i) for i in range(1, 6)] + m = compute_trajectory_metrics(log, _golden(allowed_max_steps="5")) + assert m.max_steps_touched is False + assert "allowed_max_steps must be an integer" in m.violations + + +# --------------------------------------------------------------------------- +# 4b. total_steps input (final answer round) +# --------------------------------------------------------------------------- +class TestTotalStepsInput: + def test_total_steps_extends_step_metrics_beyond_log(self): + log = [_entry(step=1), _entry(step=2)] + m = compute_trajectory_metrics(log, _golden(allowed_max_steps=5), total_steps=4) + assert m.distinct_steps == 4 + assert m.max_steps_touched is False + + def test_total_steps_can_touch_the_limit(self): + log = [_entry(step=1), _entry(step=2)] + m = compute_trajectory_metrics(log, _golden(allowed_max_steps=3), total_steps=3) + assert m.max_steps_touched is True + assert m.distinct_steps == 3 + + def test_log_wins_when_it_reaches_further(self): + log = [_entry(step=i) for i in range(1, 5)] + m = compute_trajectory_metrics(log, _golden(allowed_max_steps=5), total_steps=2) + assert m.distinct_steps == 4 + assert m.max_steps_touched is False + + def test_none_keeps_log_only_behaviour(self): + m = compute_trajectory_metrics([_entry(step=1)], _golden()) + assert m.distinct_steps == 1 + + def test_non_numeric_total_steps_ignored(self): + m = compute_trajectory_metrics([_entry(step=1)], _golden(), total_steps="not-a-number") + assert m.distinct_steps == 1 + + +# --------------------------------------------------------------------------- +# 5. Tolerant entry shapes (missing fields) +# --------------------------------------------------------------------------- +class TestTolerantEntries: + def test_missing_optional_fields_defaulted(self): + m = compute_trajectory_metrics([{"step": 1, "tool": "get_realtime_quote"}], _golden()) + assert m.failed_calls == 0 + assert m.cached_calls == 0 + assert m.expected_hit_rate == pytest.approx(1 / 3) + + def test_entries_without_arguments_share_one_identity(self): + # Arguments-less entries key as an empty object: a repeated call of + # the same tool is redundant even without an arguments payload. + log = [ + {"step": 1, "tool": "get_realtime_quote", "success": True}, + {"step": 2, "tool": "get_realtime_quote", "success": True}, + ] + m = compute_trajectory_metrics(log, _golden()) + assert m.redundant_calls == 1 + assert m.retries == 0 + + def test_invalid_step_coerced_to_zero(self): + m = compute_trajectory_metrics([_entry(step="not-a-number")], _golden()) + assert m.distinct_steps == 0 + + +# --------------------------------------------------------------------------- +# 6. Text report rendering +# --------------------------------------------------------------------------- +class TestFormatTextReport: + def test_contains_hit_fraction_and_percent(self): + text = format_text_report(_metrics()) + assert "2/3" in text + assert "66.7%" in text + + def test_empties_render_placeholder(self): + m = _metrics( + expected_hit_rate=0.0, + expected_total=3, + missing_expected=["get_realtime_quote", "get_daily_history", "analyze_trend"], + ) + text = format_text_report(m) + assert "缺失期望工具: get_realtime_quote, get_daily_history, analyze_trend" in text + assert "期望外工具: 无" in text + assert "违规项: 无" in text + assert "触碰 max_steps: 否" in text + + def test_violations_rendered(self): + text = format_text_report(_metrics(violations=["trajectory reached allowed_max_steps (5)"])) + assert "违规项: trajectory reached allowed_max_steps (5)" in text + + def test_deterministic(self): + m = _metrics(redundant_calls=2, retries=1, max_steps_touched=True) + assert format_text_report(m) == format_text_report(m) + + +# --------------------------------------------------------------------------- +# 7. Golden samples file (schema + registry membership) +# --------------------------------------------------------------------------- +def _repo_tool_names(): + """Authoritative tool names from the five tool modules (lazy import).""" + from src.agent.tools.analysis_tools import ALL_ANALYSIS_TOOLS + from src.agent.tools.backtest_tools import ALL_BACKTEST_TOOLS + from src.agent.tools.data_tools import ALL_DATA_TOOLS + from src.agent.tools.market_tools import ALL_MARKET_TOOLS + from src.agent.tools.search_tools import ALL_SEARCH_TOOLS + + all_tools = ALL_DATA_TOOLS + ALL_ANALYSIS_TOOLS + ALL_SEARCH_TOOLS + ALL_MARKET_TOOLS + ALL_BACKTEST_TOOLS + return {tool_def.name for tool_def in all_tools} + + +class TestGoldenSamplesFile: + def test_samples_load_clean_with_registry_names(self): + samples = load_golden_samples(known_tool_names=_repo_tool_names()) + assert len(samples) == 2 + assert [s.id for s in samples] == ["600519_technical", "000001_core_data_strict"] + + def test_each_sample_passes_structural_validation(self): + for sample in load_golden_samples(): + assert validate_golden_sample(sample, _repo_tool_names()) == [] + + def test_expected_tools_exist_in_repo_registry(self): + known = _repo_tool_names() + for sample in load_golden_samples(): + unknown = [t for t in sample.expected_tools if t not in known] + assert unknown == [], f"sample '{sample.id}' expects unknown tools: {unknown}" + + def test_contains_strict_sample_without_optional_tools(self): + samples = load_golden_samples() + assert any(not s.allow_optional_tools for s in samples) + + def test_samples_have_required_text_fields(self): + for sample in load_golden_samples(): + assert sample.id.strip() + assert sample.task_description.strip() + assert sample.stock_code.strip() + assert sample.allowed_max_steps >= 1 + + def test_empty_stock_code_is_the_valid_no_context_default(self): + sample = GoldenSample(id="x", task_description="t", stock_code="", expected_tools=["get_realtime_quote"]) + assert validate_golden_sample(sample) == [] + + def test_whitespace_only_stock_code_fails_validation(self): + sample = GoldenSample(id="x", task_description="t", stock_code=" ", expected_tools=["get_realtime_quote"]) + issues = validate_golden_sample(sample) + assert any("stock_code must not contain leading or trailing whitespace" in i for i in issues) + + def test_non_string_stock_code_fails_validation(self): + sample = GoldenSample(id="x", task_description="t", stock_code=None, expected_tools=["get_realtime_quote"]) + issues = validate_golden_sample(sample) + assert any("stock_code must be a string" in i for i in issues) + + def test_string_expected_tools_fails_validation(self): + sample = GoldenSample( + id="x", + task_description="t", + stock_code="600519", + expected_tools="get_realtime_quote", + ) + issues = validate_golden_sample(sample) + assert any("must be a list" in i for i in issues) + + def test_non_bool_allow_optional_tools_fails_validation(self): + sample = GoldenSample( + id="x", + task_description="t", + stock_code="600519", + expected_tools=["get_realtime_quote"], + allow_optional_tools="false", + ) + issues = validate_golden_sample(sample) + assert any("allow_optional_tools must be a boolean" in i for i in issues) + + def test_mistyped_fields_fail_validation_not_crash(self): + # Same defect class as the string expected_tools bug: hand-edited JSON + # with mistyped fields must be rejected cleanly, never crash or pass. + bad = GoldenSample( + id=5, + task_description=None, + stock_code="600519", + expected_tools=["get_realtime_quote"], + allowed_max_steps="5", + allow_optional_tools=1, + ) + issues = validate_golden_sample(bad) + assert any("id must be a non-empty string" in i for i in issues) + assert any("task_description must be a non-empty string" in i for i in issues) + assert any("allowed_max_steps must be an integer" in i for i in issues) + assert any("allow_optional_tools must be a boolean" in i for i in issues) + + def test_non_iterable_expected_tools_with_known_names_does_not_crash(self): + sample = GoldenSample( + id="x", + task_description="t", + stock_code="600519", + expected_tools=1, + ) + issues = validate_golden_sample(sample, {"get_realtime_quote"}) + assert any("expected_tools must be a list" in i for i in issues) + + def test_registry_membership_with_one_shot_generator(self): + # The helper accepts any Iterable[str]; a one-shot generator must be + # materialized internally so membership checks never consume it. + sample = GoldenSample( + id="x", + task_description="t", + stock_code="600519", + expected_tools=["b", "a"], + ) + known = (name for name in ["a", "b"]) + assert validate_golden_sample(sample, known) == [] + + def test_duplicate_expected_tools_fail_validation(self): + sample = GoldenSample( + id="x", + task_description="t", + stock_code="600519", + expected_tools=["get_realtime_quote", "get_realtime_quote"], + ) + issues = validate_golden_sample(sample) + assert any("must not contain duplicate names" in i for i in issues) + + def test_loader_materializes_registry_once_for_multiple_samples(self): + # A one-shot generator must survive loading the whole checked-in file: + # the first sample must not exhaust it for the remaining samples. + samples = load_golden_samples(known_tool_names=(name for name in _repo_tool_names())) + assert len(samples) == 2 + + +class TestLoadGoldenSamplesErrors: + @staticmethod + def _write_sample(tmp_path, payload, name="golden.json"): + target = tmp_path / name + target.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") + return str(target) + + def test_missing_file_raises(self): + with pytest.raises(FileNotFoundError): + load_golden_samples(path="no/such/golden_samples.json") + + def test_non_list_root_raises(self, tmp_path): + path = self._write_sample(tmp_path, {"id": "x"}) + with pytest.raises(ValueError, match="JSON list"): + load_golden_samples(path=path) + + def test_malformed_json_raises(self, tmp_path): + target = tmp_path / "golden.json" + target.write_text("{not json", encoding="utf-8") + with pytest.raises(ValueError): + load_golden_samples(path=str(target)) + + def test_duplicate_ids_raise(self, tmp_path): + sample = { + "id": "dup", + "task_description": "t", + "stock_code": "600519", + "expected_tools": ["get_realtime_quote"], + } + path = self._write_sample(tmp_path, [sample, sample]) + with pytest.raises(ValueError, match="duplicate sample id: dup"): + load_golden_samples(path=path) + + def test_unknown_expected_tool_flagged_when_names_given(self, tmp_path): + sample = { + "id": "x", + "task_description": "t", + "stock_code": "600519", + "expected_tools": ["not_a_real_tool"], + } + path = self._write_sample(tmp_path, [sample]) + with pytest.raises(ValueError, match="unknown expected_tools: not_a_real_tool"): + load_golden_samples(path=path, known_tool_names=_repo_tool_names()) + + def test_unknown_expected_tool_allowed_without_names(self, tmp_path): + sample = { + "id": "x", + "task_description": "t", + "stock_code": "600519", + "expected_tools": ["not_a_real_tool"], + } + path = self._write_sample(tmp_path, [sample]) + assert [s.id for s in load_golden_samples(path=path)] == ["x"] + + def test_extra_json_keys_ignored(self, tmp_path): + sample = { + "id": "x", + "task_description": "t", + "stock_code": "600519", + "expected_tools": ["get_realtime_quote"], + "notes": "forward-looking metadata", + } + path = self._write_sample(tmp_path, [sample]) + assert load_golden_samples(path=path)[0].id == "x" + + def test_invalid_max_steps_flagged(self, tmp_path): + sample = { + "id": "x", + "task_description": "t", + "stock_code": "600519", + "expected_tools": ["get_realtime_quote"], + "allowed_max_steps": 0, + } + path = self._write_sample(tmp_path, [sample]) + with pytest.raises(ValueError, match="allowed_max_steps must be >= 1"): + load_golden_samples(path=path) + + def test_whitespace_only_stock_code_raises(self, tmp_path): + sample = { + "id": "x", + "task_description": "t", + "stock_code": " ", + "expected_tools": ["get_realtime_quote"], + } + path = self._write_sample(tmp_path, [sample]) + with pytest.raises(ValueError, match="stock_code must not contain leading or trailing whitespace"): + load_golden_samples(path=path) + + def test_string_expected_tools_raises(self, tmp_path): + sample = { + "id": "x", + "task_description": "t", + "stock_code": "600519", + "expected_tools": "get_realtime_quote", + } + path = self._write_sample(tmp_path, [sample]) + with pytest.raises(ValueError, match="expected_tools must be a list"): + load_golden_samples(path=path) + + def test_non_list_expected_tools_with_known_names_raises_valueerror(self, tmp_path): + # Regression for OR-COR-4e0e3cf1: the registry membership check must + # not iterate a rejected non-list value and leak a TypeError. + sample = { + "id": "x", + "task_description": "t", + "stock_code": "600519", + "expected_tools": 1, + } + path = self._write_sample(tmp_path, [sample]) + with pytest.raises(ValueError, match="expected_tools must be a list"): + load_golden_samples(path=path, known_tool_names={"get_realtime_quote"}) + + def test_unhashable_id_raises_valueerror(self, tmp_path): + # Structural validation must run before duplicate detection: an + # unhashable id would otherwise crash the seen_ids membership check + # with a TypeError instead of the documented ValueError. + sample = { + "id": ["x"], + "task_description": "t", + "stock_code": "600519", + "expected_tools": ["get_realtime_quote"], + } + path = self._write_sample(tmp_path, [sample]) + with pytest.raises(ValueError, match="id must be a non-empty string"): + load_golden_samples(path=path) + + def test_non_bool_allow_optional_tools_raises(self, tmp_path): + sample = { + "id": "x", + "task_description": "t", + "stock_code": "600519", + "expected_tools": ["get_realtime_quote"], + "allow_optional_tools": "false", + } + path = self._write_sample(tmp_path, [sample]) + with pytest.raises(ValueError, match="allow_optional_tools must be a boolean"): + load_golden_samples(path=path) + + def test_duplicate_expected_tools_raise(self, tmp_path): + sample = { + "id": "x", + "task_description": "t", + "stock_code": "600519", + "expected_tools": ["get_realtime_quote", "get_realtime_quote"], + } + path = self._write_sample(tmp_path, [sample]) + with pytest.raises(ValueError, match="expected_tools must not contain duplicate names"): + load_golden_samples(path=path) diff --git a/tests/test_agent_trajectory_run_eval.py b/tests/test_agent_trajectory_run_eval.py new file mode 100644 index 00000000000..a9fe9beff0e --- /dev/null +++ b/tests/test_agent_trajectory_run_eval.py @@ -0,0 +1,436 @@ +# -*- coding: utf-8 -*- +"""Unit tests for the runnable agent trajectory eval entry (Issue #1956). + +All tests are offline: ``run_eval._build_executor`` is monkeypatched with a +duck-typed stub, and the three checked-in fixtures provide real-shaped +``tool_calls_log`` payloads covering the positive path, the negative path +(missing expected tool + cached failure + max_steps) and the retry path. +The two runtime-seam guards (multi-arch rejection and golden validation +against the real tool registry) are exercised via monkeypatched config / +registry access plus one lazy real-registry check. +""" + +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from evals.agent_trajectory import run_eval +from evals.agent_trajectory.metrics import GoldenSample, load_golden_samples + +FIXTURES_DIR = Path(__file__).resolve().parent / "fixtures" / "agent_trajectory" + + +def _stub_executor(log, total_steps=None): + """Duck-typed executor recording its run calls (no src/ import).""" + + class _Stub: + def __init__(self): + self.calls = [] + + def run(self, task, context=None): + self.calls.append((task, context)) + return SimpleNamespace(tool_calls_log=list(log), total_steps=total_steps) + + return _Stub() + + +def _fixture(name): + """Load a checked-in fixture payload: (tool_calls_log, total_steps).""" + payload = json.loads((FIXTURES_DIR / f"{name}.json").read_text(encoding="utf-8")) + return payload["tool_calls_log"], payload["total_steps"] + + +def _result_executor(result): + """Duck-typed executor whose run always returns a fixed result object.""" + return SimpleNamespace(run=lambda task, context=None: result) + + +def _goldens(): + return {sample.id: sample for sample in load_golden_samples()} + + +# --------------------------------------------------------------------------- +# 1. run_sample: positive path +# --------------------------------------------------------------------------- +class TestRunSamplePositive: + def test_full_hit_and_clean_metrics(self): + log, total_steps = _fixture("positive_600519_technical") + executor = _stub_executor(log, total_steps) + m = run_eval.run_sample(executor, _goldens()["600519_technical"]) + assert m.expected_hit_rate == 1.0 + assert m.missing_expected == [] + assert m.optional_tools_used == ["search_stock_news"] + assert m.distinct_steps == 5 + assert m.violations == [] + + def test_json_report_contract(self, tmp_path): + log, total_steps = _fixture("positive_600519_technical") + out = tmp_path / "report.json" + m = run_eval.run_sample(_stub_executor(log, total_steps), _goldens()["600519_technical"], json_out=out) + report = json.loads(out.read_text(encoding="utf-8")) + assert report["sample_id"] == "600519_technical" + assert report["task_description"] + assert report["stock_code"] == "600519" + assert report["violations"] == m.violations + metrics = report["metrics"] + expected_fields = { + "expected_hit_rate", + "expected_total", + "missing_expected", + "optional_tools_used", + "redundant_calls", + "cached_calls", + "failed_calls", + "retries", + "distinct_steps", + "max_steps_touched", + "violations", + } + assert set(metrics) == expected_fields + assert metrics["expected_hit_rate"] == 1.0 + + def test_text_summary_printed(self, capsys): + log, total_steps = _fixture("positive_600519_technical") + run_eval.run_sample(_stub_executor(log, total_steps), _goldens()["600519_technical"]) + out = capsys.readouterr().out + assert "Agent Trajectory 评估报告" in out + assert "3/3" in out + assert "违规项: 无" in out + + def test_context_carries_stock_code(self): + executor = _stub_executor([], total_steps=1) + run_eval.run_sample(executor, _goldens()["600519_technical"]) + assert len(executor.calls) == 1 + task, context = executor.calls[0] + assert context == {"stock_code": "600519"} + assert "600519" in task + + def test_empty_stock_code_passes_no_context(self): + executor = _stub_executor([], total_steps=1) + sample = GoldenSample( + id="no_context", + task_description="t", + stock_code="", + expected_tools=["get_realtime_quote"], + ) + run_eval.run_sample(executor, sample) + _, context = executor.calls[0] + assert context is None + + +# --------------------------------------------------------------------------- +# 2. run_sample: negative path (violations are findings, not exceptions) +# --------------------------------------------------------------------------- +class TestRunSampleNegative: + def test_missing_tool_and_max_steps_violations(self): + log, total_steps = _fixture("negative_600519_technical") + m = run_eval.run_sample(_stub_executor(log, total_steps), _goldens()["600519_technical"]) + assert m.expected_hit_rate == pytest.approx(2 / 3) + assert m.missing_expected == ["analyze_trend"] + assert m.redundant_calls == 1 + assert m.cached_calls == 1 + assert m.failed_calls == 1 + assert m.max_steps_touched is True + assert "trajectory reached allowed_max_steps (8)" in m.violations + + def test_violations_do_not_raise(self): + log, total_steps = _fixture("negative_600519_technical") + m = run_eval.run_sample(_stub_executor(log, total_steps), _goldens()["600519_technical"]) + assert m.violations # the eval is a reporter, not a gate + + def test_executor_without_total_steps_still_scores(self): + # A result without total_steps keeps the log-only step behaviour. + log, _ = _fixture("negative_600519_technical") + m = run_eval.run_sample(_stub_executor(log, None), _goldens()["600519_technical"]) + assert m.distinct_steps == 4 + assert m.max_steps_touched is False + + +# --------------------------------------------------------------------------- +# 3. run_sample: retry path (fail -> success -> success contract) +# --------------------------------------------------------------------------- +class TestRunSampleRetry: + def test_fail_success_success_counts_one_retry(self): + log, total_steps = _fixture("retry_000001_core_data_strict") + m = run_eval.run_sample(_stub_executor(log, total_steps), _goldens()["000001_core_data_strict"]) + assert m.expected_hit_rate == 1.0 + assert m.retries == 1 + assert m.redundant_calls == 2 + assert m.failed_calls == 1 + assert m.cached_calls == 0 + assert m.optional_tools_used == [] + assert m.violations == [] + + +# --------------------------------------------------------------------------- +# 3.5 run failure: results carrying an explicit success=False +# --------------------------------------------------------------------------- +class TestRunFailure: + def test_unsuccessful_result_raises_before_scoring(self, capsys): + # Owner repro: a real AgentResult with success=False must not be scored. + executor = _result_executor(SimpleNamespace(success=False, error="boom", tool_calls_log=[], total_steps=0)) + with pytest.raises(RuntimeError, match="boom"): + run_eval.run_sample(executor, _goldens()["600519_technical"]) + assert "Agent Trajectory 评估报告" not in capsys.readouterr().out + + def test_unsuccessful_result_without_error_raises(self): + executor = _result_executor(SimpleNamespace(success=False, tool_calls_log=[], total_steps=0)) + with pytest.raises(RuntimeError, match="success=false"): + run_eval.run_sample(executor, _goldens()["600519_technical"]) + + def test_explicit_success_true_scores_normally(self): + log, total_steps = _fixture("positive_600519_technical") + result = SimpleNamespace(success=True, tool_calls_log=list(log), total_steps=total_steps) + m = run_eval.run_sample(_result_executor(result), _goldens()["600519_technical"]) + assert m.expected_hit_rate == 1.0 + + def test_missing_success_field_is_tolerated(self): + # Duck-typed stubs without a success attribute keep the old behaviour. + log, total_steps = _fixture("positive_600519_technical") + result = SimpleNamespace(tool_calls_log=list(log), total_steps=total_steps) + m = run_eval.run_sample(_result_executor(result), _goldens()["600519_technical"]) + assert m.expected_hit_rate == 1.0 + + def test_success_none_is_tolerated(self): + log, total_steps = _fixture("positive_600519_technical") + result = SimpleNamespace(success=None, tool_calls_log=list(log), total_steps=total_steps) + m = run_eval.run_sample(_result_executor(result), _goldens()["600519_technical"]) + assert m.expected_hit_rate == 1.0 + + +# --------------------------------------------------------------------------- +# 4. runtime-seam guards: multi-arch rejection + golden registry validation +# --------------------------------------------------------------------------- +class TestArchGuard: + def test_multi_arch_raises(self, monkeypatch): + import src.config + + monkeypatch.setattr(src.config, "get_config", lambda: SimpleNamespace(agent_arch="multi")) + with pytest.raises(RuntimeError, match="multi"): + run_eval._check_agent_arch() + + def test_single_arch_passes(self, monkeypatch): + import src.config + + monkeypatch.setattr(src.config, "get_config", lambda: SimpleNamespace(agent_arch="single")) + run_eval._check_agent_arch() # no raise + + +class TestGoldenRegistryValidation: + def test_unknown_expected_tools_exit_one(self, tmp_path, monkeypatch, capsys): + # A misspelled expected tool must fail as an invalid sample, not score low. + custom = [ + { + "id": "typo_sample", + "task_description": "t", + "stock_code": "", + "expected_tools": ["get_daily_histroy"], + "allowed_max_steps": 10, + "allow_optional_tools": True, + } + ] + golden_path = tmp_path / "golden.json" + golden_path.write_text(json.dumps(custom, ensure_ascii=False), encoding="utf-8") + monkeypatch.setattr(run_eval, "_known_tool_names", lambda: {"get_realtime_quote"}) + assert run_eval.main(["--sample", "typo_sample", "--golden-path", str(golden_path)]) == 1 + err = capsys.readouterr().err + assert "unknown expected_tools" in err + assert "get_daily_histroy" in err + + def test_checked_in_goldens_pass_real_registry(self): + known = run_eval._known_tool_names() + assert len(known) > 5 # sanity: the real registry is non-trivial + load_golden_samples(known_tool_names=known) # must not raise + + def test_registry_load_failure_exit_one(self, monkeypatch, capsys): + def _boom(): + raise ImportError("no tool modules") + + monkeypatch.setattr(run_eval, "_known_tool_names", _boom) + assert run_eval.main(["--sample", "600519_technical"]) == 1 + assert "failed to load tool registry" in capsys.readouterr().err + + +# --------------------------------------------------------------------------- +# 5. CLI (main): exit codes, selection, JSON output +# --------------------------------------------------------------------------- +class TestMainCli: + @pytest.fixture(autouse=True) + def _stub_builder(self, monkeypatch): + executor = _stub_executor([], total_steps=1) + monkeypatch.setattr(run_eval, "_build_executor", lambda: executor) + return executor + + def test_exit_zero_successful_sample(self, capsys): + assert run_eval.main(["--sample", "600519_technical"]) == 0 + out = capsys.readouterr().out + assert "[eval] sample: 600519_technical" in out + assert "Agent Trajectory 评估报告" in out + + def test_unknown_sample_id_exit_one(self, capsys): + assert run_eval.main(["--sample", "no-such-id"]) == 1 + err = capsys.readouterr().err + assert "unknown sample id 'no-such-id'" in err + assert "600519_technical" in err and "000001_core_data_strict" in err + + def test_missing_arguments_exit_two(self): + with pytest.raises(SystemExit) as excinfo: + run_eval.main([]) + assert excinfo.value.code == 2 + + def test_both_flags_exit_two(self): + with pytest.raises(SystemExit) as excinfo: + run_eval.main(["--sample", "600519_technical", "--all"]) + assert excinfo.value.code == 2 + + def test_build_failure_exit_one(self, monkeypatch, capsys): + def _boom(): + raise RuntimeError("no api key configured") + + monkeypatch.setattr(run_eval, "_build_executor", _boom) + assert run_eval.main(["--sample", "600519_technical"]) == 1 + assert "failed to build agent executor" in capsys.readouterr().err + + def test_multi_arch_build_rejection_exit_one(self, monkeypatch, capsys): + def _boom(): + raise RuntimeError("AGENT_ARCH=multi is not supported by this minimal eval") + + monkeypatch.setattr(run_eval, "_build_executor", _boom) + assert run_eval.main(["--sample", "600519_technical"]) == 1 + assert "multi" in capsys.readouterr().err + + def test_run_failure_exit_one(self, monkeypatch, capsys): + class _Exploding: + def run(self, task, context=None): + raise RuntimeError("llm timeout") + + monkeypatch.setattr(run_eval, "_build_executor", lambda: _Exploding()) + assert run_eval.main(["--sample", "600519_technical"]) == 1 + assert "sample '600519_technical' failed" in capsys.readouterr().err + + def test_unsuccessful_result_exit_one(self, monkeypatch, capsys): + # Owner repro: a result object with success=False is a run failure. + result = SimpleNamespace(success=False, error="boom", tool_calls_log=[], total_steps=0) + monkeypatch.setattr(run_eval, "_build_executor", lambda: _result_executor(result)) + assert run_eval.main(["--sample", "600519_technical"]) == 1 + err = capsys.readouterr().err + assert "sample '600519_technical' failed" in err + assert "boom" in err + + def test_all_returns_one_when_a_sample_result_is_unsuccessful(self, monkeypatch, capsys): + result = SimpleNamespace(success=False, tool_calls_log=[], total_steps=0) + monkeypatch.setattr(run_eval, "_build_executor", lambda: _result_executor(result)) + assert run_eval.main(["--all"]) == 1 + assert "failed" in capsys.readouterr().err + + def test_violations_still_exit_zero(self, monkeypatch, capsys): + log, total_steps = _fixture("negative_600519_technical") + monkeypatch.setattr(run_eval, "_build_executor", lambda: _stub_executor(log, total_steps)) + assert run_eval.main(["--sample", "600519_technical"]) == 0 + assert "trajectory reached allowed_max_steps (8)" in capsys.readouterr().out + + def test_all_writes_keyed_json(self, tmp_path, capsys): + out = tmp_path / "all.json" + assert run_eval.main(["--all", "--json-out", str(out)]) == 0 + report = json.loads(out.read_text(encoding="utf-8")) + assert set(report) == {"600519_technical", "000001_core_data_strict"} + for sample_report in report.values(): + assert set(sample_report) == {"sample_id", "task_description", "stock_code", "metrics", "violations"} + + def test_single_sample_json_out_is_not_keyed(self, tmp_path): + out = tmp_path / "one.json" + assert run_eval.main(["--sample", "600519_technical", "--json-out", str(out)]) == 0 + report = json.loads(out.read_text(encoding="utf-8")) + assert report["sample_id"] == "600519_technical" + + def test_utf8_chinese_roundtrip(self, tmp_path): + out = tmp_path / "utf8.json" + assert run_eval.main(["--sample", "600519_technical", "--json-out", str(out)]) == 0 + text = out.read_text(encoding="utf-8") + assert "贵州茅台" in text + json.loads(text) # valid JSON with raw UTF-8 content + + def test_golden_path_override(self, tmp_path, capsys): + custom = [ + { + "id": "custom_sample", + "task_description": "自定义任务", + "stock_code": "", + "expected_tools": ["get_realtime_quote"], + "allowed_max_steps": 3, + "allow_optional_tools": True, + } + ] + golden_path = tmp_path / "golden.json" + golden_path.write_text(json.dumps(custom, ensure_ascii=False), encoding="utf-8") + assert run_eval.main(["--sample", "custom_sample", "--golden-path", str(golden_path)]) == 0 + assert "[eval] sample: custom_sample" in capsys.readouterr().out + + def test_load_failure_exit_one(self, capsys): + assert run_eval.main(["--sample", "x", "--golden-path", "no/such/file.json"]) == 1 + assert "failed to load golden samples" in capsys.readouterr().err + + +# --------------------------------------------------------------------------- +# 6. Checked-in fixtures end to end (the owner-requested real-entry coverage) +# --------------------------------------------------------------------------- +@pytest.mark.parametrize( + "fixture_name,golden_id,expected", + [ + ( + "positive_600519_technical", + "600519_technical", + dict( + expected_hit_rate=1.0, + missing_expected=[], + redundant_calls=0, + cached_calls=0, + failed_calls=0, + retries=0, + distinct_steps=5, + max_steps_touched=False, + violations=[], + ), + ), + ( + "negative_600519_technical", + "600519_technical", + dict( + expected_hit_rate=pytest.approx(2 / 3), + missing_expected=["analyze_trend"], + redundant_calls=1, + cached_calls=1, + failed_calls=1, + retries=0, + distinct_steps=8, + max_steps_touched=True, + ), + ), + ( + "retry_000001_core_data_strict", + "000001_core_data_strict", + dict( + expected_hit_rate=1.0, + missing_expected=[], + redundant_calls=2, + cached_calls=0, + failed_calls=1, + retries=1, + distinct_steps=5, + max_steps_touched=False, + violations=[], + ), + ), + ], +) +def test_fixtures_end_to_end(fixture_name, golden_id, expected): + log, total_steps = _fixture(fixture_name) + m = run_eval.run_sample(_stub_executor(log, total_steps), _goldens()[golden_id]) + for field, value in expected.items(): + assert getattr(m, field) == value, (fixture_name, field) + if "violations" in expected: + assert m.violations == expected["violations"] + else: + assert m.violations and "trajectory reached allowed_max_steps (8)" in m.violations From e866cfa48d72807c70d2fb48f0ffae85fde3acf2 Mon Sep 17 00:00:00 2001 From: Elvis Wang Date: Fri, 4 Sep 2026 18:04:14 +0800 Subject: [PATCH 2/2] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=20Bot=20?= =?UTF-8?q?=E6=8C=87=E6=95=B0=E5=88=86=E6=9E=90=E5=85=A5=E5=8F=A3=E4=B8=8E?= =?UTF-8?q?=E5=9C=A8=E7=BA=BF=E9=AA=8C=E6=94=B6=20(#2327)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: add bot index analysis entry * test: add Bot index online smoke * fix: guard Windows-only spawn flag in smoke tests for Linux CI * fix: clean up worker tree on parent interrupt in smoke runner * fix: surface interrupt cleanup failures in smoke runner --------- Co-authored-by: zhulinsen <42829555+ZhuLinsen@users.noreply.github.com> --- bot/commands/analyze.py | 211 ++++- docs/CHANGELOG.md | 2 + docs/bot-command.md | 29 +- docs/bot-command_EN.md | 24 +- docs/bot/discord-bot-config.md | 8 +- docs/full-guide.md | 4 +- docs/full-guide_EN.md | 4 +- scripts/smoke_bot_index_entry.py | 506 ++++++++++++ src/services/stock_list_parser.py | 55 ++ src/services/task_service.py | 40 +- tests/test_bot_analyze_command.py | 363 +++++++++ tests/test_smoke_bot_index_entry.py | 1170 +++++++++++++++++++++++++++ tests/test_stock_list_parser.py | 88 ++ tests/test_task_service.py | 101 +++ 14 files changed, 2549 insertions(+), 56 deletions(-) create mode 100644 scripts/smoke_bot_index_entry.py create mode 100644 tests/test_bot_analyze_command.py create mode 100644 tests/test_smoke_bot_index_entry.py diff --git a/bot/commands/analyze.py b/bot/commands/analyze.py index 2ad7cec0c0a..982935e3c65 100644 --- a/bot/commands/analyze.py +++ b/bot/commands/analyze.py @@ -4,16 +4,24 @@ 股票分析命令 =================================== -分析指定股票,调用 AI 生成分析报告。 +分析指定股票或已登记指数,调用 AI 生成分析报告。 """ -import re import logging -from typing import List, Optional +import re +import unicodedata +from dataclasses import replace +from typing import List, Optional, Tuple, Union from bot.commands.base import BotCommand from bot.models import BotMessage, BotResponse -from src.services.stock_code_utils import resolve_index_stock_code_for_analysis +from src.services.stock_code_utils import is_code_like, resolve_index_stock_code_for_analysis +from src.services.stock_list_parser import ( + AnalysisTarget, + ParseStatus, + default_index_registry, + parse_analysis_target, +) logger = logging.getLogger(__name__) @@ -22,11 +30,14 @@ class AnalyzeCommand(BotCommand): """ 股票分析命令 - 分析指定股票代码,生成 AI 分析报告并推送。 + 分析指定股票代码或已登记指数,生成 AI 分析报告并推送。 用法: /analyze 600519 - 分析贵州茅台(精简报告) /analyze 600519 full - 分析并生成完整报告 + /analyze sh000016 - 分析上证50指数 + /analyze 930955.CSI - 分析红利低波100指数(alias 收敛) + /analyze 上证50 - 按注册名称分析上证50指数 """ @property @@ -39,69 +50,195 @@ def aliases(self) -> List[str]: @property def description(self) -> str: - return "分析指定股票" + return "分析指定股票或指数" @property def usage(self) -> str: - return "/analyze <股票代码> [full]" + return "/analyze <股票代码/指数代码/指数名称> [full]" def validate_args(self, args: List[str]) -> Optional[str]: - """验证参数""" + """验证参数(仅结构检查;语义校验在 execute 中完成)""" if not args: - return "请输入股票代码" - - code = args[0].upper() - - # 验证股票代码格式 - # A股:6位数字 - # 港股:HK+5位数字 - # 美股:1-5个大写字母+.+2个后缀字母 - is_a_stock = re.match(r'^\d{6}$', code) - is_hk_stock = re.match(r'^HK\d{5}$', code) - is_us_stock = re.match(r'^[A-Z]{1,5}(\.[A-Z]{1,2})?$', code) - - if not (is_a_stock or is_hk_stock or is_us_stock): - return f"无效的股票代码: {code}(A股6位数字 / 港股HK+5位数字 / 美股1-5个字母)" - + return "请输入股票代码或指数名称" return None def execute(self, message: BotMessage, args: List[str]) -> BotResponse: """执行分析命令""" - code = resolve_index_stock_code_for_analysis(args[0]) - + raw = (args[0] or "").strip() + if not raw: + return BotResponse.error_response("请输入股票代码或指数名称") + # 检查是否需要完整报告(默认精简,传 full/完整/详细 切换) report_type = "simple" if len(args) > 1 and args[1].lower() in ["full", "完整", "详细"]: report_type = "full" - logger.info(f"[AnalyzeCommand] 分析股票: {code}, 报告类型: {report_type}") - + try: + code, analysis_target = self._resolve_analysis_input(raw) + if code is None: + error_msg = analysis_target + if not isinstance(error_msg, str): + error_msg = "无法识别标的" + return BotResponse.error_response(error_msg) + if isinstance(analysis_target, str): + return BotResponse.error_response(analysis_target) + + logger.info(f"[AnalyzeCommand] 分析标的: {code}, 报告类型: {report_type}") + # 调用分析服务 from src.services.task_service import get_task_service from src.enums import ReportType - + service = get_task_service() - + # 提交异步分析任务 result = service.submit_analysis( code=code, report_type=ReportType.from_str(report_type), - source_message=message + source_message=message, + analysis_target=analysis_target, ) - + if result.get("success"): task_id = result.get("task_id", "") - return BotResponse.markdown_response( + # ``extra`` 仅供内部任务 identity 透传(transport-independent + # 消费者,如 E2E smoke),文本保持既有契约不变,平台适配器可忽略。 + response = BotResponse.markdown_response( f"✅ **分析任务已提交**\n\n" - f"• 股票代码: `{code}`\n" + f"• 标的: `{code}`\n" f"• 报告类型: {ReportType.from_str(report_type).display_name}\n" f"• 任务 ID: `{task_id[:20]}...`\n\n" f"分析完成后将自动推送结果。" ) - else: - error = result.get("error", "未知错误") - return BotResponse.error_response(f"提交分析任务失败: {error}") - + response.extra = { + "task_id": task_id, + "stock_code": code, + } + return response + error = result.get("error", "未知错误") + return BotResponse.error_response(f"提交分析任务失败: {error}") + except Exception as e: logger.error(f"[AnalyzeCommand] 执行失败: {e}") return BotResponse.error_response(f"分析失败: {str(e)[:100]}") + + def _resolve_analysis_input( + self, raw: str + ) -> Tuple[Optional[str], Union[AnalysisTarget, str, None]]: + """Resolve one ``/analyze`` argument into ``(code, analysis_target)``. + + Registered index first, existing stock-name resolution as fallback. + + 1. Explicit index identity/alias (``sh000016`` / ``930955.CSI`` / + ``csi930955``) via + :meth:`IndexRegistry.find_by_explicit_key`. + 2. Exact registered display name (``上证50``) via + :meth:`IndexRegistry.find_by_display_name` — before any stock-name + fallback; ambiguous names fail with an explicit error. + 3. Parser INDEX acceptance: when :func:`parse_analysis_target` + classifies the raw input as INDEX (e.g. dotted-prefix aliases such + as ``SH.000016`` the registry key lookup misses), submit the + registry canonical with the matching structured target. Parser + STOCK results are deliberately ignored here so the legacy stock + gate stays authoritative for stock shapes. + 4. Explicit CSI forms (``csi`` + one or more digits, or one or more + digits + ``.csi``) that no registry entry claimed — they surface + the parser's ``unsupported`` details (never a stock-name fallback + or a US-ticker guess). + 5. Legacy stock-code gate, preserved exactly as before this change + (case-insensitive): A-share six digits, ``HK`` + five digits, and + US 1-5 letters with optional ``.XX`` suffix. Matches keep the + legacy code path (no structured target) so lowercase real tickers + like ``usfd`` still resolve to ``USFD``. + 6. Any remaining parser-UNSUPPORTED input (e.g. ``us1``, + ``600519.BJ``, ``1234567.SH``) is an explicit error — never sent + into stock-name resolution. + 7. Anything code-like the legacy gate rejected (``12345``, bare + ``00700``, ``600519.SH``, unregistered ``sh999999``) is an + explicit error — never silently submitted. + 8. Non-code names through :func:`resolve_name_to_code` (stock only). + + Only INDEX targets are carried downstream; stock inputs keep the + legacy code path so ``600519`` is never rewritten into a parser + canonical. On failure returns ``(None, error_message)``. + """ + from src.services.name_to_code_resolver import resolve_name_to_code + + registry = default_index_registry() + + # 1) Explicit index identity/alias — registered index wins over any + # stock-name fallback and is submitted with its lowercase + # canonical_id verbatim. + if registry.find_by_explicit_key(raw) is not None: + target = parse_analysis_target(raw, registry=registry) + return target.canonical_id, target + + # 2) Exact registered display name — independent of identity aliases; + # a Chinese name must never become a parser identity alias. + if registry.is_ambiguous_display_name(raw): + return None, ( + f"指数名称 `{raw}` 存在歧义,请改用显式代码(如 `sh000016`)" + ) + entry = registry.find_by_display_name(raw) + if entry is not None: + target = replace( + parse_analysis_target(entry.canonical_id, registry=registry), + raw_input=raw, + ) + return target.canonical_id, target + + # 3) Parser INDEX acceptance — the shared parser recognizes forms the + # registry key lookup above misses (e.g. dotted-prefix aliases + # ``SH.000016`` / ``SZ.399001``). Only an INDEX result short-circuits + # here; STOCK and UNSUPPORTED results continue to the legacy gates + # below so the legacy stock contract stays authoritative. + target = parse_analysis_target(raw, registry=registry) + if target.asset_type == ParseStatus.INDEX: + return target.canonical_id, target + + # 4) Explicit CSI forms — registered ones were claimed in step 1, so + # anything reaching here is unregistered and must surface the + # parser's UNSUPPORTED details. The full numeric explicit CSI + # family (``csi`` + one or more digits, or one or more digits + + # ``.csi``) is covered, not only six-digit forms. + normalized = unicodedata.normalize("NFKC", raw).strip().casefold() + if re.fullmatch(r"(?:csi\d+|\d+\.csi)", normalized): + reason = target.unsupported_reason or f"无法识别标的: {raw}" + return None, f"无法分析 `{raw}`:{reason}" + + # 5) Legacy stock-code gate — case-insensitive, exactly the shapes the + # old ``validate_args`` accepted. Matches keep the legacy code + # path (no structured target), including lowercase real tickers + # like ``usfd`` -> ``USFD``. + upper = raw.upper() + if ( + re.fullmatch(r"\d{6}", upper) + or re.fullmatch(r"HK\d{5}", upper) + or re.fullmatch(r"[A-Z]{1,5}(?:\.[A-Z]{1,2})?", upper) + ): + return resolve_index_stock_code_for_analysis(raw), None + + # 6) Any remaining parser-UNSUPPORTED input is an explicit error — + # never sent into stock-name resolution. This covers malformed + # code shapes the parser rejected (``us1``, ``600519.BJ``, + # ``1234567.SH``) that the legacy gate above did not claim. + if target.asset_type == ParseStatus.UNSUPPORTED: + reason = target.unsupported_reason or f"无法识别标的: {raw}" + return None, f"无法分析 `{raw}`:{reason}" + + # 7) Code-like inputs the legacy gate rejected are explicit errors — + # never submitted, never routed into stock-name resolution. This + # includes ``sh``/``sz`` prefixed six-digit forms (``sh999999``) + # that ``is_code_like`` misses because the bare digits classify as + # a different exchange. + if is_code_like(raw) or re.fullmatch(r"(?:sh|sz)\d{6}", normalized): + return None, ( + f"无效的标的代码: `{raw}`" + f"(A股6位数字 / HK+5位数字 / 美股1-5个字母 / 已登记指数代码或名称)" + ) + + # 8) Name input → stock-name fallback. + code = resolve_name_to_code(raw) + if not code: + return None, f"无法识别标的: {raw}" + return code, None diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 4b1183d19af..e8fb2ceaa0c 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -8,6 +8,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/). > For user-friendly release highlights, see the [GitHub Releases](https://github.com/ZhuLinsen/daily_stock_analysis/releases) page. ## [Unreleased] +- [测试] 新增 Bot 指数入口 transport-independent 在线 E2E smoke(`scripts/smoke_bot_index_entry.py`):worker 子进程经真实 `CommandDispatcher.dispatch_async` 提交并在同进程轮询 `TaskService` 贯穿到 `StockAnalysisPipeline`,父进程只负责 deadline、进程树清理(Windows `taskkill /T /F`、POSIX 杀进程组)与退出码(0=成功/1=失败/124=超时),输出单行 `E2E_EVENT {json}` 事件(`phase=submitted|completed|failed|timeout`);smoke 覆盖 `SH.000016`/`上证50`/`930955.CSI` 矩阵,期望 code/name 取脚本内置权威映射(不信任响应/结果自报身份,提交 code mismatch 输出含期望值与实际值的显式错误并携带结构化实际 `stock_code`,dispatcher 路由错误也失败),矩阵外 target 与非正 `--timeout` 在提交与 spawn 之前即被拒绝(退出码 2),completed 须 exact canonical code、exact 注册名称且 `analysis_summary`/`operation_advice`/`trend_prediction` 非空(仅空白视为空),失败或结果不完整即非零退出;超时清理进程树(Windows `taskkill /T /F`、POSIX 杀进程组),清理成功输出 `timeout` 事件并退出 124、清理失败输出含清理错误的 `failed` 事件并退出 1,不回滚 DB/报告/通知副作用;用户 Ctrl-C 中止时父进程同样先清理进程树,清理成功透传中断、清理失败输出含清理错误的 `failed` 事件并退出 1,绝不静默吞掉清理失败;worker 意外异常输出 `failed` 事件并退出 1(stderr 保留异常证据,`KeyboardInterrupt` 不按普通失败处理),父进程将 worker 任意其他退出码归一化为 1(运行时契约只暴露 0/1/124);父进程以内部 `--worker` flag 显式拉起子进程(不依赖环境变量,防外部预置绕过硬超时);不 mock 在线依赖、不 dry-run、不修 transport,不加入离线 gate。 +- [新功能] Bot `/analyze` 支持已登记指数入口:显式代码(`sh000016`)、CSI alias(`930955.CSI` 收敛为 `csi930955`)与注册中文名(`上证50`)均可提交,指数以结构化 `AnalysisTarget` 经 `TaskService` 贯穿到 Pipeline `process_single_stock`(`sh000016` 不再被改写为 `SH000016`);注册名称查询独立于 parser identity alias(中文名不进入 `find_by_explicit_key`/`parse_analysis_target`),同名歧义返回明确错误并要求显式代码,未登记 CSI 与未知名称返回明确错误且不提交任务;个股代码(A/HK/US)保持既有 legacy code 路径不变,股票名称输入(如 `贵州茅台`)由本次 Bot 入口新暴露——复用既有名称解析器(`resolve_name_to_code`)解析后提交 legacy code,不携带结构化 target;提交成功响应在 `BotResponse.extra` 暴露内部任务 identity(`task_id`/`stock_code`)供在线验收等内部流程使用,文本与错误路径不变、平台适配器可忽略 `extra`。 - [新功能] 新增最小 Agent 轨迹评估入口 `evals/agent_trajectory/`(Refs #1956):纯函数指标层只消费真实 `tool_calls_log + AgentResult`,冻结最小指标契约(工具命中、冗余/缓存、失败/重试、总步数/max_steps),`run_eval.py` 经 `build_agent_executor` 真实执行并输出文本摘要 + 结构化 JSON 报告;评估为 reporter 非 gate,零 `src/` 改动 - [修复] 将 litellm 依赖窗口上界收敛到 `<1.99.0`:1.99.0 起把 `prompt_cache_key` 透传给 OpenAI provider,破坏 provider 缓存测试对不透传行为的既有断言(CI backend-tests 3/3 与 backend-gate 失败);保留历史最低版本与 `!=1.82.7`/`!=1.82.8` 事故排除,同时同步更新各 LLM 兼容文档中写死的依赖约束表述,避免文档与 requirements.txt 漂移 diff --git a/docs/bot-command.md b/docs/bot-command.md index d8558aa7536..5a12bfd6015 100644 --- a/docs/bot-command.md +++ b/docs/bot-command.md @@ -52,7 +52,7 @@ bot/ ├── commands/ # 命令处理器 │ ├── __init__.py │ ├── base.py # 命令抽象基类 -│ ├── analyze.py # /analyze 股票分析 +│ ├── analyze.py # /analyze 股票/指数分析 │ ├── market.py # /market 大盘复盘 │ ├── help.py # /help 帮助信息 │ └── status.py # /status 系统状态 @@ -185,7 +185,7 @@ class CommandDispatcher: |------|------|------|------| -| /analyze | /a, 分析 | 分析指定股票 | `/analyze 600519` | +| /analyze | /a, 分析 | 分析指定股票或已登记指数 | `/analyze 600519`、`/analyze sh000016`、`/analyze 上证50` | | /market | /m, 大盘 | 大盘复盘 | `/market` | @@ -195,6 +195,31 @@ class CommandDispatcher: | /status | /s, 状态 | 系统状态 | `/status` | +### `/analyze` 支持边界 + +- 股票:A 股 6 位数字(`600519`)、港股 `HK+5 位数字`(`hk00700`)、美股 1-5 个字母(`AAPL`、`usfd`→`USFD`)。股票名称(`贵州茅台`)由本次 Bot 入口新暴露:复用既有名称解析器(`resolve_name_to_code`)解析后提交 legacy code,不携带结构化 target。 +- 已登记指数:显式代码(`sh000016`)、CSI alias(`930955.CSI` 收敛为 `csi930955`)、注册中文名(`上证50`)均可提交;指数以结构化 `AnalysisTarget` 贯穿到分析 Pipeline,`sh000016` 不会被改写为 `SH000016`。 +- 未登记 CSI(如 `930956.CSI`)、旧闸门拒绝的代码形态(如 `12345`、裸 `00700`、`600519.SH`、未登记 `sh999999`)或无法识别的名称:返回明确错误,不提交任务。 +- 注册表内存在等价名称歧义时:要求改用显式代码,不猜测、不进入股票名称兜底。 + +### Bot 指数入口在线 E2E smoke(`scripts/smoke_bot_index_entry.py`) + +用于从真实 `CommandDispatcher.dispatch_async -> AnalyzeCommand -> TaskService -> StockAnalysisPipeline` 在线贯穿单标的分析,覆盖 `SH.000016` / `上证50` / `930955.CSI` 三条矩阵场景,不经过任何 webhook transport(不 mock 在线依赖、不 dry-run)。 + +运行(单 target 参数,`--timeout` 默认 900 秒): + +```powershell +.venv\Scripts\python.exe scripts/smoke_bot_index_entry.py "SH.000016" +.venv\Scripts\python.exe scripts/smoke_bot_index_entry.py "上证50" +.venv\Scripts\python.exe scripts/smoke_bot_index_entry.py "930955.CSI" +``` + +进程职责:worker 独立子进程提交并轮询(同进程 `TaskService`),输出单行 `E2E_EVENT {json}` 事件(`phase=submitted|completed|failed|timeout`,含 `target`,按阶段附加 `task_id`/`stock_code`/`result`/`error`);父进程只负责 deadline、进程树清理和退出码(0=成功 / 1=失败 / 124=超时)。 + +失败语义:任务失败、completed 但结果不完整(canonical code 或注册名称与矩阵期望不符,或 `analysis_summary`/`operation_advice`/`trend_prediction` 任一为空或仅空白)即输出 `failed` 事件并不为零退出;超时清理进程树(Windows `taskkill /T /F`,POSIX 杀进程组),清理成功输出 `timeout` 事件并退出 124,清理失败则输出含清理错误的 `failed` 事件并退出 1,不回滚 DB / 报告 / 通知等既有副作用。用户 Ctrl-C 中止时父进程同样先清理进程树:清理成功透传中断,清理失败输出含清理错误的 `failed` 事件并退出 1,绝不静默吞掉清理失败。worker 的期望 code/name 来自脚本内置的矩阵权威映射(`SH.000016`/`上证50` → `sh000016`/`上证50`,`930955.CSI` → `csi930955`/`红利低波100`),不信任响应或任务结果自报身份:提交响应的 `stock_code` 与期望不符时输出含期望值与实际值的显式 mismatch 错误(failed 事件同时携带结构化 `stock_code` 实际值);矩阵之外的 target 与非正 `--timeout` 在提交与子进程 spawn 之前即被拒绝(参数/输入错误,退出码 2)。worker 意外异常(dispatch/轮询/事件序列化)输出 `failed` 事件并退出 1(异常证据保留在 stderr),`KeyboardInterrupt` 不按普通失败处理;父进程将 worker 的任意其他退出码归一化为 1,运行时契约只暴露 0 / 1 / 124。父进程以内部 `--worker` flag 显式拉起子进程,不依赖环境变量。 + +前置条件:需要网络与数据源/AI 凭据配置齐全(在线链路)。本脚本不属于离线 gate,不进入 CI。 + ## 五、`/status` 与模型配置诊断说明 ### 可配置层级与可用性判断依据 diff --git a/docs/bot-command_EN.md b/docs/bot-command_EN.md index e4b80fe45f5..6cb4216f582 100644 --- a/docs/bot-command_EN.md +++ b/docs/bot-command_EN.md @@ -57,7 +57,7 @@ bot/ ├── commands/ # Command handlers │ ├── __init__.py │ ├── base.py # Abstract base class for commands -│ ├── analyze.py # /analyze — stock analysis +│ ├── analyze.py # /analyze — stock/index analysis │ ├── ask.py # /ask — single-turn question │ ├── batch.py # /batch — batch watchlist analysis │ ├── chat.py # /chat — multi-turn strategy chat @@ -152,7 +152,7 @@ class BotCommand(ABC): | Command | Description | Example | |---------|-------------|---------| -| `/analyze` | Analyze a specific stock | `/analyze AAPL` or `/analyze 600519` | +| `/analyze` | Analyze a specific stock or a registered index | `/analyze AAPL`, `/analyze 600519`, `/analyze sh000016`, `/analyze 上证50` | | `/ask` | Single-turn question about a stock or the market | `/ask what is RSI for AAPL` | | `/batch` | Batch-analyze your configured watchlist | `/batch` | | `/chat` | Multi-turn strategy chat (maintains conversation context) | `/chat` | @@ -162,6 +162,26 @@ class BotCommand(ABC): > **Stock code formats:** A-shares use 6-digit codes (e.g. `600519`); HK stocks prefix `hk` (e.g. `hk00700`); US stocks use ticker symbols (e.g. `AAPL`, `TSLA`). +> **Registered index inputs:** explicit codes (`sh000016`), CSI aliases (`930955.CSI` converges to `csi930955`) and registered Chinese names (`上证50`) are all accepted. Index inputs are submitted as a structured `AnalysisTarget` that flows through to the analysis pipeline, so `sh000016` is never rewritten to `SH000016`. Unregistered CSI forms (e.g. `930956.CSI`), code shapes the legacy gate rejected (`12345`, bare `00700`, `600519.SH`, unregistered `sh999999`) and unrecognized names return an explicit error without submitting a task; ambiguous registered names require an explicit code instead of guessing. Stock inputs (A-share 6-digit, `HK`+5-digit, US 1-5 letters, e.g. `usfd`→`USFD`) keep the legacy code path. Stock-name inputs (e.g. `贵州茅台`) are newly exposed by this Bot entry: they reuse the existing name resolver (`resolve_name_to_code`) and then submit the legacy code without a structured target. + +### Bot index entry online E2E smoke (`scripts/smoke_bot_index_entry.py`) + +Walks the real `CommandDispatcher.dispatch_async -> AnalyzeCommand -> TaskService -> StockAnalysisPipeline` online for a single target, covering the `SH.000016` / `上证50` / `930955.CSI` matrix scenarios without any webhook transport (no mocked online dependencies, no dry-run). + +Run with a single target argument (`--timeout` defaults to 900 seconds): + +```powershell +.venv\Scripts\python.exe scripts/smoke_bot_index_entry.py "SH.000016" +.venv\Scripts\python.exe scripts/smoke_bot_index_entry.py "上证50" +.venv\Scripts\python.exe scripts/smoke_bot_index_entry.py "930955.CSI" +``` + +Process responsibilities: a worker subprocess submits and polls the in-process `TaskService` and prints single-line `E2E_EVENT {json}` events (`phase=submitted|completed|failed|timeout`, with `target`, plus `task_id`/`stock_code`/`result`/`error` per phase); the parent only enforces the deadline, cleans up the process tree and maps exit codes (0=success / 1=failure / 124=timeout). + +Failure semantics: a failed task or a completed-but-incomplete result (canonical code or registered name not matching the matrix expectation, or any of `analysis_summary`/`operation_advice`/`trend_prediction` empty or whitespace-only) emits a `failed` event and exits non-zero; on timeout the process tree is killed (Windows `taskkill /T /F`, POSIX process group) — a successful cleanup emits a `timeout` event and exits 124, a failed cleanup emits a `failed` event carrying the cleanup error and exits 1 — never rolling back DB / reports / notifications side effects. On a user Ctrl-C the parent also cleans up the process tree first: a successful cleanup propagates the interrupt, a failed cleanup emits a `failed` event carrying the cleanup error and exits 1 — a cleanup failure is never silently swallowed. The worker's expected code/name come from the script's built-in authoritative matrix map (`SH.000016`/`上证50` → `sh000016`/`上证50`, `930955.CSI` → `csi930955`/`红利低波100`) — never from the response or the result's self-reported identity: a submission whose `extra.stock_code` does not match the expectation fails with an explicit mismatch error carrying the expected and actual values (the failed event also carries the structured actual `stock_code`), and targets outside the matrix as well as non-positive `--timeout` are rejected before any submission or subprocess spawn (argument/input error, exit code 2). Unexpected worker exceptions (dispatch / poll / event serialization) emit a `failed` event and exit 1 with the exception evidence kept on stderr; `KeyboardInterrupt` is not treated as an ordinary failure; the parent normalizes any other worker exit code to 1 so the runtime contract only exposes 0 / 1 / 124. The parent spawns the worker with an internal `--worker` flag, not via environment variables. + +Prerequisites: network plus configured data-source and AI credentials (online chain). This script is not part of the offline gate and does not run in CI. + --- ## 5. `/status` and LLM configuration diagnostics diff --git a/docs/bot/discord-bot-config.md b/docs/bot/discord-bot-config.md index e432c2d7fff..d353177448c 100644 --- a/docs/bot/discord-bot-config.md +++ b/docs/bot/discord-bot-config.md @@ -73,19 +73,21 @@ DISCORD_BOT_STATUS=A股智能分析 | /help Discord机器人支持以下Slash命令: -1. `/analyze [full_report]` - 分析指定股票代码 - - `stock_code`: 股票代码,如 600519 +1. `/analyze [full_report]` - 分析指定股票、已登记指数或股票名称 + - `target`: 分析标的,可为股票代码(如 `600519`)、已登记指数(如 `sh000016`、`930955.CSI`、`上证50`)或股票名称(如 `贵州茅台`) - `full_report`: 可选,是否生成完整报告(包含大盘) 2. `/market_review` - 获取大盘复盘报告 3. `/help` - 查看帮助信息 +> 边界:`/analyze` 支持已登记指数入口与股票名称输入(股票名称复用既有名称解析器并提交 legacy code);`/ask` 与 `/batch` 暂不支持指数输入。 + ## 测试机器人 1. 确保机器人已成功添加到你的服务器 2. 在频道中输入`/help`,机器人会返回帮助信息 -3. 输入`/analyze 600519`测试股票分析功能 +3. 输入`/analyze 600519`测试股票分析功能(已登记指数如 `/analyze sh000016`、股票名称如 `/analyze 贵州茅台` 同样可用) 4. 输入`/market_review`测试大盘复盘功能 ## 注意事项 diff --git a/docs/full-guide.md b/docs/full-guide.md index e24903a92f8..62bbd1c8cf4 100644 --- a/docs/full-guide.md +++ b/docs/full-guide.md @@ -744,7 +744,9 @@ Web 自动补全与搜索已放行已登记指数:搜索注册中文名(如 API `/analyze` 对显式指数输入构造结构化 `AnalysisTarget`:`sh000016` 以 `asset_type=INDEX` 且 `canonical_id=sh000016` 入队,`930955.CSI`/`csi930955` 收敛为 `csi930955`。指数与同码个股(如 `sh000016` 与 `000016`)独立去重调度、互不折叠;未登记的 CSI 输入(如 `930956.CSI`)在异步单股或同步模式返回明确的 4xx,在异步批量中仅该目标进入响应 `rejected` 列表、同批其他目标正常入队。中文名称输入(如 `贵州茅台`)仍走既有股票名解析,不进入指数判型。 -> **Phase 2 边界**:默认 `STOCK_LIST`、`--schedule`、Bot 与 GitHub Actions 每日工作流暂不开放指数入口;Web/API 与一次性 `--stocks` 已支持指数,Bot/定时/每日工作流入口留待 Phase 2 后续 PR。 +Bot `/analyze` 已支持已登记指数的显式代码(`sh000016`)、CSI alias(`930955.CSI`)和注册中文名(`上证50`)。指数以 registry canonical 和结构化 `AnalysisTarget` 进入与 CLI/API 相同的 Pipeline;未登记 CSI、未知名称或歧义注册名称会明确报错且不提交任务。普通 A/HK/US 代码与股票名称继续沿用 legacy code 路径。 + +> **Phase 2 边界**:默认 `STOCK_LIST`、`--schedule`、Bot `/ask`、Bot `/batch` 与 GitHub Actions 每日工作流仍未开放指数入口;Web/API、Bot `/analyze` 与一次性 `--stocks` 已支持指数,其余定时/每日工作流入口留待后续 PR。 ### 指数与个股 Dashboard canonical 隔离(PR #2312) diff --git a/docs/full-guide_EN.md b/docs/full-guide_EN.md index 47253fc7647..62592975116 100644 --- a/docs/full-guide_EN.md +++ b/docs/full-guide_EN.md @@ -683,7 +683,9 @@ Web autocomplete and search now expose registered indices: searching a registry The API `/analyze` endpoint builds a structured `AnalysisTarget` for explicit index inputs: `sh000016` is enqueued as `asset_type=INDEX` with `canonical_id=sh000016`, and `930955.CSI`/`csi930955` converge to `csi930955`. Indices and same-digit stocks (e.g. `sh000016` vs `000016`) are deduplicated independently and never collapse. An unregistered CSI input (e.g. `930956.CSI`) returns an explicit 4xx for a single async or sync request, and in an async batch only that target enters the response `rejected` list while the rest of the batch is enqueued normally. Chinese-name inputs (e.g. `贵州茅台`) keep the existing stock-name resolution path and never enter index classification. -> **Phase 2 boundary**: default `STOCK_LIST`, `--schedule`, Bot, and the GitHub Actions daily workflow do not yet expose index entrypoints; Web/API and the one-shot `--stocks` entry support indices, with Bot/scheduled/daily-workflow entries landing in later Phase 2 PRs. +Bot `/analyze` now accepts registered-index explicit codes (`sh000016`), CSI aliases (`930955.CSI`), and registered Chinese names (`上证50`). The registry canonical and structured `AnalysisTarget` flow into the same Pipeline used by CLI/API; unregistered CSI forms, unknown names, and ambiguous registered names return an explicit error without submitting a task. Existing A/HK/US codes and stock names keep the legacy-code path. + +> **Phase 2 boundary**: default `STOCK_LIST`, `--schedule`, Bot `/ask`, Bot `/batch`, and the GitHub Actions daily workflow still do not expose index entrypoints. Web/API, Bot `/analyze`, and the one-shot `--stocks` entry support indices; the remaining scheduled/daily-workflow entry lands in a later PR. ### Index vs stock Dashboard canonical isolation (PR #2312) diff --git a/scripts/smoke_bot_index_entry.py b/scripts/smoke_bot_index_entry.py new file mode 100644 index 00000000000..95a3c78e3b2 --- /dev/null +++ b/scripts/smoke_bot_index_entry.py @@ -0,0 +1,506 @@ +# -*- coding: utf-8 -*- +""" +============================================= +Bot 指数入口 transport-independent 在线 E2E smoke +============================================= + +从真实 ``CommandDispatcher.dispatch_async -> AnalyzeCommand -> +TaskService -> StockAnalysisPipeline`` 在线贯穿单标的分析,覆盖 +SH_ALIAS / REGISTERED_NAME / CSI_ALIAS 三条矩阵场景,不经过任何 webhook +transport(不修 transport,不 mock 在线依赖,不 dry-run)。 + +运行方式(单 target 参数,--timeout 默认 900 秒):: + + .venv\\Scripts\\python.exe scripts/smoke_bot_index_entry.py "SH.000016" + .venv\\Scripts\\python.exe scripts/smoke_bot_index_entry.py "上证50" + .venv\\Scripts\\python.exe scripts/smoke_bot_index_entry.py "930955.CSI" + .venv\\Scripts\\python.exe scripts/smoke_bot_index_entry.py "SH.000016" --timeout 1800 + +进程职责: +- 父进程: 只负责 deadline、进程树清理和退出码;worker 继承控制台。 +- worker: 独立子进程(由父进程以内部 ``--worker`` flag 显式拉起,不依赖 + 任何环境变量),经真实 dispatcher 提交并在同一进程内轮询 + ``TaskService``,输出单行 ``E2E_EVENT {json}`` 事件。 + +事件契约(单行 ``E2E_EVENT {json}``,phase=submitted|completed|failed|timeout, +含 target,按阶段附加 task_id / stock_code / result / error): +- submitted : 任务已提交,附带 ``task_id`` / ``stock_code``。 +- completed : 任务完成且结构断言通过,附带 ``result``。 +- failed : 任务失败或 completed 但结果不完整,附带 ``error``。 +- timeout : worker 超过 deadline 被清理(父进程输出)。 + +退出码: 0 = 成功;1 = 失败(结构断言或 failed 事件);124 = 超时。 + +超时清理: Windows 使用 ``taskkill /T /F`` 结束整个进程树;POSIX 向进程组 +发送 SIGKILL。超时只清理进程树,不回滚 DB / 报告 / 通知等既有副作用。 + +Ctrl-C 中止: 父进程在轮询窗口收到 Ctrl-C 时同样先清理进程树——清理成功 +透传中断,清理失败输出含清理错误的 ``failed`` 事件并退出 1,绝不静默 +吞掉清理失败。 +""" + +from __future__ import annotations + +import argparse +import json +import os +import signal +import subprocess +import sys +import time +from pathlib import Path +from typing import Optional + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from scripts.check_env import _reconfigure_output_stream # noqa: E402 + +EVENT_PREFIX = "E2E_EVENT " + +# 矩阵输入 -> (canonical code, registered display name) 的权威映射。 +# worker 的期望 code/name 只从这里取值,绝不信任响应或任务结果自报的身份, +# 防止 dispatcher 路由错误时仍假通过。 +EXPECTED_OUTCOMES = { + "SH.000016": ("sh000016", "上证50"), + "上证50": ("sh000016", "上证50"), + "930955.CSI": ("csi930955", "红利低波100"), +} + + +def _resolve_expected(target: str): + """Return ``(expected_code, expected_name)`` for a matrix target. + + Raises ``ValueError`` for targets outside the required matrix. + """ + try: + return EXPECTED_OUTCOMES[target] + except KeyError: + raise ValueError( + f"unsupported smoke target: {target!r} (must be one of " + f"{sorted(EXPECTED_OUTCOMES)!r})" + ) + + +def _emit_event(phase: str, target: str, **fields) -> None: + """Print one single-line ``E2E_EVENT {json}`` event to stdout.""" + payload = {"phase": phase, "target": target} + payload.update(fields) + print(f"{EVENT_PREFIX}{json.dumps(payload, ensure_ascii=False)}", flush=True) + + +def _spawn_kwargs(platform_name: str) -> dict: + """Worker spawn kwargs: inherit the console (never ``PIPE``) and detach + the child into its own session / new process group so the parent can + kill the whole tree on timeout.""" + if platform_name == "nt": + creationflags = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0) + return {"creationflags": creationflags} if creationflags else {} + return {"start_new_session": True} + + +def _terminate_process_tree(proc, platform_name: str) -> Optional[str]: + """Kill the whole worker process tree. + + Returns ``None`` only when tree cleanup is confirmed: a successful + ``taskkill /T /F`` (Windows) or process-group kill (POSIX), or a + ``ProcessLookupError`` for the tree/group (already gone). A failed tree + cleanup returns an error string even when the direct ``proc.kill()`` + best-effort fallback succeeds — direct kill only proves the worker + process itself was killed, not its descendants, so it never erases the + original tree-cleanup error. + """ + if platform_name == "nt": + try: + result = subprocess.run( + ["taskkill", "/T", "/F", "/PID", str(proc.pid)], + timeout=30, + ) + if result.returncode == 0: + return None + taskkill_error = f"taskkill exited {result.returncode}" + except Exception as exc: + taskkill_error = f"taskkill failed: {exc}" + # Best-effort damage control: kill the worker process itself, but + # never report a confirmed tree cleanup. + try: + proc.kill() + return ( + f"{taskkill_error}; direct worker kill succeeded but " + f"tree cleanup is unconfirmed" + ) + except ProcessLookupError: + return ( + f"{taskkill_error}; worker process already gone but " + f"tree cleanup is unconfirmed" + ) + except Exception as exc: + return f"{taskkill_error}; direct worker kill also failed: {exc}" + kill_signal = getattr(signal, "SIGKILL", signal.SIGTERM) + killpg = getattr(os, "killpg", None) + try: + if killpg is not None: + killpg(proc.pid, kill_signal) + else: + # 无进程组原语:直接 kill 只能证明 worker 本身被杀,不能证明 + # 后代已清理,不得返回 None 声称树清理已确认。 + proc.kill() + return ( + "process-group kill unavailable; direct worker kill " + "succeeded but tree cleanup is unconfirmed" + ) + return None + except ProcessLookupError: + # The process group is already gone — confirmed success. + return None + except OSError as exc: + try: + proc.kill() + return ( + f"process-group kill failed: {exc}; " + f"direct worker kill succeeded but tree cleanup is unconfirmed" + ) + except ProcessLookupError: + return ( + f"process-group kill failed: {exc}; " + f"worker process already gone but tree cleanup is unconfirmed" + ) + except Exception as kill_exc: + return ( + f"process-group kill failed: {exc}; " + f"direct worker kill also failed: {kill_exc}" + ) + + +def _cleanup_process_tree(proc, platform_name: str) -> Optional[str]: + """Terminate the worker tree and wait for the worker to exit. + + Returns ``None`` only when tree cleanup is confirmed; any terminate / + post-cleanup wait / kill failure is merged into the returned error + string so callers never silently claim a confirmed cleanup. + """ + cleanup_error = _terminate_process_tree(proc, platform_name) + # Post-cleanup handling must never escape as an uncaught exception: + # merge any failure into ``cleanup_error``. + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + try: + proc.kill() + except Exception as exc: + post_error = f"post-cleanup kill failed: {exc}" + cleanup_error = ( + f"{cleanup_error}; {post_error}" + if cleanup_error is not None + else post_error + ) + except Exception as exc: + post_error = f"post-cleanup wait failed: {exc}" + cleanup_error = ( + f"{cleanup_error}; {post_error}" + if cleanup_error is not None + else post_error + ) + return cleanup_error + + +def _assert_complete_result(result: dict, expected_code: str, expected_name: str): + """Validate a completed task result. + + Returns ``None`` on success, or a human-readable failure reason string. + A completed task is only a success when the canonical code equals the + authoritative expected code, the name equals the registered display + name, and the three non-empty result fields (analysis_summary / + operation_advice / trend_prediction) are present. + """ + if not isinstance(result, dict): + return "completed result is not a dict" + if result.get("code") != expected_code: + return ( + f"result code mismatch: expected {expected_code!r}, " + f"got {result.get('code')!r}" + ) + if result.get("name") != expected_name: + return ( + f"result name mismatch: expected {expected_name!r}, " + f"got {result.get('name')!r}" + ) + missing = [ + key + for key in ("analysis_summary", "operation_advice", "trend_prediction") + if not (result.get(key) or "").strip() + ] + if missing: + return f"completed result missing non-empty fields: {missing}" + return None + + +def _poll_once(service, task_id: str, target: str, stock_code: str): + """One poll of the in-process ``TaskService``. + + Empty initial state (``None`` / ``running``) returns ``None`` so the + caller keeps waiting. Terminal states return exactly one event dict: + ``completed`` (structure assertions passed against the authoritative + matrix expectation) or ``failed`` (task failed or completed but + incomplete). + """ + expected_code, expected_name = _resolve_expected(target) + status = service.get_task_status(task_id) + if status is None or status.get("status") in ("running", "pending"): + return None + if status.get("status") == "completed": + result = status.get("result") + reason = _assert_complete_result(result, expected_code, expected_name) + if reason is not None: + return { + "phase": "failed", + "target": target, + "task_id": task_id, + "stock_code": stock_code, + "error": reason, + } + return { + "phase": "completed", + "target": target, + "task_id": task_id, + "stock_code": stock_code, + "result": result, + } + return { + "phase": "failed", + "target": target, + "task_id": task_id, + "stock_code": stock_code, + "error": status.get("error") or f"task status is {status.get('status')!r}", + } + + +# --------------------------------------------------------------------------- +# Worker +# --------------------------------------------------------------------------- +def _run_worker(target: str) -> int: + """Worker entrypoint: submit via the real dispatcher in this process and + poll the same process's TaskService until a terminal state. + + Only exits 0 when a completed event with passing structure assertions + was produced. Authoritative target validation runs BEFORE any dispatcher + construction or submission, so an unsupported target can never submit. + Unexpected exceptions from dispatch / poll / event serialization are + converted into a ``failed`` E2E event with the exception evidence on + stderr and exit 1 — never an uncaught traceback. ``KeyboardInterrupt`` + is not treated as an ordinary failure. + """ + expected_code = _resolve_expected(target)[0] + + try: + return _run_worker_inner(target, expected_code) + except KeyboardInterrupt: + raise + except Exception as exc: + _emit_event("failed", target, error=f"worker exception: {exc}") + print(f"ERROR: worker exception: {exc}", file=sys.stderr) + return 1 + + +def _run_worker_inner(target: str, expected_code: str) -> int: + """Dispatch + poll loop of the worker (see :func:`_run_worker`).""" + from datetime import datetime + + from bot.commands.analyze import AnalyzeCommand + from bot.dispatcher import CommandDispatcher + from bot.models import BotMessage, ChatType + from src.services.task_service import get_task_service + + dispatcher = CommandDispatcher() + dispatcher.register(AnalyzeCommand()) + + message = BotMessage( + platform="smoke", + message_id="smoke-e2e", + user_id="smoke", + user_name="smoke", + chat_id="smoke", + chat_type=ChatType.PRIVATE, + content=f"/analyze {target}", + raw_content=f"/analyze {target}", + mentioned=False, + timestamp=datetime.now(), + ) + + import asyncio + + response = asyncio.run(dispatcher.dispatch_async(message)) + + # 权威期望只来自矩阵映射,绝不信任 ``extra.stock_code`` 或任务结果自报 + # 身份:dispatcher 路由错误(提交了错误 code/name)时仍会失败。 + response_code = response.extra.get("stock_code") + response_task_id = response.extra.get("task_id") + if response_task_id and response_code == expected_code: + task_id = response_task_id + _emit_event( + "submitted", + target, + task_id=task_id, + stock_code=expected_code, + ) + elif response_task_id: + # 有任务 identity 但 code 与矩阵期望不符:提交了错误的标的,输出 + # 明确的 mismatch 错误(含期望值与实际值)与结构化实际 code, + # 而不是成功响应文本。 + _emit_event( + "failed", + target, + task_id=response_task_id, + stock_code=response_code, + error=( + f"submitted code mismatch: expected {expected_code!r}, " + f"got {response_code!r}" + ), + ) + return 1 + else: + _emit_event("failed", target, error=response.text) + return 1 + + service = get_task_service() + while True: + event = _poll_once(service, task_id, target, expected_code) + if event is not None: + _emit_event(event["phase"], target, **{ + k: v + for k, v in event.items() + if k not in ("phase", "target") + }) + return 0 if event["phase"] == "completed" else 1 + time.sleep(5) + + +# --------------------------------------------------------------------------- +# Parent +# --------------------------------------------------------------------------- +def _run_parent(target: str, timeout: int) -> int: + """Parent entrypoint: spawn the worker (inheriting the console), enforce + the deadline, clean up the process tree on timeout and on Ctrl-C, and + map to exit codes 0 / 1 / 124. Authoritative target validation runs + before the subprocess spawn, so an unsupported target never reaches + ``Popen``; a non-positive timeout is rejected the same way. On Ctrl-C + the parent cleans up the worker tree first: a confirmed cleanup + propagates the interrupt, a failed cleanup emits a structured ``failed`` + event and returns 1.""" + _resolve_expected(target) # raises ValueError for unsupported targets + if timeout <= 0: + raise ValueError(f"timeout must be positive, got {timeout}") + + # ``proc.wait`` without ``timeout`` would block SIGINT handling on + # Windows, so poll with the deadline instead. + child_args = [sys.executable, str(Path(__file__).resolve()), "--worker", target] + if os.name == "nt": + proc = subprocess.Popen( + child_args, + cwd=str(REPO_ROOT), + **_spawn_kwargs("nt"), + ) + else: + proc = subprocess.Popen( + child_args, + cwd=str(REPO_ROOT), + **_spawn_kwargs("posix"), + ) + deadline = time.monotonic() + timeout + while True: + try: + exit_code = proc.wait(timeout=1) + except subprocess.TimeoutExpired: + exit_code = None + except KeyboardInterrupt: + # 用户主动中止:清理 worker 进程树。清理失败不得静默吞掉—— + # 与 timeout 分支一致,输出结构化 failed 事件并返回 1,避免 + # 用户误以为进程树已清理而 worker 后代仍在跑真实副作用。 + if proc.poll() is not None: + # worker 已自行退出:无需清理,直接透传中断。 + raise + cleanup_error = _cleanup_process_tree( + proc, "nt" if os.name == "nt" else "posix" + ) + if cleanup_error is not None: + _emit_event( + "failed", + target, + error=f"interrupt cleanup failed: {cleanup_error}", + ) + return 1 + raise + if exit_code is not None: + # 文档化运行时契约只暴露 0 / 1 / 124:worker 的任意其他退出码 + # 归一化为 1,避免泄漏任意崩溃码。 + if exit_code in (0, 1, 124): + return exit_code + return 1 + if time.monotonic() >= deadline: + cleanup_error = _cleanup_process_tree( + proc, "nt" if os.name == "nt" else "posix" + ) + if cleanup_error is not None: + # 清理失败不得静默声称成功:输出结构化 failed 事件并返回 1。 + _emit_event( + "failed", + target, + error=f"timeout cleanup failed: {cleanup_error}", + ) + return 1 + _emit_event("timeout", target) + return 124 + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser( + description=( + "Bot 指数入口 transport-independent 在线 E2E smoke:" + "从真实 dispatcher 贯穿 Pipeline,单标的在线分析。" + ) + ) + parser.add_argument("target", help="矩阵输入:SH.000016 / 上证50 / 930955.CSI") + parser.add_argument( + "--timeout", + type=int, + default=900, + help="worker 超时秒数(默认 900 秒;超时清理进程树,不回滚副作用)", + ) + parser.add_argument( + "--worker", + action="store_true", + help=argparse.SUPPRESS, + ) + args = parser.parse_args(argv) + + target = (args.target or "").strip() + if not target: + print("ERROR: target 不能为空", file=sys.stderr) + return 2 + + # 权威 target 校验必须先于任何角色分支:不支持的 target 不得构造 + # dispatcher、不得提交、不得 spawn 子进程(参数/输入错误,非零返回)。 + try: + _resolve_expected(target) + except ValueError as exc: + print(f"ERROR: {exc}", file=sys.stderr) + return 2 + + # ``--timeout`` 必须为正:非正超时在 spawn/提交之前即拒绝(输入错误)。 + if args.timeout <= 0: + print(f"ERROR: --timeout 必须为正整数,got {args.timeout}", file=sys.stderr) + return 2 + + _reconfigure_output_stream(sys.stdout) + _reconfigure_output_stream(sys.stderr) + + # 角色选择只由显式 ``--worker`` flag 决定(父进程拉起子进程时显式传入), + # 不依赖任何环境变量,避免外部预置环境变量绕过父进程的硬超时。 + if args.worker: + return _run_worker(target) + return _run_parent(target, args.timeout) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/services/stock_list_parser.py b/src/services/stock_list_parser.py index 9e3e0f7fc22..65105c87753 100644 --- a/src/services/stock_list_parser.py +++ b/src/services/stock_list_parser.py @@ -87,6 +87,20 @@ def _normalize_index_key(value: str) -> str: return normalized +def _normalize_display_name(value: str) -> str: + """Normalize a display name for exact name lookup only. + + Exactly NFKC + trim + casefold. Deliberately **not** the identity + normalization of :func:`_normalize_index_key`, which rewrites exchange + variants (``000016.SH`` collapses to ``sh000016``): code-shaped display + names that are distinct under exact text equality must stay distinct here, + otherwise a name lookup would falsely report them as one key or as + ambiguous. Display-name equality is exact-text equality after this + normalization — no fuzzy search. + """ + return unicodedata.normalize("NFKC", str(value or "")).strip().casefold() + + # --------------------------------------------------------------------------- # Legacy helpers (unchanged). # --------------------------------------------------------------------------- @@ -392,6 +406,47 @@ def find_by_explicit_key(self, key: str) -> Optional[IndexEntry]: """ return self._by_resolver_key.get(_normalize_index_key(key)) + def find_by_display_name(self, name: str) -> Optional[IndexEntry]: + """Look up an index by its exact registered display name. + + Only NFKC + trim + casefold exact matches are considered — no fuzzy + search. Display names are deliberately NOT identity aliases: this + lookup is independent of :meth:`find_by_explicit_key` and never feeds + ``_by_resolver_key`` / :func:`parse_analysis_target`, so a Chinese + name can never become a parser identity alias. When two registered + entries have NFKC/casefold-equivalent display names the lookup is + ambiguous and returns ``None``; callers should detect that via + :meth:`is_ambiguous_display_name` and ask the user for an explicit + code instead of falling back to stock-name resolution. + """ + key = _normalize_display_name(name) + if not key: + return None + matches = [ + entry + for entry in self._entries + if _normalize_display_name(entry.display_name) == key + ] + if len(matches) == 1: + return matches[0] + return None + + def is_ambiguous_display_name(self, name: str) -> bool: + """True when two or more registered entries share an NFKC/casefold- + equivalent display name, so :meth:`find_by_display_name` cannot pick + a single entry.""" + key = _normalize_display_name(name) + if not key: + return False + return ( + sum( + 1 + for entry in self._entries + if _normalize_display_name(entry.display_name) == key + ) + > 1 + ) + def find_by_bare_conflict(self, bare_code: str) -> Optional[IndexEntry]: """Return the index whose explicit alias base equals ``bare_code``.""" return self._by_bare_conflict.get(_normalize_index_key(bare_code)) diff --git a/src/services/task_service.py b/src/services/task_service.py index 4606864e4cd..1411bc70941 100644 --- a/src/services/task_service.py +++ b/src/services/task_service.py @@ -24,6 +24,7 @@ from src.storage import get_db from bot.models import BotMessage from src.services.stock_code_utils import resolve_index_stock_code_for_analysis +from src.services.stock_list_parser import AnalysisTarget, ParseStatus logger = logging.getLogger(__name__) @@ -72,7 +73,8 @@ def submit_analysis( report_type: Union[ReportType, str] = ReportType.SIMPLE, source_message: Optional[BotMessage] = None, save_context_snapshot: Optional[bool] = None, - query_source: str = "bot" + query_source: str = "bot", + analysis_target: Optional[AnalysisTarget] = None ) -> Dict[str, Any]: """ 提交异步分析任务 @@ -83,6 +85,9 @@ def submit_analysis( source_message: 来源消息(用于回复) save_context_snapshot: 是否保存上下文快照 query_source: 任务来源标识(bot/api/cli/system) + analysis_target: 可选结构化分析目标(INDEX 时原样使用 + ``target.canonical_id`` 并跳过股票代码规范化,防止 + ``sh000016`` 被改写为 ``SH000016``) Returns: 任务信息字典 @@ -91,7 +96,17 @@ def submit_analysis( if isinstance(report_type, str): report_type = ReportType.from_str(report_type) - normalized_code = resolve_index_stock_code_for_analysis(code) + if ( + analysis_target is not None + and analysis_target.asset_type != ParseStatus.INDEX + ): + raise ValueError("analysis_target must be an INDEX target") + if analysis_target is not None: + # INDEX target 携带时原样使用 canonical_id,不再走股票代码 + # 规范化路径(避免 ``sh000016`` 被改写为 ``SH000016``)。 + normalized_code = analysis_target.canonical_id + else: + normalized_code = resolve_index_stock_code_for_analysis(code) if not normalized_code: raise ValueError("股票代码不能为空或仅包含空白字符") @@ -105,7 +120,8 @@ def submit_analysis( report_type, source_message, save_context_snapshot, - query_source + query_source, + analysis_target ) logger.info( @@ -153,7 +169,8 @@ def _run_analysis( report_type: ReportType = ReportType.SIMPLE, source_message: Optional[BotMessage] = None, save_context_snapshot: Optional[bool] = None, - query_source: str = "bot" + query_source: str = "bot", + analysis_target: Optional[AnalysisTarget] = None ) -> Dict[str, Any]: """ 执行单只股票分析 @@ -191,12 +208,15 @@ def _run_analysis( ) # 执行单只股票分析(启用单股推送) - result = pipeline.process_single_stock( - code=code, - skip_analysis=False, - single_stock_notify=True, - report_type=report_type - ) + process_kwargs = { + "code": code, + "skip_analysis": False, + "single_stock_notify": True, + "report_type": report_type, + } + if analysis_target is not None: + process_kwargs["analysis_target"] = analysis_target + result = pipeline.process_single_stock(**process_kwargs) if result and result.success: result_data = { diff --git a/tests/test_bot_analyze_command.py b/tests/test_bot_analyze_command.py new file mode 100644 index 00000000000..9f69180c34e --- /dev/null +++ b/tests/test_bot_analyze_command.py @@ -0,0 +1,363 @@ +# -*- coding: utf-8 -*- +"""Tests for the shared ``/analyze`` command (Bot 指数入口, PR2). + +Covers the real ``CommandDispatcher`` gate (``validate_args`` before +``execute``) with a stubbed ``TaskService`` so the tests assert the +code/target handed to ``submit_analysis`` without touching the network or +the real pipeline. +""" + +import unittest +from datetime import datetime +from unittest.mock import patch + +# Keep tests runnable when optional deps are missing. +try: + import litellm # noqa: F401 +except ModuleNotFoundError: + from tests.litellm_stub import ensure_litellm_stub + ensure_litellm_stub() + +from bot.commands.analyze import AnalyzeCommand +from bot.dispatcher import CommandDispatcher +from bot.models import BotMessage, BotResponse, ChatType +from src.services.stock_list_parser import ParseStatus + + +class _StubTaskService: + """Records the last ``submit_analysis`` call; never touches the network. + + Supports two canned outcomes (success by default, or failure) so tests + can assert both the success ``extra`` contract and the no-identity error + contract without touching the network or the real pipeline. + """ + + def __init__(self, fail: bool = False): + self.calls = [] + self._fail = fail + + def submit_analysis(self, **kwargs): + self.calls.append(kwargs) + if self._fail: + return {"success": False, "task_id": "", "error": "boom"} + return { + "success": True, + "task_id": "task-1234567890abcdef", + "code": kwargs.get("code", ""), + } + + +def _make_message(content: str) -> BotMessage: + return BotMessage( + platform="feishu", + message_id="m1", + user_id="u1", + user_name="tester", + chat_id="c1", + chat_type=ChatType.PRIVATE, + content=content, + raw_content=content, + mentioned=False, + timestamp=datetime.now(), + ) + + +class TestAnalyzeCommandDispatcherGate(unittest.TestCase): + """Real dispatcher gate: ``validate_args`` runs before ``execute`` and the + command submits through the shared ``AnalyzeCommand``.""" + + def _dispatch(self, content: str): + dispatcher = CommandDispatcher() + command = AnalyzeCommand() + dispatcher.register(command) + stub = _StubTaskService() + with patch("src.services.task_service.get_task_service", return_value=stub): + response = dispatcher.dispatch(_make_message(content)) + return response, stub + + def test_registered_code_submits_index_target(self): + response, stub = self._dispatch("/analyze sh000016") + self.assertIsInstance(response, BotResponse) + self.assertIn("分析任务已提交", response.text) + self.assertEqual(len(stub.calls), 1) + call = stub.calls[0] + self.assertEqual(call["code"], "sh000016") + target = call["analysis_target"] + self.assertIsNotNone(target) + self.assertEqual(target.asset_type, ParseStatus.INDEX) + self.assertEqual(target.canonical_id, "sh000016") + + def test_csi_alias_converges_to_canonical_index_target(self): + response, stub = self._dispatch("/analyze 930955.CSI") + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], "csi930955") + target = call["analysis_target"] + self.assertEqual(target.asset_type, ParseStatus.INDEX) + self.assertEqual(target.canonical_id, "csi930955") + + def test_registered_prefix_alias_submits_index_target(self): + """``csi930955`` is the registered canonical CSI prefix form; it must + submit with a matching INDEX target.""" + response, stub = self._dispatch("/analyze csi930955") + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], "csi930955") + target = call["analysis_target"] + self.assertIsNotNone(target) + self.assertEqual(target.asset_type, ParseStatus.INDEX) + self.assertEqual(target.canonical_id, "csi930955") + + def test_registered_suffix_alias_submits_index_target(self): + """``000016.SH`` is the registered suffix alias of sh000016; it must + submit the registry canonical with a matching INDEX target.""" + response, stub = self._dispatch("/analyze 000016.SH") + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], "sh000016") + target = call["analysis_target"] + self.assertIsNotNone(target) + self.assertEqual(target.asset_type, ParseStatus.INDEX) + self.assertEqual(target.canonical_id, "sh000016") + + def test_dotted_us_ticker_keeps_legacy_path_without_target(self): + """``BRK.B`` is a dotted US ticker the legacy gate accepts; it must + resolve to ``BRK.B`` with no structured target.""" + response, stub = self._dispatch("/analyze BRK.B") + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], "BRK.B") + self.assertIsNone(call["analysis_target"]) + + def test_parser_index_alias_ss_dotted_prefix_submits_index_target(self): + """``SS.000300`` is a parser-recognized dotted-prefix alias of the + registered sh000300 index (SS = Shanghai alias); the Bot must submit + the registry canonical with a matching INDEX target.""" + response, stub = self._dispatch("/analyze SS.000300") + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], "sh000300") + target = call["analysis_target"] + self.assertIsNotNone(target) + self.assertEqual(target.asset_type, ParseStatus.INDEX) + self.assertEqual(target.canonical_id, "sh000300") + + def test_dotted_prefix_sh_alias_submits_index_target(self): + """``SH.000016`` is a parser-recognized dotted-prefix alias of the + registered sh000016 index; the Bot must submit the registry canonical + with a matching INDEX target.""" + response, stub = self._dispatch("/analyze SH.000016") + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], "sh000016") + target = call["analysis_target"] + self.assertIsNotNone(target) + self.assertEqual(target.asset_type, ParseStatus.INDEX) + self.assertEqual(target.canonical_id, "sh000016") + + def test_dotted_prefix_sz_alias_submits_index_target(self): + """``SZ.399001`` is a parser-recognized dotted-prefix alias of the + registered sz399001 index; the Bot must submit the registry canonical + with a matching INDEX target.""" + response, stub = self._dispatch("/analyze SZ.399001") + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], "sz399001") + target = call["analysis_target"] + self.assertIsNotNone(target) + self.assertEqual(target.asset_type, ParseStatus.INDEX) + self.assertEqual(target.canonical_id, "sz399001") + + def test_registered_name_wins_over_stock_name_fallback(self): + with patch( + "src.services.name_to_code_resolver.resolve_name_to_code" + ) as mock_resolve: + response, stub = self._dispatch("/analyze 上证50") + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], "sh000016") + target = call["analysis_target"] + self.assertEqual(target.asset_type, ParseStatus.INDEX) + self.assertEqual(target.canonical_id, "sh000016") + self.assertEqual(target.raw_input, "上证50") + mock_resolve.assert_not_called() + + def test_stock_code_keeps_legacy_code_and_no_target(self): + response, stub = self._dispatch("/analyze 600519") + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], "600519") + self.assertIsNone(call["analysis_target"]) + + def test_stock_name_fallback_keeps_legacy_code(self): + """Deterministic: the AkShare/network online map is stubbed empty so + the real top-level ``resolve_name_to_code`` runs its local tables + only and still resolves 贵州茅台 to its legacy code.""" + response, stub = None, None + with patch( + "src.services.name_to_code_resolver._get_akshare_name_to_code", + return_value={}, + ): + response, stub = self._dispatch("/analyze 贵州茅台") + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], "600519") + self.assertIsNone(call["analysis_target"]) + + def test_hk_and_us_stock_keep_legacy_code(self): + # ``hk00700`` is uppercased to ``HK00700`` by the legacy resolver — + # the same behavior the pre-PR command already had. + for content, expected in (("/analyze hk00700", "HK00700"), ("/analyze AAPL", "AAPL")): + response, stub = self._dispatch(content) + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], expected) + self.assertIsNone(call["analysis_target"]) + + def test_lowercase_us_ticker_keeps_legacy_uppercase_path(self): + """``usfd`` is a real US ticker the old gate accepted (case-insensitive + 1-5 letters); it must resolve to ``USFD`` with no target, exactly as + before this change.""" + response, stub = self._dispatch("/analyze usfd") + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], "USFD") + self.assertIsNone(call["analysis_target"]) + + def test_legacy_invalid_shapes_return_error_without_submission(self): + """Shapes the old validate_args gate rejected must stay rejected — + explicit error and no TaskService call.""" + for code in ("12345", "00700", "600519.SH", "sh999999"): + with self.subTest(code=code): + response, stub = self._dispatch(f"/analyze {code}") + self.assertIn("无效的标的代码", response.text) + self.assertEqual(len(stub.calls), 0) + + def test_unregistered_csi_returns_error_and_does_not_submit(self): + response, stub = self._dispatch("/analyze 930956.CSI") + self.assertIn("无法分析", response.text) + self.assertIn("CSI", response.text) + self.assertEqual(len(stub.calls), 0) + + def test_malformed_csi_numeric_forms_return_csi_error_without_submission( + self, + ): + """The full numeric explicit CSI family (``csi`` + digits, or digits + + ``.csi``) is rejected with the CSI-specific error — never submitted, + never routed into stock-name resolution.""" + for code in ("csi930956", "csi123", "12345.csi"): + with self.subTest(code=code): + response, stub = self._dispatch(f"/analyze {code}") + self.assertIn("无法分析", response.text) + self.assertIn("CSI", response.text) + self.assertEqual(len(stub.calls), 0) + + def test_parser_unsupported_malformed_code_returns_error_without_submission( + self, + ): + """A non-CSI parser-UNSUPPORTED malformed code shape (``us1``) must + return an explicit error and never submit a task.""" + response, stub = self._dispatch("/analyze us1") + self.assertIn("无法分析", response.text) + self.assertEqual(len(stub.calls), 0) + + def test_unknown_name_returns_error_and_does_not_submit(self): + """Deterministic: the AkShare/network online map is stubbed empty so + the real ``resolve_name_to_code`` runs its local tables only.""" + response, stub = None, None + with patch( + "src.services.name_to_code_resolver._get_akshare_name_to_code", + return_value={}, + ): + response, stub = self._dispatch("/analyze 不存在标的") + self.assertIn("无法识别标的", response.text) + self.assertEqual(len(stub.calls), 0) + + def test_empty_args_rejected_by_validate_args_gate(self): + response, stub = self._dispatch("/analyze") + self.assertIn("请输入", response.text) + self.assertEqual(len(stub.calls), 0) + + def test_full_report_flag_still_works(self): + response, stub = self._dispatch("/analyze sh000016 full") + self.assertIn("分析任务已提交", response.text) + call = stub.calls[0] + self.assertEqual(call["code"], "sh000016") + self.assertEqual(call["report_type"].value, "full") + + def test_success_text_is_unchanged_and_carries_task_identity_extra(self): + """On a successful submission the user-visible text must stay exactly + as before, while ``extra`` carries the internal task identity + (``task_id`` + ``stock_code``) for transport-independent consumers.""" + response, stub = self._dispatch("/analyze sh000016") + expected_text = ( + "✅ **分析任务已提交**\n\n" + "• 标的: `sh000016`\n" + "• 报告类型: 精简报告\n" + "• 任务 ID: `task-1234567890abcde...`\n\n" + "分析完成后将自动推送结果。" + ) + self.assertEqual(response.text, expected_text) + self.assertEqual(response.extra, { + "task_id": "task-1234567890abcdef", + "stock_code": "sh000016", + }) + + def test_success_extra_uses_normalized_code(self): + """``extra.stock_code`` carries the normalized code the task was + submitted under (the registry canonical for an index alias).""" + response, stub = self._dispatch("/analyze 930955.CSI") + self.assertIn("分析任务已提交", response.text) + self.assertEqual(response.extra["task_id"], "task-1234567890abcdef") + self.assertEqual(response.extra["stock_code"], "csi930955") + + def test_error_response_has_no_task_identity_extra(self): + """On a submission failure there is no task identity: no task was + created, so ``extra`` must stay empty.""" + dispatcher = CommandDispatcher() + dispatcher.register(AnalyzeCommand()) + stub = _StubTaskService(fail=True) + with patch("src.services.task_service.get_task_service", return_value=stub): + response = dispatcher.dispatch(_make_message("/analyze sh000016")) + self.assertIn("提交分析任务失败", response.text) + self.assertEqual(response.extra, {}) + + +class TestAnalyzeCommandAmbiguousName(unittest.TestCase): + """Ambiguous registered display names must fail with an explicit error and + never fall back to stock-name resolution.""" + + def test_ambiguous_display_name_returns_error(self): + from src.services.stock_list_parser import IndexEntry, IndexRegistry + + registry = IndexRegistry(( + IndexEntry( + bare_code="000300", + exchange="SH", + canonical_id="sh000300", + display_name="沪深300", + ), + IndexEntry( + bare_code="000999", + exchange="SH", + canonical_id="sh000999", + display_name="沪深300", + ), + )) + dispatcher = CommandDispatcher() + dispatcher.register(AnalyzeCommand()) + stub = _StubTaskService() + with patch( + "bot.commands.analyze.default_index_registry", return_value=registry + ), patch( + "src.services.name_to_code_resolver.resolve_name_to_code" + ) as mock_resolve, patch( + "src.services.task_service.get_task_service", return_value=stub + ): + response = dispatcher.dispatch(_make_message("/analyze 沪深300")) + self.assertIn("歧义", response.text) + self.assertEqual(stub.calls, []) + mock_resolve.assert_not_called() + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_smoke_bot_index_entry.py b/tests/test_smoke_bot_index_entry.py new file mode 100644 index 00000000000..8c6e423155e --- /dev/null +++ b/tests/test_smoke_bot_index_entry.py @@ -0,0 +1,1170 @@ +# -*- coding: utf-8 -*- +"""Offline contract tests for the Bot 指数入口 online E2E smoke runner +(``scripts/smoke_bot_index_entry.py``). + +Covers, without touching the network or spawning real children: + +* the I/O & edge-case matrix resolution (SH_ALIAS / REGISTERED_NAME / + CSI_ALIAS -> canonical id + registered display name), +* transport independence: worker spawn kwargs never use ``PIPE``, + POSIX uses ``start_new_session`` and Windows uses a new process group, +* failure/timeout semantics: failed tasks and incomplete completed results + produce a ``failed`` phase event; timeout cleanup kills the process tree, +* the single-line ``E2E_EVENT {json}`` wire format. +""" + +import io +import json +import os +import signal +import subprocess +import unittest +from contextlib import redirect_stdout +from unittest.mock import patch + +from scripts import smoke_bot_index_entry as smoke # noqa: E402 + + +class TestExpectedOutcomes(unittest.TestCase): + """The authoritative matrix map must cover exactly the three required + inputs and reject everything else.""" + + def test_matrix_covers_three_required_scenarios(self): + self.assertEqual( + smoke.EXPECTED_OUTCOMES, + { + "SH.000016": ("sh000016", "上证50"), + "上证50": ("sh000016", "上证50"), + "930955.CSI": ("csi930955", "红利低波100"), + }, + ) + + def test_resolve_expected_sh_alias(self): + self.assertEqual( + smoke._resolve_expected("SH.000016"), ("sh000016", "上证50") + ) + + def test_resolve_expected_registered_name(self): + self.assertEqual( + smoke._resolve_expected("上证50"), ("sh000016", "上证50") + ) + + def test_resolve_expected_csi_alias(self): + self.assertEqual( + smoke._resolve_expected("930955.CSI"), ("csi930955", "红利低波100") + ) + + def test_unknown_target_is_rejected(self): + with self.assertRaises(ValueError): + smoke._resolve_expected("AAPL") + with self.assertRaises(ValueError): + smoke._resolve_expected("600519") + + +class TestSpawnKwargs(unittest.TestCase): + """Worker spawn must inherit the console (no ``PIPE``) and detach into + its own session/process group so the parent can kill the whole tree.""" + + def test_posix_spawn_kwargs_use_start_new_session(self): + kwargs = smoke._spawn_kwargs("posix") + self.assertEqual(kwargs, {"start_new_session": True}) + + def test_windows_spawn_kwargs_use_new_process_group(self): + with patch.object( + smoke.subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200, create=True + ): + kwargs = smoke._spawn_kwargs("nt") + self.assertEqual(kwargs, {"creationflags": 0x00000200}) + + def test_spawn_kwargs_never_use_pipe(self): + with patch.object( + smoke.subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200, create=True + ): + for platform in ("posix", "nt"): + kwargs = smoke._spawn_kwargs(platform) + self.assertNotIn("stdout", kwargs) + self.assertNotIn("stderr", kwargs) + self.assertNotIn("stdin", kwargs) + + +class TestTerminateProcessTree(unittest.TestCase): + """Timeout cleanup must kill the whole tree: ``taskkill /T /F`` on + Windows, the process group on POSIX. Failures must be surfaced as an + error string — never silently swallowed as success — while an + already-gone process counts as success.""" + + @patch("subprocess.run") + def test_windows_uses_taskkill_tree_force(self, mock_run): + mock_run.return_value = type("R", (), {"returncode": 0})() + proc = type("Proc", (), {"pid": 4242})() + self.assertIsNone(smoke._terminate_process_tree(proc, "nt")) + mock_run.assert_called_once_with( + ["taskkill", "/T", "/F", "/PID", "4242"], timeout=30 + ) + + @patch.object(os, "killpg", create=True) + def test_posix_kills_process_group(self, mock_killpg): + proc = type("Proc", (), {"pid": 4242})() + self.assertIsNone(smoke._terminate_process_tree(proc, "posix")) + # ``SIGKILL`` does not exist on Windows; the script resolves it via + # ``getattr`` so this expectation stays portable. + kill_signal = getattr(signal, "SIGKILL", signal.SIGTERM) + mock_killpg.assert_called_once_with(4242, kill_signal) + + @patch("subprocess.run") + def test_windows_taskkill_failure_is_surfaced(self, mock_run): + """A non-zero taskkill must not be reported as success: the error is + returned (direct kill also failing keeps the error).""" + mock_run.return_value = type("R", (), {"returncode": 1})() + proc = type("Proc", (), {"pid": 4242, "kill": _raise_oserror})() + error = smoke._terminate_process_tree(proc, "nt") + self.assertIsNotNone(error) + self.assertIn("taskkill exited 1", error or "") + + @patch("subprocess.run") + def test_windows_taskkill_exception_is_surfaced(self, mock_run): + mock_run.side_effect = RuntimeError("taskkill missing") + proc = type("Proc", (), {"pid": 4242, "kill": _raise_oserror})() + error = smoke._terminate_process_tree(proc, "nt") + self.assertIsNotNone(error) + self.assertIn("taskkill failed", error or "") + + @patch("subprocess.run") + def test_windows_taskkill_failure_with_direct_kill_success(self, mock_run): + """When taskkill fails, a successful direct kill must NOT erase the + tree-cleanup error: direct kill only proves the worker process was + killed, not its descendants.""" + mock_run.return_value = type("R", (), {"returncode": 1})() + proc = type("Proc", (), {"pid": 4242, "kill": lambda self: None})() + error = smoke._terminate_process_tree(proc, "nt") + self.assertIsNotNone(error) + self.assertIn("taskkill exited 1", error or "") + self.assertIn("tree cleanup is unconfirmed", error or "") + + @patch.object(os, "killpg", create=True) + def test_posix_killpg_failure_is_surfaced(self, mock_killpg): + mock_killpg.side_effect = OSError("permission denied") + proc = type("Proc", (), {"pid": 4242, "kill": _raise_oserror})() + error = smoke._terminate_process_tree(proc, "posix") + self.assertIsNotNone(error) + self.assertIn("process-group kill failed", error or "") + + @patch.object(os, "killpg", create=True) + def test_posix_killpg_failure_with_direct_kill_success_still_fails(self, mock_killpg): + """A successful direct kill after a killpg failure must still surface + the tree-cleanup error (descendants are unconfirmed).""" + mock_killpg.side_effect = OSError("permission denied") + proc = type("Proc", (), {"pid": 4242, "kill": lambda self: None})() + error = smoke._terminate_process_tree(proc, "posix") + self.assertIsNotNone(error) + self.assertIn("process-group kill failed", error or "") + self.assertIn("tree cleanup is unconfirmed", error or "") + + @patch.object(os, "killpg", create=True) + def test_posix_already_gone_counts_as_success(self, mock_killpg): + mock_killpg.side_effect = ProcessLookupError() + proc = type("Proc", (), {"pid": 4242})() + self.assertIsNone(smoke._terminate_process_tree(proc, "posix")) + + @patch.object(os, "killpg", None, create=True) + def test_posix_without_killpg_never_claims_confirmed_tree_cleanup(self): + """Without a process-group primitive, a direct kill only proves the + worker itself was killed, not its descendants: the function must + return an unconfirmed-tree-cleanup error instead of None.""" + proc = type("Proc", (), {"pid": 4242, "kill": lambda self: None})() + error = smoke._terminate_process_tree(proc, "posix") + self.assertIsNotNone(error) + self.assertIn("tree cleanup is unconfirmed", error or "") + + +def _raise_oserror(): + raise OSError("direct kill failed") + + +class TestParentSpawn(unittest.TestCase): + """The parent must spawn the worker with the explicit hidden ``--worker`` + flag (never via environment), with no ``PIPE``, and the child must not + re-enter the parent branch when an environment role variable is preset.""" + + def _patch_popen(self, target, env=None, exit_code=0): + class _FakeProc: + def __init__(self, args, **kwargs): + self.args = args + self.kwargs = kwargs + + def wait(self, timeout=None): + return exit_code + + with patch.object(subprocess, "Popen", side_effect=_FakeProc) as mock_popen: + try: + result = smoke._run_parent(target, timeout=60) + finally: + pass + return result, mock_popen + + def test_parent_spawns_worker_with_explicit_flag_and_no_pipe(self): + result, mock_popen = self._patch_popen("SH.000016") + self.assertEqual(result, 0) + self.assertEqual(mock_popen.call_count, 1) + args, kwargs = mock_popen.call_args + self.assertIn("--worker", args[0]) + self.assertEqual(args[0][-1], "SH.000016") + self.assertNotIn("stdout", kwargs) + self.assertNotIn("stderr", kwargs) + self.assertNotIn("stdin", kwargs) + + def test_preset_env_role_cannot_force_worker_mode(self): + """An externally preset role variable must not switch the entrypoint + into worker mode: without ``--worker`` the parent branch still runs.""" + with patch.dict( + os.environ, {"DSA_SMOKE_ROLE": "worker"}, clear=False + ): + result, mock_popen = self._patch_popen("上证50") + self.assertEqual(result, 0) + self.assertEqual(mock_popen.call_count, 1) + args, kwargs = mock_popen.call_args + self.assertIn("--worker", args[0]) + self.assertEqual(args[0][-1], "上证50") + + def test_worker_flag_dispatches_to_worker_and_parent_flag_never_spawns(self): + """``main(["--worker", target])`` runs the worker directly; the + parent path (which is the only spawner) never sees ``--worker``.""" + with patch.object(smoke, "_run_worker", return_value=3) as mock_worker, patch.object( + smoke, "_run_parent", return_value=4 + ) as mock_parent: + self.assertEqual(smoke.main(["--worker", "SH.000016"]), 3) + mock_worker.assert_called_once_with("SH.000016") + mock_parent.assert_not_called() + + def test_run_parent_unsupported_target_never_spawns(self): + """Unsupported targets are rejected before the subprocess spawn: the + parent must raise and never reach ``Popen``.""" + def _fail_popen(*args, **kwargs): + raise AssertionError("Popen must not be called for unsupported targets") + + with patch.object(subprocess, "Popen", side_effect=_fail_popen) as mock_popen: + with self.assertRaises(ValueError): + smoke._run_parent("AAPL", timeout=60) + mock_popen.assert_not_called() + + def test_run_worker_unsupported_target_raises_before_dispatch(self): + """``_run_worker`` defensively validates before any dispatcher + construction: an unsupported target raises and never dispatches.""" + def _fail_dispatcher(*args, **kwargs): + raise AssertionError("dispatcher must not be constructed") + + with patch("bot.dispatcher.CommandDispatcher", side_effect=_fail_dispatcher) as mock_disp: + with self.assertRaises(ValueError): + smoke._run_worker("600519") + mock_disp.assert_not_called() + + def test_main_unsupported_target_returns_error_without_running_branches(self): + """``main()`` must reject unsupported targets with a non-zero + argument/input error without calling ``_run_parent`` or + ``_run_worker`` (so nothing can submit or spawn).""" + def _fail_worker(target): + raise AssertionError("_run_worker must not be called") + + def _fail_parent(target, timeout): + raise AssertionError("_run_parent must not be called") + + with patch.object(smoke, "_run_worker", side_effect=_fail_worker) as mock_worker, patch.object( + smoke, "_run_parent", side_effect=_fail_parent + ) as mock_parent: + result = smoke.main(["AAPL"]) + self.assertEqual(result, 2) + mock_worker.assert_not_called() + mock_parent.assert_not_called() + + def test_run_parent_timeout_kills_tree_emits_event_and_exits_124(self): + """TIMEOUT matrix row: when the worker outlives the deadline the + parent cleans up the process tree, emits a timeout ``E2E_EVENT`` with + the target and exits 124.""" + import io + from contextlib import redirect_stdout + + class _NeverEndingProc: + def __init__(self, args, **kwargs): + self.args = args + self.kwargs = kwargs + + def wait(self, timeout=None): + raise subprocess.TimeoutExpired("worker", timeout or 1) + + def kill(self): + pass + + def _kill(proc, platform_name): + killed.append((proc, platform_name)) + + killed = [] + buf = io.StringIO() + # 第一次 monotonic 调用计算 deadline;后续调用(轮询循环内)必须越过 + # deadline。用单调递增序列而非固定两项列表,容忍实现中任何无害的 + # 额外 ``time.monotonic()`` 调用。 + monotonic_values = iter([1000.0, 1061.0, 1062.0, 1063.0]) + with patch.object( + subprocess, "Popen", side_effect=_NeverEndingProc + ), patch.object(smoke, "_terminate_process_tree", side_effect=_kill), patch( + "time.monotonic", side_effect=lambda: next(monotonic_values) + ), redirect_stdout(buf): + result = smoke._run_parent("SH.000016", timeout=60) + + self.assertEqual(result, 124) + self.assertEqual(len(killed), 1) + event_line = next( + line for line in buf.getvalue().splitlines() + if line.startswith("E2E_EVENT ") + ) + payload = json.loads(event_line[len("E2E_EVENT "):]) + self.assertEqual(payload["phase"], "timeout") + self.assertEqual(payload["target"], "SH.000016") + + def test_run_parent_timeout_cleanup_failure_emits_failed_and_exits_1(self): + """When tree cleanup fails on timeout, the parent must NOT claim + success: it emits a structured failed event with the cleanup error + and returns 1 (not 124).""" + import io + from contextlib import redirect_stdout + + class _NeverEndingProc: + def __init__(self, args, **kwargs): + self.args = args + self.kwargs = kwargs + + def wait(self, timeout=None): + raise subprocess.TimeoutExpired("worker", timeout or 1) + + def kill(self): + pass + + monotonic_values = iter([1000.0, 1061.0, 1062.0]) + buf = io.StringIO() + with patch.object( + subprocess, "Popen", side_effect=_NeverEndingProc + ), patch.object( + smoke, + "_terminate_process_tree", + return_value="taskkill exited 128", + ), patch( + "time.monotonic", side_effect=lambda: next(monotonic_values) + ), redirect_stdout(buf): + result = smoke._run_parent("SH.000016", timeout=60) + + self.assertEqual(result, 1) + event_line = next( + line for line in buf.getvalue().splitlines() + if line.startswith("E2E_EVENT ") + ) + payload = json.loads(event_line[len("E2E_EVENT "):]) + self.assertEqual(payload["phase"], "failed") + self.assertEqual(payload["target"], "SH.000016") + self.assertIn("timeout cleanup failed", payload["error"]) + self.assertIn("taskkill exited 128", payload["error"]) + + def test_run_parent_post_cleanup_kill_failure_emits_failed_and_exits_1(self): + """A post-cleanup ``proc.kill()`` failure must not escape as an + uncaught exception: it merges into the cleanup error, emits a + structured failed event and returns 1 (never 124).""" + import io + from contextlib import redirect_stdout + + class _StuckProc: + def __init__(self, args, **kwargs): + self.args = args + self.kwargs = kwargs + + def wait(self, timeout=None): + raise subprocess.TimeoutExpired("worker", timeout or 1) + + def kill(self): + raise OSError("post-cleanup kill exploded") + + monotonic_values = iter([1000.0, 1061.0, 1062.0]) + buf = io.StringIO() + with patch.object( + subprocess, "Popen", side_effect=_StuckProc + ), patch.object( + smoke, "_terminate_process_tree", return_value=None + ), patch( + "time.monotonic", side_effect=lambda: next(monotonic_values) + ), redirect_stdout(buf): + result = smoke._run_parent("SH.000016", timeout=60) + + self.assertEqual(result, 1) + event_line = next( + line for line in buf.getvalue().splitlines() + if line.startswith("E2E_EVENT ") + ) + payload = json.loads(event_line[len("E2E_EVENT "):]) + self.assertEqual(payload["phase"], "failed") + self.assertEqual(payload["target"], "SH.000016") + self.assertIn("timeout cleanup failed", payload["error"]) + self.assertIn("post-cleanup kill failed", payload["error"]) + + def test_run_parent_normalizes_unknown_worker_exit_code_to_1(self): + """The documented runtime contract only exposes 0 / 1 / 124: any + other worker exit code is normalized to 1.""" + result, mock_popen = self._patch_popen("SH.000016", exit_code=42) + self.assertEqual(result, 1) + self.assertEqual(mock_popen.call_count, 1) + + def test_run_parent_keyboard_interrupt_cleans_tree_then_reraises(self): + """A Ctrl-C in the parent poll window must clean up the worker + process tree before propagating the interrupt, so no orphan keeps + running the real data/LLM/report/notification chain.""" + + class _InterruptingProc: + def __init__(self, args, **kwargs): + self.args = args + self.kwargs = kwargs + self._interrupted = False + + def poll(self): + return None + + def wait(self, timeout=None): + if not self._interrupted: + self._interrupted = True + raise KeyboardInterrupt() + return 0 + + def kill(self): + pass + + killed = [] + with patch.object( + subprocess, "Popen", side_effect=_InterruptingProc + ), patch.object( + smoke, "_terminate_process_tree", side_effect=lambda p, n: killed.append((p, n)) + ): + with self.assertRaises(KeyboardInterrupt): + smoke._run_parent("SH.000016", timeout=60) + self.assertEqual(len(killed), 1) + self.assertEqual(killed[0][1], "nt" if os.name == "nt" else "posix") + + def test_run_parent_keyboard_interrupt_cleanup_failure_emits_failed_and_exits_1(self): + """When tree cleanup fails on Ctrl-C, the parent must NOT silently + swallow the failure: it emits a structured failed event with the + cleanup error and returns 1 instead of re-raising the interrupt.""" + import io + from contextlib import redirect_stdout + + class _InterruptingProc: + def __init__(self, args, **kwargs): + self.args = args + self.kwargs = kwargs + self._interrupted = False + + def poll(self): + return None + + def wait(self, timeout=None): + if not self._interrupted: + self._interrupted = True + raise KeyboardInterrupt() + return 0 + + def kill(self): + pass + + buf = io.StringIO() + killed = [] + with patch.object( + subprocess, "Popen", side_effect=_InterruptingProc + ), patch.object( + smoke, + "_terminate_process_tree", + side_effect=lambda p, n: killed.append((p, n)) or "taskkill exited 128", + ), redirect_stdout(buf): + result = smoke._run_parent("SH.000016", timeout=60) + + self.assertEqual(result, 1) + self.assertEqual(len(killed), 1) + self.assertEqual(killed[0][1], "nt" if os.name == "nt" else "posix") + event_line = next( + line for line in buf.getvalue().splitlines() + if line.startswith("E2E_EVENT ") + ) + payload = json.loads(event_line[len("E2E_EVENT "):]) + self.assertEqual(payload["phase"], "failed") + self.assertEqual(payload["target"], "SH.000016") + self.assertIn("interrupt cleanup failed", payload["error"]) + self.assertIn("taskkill exited 128", payload["error"]) + + def test_run_parent_keyboard_interrupt_post_cleanup_kill_failure_emits_failed(self): + """A post-cleanup ``proc.kill()`` failure on the Ctrl-C path must + merge into the cleanup error and emit a structured failed event + (return 1), never escape as an uncaught exception.""" + import io + from contextlib import redirect_stdout + + class _StuckInterruptingProc: + def __init__(self, args, **kwargs): + self.args = args + self.kwargs = kwargs + self._interrupted = False + + def poll(self): + return None + + def wait(self, timeout=None): + if not self._interrupted: + self._interrupted = True + raise KeyboardInterrupt() + raise subprocess.TimeoutExpired("worker", timeout or 1) + + def kill(self): + raise OSError("post-cleanup kill exploded") + + buf = io.StringIO() + with patch.object( + subprocess, "Popen", side_effect=_StuckInterruptingProc + ), patch.object( + smoke, "_terminate_process_tree", return_value=None + ), redirect_stdout(buf): + result = smoke._run_parent("SH.000016", timeout=60) + + self.assertEqual(result, 1) + event_line = next( + line for line in buf.getvalue().splitlines() + if line.startswith("E2E_EVENT ") + ) + payload = json.loads(event_line[len("E2E_EVENT "):]) + self.assertEqual(payload["phase"], "failed") + self.assertEqual(payload["target"], "SH.000016") + self.assertIn("interrupt cleanup failed", payload["error"]) + self.assertIn("post-cleanup kill failed", payload["error"]) + + def test_run_parent_keyboard_interrupt_cleanup_confirmed_via_kill_reraises(self): + """When tree cleanup succeeds but the post-cleanup wait times out and + the follow-up kill succeeds, cleanup is still confirmed: the parent + re-raises the interrupt instead of emitting a failed event.""" + import io + from contextlib import redirect_stdout + + class _KillableInterruptingProc: + def __init__(self, args, **kwargs): + self.args = args + self.kwargs = kwargs + self._interrupted = False + + def poll(self): + return None + + def wait(self, timeout=None): + if not self._interrupted: + self._interrupted = True + raise KeyboardInterrupt() + raise subprocess.TimeoutExpired("worker", timeout or 1) + + def kill(self): + pass + + buf = io.StringIO() + with patch.object( + subprocess, "Popen", side_effect=_KillableInterruptingProc + ), patch.object( + smoke, "_terminate_process_tree", return_value=None + ), redirect_stdout(buf): + with self.assertRaises(KeyboardInterrupt): + smoke._run_parent("SH.000016", timeout=60) + self.assertEqual(buf.getvalue(), "") + + def test_run_parent_keyboard_interrupt_skips_cleanup_when_worker_exited(self): + """A Ctrl-C arriving after the worker already exited must NOT run + tree cleanup (which would misreport a spurious failure on Windows + taskkill against a dead PID): the interrupt is propagated directly.""" + import io + from contextlib import redirect_stdout + + class _ExitedInterruptingProc: + def __init__(self, args, **kwargs): + self.args = args + self.kwargs = kwargs + self._interrupted = False + + def poll(self): + return 0 + + def wait(self, timeout=None): + if not self._interrupted: + self._interrupted = True + raise KeyboardInterrupt() + return 0 + + def kill(self): + pass + + buf = io.StringIO() + with patch.object( + subprocess, "Popen", side_effect=_ExitedInterruptingProc + ), patch.object( + smoke, "_terminate_process_tree", side_effect=AssertionError( + "cleanup must not run when the worker already exited" + ) + ), redirect_stdout(buf): + with self.assertRaises(KeyboardInterrupt): + smoke._run_parent("SH.000016", timeout=60) + self.assertEqual(buf.getvalue(), "") + + def test_run_parent_preserves_known_exit_codes(self): + for code in (0, 1, 124): + result, _ = self._patch_popen("SH.000016", exit_code=code) + self.assertEqual(result, code) + + def test_run_parent_rejects_non_positive_timeout_before_spawn(self): + """A non-positive timeout is a defensive input error: ``_run_parent`` + raises before any subprocess spawn.""" + def _fail_popen(*args, **kwargs): + raise AssertionError("Popen must not be called for non-positive timeout") + + with patch.object(subprocess, "Popen", side_effect=_fail_popen) as mock_popen: + with self.assertRaises(ValueError): + smoke._run_parent("SH.000016", timeout=0) + with self.assertRaises(ValueError): + smoke._run_parent("SH.000016", timeout=-5) + mock_popen.assert_not_called() + + def test_main_rejects_non_positive_timeout_without_running_branches(self): + """``main()`` rejects ``--timeout <= 0`` as an input error (exit 2) + without calling ``_run_parent`` or ``_run_worker`` (no spawn).""" + def _fail_worker(target): + raise AssertionError("_run_worker must not be called") + + def _fail_parent(target, timeout): + raise AssertionError("_run_parent must not be called") + + with patch.object(smoke, "_run_worker", side_effect=_fail_worker) as mock_worker, patch.object( + smoke, "_run_parent", side_effect=_fail_parent + ) as mock_parent: + result = smoke.main(["SH.000016", "--timeout", "0"]) + self.assertEqual(result, 2) + mock_worker.assert_not_called() + mock_parent.assert_not_called() + + +class TestWorkerCodeMismatch(unittest.TestCase): + """When the response carries a task identity but the extra stock code + does not match the authoritative matrix expectation, the worker must + emit an explicit mismatch error with expected and actual values — not + the successful response text.""" + + def _run_worker_with_response(self, response): + class _FakeDispatcher: + def __init__(self, *args, **kwargs): + pass + + def register(self, command): + pass + + async def dispatch_async(self, message): + return response + + with patch("bot.dispatcher.CommandDispatcher", side_effect=_FakeDispatcher), patch( + "src.services.task_service.get_task_service" + ) as mock_service: + buf = io.StringIO() + with redirect_stdout(buf): + exit_code = smoke._run_worker("SH.000016") + mock_service.assert_not_called() + return exit_code, buf.getvalue() + + def test_code_mismatch_emits_explicit_error_with_expected_and_actual(self): + from bot.models import BotResponse + + exit_code, output = self._run_worker_with_response( + BotResponse(text="ok", extra={"task_id": "t1", "stock_code": "csi930955"}) + ) + self.assertEqual(exit_code, 1) + self.assertNotIn("E2E_EVENT {\"phase\": \"completed\"", output) + event_line = next( + line for line in output.splitlines() + if line.startswith("E2E_EVENT ") + ) + payload = json.loads(event_line[len("E2E_EVENT "):]) + self.assertEqual(payload["phase"], "failed") + self.assertEqual(payload["target"], "SH.000016") + self.assertIn("submitted code mismatch", payload["error"]) + self.assertIn("expected 'sh000016'", payload["error"]) + self.assertIn("got 'csi930955'", payload["error"]) + # 结构化 ``stock_code`` 携带实际提交的 code(与 error 中的实际值一致)。 + self.assertEqual(payload["stock_code"], "csi930955") + # 不是成功响应文本。 + self.assertNotIn("分析任务已提交", payload["error"]) + + def test_code_mismatch_with_missing_stock_code_emits_null_structured_code(self): + """When the response has a task id but no ``extra.stock_code``, the + failed event still carries a structured ``stock_code`` (null) plus + the explicit mismatch error.""" + from bot.models import BotResponse + + exit_code, output = self._run_worker_with_response( + BotResponse(text="ok", extra={"task_id": "t1"}) + ) + self.assertEqual(exit_code, 1) + event_line = next( + line for line in output.splitlines() + if line.startswith("E2E_EVENT ") + ) + payload = json.loads(event_line[len("E2E_EVENT "):]) + self.assertEqual(payload["phase"], "failed") + self.assertIn("submitted code mismatch", payload["error"]) + self.assertIn("got None", payload["error"]) + self.assertIsNone(payload["stock_code"]) + + +class TestWorkerSuccessPath(unittest.TestCase): + """Offline integration-style success path: a matching ``BotResponse.extra`` + plus a fake in-process TaskService that reaches completed must produce + ordered ``submitted`` then ``completed`` events, poll the service, and + exit 0.""" + + def _run_worker_with_service(self, service, response=None): + from bot.models import BotResponse + + if response is None: + response = BotResponse( + text="ok", extra={"task_id": "t1", "stock_code": "sh000016"} + ) + + class _FakeDispatcher: + def __init__(self, *args, **kwargs): + pass + + def register(self, command): + pass + + async def dispatch_async(self, message): + return response + + with patch("bot.dispatcher.CommandDispatcher", side_effect=_FakeDispatcher), patch( + "src.services.task_service.get_task_service", return_value=service + ), patch("time.sleep"): + buf = io.StringIO() + with redirect_stdout(buf): + exit_code = smoke._run_worker("SH.000016") + return exit_code, buf.getvalue() + + def test_success_path_polls_service_and_emits_ordered_events(self): + class _FakeService: + def __init__(self): + self.polls = 0 + + def get_task_status(self, task_id): + self.polls += 1 + if self.polls == 1: + return None # 空初始状态:等待 + return { + "status": "completed", + "code": "sh000016", + "result": { + "code": "sh000016", + "name": "上证50", + "analysis_summary": "摘要", + "operation_advice": "持有", + "trend_prediction": "震荡", + }, + } + + service = _FakeService() + exit_code, output = self._run_worker_with_service(service) + self.assertEqual(exit_code, 0) + self.assertEqual(service.polls, 2) + events = [ + json.loads(line[len("E2E_EVENT "):]) + for line in output.splitlines() + if line.startswith("E2E_EVENT ") + ] + self.assertEqual([e["phase"] for e in events], ["submitted", "completed"]) + self.assertEqual(events[0]["task_id"], "t1") + self.assertEqual(events[0]["stock_code"], "sh000016") + self.assertEqual(events[1]["result"]["code"], "sh000016") + self.assertEqual(events[1]["result"]["name"], "上证50") + + def test_no_task_id_response_returns_1_with_failed_event(self): + """A response without a task identity (e.g. submission failure) must + return 1 with a failed event and never poll the service.""" + class _FakeService: + def get_task_status(self, task_id): + raise AssertionError("service must not be polled") + + from bot.models import BotResponse + + exit_code, output = self._run_worker_with_service( + _FakeService(), + response=BotResponse(text="❌ 错误:提交分析任务失败: boom"), + ) + self.assertEqual(exit_code, 1) + events = [ + json.loads(line[len("E2E_EVENT "):]) + for line in output.splitlines() + if line.startswith("E2E_EVENT ") + ] + self.assertEqual([e["phase"] for e in events], ["failed"]) + self.assertIn("提交分析任务失败", events[0]["error"]) + + +class TestWorkerExceptionContract(unittest.TestCase): + """Unexpected exceptions from dispatch / poll / event serialization must + produce a ``failed`` E2E event and exit 1 (with evidence on stderr), + never an uncaught traceback. ``KeyboardInterrupt`` is not treated as an + ordinary failure.""" + + def _run_worker_with_dispatcher(self, dispatcher): + with patch("bot.dispatcher.CommandDispatcher", side_effect=dispatcher): + buf = io.StringIO() + err = io.StringIO() + with redirect_stdout(buf), patch("sys.stderr", err): + exit_code = smoke._run_worker("SH.000016") + return exit_code, buf.getvalue(), err.getvalue() + + def test_dispatch_exception_emits_failed_event_and_exit_1(self): + class _BoomDispatcher: + def __init__(self, *args, **kwargs): + pass + + def register(self, command): + pass + + async def dispatch_async(self, message): + raise RuntimeError("dispatch exploded") + + exit_code, output, err = self._run_worker_with_dispatcher(_BoomDispatcher) + self.assertEqual(exit_code, 1) + event_line = next( + line for line in output.splitlines() + if line.startswith("E2E_EVENT ") + ) + payload = json.loads(event_line[len("E2E_EVENT "):]) + self.assertEqual(payload["phase"], "failed") + self.assertEqual(payload["target"], "SH.000016") + self.assertIn("worker exception", payload["error"]) + self.assertIn("dispatch exploded", payload["error"]) + self.assertIn("dispatch exploded", err) + + def test_poll_exception_emits_failed_event_and_exit_1(self): + from bot.models import BotResponse + + class _BoomService: + def get_task_status(self, task_id): + raise RuntimeError("poll exploded") + + class _FakeDispatcher: + def __init__(self, *args, **kwargs): + pass + + def register(self, command): + pass + + async def dispatch_async(self, message): + return BotResponse( + text="ok", extra={"task_id": "t1", "stock_code": "sh000016"} + ) + + with patch("bot.dispatcher.CommandDispatcher", side_effect=_FakeDispatcher), patch( + "src.services.task_service.get_task_service", return_value=_BoomService() + ), patch("time.sleep"): + buf = io.StringIO() + err = io.StringIO() + with redirect_stdout(buf), patch("sys.stderr", err): + exit_code = smoke._run_worker("SH.000016") + self.assertEqual(exit_code, 1) + events = [ + json.loads(line[len("E2E_EVENT "):]) + for line in buf.getvalue().splitlines() + if line.startswith("E2E_EVENT ") + ] + self.assertEqual([e["phase"] for e in events], ["submitted", "failed"]) + self.assertIn("poll exploded", events[1]["error"]) + self.assertIn("poll exploded", err.getvalue()) + + def test_keyboard_interrupt_is_not_swallowed(self): + class _KillDispatcher: + def __init__(self, *args, **kwargs): + pass + + def register(self, command): + pass + + async def dispatch_async(self, message): + raise KeyboardInterrupt() + + with patch("bot.dispatcher.CommandDispatcher", side_effect=_KillDispatcher): + with self.assertRaises(KeyboardInterrupt): + smoke._run_worker("SH.000016") + + +class TestResultCompleteness(unittest.TestCase): + """A completed task is only a success when the canonical code equals the + authoritative expected code, the name equals the registered display name, + and the three non-empty result fields (analysis_summary / + operation_advice / trend_prediction) are present.""" + + def _complete(self): + return { + "code": "sh000016", + "name": "上证50", + "analysis_summary": "摘要", + "operation_advice": "持有", + "trend_prediction": "震荡", + } + + def test_complete_result_has_no_error(self): + self.assertIsNone( + smoke._assert_complete_result(self._complete(), "sh000016", "上证50") + ) + + def test_missing_code_is_failure(self): + result = self._complete() + del result["code"] + self.assertIn("code", smoke._assert_complete_result(result, "sh000016", "上证50") or "") + + def test_wrong_code_is_failure(self): + result = self._complete() + result["code"] = "csi930955" + self.assertIn("code", smoke._assert_complete_result(result, "sh000016", "上证50") or "") + + def test_missing_name_is_failure(self): + result = self._complete() + del result["name"] + self.assertIn("name", smoke._assert_complete_result(result, "sh000016", "上证50") or "") + + def test_wrong_name_is_failure(self): + result = self._complete() + result["name"] = "红利低波100" + self.assertIn("name", smoke._assert_complete_result(result, "sh000016", "上证50") or "") + + def test_missing_analysis_summary_is_failure(self): + result = self._complete() + del result["analysis_summary"] + self.assertIn( + "analysis_summary", + smoke._assert_complete_result(result, "sh000016", "上证50") or "", + ) + + def test_missing_operation_advice_is_failure(self): + result = self._complete() + del result["operation_advice"] + self.assertIn( + "operation_advice", + smoke._assert_complete_result(result, "sh000016", "上证50") or "", + ) + + def test_missing_trend_prediction_is_failure(self): + result = self._complete() + del result["trend_prediction"] + self.assertIn( + "trend_prediction", + smoke._assert_complete_result(result, "sh000016", "上证50") or "", + ) + + def test_empty_operation_advice_is_failure(self): + result = self._complete() + result["operation_advice"] = "" + self.assertIn( + "operation_advice", + smoke._assert_complete_result(result, "sh000016", "上证50") or "", + ) + + def test_whitespace_only_analysis_summary_is_failure(self): + result = self._complete() + result["analysis_summary"] = " \t " + self.assertIn( + "analysis_summary", + smoke._assert_complete_result(result, "sh000016", "上证50") or "", + ) + + def test_whitespace_only_operation_advice_is_failure(self): + result = self._complete() + result["operation_advice"] = " \n " + self.assertIn( + "operation_advice", + smoke._assert_complete_result(result, "sh000016", "上证50") or "", + ) + + def test_whitespace_only_trend_prediction_is_failure(self): + result = self._complete() + result["trend_prediction"] = " " + self.assertIn( + "trend_prediction", + smoke._assert_complete_result(result, "sh000016", "上证50") or "", + ) + + def test_sentiment_score_is_not_required(self): + """``sentiment_score`` is not part of the spec's required fields.""" + result = self._complete() + self.assertNotIn("sentiment_score", result) + self.assertIsNone( + smoke._assert_complete_result(result, "sh000016", "上证50") + ) + + +class TestPollOnce(unittest.TestCase): + """Empty initial state must wait (None), then surface exactly one final + phase event: completed / failed.""" + + def _service(self, status_payload): + class _FakeService: + def get_task_status(self, task_id): + return status_payload + + return _FakeService() + + def test_empty_initial_state_returns_none(self): + self.assertIsNone( + smoke._poll_once( + self._service(None), "t1", "SH.000016", "sh000016" + ) + ) + + def test_running_state_returns_none(self): + self.assertIsNone( + smoke._poll_once( + self._service({"status": "running"}), + "t1", + "SH.000016", + "sh000016", + ) + ) + + def test_completed_state_emits_completed_event(self): + event = smoke._poll_once( + self._service( + { + "status": "completed", + "code": "sh000016", + "result": { + "code": "sh000016", + "name": "上证50", + "analysis_summary": "摘要", + "operation_advice": "持有", + "trend_prediction": "震荡", + }, + } + ), + "t1", + "SH.000016", + "sh000016", + ) + self.assertEqual(event["phase"], "completed") + self.assertEqual(event["target"], "SH.000016") + self.assertEqual(event["task_id"], "t1") + self.assertEqual(event["stock_code"], "sh000016") + self.assertEqual(event["result"]["code"], "sh000016") + + def test_completed_with_wrong_code_emits_failed_event(self): + """Dispatcher routed the wrong code: the completed result carries a + different canonical, which must fail against the matrix expectation.""" + event = smoke._poll_once( + self._service( + { + "status": "completed", + "code": "csi930955", + "result": { + "code": "csi930955", + "name": "红利低波100", + "analysis_summary": "摘要", + "operation_advice": "持有", + "trend_prediction": "震荡", + }, + } + ), + "t1", + "SH.000016", + "sh000016", + ) + self.assertEqual(event["phase"], "failed") + self.assertIn("code", event.get("error", "")) + + def test_completed_with_wrong_name_emits_failed_event(self): + """The pipeline reported the wrong display name: must fail.""" + event = smoke._poll_once( + self._service( + { + "status": "completed", + "code": "sh000016", + "result": { + "code": "sh000016", + "name": "红利低波100", + "analysis_summary": "摘要", + "operation_advice": "持有", + "trend_prediction": "震荡", + }, + } + ), + "t1", + "SH.000016", + "sh000016", + ) + self.assertEqual(event["phase"], "failed") + self.assertIn("name", event.get("error", "")) + + def test_completed_without_analysis_summary_emits_failed_event(self): + event = smoke._poll_once( + self._service( + { + "status": "completed", + "code": "sh000016", + "result": { + "code": "sh000016", + "name": "上证50", + "operation_advice": "持有", + "trend_prediction": "震荡", + }, + } + ), + "t1", + "SH.000016", + "sh000016", + ) + self.assertEqual(event["phase"], "failed") + self.assertIn("analysis_summary", event.get("error", "")) + + def test_failed_state_emits_failed_event(self): + event = smoke._poll_once( + self._service({"status": "failed", "error": "数据源不可用"}), + "t1", + "SH.000016", + "sh000016", + ) + self.assertEqual(event["phase"], "failed") + self.assertIn("数据源不可用", event.get("error", "")) + + def test_completed_but_incomplete_result_emits_failed_event(self): + event = smoke._poll_once( + self._service( + { + "status": "completed", + "code": "sh000016", + "result": {"code": "sh000016", "name": "上证50"}, + } + ), + "t1", + "SH.000016", + "sh000016", + ) + self.assertEqual(event["phase"], "failed") + self.assertIn("analysis_summary", event.get("error", "")) + + +class TestEventEmit(unittest.TestCase): + """Events are single-line ``E2E_EVENT {json}`` on stdout.""" + + def test_emit_event_is_single_line_json(self): + import io + from contextlib import redirect_stdout + + buf = io.StringIO() + with redirect_stdout(buf): + smoke._emit_event("submitted", "SH.000016", task_id="t1") + line = buf.getvalue().strip() + self.assertTrue(line.startswith("E2E_EVENT ")) + payload = json.loads(line[len("E2E_EVENT "):]) + self.assertEqual(payload["phase"], "submitted") + self.assertEqual(payload["target"], "SH.000016") + self.assertEqual(payload["task_id"], "t1") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_stock_list_parser.py b/tests/test_stock_list_parser.py index 03dfaf73eb0..1cfb214a91c 100644 --- a/tests/test_stock_list_parser.py +++ b/tests/test_stock_list_parser.py @@ -429,6 +429,60 @@ def test_display_name_is_not_an_identity_alias(self) -> None: target = parse_analysis_target("沪深300") assert target.asset_type != ParseStatus.INDEX + def test_find_by_display_name_resolves_registered_name(self) -> None: + """PR2: exact registered display names resolve through the dedicated + name lookup — independent of ``find_by_explicit_key``.""" + registry = default_index_registry() + entry = registry.find_by_display_name("上证50") + assert entry is not None + assert entry.canonical_id == "sh000016" + entry2 = registry.find_by_display_name("沪深300") + assert entry2 is not None + assert entry2.canonical_id == "sh000300" + + def test_find_by_display_name_is_nfkc_trim_casefold_exact(self) -> None: + """PR2: name lookup normalizes NFKC + trim + casefold before the exact + match, but never falls back to fuzzy matching.""" + registry = default_index_registry() + # Full-width / whitespace variants of a registered name still match. + assert registry.find_by_display_name(" 上证50 ") is not None + assert registry.find_by_display_name("上证50") is not None + # Unknown names return None (no fuzzy fallback). + assert registry.find_by_display_name("不存在标的") is None + assert registry.find_by_display_name("上证5") is None + + def test_find_by_display_name_does_not_leak_into_identity_alias(self) -> None: + """PR2: a display-name hit must not make the name resolvable as an + identity alias — the parser contract stays untouched.""" + registry = default_index_registry() + assert registry.find_by_display_name("上证50") is not None + assert registry.find_by_explicit_key("上证50") is None + target = parse_analysis_target("上证50") + assert target.asset_type != ParseStatus.INDEX + + def test_ambiguous_display_name_is_reported(self) -> None: + """PR2: two entries with NFKC/casefold-equivalent display names make + the name lookup ambiguous — no guessing, no single winner.""" + registry = IndexRegistry(( + IndexEntry( + bare_code="000300", + exchange="SH", + canonical_id="sh000300", + display_name="沪深300", + ), + IndexEntry( + bare_code="000999", + exchange="SH", + canonical_id="sh000999", + display_name="沪深300", + ), + )) + assert registry.is_ambiguous_display_name("沪深300") is True + assert registry.find_by_display_name("沪深300") is None + # Explicit identity still resolves deterministically. + assert registry.find_by_explicit_key("sh000300") is not None + assert registry.find_by_explicit_key("sh000999") is not None + def test_custom_registry_rejects_text_identity_alias(self) -> None: with pytest.raises(ValueError, match="explicit code form"): IndexRegistry(( @@ -441,6 +495,40 @@ def test_custom_registry_rejects_text_identity_alias(self) -> None: ), )) + def test_code_shaped_display_names_stay_distinct_under_exact_name_lookup( + self, + ) -> None: + """PR2 review fix: display-name equality is exactly NFKC + trim + + casefold. Code-shaped names (``000016.SH`` vs ``sh000016``) that + identity normalization would falsely collapse (``_normalize_index_key`` + treats them as the same resolver key ``sh000016``) must stay distinct + for the name lookup, so each exact query resolves its own entry and + neither is reported ambiguous.""" + registry = IndexRegistry(( + IndexEntry( + bare_code="000016", + exchange="SH", + canonical_id="sh000016", + display_name="000016.SH", + ), + IndexEntry( + bare_code="000999", + exchange="SH", + canonical_id="sh000999", + display_name="sh000016", + ), + )) + # Identity normalization collapses both names to ``sh000016``, but the + # name lookup must NOT reuse it — each display name resolves exactly. + entry = registry.find_by_display_name("000016.SH") + assert entry is not None + assert entry.display_name == "000016.SH" + entry = registry.find_by_display_name("sh000016") + assert entry is not None + assert entry.display_name == "sh000016" + assert registry.is_ambiguous_display_name("000016.SH") is False + assert registry.is_ambiguous_display_name("sh000016") is False + # --------------------------------------------------------------------------- # Batch parsing helper. diff --git a/tests/test_task_service.py b/tests/test_task_service.py index 7053394e3f5..f33d93df52b 100644 --- a/tests/test_task_service.py +++ b/tests/test_task_service.py @@ -43,6 +43,19 @@ def process_single_stock(self, *args, **kwargs): return _make_failed_result(kwargs["code"]) +class _CapturingPipeline: + """Records the final ``process_single_stock`` kwargs for target assertions.""" + + calls = [] # class-level so tests can assert via the fake module attribute + + def __init__(self, *args, **kwargs): + pass + + def process_single_stock(self, *args, **kwargs): + type(self).calls.append(kwargs) + return _make_failed_result(kwargs["code"]) + + class TestTaskService(unittest.TestCase): def test_run_analysis_marks_failed_for_unsuccessful_result(self): service = TaskService() @@ -116,6 +129,94 @@ def capture_submit(*args, **kwargs): # executor.submit(self._run_analysis, code, task_id, ...) — code is arg[1] self.assertEqual(captured["args"][1], "csi930955") + def test_submit_analysis_with_index_target_skips_resolver_and_keeps_canonical(self): + """PR2: when an INDEX ``AnalysisTarget`` is supplied, ``submit_analysis`` + must use ``target.canonical_id`` verbatim and skip the stock-code + resolver — otherwise ``sh000016`` would be rewritten to ``SH000016``.""" + from src.services.stock_list_parser import AnalysisTarget, ParseStatus + + service = TaskService() + service._tasks = {} + service._tasks_lock = threading.Lock() + captured = {} + + executor = MagicMock() + + def capture_submit(*args, **kwargs): + captured["args"] = args + return "future" + + executor.submit.side_effect = capture_submit + service._executor = executor + + target = AnalysisTarget( + raw_input="sh000016", + asset_type=ParseStatus.INDEX, + canonical_id="sh000016", + display_code="上证50", + exchange="SH", + ) + + with patch("src.services.task_service.resolve_index_stock_code_for_analysis") as mock_resolve: + result = service.submit_analysis( + "sh000016", report_type="simple", query_source="cli", + analysis_target=target, + ) + + mock_resolve.assert_not_called() + self.assertEqual(result["code"], "sh000016") + self.assertIn("args", captured) + # executor.submit(self._run_analysis, code, task_id, ...) — code is arg[1] + self.assertEqual(captured["args"][1], "sh000016") + # analysis_target is the last positional arg handed to _run_analysis + self.assertIs(captured["args"][-1], target) + + def test_submit_analysis_rejects_non_index_target(self): + from src.services.stock_list_parser import parse_analysis_target + + service = TaskService() + service._executor = MagicMock() + target = parse_analysis_target("600519") + + with self.assertRaisesRegex(ValueError, "must be an INDEX target"): + service.submit_analysis("600519", analysis_target=target) + service._executor.submit.assert_not_called() + + def test_run_analysis_passes_index_target_to_pipeline(self): + """PR2: the background task must forward the same ``analysis_target`` + to ``process_single_stock`` so the pipeline receives canonical code and + the structured INDEX target together.""" + from src.services.stock_list_parser import AnalysisTarget, ParseStatus + + service = TaskService() + service._tasks = {} + service._tasks_lock = threading.Lock() + + fake_main = ModuleType("main") + fake_main.StockAnalysisPipeline = _CapturingPipeline + + target = AnalysisTarget( + raw_input="930955.CSI", + asset_type=ParseStatus.INDEX, + canonical_id="csi930955", + display_code="红利低波100", + exchange="CSI", + ) + + _CapturingPipeline.calls = [] + with patch.dict("sys.modules", {"main": fake_main}), patch( + "src.config.get_config", return_value=SimpleNamespace() + ): + result = service._run_analysis( + code="csi930955", task_id="task-index-1", analysis_target=target + ) + + self.assertFalse(result["success"]) # _CapturingPipeline returns failure + self.assertEqual(len(_CapturingPipeline.calls), 1) + call = _CapturingPipeline.calls[0] + self.assertEqual(call["code"], "csi930955") + self.assertIs(call["analysis_target"], target) + if __name__ == "__main__": import unittest