Open
【功能挑战赛】赛道4: 工作流多分支全量验收与断点续验 #7337
执心834Add on 6 hours ago
【功能挑战赛】赛道4: 工作流多分支全量验收与断点续验 #7337
Open
Total: 9 files changed+1170-80
| @@ -0,0 +1,36 @@ | |||
| 1 | +# 多目标验收与断点续验 | ||
| 2 | + | ||
| 3 | +同时跑配置检查、冒烟推理和精度校验时,旧版只看第一个依赖。配置一通过,即使精度没达标,也可能把错误模型放行。现在每项都要通过,工作流才会继续交付。 | ||
| 4 | + | ||
| 5 | +## 指定验收目标 | ||
| 6 | + | ||
| 7 | +`depends_on` 决定步骤的执行顺序。省略 `verify_targets` 时,验收会检查全部依赖。`verify_targets` 可以列出真正需要验收的步骤,把只负责安排顺序的依赖留在 `depends_on` 里。 | ||
| 8 | + | ||
| 9 | +```json | ||
| 10 | +{ | ||
| 11 | + "id": "verify", | ||
| 12 | + "type": "verify", | ||
| 13 | + "depends_on": ["prepare", "checks", "accuracy"], | ||
| 14 | + "verify_targets": ["checks::smoke", "accuracy"] | ||
| 15 | +} | ||
| 16 | +``` | ||
| 17 | + | ||
| 18 | +上面会等 `prepare`、`checks` 和 `accuracy` 跑完,只验收 `checks` 的 `smoke` 分支和 `accuracy`。如果目标写成 `checks`,验收会展开它的所有并行分支。报告会逐项标明通过、未通过或证据不足。验收失败时,报告和每项原始判定仍会保存在检查点里。 | ||
| 19 | + | ||
| 20 | +## 中断后怎么继续 | ||
| 21 | + | ||
| 22 | +每核对完一项,系统就把判定、证据指纹和验收规则指纹写到独立的 `<workflow_id>.verify.json`。整个工作流的检查点 `<workflow_id>.json` 仍按原有的执行批次保存。恢复时,只有证据和规则都相同的通过项可以复用。证据变了会重验,输出缺失或只有空白就直接记为证据不足。删除检查点时,逐项记录也会一起删除。 | ||
| 23 | + | ||
| 24 | +上游执行失败后,如果恢复计划把它拆成多个最终步骤,这些步骤都要验收。如果恢复计划跳过了上游步骤,验收仍会指出那一项缺少证据。指定的并行分支只有在唯一的最终替代步骤中找到同名分支时,才会指向新分支。 | ||
| 25 | + | ||
| 26 | +老计划和老检查点可以直接读取。单目标仍返回 `passed`、`verdict` 和 `verified_step`,其中 `verdict` 保留本次验收原文。老检查点没有逐项记录时,待执行的验收会正常检查已有输出。 | ||
| 27 | + | ||
| 28 | +## 用 CPU 离线复现 | ||
| 29 | + | ||
| 30 | +在已安装项目依赖的本机环境或 Docker 容器中,进入 `server/` 后运行同一条命令。 | ||
| 31 | + | ||
| 32 | +```bash | ||
| 33 | +python scripts/benchmark_workflow_verify.py | ||
| 34 | +``` | ||
| 35 | + | ||
| 36 | +脚本用固定数据模拟工具和验收器,并在第三项验收开始时退出子进程。为比较同样的三项工作,续验基线在同一批运行三个单目标验收步骤,多目标方案用一个验收步骤检查三项。脚本输出漏检放行、证据保留、续验省下的调用和旧结论拦截四项统计。加 `--json` 可输出机器可读结果。任一结果与预期不符,脚本会以非零状态退出。 | ||
| @@ -22,6 +22,7 @@ from app.tools.workflow.types import ( | |||
| 22 | WorkflowPlan, | 22 | WorkflowPlan, |
| 23 | WorkflowStep, | 23 | WorkflowStep, |
| 24 | ) | 24 | ) |
| 25 | +from app.tools.workflow.verification_ledger import VerificationLedger | ||
| 25 | 26 | ||
| 26 | 27 | ||
| 27 | def _get_checkpoint_dir() -> Path: | 28 | def _get_checkpoint_dir() -> Path: |
| @@ -41,6 +42,10 @@ class Checkpointer: | |||
| 41 | def __init__(self, checkpoint_dir: str | Path | None = None): | 42 | def __init__(self, checkpoint_dir: str | Path | None = None): |
| 42 | self._dir = Path(checkpoint_dir) if checkpoint_dir else _get_checkpoint_dir() | 43 | self._dir = Path(checkpoint_dir) if checkpoint_dir else _get_checkpoint_dir() |
| 43 | 44 | ||
| 45 | + @property | ||
| 46 | + def verification_ledger_dir(self) -> Path: | ||
| 47 | + return self._dir | ||
| 48 | + | ||
| 44 | async def save(self, plan: WorkflowPlan, ctx: ExecutionContext) -> None: | 49 | async def save(self, plan: WorkflowPlan, ctx: ExecutionContext) -> None: |
| 45 | """保存工作流状态到 JSON 文件。""" | 50 | """保存工作流状态到 JSON 文件。""" |
| 46 | data = { | 51 | data = { |
| @@ -112,7 +117,8 @@ class Checkpointer: | |||
| 112 | async def list_checkpoints(self) -> list[dict[str, Any]]: | 117 | async def list_checkpoints(self) -> list[dict[str, Any]]: |
| 113 | """列出所有可恢复的工作流。""" | 118 | """列出所有可恢复的工作流。""" |
| 114 | checkpoints = [] | 119 | checkpoints = [] |
| 115 | - for f in sorted(self._dir.glob("*.json"), key=os.path.getmtime, reverse=True): | 120 | + files = (f for f in self._dir.glob("*.json") if not f.name.endswith(".verify.json")) |
| 121 | + for f in sorted(files, key=os.path.getmtime, reverse=True): | ||
| 116 | try: | 122 | try: |
| 117 | data = json.loads(f.read_text(encoding="utf-8", errors="ignore")) | 123 | data = json.loads(f.read_text(encoding="utf-8", errors="ignore")) |
| 118 | plan = data.get("plan", {}) | 124 | plan = data.get("plan", {}) |
| @@ -137,12 +143,16 @@ class Checkpointer: | |||
| 137 | 143 | ||
| 138 | async def delete(self, workflow_id: str) -> bool: | 144 | async def delete(self, workflow_id: str) -> bool: |
| 139 | """删除指定工作流的 checkpoint。""" | 145 | """删除指定工作流的 checkpoint。""" |
| 146 | + self.delete_verification_ledger(workflow_id) | ||
| 140 | filepath = self._dir / f"{workflow_id}.json" | 147 | filepath = self._dir / f"{workflow_id}.json" |
| 141 | if filepath.is_file(): | 148 | if filepath.is_file(): |
| 142 | filepath.unlink() | 149 | filepath.unlink() |
| 143 | return True | 150 | return True |
| 144 | return False | 151 | return False |
| 145 | 152 | ||
| 153 | + def delete_verification_ledger(self, workflow_id: str) -> None: | ||
| 154 | + VerificationLedger(self.verification_ledger_dir, workflow_id).delete() | ||
| 155 | + | ||
| 146 | # ── 序列化辅助 ── | 156 | # ── 序列化辅助 ── |
| 147 | 157 | ||
| 148 | @staticmethod | 158 | @staticmethod |
| @@ -211,6 +221,10 @@ class Checkpointer: | |||
| 211 | else str(dep) | 221 | else str(dep) |
| 212 | for dep in deps | 222 | for dep in deps |
| 213 | ] | 223 | ] |
| 224 | + targets = data.get("verify_targets") | ||
| 225 | + values["verify_targets"] = [ | ||
| 226 | + target for target in targets if isinstance(target, str) and target.strip() | ||
| 227 | + ] if isinstance(targets, list) else [] | ||
| 214 | children = data.get("parallel_steps") | 228 | children = data.get("parallel_steps") |
| 215 | if children is not None: | 229 | if children is not None: |
| 216 | if not isinstance(children, list): | 230 | if not isinstance(children, list): |
| @@ -24,11 +24,14 @@ from app.tools.workflow.patterns import ( | |||
| 24 | ) | 24 | ) |
| 25 | from app.tools.workflow.planner import DynamicPlanner | 25 | from app.tools.workflow.planner import DynamicPlanner |
| 26 | from app.tools.workflow.types import ( | 26 | from app.tools.workflow.types import ( |
| 27 | + SUB_ID_SEP, | ||
| 27 | ExecutionContext, | 28 | ExecutionContext, |
| 28 | StepStatus, | 29 | StepStatus, |
| 30 | + StepType, | ||
| 29 | WorkflowPlan, | 31 | WorkflowPlan, |
| 30 | WorkflowStep, | 32 | WorkflowStep, |
| 31 | ) | 33 | ) |
| 34 | +from app.tools.workflow.verification_ledger import resolve_verify_targets | ||
| 32 | 35 | ||
| 33 | logger = __import__("logging").getLogger(__name__) | 36 | logger = __import__("logging").getLogger(__name__) |
| 34 | 37 | ||
| @@ -43,6 +46,7 @@ def _step_progress_payload(step: WorkflowStep) -> dict[str, Any]: | |||
| 43 | "skill_name": step.skill_name, | 46 | "skill_name": step.skill_name, |
| 44 | "prompt_template": step.prompt_template, | 47 | "prompt_template": step.prompt_template, |
| 45 | "depends_on": list(step.depends_on), | 48 | "depends_on": list(step.depends_on), |
| 49 | + "verify_targets": list(step.verify_targets), | ||
| 46 | "params": dict(step.params or {}), | 50 | "params": dict(step.params or {}), |
| 47 | "max_retries": step.max_retries, | 51 | "max_retries": step.max_retries, |
| 48 | "timeout": step.timeout, | 52 | "timeout": step.timeout, |
| @@ -69,6 +73,7 @@ def _step_signature(step: WorkflowStep) -> tuple[Any, ...]: | |||
| 69 | str(step.description or "").strip(), | 73 | str(step.description or "").strip(), |
| 70 | str(step.skill_name or "").strip(), | 74 | str(step.skill_name or "").strip(), |
| 71 | str(step.prompt_template or "").strip(), | 75 | str(step.prompt_template or "").strip(), |
| 76 | + tuple(step.verify_targets), | ||
| 72 | params, | 77 | params, |
| 73 | step.max_retries, | 78 | step.max_retries, |
| 74 | step.timeout, | 79 | step.timeout, |
| @@ -111,6 +116,11 @@ def _rewrite_step_refs(node: WorkflowStep, mapping: dict[str, list[str]]) -> Non | |||
| 111 | _rewrite_step_refs(child, mapping) | 116 | _rewrite_step_refs(child, mapping) |
| 112 | 117 | ||
| 113 | 118 | ||
| 119 | +def _freeze_verify_targets(node: WorkflowStep, plan: WorkflowPlan) -> None: | ||
| 120 | + if node.type == StepType.VERIFY and not node.verify_targets: | ||
| 121 | + node.verify_targets = resolve_verify_targets(node, plan) | ||
| 122 | + | ||
| 123 | + | ||
| 114 | def _log_hermes_error(task: "asyncio.Task") -> None: | 124 | def _log_hermes_error(task: "asyncio.Task") -> None: |
| 115 | """记录 Hermes 后台任务异常。""" | 125 | """记录 Hermes 后台任务异常。""" |
| 116 | try: | 126 | try: |
| @@ -151,11 +161,12 @@ class WorkflowExecutor: | |||
| 151 | ) -> ExecutionContext: | 161 | ) -> ExecutionContext: |
| 152 | """执行完整工作流,返回执行上下文。 | 162 | """执行完整工作流,返回执行上下文。 |
| 153 | 163 | ||
| 154 | - ctx 仅供 resume() 传入 checkpoint 恢复的上下文;默认 None 时新建空 | 164 | + ctx 仅供 resume() 传入 checkpoint 恢复的上下文;默认 None 时新建上下文。 |
| 155 | - 上下文,与原行为逐字节一致。 | ||
| 156 | """ | 165 | """ |
| 157 | if ctx is None: | 166 | if ctx is None: |
| 158 | ctx = ExecutionContext(workflow_id=plan.workflow_id) | 167 | ctx = ExecutionContext(workflow_id=plan.workflow_id) |
| 168 | + ctx.metadata["_verify_ledger_dir"] = str(self._checkpointer.verification_ledger_dir) | ||
| 169 | + | ||
| 159 | async def report_progress(event: dict) -> None: | 170 | async def report_progress(event: dict) -> None: |
| 160 | try: | 171 | try: |
| 161 | await progress_callback(event) | 172 | await progress_callback(event) |
| @@ -286,7 +297,13 @@ class WorkflowExecutor: | |||
| 286 | step, ctx, plan, | 297 | step, ctx, plan, |
| 287 | progress_callback=self._progress_callback, | 298 | progress_callback=self._progress_callback, |
| 288 | ) | 299 | ) |
| 289 | - validate_workflow_step_result(result) | 300 | + try: |
| 301 | + validate_workflow_step_result(result) | ||
| 302 | + except WorkflowStepExecutionError: | ||
| 303 | + if step.type == StepType.VERIFY: | ||
| 304 | + step.result = result | ||
| 305 | + ctx.set_step_result(step.id, result) | ||
| 306 | + raise | ||
| 290 | step.status = StepStatus.COMPLETED | 307 | step.status = StepStatus.COMPLETED |
| 291 | step.result = result | 308 | step.result = result |
| 292 | step.error = None | 309 | step.error = None |
| @@ -379,6 +396,7 @@ class WorkflowExecutor: | |||
| 379 | if node is failed: | 396 | if node is failed: |
| 380 | continue | 397 | continue |
| 381 | if failed.id in node.depends_on: | 398 | if failed.id in node.depends_on: |
| 399 | + _freeze_verify_targets(node, plan) | ||
| 382 | node.depends_on = list(dict.fromkeys( | 400 | node.depends_on = list(dict.fromkeys( |
| 383 | [d for d in node.depends_on if d != failed.id] + upstream | 401 | [d for d in node.depends_on if d != failed.id] + upstream |
| 384 | )) | 402 | )) |
| @@ -459,12 +477,38 @@ class WorkflowExecutor: | |||
| 459 | if new.id != failed.id and plan.get_step(new.id) is not None: | 477 | if new.id != failed.id and plan.get_step(new.id) is not None: |
| 460 | replacement_ref_map[new.id] = [new.id] | 478 | replacement_ref_map[new.id] = [new.id] |
| 461 | _rewrite_step_refs(new, replacement_ref_map) | 479 | _rewrite_step_refs(new, replacement_ref_map) |
| 480 | + if new.verify_targets: | ||
| 481 | + targets = [] | ||
| 482 | + for target in new.verify_targets: | ||
| 483 | + base, separator, child = target.partition(SUB_ID_SEP) | ||
| 484 | + new_base = id_map.get(base, base) if base != new.id else base | ||
| 485 | + targets.append(f"{new_base}{separator}{child}") | ||
| 486 | + new.verify_targets = list(dict.fromkeys(targets)) | ||
| 462 | new.id = id_map[new.id] | 487 | new.id = id_map[new.id] |
| 463 | new.depends_on = dependencies[new.id] | 488 | new.depends_on = dependencies[new.id] |
| 464 | - for node in downstream: | 489 | + |
| 465 | - node.depends_on = dependencies[node.id] | 490 | + target_map = {failed.id: terminals} |
| 491 | + if len(terminals) == 1: | ||
| 492 | + terminal = next(new for new in replacements if new.id == terminals[0]) | ||
| 493 | + if terminal.type == StepType.PARALLEL: | ||
| 494 | + for child in terminal.parallel_steps or []: | ||
| 495 | + target_map[f"{failed.id}{SUB_ID_SEP}{child.id}"] = [ | ||
| 496 | + f"{terminal.id}{SUB_ID_SEP}{child.id}", | ||
| 497 | + ] | ||
| 498 | + | ||
| 466 | for node in plan.steps: | 499 | for node in plan.steps: |
| 467 | - if node is not failed and node.status == StepStatus.PENDING: | 500 | + if node is failed: |
| 501 | + continue | ||
| 502 | + if failed.id in node.depends_on: | ||
| 503 | + _freeze_verify_targets(node, plan) | ||
| 504 | + node.depends_on = dependencies[node.id] | ||
| 505 | + if node.type == StepType.VERIFY: | ||
| 506 | + node.verify_targets = list(dict.fromkeys( | ||
| 507 | + replacement | ||
| 508 | + for target in node.verify_targets | ||
| 509 | + for replacement in target_map.get(target, [target]) | ||
| 510 | + )) | ||
| 511 | + if node.status == StepStatus.PENDING: | ||
| 468 | _rewrite_step_refs(node, {failed.id: terminals}) | 512 | _rewrite_step_refs(node, {failed.id: terminals}) |
| 469 | plan.steps.extend(replacements) | 513 | plan.steps.extend(replacements) |
| 470 | failed.status = StepStatus.SKIPPED | 514 | failed.status = StepStatus.SKIPPED |
| @@ -15,19 +15,27 @@ import dataclasses | |||
| 15 | import json | 15 | import json |
| 16 | import re | 16 | import re |
| 17 | import time | 17 | import time |
| 18 | -from typing import Any | 18 | +from typing import Any, Literal, cast |
| 19 | 19 | ||
| 20 | from app.config import settings | 20 | from app.config import settings |
| 21 | from app.tools.workflow.types import ( | 21 | from app.tools.workflow.types import ( |
| 22 | + SUB_ID_SEP, | ||
| 22 | ExecutionContext, | 23 | ExecutionContext, |
| 23 | StepStatus, | 24 | StepStatus, |
| 24 | StepType, | 25 | StepType, |
| 25 | WorkflowPlan, | 26 | WorkflowPlan, |
| 26 | WorkflowStep, | 27 | WorkflowStep, |
| 27 | ) | 28 | ) |
| 28 | - | 29 | +from app.tools.workflow.verification_ledger import ( |
| 29 | -# parallel 子节点图 id 分隔符,与 dashboard_bridge.SUB_SEP 一致 | 30 | + VerificationLedger, |
| 30 | -SUB_ID_SEP = "::" | 31 | + extract_target_evidence, |
| 32 | + format_evidence, | ||
| 33 | + format_verify_report, | ||
| 34 | + hash_criteria, | ||
| 35 | + hash_evidence, | ||
| 36 | + resolve_verify_targets, | ||
| 37 | + summarize_verdict, | ||
| 38 | +) | ||
| 31 | 39 | ||
| 32 | 40 | ||
| 33 | class WorkflowStepExecutionError(RuntimeError): | 41 | class WorkflowStepExecutionError(RuntimeError): |
| @@ -65,8 +73,15 @@ def validate_workflow_step_result(result: Any) -> None: | |||
| 65 | detail = str(result.get("verdict") or result.get("error") or "").strip() | 73 | detail = str(result.get("verdict") or result.get("error") or "").strip() |
| 66 | message = f"验证未通过:{detail}" if detail else "验证未通过" | 74 | message = f"验证未通过:{detail}" if detail else "验证未通过" |
| 67 | raise WorkflowStepExecutionError(message, retryable=False) | 75 | raise WorkflowStepExecutionError(message, retryable=False) |
| 68 | - for value in result.values(): | 76 | + is_verify_report = ( |
| 69 | - validate_workflow_step_result(value) | 77 | + result.get("passed") is True |
| 78 | + and result.get("status") == "PASS" | ||
| 79 | + and isinstance(result.get("target_reports"), list) | ||
| 80 | + ) | ||
| 81 | + for key, value in result.items(): | ||
| 82 | + # 验收判定已解析;报告可引用包含错误关键词的原始文本。 | ||
| 83 | + if not (is_verify_report and key in ("verdict", "target_reports")): | ||
| 84 | + validate_workflow_step_result(value) | ||
| 70 | return | 85 | return |
| 71 | if isinstance(result, (list, tuple)): | 86 | if isinstance(result, (list, tuple)): |
| 72 | for value in result: | 87 | for value in result: |
| @@ -203,8 +218,9 @@ async def _execute_parallel( | |||
| 203 | return results | 218 | return results |
| 204 | 219 | ||
| 205 | 220 | ||
| 206 | -# 结构化结论标记:`RESULT: PASS` / `RESULT: FAIL`(大小写不敏感,中英冒号均可) | 221 | +# 最后一个结构化标记为准,大小写不敏感,中英冒号均可。 |
| 207 | -_VERDICT_RE = re.compile(r"RESULT\s*[::]\s*(PASS|FAIL)", re.IGNORECASE) | 222 | +_VERDICT_RE = re.compile(r"RESULT\s*[::]\s*(PASS|FAIL|INSUFFICIENT_EVIDENCE)", re.IGNORECASE) |
| 223 | +_VerifyStatus = Literal["PASS", "FAIL", "INSUFFICIENT_EVIDENCE"] | ||
| 208 | 224 | ||
| 209 | # 结论行退化匹配用的关键词。否定式优先判定,避免 “未通过”/“not passed” 因子串误判为通过。 | 225 | # 结论行退化匹配用的关键词。否定式优先判定,避免 “未通过”/“not passed” 因子串误判为通过。 |
| 210 | _VERIFY_NEGATIVE = ( | 226 | _VERIFY_NEGATIVE = ( |
| @@ -216,6 +232,9 @@ _VERIFY_POSITIVE = ( | |||
| 216 | "通过", "正确", "一致", "有效", "符合", | 232 | "通过", "正确", "一致", "有效", "符合", |
| 217 | r"\bpass", r"\bvalid", r"\bcorrect", r"\bconsistent", r"\byes\b", | 233 | r"\bpass", r"\bvalid", r"\bcorrect", r"\bconsistent", r"\byes\b", |
| 218 | ) | 234 | ) |
| 235 | +_VERIFY_INSUFFICIENT = ( | ||
| 236 | + "证据不足", "无法验证", "缺少证据", r"\binsufficient\s+evidence\b", r"\bcannot\s+verify\b", | ||
| 237 | +) | ||
| 219 | 238 | ||
| 220 | 239 | ||
| 221 | def _keyword_hit(text: str, keywords: tuple[str, ...]) -> bool: | 240 | def _keyword_hit(text: str, keywords: tuple[str, ...]) -> bool: |
| @@ -230,44 +249,26 @@ def _keyword_hit(text: str, keywords: tuple[str, ...]) -> bool: | |||
| 230 | return False | 249 | return False |
| 231 | 250 | ||
| 232 | 251 | ||
| 233 | -def _parse_verify_verdict(result: str) -> bool: | 252 | +def _parse_verify_status(result: str) -> _VerifyStatus: |
| 234 | - """从验证响应中解析“是否通过”的结论。 | 253 | + """优先采用结构化判定,否则只读最后一行的结论。""" |
| 235 | - | ||
| 236 | - 原实现直接在响应全文里做子串匹配,任意位置出现 “通过/pass/yes …” | ||
| 237 | - 即判通过——被验证内容(可能来自不可信的前步/MCP 输出)藏一个 “yes” | ||
| 238 | - 就能骗过验证;且 “未通过”/“not passed” 因含 “通过”/“pass” 子串 | ||
| 239 | - 反被误判为通过。 | ||
| 240 | - | ||
| 241 | - 修复策略: | ||
| 242 | - 1. 优先解析约定的结构化结论标记 ``RESULT: PASS|FAIL``,取最后一次 | ||
| 243 | - 出现作为模型最终结论; | ||
| 244 | - 2. 若模型未按约定输出标记,则**仅检查响应的结论行(最后一个非空行)**, | ||
| 245 | - 并对否定式表述优先判定,避免子串误判; | ||
| 246 | - 3. 无法得出明确肯定结论时一律判为未通过(fail-closed),确保验证门禁 | ||
| 247 | - 不会被不可信内容里偶然出现的关键词绕过。 | ||
| 248 | - """ | ||
| 249 | text = result or "" | 254 | text = result or "" |
| 250 | - | ||
| 251 | - # 1) 结构化标记优先(最后一次匹配 = 最终结论) | ||
| 252 | matches = _VERDICT_RE.findall(text) | 255 | matches = _VERDICT_RE.findall(text) |
| 253 | if matches: | 256 | if matches: |
| 254 | - return matches[-1].upper() == "PASS" | 257 | + return cast(_VerifyStatus, matches[-1].upper()) |
| 255 | 258 | ||
| 256 | - # 2) 退化:仅检查结论行(最后一个非空行) | 259 | + conclusion = next((line.strip().lower() for line in reversed(text.splitlines()) if line.strip()), "") |
| 257 | - lines = [ln.strip() for ln in text.splitlines() if ln.strip()] | ||
| 258 | - if not lines: | ||
| 259 | - return False | ||
| 260 | - conclusion = lines[-1].lower() | ||
| 261 | - | ||
| 262 | - # 否定式优先,避免 “未通过/not passed” 被误判 | ||
| 263 | if _keyword_hit(conclusion, _VERIFY_NEGATIVE): | 260 | if _keyword_hit(conclusion, _VERIFY_NEGATIVE): |
| 264 | - return False | 261 | + return "FAIL" |
| 265 | - # 仅在存在明确肯定结论时判为通过 | 262 | + if _keyword_hit(conclusion, _VERIFY_INSUFFICIENT): |
| 263 | + return "INSUFFICIENT_EVIDENCE" | ||
| 266 | if _keyword_hit(conclusion, _VERIFY_POSITIVE): | 264 | if _keyword_hit(conclusion, _VERIFY_POSITIVE): |
| 267 | - return True | 265 | + return "PASS" |
| 266 | + return "INSUFFICIENT_EVIDENCE" | ||
| 268 | 267 | ||
| 269 | - # 3) 无法确定 -> 未通过(安全默认) | 268 | + |
| 270 | - return False | 269 | +def _parse_verify_verdict(result: str) -> bool: |
| 270 | + """兼容只需要是否通过的调用方。""" | ||
| 271 | + return _parse_verify_status(result) == "PASS" | ||
| 271 | 272 | ||
| 272 | 273 | ||
| 273 | async def _execute_verify( | 274 | async def _execute_verify( |
| @@ -276,41 +277,86 @@ async def _execute_verify( | |||
| 276 | plan: WorkflowPlan, | 277 | plan: WorkflowPlan, |
| 277 | progress_callback: Any = None, | 278 | progress_callback: Any = None, |
| 278 | ) -> dict[str, Any]: | 279 | ) -> dict[str, Any]: |
| 279 | - """验证步骤:检查前一步的输出。""" | 280 | + """逐项验收,所有目标都通过后才放行。""" |
| 280 | - # 找到被验证的步骤 | 281 | + targets = resolve_verify_targets(step, plan) |
| 281 | - target_id = step.depends_on[0] if step.depends_on else None | 282 | + ledger_dir = ctx.metadata.get("_verify_ledger_dir") |
| 282 | - target_result = ctx.get(target_id, "") if target_id else "" | 283 | + ledger = VerificationLedger(ledger_dir, ctx.workflow_id) if ledger_dir and targets else None |
| 284 | + base_prompt = ctx.render_prompt(step.prompt_template or "") | ||
| 285 | + criteria_sha256 = hash_criteria(base_prompt, skill_name=step.skill_name or "", params=step.params) | ||
| 283 | 286 | ||
| 284 | - prompt = ctx.render_prompt(step.prompt_template) | 287 | + target_reports = [] |
| 285 | - prompt += f"\n\n## 待验证的输出\n\n{target_result}" | 288 | + for target_id in targets: |
| 286 | - prompt += ( | 289 | + found, evidence, missing_reason = extract_target_evidence(target_id, ctx, plan) |
| 287 | - "\n\n## 结论输出要求\n\n" | 290 | + evidence_sha256 = hash_evidence(evidence) if found else None |
| 288 | - "请先简要说明判断理由,然后在回复的**最后一行单独输出结论**," | 291 | + cached = ( |
| 289 | - "格式必须严格为 `RESULT: PASS`(验证通过)或 `RESULT: FAIL`(验证不通过)," | 292 | + ledger.get_reusable_pass(step.id, target_id, evidence_sha256, criteria_sha256) |
| 290 | - "结论行不要包含任何其它文字。" | 293 | + if ledger is not None and evidence_sha256 is not None else None |
| 294 | + ) | ||
| 295 | + if cached is not None: | ||
| 296 | + target_reports.append({**cached, "reused": True}) | ||
| 297 | + continue | ||
| 298 | + | ||
| 299 | + status = "INSUFFICIENT_EVIDENCE" | ||
| 300 | + verdict = missing_reason | ||
| 301 | + if evidence_sha256 is not None: | ||
| 302 | + prompt = ( | ||
| 303 | + f"{base_prompt}\n\n## 验收目标\n\n{target_id}" | ||
| 304 | + f"\n\n## 待验证的输出\n\n{format_evidence(evidence)}" | ||
| 305 | + "\n\n## 结论输出要求\n\n" | ||
| 306 | + "请只验收当前目标并简要说明理由。最后一行单独输出以下结论之一:" | ||
| 307 | + "`RESULT: PASS`(通过)、`RESULT: FAIL`(未通过)、" | ||
| 308 | + "`RESULT: INSUFFICIENT_EVIDENCE`(证据不足)。" | ||
| 309 | + ) | ||
| 310 | + result = await _call_skill_or_tool( | ||
| 311 | + WorkflowStep( | ||
| 312 | + id=f"{step.id}_exec", | ||
| 313 | + type=StepType.CLAUDE_SKILL, | ||
| 314 | + name=step.name, | ||
| 315 | + skill_name=step.skill_name, | ||
| 316 | + prompt_template=prompt, | ||
| 317 | + params=step.params, | ||
| 318 | + timeout=step.timeout, | ||
| 319 | + ), | ||
| 320 | + ctx, | ||
| 321 | + progress_callback=progress_callback, | ||
| 322 | + ) | ||
| 323 | + verdict = str(result or "") | ||
| 324 | + status = _parse_verify_status(verdict) | ||
| 325 | + | ||
| 326 | + row = { | ||
| 327 | + "target_id": target_id, | ||
| 328 | + "status": status, | ||
| 329 | + "evidence_sha256": evidence_sha256, | ||
| 330 | + "criteria_sha256": criteria_sha256, | ||
| 331 | + "summary": summarize_verdict(verdict), | ||
| 332 | + "verdict": verdict, | ||
| 333 | + "updated_at": time.time(), | ||
| 334 | + } | ||
| 335 | + if ledger is not None: | ||
| 336 | + ledger.upsert(step.id, row) | ||
| 337 | + target_reports.append({**row, "reused": False}) | ||
| 338 | + | ||
| 339 | + failed_targets = [row["target_id"] for row in target_reports if row["status"] != "PASS"] | ||
| 340 | + passed = bool(target_reports) and not failed_targets | ||
| 341 | + overall_status = "PASS" if passed else ( | ||
| 342 | + "FAIL" if any(row["status"] == "FAIL" for row in target_reports) else "INSUFFICIENT_EVIDENCE" | ||
| 291 | ) | 343 | ) |
| 292 | - | 344 | + verdict = format_verify_report(target_reports) |
| 293 | - result = await _call_skill_or_tool( | 345 | + if len(target_reports) == 1 and not target_reports[0]["reused"]: |
| 294 | - WorkflowStep( | 346 | + raw_verdict = target_reports[0]["verdict"] |
| 295 | - id=f"{step.id}_exec", | 347 | + if raw_verdict and raw_verdict not in verdict: |
| 296 | - type=StepType.CLAUDE_SKILL, | 348 | + verdict += f"\n\n{raw_verdict}" |
| 297 | - name=step.name, | ||
| 298 | - skill_name=step.skill_name, | ||
| 299 | - prompt_template=prompt, | ||
| 300 | - params=step.params, | ||
| 301 | - timeout=step.timeout, | ||
| 302 | - ), | ||
| 303 | - ctx, | ||
| 304 | - progress_callback=progress_callback, | ||
| 305 | - ) | ||
| 306 | - | ||
| 307 | - # 判断是否通过:解析结构化结论,而非在全文里做子串匹配 | ||
| 308 | - passed = _parse_verify_verdict(result or "") | ||
| 309 | 349 | ||
| 310 | return { | 350 | return { |
| 311 | "passed": passed, | 351 | "passed": passed, |
| 312 | - "verdict": result, | 352 | + "status": overall_status, |
| 313 | - "verified_step": target_id, | 353 | + "verdict": verdict, |
| 354 | + "verified_step": targets[0] if len(targets) == 1 else None, | ||
| 355 | + "verified_steps": targets, | ||
| 356 | + "failed_targets": failed_targets, | ||
| 357 | + "reused_targets": [row["target_id"] for row in target_reports if row["reused"]], | ||
| 358 | + "evaluated_targets": [row["target_id"] for row in target_reports if not row["reused"]], | ||
| 359 | + "target_reports": target_reports, | ||
| 314 | } | 360 | } |
| 315 | 361 | ||
| 316 | 362 | ||
| @@ -17,6 +17,7 @@ from app.config import settings | |||
| 17 | from app.core.llm_factory import build_workflow_llm, extract_text_content, handle_api_error, retry_llm_call | 17 | from app.core.llm_factory import build_workflow_llm, extract_text_content, handle_api_error, retry_llm_call |
| 18 | from app.tools.skills.registry import get_skill_registry | 18 | from app.tools.skills.registry import get_skill_registry |
| 19 | from app.tools.workflow.types import ( | 19 | from app.tools.workflow.types import ( |
| 20 | + SUB_ID_SEP, | ||
| 20 | StepType, | 21 | StepType, |
| 21 | WorkflowPlan, | 22 | WorkflowPlan, |
| 22 | WorkflowStep, | 23 | WorkflowStep, |
| @@ -129,7 +130,7 @@ MCP 工具通过 MCP 协议连接到外部 Agent 服务,用于特定场景。 | |||
| 129 | 1. **claude_skill** — 调用一个 Claude Code Skill 执行复杂任务(需要文件操作、代码执行、多步推理等)。**仅当任务确实需要工具链操作时使用**,启动较慢(30-60s)。 | 130 | 1. **claude_skill** — 调用一个 Claude Code Skill 执行复杂任务(需要文件操作、代码执行、多步推理等)。**仅当任务确实需要工具链操作时使用**,启动较慢(30-60s)。 |
| 130 | 2. **llm_tool** — 调用一个 LangChain 工具执行单一操作。**适合所有简单任务**:查询、搜索、问候、解释、输出文本等不需要工具链操作的场景。 | 131 | 2. **llm_tool** — 调用一个 LangChain 工具执行单一操作。**适合所有简单任务**:查询、搜索、问候、解释、输出文本等不需要工具链操作的场景。 |
| 131 | 3. **mcp_tool** — 调用外部 MCP Agent 工具。当任务需要特定外部能力(如算子开发、Profiling 分析)时使用。需在 params 中指定 mcp_server。 | 132 | 3. **mcp_tool** — 调用外部 MCP Agent 工具。当任务需要特定外部能力(如算子开发、Profiling 分析)时使用。需在 params 中指定 mcp_server。 |
| 132 | -4. **verify** — 验证前一个步骤的输出是否正确。将前一步的结果发给另一个 Skill 或 LLM 做交叉验证。 | 133 | +4. **verify** — 逐项检查目标步骤的输出,全部通过后再继续。 |
| 133 | 5. **condition** — 条件分支。根据前一步结果决定后续走向,必须提供 condition_expression(用 {{ctx.step_id}} 引用前一步输出)。仅描述分支意图而无从判定的条件时,不要生成此类型。 | 134 | 5. **condition** — 条件分支。根据前一步结果决定后续走向,必须提供 condition_expression(用 {{ctx.step_id}} 引用前一步输出)。仅描述分支意图而无从判定的条件时,不要生成此类型。 |
| 134 | 6. **parallel** — 并行执行多个子步骤(用 parallel_steps 定义)。适合无依赖的独立任务。 | 135 | 6. **parallel** — 并行执行多个子步骤(用 parallel_steps 定义)。适合无依赖的独立任务。 |
| 135 | 7. **loop** — 循环执行一个步骤直到满足条件。 | 136 | 7. **loop** — 循环执行一个步骤直到满足条件。 |
| @@ -159,7 +160,8 @@ mcp_tool 步骤示例: | |||
| 159 | 160 | ||
| 160 | - 如果步骤 A 需要步骤 B 的输出,将 A 的 depends_on 设为 [B.id] | 161 | - 如果步骤 A 需要步骤 B 的输出,将 A 的 depends_on 设为 [B.id] |
| 161 | - 无依赖的步骤可以并行执行,放在 parallel 类型中 | 162 | - 无依赖的步骤可以并行执行,放在 parallel 类型中 |
| 162 | -- 验证步骤应紧跟在被验证的步骤之后 | 163 | +- 交付前要验收多项检查时,在 verify 步骤写 `"verify_targets": ["step_a", "step_b"]`。只验收指定并行分支时可写 `"verify_targets": ["parallel_step::child_a"]`。 |
| 164 | +- 在 verify 的 depends_on 写上所有目标的主步骤 ID。省略 verify_targets 时会验收全部依赖,并展开并行分支。 | ||
| 163 | - prompt_template 中可以用 {{ctx.step_id}} 引用前一步的输出 | 165 | - prompt_template 中可以用 {{ctx.step_id}} 引用前一步的输出 |
| 164 | - mcp_tool 步骤必须设置 params.mcp_server 指定目标服务器 | 166 | - mcp_tool 步骤必须设置 params.mcp_server 指定目标服务器 |
| 165 | - condition 步骤必须带 condition_expression,缺省会被降级为普通步骤 | 167 | - condition 步骤必须带 condition_expression,缺省会被降级为普通步骤 |
| @@ -446,6 +448,7 @@ class DynamicPlanner: | |||
| 446 | """从 LLM 返回的 dict 构建 WorkflowPlan。""" | 448 | """从 LLM 返回的 dict 构建 WorkflowPlan。""" |
| 447 | steps = [] | 449 | steps = [] |
| 448 | duplicate_ids: dict[str, str] = {} | 450 | duplicate_ids: dict[str, str] = {} |
| 451 | + duplicate_children: dict[str, str] = {} | ||
| 449 | seen_steps: dict[tuple[Any, ...], WorkflowStep] = {} | 452 | seen_steps: dict[tuple[Any, ...], WorkflowStep] = {} |
| 450 | for s in plan_dict.get("steps", []): | 453 | for s in plan_dict.get("steps", []): |
| 451 | step_type_str = s.get("type", "claude_skill") | 454 | step_type_str = s.get("type", "claude_skill") |
| @@ -472,6 +475,10 @@ class DynamicPlanner: | |||
| 472 | for i, ps in enumerate(s["parallel_steps"]) | 475 | for i, ps in enumerate(s["parallel_steps"]) |
| 473 | ] | 476 | ] |
| 474 | 477 | ||
| 478 | + targets = s.get("verify_targets") | ||
| 479 | + verify_targets = [ | ||
| 480 | + target.strip() for target in targets if isinstance(target, str) and target.strip() | ||
| 481 | + ] if step_type == StepType.VERIFY and isinstance(targets, list) else [] | ||
| 475 | step = WorkflowStep( | 482 | step = WorkflowStep( |
| 476 | id=s.get("id", f"step_{len(steps) + 1}"), | 483 | id=s.get("id", f"step_{len(steps) + 1}"), |
| 477 | type=step_type, | 484 | type=step_type, |
| @@ -480,6 +487,7 @@ class DynamicPlanner: | |||
| 480 | skill_name=s.get("skill_name"), | 487 | skill_name=s.get("skill_name"), |
| 481 | prompt_template=s.get("prompt_template", ""), | 488 | prompt_template=s.get("prompt_template", ""), |
| 482 | depends_on=s.get("depends_on", []), | 489 | depends_on=s.get("depends_on", []), |
| 490 | + verify_targets=list(dict.fromkeys(verify_targets)), | ||
| 483 | params=s.get("params", {}), | 491 | params=s.get("params", {}), |
| 484 | max_retries=s.get("max_retries", 2), | 492 | max_retries=s.get("max_retries", 2), |
| 485 | timeout=_planned_timeout(s.get("timeout"), step_type), | 493 | timeout=_planned_timeout(s.get("timeout"), step_type), |
| @@ -497,6 +505,10 @@ class DynamicPlanner: | |||
| 497 | previous = seen_steps.get(signature) | 505 | previous = seen_steps.get(signature) |
| 498 | if previous is not None: | 506 | if previous is not None: |
| 499 | duplicate_ids[step.id] = previous.id | 507 | duplicate_ids[step.id] = previous.id |
| 508 | + for child, retained in zip(step.parallel_steps or [], previous.parallel_steps or []): | ||
| 509 | + duplicate_children[f"{step.id}{SUB_ID_SEP}{child.id}"] = ( | ||
| 510 | + f"{previous.id}{SUB_ID_SEP}{retained.id}" | ||
| 511 | + ) | ||
| 500 | previous.depends_on = list(dict.fromkeys( | 512 | previous.depends_on = list(dict.fromkeys( |
| 501 | [*previous.depends_on, *step.depends_on], | 513 | [*previous.depends_on, *step.depends_on], |
| 502 | )) | 514 | )) |
| @@ -510,6 +522,13 @@ class DynamicPlanner: | |||
| 510 | duplicate_ids.get(dep, dep) for dep in step.depends_on | 522 | duplicate_ids.get(dep, dep) for dep in step.depends_on |
| 511 | if duplicate_ids.get(dep, dep) != step.id | 523 | if duplicate_ids.get(dep, dep) != step.id |
| 512 | )) | 524 | )) |
| 525 | + targets = [] | ||
| 526 | + for target in step.verify_targets: | ||
| 527 | + base, separator, child = target.partition(SUB_ID_SEP) | ||
| 528 | + targets.append(duplicate_children.get( | ||
| 529 | + target, f"{duplicate_ids.get(base, base)}{separator}{child}", | ||
| 530 | + )) | ||
| 531 | + step.verify_targets = list(dict.fromkeys(targets)) | ||
| 513 | for field_name in ("prompt_template", "condition_expression", "loop_condition"): | 532 | for field_name in ("prompt_template", "condition_expression", "loop_condition"): |
| 514 | value = getattr(step, field_name) | 533 | value = getattr(step, field_name) |
| 515 | if not value: | 534 | if not value: |
| @@ -543,6 +562,7 @@ class DynamicPlanner: | |||
| 543 | str(step.description or "").strip(), | 562 | str(step.description or "").strip(), |
| 544 | str(step.skill_name or "").strip(), | 563 | str(step.skill_name or "").strip(), |
| 545 | str(step.prompt_template or "").strip(), | 564 | str(step.prompt_template or "").strip(), |
| 565 | + tuple(step.verify_targets), | ||
| 546 | params, | 566 | params, |
| 547 | step.max_retries, | 567 | step.max_retries, |
| 548 | step.timeout, | 568 | step.timeout, |
| @@ -646,10 +666,16 @@ class DynamicPlanner: | |||
| 646 | """校验计划的合法性。""" | 666 | """校验计划的合法性。""" |
| 647 | step_ids = {s.id for s in plan.steps} | 667 | step_ids = {s.id for s in plan.steps} |
| 648 | 668 | ||
| 649 | - if not preserve_external_dependencies: | 669 | + for step in plan.steps: |
| 650 | - for step in plan.steps: | 670 | + if not preserve_external_dependencies: |
| 651 | # 初始计划没有外部步骤,自动移除不存在的依赖。 | 671 | # 初始计划没有外部步骤,自动移除不存在的依赖。 |
| 652 | step.depends_on = [d for d in step.depends_on if d in step_ids] | 672 | step.depends_on = [d for d in step.depends_on if d in step_ids] |
| 673 | + targets = [] | ||
| 674 | + for target in step.verify_targets: | ||
| 675 | + base = target.partition(SUB_ID_SEP)[0] | ||
| 676 | + if base and base != step.id and (base in step_ids or preserve_external_dependencies): | ||
| 677 | + targets.append(target) | ||
| 678 | + step.verify_targets = list(dict.fromkeys(targets)) | ||
| 653 | 679 | ||
| 654 | # skill_name / tool_name 存在性校验(主步骤与并行子步骤同一口径):未知 claude_skill 名退化通用步骤,LLM_TOOL 占位名退化 claude_skill | 680 | # skill_name / tool_name 存在性校验(主步骤与并行子步骤同一口径):未知 claude_skill 名退化通用步骤,LLM_TOOL 占位名退化 claude_skill |
| 655 | self._validate_skill_fields(plan.steps) | 681 | self._validate_skill_fields(plan.steps) |
| @@ -7,6 +7,9 @@ from dataclasses import dataclass, field | |||
| 7 | from enum import Enum | 7 | from enum import Enum |
| 8 | from typing import Any | 8 | from typing import Any |
| 9 | 9 | ||
| 10 | +# 并行分支的限定 ID 分隔符,与 dashboard_bridge.SUB_SEP 一致。 | ||
| 11 | +SUB_ID_SEP = "::" | ||
| 12 | + | ||
| 10 | 13 | ||
| 11 | class StepType(str, Enum): | 14 | class StepType(str, Enum): |
| 12 | """工作流步骤类型""" | 15 | """工作流步骤类型""" |
| @@ -55,6 +58,9 @@ class WorkflowStep: | |||
| 55 | started_at: float | None = None | 58 | started_at: float | None = None |
| 56 | completed_at: float | None = None | 59 | completed_at: float | None = None |
| 57 | 60 | ||
| 61 | + # 留空时验收全部依赖;追加字段以保留旧的构造参数位置。 | ||
| 62 | + verify_targets: list[str] = field(default_factory=list) | ||
| 63 | + | ||
| 58 | 64 | ||
| 59 | def _new_id() -> str: | 65 | def _new_id() -> str: |
| 60 | return uuid.uuid4().hex[:8] | 66 | return uuid.uuid4().hex[:8] |
| @@ -0,0 +1,224 @@ | |||
| 1 | +"""逐目标验收的证据、判定记录与摘要。""" | ||
| 2 | + | ||
| 3 | +from __future__ import annotations | ||
| 4 | + | ||
| 5 | +import hashlib | ||
| 6 | +import json | ||
| 7 | +import os | ||
| 8 | +from pathlib import Path, PureWindowsPath | ||
| 9 | +from tempfile import NamedTemporaryFile | ||
| 10 | +from threading import Lock | ||
| 11 | +from typing import Any | ||
| 12 | + | ||
| 13 | +from app.tools.workflow.types import ( | ||
| 14 | + SUB_ID_SEP, | ||
| 15 | + ExecutionContext, | ||
| 16 | + StepStatus, | ||
| 17 | + StepType, | ||
| 18 | + WorkflowPlan, | ||
| 19 | + WorkflowStep, | ||
| 20 | +) | ||
| 21 | + | ||
| 22 | +_MISSING = object() | ||
| 23 | +_LEDGER_LOCK = Lock() | ||
| 24 | +_STATUS_LABELS = {"PASS": "通过", "FAIL": "未通过", "INSUFFICIENT_EVIDENCE": "证据不足"} | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def _canonical_json(value: Any) -> str: | ||
| 28 | + # Checkpoint 同样将非 JSON 对象转成文本。混合类型的字典键先转成 JSON 键再排序。 | ||
| 29 | + try: | ||
| 30 | + return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str) | ||
| 31 | + except TypeError: | ||
| 32 | + normalized = json.loads(json.dumps(value, ensure_ascii=False, default=str)) | ||
| 33 | + return json.dumps(normalized, ensure_ascii=False, sort_keys=True, separators=(",", ":")) | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def format_evidence(value: Any) -> str: | ||
| 37 | + return value if isinstance(value, str) else _canonical_json(value) | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def _has_evidence(value: Any) -> bool: | ||
| 41 | + return value is not _MISSING and value is not None and (not isinstance(value, str) or bool(value.strip())) | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +def hash_evidence(value: Any) -> str | None: | ||
| 45 | + if not _has_evidence(value): | ||
| 46 | + return None | ||
| 47 | + return hashlib.sha256(_canonical_json(value).encode("utf-8")).hexdigest() | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def hash_criteria( | ||
| 51 | + rendered_prompt: str, | ||
| 52 | + *, | ||
| 53 | + skill_name: str = "", | ||
| 54 | + params: dict[str, Any] | None = None, | ||
| 55 | + protocol_version: str = "v1", | ||
| 56 | +) -> str: | ||
| 57 | + criteria = { | ||
| 58 | + "prompt": rendered_prompt, | ||
| 59 | + "skill_name": skill_name, | ||
| 60 | + "params": params or {}, | ||
| 61 | + "protocol_version": protocol_version, | ||
| 62 | + } | ||
| 63 | + return hashlib.sha256(_canonical_json(criteria).encode("utf-8")).hexdigest() | ||
| 64 | + | ||
| 65 | + | ||
| 66 | +def resolve_verify_targets(step: WorkflowStep, plan: WorkflowPlan) -> list[str]: | ||
| 67 | + targets = [] | ||
| 68 | + for target_id in step.verify_targets or step.depends_on: | ||
| 69 | + source = plan.get_step(target_id) if SUB_ID_SEP not in target_id else None | ||
| 70 | + if source and source.type == StepType.PARALLEL and source.parallel_steps: | ||
| 71 | + targets.extend(f"{source.id}{SUB_ID_SEP}{child.id}" for child in source.parallel_steps) | ||
| 72 | + else: | ||
| 73 | + targets.append(target_id) | ||
| 74 | + return list(dict.fromkeys(targets)) | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +def extract_target_evidence( | ||
| 78 | + target_id: str, ctx: ExecutionContext, plan: WorkflowPlan, | ||
| 79 | +) -> tuple[bool, Any, str]: | ||
| 80 | + parent_id, separator, child_id = target_id.partition(SUB_ID_SEP) | ||
| 81 | + source = plan.get_step(parent_id) | ||
| 82 | + if source and source.status == StepStatus.SKIPPED: | ||
| 83 | + return False, None, f"步骤 {parent_id} 已跳过" | ||
| 84 | + if source and source.status == StepStatus.FAILED: | ||
| 85 | + return False, None, f"步骤 {parent_id} 执行失败" | ||
| 86 | + | ||
| 87 | + # 显式的空输出也有含义,不能用旧结果填补。 | ||
| 88 | + evidence = ctx.get(target_id, _MISSING) | ||
| 89 | + if separator: | ||
| 90 | + if source is None: | ||
| 91 | + return False, None, f"找不到并行步骤 {parent_id}" | ||
| 92 | + for index, child in enumerate(source.parallel_steps or []): | ||
| 93 | + if child.id != child_id: | ||
| 94 | + continue | ||
| 95 | + if child.status == StepStatus.SKIPPED: | ||
| 96 | + return False, None, f"分支 {target_id} 已跳过" | ||
| 97 | + if child.status == StepStatus.FAILED: | ||
| 98 | + return False, None, f"分支 {target_id} 执行失败" | ||
| 99 | + if evidence is _MISSING: | ||
| 100 | + if child.status == StepStatus.COMPLETED: | ||
| 101 | + evidence = child.result | ||
| 102 | + else: | ||
| 103 | + parent_result = ctx.get(parent_id) | ||
| 104 | + if isinstance(parent_result, list) and index < len(parent_result): | ||
| 105 | + evidence = parent_result[index] | ||
| 106 | + break | ||
| 107 | + else: | ||
| 108 | + return False, None, f"找不到并行分支 {target_id}" | ||
| 109 | + elif evidence is _MISSING and source and source.status == StepStatus.COMPLETED: | ||
| 110 | + evidence = source.result | ||
| 111 | + | ||
| 112 | + if not _has_evidence(evidence): | ||
| 113 | + return False, None, "未取得有效输出" | ||
| 114 | + return True, evidence, "" | ||
| 115 | + | ||
| 116 | + | ||
| 117 | +class VerificationLedger: | ||
| 118 | + """独立于整波检查点,验收完一项就保存其判定。""" | ||
| 119 | + | ||
| 120 | + def __init__(self, checkpoint_dir: str | Path, workflow_id: str): | ||
| 121 | + if ( | ||
| 122 | + not isinstance(workflow_id, str) | ||
| 123 | + or not workflow_id.strip() | ||
| 124 | + or workflow_id == "." | ||
| 125 | + or ".." in workflow_id | ||
| 126 | + or any(char in workflow_id for char in ("/", "\\", ":", "\0")) | ||
| 127 | + or PureWindowsPath(f"{workflow_id}.verify.json").is_reserved() | ||
| 128 | + ): | ||
| 129 | + raise ValueError("无效的工作流 ID") | ||
| 130 | + directory = Path(checkpoint_dir).resolve() | ||
| 131 | + self._path = directory / f"{workflow_id}.verify.json" | ||
| 132 | + if self._path.resolve() != self._path: | ||
| 133 | + raise ValueError("验收记录路径必须位于检查点目录内") | ||
| 134 | + | ||
| 135 | + def _load(self) -> dict[str, Any]: | ||
| 136 | + try: | ||
| 137 | + data = json.loads(self._path.read_text(encoding="utf-8")) | ||
| 138 | + except (OSError, ValueError, RecursionError): | ||
| 139 | + return {} | ||
| 140 | + return data if isinstance(data, dict) else {} | ||
| 141 | + | ||
| 142 | + def load_step_rows(self, step_id: str) -> dict[str, dict]: | ||
| 143 | + with _LEDGER_LOCK: | ||
| 144 | + rows = self._load().get(step_id) | ||
| 145 | + if not isinstance(rows, dict): | ||
| 146 | + return {} | ||
| 147 | + return { | ||
| 148 | + target_id: row | ||
| 149 | + for target_id, row in rows.items() | ||
| 150 | + if isinstance(row, dict) | ||
| 151 | + and row.get("target_id") == target_id | ||
| 152 | + and isinstance(row.get("status"), str) | ||
| 153 | + and row["status"] in _STATUS_LABELS | ||
| 154 | + and (row.get("evidence_sha256", _MISSING) is None or isinstance(row.get("evidence_sha256"), str)) | ||
| 155 | + and isinstance(row.get("criteria_sha256"), str) | ||
| 156 | + and isinstance(row.get("summary"), str) | ||
| 157 | + and isinstance(row.get("verdict"), str) | ||
| 158 | + and type(row.get("updated_at")) in (int, float) | ||
| 159 | + } | ||
| 160 | + | ||
| 161 | + def get_reusable_pass( | ||
| 162 | + self, step_id: str, target_id: str, evidence_sha256: str | None, criteria_sha256: str, | ||
| 163 | + ) -> dict | None: | ||
| 164 | + if evidence_sha256 is None: | ||
| 165 | + return None | ||
| 166 | + row = self.load_step_rows(step_id).get(target_id) | ||
| 167 | + if ( | ||
| 168 | + row is not None | ||
| 169 | + and row["status"] == "PASS" | ||
| 170 | + and row["evidence_sha256"] == evidence_sha256 | ||
| 171 | + and row["criteria_sha256"] == criteria_sha256 | ||
| 172 | + ): | ||
| 173 | + return row | ||
| 174 | + return None | ||
| 175 | + | ||
| 176 | + def upsert(self, step_id: str, row: dict) -> None: | ||
| 177 | + with _LEDGER_LOCK: | ||
| 178 | + data = self._load() | ||
| 179 | + rows = data.get(step_id) | ||
| 180 | + if not isinstance(rows, dict): | ||
| 181 | + rows = data[step_id] = {} | ||
| 182 | + rows[row["target_id"]] = row | ||
| 183 | + | ||
| 184 | + self._path.parent.mkdir(parents=True, exist_ok=True) | ||
| 185 | + tmp_path = None | ||
| 186 | + try: | ||
| 187 | + with NamedTemporaryFile( | ||
| 188 | + mode="w", encoding="utf-8", dir=self._path.parent, | ||
| 189 | + prefix=f".{self._path.name}.", suffix=".tmp", delete=False, | ||
| 190 | + ) as temp: | ||
| 191 | + tmp_path = Path(temp.name) | ||
| 192 | + json.dump(data, temp, ensure_ascii=False, indent=2) | ||
| 193 | + os.replace(tmp_path, self._path) | ||
| 194 | + finally: | ||
| 195 | + if tmp_path is not None: | ||
| 196 | + tmp_path.unlink(missing_ok=True) | ||
| 197 | + | ||
| 198 | + def delete(self) -> None: | ||
| 199 | + with _LEDGER_LOCK: | ||
| 200 | + self._path.unlink(missing_ok=True) | ||
| 201 | + | ||
| 202 | + | ||
| 203 | +def summarize_verdict(verdict: str, limit: int = 150) -> str: | ||
| 204 | + line = next((text.strip() for text in verdict.splitlines() if text.strip()), "验收未返回结论") | ||
| 205 | + return line if len(line) <= limit else line[:limit] + "…" | ||
| 206 | + | ||
| 207 | + | ||
| 208 | +def format_verify_report(rows: list[dict[str, Any]]) -> str: | ||
| 209 | + if not rows: | ||
| 210 | + return "没有声明或找到可验收的目标,无法判断是否通过。" | ||
| 211 | + | ||
| 212 | + counts = {status: 0 for status in _STATUS_LABELS} | ||
| 213 | + for row in rows: | ||
| 214 | + counts[row["status"]] += 1 | ||
| 215 | + reused = sum(bool(row.get("reused")) for row in rows) | ||
| 216 | + lines = [ | ||
| 217 | + f"共 {len(rows)} 项验收,通过 {counts['PASS']} 项,未通过 {counts['FAIL']} 项," | ||
| 218 | + f"证据不足 {counts['INSUFFICIENT_EVIDENCE']} 项,复用 {reused} 项。" | ||
| 219 | + ] | ||
| 220 | + for row in rows: | ||
| 221 | + label = _STATUS_LABELS[row["status"]] | ||
| 222 | + reuse_note = "(复用)" if row.get("reused") else "" | ||
| 223 | + lines.append(f"- {row['target_id']} — {label}{reuse_note}:{row['summary']}") | ||
| 224 | + return "\n".join(lines) | ||
| @@ -0,0 +1,269 @@ | |||
| 1 | +"""用固定输入对比单目标验收和多目标续验。所有工具调用均在本进程模拟。""" | ||
| 2 | + | ||
| 3 | +from __future__ import annotations | ||
| 4 | + | ||
| 5 | +import argparse | ||
| 6 | +import asyncio | ||
| 7 | +import json | ||
| 8 | +import os | ||
| 9 | +import shutil | ||
| 10 | +import subprocess | ||
| 11 | +import sys | ||
| 12 | +from contextlib import contextmanager | ||
| 13 | +from dataclasses import replace | ||
| 14 | +from pathlib import Path | ||
| 15 | +from tempfile import TemporaryDirectory | ||
| 16 | +from types import SimpleNamespace | ||
| 17 | +from unittest.mock import patch | ||
| 18 | + | ||
| 19 | +sys.dont_write_bytecode = True | ||
| 20 | +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) | ||
| 21 | +os.environ.setdefault("ANTHROPIC_AUTH_TOKEN", "offline-test-token") | ||
| 22 | +os.environ.setdefault("ANTHROPIC_BASE_URL", "http://127.0.0.1:1") | ||
| 23 | +os.environ.setdefault("LANGSMITH_TRACING", "false") | ||
| 24 | +os.environ.setdefault("LTS_ENABLED", "false") | ||
| 25 | + | ||
| 26 | +from app.tools.workflow import patterns | ||
| 27 | +from app.tools.workflow.checkpointer import Checkpointer | ||
| 28 | +from app.tools.workflow.executor import WorkflowExecutor | ||
| 29 | +from app.tools.workflow.types import ExecutionContext, StepStatus, StepType, WorkflowPlan, WorkflowStep | ||
| 30 | +from app.tools.workflow.verification_ledger import VerificationLedger, hash_criteria, hash_evidence | ||
| 31 | + | ||
| 32 | +_MULTI_VERIFY = patterns._execute_verify | ||
| 33 | +_TARGET_HEADING = "\n\n## 验收目标\n\n" | ||
| 34 | +_EVIDENCE_HEADING = "\n\n## 待验证的输出\n\n" | ||
| 35 | +_CRASH_EXIT = 23 | ||
| 36 | +_RESTART_ID = "wf-restart" | ||
| 37 | +_RESTART_TARGETS = ("one", "two", "three") | ||
| 38 | + | ||
| 39 | + | ||
| 40 | +def require(condition, message): | ||
| 41 | + if not condition: | ||
| 42 | + raise RuntimeError(message) | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +class OfflineTools: | ||
| 46 | + def __init__(self, outputs, crash=False): | ||
| 47 | + self.outputs = outputs | ||
| 48 | + self.crash = crash | ||
| 49 | + self.producer_calls = [] | ||
| 50 | + self.verifier_calls = [] | ||
| 51 | + | ||
| 52 | + async def produce(self, name, *args, **kwargs): | ||
| 53 | + self.producer_calls.append(name) | ||
| 54 | + value = self.outputs.get(name, f"good: {name}") | ||
| 55 | + if isinstance(value, Exception): | ||
| 56 | + raise value | ||
| 57 | + return value | ||
| 58 | + | ||
| 59 | + async def skill(self, step, ctx, progress_callback=None, step_id=""): | ||
| 60 | + if step.skill_name != "offline-verifier": | ||
| 61 | + return await self.produce(step_id or step.id) | ||
| 62 | + target_block = step.prompt_template.split(_TARGET_HEADING, 1)[1] | ||
| 63 | + target, evidence = target_block.split(_EVIDENCE_HEADING, 1) | ||
| 64 | + self.verifier_calls.append(target) | ||
| 65 | + if self.crash and target == _RESTART_TARGETS[-1]: | ||
| 66 | + require(tuple(self.verifier_calls) == _RESTART_TARGETS, "子进程未按顺序验收三项") | ||
| 67 | + # 模拟进程退出,跳过整波保存和异常清理。 | ||
| 68 | + os._exit(_CRASH_EXIT) | ||
| 69 | + return "实测未达标\nRESULT: FAIL" if evidence.startswith("bad:") else "实测达标\nRESULT: PASS" | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +async def baseline_verify(step, ctx, plan, progress_callback=None): | ||
| 73 | + """基线每个 verify 步骤只验收第一个依赖,返回旧式结果。""" | ||
| 74 | + target_id = step.depends_on[0] if step.depends_on else "" | ||
| 75 | + prompt = f"{ctx.render_prompt(step.prompt_template)}{_TARGET_HEADING}{target_id}{_EVIDENCE_HEADING}{ctx.get(target_id, '')}" | ||
| 76 | + verdict = await patterns._call_skill_or_tool( | ||
| 77 | + replace(step, type=StepType.CLAUDE_SKILL, prompt_template=prompt), | ||
| 78 | + ctx, | ||
| 79 | + progress_callback=progress_callback, | ||
| 80 | + ) | ||
| 81 | + return {"passed": patterns._parse_verify_verdict(verdict), "verdict": verdict, "verified_step": target_id} | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +@contextmanager | ||
| 85 | +def offline_tools(baseline, outputs=None, *, crash=False): | ||
| 86 | + tools = OfflineTools(outputs or {}, crash) | ||
| 87 | + with ( | ||
| 88 | + patch.object(patterns, "_call_llm_tool", tools.produce), | ||
| 89 | + patch.object(patterns, "_call_skill_or_tool", tools.skill), | ||
| 90 | + patch.object(patterns, "_execute_verify", baseline_verify if baseline else _MULTI_VERIFY), | ||
| 91 | + ): | ||
| 92 | + yield tools | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +def producer(step_id, *deps): | ||
| 96 | + return WorkflowStep(step_id, StepType.LLM_TOOL, step_id, skill_name=step_id, depends_on=list(deps), max_retries=0) | ||
| 97 | + | ||
| 98 | + | ||
| 99 | +def verifier(step_id, dependencies): | ||
| 100 | + return WorkflowStep( | ||
| 101 | + step_id, StepType.VERIFY, "交付验收", skill_name="offline-verifier", | ||
| 102 | + prompt_template="验收交付标准。", depends_on=list(dependencies), | ||
| 103 | + ) | ||
| 104 | + | ||
| 105 | + | ||
| 106 | +def plan_with_gate(sources, deps): | ||
| 107 | + return WorkflowPlan(steps=[*sources, verifier("verify", deps), producer("deploy", "verify")]) | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +async def replan_skip(**kwargs): | ||
| 111 | + return WorkflowPlan(steps=[]) | ||
| 112 | + | ||
| 113 | + | ||
| 114 | +def executor(directory): | ||
| 115 | + return WorkflowExecutor( | ||
| 116 | + checkpointer=Checkpointer(directory), planner=SimpleNamespace(replan=replan_skip), experience_enabled=False, | ||
| 117 | + ) | ||
| 118 | + | ||
| 119 | + | ||
| 120 | +async def failure_metrics(directory, baseline): | ||
| 121 | + outputs = {"accuracy": "bad: accuracy", "branches::accuracy": "bad: accuracy"} | ||
| 122 | + branches = WorkflowStep( | ||
| 123 | + "branches", StepType.PARALLEL, "并行检查", parallel_steps=[producer("smoke"), producer("accuracy")], | ||
| 124 | + ) | ||
| 125 | + plans = [ | ||
| 126 | + plan_with_gate([producer("config"), producer("accuracy")], ["config", "accuracy"]), | ||
| 127 | + plan_with_gate([producer("config"), producer("accuracy")], ["accuracy", "config"]), | ||
| 128 | + plan_with_gate([producer("config"), branches], ["config", "branches"]), | ||
| 129 | + ] | ||
| 130 | + leaked = 0 | ||
| 131 | + for plan in plans: | ||
| 132 | + with offline_tools(baseline, outputs) as tools: | ||
| 133 | + await executor(directory).execute(plan) | ||
| 134 | + leaked += tools.producer_calls.count("deploy") | ||
| 135 | + | ||
| 136 | + # 两种模式都能看到首项失败,用这个场景比较失败报告。 | ||
| 137 | + saved, ctx = await Checkpointer(directory).load(plans[1].workflow_id) | ||
| 138 | + verify = saved.get_step("verify") | ||
| 139 | + require(verify.status == StepStatus.FAILED, "首项失败场景应拦截交付") | ||
| 140 | + report = ctx.get("verify") or {} | ||
| 141 | + rows = report.get("target_reports", []) | ||
| 142 | + retained = ( | ||
| 143 | + report == verify.result | ||
| 144 | + and [row["status"] for row in rows] == ["FAIL", "PASS"] | ||
| 145 | + and all(row["evidence_sha256"] and row["criteria_sha256"] and row["verdict"] for row in rows) | ||
| 146 | + ) | ||
| 147 | + return leaked, int(retained) | ||
| 148 | + | ||
| 149 | + | ||
| 150 | +async def crash_worker(directory, baseline): | ||
| 151 | + sources = [producer(target) for target in _RESTART_TARGETS] | ||
| 152 | + gates = ( | ||
| 153 | + [verifier(f"verify_{target}", [target]) for target in _RESTART_TARGETS] | ||
| 154 | + if baseline else [verifier("verify", _RESTART_TARGETS)] | ||
| 155 | + ) | ||
| 156 | + plan = WorkflowPlan( | ||
| 157 | + workflow_id=_RESTART_ID, max_concurrency=1, | ||
| 158 | + steps=[*sources, *gates, producer("deploy", *(step.id for step in gates))], | ||
| 159 | + ) | ||
| 160 | + with offline_tools(baseline, crash=True): | ||
| 161 | + await executor(directory).execute(plan) | ||
| 162 | + raise RuntimeError("子进程未触发中断") | ||
| 163 | + | ||
| 164 | + | ||
| 165 | +async def restart_metrics(directory, baseline): | ||
| 166 | + resume_dir = directory / "resume" | ||
| 167 | + resume_dir.mkdir() | ||
| 168 | + env = {**os.environ, "PYTHONIOENCODING": "utf-8"} | ||
| 169 | + child = subprocess.run( | ||
| 170 | + [sys.executable, str(Path(__file__).resolve()), "--crash", str(resume_dir), "baseline" if baseline else "multi"], | ||
| 171 | + capture_output=True, encoding="utf-8", env=env, timeout=45, | ||
| 172 | + ) | ||
| 173 | + require(child.returncode == _CRASH_EXIT, f"子进程未按预期中断:{child.stderr}") | ||
| 174 | + saved, _ = await Checkpointer(resume_dir).load(_RESTART_ID) | ||
| 175 | + require(all(step.status == StepStatus.PENDING for step in saved.steps if step.type == StepType.VERIFY), | ||
| 176 | + "验收期间整波检查点发生变化") | ||
| 177 | + rows = VerificationLedger(resume_dir, _RESTART_ID).load_step_rows("verify") | ||
| 178 | + require(list(rows) == ([] if baseline else list(_RESTART_TARGETS[:2])), "中断时逐项记录不完整") | ||
| 179 | + require(all(row["status"] == "PASS" for row in rows.values()), "已完成验收应为通过") | ||
| 180 | + | ||
| 181 | + altered_dir = directory / "altered" | ||
| 182 | + shutil.copytree(resume_dir, altered_dir) | ||
| 183 | + with offline_tools(baseline) as tools: | ||
| 184 | + ctx = await executor(resume_dir).resume(_RESTART_ID) | ||
| 185 | + expected_calls = list(_RESTART_TARGETS if baseline else _RESTART_TARGETS[-1:]) | ||
| 186 | + require(ctx is not None and tools.producer_calls == ["deploy"], "恢复时重跑了上游或未执行交付") | ||
| 187 | + require(tools.verifier_calls == expected_calls, "恢复时验收调用与预期不符") | ||
| 188 | + if not baseline: | ||
| 189 | + require(ctx.get("verify")["reused_targets"] == list(_RESTART_TARGETS[:2]), "未复用已通过的两项") | ||
| 190 | + | ||
| 191 | + altered_cp = Checkpointer(altered_dir) | ||
| 192 | + altered_plan, altered_ctx = await altered_cp.load(_RESTART_ID) | ||
| 193 | + altered_ctx.set_step_result("one", "bad: changed evidence") | ||
| 194 | + await altered_cp.save(altered_plan, altered_ctx) | ||
| 195 | + with offline_tools(baseline) as altered_tools: | ||
| 196 | + result = await executor(altered_dir).resume(_RESTART_ID) | ||
| 197 | + report = result.get("verify_one" if baseline else "verify") | ||
| 198 | + tamper_blocked = ( | ||
| 199 | + report["passed"] is False and "one" in altered_tools.verifier_calls and "deploy" not in altered_tools.producer_calls | ||
| 200 | + ) | ||
| 201 | + return len(_RESTART_TARGETS) - len(tools.verifier_calls), int(tamper_blocked) | ||
| 202 | + | ||
| 203 | + | ||
| 204 | +async def skip_metric(directory, baseline): | ||
| 205 | + plan = plan_with_gate([producer("setup"), producer("checks", "setup")], ["checks"]) | ||
| 206 | + ctx = ExecutionContext(plan.workflow_id) | ||
| 207 | + old_evidence = "good: old checks" | ||
| 208 | + ctx.set_step_result("checks", old_evidence) | ||
| 209 | + if not baseline: | ||
| 210 | + verify = plan.get_step("verify") | ||
| 211 | + VerificationLedger(directory, plan.workflow_id).upsert(verify.id, { | ||
| 212 | + "target_id": "checks", "status": "PASS", "evidence_sha256": hash_evidence(old_evidence), | ||
| 213 | + "criteria_sha256": hash_criteria(verify.prompt_template, skill_name=verify.skill_name), | ||
| 214 | + "summary": "通过", "verdict": "RESULT: PASS", "updated_at": 1.0, | ||
| 215 | + }) | ||
| 216 | + with offline_tools(baseline, {"checks": RuntimeError("模拟上游失败")}) as tools: | ||
| 217 | + ctx = await executor(directory).execute(plan, ctx=ctx) | ||
| 218 | + require(plan.get_step("checks").status == StepStatus.SKIPPED, "恢复计划未跳过故障步骤") | ||
| 219 | + report = ctx.get("verify") | ||
| 220 | + return int( | ||
| 221 | + report.get("status") == "INSUFFICIENT_EVIDENCE" and report["failed_targets"] == ["checks"] | ||
| 222 | + and tools.verifier_calls == [] and "deploy" not in tools.producer_calls | ||
| 223 | + ) | ||
| 224 | + | ||
| 225 | + | ||
| 226 | +async def measure(directory, baseline): | ||
| 227 | + directory.mkdir() | ||
| 228 | + leaked, retained = await failure_metrics(directory, baseline) | ||
| 229 | + saved, blocked_tamper = await restart_metrics(directory, baseline) | ||
| 230 | + blocked_skip = await skip_metric(directory, baseline) | ||
| 231 | + return leaked, retained, saved, blocked_tamper + blocked_skip | ||
| 232 | + | ||
| 233 | + | ||
| 234 | +def main(): | ||
| 235 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 236 | + parser.add_argument("--json", action="store_true", help="以 JSON 输出统计结果") | ||
| 237 | + parser.add_argument("--crash", nargs=2, help=argparse.SUPPRESS) | ||
| 238 | + args = parser.parse_args() | ||
| 239 | + if args.crash: | ||
| 240 | + directory, mode = args.crash | ||
| 241 | + asyncio.run(crash_worker(Path(directory), mode == "baseline")) | ||
| 242 | + | ||
| 243 | + with TemporaryDirectory(prefix="workflow-verify-") as temp: | ||
| 244 | + baseline = asyncio.run(measure(Path(temp) / "baseline", baseline=True)) | ||
| 245 | + multi = asyncio.run(measure(Path(temp) / "multi", baseline=False)) | ||
| 246 | + | ||
| 247 | + metrics = ( | ||
| 248 | + ("missed_failures", "多分支隐藏失败漏检放行率", 3), | ||
| 249 | + ("retained_evidence", "验收失败结构化证据保留率", 1), | ||
| 250 | + ("saved_verifier_calls", "中断重启续验可省验收调用比例", 3), | ||
| 251 | + ("blocked_stale_passes", "证据篡改 / 跳过步骤防旧判冒用拦截率", 2), | ||
| 252 | + ) | ||
| 253 | + if args.json: | ||
| 254 | + print(json.dumps({ | ||
| 255 | + key: {mode: {"count": count, "total": total, "rate": count / total} | ||
| 256 | + for mode, count in zip(("baseline", "multi_target"), (before, after))} | ||
| 257 | + for (key, _, total), before, after in zip(metrics, baseline, multi) | ||
| 258 | + }, ensure_ascii=False, indent=2)) | ||
| 259 | + else: | ||
| 260 | + print("| 指标 | 基线(仅验首个依赖) | 多目标验收与续验 |") | ||
| 261 | + print("| --- | ---: | ---: |") | ||
| 262 | + for (_, label, total), before, after in zip(metrics, baseline, multi): | ||
| 263 | + print(f"| {label} | {before}/{total}({before / total:.1%}) | {after}/{total}({after / total:.1%}) |") | ||
| 264 | + require(baseline == (2, 0, 0, 1) and multi == (0, 1, 2, 2), "基准结果与预期不符") | ||
| 265 | + return 0 | ||
| 266 | + | ||
| 267 | + | ||
| 268 | +if __name__ == "__main__": | ||
| 269 | + raise SystemExit(main()) | ||
| @@ -0,0 +1,425 @@ | |||
| 1 | +"""Offline acceptance tests for verification gates and their checkpoints.""" | ||
| 2 | + | ||
| 3 | +from __future__ import annotations | ||
| 4 | + | ||
| 5 | +import asyncio | ||
| 6 | +import json | ||
| 7 | +from types import SimpleNamespace | ||
| 8 | +from unittest.mock import AsyncMock | ||
| 9 | + | ||
| 10 | +import pytest | ||
| 11 | + | ||
| 12 | +from app.tools.workflow import patterns | ||
| 13 | +from app.tools.workflow.checkpointer import Checkpointer | ||
| 14 | +from app.tools.workflow.executor import WorkflowExecutor | ||
| 15 | +from app.tools.workflow.planner import DynamicPlanner | ||
| 16 | +from app.tools.workflow.types import ExecutionContext, StepStatus, StepType, WorkflowPlan, WorkflowStep | ||
| 17 | +from app.tools.workflow.verification_ledger import ( | ||
| 18 | + VerificationLedger, | ||
| 19 | + extract_target_evidence, | ||
| 20 | + hash_criteria, | ||
| 21 | + hash_evidence, | ||
| 22 | +) | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def producer(step_id, *deps): | ||
| 26 | + return WorkflowStep(step_id, StepType.LLM_TOOL, step_id, skill_name=step_id, depends_on=list(deps), max_retries=0) | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +def parallel(step_id, *children): | ||
| 30 | + return WorkflowStep(step_id, StepType.PARALLEL, step_id, parallel_steps=[producer(child) for child in children]) | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +def gated_plan(sources, dependencies, targets=()): | ||
| 34 | + verify = WorkflowStep( | ||
| 35 | + "verify", StepType.VERIFY, "交付验收", skill_name="fake-verifier", | ||
| 36 | + prompt_template="检查目标是否满足交付标准。", depends_on=list(dependencies), verify_targets=list(targets), | ||
| 37 | + ) | ||
| 38 | + return WorkflowPlan(steps=[*sources, verify, producer("deploy", verify.id)]) | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def new_executor(path, planner=None): | ||
| 42 | + return WorkflowExecutor(checkpointer=Checkpointer(path), planner=planner, experience_enabled=False) | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +class OfflineTools: | ||
| 46 | + def __init__(self, monkeypatch, outputs=None, before_verify=None): | ||
| 47 | + self.outputs = outputs or {} | ||
| 48 | + self.before_verify = before_verify | ||
| 49 | + self.producer_calls = [] | ||
| 50 | + self.verifier_calls = [] | ||
| 51 | + monkeypatch.setattr(patterns, "_call_llm_tool", self.produce) | ||
| 52 | + monkeypatch.setattr(patterns, "_call_skill_or_tool", self.call) | ||
| 53 | + | ||
| 54 | + async def produce(self, name, *args, **kwargs): | ||
| 55 | + self.producer_calls.append(name) | ||
| 56 | + output = self.outputs.get(name, f"good: {name}") | ||
| 57 | + if isinstance(output, Exception): | ||
| 58 | + raise output | ||
| 59 | + return output | ||
| 60 | + | ||
| 61 | + async def call(self, step, ctx, progress_callback=None, step_id=""): | ||
| 62 | + if step.skill_name != "fake-verifier": | ||
| 63 | + return await self.produce(step_id or step.skill_name) | ||
| 64 | + target, evidence_block = step.prompt_template.split("\n\n## 验收目标\n\n", 1)[1].split( | ||
| 65 | + "\n\n## 待验证的输出\n\n", 1, | ||
| 66 | + ) | ||
| 67 | + evidence, instructions = evidence_block.split("\n\n## 结论输出要求", 1) | ||
| 68 | + for status in ("PASS", "FAIL", "INSUFFICIENT_EVIDENCE"): | ||
| 69 | + assert f"RESULT: {status}" in instructions | ||
| 70 | + self.verifier_calls.append(target) | ||
| 71 | + if self.before_verify: | ||
| 72 | + self.before_verify(target) | ||
| 73 | + if evidence.startswith("bad:"): | ||
| 74 | + return "实测结果未达到标准\nRESULT: FAIL" | ||
| 75 | + return "error: 0\n未通过: 0\nRESULT: PASS" | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +@pytest.mark.parametrize("order", [("config_ok", "accuracy_fail"), ("accuracy_fail", "config_ok")]) | ||
| 79 | +async def test_order_invariance_and_structured_failure(tmp_path, monkeypatch, order): | ||
| 80 | + tools = OfflineTools(monkeypatch, {"accuracy_fail": "bad: accuracy 0.45"}) | ||
| 81 | + plan = gated_plan([producer("config_ok"), producer("accuracy_fail")], order) | ||
| 82 | + ctx = await new_executor(tmp_path).execute(plan) | ||
| 83 | + | ||
| 84 | + verify = plan.get_step("verify") | ||
| 85 | + report = verify.result | ||
| 86 | + assert verify.status == StepStatus.FAILED | ||
| 87 | + assert report == ctx.step_results["verify"] == ctx.get("verify.output") | ||
| 88 | + assert report["passed"] is False and report["status"] == "FAIL" | ||
| 89 | + assert report["verified_steps"] == tools.verifier_calls == list(order) | ||
| 90 | + assert report["failed_targets"] == ["accuracy_fail"] | ||
| 91 | + assert "accuracy_fail" in verify.error and "未通过 1 项" in verify.error | ||
| 92 | + assert tools.producer_calls.count("deploy") == 0 | ||
| 93 | + | ||
| 94 | + responses = {row["target_id"]: row for row in report["target_reports"]} | ||
| 95 | + assert responses["config_ok"]["verdict"].endswith("RESULT: PASS") | ||
| 96 | + assert responses["accuracy_fail"]["verdict"].endswith("RESULT: FAIL") | ||
| 97 | + for target in order: | ||
| 98 | + row = responses[target] | ||
| 99 | + assert row["evidence_sha256"] == hash_evidence(ctx.get(target)) | ||
| 100 | + assert row["criteria_sha256"] == hash_criteria(verify.prompt_template, skill_name=verify.skill_name) | ||
| 101 | + assert row["reused"] is False | ||
| 102 | + cp = Checkpointer(tmp_path) | ||
| 103 | + saved_plan, saved_ctx = await cp.load(plan.workflow_id) | ||
| 104 | + assert saved_plan.get_step("verify").result == saved_ctx.step_results["verify"] == report | ||
| 105 | + rows = VerificationLedger(tmp_path, plan.workflow_id).load_step_rows("verify") | ||
| 106 | + assert {key: row["status"] for key, row in rows.items()} == {"config_ok": "PASS", "accuracy_fail": "FAIL"} | ||
| 107 | + assert [item["workflow_id"] for item in await cp.list_checkpoints()] == [plan.workflow_id] | ||
| 108 | + assert await cp.delete(plan.workflow_id) | ||
| 109 | + assert list(tmp_path.iterdir()) == [] | ||
| 110 | + | ||
| 111 | + | ||
| 112 | +async def test_explicit_targets_ignore_order_only_dependency(tmp_path, monkeypatch): | ||
| 113 | + tools = OfflineTools(monkeypatch, {"prep_order": "bad: setup is not acceptance evidence"}) | ||
| 114 | + sources = [producer(name) for name in ("prep_order", "check_a", "check_b")] | ||
| 115 | + plan = gated_plan(sources, [source.id for source in sources], ["check_a", "check_b", "check_a"]) | ||
| 116 | + ctx = await new_executor(tmp_path).execute(plan) | ||
| 117 | + | ||
| 118 | + report = ctx.get("verify") | ||
| 119 | + assert report["passed"] is True and report["status"] == "PASS" | ||
| 120 | + assert tools.verifier_calls == report["evaluated_targets"] == ["check_a", "check_b"] | ||
| 121 | + assert report["target_reports"][0]["verdict"].startswith("error: 0") | ||
| 122 | + assert tools.producer_calls.count("deploy") == 1 | ||
| 123 | + saved, _ = await Checkpointer(tmp_path).load(plan.workflow_id) | ||
| 124 | + assert saved.get_step("verify").verify_targets == ["check_a", "check_b", "check_a"] | ||
| 125 | + | ||
| 126 | + | ||
| 127 | +@pytest.mark.parametrize("targets,expected", [ | ||
| 128 | + ([], ["checks::config", "checks::smoke", "checks::accuracy"]), | ||
| 129 | + (["checks", "checks::config"], ["checks::config", "checks::smoke", "checks::accuracy"]), | ||
| 130 | + (["checks::config", "checks::accuracy"], ["checks::config", "checks::accuracy"]), | ||
| 131 | +]) | ||
| 132 | +async def test_parallel_children_are_verified_individually(tmp_path, monkeypatch, targets, expected): | ||
| 133 | + tools = OfflineTools(monkeypatch, {"checks::accuracy": "bad: accuracy 0.45"}) | ||
| 134 | + plan = gated_plan([parallel("checks", "config", "smoke", "accuracy")], ["checks"], targets) | ||
| 135 | + ctx = await new_executor(tmp_path).execute(plan) | ||
| 136 | + | ||
| 137 | + report = ctx.get("verify") | ||
| 138 | + assert report["status"] == "FAIL" | ||
| 139 | + assert report["verified_steps"] == tools.verifier_calls == expected | ||
| 140 | + assert report["failed_targets"] == ["checks::accuracy"] | ||
| 141 | + assert tools.producer_calls.count("deploy") == 0 | ||
| 142 | + | ||
| 143 | + | ||
| 144 | +async def interrupt_after_two_targets(tmp_path, monkeypatch): | ||
| 145 | + targets = ["one", "two", "three"] | ||
| 146 | + plan = gated_plan([producer(target) for target in targets], targets) | ||
| 147 | + checkpoint = tmp_path / f"{plan.workflow_id}.json" | ||
| 148 | + snapshot = None | ||
| 149 | + | ||
| 150 | + def stop(target): | ||
| 151 | + nonlocal snapshot | ||
| 152 | + if target == "one": | ||
| 153 | + snapshot = checkpoint.read_bytes() | ||
| 154 | + if target == "three": | ||
| 155 | + rows = VerificationLedger(tmp_path, plan.workflow_id).load_step_rows("verify") | ||
| 156 | + assert [row["status"] for row in rows.values()] == ["PASS", "PASS"] | ||
| 157 | + assert list(rows) == targets[:2] | ||
| 158 | + assert checkpoint.read_bytes() == snapshot | ||
| 159 | + raise asyncio.CancelledError | ||
| 160 | + | ||
| 161 | + tools = OfflineTools(monkeypatch, before_verify=stop) | ||
| 162 | + with pytest.raises(asyncio.CancelledError): | ||
| 163 | + await new_executor(tmp_path).execute(plan) | ||
| 164 | + assert tools.verifier_calls == targets | ||
| 165 | + assert tools.producer_calls == targets | ||
| 166 | + saved, _ = await Checkpointer(tmp_path).load(plan.workflow_id) | ||
| 167 | + assert saved.get_step("verify").status == StepStatus.RUNNING | ||
| 168 | + return plan.workflow_id, checkpoint | ||
| 169 | + | ||
| 170 | + | ||
| 171 | +async def test_fresh_executor_resumes_only_unfinished_target(tmp_path, monkeypatch): | ||
| 172 | + workflow_id, _ = await interrupt_after_two_targets(tmp_path, monkeypatch) | ||
| 173 | + tools = OfflineTools(monkeypatch) | ||
| 174 | + ctx = await new_executor(tmp_path).resume(workflow_id) | ||
| 175 | + | ||
| 176 | + report = ctx.get("verify") | ||
| 177 | + assert report["passed"] is True | ||
| 178 | + assert report["reused_targets"] == ["one", "two"] | ||
| 179 | + assert report["evaluated_targets"] == tools.verifier_calls == ["three"] | ||
| 180 | + assert tools.producer_calls == ["deploy"] | ||
| 181 | + assert "复用 2 项" in report["verdict"] | ||
| 182 | + | ||
| 183 | + | ||
| 184 | +@pytest.mark.parametrize("change,expected_calls,reused,expected_status", [ | ||
| 185 | + ("evidence", ["one", "three"], ["two"], "FAIL"), | ||
| 186 | + ("criteria", ["one", "two", "three"], [], "PASS"), | ||
| 187 | + ("missing", ["three"], ["two"], "INSUFFICIENT_EVIDENCE"), | ||
| 188 | + ("blank", ["three"], ["two"], "INSUFFICIENT_EVIDENCE"), | ||
| 189 | +]) | ||
| 190 | +async def test_resume_checks_current_evidence_and_criteria( | ||
| 191 | + tmp_path, monkeypatch, change, expected_calls, reused, expected_status, | ||
| 192 | +): | ||
| 193 | + workflow_id, checkpoint = await interrupt_after_two_targets(tmp_path, monkeypatch) | ||
| 194 | + saved = json.loads(checkpoint.read_text(encoding="utf-8")) | ||
| 195 | + if change == "criteria": | ||
| 196 | + verify = next(step for step in saved["plan"]["steps"] if step["id"] == "verify") | ||
| 197 | + verify["prompt_template"] = "验收采用更新后的标准。" | ||
| 198 | + else: | ||
| 199 | + evidence = {"evidence": "bad: changed accuracy", "missing": None, "blank": " \t\n "}[change] | ||
| 200 | + saved["context"]["variables"]["one"] = evidence | ||
| 201 | + saved["context"]["variables"]["one.output"] = evidence | ||
| 202 | + saved["context"]["step_results"]["one"] = evidence | ||
| 203 | + checkpoint.write_text(json.dumps(saved, ensure_ascii=False), encoding="utf-8") | ||
| 204 | + | ||
| 205 | + old_row = VerificationLedger(tmp_path, workflow_id).load_step_rows("verify")["one"] | ||
| 206 | + tools = OfflineTools(monkeypatch) | ||
| 207 | + ctx = await new_executor(tmp_path).resume(workflow_id) | ||
| 208 | + report = ctx.get("verify") | ||
| 209 | + | ||
| 210 | + assert report["status"] == expected_status | ||
| 211 | + assert tools.verifier_calls == expected_calls and report["reused_targets"] == reused | ||
| 212 | + assert tools.producer_calls == (["deploy"] if expected_status == "PASS" else []) | ||
| 213 | + current_row = report["target_reports"][0] | ||
| 214 | + assert current_row["reused"] is False | ||
| 215 | + if change == "criteria": | ||
| 216 | + assert current_row["criteria_sha256"] != old_row["criteria_sha256"] | ||
| 217 | + else: | ||
| 218 | + assert report["failed_targets"] == ["one"] | ||
| 219 | + assert current_row["evidence_sha256"] == hash_evidence(evidence) | ||
| 220 | + assert current_row["evidence_sha256"] != old_row["evidence_sha256"] | ||
| 221 | + | ||
| 222 | + | ||
| 223 | +async def test_replan_split_verifies_both_replacement_terminals(tmp_path, monkeypatch): | ||
| 224 | + tools = OfflineTools(monkeypatch, {"failed": RuntimeError("producer stopped"), "accuracy": "bad: precision"}) | ||
| 225 | + plan = gated_plan([producer("setup"), producer("failed", "setup")], ["failed"]) | ||
| 226 | + planner = SimpleNamespace(replan=AsyncMock(return_value=WorkflowPlan(steps=[producer("smoke"), producer("accuracy")]))) | ||
| 227 | + ctx = await new_executor(tmp_path, planner).execute(plan) | ||
| 228 | + | ||
| 229 | + planner.replan.assert_awaited_once() | ||
| 230 | + assert plan.get_step("failed").status == StepStatus.SKIPPED | ||
| 231 | + assert plan.get_step("verify").verify_targets == ["smoke", "accuracy"] | ||
| 232 | + assert tools.verifier_calls == ["smoke", "accuracy"] | ||
| 233 | + assert ctx.get("verify")["failed_targets"] == ["accuracy"] | ||
| 234 | + assert tools.producer_calls.count("deploy") == 0 | ||
| 235 | + | ||
| 236 | + | ||
| 237 | +async def test_replan_skip_keeps_obligation_even_with_old_pass(tmp_path, monkeypatch): | ||
| 238 | + tools = OfflineTools(monkeypatch, {"failed": RuntimeError("producer stopped")}) | ||
| 239 | + plan = gated_plan([producer("setup"), producer("failed", "setup")], ["failed"]) | ||
| 240 | + verify = plan.get_step("verify") | ||
| 241 | + ctx = ExecutionContext(plan.workflow_id) | ||
| 242 | + ctx.set_step_result("failed", "old evidence") | ||
| 243 | + ledger = VerificationLedger(tmp_path, plan.workflow_id) | ||
| 244 | + ledger.upsert(verify.id, { | ||
| 245 | + "target_id": "failed", "status": "PASS", "evidence_sha256": hash_evidence("old evidence"), | ||
| 246 | + "criteria_sha256": hash_criteria(verify.prompt_template, skill_name=verify.skill_name), | ||
| 247 | + "summary": "通过", "verdict": "RESULT: PASS", "updated_at": 1.0, | ||
| 248 | + }) | ||
| 249 | + planner = SimpleNamespace(replan=AsyncMock(return_value=WorkflowPlan(steps=[]))) | ||
| 250 | + ctx = await new_executor(tmp_path, planner).execute(plan, ctx=ctx) | ||
| 251 | + | ||
| 252 | + assert plan.get_step("failed").status == StepStatus.SKIPPED | ||
| 253 | + assert verify.depends_on == ["setup"] and verify.verify_targets == ["failed"] | ||
| 254 | + assert tools.verifier_calls == [] and tools.producer_calls.count("deploy") == 0 | ||
| 255 | + report = ctx.get("verify") | ||
| 256 | + assert report["status"] == "INSUFFICIENT_EVIDENCE" and report["failed_targets"] == ["failed"] | ||
| 257 | + assert "已跳过" in report["verdict"] | ||
| 258 | + assert ledger.load_step_rows(verify.id)["failed"]["evidence_sha256"] is None | ||
| 259 | + | ||
| 260 | + | ||
| 261 | +@pytest.mark.parametrize("replacement_children,extra_terminal,expected", [ | ||
| 262 | + (["config"], False, "replacement::config"), | ||
| 263 | + (["smoke"], False, "checks::config"), | ||
| 264 | + (["config"], True, "checks::config"), | ||
| 265 | +]) | ||
| 266 | +async def test_qualified_target_remap_requires_one_matching_parallel_terminal( | ||
| 267 | + tmp_path, monkeypatch, replacement_children, extra_terminal, expected, | ||
| 268 | +): | ||
| 269 | + tools = OfflineTools(monkeypatch) | ||
| 270 | + failed = parallel("checks", "config") | ||
| 271 | + failed.status = StepStatus.FAILED | ||
| 272 | + plan = gated_plan([failed], ["checks"]) | ||
| 273 | + replacements = [parallel("replacement", *replacement_children)] | ||
| 274 | + if extra_terminal: | ||
| 275 | + replacements.append(producer("other")) | ||
| 276 | + WorkflowExecutor._merge_replanned_steps(plan, failed, replacements) | ||
| 277 | + | ||
| 278 | + ctx = await new_executor(tmp_path).execute(plan) | ||
| 279 | + assert plan.get_step("verify").verify_targets == [expected] | ||
| 280 | + assert ctx.get("verify")["verified_step"] == expected | ||
| 281 | + if expected == "replacement::config": | ||
| 282 | + assert tools.verifier_calls == [expected] and tools.producer_calls.count("deploy") == 1 | ||
| 283 | + else: | ||
| 284 | + assert tools.verifier_calls == [] and tools.producer_calls.count("deploy") == 0 | ||
| 285 | + assert ctx.get("verify")["status"] == "INSUFFICIENT_EVIDENCE" | ||
| 286 | + | ||
| 287 | + | ||
| 288 | +@pytest.mark.parametrize("from_legacy_checkpoint", [False, True]) | ||
| 289 | +async def test_single_target_backward_compatibility(tmp_path, monkeypatch, from_legacy_checkpoint): | ||
| 290 | + tools = OfflineTools(monkeypatch) | ||
| 291 | + plan = gated_plan([producer("only")], ["only"]) | ||
| 292 | + executor = new_executor(tmp_path) | ||
| 293 | + if from_legacy_checkpoint: | ||
| 294 | + source = plan.get_step("only") | ||
| 295 | + source.status = StepStatus.COMPLETED | ||
| 296 | + source.result = "good: cached producer output" | ||
| 297 | + ctx = ExecutionContext(plan.workflow_id) | ||
| 298 | + ctx.set_step_result(source.id, source.result) | ||
| 299 | + await Checkpointer(tmp_path).save(plan, ctx) | ||
| 300 | + checkpoint = tmp_path / f"{plan.workflow_id}.json" | ||
| 301 | + raw = json.loads(checkpoint.read_text(encoding="utf-8")) | ||
| 302 | + for step in raw["plan"]["steps"]: | ||
| 303 | + step.pop("verify_targets") | ||
| 304 | + checkpoint.write_text(json.dumps(raw), encoding="utf-8") | ||
| 305 | + assert not (tmp_path / f"{plan.workflow_id}.verify.json").exists() | ||
| 306 | + ctx = await executor.resume(plan.workflow_id) | ||
| 307 | + else: | ||
| 308 | + ctx = await executor.execute(plan) | ||
| 309 | + | ||
| 310 | + report = ctx.get("verify") | ||
| 311 | + assert report["passed"] is True and report["verified_step"] == "only" | ||
| 312 | + assert "error: 0\n未通过: 0\nRESULT: PASS" in report["verdict"] | ||
| 313 | + assert tools.verifier_calls == ["only"] | ||
| 314 | + assert tools.producer_calls == (["deploy"] if from_legacy_checkpoint else ["only", "deploy"]) | ||
| 315 | + | ||
| 316 | + | ||
| 317 | +async def test_no_targets_blocks_without_verifier_call(tmp_path, monkeypatch): | ||
| 318 | + tools = OfflineTools(monkeypatch) | ||
| 319 | + plan = gated_plan([], []) | ||
| 320 | + ctx = await new_executor(tmp_path).execute(plan) | ||
| 321 | + | ||
| 322 | + report = ctx.get("verify") | ||
| 323 | + assert report["status"] == "INSUFFICIENT_EVIDENCE" and report["target_reports"] == [] | ||
| 324 | + assert "没有声明或找到可验收的目标" in report["verdict"] | ||
| 325 | + assert tools.verifier_calls == tools.producer_calls == [] | ||
| 326 | + | ||
| 327 | + | ||
| 328 | +def test_planner_validates_explicit_targets_and_preserves_parallel_aliases(): | ||
| 329 | + planner = DynamicPlanner(llm=object(), experience_enabled=False) | ||
| 330 | + plan = planner._build_plan({"steps": [ | ||
| 331 | + {"id": "setup", "name": "设置"}, | ||
| 332 | + {"id": "checks", "type": "parallel", "parallel_steps": [{"id": "config", "name": "查配置"}]}, | ||
| 333 | + {"id": "alias", "type": "parallel", "parallel_steps": [{"id": "cfg", "name": "查配置"}]}, | ||
| 334 | + {"id": "verify", "type": "verify", "depends_on": ["setup", "alias"], | ||
| 335 | + "verify_targets": ["alias::cfg", "checks::config", "unknown", "verify::self", 1, ""]}, | ||
| 336 | + {"id": "legacy", "type": "verify", "depends_on": ["checks"]}, | ||
| 337 | + ]}, "查配置") | ||
| 338 | + planner._validate_plan(plan) | ||
| 339 | + | ||
| 340 | + assert plan.get_step("verify").depends_on == ["setup", "checks"] | ||
| 341 | + assert plan.get_step("verify").verify_targets == ["checks::config"] | ||
| 342 | + assert plan.get_step("legacy").verify_targets == [] | ||
| 343 | + | ||
| 344 | + | ||
| 345 | +def test_evidence_sources_and_canonical_hashes(): | ||
| 346 | + source = producer("one") | ||
| 347 | + source.status = StepStatus.COMPLETED | ||
| 348 | + source.result = 0 | ||
| 349 | + parent = parallel("checks", "config", "accuracy") | ||
| 350 | + parent.parallel_steps[0].status = StepStatus.COMPLETED | ||
| 351 | + parent.parallel_steps[0].result = "child result" | ||
| 352 | + plan = WorkflowPlan(steps=[source, parent]) | ||
| 353 | + ctx = ExecutionContext(plan.workflow_id) | ||
| 354 | + ctx.set_step_result("checks", ["old config", "legacy accuracy"]) | ||
| 355 | + | ||
| 356 | + assert extract_target_evidence("one", ctx, plan) == (True, 0, "") | ||
| 357 | + assert extract_target_evidence("checks::config", ctx, plan) == (True, "child result", "") | ||
| 358 | + assert extract_target_evidence("checks::accuracy", ctx, plan) == (True, "legacy accuracy", "") | ||
| 359 | + ctx.set_step_result("checks::config", "direct") | ||
| 360 | + assert extract_target_evidence("checks::config", ctx, plan) == (True, "direct", "") | ||
| 361 | + parent.status = StepStatus.SKIPPED | ||
| 362 | + assert extract_target_evidence("checks::config", ctx, plan)[0] is False | ||
| 363 | + assert extract_target_evidence("missing::child", ctx, plan)[0] is False | ||
| 364 | + assert hash_evidence({"b": 0, "a": "昇腾"}) == hash_evidence({"a": "昇腾", "b": 0}) | ||
| 365 | + assert hash_evidence(0) != hash_evidence("0") | ||
| 366 | + assert hash_evidence(None) is hash_evidence(" ") is None | ||
| 367 | + assert hash_criteria("规则", params={"b": 2, "a": 1}) == hash_criteria("规则", params={"a": 1, "b": 2}) | ||
| 368 | + assert hash_criteria("规则", skill_name="a") != hash_criteria("规则", skill_name="b") | ||
| 369 | + assert hash_criteria("规则", protocol_version="v1") != hash_criteria("规则", protocol_version="v2") | ||
| 370 | + | ||
| 371 | + | ||
| 372 | +@pytest.mark.parametrize("response,status", [ | ||
| 373 | + ("RESULT: PASS\nresult:insufficient_evidence", "INSUFFICIENT_EVIDENCE"), | ||
| 374 | + ("RESULT: FAIL\nResult:pass", "PASS"), | ||
| 375 | + ("最终RESULT:PASS\n以下是备注", "PASS"), | ||
| 376 | + ("判定未通过", "FAIL"), | ||
| 377 | + ("Not passed", "FAIL"), | ||
| 378 | + ("证据不足,无法验证模型是否正确", "INSUFFICIENT_EVIDENCE"), | ||
| 379 | + ("缺少证据,无法判断是否符合要求", "INSUFFICIENT_EVIDENCE"), | ||
| 380 | + ("cannot verify correctness", "INSUFFICIENT_EVIDENCE"), | ||
| 381 | + ("insufficient evidence", "INSUFFICIENT_EVIDENCE"), | ||
| 382 | + ("结论是通过", "PASS"), | ||
| 383 | + ("文中引用 yes\n需要进一步检查", "INSUFFICIENT_EVIDENCE"), | ||
| 384 | +]) | ||
| 385 | +def test_verify_status_and_legacy_boolean(response, status): | ||
| 386 | + assert patterns._parse_verify_status(response) == status | ||
| 387 | + assert patterns._parse_verify_verdict(response) is (status == "PASS") | ||
| 388 | + | ||
| 389 | + | ||
| 390 | +def test_ledger_rejects_unsafe_ids_and_ignores_corruption(tmp_path): | ||
| 391 | + for workflow_id in ("../escape", "sub/path", "sub\\path", "..", "C:alt", "NUL"): | ||
| 392 | + with pytest.raises(ValueError): | ||
| 393 | + VerificationLedger(tmp_path, workflow_id) | ||
| 394 | + ledger = VerificationLedger(tmp_path, "wf-corrupt") | ||
| 395 | + path = tmp_path / "wf-corrupt.verify.json" | ||
| 396 | + for content in ("{", "[]", '{"verify":{"one":{"target_id":"one","status":"PASS"}}}'): | ||
| 397 | + path.write_text(content, encoding="utf-8") | ||
| 398 | + assert ledger.load_step_rows("verify") == {} | ||
| 399 | + assert ledger.get_reusable_pass("verify", "one", None, "criteria") is None | ||
| 400 | + | ||
| 401 | + | ||
| 402 | +async def test_chat_workflow_blocks_delivery_when_multi_target_verification_fails(tmp_path, monkeypatch): | ||
| 403 | + from app.config import settings | ||
| 404 | + from app.services import chat_service | ||
| 405 | + | ||
| 406 | + tools = OfflineTools(monkeypatch, {"accuracy_fail": "bad: accuracy 0.45"}) | ||
| 407 | + plan = gated_plan([producer("config_ok"), producer("accuracy_fail")], ["config_ok", "accuracy_fail"]) | ||
| 408 | + planner = SimpleNamespace(aplan=AsyncMock(return_value=plan)) | ||
| 409 | + monkeypatch.setattr(chat_service, "DynamicPlanner", lambda: planner) | ||
| 410 | + monkeypatch.setattr(settings, "workflow_checkpoint_dir", str(tmp_path)) | ||
| 411 | + monkeypatch.setattr(settings, "hermes_enabled", False) | ||
| 412 | + | ||
| 413 | + chunks = [chunk async for chunk in chat_service._execute_workflow_with_context( | ||
| 414 | + {"user_input": "交付前验收配置和精度"}, "chunk", "offline", | ||
| 415 | + )] | ||
| 416 | + content = "".join( | ||
| 417 | + json.loads(chunk.removeprefix("data: "))["choices"][0]["delta"].get("content") or "" | ||
| 418 | + for chunk in chunks if chunk.startswith("data: {") | ||
| 419 | + ) | ||
| 420 | + assert "验证未通过" in content and "accuracy_fail" in content | ||
| 421 | + assert tools.verifier_calls == ["config_ok", "accuracy_fail"] | ||
| 422 | + assert tools.producer_calls.count("deploy") == 0 | ||
| 423 | + saved, ctx = await Checkpointer(tmp_path).load(plan.workflow_id) | ||
| 424 | + assert saved.get_step("deploy").status == StepStatus.PENDING | ||
| 425 | + assert ctx.get("verify")["failed_targets"] == ["accuracy_fail"] | ||