regression_freeze.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. """一套命令跑完"冻结点"回归(发版 / 交付 / 改判据之后必跑)。
  2. 为什么要一个总脚本:判据链现在有五层(C++ 契约自检、Python 单测、v1 `edge` 现场回放、
  3. v2 `edge-v2` 现场回放、**数据集安全门禁**),分散在四五个命令里,现场/验收时**很容易漏跑
  4. 一组**,而漏跑的那一组往往正是"刚刚被改动"的那一组。
  5. 用法::
  6. # 全部跑(默认路径就是本仓库的布局)
  7. python scripts/regression_freeze.py
  8. # 数据集门禁要指语料目录(没有现场素材时它会明确 FAIL/SKIP,而不是静默跳过)
  9. python scripts/regression_freeze.py --dataset-dir "D:/语料/dataset_20251120"
  10. # 也可以走环境变量
  11. set PORTCV_DATASET_DIR=D:/语料/dataset_20251120
  12. # 产物不在默认位置 / 只想跑其中几组(调试用;正式验收请跑全量)
  13. python scripts/regression_freeze.py --build-dir build --only ctest,py
  14. 设计原则(与 `replay_check.py` 同一套价值观):
  15. * **不吞失败**:任何一组没跑成(缺目录 / 缺 dump / 退出码非 0)都记 FAIL,退出码 1;
  16. * **已知失败必须写进白名单**:`A_s2` 那 1 条"投票器把 1/2 混了"是**故意保留**的断言
  17. (见 `docs/edge_evidence.md` §7.1 ⑤-2),白名单里写清"允许 1 条且必须匹配该模式",
  18. 多一条、或换了原因,都算 FAIL —— 绝不因为"有一条已知失败"就把整组标记成跳过;
  19. * **缺产物不静默跳过**:直接给出**生成命令**并记 FAIL;只有显式 `--allow-missing`
  20. 才降级为 SKIP(报告里照样逐条列出),用于"没有现场素材的纯算法机";
  21. * **数据集门禁只卡“变差”**:`--baseline-violations` 允许基线里已有的违例存在
  22. (它们已记录在 `docs/evidence/test_2026-11-20/`),**新增一条就 FAIL**;
  23. 修好一条会提示同步基线 —— 既不因为"有 9 条历史违例"就永远红,也不许悄悄变差。
  24. 退出码:``0`` 全绿;``1`` 有 FAIL;``2`` 用法 / 环境问题。
  25. """
  26. from __future__ import annotations
  27. import argparse
  28. import json
  29. import os
  30. import re
  31. import subprocess
  32. import sys
  33. REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  34. # 白名单:JSONL 相对路径 → (允许的 FAIL 条数, 必须匹配的模式)。不在表里 = 不允许任何 FAIL。
  35. KNOWN_FAIL = {
  36. "runs/ab_A_s2.jsonl": (1, "投票器把 1/2 混了"),
  37. }
  38. def _rel(path: str) -> str:
  39. return path.replace(os.sep, "/")
  40. def _use_utf8_stdout() -> None:
  41. """Windows 控制台默认 GBK:子进程输出里的 `≠`/`⇒` 之类字符会让 `print` 抛异常。
  42. 这里统一成 UTF-8 + ``errors="replace"``:宁可控制台显示成问号,也不能因为
  43. "报告打印不出来"而把一次真实的回归结果吞掉。
  44. """
  45. for stream in (sys.stdout, sys.stderr):
  46. try:
  47. stream.reconfigure(encoding="utf-8", errors="replace")
  48. except Exception: # pragma: no cover - 老 Python / 被重定向的流
  49. pass
  50. def run(cmd: list, cwd: str = REPO) -> tuple:
  51. """跑一条命令,返回 ``(returncode, stdout+stderr)``(合并输出,便于定位)。"""
  52. env = dict(os.environ)
  53. env["PYTHONIOENCODING"] = "utf-8" # 子进程(replay_check / unittest)也走 UTF-8
  54. proc = subprocess.run(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env)
  55. return proc.returncode, proc.stdout.decode("utf-8", "replace")
  56. def check_ctest(build_dir: str) -> tuple:
  57. if not os.path.isdir(build_dir):
  58. return False, ("找不到构建目录 %s\n 先生成:cmake -S cpp -B %s -DCMAKE_BUILD_TYPE=Release"
  59. " && cmake --build %s" % (build_dir, build_dir, build_dir))
  60. code, out = run(["ctest", "--test-dir", build_dir, "--output-on-failure"])
  61. # ctest 3.31 起汇总行是 "100% tests passed out of 7"(旧版多一段 ", N tests failed"),
  62. # 两种都认,只要求 100% + 总组数。
  63. pct = re.search(r"(\d+)% tests passed", out)
  64. total = re.search(r"out of (\d+)", out)
  65. if not pct or not total:
  66. return False, "ctest 没有汇总行(rc=%d)\n%s" % (code, out[-2000:])
  67. if code != 0 or pct.group(1) != "100":
  68. return False, "ctest 只有 %s%% 通过(共 %s 组)\n%s" % (pct.group(1), total.group(1),
  69. out[-2000:])
  70. return True, "ctest %s/%s 全绿" % (total.group(1), total.group(1))
  71. def check_python(discover_dir: str) -> tuple:
  72. code, out = run([sys.executable, "-m", "unittest", "discover", "-s", discover_dir, "-t", "."])
  73. m = re.search(r"Ran (\d+) tests", out)
  74. if code != 0 or not re.search(r"(?m)^OK\b", out):
  75. return False, "unittest 未全绿(rc=%d)\n%s" % (code, out[-3000:])
  76. return True, "unittest %s 项 OK" % (m.group(1) if m else "?")
  77. def check_replay(jsonl: str, images: str, allow_missing: bool) -> tuple:
  78. """回放一组;返回 ``(ok, note)``。已知失败按白名单核对**条数与原因**。"""
  79. jpath = os.path.join(REPO, jsonl)
  80. if not os.path.exists(jpath):
  81. return False, "缺导出 %s\n 生成:见 docs/edge_evidence.md §7.1 / §7.2 的采集命令" % jsonl
  82. ipath = os.path.join(REPO, images)
  83. if not os.path.isdir(ipath):
  84. if allow_missing:
  85. return True, "SKIP(--allow-missing):缺图目录 %s" % images
  86. return False, "缺图目录 %s(不带 --allow-missing 时不允许跳过)" % images
  87. code, out = run([sys.executable, os.path.join("scripts", "replay_check.py"),
  88. _rel(jsonl), "--images", _rel(images)])
  89. tail = [ln for ln in out.splitlines() if ln.startswith("结论:")]
  90. if not tail:
  91. return False, "回放没有输出结论行(rc=%d)\n%s" % (code, out[-2000:])
  92. # 条数以汇总行为准(`--limit` 只影响打印多少条明细,不能让"没打印"变成"没失败")
  93. m = re.search(r"FAIL (\d+) / WARN (\d+)", tail[-1])
  94. n_fail = int(m.group(1)) if m else -1
  95. detail = [ln for ln in out.splitlines() if "[FAIL]" in ln]
  96. allowed, pattern = KNOWN_FAIL.get(_rel(jsonl), (0, ""))
  97. if n_fail < 0:
  98. return False, "结论行里没有 FAIL 计数:%s" % tail[-1]
  99. if n_fail > allowed:
  100. extra = [ln for ln in detail if pattern not in ln]
  101. return False, "FAIL %d 条 > 白名单 %d 条:\n%s" % (n_fail, allowed,
  102. "\n".join(extra[:10]) or tail[-1])
  103. if allowed and n_fail != allowed:
  104. return False, ("白名单要求恰好 %d 条已知 FAIL,实际 %d 条"
  105. "(是不是被顺手修好了?请同步白名单)" % (allowed, n_fail))
  106. note = tail[-1].replace("结论: ", "")
  107. if allowed:
  108. note += "(白名单:允许 %d 条已知 FAIL「%s」)" % (allowed, pattern)
  109. return True, note
  110. def check_dataset_gate(dataset_dir: str, repeats: int, allow_missing: bool) -> tuple:
  111. """数据集回归门禁:跑 `dataset_harness.py`,**只卡“新增违例”**(基线见 labels 同目录)。
  112. 为什么放进冻结点回归:2026-11-20 的 9 条危险误判(载车判 3 / 空车判 1、2)原先只写在
  113. 报告里,改判据时没有任何东西会拦住“变差”。这里用 `--baseline-violations` 把“禁止变差”
  114. 变成一条可执行的门禁;域内精度仍要等现场素材(`docs/field_capture_spec.md`)。
  115. """
  116. dpath = dataset_dir if os.path.isabs(dataset_dir) else os.path.join(REPO, dataset_dir)
  117. if not os.path.isdir(dpath):
  118. if allow_missing:
  119. return True, "SKIP(--allow-missing):缺语料目录 %s" % dataset_dir
  120. return False, ("缺语料目录 %s\n 采集规范:docs/field_capture_spec.md §4;"
  121. "或用 --dataset-dir / 环境变量 PORTCV_DATASET_DIR 指定" % dataset_dir)
  122. labels = os.path.join("docs", "evidence", "test_2026-11-20", "labels.json")
  123. baseline = os.path.join("docs", "evidence", "test_2026-11-20", "baseline_violations.json")
  124. for name in (labels, baseline):
  125. if not os.path.exists(os.path.join(REPO, name)):
  126. return False, "缺判读/基线文件 %s" % name
  127. out_json = os.path.join("runs", "harness_gate", "dataset_harness.json")
  128. code, out = run([sys.executable, os.path.join("scripts", "dataset_harness.py"),
  129. "--images", _rel(dpath), "--labels", labels,
  130. "--baseline-violations", baseline,
  131. "--repeats", str(repeats), "--no-single",
  132. "--out", os.path.join("runs", "harness_gate")])
  133. if code not in (0, 1):
  134. return False, "harness 跑不起来(rc=%d)\n%s" % (code, out[-1500:])
  135. summary = {}
  136. path = os.path.join(REPO, out_json)
  137. if os.path.exists(path):
  138. try:
  139. with open(path, encoding="utf-8-sig") as fh:
  140. summary = json.load(fh)
  141. except (OSError, ValueError):
  142. summary = {}
  143. new = summary.get("new_violations") or []
  144. fixed = summary.get("fixed_violations") or []
  145. by_domain = summary.get("by_domain") or {}
  146. total_v = len(summary.get("violations") or [])
  147. note = ("%d 张;当前违例 %d 条(基线 %d)/ 新增 %d / 已修复 %d;域:%s"
  148. % (summary.get("samples", -1), total_v,
  149. len(load_baseline_keys(baseline)), len(new), len(fixed),
  150. ", ".join("%s %d 张" % (d, b.get("total", 0))
  151. for d, b in sorted(by_domain.items())) or "-"))
  152. if code == 1 or new:
  153. return False, note + "\n 新增违例:" + "、".join(new)
  154. return True, note
  155. def load_baseline_keys(baseline_rel: str) -> list:
  156. path = os.path.join(REPO, baseline_rel)
  157. try:
  158. with open(path, encoding="utf-8-sig") as fh:
  159. data = json.load(fh)
  160. except (OSError, ValueError):
  161. return []
  162. items = data.get("violations", data if isinstance(data, list) else [])
  163. return [str(item) for item in items]
  164. def main(argv: list | None = None) -> int:
  165. _use_utf8_stdout()
  166. parser = argparse.ArgumentParser(description="冻结点回归:ctest + unittest + v1/v2 现场回放")
  167. parser.add_argument("--build-dir", default=os.path.join("build-cmake", "windows-zig-release"),
  168. help="CMake 构建目录(ctest 用)")
  169. parser.add_argument("--tests-dir", default="tests", help="unittest discover 目录")
  170. parser.add_argument("--only", default="ctest,py,v1,v2,gate",
  171. help="只跑其中几组:ctest,py,v1,v2,gate(默认全跑)")
  172. parser.add_argument("--allow-missing", action="store_true",
  173. help="缺现场素材时把该组降级为 SKIP(纯算法机用;正式验收不要带)")
  174. parser.add_argument("--dataset-dir",
  175. default=os.environ.get("PORTCV_DATASET_DIR", ""),
  176. help="数据集回归语料目录(缺省取环境变量 PORTCV_DATASET_DIR;"
  177. "采集规范见 docs/field_capture_spec.md)")
  178. parser.add_argument("--gate-repeats", type=int, default=20,
  179. help="数据集门禁里“同图重复帧数”(默认 20,与测试报告同口径)")
  180. parser.add_argument("--report", default=None, help="把汇总另存一份(UTF-8)")
  181. args = parser.parse_args(argv)
  182. groups = [g.strip() for g in args.only.split(",") if g.strip()]
  183. unknown = [g for g in groups if g not in ("ctest", "py", "v1", "v2", "gate")]
  184. if unknown:
  185. print("不认识的组: %s(只用 ctest,py,v1,v2,gate)" % ",".join(unknown), file=sys.stderr)
  186. return 2
  187. results: list = []
  188. if "ctest" in groups:
  189. ok, note = check_ctest(os.path.join(REPO, args.build_dir))
  190. results.append(("C++ 自检(ctest)", ok, note))
  191. if "py" in groups:
  192. ok, note = check_python(args.tests_dir)
  193. results.append(("Python 单测(unittest discover)", ok, note))
  194. if "v1" in groups:
  195. for name, images in (("runs/ab_A_def.jsonl", "runs/field_A1/frames"),
  196. ("runs/ab_A_s2.jsonl", "runs/field_A1/frames"),
  197. ("runs/ab_B_def.jsonl", "runs/field_B/frames"),
  198. ("runs/ab_B_s2.jsonl", "runs/field_B/frames")):
  199. ok, note = check_replay(name, images, args.allow_missing)
  200. results.append(("v1 回放 %s" % name, ok, note))
  201. if "v2" in groups:
  202. for name, images in (("runs/v2gate_A4.jsonl", "runs/_v2gate_A4"),
  203. ("runs/v2gate_B4.jsonl", "runs/_v2gate_B4")):
  204. ok, note = check_replay(name, images, args.allow_missing)
  205. results.append(("v2 回放 %s" % name, ok, note))
  206. if "gate" in groups:
  207. if not args.dataset_dir:
  208. ok, note = True, "SKIP:未指定 --dataset-dir / PORTCV_DATASET_DIR(数据集门禁不跑)"
  209. else:
  210. ok, note = check_dataset_gate(args.dataset_dir, args.gate_repeats,
  211. args.allow_missing)
  212. results.append(("数据集安全门禁(禁止新增违例)", ok, note))
  213. lines: list = ["", "=" * 78, "冻结点回归", "=" * 78]
  214. bad = 0
  215. for title, ok, note in results:
  216. lines.append("%s %s\n %s" % ("[PASS]" if ok else "[FAIL]", title, note))
  217. if not ok:
  218. bad += 1
  219. lines.append("-" * 78)
  220. lines.append("共 %d 组:%d 通过 / %d 失败" % (len(results), len(results) - bad, bad))
  221. text = "\n".join(lines)
  222. print(text)
  223. if args.report:
  224. with open(args.report, "w", encoding="utf-8") as fh:
  225. fh.write(text + "\n")
  226. return 0 if bad == 0 else 1
  227. if __name__ == "__main__":
  228. sys.exit(main())