Debian Codegraph @

src/con_duct/_utils.py

raw symbols SCIP
1 """Utility functions for con-duct."""
2
3 from typing import Any
4
5
6 def assert_num(*values: Any) -> None:
7 for value in values:
8 assert isinstance(value, (float, int))
9
10
11 # TODO: consider asking ps for `etimes` (seconds) directly via
12 # `-o etimes` instead of parsing `etime`. Even if we switch, this
13 # parser is worth keeping for backwards compatibility with existing
14 # usage.jsonl logs that persist `etime` as a string.
15 def etime_to_etimes(etime: str) -> float:
16 """Parse a ps ``etime`` string into seconds.
17
18 ps's ``etime`` format is ``[[DD-]HH:]MM:SS``: ``MM:SS`` always,
19 with ``HH:`` prepended after one hour and ``DD-`` prepended after
20 one day.
21
22 :param etime: elapsed-time string from ``ps -o etime``.
23 :returns: elapsed time in seconds.
24 :raises ValueError: if ``etime`` does not match the expected shape.
25 """
26 if "-" in etime:
27 days_str, rest = etime.split("-", 1)
28 days = int(days_str)
29 else:
30 days = 0
31 rest = etime
32 parts = rest.split(":")
33 if len(parts) == 2:
34 hours, minutes, seconds = 0, int(parts[0]), int(parts[1])
35 elif len(parts) == 3:
36 hours, minutes, seconds = int(parts[0]), int(parts[1]), int(parts[2])
37 else:
38 raise ValueError(f"Unparsable etime: {etime!r}")
39 return float(days * 86400 + hours * 3600 + minutes * 60 + seconds)
40
41
42 def is_same_pid(
43 prev_etimes: float,
44 curr_etimes: float,
45 wall_delta: float,
46 *,
47 tolerance: float = 2.0,
48 ) -> bool:
49 """Decide whether two consecutive observations of the same pid number
50 correspond to the same physical process (vs kernel pid reuse).
51
52 A continuously-existing pid's ``etime`` grows by exactly the
53 wall-clock time between two samples (etime is wall-since-fork,
54 not cputime). ps reports ``etime`` at integer-second resolution,
55 so the only slack is rounding plus small clock drift.
56
57 A stricter ``etime_2 < etime_1`` check would miss reuses where
58 the new pid's etime crept above the old pid's last reading by
59 less than the sample interval. Comparing ``Δetime`` against
60 ``Δwall`` catches those too.
61
62 :param prev_etimes: elapsed seconds at the earlier sample.
63 :param curr_etimes: elapsed seconds at the later sample.
64 :param wall_delta: wall-clock seconds between the two samples.
65 :param tolerance: slack (seconds) absorbed by ps's integer-second
66 ``etime`` plus clock drift. 2 seconds is plenty in practice.
67 :returns: ``True`` iff ``Δetime`` is close enough to ``Δwall``
68 to be the same continuous process.
69 """
70 return curr_etimes - prev_etimes >= wall_delta - tolerance
71
72
73 def pdcpu_from_pcpu(
74 prev_pcpu: float,
75 prev_etimes: float,
76 curr_pcpu: float,
77 curr_etimes: float,
78 ) -> float | None:
79 """Delta-corrected %CPU between two ps samples of the same pid.
80
81 Inverts the procps identity ``pcpu = cputime / etime * 100`` to
82 recover cputime at each sample, takes the cputime delta, and
83 divides by the elapsed interval. The ``/100`` and ``*100``
84 cancel, so the result is in the same units as ``pcpu``.
85
86 Linux-only: assumes ``pcpu`` is the cumulative ``cputime/etime``
87 ratio. Invalid on Darwin (decayed EWMA).
88
89 Identity is the caller's responsibility: invoke ``is_same_pid``
90 first. If the inputs satisfy that precondition, ``Δetime`` is
91 positive and the math is well-defined.
92
93 :param prev_pcpu: %CPU from the earlier sample.
94 :param prev_etimes: elapsed seconds at the earlier sample.
95 :param curr_pcpu: %CPU from the later sample.
96 :param curr_etimes: elapsed seconds at the later sample.
97 :returns: delta-corrected %CPU over the interval, or ``None``
98 in two "no measurement" cases:
99
100 - ``Δetime <= 0`` -- defensive guard for callers that
101 skipped ``is_same_pid``; covers sub-quantum and obvious
102 pid-reuse.
103 - Computed ``pdcpu < 0`` -- aggregation-timing artifact.
104 When duct's per-pid ``pcpu`` is max-across-samples while
105 ``etime`` is from the last sample, a spike-then-idle
106 pattern earlier in the run inflates ``prev_pcpu *
107 prev_etimes`` enough that the cputime "delta" goes
108 negative. The pid is the same; the math is just noisy.
109 A small minus dip is honestly null, not zero.
110 """
111 interval = curr_etimes - prev_etimes
112 if interval <= 0:
113 return None
114 pdcpu = (curr_pcpu * curr_etimes - prev_pcpu * prev_etimes) / interval
115 if pdcpu < 0:
116 return None
117 return pdcpu
118
119
120 def parse_version(version_str: str) -> tuple[int, int, int]:
121 x_y_z = version_str.split(".")
122 if len(x_y_z) != 3:
123 raise ValueError(
124 f"Invalid version format: {version_str}. Expected 'x.y.z' format."
125 )
126
127 x, y, z = map(int, x_y_z) # Unpacking forces exactly 3 elements
128 return (x, y, z)