"""一套命令跑完"冻结点"回归(发版 / 交付 / 改判据之后必跑)。 为什么要一个总脚本:判据链现在有四层(C++ 契约自检 8 个、Python 330 单测、 v1 `edge` 现场回放 4 份、v2 `edge-v2` 现场回放 2 份),分散在四五个命令里, 现场/验收时**很容易漏跑一组**,而漏跑的那一组往往正是"刚刚被改动"的那一组。 用法:: # 全部跑(默认路径就是本仓库的布局) python scripts/regression_freeze.py # 产物不在默认位置 / 只想跑其中几组(调试用;正式验收请跑全量) python scripts/regression_freeze.py --build-dir build --only ctest,py 设计原则(与 `replay_check.py` 同一套价值观): * **不吞失败**:任何一组没跑成(缺目录 / 缺 dump / 退出码非 0)都记 FAIL,退出码 1; * **已知失败必须写进白名单**:`A_s2` 那 1 条"投票器把 1/2 混了"是**故意保留**的断言 (见 `docs/edge_evidence.md` §7.1 ⑤-2),白名单里写清"允许 1 条且必须匹配该模式", 多一条、或换了原因,都算 FAIL —— 绝不因为"有一条已知失败"就把整组标记成跳过; * **缺产物不静默跳过**:直接给出**生成命令**并记 FAIL;只有显式 `--allow-missing` 才降级为 SKIP(报告里照样逐条列出),用于"没有现场素材的纯算法机"。 退出码:``0`` 全绿;``1`` 有 FAIL;``2`` 用法 / 环境问题。 """ from __future__ import annotations import argparse import os import re import subprocess import sys REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 白名单:JSONL 相对路径 → (允许的 FAIL 条数, 必须匹配的模式)。不在表里 = 不允许任何 FAIL。 KNOWN_FAIL = { "runs/ab_A_s2.jsonl": (1, "投票器把 1/2 混了"), } def _rel(path: str) -> str: return path.replace(os.sep, "/") def _use_utf8_stdout() -> None: """Windows 控制台默认 GBK:子进程输出里的 `≠`/`⇒` 之类字符会让 `print` 抛异常。 这里统一成 UTF-8 + ``errors="replace"``:宁可控制台显示成问号,也不能因为 "报告打印不出来"而把一次真实的回归结果吞掉。 """ for stream in (sys.stdout, sys.stderr): try: stream.reconfigure(encoding="utf-8", errors="replace") except Exception: # pragma: no cover - 老 Python / 被重定向的流 pass def run(cmd: list, cwd: str = REPO) -> tuple: """跑一条命令,返回 ``(returncode, stdout+stderr)``(合并输出,便于定位)。""" env = dict(os.environ) env["PYTHONIOENCODING"] = "utf-8" # 子进程(replay_check / unittest)也走 UTF-8 proc = subprocess.run(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env) return proc.returncode, proc.stdout.decode("utf-8", "replace") def check_ctest(build_dir: str) -> tuple: if not os.path.isdir(build_dir): return False, ("找不到构建目录 %s\n 先生成:cmake -S cpp -B %s -DCMAKE_BUILD_TYPE=Release" " && cmake --build %s" % (build_dir, build_dir, build_dir)) code, out = run(["ctest", "--test-dir", build_dir, "--output-on-failure"]) # ctest 3.31 起汇总行是 "100% tests passed out of 7"(旧版多一段 ", N tests failed"), # 两种都认,只要求 100% + 总组数。 pct = re.search(r"(\d+)% tests passed", out) total = re.search(r"out of (\d+)", out) if not pct or not total: return False, "ctest 没有汇总行(rc=%d)\n%s" % (code, out[-2000:]) if code != 0 or pct.group(1) != "100": return False, "ctest 只有 %s%% 通过(共 %s 组)\n%s" % (pct.group(1), total.group(1), out[-2000:]) return True, "ctest %s/%s 全绿" % (total.group(1), total.group(1)) def check_python(discover_dir: str) -> tuple: code, out = run([sys.executable, "-m", "unittest", "discover", "-s", discover_dir, "-t", "."]) m = re.search(r"Ran (\d+) tests", out) if code != 0 or not re.search(r"(?m)^OK\b", out): return False, "unittest 未全绿(rc=%d)\n%s" % (code, out[-3000:]) return True, "unittest %s 项 OK" % (m.group(1) if m else "?") def check_replay(jsonl: str, images: str, allow_missing: bool) -> tuple: """回放一组;返回 ``(ok, note)``。已知失败按白名单核对**条数与原因**。""" jpath = os.path.join(REPO, jsonl) if not os.path.exists(jpath): return False, "缺导出 %s\n 生成:见 docs/edge_evidence.md §7.1 / §7.2 的采集命令" % jsonl ipath = os.path.join(REPO, images) if not os.path.isdir(ipath): if allow_missing: return True, "SKIP(--allow-missing):缺图目录 %s" % images return False, "缺图目录 %s(不带 --allow-missing 时不允许跳过)" % images code, out = run([sys.executable, os.path.join("scripts", "replay_check.py"), _rel(jsonl), "--images", _rel(images)]) tail = [ln for ln in out.splitlines() if ln.startswith("结论:")] if not tail: return False, "回放没有输出结论行(rc=%d)\n%s" % (code, out[-2000:]) # 条数以汇总行为准(`--limit` 只影响打印多少条明细,不能让"没打印"变成"没失败") m = re.search(r"FAIL (\d+) / WARN (\d+)", tail[-1]) n_fail = int(m.group(1)) if m else -1 detail = [ln for ln in out.splitlines() if "[FAIL]" in ln] allowed, pattern = KNOWN_FAIL.get(_rel(jsonl), (0, "")) if n_fail < 0: return False, "结论行里没有 FAIL 计数:%s" % tail[-1] if n_fail > allowed: extra = [ln for ln in detail if pattern not in ln] return False, "FAIL %d 条 > 白名单 %d 条:\n%s" % (n_fail, allowed, "\n".join(extra[:10]) or tail[-1]) if allowed and n_fail != allowed: return False, ("白名单要求恰好 %d 条已知 FAIL,实际 %d 条" "(是不是被顺手修好了?请同步白名单)" % (allowed, n_fail)) note = tail[-1].replace("结论: ", "") if allowed: note += "(白名单:允许 %d 条已知 FAIL「%s」)" % (allowed, pattern) return True, note def main(argv: list | None = None) -> int: _use_utf8_stdout() parser = argparse.ArgumentParser(description="冻结点回归:ctest + unittest + v1/v2 现场回放") parser.add_argument("--build-dir", default=os.path.join("build-cmake", "windows-zig-release"), help="CMake 构建目录(ctest 用)") parser.add_argument("--tests-dir", default="tests", help="unittest discover 目录") parser.add_argument("--only", default="ctest,py,v1,v2", help="只跑其中几组:ctest,py,v1,v2(默认全跑)") parser.add_argument("--allow-missing", action="store_true", help="缺现场素材时把该组降级为 SKIP(纯算法机用;正式验收不要带)") parser.add_argument("--report", default=None, help="把汇总另存一份(UTF-8)") args = parser.parse_args(argv) groups = [g.strip() for g in args.only.split(",") if g.strip()] unknown = [g for g in groups if g not in ("ctest", "py", "v1", "v2")] if unknown: print("不认识的组: %s(只用 ctest,py,v1,v2)" % ",".join(unknown), file=sys.stderr) return 2 results: list = [] if "ctest" in groups: ok, note = check_ctest(os.path.join(REPO, args.build_dir)) results.append(("C++ 自检(ctest)", ok, note)) if "py" in groups: ok, note = check_python(args.tests_dir) results.append(("Python 单测(unittest discover)", ok, note)) if "v1" in groups: for name, images in (("runs/ab_A_def.jsonl", "runs/field_A1/frames"), ("runs/ab_A_s2.jsonl", "runs/field_A1/frames"), ("runs/ab_B_def.jsonl", "runs/field_B/frames"), ("runs/ab_B_s2.jsonl", "runs/field_B/frames")): ok, note = check_replay(name, images, args.allow_missing) results.append(("v1 回放 %s" % name, ok, note)) if "v2" in groups: for name, images in (("runs/v2gate_A4.jsonl", "runs/_v2gate_A4"), ("runs/v2gate_B4.jsonl", "runs/_v2gate_B4")): ok, note = check_replay(name, images, args.allow_missing) results.append(("v2 回放 %s" % name, ok, note)) lines: list = ["", "=" * 78, "冻结点回归", "=" * 78] bad = 0 for title, ok, note in results: lines.append("%s %s\n %s" % ("[PASS]" if ok else "[FAIL]", title, note)) if not ok: bad += 1 lines.append("-" * 78) lines.append("共 %d 组:%d 通过 / %d 失败" % (len(results), len(results) - bad, bad)) text = "\n".join(lines) print(text) if args.report: with open(args.report, "w", encoding="utf-8") as fh: fh.write(text + "\n") return 0 if bad == 0 else 1 if __name__ == "__main__": sys.exit(main())