Bläddra i källkod

fix(soak): 板端浸泡收口 + INT8 定性结论(soak_watch 修假象/假绿,330 单测)

板端(WXD-A576 / RK3576,Python + rknn FP16,合成帧 15 fps,独占 NPU)跑满 30 min:
- RSS 139.09→146.82 MB(+0.01 MB/min)、句柄 10→10、线程 24→24、fps 15.00→14.96(不衰减)
- 温度 soc/npu/bigcore 峰 48.1/48.1/49.0 ℃,NPU Core0 32~35%,[warn] 0 行,退出码 0
- 但端到端只有 13.1 fps(23521 帧 / 1800 s):640×640 FP16 跑不满 max_fps=15

修 soak_watch.py 四个会误导人的地方(每处都有单测兜住):
- 带时间戳前缀的 [stat] / Python 单行摘要解析不出 frames/fps → 改子串正则,CSV 增 fps 列
- 子进程秒退(rc=2 端口占用)也输出"无明显泄漏迹象" → rc≠0 判"本次数据不作数",
  预热后有效样本 <5 判"不足以判定"
- Linux 把 VmSize 当"私有提交"(摘要出现 1530 MB 假数)→ 改读 RssAnon,抽出 parse_proc_status()
- 线程趋势含 t=0 的 exec 瞬间(1→24 误判泄漏)→ thread_leak() 只吃预热后窗口,首值同改预热后
- 新增 --replay:旧 CSV 换判据直接重算(那份 30 min 证据就是这么救回来的)

INT8 定性(160 张真实帧校准集,见 docs/deployment.md §1.3.2):
- w8a8 转换成功(10.26 MB,比 FP16 小 23%),快 1.58×(41.1 ms/24.3 fps vs 64.9 ms/15.4 fps)
- 但 verify_rknn 判 FAIL:整体 cos 0.999 是假象,类别分支 cos=0.000、top-50 anchor 0/50、解码框 0
- w16a16i 在 build 阶段报 unsupported tensor dtype in Sub (/model.22/...) → 这条路也不通
- 结论:现场继续 FP16;configs/README 与 §1.3.2 都写死了"整体 cos 会骗人"的三件套判据

新增 scripts/make_calib_dataset.py(像素级去重 + 按来源目录轮转抽样 + letterbox +
dataset.txt/manifest.csv/summary.txt,纯标准库也能跑);新增 tests/test_soak_watch.py(18 项)
与 tests/test_make_calib_dataset.py(13 项);make_docx.py 的测试数改成运行时计数
(此前手写 7 处,漏改比写错更常见),并顺手把 README 里 C++ 自检项数订正为实测值
(200/269/231,8 组共 1128 项断言,rc=0)。
Administrator 6 dagar sedan
förälder
incheckning
60527edcee

+ 9 - 7
README.md

@@ -30,7 +30,7 @@ git push -u origin develop      # 推到 Gitee 私有库(首次需认证,见
 
 分支模型、提交规范、发布检查清单、回滚与远程仓库接入:见
 **[docs/git_workflow.md](docs/git_workflow.md)**。
-提交钩子(`.githooks/pre-commit`,跑 299 项单测)需每人执行一次
+提交钩子(`.githooks/pre-commit`,跑 330 项单测)需每人执行一次
 `git config core.hooksPath .githooks` 才会生效。
 
 远端:`origin` = `https://gitee.com/kwass122/hengda--kwass.git`(**私有库**)。
@@ -112,11 +112,12 @@ portcv/            主程序包(Python 参考实现 + 工具链)
 cpp/               C++17 生产实现(零外部依赖的核心 + Modbus 服务端 + 自检)
   include/portcv/  registers / schema / crc16 / mbap / modbus_server / decision / scene / detector / snapshot
   src/             main(主循环)+ 各实现
-  tests/selftest.cpp  173 项自检(含真实 socket 回环、双客户端、粘包/半包与 Python 黄金值对拍)
+  tests/selftest.cpp  200 项自检(含真实 socket 回环、双客户端、粘包/半包与 Python 黄金值对拍)
 scripts/           开发机/现场工具:gen_cpp_constants / check_configs / dump_default_config /
                    calib_record(标定记录封存/校验)/ evidence_drill(证据恢复演练)/
                    video_eval + summarize_eval + verify_equiv(回放评估)/
-                   export_onnx / onnx_to_rknn / build_trt / soak_watch / soak_7x24
+                   export_onnx / onnx_to_rknn / make_calib_dataset(INT8 校准集去重+抽样)/
+                   verify_rknn(ONNX↔NPU 数值比对)/ build_trt / soak_watch / soak_7x24
 configs/           现场配置模板(default.json 由脚本生成)
 deploy/            systemd 服务单元、DeepStream 配置模板
 docs/              技术路线、PLC 接口、部署、架构说明
@@ -192,7 +193,7 @@ cmake -S cpp -B build -DCMAKE_BUILD_TYPE=Release
 cmake --build build -j
 ctest --test-dir build --output-on-failure     # 八个自检全绿(200 / 269 / 110 / 231 / 112 / 54 / 48 / 104)
 
-# 一条命令跑完"冻结点"回归(ctest + Python 299 单测 + v1/v2 现场回放),失败即非 0 退出
+# 一条命令跑完"冻结点"回归(ctest + Python 330 单测 + v1/v2 现场回放),失败即非 0 退出
 python scripts/regression_freeze.py --build-dir build
 
 # 跑起来(PLC 用 MB_CLIENT 轮询 1502 端口读 12 个字结果区)
@@ -215,11 +216,12 @@ Modbus 报文(FC3/4/6/16 + 异常码)、时序滤波状态游走(与 Pytho
 以及**真实 socket 回环**(起服务端,用原始报文读结果区/写指令区/验异常码)。
 另有 **边缘几何证据自检** `portcv_edge_selftest`(合成场景回归 / 安全铁律 / 运动门控;
 12 项历史失败已于 2026-10-27 清零 → **112/0**,修法与残留风险见 `docs/edge_evidence.md` §7.1)、**现场配置自检** `portcv_config_selftest`
-(JSON 严格解析 / 键映射 / 与 Python 同默认值,263 项)、**帧率/时延自检** `portcv_rate_selftest`
+(JSON 严格解析 / 键映射 / 与 Python 同默认值,269 项)、**帧率/时延自检** `portcv_rate_selftest`
 (2 s 滑窗实测 fps、p50/p95/p99、`LOW_FPS` 判据、`fps_x10` 编码,110 项)
 与 **取流层自检** `portcv_capture_selftest`(帧槽只留最新帧 / 合成帧源逐字节确定 / GStreamer 管线拼装 /
-`redact_uri` / PGM+JSONL 导出格式 / images(PGM 序列)源离线复盘 / `source.*` 校验,228 项 ——
-**不需要相机、不需要 GStreamer**)。
+`redact_uri` / PGM+JSONL 导出格式 / images(PGM 序列)源离线复盘 / `source.*` 校验,231 项 ——
+**不需要相机、不需要 GStreamer**)。以上项数均为 **2026-11-16 本机复跑实测**(`build-cmake\windows-zig-release`,
+8 组全 rc=0,合计 1128 项断言)。
 
 **真机取流(A1)**:`source.type=none|synth|images|gst|rtsp|file|usb`(键名与 Python `source.*` 同名同义);
 `rtsp|usb|file|gst` 需 `-DPORTCV_WITH_GSTREAMER=ON`,**不引入 OpenCV**;未编译/类型不认识 →

+ 1 - 1
configs/README.md

@@ -7,7 +7,7 @@
 | --- | --- |
 | `default.json` | 全量默认值,**由脚本生成**,用于对照/评审(README 与代码不会漂移) |
 | `jetson-rtsp.json` | Jetson(Orin/Xavier) + RTSP + TensorRT |
-| `rk3588-rtsp.json` | **现场机型(WXD-A576 / 主板 DC-A576 / RK3576)** + RTSP + RKNN + 按需识别(gating);**RK3576 是双 NPU core(`model.rknn_core` 可写 `auto` 或 `0_1`,板端 debugfs 实测)**。模板里 `quantized: true` 是**量化通过后的目标态**:INT8 需 200~500 张同机位真实图校准(合成图实测 cls cos=0.000),未攒够前请用 FP16(`--no-quantize --mean 0,0,0 --std 255,255,255` + `quantized: false` + `input_format: rgb_uint8`,实测 15.4 fps)。注意 `model.quantized` 只是 `describe()` 的状态元数据,**归一化是否在 NPU 内做由转换参数决定**,别指望改它来切换输入处理,见 docs/deployment.md §1.3.0 |
+| `rk3588-rtsp.json` | **现场机型(WXD-A576 / 主板 DC-A576 / RK3576)** + RTSP + RKNN + 按需识别(gating);**RK3576 是双 NPU core(`model.rknn_core` 可写 `auto` 或 `0_1`,板端 debugfs 实测)**。模板里 `quantized: true` 是**量化通过后的目标态**:INT8 需 200~500 张同机位真实图校准,且**2026-11-16 实测 160 张真实帧 w8a8 仍把类别分支打废(cls cos=0.000,整体 cos 0.999 是假象)、`w16a16i` 直接编不过**(`docs/deployment.md` §1.3.2),所以当前一律用 FP16(`--no-quantize --mean 0,0,0 --std 255,255,255` + `quantized: false` + `input_format: rgb_uint8`,板端实测 15.4 fps)。校准集怎么攒:`python scripts/make_calib_dataset.py --src runs --limit 200 --resize 640x640 --letterbox`(按像素去重 + 按来源目录轮转抽样 + 写 `dataset.txt`),转完**必须** `scripts/verify_rknn.py` 过门(类别分支 cos ≥ 0.99、框 IoU ≥ 0.9),不过就别上板。注意 `model.quantized` 只是 `describe()` 的状态元数据,**归一化是否在 NPU 内做由转换参数决定**,别指望改它来切换输入处理,见 docs/deployment.md §1.3.0 |
 | `bench-synthetic.json` | **台架自检**:合成帧 + `mock` 后端 + Modbus 服务端,**不需要相机也不需要 `.rknn` 权重**;用来先把寄存器/心跳与整链时序对齐,再换真源 |
 | `edge-cpp.json` | **C++ 版(`portcv_run`)专用**:`run.backend=edge`(二维边缘几何证据,不需要 NPU/OpenCV/模型)+ `edge.*` 参数模板。键名与 Python 同名同义,但 `backend=edge` 只有 C++ 版认识 —— Python 侧请继续用上面的模板 |
 | `demo-yolov8n.json` | **RKNN 数值冒烟专用**(不是现场模板):COCO YOLOv8n 的 80 类权重 + `input_format=rgb_uint8` + `quantized=false`,配 `scripts/verify_rknn.py` 做 ONNX↔NPU 数值比对(bus.jpg 应出 person×3 + bus)。`demo-*.json` 由 `scripts/check_configs.py` 自动跳过 4 类契约 |

+ 73 - 3
docs/deployment.md

@@ -123,9 +123,12 @@ python -m portcv doctor --backend onnx --deep
 python scripts/onnx_to_rknn.py --onnx weights/model.onnx --target rk3576 --no-quantize \
     --mean 0,0,0 --std 255,255,255 --config configs/demo-yolov8n.json
 # 攒够现场校准图后再量化(同机位、同光照,200~500 张)
-python scripts/onnx_to_rknn.py --make-dataset samples/calib --dataset calib.txt --limit 300
-python scripts/onnx_to_rknn.py --onnx weights/model.onnx --target rk3576 --dataset calib.txt \
-    --config configs/rk3588-rtsp.json   # 模板可复用,现场改存为 configs/site.json
+#   ① 从采集帧造校准集:按**像素内容**去重 + 按来源目录轮转抽样 + letterbox 到模型输入
+python scripts/make_calib_dataset.py --src runs --limit 200 --resize 640x640 --letterbox
+#   -> runs/calib_<时间戳>/{images/*.png, dataset.txt, manifest.csv, summary.txt}
+python scripts/onnx_to_rknn.py --onnx weights/model.onnx --target rk3576 \
+    --dataset runs/calib_<时间戳>/dataset.txt --config configs/rk3588-rtsp.json
+#   现场也可用旧路子(不推荐):--make-dataset samples/calib --dataset calib.txt --limit 300
 
 # ★ 转换完**必须**做数值校验(cos / top-K anchor / 解码框),不然「能跑但算错」无从发现
 python scripts/verify_rknn.py --onnx weights/model.onnx --rknn weights/model.rknn \
@@ -137,6 +140,8 @@ python -m portcv doctor --backend rknn --deep
 
 校准图必须**同机位、同光照分布**(200~500 张),否则车斗/平板车最易混;**合成图校准会直接毁掉
 类别分支**(实测 24 张合成图 → cls cos=0.000,出框全是同一类),校准图不够就别量化、走 FP16。
+**2026-11-16 追加实测**:换成 160 张真实采集帧重跑 w8a8,类别分支 cos 仍是 **0.000**(整体 cos 0.999
+是假象),`w16a16i` 在 build 阶段就报 `unsupported tensor dtype in Sub (/model.22/...)` —— 详见 §1.3.2。
 
 #### 1.3.0 工具链版本 = 精度生死线(RK3576 + YOLOv8 实测)
 
@@ -238,6 +243,71 @@ python scripts/rknpu_ratio.py --config configs/site.json --video samples/crane.m
 
 
 
+#### 1.3.2 INT8 实测:160 张真实帧也救不回来;`w16a16i` 直接编不过(2026-11-16)
+
+§1.3 上一轮只有"24 张合成图 → cls cos=0.000"这一条证据,容易被反问"图太少/太假"。
+本轮用**真实采集帧**把这条路走完,结论没变——而且顺带钉住一个更危险的东西:**整体 cos 会骗人**。
+
+**① 造校准集**(`scripts/make_calib_dataset.py`,可复现;`runs/` 里的采集帧本来就一堆重复拷贝):
+
+```bash
+python scripts/make_calib_dataset.py --src runs --limit 200 --resize 640x640 --letterbox
+#   -> 扫描 397 个文件 / 解码 392 / 按像素去重丢 232 → 唯一 160 张(9 个来源目录)
+#   -> 640x640 letterbox,PNG 28.1 MB,dataset.txt 160 行绝对路径 + manifest.csv(sha1 可追溯)
+```
+
+**② 转换**(本板 aarch64 直转,toolkit 2.3.2,参数与 FP16 完全一致,只多 `--dataset`):
+
+```bash
+python scripts/onnx_to_rknn.py --onnx weights/demo/yolov8n.onnx -o /tmp/yolov8n_int8.rknn \
+    --target rk3576 --imgsz 640 --dataset runs/calib_<ts>/dataset.txt \
+    --quantized-dtype w8a8 --mean 0,0,0 --std 255,255,255
+#   -> 10.26 MB(FP16 13.40 MB,小 23%);模型头 input/output dtype=int8,target rk3576
+```
+
+**③ 数值校验**(`scripts/verify_rknn.py`,参考 = ONNX,同一张真实帧 `images/000042.png`):
+
+| 模型 | 整体 cos | **类别分支 cos** | top-50 anchor 重合 | 解码框 | 判定 |
+| --- | --- | --- | --- | --- | --- |
+| FP16(现用) | 1.000000 | **0.999261** | 50/50 | 1 个,IoU **0.995** | **PASS**(rc=0) |
+| INT8 `w8a8` | 0.999064 | **0.000000** | **0/50** | **0 个**,IoU 0 | **FAIL**(rc=1) |
+
+**④ 速度**(`portcv bench --backend rknn --frames 30 --width 1280 --height 720`,同一块板):
+
+| 模型 | 纯推理 mean / p95 | 整链 mean | 帧率 |
+| --- | --- | --- | --- |
+| FP16 | 64.85 / 72.76 ms | 64.21 ms | 15.4 fps |
+| INT8 `w8a8` | **41.14 / 49.63 ms** | 41.81 ms | **24.3 fps** |
+
+1.58× 的加速是真的,但换不来正确的类别 —— **不能用**。
+
+**两条被这组数字钉住的教训**:
+
+1. **"整体 cos 0.999" 会骗人**。`output0` 是 `84×8400`(80 维类别 + 4 维 DFL 框),箱子那半边拟合得好,
+   整体 cos 就能到 0.999,而**类别分支已经全废**(0.000)、anchor 交集为 0。用"整体 cos ≥ 0.99"当验收,
+   会直接放行一个只会输出垃圾类别的模型。判据必须是三件套:**类别分支 cos + top-K anchor 重合 + 解码框 IoU**
+   (`verify_rknn.py` 默认就是这么判的,所以它判了 FAIL)。
+2. **校准图数量不是根因**。160 张真实帧(略少于常见 200~500 下限,但远不是 24 张合成图的量级)结果一致。
+   在 RK3576 + toolkit 2.3.2 上,这类**无 NMS 的 YOLOv8 DFL 头** w8a8 量化不可用。
+
+**⑤ 换 `--quantized-dtype w16a16i`(保真优先)—— 编不过**:
+
+```
+E RKNN: Lut fuse dtype not support yet!, dtype: 5          ×N
+E RKNN: Meet unsupported tensor dtype in Sub, tensor name is: /model.22/Constant_12_output_0
+```
+
+`model.22` 就是 DFL 解码头:toolkit 2.3.2 的 w16a16i 通路在 `Sub` 上不支持 int16 张量,
+**在 build 阶段就失败**(不出 .rknn)。所以"退一步用 w16a16i"这条路在这个模型上走不通。
+
+**现在的现场口径**:继续用 **FP16**(`--no-quantize --mean 0,0,0 --std 255,255,255` +
+`input_format=rgb_uint8` + `quantized=false`),`configs/rk3588-rtsp.json` 里的 `quantized: true` 只是目标态。
+真想再试,按性价比排序:① 校准图扩到 500+ 且覆盖全部机位/逆光(**不保证有效**,见上第 2 条);
+② 换 toolkit 版本(2.3.2 是"精度生死线",见 §1.3.0,升级必须重跑 `verify_rknn.py`);
+③ 换成带 NMS 的导出图(`weights/demo/yolov8n_nms.onnx`,把 decode 进图后量化误差不再放大到类别轴)——
+但**换图属于换判据**,必须重跑阈值整定与现场片段回放(`docs/runtime_route_decision.md` §4)。
+
+
 ### 1.4 现场硬件确认清单(WXD-A576,采购/开箱先核这 9 项,依据《WXD-A576 工控主机(铝合金)规格说明书》)
 
 | 项 | 规格书值 | 现场必须确认 |

+ 2 - 2
docs/git_workflow.md

@@ -18,7 +18,7 @@
 | 首版基线 | 附注标签 `v0.1.0` —— 与本轮桌面交付包一致 |
 | 行尾策略 | `.gitattributes`:库内统一 LF,`*.bat/*.cmd/*.ps1` 检出为 CRLF |
 | 提交模板 | `.gitmessage`(`git config commit.template`) |
-| 提交钩子 | `.githooks/pre-commit`:跑 L1 单测(299 项,约 4 s) |
+| 提交钩子 | `.githooks/pre-commit`:跑 L1 单测(330 项,约 6 s) |
 | 忽略清单 | `.gitignore`:`runs/`、`build/`、`build-cmake/`、权重(`*.onnx/*.rknn/*.engine`)、`*.out/*.err`… |
 | 远端仓库 | `origin` → `git@gitee.com:kwass122/hengda--kwass.git`(Gitee **私有库**;`main`/`develop`/`v0.1.0` 已于 2026-11-09 推送,见 §6.1) |
 
@@ -260,7 +260,7 @@ git bisect good v0.1.0
 # 1) 工作区必须干净,且当前在 release/* 或 main 上
 git status -sb
 
-# 2) L1 单元测试(299 项)
+# 2) L1 单元测试(330 项)
 python -m unittest discover -s tests -q
 
 # 3) L2 契约自检(C++ 侧 8 组 1128 项断言)

+ 1 - 1
docs/runtime_route_decision.md

@@ -183,7 +183,7 @@ python scripts/replay_check.py runs/field_B/dump.jsonl --report runs/field_B/rep
 | **P0 修复:v2 导出契约缺口** | `replay_check.py` 对 v2 dump | 修前 20 FAIL(`abstain` 被写死 false、脚本只认 v1 的 14 项 `ev`)→ 修后 `abstain` 如实填写 + 脚本支持双口径 + 新增"高悬命中 ⇒ `edge_state=255` 且 `abstain=true`"断言 |
 | **残留风险**(2026-10-27 复核) | 同一批帧的 `edge_state` | v1:B 有 **2 帧**本帧结论 = `1`(未成串、未发布);A 打开 `allow_state2` 后 **1 帧** = `2`(`px_per_m=67.4` 最远帧)。v2:修 `min_bed_roi_px` 后 B 已 **0 帧** = `1`,但 A 255×9 / B 255×48 说明**远距与遮挡帧仍大量弃权**;需 step 1 连续帧 + 现场补拍整定 → `docs/edge_evidence.md` §7.1 ⑤ / §7.2 ③ |
 | **确定性复核** | 同一批 PGM 再跑一遍,与第一遍逐帧对拍(`replay_check.py --baseline`) | **状态 0 / 置信度 0 / 证据 0 / 像素 0 处差异**,1887 项断言 PASS → 判据链确定性成立 |
-| **冻结点回归(一条命令)** | `python scripts/regression_freeze.py` | **8 组全绿**:ctest 8/8、unittest 299、v1 回放 4 份(`A_s2` 按白名单恰好 1 条已知 FAIL)、v2 回放 2 份;缺产物 / 多一条失败即非 0 退出,绝不静默跳过(`runs/_freeze.txt`) |
+| **冻结点回归(一条命令)** | `python scripts/regression_freeze.py` | **8 组全绿**:ctest 8/8、unittest 330、v1 回放 4 份(`A_s2` 按白名单恰好 1 条已知 FAIL)、v2 回放 2 份;缺产物 / 多一条失败即非 0 退出,绝不静默跳过(`runs/_freeze.txt`) |
 | **现场语料的负向对照** | 把 1 帧的 1 个像素字节 +1 后回放 | 1 FAIL(`gray_crc32=2002841861 与像素实算 3586875639 不符`),退出码 1 → 现场语料同样"能过也能不过" |
 | **连续帧窗口**(f1550–1569,step 1) | 同上,`--start 1550 --stop 1569 --step 1` | 20 帧全 `255`;**`motion=0/20`**(对比 step5 的 37/59),`px_per_m` 115.07–115.49、`box_h_px` 298.1–299.2 → 运动门控与几何量都稳定 |
 | P0 修复:`--fps nan` | `python scripts/fuzz_app.py --exe … --only fps_nan` | 改前 `rc=0`(全速空转风险)→ 改后 **`rc=2` + `--fps 必须 ∈ (0, 240]`**(判据写成 `!(x > 0)`,NaN 比较恒 false 的坑) |

+ 1 - 1
docs/soak_7x24.md

@@ -257,6 +257,6 @@ ASAN_OPTIONS=detect_leaks=1:abort_on_error=1 \
 - 此前跑过 6 s 冒烟(`runs/soak7_final4`):PASS,4 个样本,FC4+CRC 探活 100%。
 - 质量补丁/报告脱敏/终止事件硬失败后再次跑 6 s 冒烟(`runs/soak7_postpatch6`,合成输入 + 放宽阈值):
   PASS,4 个样本、0 重启、FC4+CRC 探活 100%;仅验证链路,不是 168 h 证据。
-- 单测 `python -m unittest discover -s tests -t .` 共 184 项全部通过(当时口径;当前主线为 299 项,见 `docs/stability_soak.md`)。
+- 单测 `python -m unittest discover -s tests -t .` 共 184 项全部通过(当时口径;当前主线为 330 项,见 `docs/stability_soak.md`)。
 - **168 h 未在本聊天会话内执行**:它必须在目标板卡 + 真实 RTSP + 真实 PLC 环境连续运行;
   本页给出的是可复现的执行与验收方法,不能把 20 s 冒烟当成 7×24 结论。

+ 84 - 1
docs/stability_soak.md

@@ -38,6 +38,9 @@ python scripts/modbus_torture.py --host 127.0.0.1 --port 1502 --no-launch   # 
 python scripts/soak_watch.py -- python/build/portcv_run -c configs/edge-cpp.json \
     --backend edge --edge-demo ground --no-plc --max-frames 20000
 python scripts/soak_watch.py --pid $(pgrep portcv_run) --minutes 30        # 板子上盯已在跑的进程
+#    Python 版服务也照样盯(C++ 与 Python 两种日志格式都认,见下面 §1.1):
+python scripts/soak_watch.py --warmup 120 --interval 10 --minutes 30 -- \
+    .venv/bin/python -m portcv run -c configs/demo-yolov8n.json
 
 # 4) 7x24 长跑(168 h、边采边落盘、重启续跑、Modbus 探活;详见 docs/soak_7x24.md)
 python scripts/soak_7x24.py --duration 7d --interval 60 --warmup 3600 \
@@ -53,6 +56,29 @@ python scripts/replay_check.py runs/dump/new.jsonl --baseline runs/dump/golden.j
 第 5 条与前四条的**判据口径一致**(`0` 通过 / `1` 有 FAIL / `2` 用法环境),但管的不是"稳不稳",
 而是**"这一帧的结论与它的证据是否自洽、与基线是否一致"** —— 详见 `docs/runtime_route_decision.md` §4。
 
+### 1.1 `soak_watch.py` 认哪些日志、以及"什么情况下它不给你判绿"
+
+2026-11-16 在 RK3576 上做 30 min 浸泡时踩到两个坑,已经不是坑了,写在这里免得再走一遍:
+
+| 现象 | 原因 | 现在的行为 |
+| --- | --- | --- |
+| `runs/soak_*.csv` 里 `frames`、`fps` 全是 `None`,进度停滞完全看不出来 | 旧实现用 `line.startswith("[stat]")` 匹配,而经 systemd/journald/`tee` 转发的行首带 `16:17:55 \| INFO \| portcv.runner \| ` 前缀;Python 版 `portcv run` 用的又根本不是 `[stat]` 格式 | 改成**子串正则**:C++ 的 `[stat] 已发布 N 帧` + `fps_x10=`、Python 的 `seq= fps= lat= … frames= pub= chg= err=` 都能解析,CSV 里多了 `fps` 列 |
+| 子进程秒退(rc=2,端口被占用)也输出了"结论: 无明显泄漏迹象" | 判定只看 RSS/句柄趋势,不看"这份数据是否作数" | 先判数据有效性:**子进程 rc≠0** → "本次数据不作数";**预热后有效样本 < 5** → "不足以判定";两种情况退出码都是 `1` |
+| 长跑收尾留一堆 `ResourceWarning: unclosed file …stdout.log` | 被测进程日志句柄没关 | `finally` 里关掉 |
+| 摘要写"私有提交 1530 MB" | Linux 采样把 **`VmSize`**(虚拟地址空间,cv2/numpy 映射常驻 1.5 GB)当成"私有提交" | 改读 **`RssAnon`**(匿名常驻 ≈ 私有提交);解析抽成 `parse_proc_status()` 纯函数好单测 |
+| 摘要判"线程数 1 → 24 → 疑似线程泄漏" | 线程趋势用了**全部**采样行,t=0 那次撞在子进程刚 exec 的瞬间(`Threads: 1`、RSS 0) | 抽出 `thread_leak(rows)` 且**只吃预热后的窗口**;摘要里的"首值"同样改取预热后 |
+
+板上跑完的 30 min 浸泡就是被后两条坑到过——`runs/soak_board_20261116/` 里那份原始摘要写的是
+"疑似线程泄漏 / 私有 1530 MB",同一份 CSV 用现在的判据重算是"无泄漏迹象、线程 24→24":
+
+```bash
+python scripts/soak_watch.py --replay runs/soak_board_20261116/soak_20261116_161701.csv --warmup 120
+```
+
+`--replay` 就是为此加的:**旧 CSV 不必重跑 30 min**,换判据直接重算(`.replay.txt` 会写在 CSV 旁边)。
+
+对应的单测在 `tests/test_soak_watch.py`(12 项),改这两个函数不用上板就能验。
+
 这些脚本的产出都落在 `runs/`(**已在 `.gitignore` 里**):`fuzz_<时间戳>.txt` + 语料目录、
 `modbus_torture_<时间戳>.txt` + 服务端日志、`soak_<时间戳>.{csv,txt}` + 被测进程日志、
 `soak7_*/`(7×24 campaign:samples/events/report/stdout 日志)。
@@ -70,7 +96,7 @@ CSV 每行一次采样,可直接拖进表格画曲线,也可以当交付证
 | 运行期观测量自检(p50/p95/p99 / LOW_FPS / `fps_x10`) | `portcv_rate_selftest` | **110 通过 / 0 失败**(两个变体一致) |
 | 边缘证据自检 | `portcv_edge_selftest` | **112 通过 / 0 失败**(2026-10-27:C1/F2/F3/G2 等 12 项历史失败清零) |
 | 标定记录自检(sha256 / canonical JSON 跨语言黄金向量 / 过期与漂移) | `portcv_calib_selftest` | **104 通过 / 0 失败**(2026-10-27 新增;`ctest` **8/8**) |
-| Python 回归 | `python -m unittest discover -s tests -t .` | **299 项全绿**(本机 3.9 s,2026-11-16 复核) |
+| Python 回归 | `python -m unittest discover -s tests -t .` | **330 项全绿**(本机 6.0 s,2026-11-16 复核) |
 | 配置模板校验 | `python scripts/check_configs.py` | **4/4 通过**(default / edge-cpp / jetson-rtsp / rk3588-rtsp) |
 | 默认值防漂移 | `dump_default_config.py` 与 `configs/default.json` 逐字节对比 | **完全一致**(4945 字节) |
 | 默认值防漂移 | `dump_default_config.py --stdout` 与 `configs/default.json` 逐字节对比 | **完全一致**(2815 字节) |
@@ -361,6 +387,63 @@ python3 scripts/fuzz_app.py --exe /opt/portcv/bin/portcv_run
 建议把三条命令的输出(`runs/soak_*.txt`、`runs/modbus_torture_*.txt`、`runs/fuzz_*.txt`)
 随验收记录一起归档——它们比"跑了一遍没问题"这句话有用得多。
 
+### 6.1 2026-11-16 RK3576 板端实跑(Python + `rknn` 后端,30 min)
+
+§6 那三步是给 **C++ `portcv_run`** 的清单;RK3576 现场跑的是 **Python 服务 + RKNN 后端**,
+所以这里单独记一次真机结果——开发机的数字不能当板卡数字。
+
+**环境**:WXD-A576 / `ztl,rk3576 A576`、aarch64、Python 3.11.2、运行时 `rknn-toolkit-lite2 2.5.0`、
+模型 `weights/demo/yolov8n.rknn`(**FP16**,由 toolkit **2.3.2** 转,target 写死 `rk3576`,
+输入 640×640 `rgb_uint8`,`std=255` 归一化在 NPU 内做)。
+
+**负载**:合成帧 15 fps + `mode=composed` + Modbus 服务端 `:1503`(刻意只测视觉侧,不含相机/网络抖动)。
+浸泡期间 `systemctl stop portcv` 独占 NPU,结束后恢复服务(`NRestarts=0`)。
+
+```bash
+systemctl stop portcv
+python scripts/soak_watch.py --warmup 120 --interval 10 --minutes 30 -- \
+    .venv/bin/python -m portcv run -c /tmp/_soak.json       # demo COCO + rknn + 合成帧 15 fps
+# 另一个窗口每 10 s 采一次 /sys/class/thermal/thermal_zone*/temp 与 /sys/kernel/debug/rknpu/load
+```
+
+| 项 | 判据 | 实测 | 结论 |
+| --- | --- | --- | --- |
+| 采样 | 30 min | 181 样本 / 30.0 min(间隔 10 s;预热 120 s 不计) | — |
+| RSS | < 1 MB/min | 139.09 → 146.82 MB(峰 147.60),**+0.01 MB/min** | 通过 |
+| 句柄(fd) | 净增 < 10 | 10 → 10(净 **0**,0.00 个/min) | 通过 |
+| 线程 | 不涨 | 24 → 24(全程峰 24) | 通过 |
+| 帧率 | 不衰减 | 前 60 条 `fps=` **15.00** / 后 60 条 **14.96**(−0.3%) | 通过 |
+| 吞吐 | — | 30 min 共 **23 521 帧** → 端到端 **13.1 fps**(模型链占 79%) | 见下 |
+| 温度 | < 85 ℃ | soc 40.7→48.1 ℃、npu 44.4→48.1 ℃、bigcore 45.3→49.0 ℃ | 通过(工作温度 0~70 ℃) |
+| NPU 占用 | 无降频 | Core0 32~35%(0% 只出现在启动瞬间) | 通过 |
+| 日志噪声 | 不刷屏 | `[warn]` **0** 行;另有 1 条 RKNN 初始化提示见下 | 通过 |
+| 退出码 | 0 | 0 | 通过 |
+
+**三个必须记住的数**:
+
+* `grabber` 报 15.0 fps,**主循环端到端只有 13.1 fps**(23 521 / 1800 s)。即 `run.max_fps=15`
+  在 640×640 **FP16** 上跑不满,差值就是丢帧——NPU 纯推理上限约 15.4 fps(`docs/deployment.md` §1.3)。
+  真要 15 fps 只有三条路:降 `model.input_size`(**必须重跑阈值整定**)、把 `run.max_fps` 明示降到
+  10~12(PLC 侧要知道)、或走 INT8(**实测 w8a8 类别分支报废、`w16a16i` 编不出来**,
+  见 `docs/deployment.md` §1.3.2 —— 这条路目前不通)。
+* 决策状态全程 `state=255(unknown)`:合成帧本来没有车/箱,**255 是弃权安全值**,符合
+  `docs/runtime_route_decision.md` 的设计(没看清就不硬判)。
+* 日志里那条 `Query dynamic range failed. Ret code: RKNN_ERR_MODEL_INVALID. (If it is a static shape
+  RKNN model, please ignore the above warning message.)` 是 rknnlite 对**静态 shape** 模型的良性提示,
+  不是错误;`doctor --backend rknn --deep` 通过即可忽略。
+
+**证据**:`runs/soak_board_20261116/soak_20261116_161701.{csv,txt,stdout.log}`(`runs/` 已 gitignore,
+随验收记录归档)。**磁盘上那份 `.txt` 是旧判据生成的**(线程假阳性 / 私有提交写成了 VmSize),
+以后者为准请看 `--replay` 重算:
+
+```bash
+python scripts/soak_watch.py --replay runs/soak_board_20261116/soak_20261116_161701.csv --warmup 120
+#   -> 结论: 无明显泄漏迹象(RSS 0.01 MB/min、句柄 0.00 个/min,均在阈值内);退出码 0
+```
+
+**本轮尚未做**:§6 的第②③步(`modbus_torture` / `fuzz_app`)只在开发机跑过,板端还没跑;
+168 h 长跑(`docs/soak_7x24.md`)也没做——**30 min 浸泡不能替代 168 h**。
+
 ## 7. 结论与后续动作
 
 **结论**:C++ 边端程序在本轮**稳定性 / 鲁棒性 / 浸泡**测试中表现扎实——

+ 429 - 0
scripts/make_calib_dataset.py

@@ -0,0 +1,429 @@
+"""从采集帧里生成 RKNN **INT8 量化校准集**(去重 + 抽样 + 归一尺寸 + ``dataset.txt``)。
+
+为什么需要它:``scripts/onnx_to_rknn.py`` 的 ``--make-dataset`` 只是把目录里**每个文件**
+列进 txt,不去重、不归一尺寸。现场采集(``--dump-frames``)一晚上会留下大量**同一帧的重复拷贝**
+(本轮实测 ``runs/`` 397 个文件去重后只有 165 张真实帧),直接拿去校准会让统计量偏向那些重复
+场景,而且 640×480 的图与模型 640×640 输入也不一致。
+
+用法::
+
+    # 1) 台架/开发机:从 runs/ 造一个 200 张的校准集(默认写 PNG,纯标准库,不依赖 Pillow/cv2)
+    python scripts/make_calib_dataset.py --src runs --limit 200 \
+        --resize 640x640 --letterbox
+
+    # 2) 打包上传(板端转换那台机器)
+    tar czf calib.tgz -C runs calib_<时间戳>
+
+    # 3) 板端转换(YOLOv8 必须钉 toolkit 2.3.2,见 requirements-rknn.txt)
+    python scripts/onnx_to_rknn.py --onnx weights/yolov8n.onnx -o /tmp/yolov8n_int8.rknn \
+        --target rk3588 --imgsz 640 --dataset /opt/portcv/runs/calib_<时间戳>/dataset.txt \
+        --quantized-dtype w8a8
+
+    # 4) 一定要验:cls cos / 框 IoU 不达标就别上板
+    python scripts/verify_rknn.py --fp16 weights/yolov8n.rknn --int8 /tmp/yolov8n_int8.rknn
+
+输出(都在 ``--out`` 下)::
+
+    images/000001.png ...   归一后的校准图(默认 PNG,按需 ``--format jpg``)
+    dataset.txt             每行一个**绝对路径**,直接喂 ``onnx_to_rknn.py --dataset``
+    manifest.csv            sha1, 源文件, 输出文件, 宽, 高, 字节数 —— 交付记录要能追溯
+    summary.txt             本次造集的数字(扫描/去重/抽样),随验收记录归档
+
+判据(本脚本只负责"造得对",精度由 ``verify_rknn.py`` 判):
+
+* 去重按**像素内容**算 sha1(同一帧存两个文件名只算一张);
+* 抽样按**来源目录轮转**(``runs/dump_a``、``runs/dump_b`` … 各取几张),避免某一批场景霸屏;
+* 200~500 张是经验区间:太少统计量不稳,太多只是拖长转换时间(13 min/次量级)。
+
+只用标准库:PGM(P5/P6)自带解码,PNG 自带编码(zlib)。其它格式(JPG/PNG 输入)需要
+Pillow 或 OpenCV,装了就自动用,没装就跳过并计数,不会让整个流程失败。
+"""
+
+from __future__ import annotations
+
+import argparse
+import csv
+import datetime as _dt
+import hashlib
+import os
+import struct
+import sys
+import zlib
+
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+IMAGE_EXT = (".pgm", ".png", ".jpg", ".jpeg", ".bmp")
+PNG_SIG = b"\x89PNG\r\n\x1a\n"
+
+
+class ImageError(Exception):
+    """读不出来 / 不支持的格式。"""
+
+
+def read_pgm(path: str):
+    """读 PGM(P5 灰度 / P6 彩色),返回 ``(w, h, channels, pixels_bytes)``。"""
+    with open(path, "rb") as fh:
+        data = fh.read()
+    if not data.startswith((b"P5", b"P6")):
+        raise ImageError("不是 P5/P6 PGM:%s" % path)
+    channels = 1 if data[1:2] == b"5" else 3
+    pos = 2
+    values = []
+    while len(values) < 3:
+        while pos < len(data) and data[pos:pos + 1].isspace():
+            pos += 1
+        if data[pos:pos + 1] == b"#":                     # 注释行
+            while pos < len(data) and data[pos:pos + 1] not in (b"\n", b"\r"):
+                pos += 1
+            continue
+        start = pos
+        while pos < len(data) and not data[pos:pos + 1].isspace():
+            pos += 1
+        if start == pos:
+            raise ImageError("PGM 头部损坏:%s" % path)
+        values.append(int(data[start:pos]))
+    pos += 1                                              # 头部与像素之间恰好一个空白
+    width, height, maxval = values
+    if maxval != 255:
+        raise ImageError("只支持 8 位 PGM(maxval=255),得到 %d:%s" % (maxval, path))
+    need = width * height * channels
+    pixels = data[pos:pos + need]
+    if len(pixels) != need:
+        raise ImageError("PGM 像素不足:%s(%d/%d)" % (path, len(pixels), need))
+    return width, height, channels, pixels
+
+
+def read_other(path: str):
+    """非 PGM 输入:有 Pillow / OpenCV 就解码成 RGB,没有就抛 :class:`ImageError`。"""
+    try:  # Pillow
+        from PIL import Image  # type: ignore
+
+        with Image.open(path) as img:
+            img = img.convert("RGB")
+            return img.size[0], img.size[1], 3, img.tobytes()
+    except ImportError:
+        pass
+    try:  # OpenCV(BGR → RGB)
+        import cv2  # type: ignore
+
+        img = cv2.imread(path, cv2.IMREAD_COLOR)
+        if img is None:
+            raise ImageError("OpenCV 读不出来:%s" % path)
+        rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
+        return rgb.shape[1], rgb.shape[0], 3, rgb.tobytes()
+    except ImportError:
+        raise ImageError("读 %s 需要 Pillow 或 OpenCV(PGM 除外)" % path)
+
+
+
+
+def load_image(path: str):
+    """统一入口:按魔数分派,返回 ``(w, h, channels, pixels)``。"""
+    with open(path, "rb") as fh:
+        magic = fh.read(2)
+    if magic in (b"P5", b"P6"):
+        return read_pgm(path)
+    return read_other(path)
+
+
+def content_sha1(w: int, h: int, channels: int, pixels: bytes) -> str:
+    """按**像素内容**算 sha1(同一帧存两个文件名 → 同一个哈希)。"""
+    digest = hashlib.sha1()
+    digest.update(("%dx%dx%d|" % (w, h, channels)).encode("ascii"))
+    digest.update(pixels)
+    return digest.hexdigest()
+def resize(w: int, h: int, channels: int, pixels: bytes, tw: int, th: int,
+           letterbox: bool = False, pad: int = 114):
+    """双线性缩放到 ``(tw, th)``;``letterbox`` 时保持长宽比并用 ``pad`` 填充。"""
+    if (tw, th) == (w, h):
+        return w, h, pixels
+    if letterbox:
+        scale = min(tw / float(w), th / float(h))
+        nw = max(1, int(round(w * scale)))
+        nh = max(1, int(round(h * scale)))
+    else:
+        nw, nh = tw, th
+    scaled = _bilinear(w, h, channels, pixels, nw, nh)
+    if (nw, nh) == (tw, th):
+        return tw, th, scaled
+    canvas = bytearray([pad]) * (tw * th * channels)
+    x0 = (tw - nw) // 2
+    y0 = (th - nh) // 2
+    row_bytes = nw * channels
+    for y in range(nh):
+        src = y * row_bytes
+        dst = ((y0 + y) * tw + x0) * channels
+        canvas[dst:dst + row_bytes] = scaled[src:src + row_bytes]
+    return tw, th, bytes(canvas)
+
+
+def _bilinear(w: int, h: int, channels: int, pixels: bytes, nw: int, nh: int) -> bytes:
+    """双线性缩放。有 numpy 走向量化(960×540→640×360 约 3 ms),没有就纯 Python 兜底。"""
+    x_ratio = (w - 1) / float(max(1, nw - 1)) if nw > 1 else 0.0
+    y_ratio = (h - 1) / float(max(1, nh - 1)) if nh > 1 else 0.0
+    try:
+        import numpy as np  # type: ignore
+    except ImportError:
+        np = None
+    if np is not None:
+        arr = np.frombuffer(pixels, dtype=np.uint8)
+        arr = arr.reshape((h, w, channels) if channels > 1 else (h, w))
+        ys = np.clip(np.arange(nh, dtype=np.float32) * y_ratio, 0, h - 1)
+        xs = np.clip(np.arange(nw, dtype=np.float32) * x_ratio, 0, w - 1)
+        y0 = ys.astype(np.intp)
+        x0 = xs.astype(np.intp)
+        y1 = np.minimum(y0 + 1, h - 1)
+        x1 = np.minimum(x0 + 1, w - 1)
+        fy = (ys - y0).astype(np.float32)
+        fx = (xs - x0).astype(np.float32)
+        if channels > 1:
+            fy, fx = fy[:, None, None], fx[None, :, None]
+        else:
+            fy, fx = fy[:, None], fx[None, :]
+        top = arr[y0][:, x0].astype(np.float32) * (1 - fx) + arr[y0][:, x1].astype(np.float32) * fx
+        bot = arr[y1][:, x0].astype(np.float32) * (1 - fx) + arr[y1][:, x1].astype(np.float32) * fx
+        return (top * (1 - fy) + bot * fy + 0.5).astype(np.uint8).tobytes()
+
+    out = bytearray(nw * nh * channels)
+    for y in range(nh):
+        sy = y * y_ratio
+        y0 = int(sy)
+        y1 = min(h - 1, y0 + 1)
+        fy = sy - y0
+        row0 = y0 * w * channels
+        row1 = y1 * w * channels
+        dst = y * nw * channels
+        for x in range(nw):
+            sx = x * x_ratio
+            x0 = int(sx)
+            x1 = min(w - 1, x0 + 1)
+            fx = sx - x0
+            a = row0 + x0 * channels
+            b = row0 + x1 * channels
+            c = row1 + x0 * channels
+            d = row1 + x1 * channels
+            for ch in range(channels):
+                top = pixels[a + ch] * (1 - fx) + pixels[b + ch] * fx
+                bot = pixels[c + ch] * (1 - fx) + pixels[d + ch] * fx
+                out[dst + x * channels + ch] = int(top * (1 - fy) + bot * fy + 0.5)
+    return bytes(out)
+
+
+def write_png(path: str, w: int, h: int, channels: int, pixels: bytes) -> None:
+    """写 8 位灰度/彩色 PNG(filter=0,纯 zlib;不依赖 Pillow)。"""
+    color_type = 0 if channels == 1 else 2
+    stride = w * channels
+    raw = bytearray()
+    for y in range(h):
+        raw.append(0)                                     # 每行 filter type = 0
+        raw += pixels[y * stride:(y + 1) * stride]
+
+    def chunk(tag: bytes, payload: bytes) -> bytes:
+        return (struct.pack(">I", len(payload)) + tag + payload
+                + struct.pack(">I", zlib.crc32(tag + payload) & 0xFFFFFFFF))
+
+    ihdr = struct.pack(">IIBBBBB", w, h, 8, color_type, 0, 0, 0)
+    with open(path, "wb") as fh:
+        fh.write(PNG_SIG + chunk(b"IHDR", ihdr)
+                 + chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + chunk(b"IEND", b""))
+
+def write_jpg(path: str, w: int, h: int, channels: int, pixels: bytes, quality: int) -> None:
+    """写 JPEG(需要 Pillow 或 OpenCV;都没有就抛 :class:`ImageError`)。"""
+    try:
+        from PIL import Image  # type: ignore
+
+        mode = "L" if channels == 1 else "RGB"
+        Image.frombytes(mode, (w, h), pixels).save(path, quality=int(quality))
+        return
+    except ImportError:
+        pass
+    try:
+        import cv2  # type: ignore
+        import numpy as np  # type: ignore
+
+        flat = np.frombuffer(pixels, dtype=np.uint8)
+        arr = flat.reshape((h, w)) if channels == 1 else flat.reshape((h, w, channels))
+        img = arr if channels == 1 else cv2.cvtColor(arr, cv2.COLOR_RGB2BGR)
+        if not cv2.imwrite(path, img, [int(cv2.IMWRITE_JPEG_QUALITY), int(quality)]):
+            raise ImageError("cv2.imwrite 失败:%s" % path)
+        return
+    except ImportError:
+        raise ImageError("--format jpg 需要 Pillow 或 OpenCV;本机都没有,请用 --format png")
+
+
+
+
+# --------------------------------------------------------------------------- 扫描 / 抽样
+def iter_images(src: str, exts=IMAGE_EXT):
+    """递归列出 ``src`` 下的候选图片(排序,保证可复现)。"""
+    found = []
+    for root, _dirs, files in os.walk(src):
+        for name in files:
+            if name.lower().endswith(tuple(exts)):
+                found.append(os.path.join(root, name))
+    return sorted(found)
+
+
+def scan(src: str, dedupe: bool = True) -> dict:
+    """解码 + 去重,返回 ``{"groups": {目录: [frame...]}, "stats": {...}}``。
+
+    frame = ``{path, w, h, channels, pixels, sha1}``;去重后**保留首次出现的那张**
+    (``iter_images`` 有序,所以结果可复现)。
+    """
+    stats = {"scanned": 0, "decoded": 0, "failed": 0, "dup": 0, "uniq": 0}
+    groups: dict = {}
+    seen: dict = {}
+    for path in iter_images(src):
+        stats["scanned"] += 1
+        try:
+            w, h, channels, pixels = load_image(path)
+        except (ImageError, OSError, ValueError):
+            stats["failed"] += 1
+            continue
+        stats["decoded"] += 1
+        sha = content_sha1(w, h, channels, pixels)
+        if dedupe and sha in seen:
+            stats["dup"] += 1
+            continue
+        seen[sha] = path
+        group = os.path.dirname(os.path.relpath(path, src)) or "."
+        groups.setdefault(group, []).append(
+            {"path": path, "w": w, "h": h, "channels": channels, "pixels": pixels, "sha1": sha})
+    stats["uniq"] = sum(len(v) for v in groups.values())
+    return {"groups": groups, "stats": stats}
+
+
+def pick(groups: dict, limit: int) -> list:
+    """按来源目录**轮转**抽样:每个目录各取一张,循环直到够数(``limit<=0`` 表示全取)。"""
+    if limit <= 0:
+        return [f for key in sorted(groups) for f in groups[key]]
+    order = sorted(groups)
+    queues = [list(groups[key]) for key in order]
+    out: list = []
+    while len(out) < limit and any(queues):
+        for queue in queues:
+            if not queue:
+                continue
+            out.append(queue.pop(0))
+            if len(out) >= limit:
+                break
+    return out
+
+def build(src: str, out: str, limit: int = 200, resize_to: str = "", letterbox: bool = False,
+          pad: int = 114, fmt: str = "png", quality: int = 88, dedupe: bool = True,
+          dataset_name: str = "dataset.txt", quiet: bool = False) -> int:
+    """造集主流程;返回进程退出码(0 成功 / 2 没有可用图片 / 3 输出格式不可用)。"""
+    target = None
+    if resize_to:
+        try:
+            tw, th = [int(part) for part in resize_to.lower().split("x")]
+        except ValueError:
+            print("--resize 需要 WxH 形式(如 640x640),得到 %r" % resize_to, file=sys.stderr)
+            return 2
+        if tw <= 0 or th <= 0 or tw % 32 or th % 32:
+            print("--resize 的宽高必须是 32 的正整数倍(RKNN 输入对齐),得到 %dx%d" % (tw, th),
+                  file=sys.stderr)
+            return 2
+        target = (tw, th)
+
+    result = scan(src, dedupe=dedupe)
+    stats = result["stats"]
+    frames = pick(result["groups"], limit)
+    if not frames:
+        print("没有可用图片:扫描 %d,解码失败 %d(--src 指对了吗?)"
+              % (stats["scanned"], stats["failed"]), file=sys.stderr)
+        return 2
+
+    img_dir = os.path.join(out, "images")
+    os.makedirs(img_dir, exist_ok=True)
+    rows = []
+    for idx, frame in enumerate(frames, 1):
+        w, h, ch, px = frame["w"], frame["h"], frame["channels"], frame["pixels"]
+        if target is not None:
+            w, h, px = resize(w, h, ch, px, target[0], target[1],
+                              letterbox=letterbox, pad=pad)
+        dst = os.path.abspath(os.path.join(img_dir, "%06d.%s" % (idx, fmt)))
+        try:
+            if fmt == "jpg":
+                write_jpg(dst, w, h, ch, px, quality)
+            else:
+                write_png(dst, w, h, ch, px)
+        except ImageError as exc:
+            print(str(exc), file=sys.stderr)
+            return 3
+        rows.append({"sha1": frame["sha1"], "src": frame["path"], "out": dst,
+                     "width": w, "height": h, "bytes": os.path.getsize(dst)})
+
+    dataset = os.path.abspath(os.path.join(out, dataset_name))
+    with open(dataset, "w", encoding="utf-8") as fh:
+        for row in rows:
+            fh.write(row["out"] + "\n")
+    manifest = os.path.abspath(os.path.join(out, "manifest.csv"))
+    with open(manifest, "w", newline="", encoding="utf-8") as fh:
+        writer = csv.DictWriter(fh, fieldnames=list(rows[0]))
+        writer.writeheader()
+        writer.writerows(rows)
+
+    total_mb = sum(row["bytes"] for row in rows) / 1048576.0
+    size_note = ("原尺寸 %dx%d" % (rows[0]["width"], rows[0]["height"])) if target is None \
+        else ("%dx%d%s" % (target[0], target[1],
+                           " letterbox(pad=%d)" % pad if letterbox else " 拉伸"))
+    summary = [
+        "INT8 校准集构建摘要",
+        "  来源: %s" % os.path.abspath(src),
+        "  扫描: %d 个文件 → 解码成功 %d / 失败 %d" % (stats["scanned"], stats["decoded"],
+                                                stats["failed"]),
+        "  去重: %s(唯一 %d 张)" % ("丢重复 %d 个" % stats["dup"] if dedupe else "未去重",
+                                stats["uniq"]),
+        "  抽样: %d 张(按来源目录轮转;目录 %d 个)" % (len(rows), len(result["groups"])),
+        "  尺寸: %s;格式 %s" % (size_note, fmt),
+        "  写盘: %s(%.1f MB,平均 %.0f KB/张)" % (img_dir, total_mb,
+                                              total_mb * 1024.0 / max(1, len(rows))),
+        "  dataset.txt: %s(%d 行绝对路径)" % (dataset, len(rows)),
+        "  manifest.csv: %s" % manifest,
+        "",
+        "下一步(在装好 rknn-toolkit2 2.3.2 的机器上):",
+        "  python scripts/onnx_to_rknn.py --onnx weights/yolov8n.onnx -o /tmp/yolov8n_int8.rknn "
+        "--target rk3588 --imgsz %d --dataset %s --quantized-dtype w8a8"
+        % (target[0] if target else 640, dataset),
+        "  python scripts/verify_rknn.py --fp16 weights/demo/yolov8n.rknn --int8 /tmp/yolov8n_int8.rknn",
+    ]
+    text = "\n".join(summary) + "\n"
+    with open(os.path.abspath(os.path.join(out, "summary.txt")), "w", encoding="utf-8") as fh:
+        fh.write(text)
+    if not quiet:
+        print(text)
+    return 0
+
+
+def main(argv=None) -> int:
+    parser = argparse.ArgumentParser(
+        description="从采集帧生成 RKNN INT8 校准集(去重 + 抽样 + 归一尺寸 + dataset.txt)")
+    parser.add_argument("--src", default=os.path.join(REPO, "runs"),
+                        help="采集帧目录(递归;默认 runs)")
+    parser.add_argument("--out", default=None, help="输出目录;默认 runs/calib_<时间戳>")
+    parser.add_argument("--limit", type=int, default=200,
+                        help="最多取多少张(按目录轮转;0=全取;经验 200~500)")
+    parser.add_argument("--resize", default="", help="归一尺寸 WxH(32 的倍数,如 640x640)")
+    parser.add_argument("--letterbox", action="store_true",
+                        help="等比缩放 + 居中填充(与生产预处理一致,推荐)")
+    parser.add_argument("--pad", type=int, default=114, help="letterbox 填充灰度(默认 114)")
+    parser.add_argument("--format", dest="fmt", default="png", choices=("png", "jpg"),
+                        help="输出格式(png 纯标准库;jpg 需要 Pillow/OpenCV)")
+    parser.add_argument("--quality", type=int, default=88, help="jpg 质量(默认 88)")
+    parser.add_argument("--no-dedupe", dest="dedupe", action="store_false",
+                        help="不去重(默认按像素内容去重)")
+    parser.add_argument("--dataset-name", default="dataset.txt", help="列表文件名")
+    parser.add_argument("-q", "--quiet", action="store_true", help="不打印摘要")
+    args = parser.parse_args(argv)
+
+    if args.letterbox and not args.resize:
+        parser.error("--letterbox 需要同时给 --resize WxH")
+    out = args.out or os.path.join(REPO, "runs",
+                                   "calib_" + _dt.datetime.now().strftime("%Y%m%d_%H%M%S"))
+    return build(args.src, out, limit=args.limit, resize_to=args.resize,
+                 letterbox=args.letterbox, pad=args.pad, fmt=args.fmt, quality=args.quality,
+                 dedupe=args.dedupe, dataset_name=args.dataset_name, quiet=args.quiet)
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 42 - 11
scripts/make_docx.py

@@ -38,6 +38,31 @@ MONO = "Consolas"
 NAVY = RGBColor(0x1F, 0x3A, 0x5F)
 GREY = RGBColor(0x55, 0x55, 0x55)
 DARK = RGBColor(0x1A, 0x1A, 0x1A)
+
+REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+
+def repo_counts() -> dict:
+    """运行时数一遍仓库:``tests/`` 文件数与用例数、``scripts/`` 脚本数。
+
+    这些数字以前是手写的("20 个 unittest 文件(229 项)"),每加一个测试就得手动改 7 处,
+    漏改比写错更常见——2026-11-16 就把 299 项写成了 229 项。改成生成时现算。
+    """
+    counts = {"tests_files": 0, "tests_cases": 0, "scripts": 0}
+    tests_dir = os.path.join(REPO, "tests")
+    for name in sorted(os.listdir(tests_dir)):
+        if not (name.startswith("test_") and name.endswith(".py")):
+            continue
+        counts["tests_files"] += 1
+        with open(os.path.join(tests_dir, name), encoding="utf-8") as fh:
+            counts["tests_cases"] += sum(1 for line in fh
+                                        if line.lstrip().startswith("def test_"))
+    scripts_dir = os.path.join(REPO, "scripts")
+    counts["scripts"] = len([n for n in os.listdir(scripts_dir) if n.endswith(".py")])
+    return counts
+
+
+COUNTS = repo_counts()
 WHITE = RGBColor(0xFF, 0xFF, 0xFF)
 
 _TOK = re.compile(r"(\*\*.+?\*\*|`.+?`)")
@@ -551,16 +576,19 @@ def sec4b(doc):
         ["`cpp/`", "25 个头文件 + 28 个实现:`registers` / `crc16` / `mbap` / `modbus_server` / `snapshot` / `decision` / "
                    "`scene` / `edge_evidence` / `edge_lines` / `edge_v2` / `edge_v2_gates` / `publish_gate` / `rate_stats` / "
                    "`sha256` / `frame_dump` / `capture`(gst·images·synth)"],
-        ["`scripts/`", "`gen_cpp_constants` / `check_configs` / `dump_default_config` / `calib_record` / `evidence_drill` / "
-                       "`video_eval` + `summarize_eval` + `verify_equiv` / `replay_check` / `fuzz_app` / `modbus_torture` / "
-                       "`soak_watch` / `soak_7x24` / `regression_freeze` / `export_onnx` / `onnx_to_rknn` / `build_trt`"],
-        ["`tests/`", "20 个标准库 unittest 文件(229 项),含 mock 端到端、PLC 读写回环、负样本回归、证据演练"],
+        ["`scripts/`", "%d 个脚本:`gen_cpp_constants` / `check_configs` / `dump_default_config` / `calib_record` / "
+                       "`evidence_drill` / `video_eval` + `summarize_eval` + `verify_equiv` / `replay_check` / "
+                       "`fuzz_app` / `modbus_torture` / `soak_watch` / `soak_7x24` / `regression_freeze` / "
+                       "`export_onnx` / `onnx_to_rknn` / `make_calib_dataset` / `build_trt`" % COUNTS["scripts"]],
+        ["`tests/`", "%d 个标准库 unittest 文件(%d 项),含 mock 端到端、PLC 读写回环、负样本回归、证据演练"
+                     % (COUNTS["tests_files"], COUNTS["tests_cases"])],
         ["`configs/` / `deploy/` / `docs/`", "现场配置模板(default 由脚本生成)/ systemd 单元与 DeepStream 模板 / "
                                             "`docs/` 17 篇技术文档(全仓库 Markdown 共 23 篇)"],
     ], widths=[4.0, 12.6], size=8.5)
     para(doc, "一条命令跑完「冻结点」回归(失败即非 0 退出),换版前必跑:")
     code(doc, """python scripts/regression_freeze.py --build-dir build-cmake\\windows-zig-release
-  -> ctest 8/8 通过,Python 229 单测 OK,v1/v2 现场片段回放通过,共 8 组:8 通过 / 0 失败""")
+  -> ctest 8/8 通过,Python %d 单测 OK,v1/v2 现场片段回放通过,共 8 组:8 通过 / 0 失败"""
+         % COUNTS["tests_cases"])
 
 
 # ---SEC5---
@@ -610,7 +638,8 @@ def sec5(doc):
     h2(doc, "5.3 自检与回归(2026-11-03 全量复跑)", level=3)
     table(doc, ["项目", "命令/入口", "结果"], [
         ["C++ 自检 8 组", "`ctest --test-dir build-cmake\\windows-zig-release`", "**8/8 通过**,合计 1128 项断言"],
-        ["Python 回归", "`python -m unittest discover -s tests -t .`", "**229 项全绿**(约 3.7 s)"],
+        ["Python 回归", "`python -m unittest discover -s tests -t .`",
+         "**%d 项全绿**(约 5 s)" % COUNTS["tests_cases"]],
         ["冻结点回归", "`python scripts/regression_freeze.py --build-dir …`",
          "**8 组:8 通过 / 0 失败**(ctest + 单测 + v1/v2 回放),rc=0"],
         ["黄金语料回放", "`python scripts/replay_check.py runs/dump/dump.jsonl`", "322 项断言通过 / 0 FAIL(含像素 CRC 互检)"],
@@ -624,10 +653,10 @@ def sec5(doc):
               "它们是**不需要相机、不需要模型、不需要 PLC** 就能跑的可复现证据。")
     para(doc, "**本次附带修复(验收时实测发现)**:把交付包放进中文目录(如「正面吊」)后,"
               "`cv2.imread` 在 Windows 上把路径按 ANSI 解释、对非 ASCII 路径静默返回 `None`,"
-              "导致负样本回归读不到取证帧(229 项里 1 项失败)。已统一改走 "
+              "导致负样本回归读不到取证帧(当时 229 项里有 1 项失败)。已统一改走 "
               "`imread_any()`(`np.fromfile` + `cv2.imdecode`),在 `portcv/io/capture.py`、"
               "`scripts/replay_evidence_v2.py`、`tests/test_negative_frame_regression.py` 三处生效。"
-              "修复后在 `Desktop\\正面吊\\` 目录内复跑:**229 项全绿、rc=0**。")
+              "修复后在 `Desktop\\正面吊\\` 目录内复跑:**全绿、rc=0**(当前项数见 5.3 表格)。")
 
     h2(doc, "5.4 稳定性与鲁棒性", level=3)
     table(doc, ["测试", "规模", "结论"], [
@@ -675,9 +704,11 @@ def sec6(doc):
     table(doc, ["路径", "说明", "是否交付"], [
         ["`portcv/`", "Python 参考实现 + 工具链(算法迭代、回放、报表)", "是"],
         ["`cpp/`", "C++17 生产实现(零外部依赖核心 + Modbus 服务端 + 8 组自检)", "是"],
-        ["`scripts/`", "23 个现场/开发工具(常量生成、标定封存、证据演练、回放评估、fuzz/浸泡、冻结点)", "是"],
+        ["`scripts/`", "%d 个现场/开发工具(常量生成、标定封存、证据演练、回放评估、fuzz/浸泡、冻结点、"
+                      "ONNX→RKNN 转换与 INT8 校准集)" % COUNTS["scripts"], "是"],
         ["`configs/`、`deploy/`", "现场配置模板;systemd 单元与 DeepStream 模板", "是"],
-        ["`tests/`、`docs/`", "229 项 unittest;30 篇技术文档(路线、PLC 接口、部署、试验计划、合规评审)", "是"],
+        ["`tests/`、`docs/`", "%d 项 unittest;30 篇技术文档(路线、PLC 接口、部署、试验计划、合规评审)"
+                              % COUNTS["tests_cases"], "是"],
         ["`build/`、`build-cmake/`、`runs/`", "编译产物与运行输出(`runs/video_eval` 除外)", "**否**(gitignore 的临时目录/现场数据)"],
     ], widths=[4.2, 9.6, 2.8], size=8.5)
 
@@ -686,7 +717,7 @@ def sec6(doc):
 python -m portcv selftest                    # 合成帧 + mock 后端 + 内置 Modbus 客户端,一条命令自证
 python -m portcv registers --scl             # 打印寄存器表 + 给 PLC 工程师的 SCL 参考代码
 python -m portcv doctor --deep               # 环境自检:依赖 / 模型 / 相机 / PLC 连通性
-python -m unittest discover -s tests -t . -v # 全量回归 229 项""")
+python -m unittest discover -s tests -t . -v # 全量回归 %d 项""" % COUNTS["tests_cases"])
     para(doc, "现场(C++,只拷二进制 + 一个 JSON):")
     code(doc, """cmake -S cpp -B build -DCMAKE_BUILD_TYPE=Release && cmake --build build -j
 ctest --test-dir build --output-on-failure    # 8 组自检全绿

+ 1 - 1
scripts/regression_freeze.py

@@ -1,6 +1,6 @@
 """一套命令跑完"冻结点"回归(发版 / 交付 / 改判据之后必跑)。
 
-为什么要一个总脚本:判据链现在有四层(C++ 契约自检 8 个、Python 299 单测、
+为什么要一个总脚本:判据链现在有四层(C++ 契约自检 8 个、Python 330 单测、
 v1 `edge` 现场回放 4 份、v2 `edge-v2` 现场回放 2 份),分散在四五个命令里,
 现场/验收时**很容易漏跑一组**,而漏跑的那一组往往正是"刚刚被改动"的那一组。
 

+ 155 - 35
scripts/soak_watch.py

@@ -33,6 +33,7 @@ import csv
 import ctypes
 import datetime as _dt
 import os
+import re
 import subprocess
 import sys
 import time
@@ -153,6 +154,29 @@ class WinSampler:
         return out
 
 
+def parse_proc_status(text: str) -> dict:
+    """解析 ``/proc/<pid>/status``(抽成纯函数,好单测,也不用上板)。
+
+    * ``rss_mb`` ← ``VmRSS``(常驻)
+    * ``peak_rss_mb`` ← ``VmHWM``(峰值常驻,内核已记)
+    * ``private_mb`` ← **``RssAnon``**(匿名常驻 ≈ 私有提交);**不能用 ``VmSize``**——
+      Python 进程的虚拟地址空间动辄 1.5 GB(cv2/numpy 的映射),拿它当"私有提交"会让
+      摘要里出现"私有 1530 MB"这种一看就假、但会被人当真的数字(2026-11-16 板端踩过)
+    * ``threads`` ← ``Threads``
+    """
+    out: dict = {}
+    for line in text.splitlines():
+        if line.startswith("VmRSS:"):
+            out["rss_mb"] = float(line.split()[1]) / 1024.0
+        elif line.startswith("VmHWM:"):
+            out["peak_rss_mb"] = float(line.split()[1]) / 1024.0
+        elif line.startswith("RssAnon:"):
+            out["private_mb"] = float(line.split()[1]) / 1024.0
+        elif line.startswith("Threads:"):
+            out["threads"] = int(line.split()[1])
+    return out
+
+
 class ProcSampler:
     """Linux(现场板卡):/proc/<pid>;句柄数 = /proc/<pid>/fd 条目数。"""
 
@@ -169,15 +193,7 @@ class ProcSampler:
         out: dict = {}
         try:
             with open("/proc/%d/status" % pid, encoding="utf-8") as fh:
-                for line in fh:
-                    if line.startswith("VmRSS:"):
-                        out["rss_mb"] = float(line.split()[1]) / 1024.0
-                    elif line.startswith("VmHWM:"):
-                        out["peak_rss_mb"] = float(line.split()[1]) / 1024.0
-                    elif line.startswith("VmSize:"):
-                        out["private_mb"] = float(line.split()[1]) / 1024.0
-                    elif line.startswith("Threads:"):
-                        out["threads"] = int(line.split()[1])
+                out.update(parse_proc_status(fh.read()))
         except OSError:
             return out
         for path, key in (("/proc/%d/fd" % pid, "handles"), ("/proc/%d/task" % pid, "task_count")):
@@ -232,9 +248,30 @@ def rise_ratio(samples: list) -> float:
     return rises / float(len(minutes) - 1)
 
 
+_RE_CXX_FRAMES = re.compile(r"已发布\s+(\d+)\s*帧")
+_RE_FPS_X10 = re.compile(r"fps_x10=(\d+)")
+# Python 侧的单行摘要(portcv/service/runner.py::status_line):
+#   state=2(no_container,0.42) seq=88 fps=15.0 lat=63ms npr=97% frames=441 pub=441 chg=0 err=0
+_RE_PY_STATUS = re.compile(
+    r"\bseq=(\d+)\s+fps=([0-9.]+)\s+lat=([0-9.]+)ms\b"
+    r".*?\bframes=(\d+)\s+pub=(\d+)\s+chg=(\d+)\s+err=(\d+)")
+_RE_WARN = re.compile(r"\[warn\]|\|\s*WARNING\b")
+
+
 def read_log_progress(path: str) -> dict:
-    """抓被测进程日志里的进度:发布帧数 / 实测 fps / [warn] 行数 / 最后一行。"""
-    out = {"frames": None, "fps": None, "warn_lines": 0, "last": "", "bytes": 0}
+    """抓被测进程日志里的进度:发布帧数 / 实测 fps / [warn] 行数 / 最后一行。
+
+    同一个脚本要能同时盯 C++ 与 Python 两个版本,两种日志格式都认:
+
+    * C++ ``portcv_run``:``[stat] 已发布 50 帧,本轮 15.0 fps(滑窗 15.0 fps)…fps_x10=150``
+    * Python ``portcv run``:``16:17:55 | INFO | portcv.runner | state=… seq=88 fps=15.0
+      lat=63ms npr=97% frames=441 pub=441 chg=0 err=0``
+
+    匹配用**子串搜索**而不是 ``startswith``:经 systemd / journald / ``tee`` 转发后
+    行首会多出时间戳前缀(2026-11-16 板端实测踩过:带前缀时 ``frames`` 恒为 ``None``,
+    进度停滞判据等于失效)。``frames`` 统一取"已发布"口径(Python 取 ``pub=``)。
+    """
+    out = {"frames": None, "fps": None, "warn_lines": 0, "errors": None, "last": "", "bytes": 0}
     if not path or not os.path.exists(path):
         return out
     out["bytes"] = os.path.getsize(path)
@@ -243,21 +280,39 @@ def read_log_progress(path: str) -> dict:
             text = fh.read()
     except OSError:
         return out
+
     for line in text.splitlines():
-        if line.startswith("[stat] 已发布"):
-            head = line.split(",")[0]
-            digits = "".join(ch for ch in head if ch.isdigit())
-            if digits:
-                out["frames"] = int(digits)
+        frames = _RE_CXX_FRAMES.search(line)
+        fps = _RE_FPS_X10.search(line)
+        py = _RE_PY_STATUS.search(line)
+        if frames or fps or py:
             out["last"] = line.strip()
-        elif line.startswith("[stat]") and "fps_x10=" in line:
-            for token in line.split():
-                if token.startswith("fps_x10="):
-                    out["fps"] = int(token.split("=")[1]) / 10.0
-    out["warn_lines"] = text.count("[warn]")
+        if frames:
+            out["frames"] = int(frames.group(1))
+        if fps:                                   # C++ 退出统计里的"发布 fps_x10="
+            out["fps"] = int(fps.group(1)) / 10.0
+        if py:
+            out["fps"] = float(py.group(2))
+            out["frames"] = int(py.group(5))      # pub = 已发布到 PLC 的帧数
+            out["errors"] = int(py.group(7))
+    out["warn_lines"] = len(_RE_WARN.findall(text))
     return out
 
 
+def thread_leak(rows: list) -> str:
+    """线程泄漏判定:**只吃预热后的窗口**。
+
+    t=0 那次采样常常撞在子进程刚 exec 的瞬间(``Threads: 1``、RSS 0),拿它当"首值"会把
+    "线程从 1 长到 24 就稳定"误判成泄漏(2026-11-16 板端 30 min 浸泡就是这么假阳性的)。
+    """
+    values = [r["threads"] for r in rows if r.get("threads")]
+    if len(values) < 2:
+        return ""
+    if values[-1] > values[0] and max(values) - min(values) > 2:
+        return "线程数 %d → %d → 疑似线程泄漏" % (values[0], values[-1])
+    return ""
+
+
 def main(argv=None) -> int:
     parser = argparse.ArgumentParser(description="浸泡测试 / 资源监测(内存·句柄·线程·CPU·IO)")
     parser.add_argument("--pid", type=int, default=0,
@@ -270,12 +325,28 @@ def main(argv=None) -> int:
     parser.add_argument("--rss-slope", type=float, default=1.0, help="RSS 斜率阈值 MB/min")
     parser.add_argument("--handle-slope", type=float, default=1.0, help="句柄斜率阈值 个/min")
     parser.add_argument("--outdir", default=os.path.join(REPO, "runs"), help="输出目录")
+    parser.add_argument("--replay", default=None,
+                        help="事后重算:读入已有的 soak_*.csv,用当前判据重新出结论(不上板、不采样)")
     parser.add_argument("cmd", nargs=argparse.REMAINDER, help="`-- 被测程序 参数...`")
     args = parser.parse_args(argv)
 
     cmd = [a for a in args.cmd if a != "--"]
     os.makedirs(args.outdir, exist_ok=True)
     stamp = _dt.datetime.now().strftime("%Y%m%d_%H%M%S")
+
+    if args.replay:
+        rows = _read_soak_csv(args.replay)
+        if not rows:
+            print("CSV 里没有采样行:%s" % args.replay, file=sys.stderr)
+            return 2
+        base = os.path.splitext(args.replay)[0]
+        deltas = sorted(b["t_s"] - a["t_s"] for a, b in zip(rows, rows[1:]))
+        if deltas:                                   # 摘要里的"间隔"按 CSV 实际采样间隔算
+            args.interval = round(deltas[len(deltas) // 2], 1)
+        print("重算 %s(%d 行;预热 %.0fs 不计入趋势)" % (args.replay, len(rows), args.warmup))
+        return analyze(rows, args, [], base + ".stdout.log", args.replay,
+                       base + ".replay.txt")
+
     csv_path = os.path.join(args.outdir, "soak_%s.csv" % stamp)
     txt_path = os.path.join(args.outdir, "soak_%s.txt" % stamp)
 
@@ -325,14 +396,15 @@ def main(argv=None) -> int:
                 "io_read_mb": round(sample.get("io_read_mb", 0.0), 3),
                 "io_write_mb": round(sample.get("io_write_mb", 0.0), 3),
                 "frames": progress["frames"],
+                "fps": progress["fps"],
                 "warn_lines": progress["warn_lines"],
                 "alive": int(alive),
             }
             rows.append(row)
             print("  t=%6.1fs rss=%8.2fMB priv=%8.2fMB handles=%s threads=%s cpu=%6.1fs "
-                  "frames=%s warn=%s"
+                  "frames=%s fps=%s warn=%s"
                   % (row["t_s"], row["rss_mb"], row["private_mb"], row["handles"], row["threads"],
-                     row["cpu_s"], row["frames"], row["warn_lines"]))
+                     row["cpu_s"], row["frames"], row["fps"], row["warn_lines"]))
             sys.stdout.flush()
             if child is not None and child.poll() is not None and not alive:
                 print("被测进程已退出,rc=%s" % child.returncode)
@@ -351,6 +423,11 @@ def main(argv=None) -> int:
                 child.wait(timeout=15)
             except subprocess.TimeoutExpired:
                 child.kill()
+        if log_path:                                  # 不关会在长跑结束时留 ResourceWarning
+            try:
+                log_fh.close()
+            except Exception:                         # noqa: BLE001 - 收尾路径不抛
+                pass
 
     if not rows:
         print("没有采样数据", file=sys.stderr)
@@ -361,6 +438,40 @@ def main(argv=None) -> int:
         writer.writeheader()
         writer.writerows(rows)
 
+    return analyze(rows, args, cmd, log_path, csv_path, txt_path,
+                   child.returncode if child is not None else None)
+
+
+def _read_soak_csv(path: str) -> list:
+    """把 ``soak_*.csv`` 读回成采样行(``--replay`` 用;缺列按 None/0 兜底)。"""
+    rows: list = []
+    with open(path, newline="", encoding="utf-8") as fh:
+        for raw in csv.DictReader(fh):
+            def num(key):
+                value = raw.get(key)
+                return None if value in (None, "", "None") else float(value)
+
+            threads = num("threads")
+            handles = num("handles")
+            rows.append({
+                "t_s": float(raw.get("t_s") or 0.0),
+                "rss_mb": num("rss_mb") or 0.0,
+                "private_mb": num("private_mb") or 0.0,
+                "handles": None if handles is None else int(handles),
+                "threads": None if threads is None else int(threads),
+                "cpu_s": num("cpu_s") or 0.0,
+                "io_read_mb": num("io_read_mb") or 0.0,
+                "io_write_mb": num("io_write_mb") or 0.0,
+                "frames": None if num("frames") is None else int(num("frames")),
+                "fps": num("fps"),
+                "warn_lines": int(num("warn_lines") or 0),
+            })
+    return rows
+
+
+def analyze(rows: list, args, cmd, log_path: str, csv_path: str, txt_path: str,
+            child_rc=None) -> int:
+    """判定 + 摘要(采样循环与 ``--replay`` 共用;``child_rc`` 非 0 时数据不作数)。"""
     # ---------------- 判定 ----------------
     post = [r for r in rows if r["t_s"] >= args.warmup] or rows[len(rows) // 2:]
     rss_series = [(r["t_s"], r["rss_mb"]) for r in post]
@@ -374,8 +485,16 @@ def main(argv=None) -> int:
     handle_rise = rise_ratio(handle_series)
     thread_values = [r["threads"] for r in rows if r["threads"]]
     last = rows[-1]
+    first = post[0] if post else rows[0]      # 首值取预热后:避开 exec 瞬间的 0 MB / 1 线程
     verdict = []
     ok = True
+    # 先判"这份数据算不算数":进程异常退出 / 有效样本太少时,任何"无泄漏"结论都是假的
+    if child_rc not in (0, None):
+        verdict.append("被测进程异常退出 rc=%s → 本次数据不作数(先看它的日志)" % child_rc)
+        ok = False
+    if len(post) < 5:
+        verdict.append("预热后有效样本仅 %d 个(< 5)→ 不足以判定泄漏" % len(post))
+        ok = False
     if rss_slope > args.rss_slope:
         verdict.append("RSS 持续上升 %.2f MB/min(阈值 %.2f)→ 疑似内存泄漏"
                        % (rss_slope, args.rss_slope))
@@ -384,9 +503,9 @@ def main(argv=None) -> int:
         verdict.append("句柄净增 %.0f 个(%.2f 个/min)→ 疑似句柄/描述符泄漏"
                        % (handle_net, handle_slope))
         ok = False
-    if len(thread_values) > 1 and max(thread_values) - min(thread_values) > 2 \
-            and thread_values[-1] > thread_values[0]:
-        verdict.append("线程数 %d → %d → 疑似线程泄漏" % (thread_values[0], thread_values[-1]))
+    leaked_threads = thread_leak(post)
+    if leaked_threads:
+        verdict.append(leaked_threads)
         ok = False
     if rss_rise >= 0.9 and rss_slope > 0:
         verdict.append("预热后 %.0f%% 的分钟 RSS 都在涨 → 值得人看一眼" % (rss_rise * 100))
@@ -404,18 +523,19 @@ def main(argv=None) -> int:
         "  被测: %s" % (cmd if cmd else "pid=%d(外部进程)" % args.pid),
         "  样本: %d 个 / %.1f 分钟(间隔 %.1fs;预热 %.0fs 不计入趋势)"
         % (len(rows), (rows[-1]["t_s"] - rows[0]["t_s"]) / 60.0, args.interval, args.warmup),
-        "  RSS: 首 %.2f → 末 %.2f MB(峰 %.2f),趋势 %+.2f MB/min"
-        % (rows[0]["rss_mb"], last["rss_mb"], max(r["rss_mb"] for r in rows), rss_slope),
-        "  私有提交: 首 %.2f → 末 %.2f MB,趋势 %+.2f MB/min"
-        % (rows[0]["private_mb"], last["private_mb"], priv_slope),
-        "  句柄: 首 %s → 末 %s(净 %+.0f,趋势 %+.2f 个/min;逐分钟上升比例 %.0f%%)"
-        % (rows[0]["handles"], last["handles"], handle_net, handle_slope, handle_rise * 100),
-        "  线程: 首 %s → 末 %s(峰值 %s)"
-        % (rows[0]["threads"], last["threads"],
+        "  RSS: 预热后首 %.2f → 末 %.2f MB(峰 %.2f),趋势 %+.2f MB/min"
+        % (first["rss_mb"], last["rss_mb"], max(r["rss_mb"] for r in rows), rss_slope),
+        "  私有提交: 预热后首 %.2f → 末 %.2f MB,趋势 %+.2f MB/min"
+        % (first["private_mb"], last["private_mb"], priv_slope),
+        "  句柄: 预热后首 %s → 末 %s(净 %+.0f,趋势 %+.2f 个/min;逐分钟上升比例 %.0f%%)"
+        % (first["handles"], last["handles"], handle_net, handle_slope, handle_rise * 100),
+        "  线程: 预热后首 %s → 末 %s(全程峰值 %s)"
+        % (first["threads"], last["threads"],
            max(r["threads"] or 0 for r in rows) or None),
         "  CPU: %.1f s(累计)  IO: 读 %.2f MB / 写 %.2f MB"
         % (last["cpu_s"], last["io_read_mb"], last["io_write_mb"]),
-        "  进度: 发布帧数=%s  [warn] 行=%d" % (last["frames"], last["warn_lines"]),
+        "  进度: 发布帧数=%s  实测 fps=%s  [warn] 行=%d"
+        % (last["frames"], last["fps"], last["warn_lines"]),
         "  日志: %s" % (log_path or "(外部进程,未由本脚本拉起)"),
         "  结论: " + ";".join(verdict),
         "  明细: %s" % csv_path,

+ 199 - 0
tests/test_make_calib_dataset.py

@@ -0,0 +1,199 @@
+"""``scripts/make_calib_dataset.py`` 的单测(INT8 校准集造集,不需要 rknn-toolkit / 板卡)。
+
+守四件事:
+
+1. **PGM 解码**(P5/P6、头部注释、像素不足要报错)与 **PNG 编码**(zlib 解回去逐字节一致);
+2. **去重按像素内容**:同一帧的两个文件名只算一张(现场 ``runs/`` 就是这种一堆重复拷贝的状态);
+3. **抽样按来源目录轮转**:不能让某一批场景把 200 张全占满;
+4. **``dataset.txt`` 必须是绝对路径**(``onnx_to_rknn.py --dataset`` 在板端 cwd 不一定对),
+   且尺寸不合法(不是 32 的倍数)时要**拒绝**而不是悄悄出个错尺寸。
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+if ROOT not in sys.path:
+    sys.path.insert(0, ROOT)
+
+
+def _load(name: str = "make_calib_dataset"):
+    """按路径加载 ``scripts/<name>.py``(scripts 不是包)。"""
+
+    path = os.path.join(ROOT, "scripts", name + ".py")
+    spec = importlib.util.spec_from_file_location(name, path)
+    module = importlib.util.module_from_spec(spec)
+    assert spec.loader is not None
+    sys.modules.setdefault(name, module)
+    spec.loader.exec_module(module)
+    return module
+
+
+calib = _load()
+
+
+def write_pgm(path: str, w: int, h: int, value: int, channels: int = 1) -> str:
+    """写一张常量灰度/彩色 PGM(P5/P6),带上注释行以覆盖头部解析。"""
+    magic = b"P5" if channels == 1 else b"P6"
+    header = magic + b"\n# generated by test\n%d %d\n255\n" % (w, h)
+    with open(path, "wb") as fh:
+        fh.write(header + bytes([value]) * (w * h * channels))
+    return path
+
+
+def read_png_pixels(path: str):
+    """解我们自己写的 PNG(filter 必须全 0),返回 ``(w, h, channels, pixels)``。"""
+    with open(path, "rb") as fh:
+        data = fh.read()
+    assert data.startswith(calib.PNG_SIG), "不是 PNG"
+    pos = len(calib.PNG_SIG)
+    width = height = channels = 0
+    idat = b""
+    while pos < len(data):
+        length = struct.unpack(">I", data[pos:pos + 4])[0]
+        tag = data[pos + 4:pos + 8]
+        payload = data[pos + 8:pos + 8 + length]
+        pos += 12 + length
+        if tag == b"IHDR":
+            width, height, depth, color_type = struct.unpack(">IIBB", payload[:10])
+            assert depth == 8
+            channels = 1 if color_type == 0 else 3
+        elif tag == b"IDAT":
+            idat += payload
+    raw = zlib.decompress(idat)
+    stride = width * channels
+    out = bytearray()
+    for y in range(height):
+        base = y * (stride + 1)
+        assert raw[base] == 0, "只支持 filter=0"
+        out += raw[base + 1:base + 1 + stride]
+    return width, height, channels, bytes(out)
+class PgmTest(unittest.TestCase):
+    def test_p5(self):
+        with tempfile.TemporaryDirectory() as tmp:
+            path = write_pgm(os.path.join(tmp, "a.pgm"), 4, 3, 7)
+            w, h, ch, px = calib.read_pgm(path)
+            self.assertEqual((w, h, ch), (4, 3, 1))
+            self.assertEqual(px, bytes([7]) * 12)
+
+    def test_p6(self):
+        with tempfile.TemporaryDirectory() as tmp:
+            path = write_pgm(os.path.join(tmp, "b.pgm"), 2, 2, 9, channels=3)
+            w, h, ch, px = calib.read_pgm(path)
+            self.assertEqual((w, h, ch), (2, 2, 3))
+            self.assertEqual(len(px), 12)
+
+    def test_truncated_pixels_rejected(self):
+        with tempfile.TemporaryDirectory() as tmp:
+            path = os.path.join(tmp, "bad.pgm")
+            with open(path, "wb") as fh:
+                fh.write(b"P5\n4 4\n255\n" + bytes(5))     # 只给 5 个像素
+            with self.assertRaises(calib.ImageError):
+                calib.read_pgm(path)
+
+
+class PngTest(unittest.TestCase):
+    def test_roundtrip_rgb(self):
+        with tempfile.TemporaryDirectory() as tmp:
+            path = os.path.join(tmp, "x.png")
+            pixels = bytes((i * 7) % 256 for i in range(6 * 4 * 3))
+            calib.write_png(path, 6, 4, 3, pixels)
+            self.assertEqual(read_png_pixels(path), (6, 4, 3, pixels))
+
+    def test_roundtrip_gray(self):
+        with tempfile.TemporaryDirectory() as tmp:
+            path = os.path.join(tmp, "y.png")
+            pixels = bytes((i * 3) % 256 for i in range(5 * 5))
+            calib.write_png(path, 5, 5, 1, pixels)
+            self.assertEqual(read_png_pixels(path), (5, 5, 1, pixels))
+
+
+class DedupeAndPickTest(unittest.TestCase):
+    def test_content_dedupe(self):
+        with tempfile.TemporaryDirectory() as tmp:
+            a = os.path.join(tmp, "a"); os.makedirs(a)
+            b = os.path.join(tmp, "b"); os.makedirs(b)
+            write_pgm(os.path.join(a, "1.pgm"), 4, 4, 10)
+            write_pgm(os.path.join(b, "2.pgm"), 4, 4, 10)   # 像素相同 → 重复
+            write_pgm(os.path.join(b, "3.pgm"), 4, 4, 11)
+            result = calib.scan(tmp)
+            self.assertEqual(result["stats"]["scanned"], 3)
+            self.assertEqual(result["stats"]["dup"], 1)
+            self.assertEqual(result["stats"]["uniq"], 2)
+            self.assertEqual(sorted(result["groups"]), ["a", "b"])
+
+    def test_no_dedupe_keeps_both(self):
+        with tempfile.TemporaryDirectory() as tmp:
+            write_pgm(os.path.join(tmp, "1.pgm"), 3, 3, 42)
+            write_pgm(os.path.join(tmp, "2.pgm"), 3, 3, 42)
+            self.assertEqual(calib.scan(tmp, dedupe=False)["stats"]["uniq"], 2)
+
+    def test_pick_round_robin(self):
+        groups = {"a": [1, 2, 3], "b": [9]}
+        self.assertEqual(calib.pick(groups, 3), [1, 9, 2])
+        self.assertEqual(calib.pick(groups, 0), [1, 2, 3, 9])
+
+
+
+class BuildTest(unittest.TestCase):
+    def test_build_writes_absolute_dataset_and_manifest(self):
+        with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as out:
+            os.makedirs(os.path.join(src, "dump_a"))
+            os.makedirs(os.path.join(src, "dump_b"))
+            write_pgm(os.path.join(src, "dump_a", "f1.pgm"), 8, 8, 1)
+            write_pgm(os.path.join(src, "dump_a", "f1_copy.pgm"), 8, 8, 1)
+            write_pgm(os.path.join(src, "dump_b", "f2.pgm"), 8, 8, 2)
+            rc = calib.build(src, out, limit=2, resize_to="64x64", letterbox=True, quiet=True)
+            self.assertEqual(rc, 0)
+            with open(os.path.join(out, "dataset.txt"), encoding="utf-8") as fh:
+                lines = [ln.strip() for ln in fh if ln.strip()]
+            self.assertEqual(len(lines), 2)
+            for line in lines:
+                self.assertTrue(os.path.isabs(line), line)
+                self.assertTrue(os.path.exists(line), line)
+            # letterbox 到 64x64:manifest 里必须是归一后的尺寸
+            with open(os.path.join(out, "manifest.csv"), encoding="utf-8") as fh:
+                rows = fh.read().strip().splitlines()
+            self.assertEqual(rows[0], "sha1,src,out,width,height,bytes")
+            self.assertEqual(len(rows), 3)
+            self.assertIn(",64,64,", rows[1])
+            self.assertTrue(os.path.exists(os.path.join(out, "summary.txt")))
+            self.assertEqual(read_png_pixels(lines[0])[0:2], (64, 64))
+
+    def test_bad_resize_rejected(self):
+        with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as out:
+            write_pgm(os.path.join(src, "f.pgm"), 8, 8, 1)
+            self.assertEqual(calib.build(src, out, resize_to="100x100", quiet=True), 2)
+            self.assertEqual(calib.build(src, out, resize_to="abc", quiet=True), 2)
+
+    def test_empty_src(self):
+        with tempfile.TemporaryDirectory() as src, tempfile.TemporaryDirectory() as out:
+            self.assertEqual(calib.build(src, out, quiet=True), 2)
+
+
+class ResizeTest(unittest.TestCase):
+    def test_letterbox_keeps_aspect_and_pads(self):
+        pixels = bytes([200]) * (4 * 2)                     # 4x2 灰度
+        w, h, out = calib.resize(4, 2, 1, pixels, 8, 8, letterbox=True, pad=0)
+        self.assertEqual((w, h), (8, 8))
+        self.assertEqual(len(out), 64)
+        self.assertEqual(out[0], 0)                         # 顶部是填充
+        self.assertEqual(out[4 * 8 + 4], 200)               # 中间是内容
+
+    def test_stretch(self):
+        w, h, out = calib.resize(2, 2, 1, bytes([5, 5, 5, 5]), 4, 4)
+        self.assertEqual((w, h), (4, 4))
+        self.assertEqual(set(out), {5})
+        self.assertEqual(calib.resize(3, 3, 1, bytes(9), 3, 3)[2], bytes(9))  # 同尺寸直通
+
+
+if __name__ == "__main__":
+    unittest.main()
+

+ 218 - 0
tests/test_soak_watch.py

@@ -0,0 +1,218 @@
+"""``scripts/soak_watch.py`` 的日志解析 / 判据单测(不需要板卡、不需要 C++ 构建)。
+
+守三件事(2026-11-16 板端 30 min 浸泡实测暴露的两个真缺陷都在这里):
+
+1. **带时间戳前缀的 ``[stat]`` 行也要解析出来**:经 systemd / journald / ``tee``
+   转发后行首会多出 ``16:17:55 | INFO | portcv.runner | ``,旧实现用
+   ``line.startswith("[stat]")`` 匹配,``frames`` 恒为 ``None``,进度停滞判据等于失效;
+2. **Python 版 ``portcv run`` 的单行摘要也要认**(``seq= fps= lat= ... pub=``),
+   否则同一个脚本盯不了 Python 服务;
+3. **进程异常退出 / 样本太少时不许判"无泄漏"**:旧实现会在子进程秒退(rc≠0,
+   例如端口被占用)时输出"结论: 无明显泄漏迹象",这是最危险的一类假绿。
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import os
+import sys
+import tempfile
+import unittest
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+if ROOT not in sys.path:
+    sys.path.insert(0, ROOT)
+
+
+def _load(name: str = "soak_watch"):
+    """按路径加载 ``scripts/<name>.py``(scripts 不是包,沿用 test_check_configs 的写法)。"""
+
+    path = os.path.join(ROOT, "scripts", name + ".py")
+    spec = importlib.util.spec_from_file_location(name, path)
+    module = importlib.util.module_from_spec(spec)
+    assert spec.loader is not None
+    sys.modules.setdefault(name, module)
+    spec.loader.exec_module(module)
+    return module
+
+
+sw = _load()
+
+CXX_RAW = "[stat] 已发布 50 帧,本轮 15.0 fps(滑窗 15.0 fps),单帧 全程均 12.34 / 近 50 帧 p50 12.10 p95 15.80 p99 18.20 / 最大 18.20 ms"
+CXX_EXIT = "实测帧率: 滑窗 14.7 fps(26 个采样 / 2.0 s 窗口)  发布 fps_x10=147  LOW_FPS 下限=3.0"
+PY_STATUS = ("16:17:55 | INFO  | portcv.runner | state=2(no_container,0.42) seq=88 fps=15.0 "
+             "lat=63ms npr=97% frames=441 pub=441 chg=0 err=0")
+
+
+class ReadLogProgressTest(unittest.TestCase):
+    def _write(self, text: str) -> str:
+        fd, path = tempfile.mkstemp(suffix=".log")
+        os.close(fd)
+        with open(path, "w", encoding="utf-8") as fh:
+            fh.write(text)
+        self.addCleanup(os.unlink, path)
+        return path
+
+    def test_cxx_raw_line(self):
+        got = sw.read_log_progress(self._write(CXX_RAW + "\n"))
+        self.assertEqual(got["frames"], 50)
+        self.assertIsNone(got["fps"])          # [stat] 行只给"本轮 fps",不给 fps_x10
+        self.assertEqual(got["warn_lines"], 0)
+
+    def test_cxx_exit_fps_x10(self):
+        got = sw.read_log_progress(self._write(CXX_EXIT + "\n"))
+        self.assertEqual(got["fps"], 14.7)
+        self.assertIsNone(got["frames"])
+
+    def test_prefixed_stat_line_still_parsed(self):
+        """回归:行首带时间戳前缀时也要能抓到帧数(旧实现这里恒为 None)。"""
+
+        text = "16:17:55 | INFO  | portcv.runner | " + CXX_RAW + "\n"
+        got = sw.read_log_progress(self._write(text))
+        self.assertEqual(got["frames"], 50)
+        self.assertIn("已发布 50 帧", got["last"])
+
+    def test_python_status_line(self):
+        got = sw.read_log_progress(self._write(PY_STATUS + "\n"))
+        self.assertEqual(got["frames"], 441)   # 取 pub=(已发布)口径
+        self.assertEqual(got["fps"], 15.0)
+        self.assertEqual(got["errors"], 0)
+
+    def test_last_progress_wins(self):
+        text = "\n".join([
+            PY_STATUS,
+            PY_STATUS.replace("seq=88", "seq=900").replace("pub=441", "pub=9000"),
+        ]) + "\n"
+        got = sw.read_log_progress(self._write(text))
+        self.assertEqual(got["frames"], 9000)
+
+    def test_warn_counting_both_styles(self):
+        text = "\n".join([
+            "[warn] 实测帧率 1.50 fps < 下限 3.00 → flags.LOW_FPS=1",
+            "16:20:01 | WARNING  | portcv.io.capture | 取流失败:rtsp 超时",
+            PY_STATUS,
+        ]) + "\n"
+        self.assertEqual(sw.read_log_progress(self._write(text))["warn_lines"], 2)
+
+    def test_missing_file_is_neutral(self):
+        got = sw.read_log_progress(os.path.join(tempfile.gettempdir(), "definitely-absent-soak.log"))
+        self.assertIsNone(got["frames"])
+        self.assertIsNone(got["fps"])
+        self.assertEqual(got["bytes"], 0)
+
+
+class TrendHelpersTest(unittest.TestCase):
+    def test_slope_per_min(self):
+        # 每 10 s +1 MB → 6 MB/min
+        samples = [(float(t), float(t) / 10.0) for t in range(0, 120, 10)]
+        self.assertAlmostEqual(sw.slope_per_min(samples), 6.0, places=6)
+
+    def test_slope_needs_three_points(self):
+        self.assertEqual(sw.slope_per_min([(0.0, 1.0), (10.0, 2.0)]), 0.0)
+
+    def test_rise_ratio(self):
+        rising = [(float(t), float(t)) for t in range(0, 180, 10)]
+        flat = [(float(t), 5.0) for t in range(0, 180, 10)]
+        self.assertEqual(sw.rise_ratio(rising), 1.0)
+        self.assertEqual(sw.rise_ratio(flat), 0.0)
+
+
+class VerdictTest(unittest.TestCase):
+    def test_child_failure_is_not_green(self):
+        """回归:子进程秒退(rc≠0)时不许输出"无泄漏迹象",退出码必须是 1。"""
+
+        with tempfile.TemporaryDirectory() as tmp:
+            rc = sw.main([
+                "--interval", "0.1", "--minutes", "0.05", "--warmup", "0",
+                "--outdir", tmp,
+                "--", sys.executable, "-c",
+                "import sys, time; time.sleep(0.3); sys.exit(3)",
+            ])
+            self.assertEqual(rc, 1)
+            txt = [os.path.join(tmp, n) for n in os.listdir(tmp) if n.endswith(".txt")]
+            self.assertEqual(len(txt), 1)
+            with open(txt[0], encoding="utf-8") as fh:
+                body = fh.read()
+            self.assertIn("不作数", body)
+            self.assertNotIn("无明显泄漏迹象", body)
+
+    def test_clean_child_is_green(self):
+        """子进程正常退出(rc=0)时不该被误判为异常。"""
+
+        with tempfile.TemporaryDirectory() as tmp:
+            rc = sw.main([
+                "--interval", "0.1", "--minutes", "0.05", "--warmup", "0",
+                "--outdir", tmp,
+                "--", sys.executable, "-c", "import time; time.sleep(0.6)",
+            ])
+            self.assertEqual(rc, 0)
+
+
+class ProcStatusTest(unittest.TestCase):
+    """Linux 采样口径:``private_mb`` 必须是 RssAnon,不是 VmSize。"""
+
+    STATUS = """Name:\tpython
+VmSize:\t1526876 kB
+VmRSS:\t  146820 kB
+RssAnon:\t   95360 kB
+VmHWM:\t  147600 kB
+Threads:\t24
+"""
+
+    def test_private_is_rss_anon_not_vmsize(self):
+        got = sw.parse_proc_status(self.STATUS)
+        self.assertAlmostEqual(got["rss_mb"], 146820 / 1024.0, places=3)
+        self.assertAlmostEqual(got["private_mb"], 95360 / 1024.0, places=3)
+        self.assertAlmostEqual(got["peak_rss_mb"], 147600 / 1024.0, places=3)
+        self.assertEqual(got["threads"], 24)
+
+    def test_missing_keys_are_absent(self):
+        self.assertEqual(sw.parse_proc_status("Name:\tpython\n"), {})
+
+
+class ThreadLeakTest(unittest.TestCase):
+    def test_exec_instant_not_counted(self):
+        """回归:t=0 的 1 线程长到 24 后稳定,不该判泄漏(预热窗口内才是判定区间)。"""
+
+        warmup = [{"threads": 1}, {"threads": 24}]
+        post = [{"threads": 24}, {"threads": 24}, {"threads": 24}]
+        self.assertEqual(sw.thread_leak(post), "")
+        # 直接把含 exec 瞬间的序列喂进去会误报 —— 所以 main() 只传预热后的窗口
+        self.assertIn("疑似线程泄漏", sw.thread_leak(warmup))
+
+    def test_real_rise_is_reported(self):
+        post = [{"threads": 20}, {"threads": 21}, {"threads": 24}]
+        self.assertIn("疑似线程泄漏", sw.thread_leak(post))
+
+    def test_too_few_samples(self):
+        self.assertEqual(sw.thread_leak([]), "")
+        self.assertEqual(sw.thread_leak([{"threads": 24}]), "")
+
+
+class ReplayTest(unittest.TestCase):
+    """``--replay``:拿旧 CSV 用修好的判据重算(板端 30 min 那份就是这么救回来的)。"""
+
+    HEADER = ("t_s,wall,rss_mb,private_mb,peak_rss_mb,paged_pool_mb,nonpaged_pool_mb,"
+              "handles,threads,cpu_s,io_read_mb,io_write_mb,frames,fps,warn_lines,alive")
+
+    def test_replay_ignores_exec_instant(self):
+        with tempfile.TemporaryDirectory() as tmp:
+            path = os.path.join(tmp, "soak_x.csv")
+            lines = [self.HEADER,
+                     "0.0,16:00:00,0.0,6.8,0,0,0,4,1,0,0,0,,,0,1",          # exec 瞬间
+                     "10.0,16:00:10,146.0,95.0,147,0,0,10,24,17,0,0,,,0,1"]  # 起来之后
+            for i in range(2, 13):
+                lines.append("%d.0,16:00:%02d,146.0,95.0,147,0,0,10,24,%d,0,0,,,0,1"
+                             % (i * 10, i, i * 17))
+            with open(path, "w", encoding="utf-8") as fh:
+                fh.write("\n".join(lines) + "\n")
+            rc = sw.main(["--replay", path, "--warmup", "60"])
+            self.assertEqual(rc, 0)
+            with open(os.path.join(tmp, "soak_x.replay.txt"), encoding="utf-8") as fh:
+                body = fh.read()
+            self.assertIn("预热后首 24 → 末 24", body)
+            self.assertNotIn("疑似线程泄漏", body)
+
+
+if __name__ == "__main__":
+    unittest.main()