test_soak_watch.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. """``scripts/soak_watch.py`` 的日志解析 / 判据单测(不需要板卡、不需要 C++ 构建)。
  2. 守三件事(2026-11-16 板端 30 min 浸泡实测暴露的两个真缺陷都在这里):
  3. 1. **带时间戳前缀的 ``[stat]`` 行也要解析出来**:经 systemd / journald / ``tee``
  4. 转发后行首会多出 ``16:17:55 | INFO | portcv.runner | ``,旧实现用
  5. ``line.startswith("[stat]")`` 匹配,``frames`` 恒为 ``None``,进度停滞判据等于失效;
  6. 2. **Python 版 ``portcv run`` 的单行摘要也要认**(``seq= fps= lat= ... pub=``),
  7. 否则同一个脚本盯不了 Python 服务;
  8. 3. **进程异常退出 / 样本太少时不许判"无泄漏"**:旧实现会在子进程秒退(rc≠0,
  9. 例如端口被占用)时输出"结论: 无明显泄漏迹象",这是最危险的一类假绿。
  10. """
  11. from __future__ import annotations
  12. import importlib.util
  13. import os
  14. import sys
  15. import tempfile
  16. import unittest
  17. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  18. if ROOT not in sys.path:
  19. sys.path.insert(0, ROOT)
  20. def _load(name: str = "soak_watch"):
  21. """按路径加载 ``scripts/<name>.py``(scripts 不是包,沿用 test_check_configs 的写法)。"""
  22. path = os.path.join(ROOT, "scripts", name + ".py")
  23. spec = importlib.util.spec_from_file_location(name, path)
  24. module = importlib.util.module_from_spec(spec)
  25. assert spec.loader is not None
  26. sys.modules.setdefault(name, module)
  27. spec.loader.exec_module(module)
  28. return module
  29. sw = _load()
  30. 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"
  31. CXX_EXIT = "实测帧率: 滑窗 14.7 fps(26 个采样 / 2.0 s 窗口) 发布 fps_x10=147 LOW_FPS 下限=3.0"
  32. PY_STATUS = ("16:17:55 | INFO | portcv.runner | state=2(no_container,0.42) seq=88 fps=15.0 "
  33. "lat=63ms npr=97% frames=441 pub=441 chg=0 err=0")
  34. class ReadLogProgressTest(unittest.TestCase):
  35. def _write(self, text: str) -> str:
  36. fd, path = tempfile.mkstemp(suffix=".log")
  37. os.close(fd)
  38. with open(path, "w", encoding="utf-8") as fh:
  39. fh.write(text)
  40. self.addCleanup(os.unlink, path)
  41. return path
  42. def test_cxx_raw_line(self):
  43. got = sw.read_log_progress(self._write(CXX_RAW + "\n"))
  44. self.assertEqual(got["frames"], 50)
  45. self.assertIsNone(got["fps"]) # [stat] 行只给"本轮 fps",不给 fps_x10
  46. self.assertEqual(got["warn_lines"], 0)
  47. def test_cxx_exit_fps_x10(self):
  48. got = sw.read_log_progress(self._write(CXX_EXIT + "\n"))
  49. self.assertEqual(got["fps"], 14.7)
  50. self.assertIsNone(got["frames"])
  51. def test_prefixed_stat_line_still_parsed(self):
  52. """回归:行首带时间戳前缀时也要能抓到帧数(旧实现这里恒为 None)。"""
  53. text = "16:17:55 | INFO | portcv.runner | " + CXX_RAW + "\n"
  54. got = sw.read_log_progress(self._write(text))
  55. self.assertEqual(got["frames"], 50)
  56. self.assertIn("已发布 50 帧", got["last"])
  57. def test_python_status_line(self):
  58. got = sw.read_log_progress(self._write(PY_STATUS + "\n"))
  59. self.assertEqual(got["frames"], 441) # 取 pub=(已发布)口径
  60. self.assertEqual(got["fps"], 15.0)
  61. self.assertEqual(got["errors"], 0)
  62. def test_last_progress_wins(self):
  63. text = "\n".join([
  64. PY_STATUS,
  65. PY_STATUS.replace("seq=88", "seq=900").replace("pub=441", "pub=9000"),
  66. ]) + "\n"
  67. got = sw.read_log_progress(self._write(text))
  68. self.assertEqual(got["frames"], 9000)
  69. def test_warn_counting_both_styles(self):
  70. text = "\n".join([
  71. "[warn] 实测帧率 1.50 fps < 下限 3.00 → flags.LOW_FPS=1",
  72. "16:20:01 | WARNING | portcv.io.capture | 取流失败:rtsp 超时",
  73. PY_STATUS,
  74. ]) + "\n"
  75. self.assertEqual(sw.read_log_progress(self._write(text))["warn_lines"], 2)
  76. def test_missing_file_is_neutral(self):
  77. got = sw.read_log_progress(os.path.join(tempfile.gettempdir(), "definitely-absent-soak.log"))
  78. self.assertIsNone(got["frames"])
  79. self.assertIsNone(got["fps"])
  80. self.assertEqual(got["bytes"], 0)
  81. class TrendHelpersTest(unittest.TestCase):
  82. def test_slope_per_min(self):
  83. # 每 10 s +1 MB → 6 MB/min
  84. samples = [(float(t), float(t) / 10.0) for t in range(0, 120, 10)]
  85. self.assertAlmostEqual(sw.slope_per_min(samples), 6.0, places=6)
  86. def test_slope_needs_three_points(self):
  87. self.assertEqual(sw.slope_per_min([(0.0, 1.0), (10.0, 2.0)]), 0.0)
  88. def test_rise_ratio(self):
  89. rising = [(float(t), float(t)) for t in range(0, 180, 10)]
  90. flat = [(float(t), 5.0) for t in range(0, 180, 10)]
  91. self.assertEqual(sw.rise_ratio(rising), 1.0)
  92. self.assertEqual(sw.rise_ratio(flat), 0.0)
  93. class VerdictTest(unittest.TestCase):
  94. def test_child_failure_is_not_green(self):
  95. """回归:子进程秒退(rc≠0)时不许输出"无泄漏迹象",退出码必须是 1。"""
  96. with tempfile.TemporaryDirectory() as tmp:
  97. rc = sw.main([
  98. "--interval", "0.1", "--minutes", "0.05", "--warmup", "0",
  99. "--outdir", tmp,
  100. "--", sys.executable, "-c",
  101. "import sys, time; time.sleep(0.3); sys.exit(3)",
  102. ])
  103. self.assertEqual(rc, 1)
  104. txt = [os.path.join(tmp, n) for n in os.listdir(tmp) if n.endswith(".txt")]
  105. self.assertEqual(len(txt), 1)
  106. with open(txt[0], encoding="utf-8") as fh:
  107. body = fh.read()
  108. self.assertIn("不作数", body)
  109. self.assertNotIn("无明显泄漏迹象", body)
  110. def test_clean_child_is_green(self):
  111. """子进程正常退出(rc=0)时不该被误判为异常。"""
  112. with tempfile.TemporaryDirectory() as tmp:
  113. rc = sw.main([
  114. "--interval", "0.1", "--minutes", "0.05", "--warmup", "0",
  115. "--outdir", tmp,
  116. "--", sys.executable, "-c", "import time; time.sleep(0.6)",
  117. ])
  118. self.assertEqual(rc, 0)
  119. class ProcStatusTest(unittest.TestCase):
  120. """Linux 采样口径:``private_mb`` 必须是 RssAnon,不是 VmSize。"""
  121. STATUS = """Name:\tpython
  122. VmSize:\t1526876 kB
  123. VmRSS:\t 146820 kB
  124. RssAnon:\t 95360 kB
  125. VmHWM:\t 147600 kB
  126. Threads:\t24
  127. """
  128. def test_private_is_rss_anon_not_vmsize(self):
  129. got = sw.parse_proc_status(self.STATUS)
  130. self.assertAlmostEqual(got["rss_mb"], 146820 / 1024.0, places=3)
  131. self.assertAlmostEqual(got["private_mb"], 95360 / 1024.0, places=3)
  132. self.assertAlmostEqual(got["peak_rss_mb"], 147600 / 1024.0, places=3)
  133. self.assertEqual(got["threads"], 24)
  134. def test_missing_keys_are_absent(self):
  135. self.assertEqual(sw.parse_proc_status("Name:\tpython\n"), {})
  136. class ThreadLeakTest(unittest.TestCase):
  137. def test_exec_instant_not_counted(self):
  138. """回归:t=0 的 1 线程长到 24 后稳定,不该判泄漏(预热窗口内才是判定区间)。"""
  139. warmup = [{"threads": 1}, {"threads": 24}]
  140. post = [{"threads": 24}, {"threads": 24}, {"threads": 24}]
  141. self.assertEqual(sw.thread_leak(post), "")
  142. # 直接把含 exec 瞬间的序列喂进去会误报 —— 所以 main() 只传预热后的窗口
  143. self.assertIn("疑似线程泄漏", sw.thread_leak(warmup))
  144. def test_real_rise_is_reported(self):
  145. post = [{"threads": 20}, {"threads": 21}, {"threads": 24}]
  146. self.assertIn("疑似线程泄漏", sw.thread_leak(post))
  147. def test_too_few_samples(self):
  148. self.assertEqual(sw.thread_leak([]), "")
  149. self.assertEqual(sw.thread_leak([{"threads": 24}]), "")
  150. class ReplayTest(unittest.TestCase):
  151. """``--replay``:拿旧 CSV 用修好的判据重算(板端 30 min 那份就是这么救回来的)。"""
  152. HEADER = ("t_s,wall,rss_mb,private_mb,peak_rss_mb,paged_pool_mb,nonpaged_pool_mb,"
  153. "handles,threads,cpu_s,io_read_mb,io_write_mb,frames,fps,warn_lines,alive")
  154. def test_replay_ignores_exec_instant(self):
  155. with tempfile.TemporaryDirectory() as tmp:
  156. path = os.path.join(tmp, "soak_x.csv")
  157. lines = [self.HEADER,
  158. "0.0,16:00:00,0.0,6.8,0,0,0,4,1,0,0,0,,,0,1", # exec 瞬间
  159. "10.0,16:00:10,146.0,95.0,147,0,0,10,24,17,0,0,,,0,1"] # 起来之后
  160. for i in range(2, 13):
  161. lines.append("%d.0,16:00:%02d,146.0,95.0,147,0,0,10,24,%d,0,0,,,0,1"
  162. % (i * 10, i, i * 17))
  163. with open(path, "w", encoding="utf-8") as fh:
  164. fh.write("\n".join(lines) + "\n")
  165. rc = sw.main(["--replay", path, "--warmup", "60"])
  166. self.assertEqual(rc, 0)
  167. with open(os.path.join(tmp, "soak_x.replay.txt"), encoding="utf-8") as fh:
  168. body = fh.read()
  169. self.assertIn("预热后首 24 → 末 24", body)
  170. self.assertNotIn("疑似线程泄漏", body)
  171. if __name__ == "__main__":
  172. unittest.main()