"""一套命令跑完"冻结点"回归(发版 / 交付 / 改判据之后必跑)。 为什么要一个总脚本:判据链现在有五层(C++ 契约自检、Python 单测、v1 `edge` 现场回放、 v2 `edge-v2` 现场回放、**数据集安全门禁**),分散在四五个命令里,现场/验收时**很容易漏跑 一组**,而漏跑的那一组往往正是"刚刚被改动"的那一组。 用法:: # 全部跑(默认路径就是本仓库的布局) python scripts/regression_freeze.py # 数据集门禁要指语料目录(没有现场素材时它会明确 FAIL/SKIP,而不是静默跳过) python scripts/regression_freeze.py --dataset-dir "D:/语料/dataset_20251120" # 也可以走环境变量 set PORTCV_DATASET_DIR=D:/语料/dataset_20251120 # 产物不在默认位置 / 只想跑其中几组(调试用;正式验收请跑全量) 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(报告里照样逐条列出),用于"没有现场素材的纯算法机"; * **数据集门禁只卡“变差”**:`--baseline-violations` 允许基线里已有的违例存在 (它们已记录在 `docs/evidence/test_2026-11-20/`),**新增一条就 FAIL**; 修好一条会提示同步基线 —— 既不因为"有 9 条历史违例"就永远红,也不许悄悄变差。 退出码:``0`` 全绿;``1`` 有 FAIL;``2`` 用法 / 环境问题。 """ from __future__ import annotations import argparse import json 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 check_dataset_gate(dataset_dir: str, repeats: int, allow_missing: bool) -> tuple: """数据集回归门禁:跑 `dataset_harness.py`,**只卡“新增违例”**(基线见 labels 同目录)。 为什么放进冻结点回归:2026-11-20 的 9 条危险误判(载车判 3 / 空车判 1、2)原先只写在 报告里,改判据时没有任何东西会拦住“变差”。这里用 `--baseline-violations` 把“禁止变差” 变成一条可执行的门禁;域内精度仍要等现场素材(`docs/field_capture_spec.md`)。 """ dpath = dataset_dir if os.path.isabs(dataset_dir) else os.path.join(REPO, dataset_dir) if not os.path.isdir(dpath): if allow_missing: return True, "SKIP(--allow-missing):缺语料目录 %s" % dataset_dir return False, ("缺语料目录 %s\n 采集规范:docs/field_capture_spec.md §4;" "或用 --dataset-dir / 环境变量 PORTCV_DATASET_DIR 指定" % dataset_dir) labels = os.path.join("docs", "evidence", "test_2026-11-20", "labels.json") baseline = os.path.join("docs", "evidence", "test_2026-11-20", "baseline_violations.json") for name in (labels, baseline): if not os.path.exists(os.path.join(REPO, name)): return False, "缺判读/基线文件 %s" % name out_json = os.path.join("runs", "harness_gate", "dataset_harness.json") code, out = run([sys.executable, os.path.join("scripts", "dataset_harness.py"), "--images", _rel(dpath), "--labels", labels, "--baseline-violations", baseline, "--repeats", str(repeats), "--no-single", "--out", os.path.join("runs", "harness_gate")]) if code not in (0, 1): return False, "harness 跑不起来(rc=%d)\n%s" % (code, out[-1500:]) summary = {} path = os.path.join(REPO, out_json) if os.path.exists(path): try: with open(path, encoding="utf-8-sig") as fh: summary = json.load(fh) except (OSError, ValueError): summary = {} new = summary.get("new_violations") or [] fixed = summary.get("fixed_violations") or [] by_domain = summary.get("by_domain") or {} total_v = len(summary.get("violations") or []) note = ("%d 张;当前违例 %d 条(基线 %d)/ 新增 %d / 已修复 %d;域:%s" % (summary.get("samples", -1), total_v, len(load_baseline_keys(baseline)), len(new), len(fixed), ", ".join("%s %d 张" % (d, b.get("total", 0)) for d, b in sorted(by_domain.items())) or "-")) if code == 1 or new: return False, note + "\n 新增违例:" + "、".join(new) return True, note def load_baseline_keys(baseline_rel: str) -> list: path = os.path.join(REPO, baseline_rel) try: with open(path, encoding="utf-8-sig") as fh: data = json.load(fh) except (OSError, ValueError): return [] items = data.get("violations", data if isinstance(data, list) else []) return [str(item) for item in items] 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,gate", help="只跑其中几组:ctest,py,v1,v2,gate(默认全跑)") parser.add_argument("--allow-missing", action="store_true", help="缺现场素材时把该组降级为 SKIP(纯算法机用;正式验收不要带)") parser.add_argument("--dataset-dir", default=os.environ.get("PORTCV_DATASET_DIR", ""), help="数据集回归语料目录(缺省取环境变量 PORTCV_DATASET_DIR;" "采集规范见 docs/field_capture_spec.md)") parser.add_argument("--gate-repeats", type=int, default=20, help="数据集门禁里“同图重复帧数”(默认 20,与测试报告同口径)") 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", "gate")] if unknown: print("不认识的组: %s(只用 ctest,py,v1,v2,gate)" % ",".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)) if "gate" in groups: if not args.dataset_dir: ok, note = True, "SKIP:未指定 --dataset-dir / PORTCV_DATASET_DIR(数据集门禁不跑)" else: ok, note = check_dataset_gate(args.dataset_dir, args.gate_repeats, args.allow_missing) results.append(("数据集安全门禁(禁止新增违例)", 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())