Coverage for performance_probe.py: 100%
129 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Opt-in, in-memory timing and teardown probes for the Lean hot path.
3V5.5.0 (Problems.md #129). Two jobs main.py could not do before:
51. Real per-call timing (#63): `TimingProbe` accumulates `perf_counter`
6 deltas in memory (no per-bar disk I/O, no logging) and `main.py` emits
7 ONE `timing-probe:` line at the end of the run. Disabled (the default)
8 every method returns immediately, so the cost is one attribute check.
92. Teardown diagnostics (#104): the chronic `PythonInitializer.Shutdown()`
10 timeout happens with `threading.enumerate()` empty, so the blocker is
11 native/.NET-side. `collect_teardown_diagnostics()` reports what a Python
12 thread listing cannot (OS thread names, GC object/freeze counts) and
13 `release_symbol_containers()` is the opt-in cleanup experiment: drop the
14 large per-symbol containers (which hold Lean `Symbol` keys) and unfreeze
15 the GC before Lean finalizes the interpreter.
17Deliberately standard-library only: main.py imports this at Lean startup,
18where heavy imports (torch, pandas) once blew the 90-second Initialize()
19isolator budget (Problems.md #16).
20"""
22from __future__ import annotations
24import gc
25import os
26import time
27from collections import defaultdict
30class TimingProbe:
31 """Accumulates call counts, wall time and process CPU time per named section.
33 CPU time (V6.1.0) separates a slow section from a busy host: a section whose wall time is far above its CPU time
34 waited for the machine (another process, memory pressure), not for its own code."""
36 def __init__(self, enabled: bool = False) -> None:
37 self.enabled = bool(enabled)
38 self._total_seconds: dict[str, float] = defaultdict(float)
39 self._cpu_seconds: dict[str, float] = defaultdict(float)
40 self._calls: dict[str, int] = defaultdict(int)
41 self._counters: dict[str, int] = defaultdict(int)
42 self._cpu_marks: dict[float, float] = {}
44 def start(self) -> float:
45 if not self.enabled:
46 return 0.0
47 started = time.perf_counter()
48 self._cpu_marks[started] = time.process_time()
49 return started
51 def stop(self, name: str, started: float) -> None:
52 if not self.enabled:
53 return
54 self._total_seconds[name] += time.perf_counter() - started
55 cpu_mark = self._cpu_marks.pop(started, None)
56 if cpu_mark is not None:
57 self._cpu_seconds[name] += time.process_time() - cpu_mark
58 self._calls[name] += 1
60 def count(self, name: str, amount: int = 1) -> None:
61 if self.enabled:
62 self._counters[name] += amount
64 def summary(self) -> dict:
65 sections = {
66 name: {
67 "calls": self._calls[name],
68 "total_ms": round(self._total_seconds[name] * 1000.0, 3),
69 "mean_ms": round(self._total_seconds[name] * 1000.0 / max(self._calls[name], 1), 4),
70 "cpu_total_ms": round(self._cpu_seconds[name] * 1000.0, 3),
71 }
72 for name in sorted(self._total_seconds)
73 }
74 return {"sections": sections, "counters": dict(sorted(self._counters.items()))}
76 def format_line(self) -> str:
77 data = self.summary()
78 parts = [
79 f"{name}=calls:{stats['calls']}/total_ms:{stats['total_ms']}/mean_ms:{stats['mean_ms']}/cpu_ms:{stats['cpu_total_ms']}"
80 for name, stats in data["sections"].items()
81 ]
82 parts.extend(f"{name}={value}" for name, value in data["counters"].items())
83 return "timing-probe: " + (" ".join(parts) if parts else "no_samples")
86def native_thread_names(proc_task_dir: str = "/proc/self/task") -> list[str]:
87 """OS-level thread names (Linux only - the Lean container). Returns []
88 anywhere else or on any error; never raises."""
89 names: list[str] = []
90 try:
91 for thread_id in sorted(os.listdir(proc_task_dir)):
92 try:
93 with open(os.path.join(proc_task_dir, thread_id, "comm"), encoding="utf-8") as handle:
94 names.append(handle.read().strip())
95 except OSError:
96 continue
97 except OSError:
98 return []
99 return names
102def collect_teardown_diagnostics() -> dict:
103 """What a Python-thread listing cannot show. All fields best-effort."""
104 diagnostics: dict = {"native_threads": native_thread_names()}
105 try:
106 diagnostics["gc_tracked_objects"] = len(gc.get_objects())
107 diagnostics["gc_frozen_objects"] = gc.get_freeze_count()
108 except Exception as error: # defensive: gc never raises today
109 diagnostics["gc_error"] = repr(error)
110 return diagnostics
113def release_symbol_containers(containers: list) -> dict:
114 """Opt-in pre-shutdown cleanup experiment (phase_v2.diagnostics.
115 teardown_cleanup). Clears each dict/list/deque/set in `containers`,
116 unfreezes the GC (main.py calls gc.freeze() after load, which pins every
117 object alive at that point out of collection) and runs a full collection.
118 Returns {"cleared": n, "collected": n, "seconds": s}. Never raises; the
119 algorithm has already finished when this runs."""
120 started = time.perf_counter()
121 cleared = 0
122 for container in containers:
123 try:
124 container.clear()
125 cleared += 1
126 except Exception:
127 continue
128 try:
129 gc.unfreeze()
130 collected = gc.collect()
131 except Exception:
132 collected = -1
133 return {"cleared": cleared, "collected": collected, "seconds": round(time.perf_counter() - started, 4)}
136def resolve_state_write_policy(raw: dict | None) -> dict:
137 """`phase_v2.diagnostics.state_write` -> {"every_n_ticks", "backtest_only_at_shutdown", "compact_json_in_backtest"}.
138 Absent = write every tick with indented JSON (the pre-V5.8.0 behaviour)."""
139 raw = raw or {}
140 try:
141 every = max(1, int(raw.get("every_n_ticks", 1)))
142 except (TypeError, ValueError):
143 every = 1
144 return {
145 "every_n_ticks": every,
146 "backtest_only_at_shutdown": bool(raw.get("backtest_only_at_shutdown", False)),
147 "compact_json_in_backtest": bool(raw.get("compact_json_in_backtest", False)),
148 }
151def should_write_runtime_state(policy: dict | None, live_mode: bool, tick_index: int) -> bool:
152 """V5.8.0: the dashboard state (6 JSON files + a CSV, ~1.1 MB) was rewritten on every tick - about 2 GB of disk
153 writes per backtest. Live/paper always write every tick (the dashboard reads them); a backtest may thin them out
154 or write only at shutdown. The initialize/shutdown writes never pass through here."""
155 if live_mode or not policy:
156 return True
157 if policy.get("backtest_only_at_shutdown"):
158 return False
159 every = int(policy.get("every_n_ticks", 1))
160 return every <= 1 or int(tick_index) % every == 0
163def state_json_indent(policy: dict | None, live_mode: bool) -> int | None:
164 """2 (human-readable) unless a backtest asked for compact JSON."""
165 if not live_mode and policy and policy.get("compact_json_in_backtest"):
166 return None
167 return 2
170def install_sigterm_witness(log) -> bool:
171 """Linux only: record WHO sends SIGTERM to this process (V5.8.0). The Codespace kills trainers with no OOM event in the
172 cgroup and no kernel line; without the sender's pid and command line the kill stays a mystery. SIGTERM is blocked in
173 the calling thread (so every thread started afterwards inherits the mask) and a daemon thread waits for it with
174 `sigwaitinfo`, logs si_pid, that process's command line and the machine's memory, then exits 143 like the default
175 action would. Call it once, first thing in `main()`. Returns False where the facility does not exist."""
176 import os
177 import signal
178 import threading
180 if not (hasattr(signal, "sigwaitinfo") and hasattr(signal, "pthread_sigmask")):
181 return False
183 def _memory_line() -> str:
184 try:
185 with open("/proc/meminfo", encoding="ascii") as handle:
186 fields = {line.split(":")[0]: line.split()[1] for line in handle if line.startswith(("MemAvailable", "MemFree"))}
187 return f"MemAvailable={int(fields['MemAvailable']) // 1024} MB MemFree={int(fields['MemFree']) // 1024} MB"
188 except (OSError, KeyError, ValueError):
189 return "meminfo unavailable"
191 def _command_of(pid: int) -> str:
192 try:
193 with open(f"/proc/{pid}/cmdline", "rb") as handle:
194 return handle.read().replace(b"\0", b" ").decode("utf-8", "replace")[:200] or "?"
195 except OSError:
196 return "?"
198 def _wait() -> None:
199 info = signal.sigwaitinfo({signal.SIGTERM})
200 sender = getattr(info, "si_pid", 0)
201 log.error("SIGTERM received from pid %s (%s), parent of sender %s; %s", sender, _command_of(sender),
202 _command_of(_parent_of(sender)), _memory_line())
203 for handler in getattr(log, "handlers", []) or []:
204 try:
205 handler.flush()
206 except Exception:
207 pass
208 os._exit(143)
210 def _parent_of(pid: int) -> int:
211 try:
212 with open(f"/proc/{pid}/stat", encoding="ascii") as handle:
213 return int(handle.read().rsplit(")", 1)[1].split()[1])
214 except (OSError, ValueError, IndexError):
215 return 0
217 signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGTERM})
218 threading.Thread(target=_wait, name="sigterm-witness", daemon=True).start()
219 return True