Skip to content

Commit 098e256

Browse files
authored
bpo-36670: Enhance regrtest (GH-16556)
* Add log() method: add timestamp and load average prefixes to main messages. * WindowsLoadTracker: * LOAD_FACTOR_1 is now computed using SAMPLING_INTERVAL * Initialize the load to the arithmetic mean of the first 5 values of the Processor Queue Length value (so over 5 seconds), rather than 0.0. * Handle BrokenPipeError and when typeperf exit. * format_duration(1.5) now returns '1.5 sec', rather than '1 sec 500 ms'
1 parent c65119d commit 098e256

File tree

5 files changed

+97
-56
lines changed

5 files changed

+97
-56
lines changed

Lib/test/libregrtest/main.py

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -139,16 +139,8 @@ def accumulate_result(self, result, rerun=False):
139139
print(xml_data, file=sys.__stderr__)
140140
raise
141141

142-
def display_progress(self, test_index, text):
143-
if self.ns.quiet:
144-
return
145-
146-
# "[ 51/405/1] test_tcl passed"
147-
line = f"{test_index:{self.test_count_width}}{self.test_count}"
148-
fails = len(self.bad) + len(self.environment_changed)
149-
if fails and not self.ns.pgo:
150-
line = f"{line}/{fails}"
151-
line = f"[{line}] {text}"
142+
def log(self, line=''):
143+
empty = not line
152144

153145
# add the system load prefix: "load avg: 1.80 "
154146
load_avg = self.getloadavg()
@@ -159,8 +151,23 @@ def display_progress(self, test_index, text):
159151
test_time = time.monotonic() - self.start_time
160152
test_time = datetime.timedelta(seconds=int(test_time))
161153
line = f"{test_time} {line}"
154+
155+
if empty:
156+
line = line[:-1]
157+
162158
print(line, flush=True)
163159

160+
def display_progress(self, test_index, text):
161+
if self.ns.quiet:
162+
return
163+
164+
# "[ 51/405/1] test_tcl passed"
165+
line = f"{test_index:{self.test_count_width}}{self.test_count}"
166+
fails = len(self.bad) + len(self.environment_changed)
167+
if fails and not self.ns.pgo:
168+
line = f"{line}/{fails}"
169+
self.log(f"[{line}] {text}")
170+
164171
def parse_args(self, kwargs):
165172
ns = _parse_args(sys.argv[1:], **kwargs)
166173

@@ -302,11 +309,11 @@ def rerun_failed_tests(self):
302309

303310
self.first_result = self.get_tests_result()
304311

305-
print()
306-
print("Re-running failed tests in verbose mode")
312+
self.log()
313+
self.log("Re-running failed tests in verbose mode")
307314
self.rerun = self.bad[:]
308315
for test_name in self.rerun:
309-
print(f"Re-running {test_name} in verbose mode", flush=True)
316+
self.log(f"Re-running {test_name} in verbose mode")
310317
self.ns.verbose = True
311318
result = runtest(self.ns, test_name)
312319

@@ -387,7 +394,7 @@ def run_tests_sequential(self):
387394

388395
save_modules = sys.modules.keys()
389396

390-
print("Run tests sequentially")
397+
self.log("Run tests sequentially")
391398

392399
previous_test = None
393400
for test_index, test_name in enumerate(self.tests, 1):

Lib/test/libregrtest/runtest_mp.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -104,13 +104,14 @@ class ExitThread(Exception):
104104

105105

106106
class TestWorkerProcess(threading.Thread):
107-
def __init__(self, worker_id, pending, output, ns, timeout):
107+
def __init__(self, worker_id, runner):
108108
super().__init__()
109109
self.worker_id = worker_id
110-
self.pending = pending
111-
self.output = output
112-
self.ns = ns
113-
self.timeout = timeout
110+
self.pending = runner.pending
111+
self.output = runner.output
112+
self.ns = runner.ns
113+
self.timeout = runner.worker_timeout
114+
self.regrtest = runner.regrtest
114115
self.current_test_name = None
115116
self.start_time = None
116117
self._popen = None
@@ -294,7 +295,8 @@ def wait_stopped(self, start_time):
294295
if not self.is_alive():
295296
break
296297
dt = time.monotonic() - start_time
297-
print(f"Waiting for {self} thread for {format_duration(dt)}", flush=True)
298+
self.regrtest.log(f"Waiting for {self} thread "
299+
f"for {format_duration(dt)}")
298300
if dt > JOIN_TIMEOUT:
299301
print_warning(f"Failed to join {self} in {format_duration(dt)}")
300302
break
@@ -316,6 +318,7 @@ def get_running(workers):
316318
class MultiprocessTestRunner:
317319
def __init__(self, regrtest):
318320
self.regrtest = regrtest
321+
self.log = self.regrtest.log
319322
self.ns = regrtest.ns
320323
self.output = queue.Queue()
321324
self.pending = MultiprocessIterator(self.regrtest.tests)
@@ -326,11 +329,10 @@ def __init__(self, regrtest):
326329
self.workers = None
327330

328331
def start_workers(self):
329-
self.workers = [TestWorkerProcess(index, self.pending, self.output,
330-
self.ns, self.worker_timeout)
332+
self.workers = [TestWorkerProcess(index, self)
331333
for index in range(1, self.ns.use_mp + 1)]
332-
print("Run tests in parallel using %s child processes"
333-
% len(self.workers))
334+
self.log("Run tests in parallel using %s child processes"
335+
% len(self.workers))
334336
for worker in self.workers:
335337
worker.start()
336338

@@ -364,7 +366,7 @@ def _get_result(self):
364366
# display progress
365367
running = get_running(self.workers)
366368
if running and not self.ns.pgo:
367-
print('running: %s' % ', '.join(running), flush=True)
369+
self.log('running: %s' % ', '.join(running))
368370

369371
def display_result(self, mp_result):
370372
result = mp_result.result
@@ -384,8 +386,7 @@ def _process_result(self, item):
384386
if item[0]:
385387
# Thread got an exception
386388
format_exc = item[1]
387-
print(f"regrtest worker thread failed: {format_exc}",
388-
file=sys.stderr, flush=True)
389+
print_warning(f"regrtest worker thread failed: {format_exc}")
389390
return True
390391

391392
self.test_index += 1

Lib/test/libregrtest/utils.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,14 @@ def format_duration(seconds):
1717
if minutes:
1818
parts.append('%s min' % minutes)
1919
if seconds:
20-
parts.append('%s sec' % seconds)
21-
if ms:
22-
parts.append('%s ms' % ms)
20+
if parts:
21+
# 2 min 1 sec
22+
parts.append('%s sec' % seconds)
23+
else:
24+
# 1.0 sec
25+
parts.append('%.1f sec' % (seconds + ms / 1000))
2326
if not parts:
24-
return '0 ms'
27+
return '%s ms' % ms
2528

2629
parts = parts[:2]
2730
return ' '.join(parts)

Lib/test/libregrtest/win_utils.py

Lines changed: 47 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import _winapi
2+
import math
23
import msvcrt
34
import os
45
import subprocess
@@ -10,11 +11,14 @@
1011

1112
# Max size of asynchronous reads
1213
BUFSIZE = 8192
13-
# Exponential damping factor (see below)
14-
LOAD_FACTOR_1 = 0.9200444146293232478931553241
15-
1614
# Seconds per measurement
1715
SAMPLING_INTERVAL = 1
16+
# Exponential damping factor to compute exponentially weighted moving average
17+
# on 1 minute (60 seconds)
18+
LOAD_FACTOR_1 = 1 / math.exp(SAMPLING_INTERVAL / 60)
19+
# Initialize the load using the arithmetic mean of the first NVALUE values
20+
# of the Processor Queue Length
21+
NVALUE = 5
1822
# Windows registry subkey of HKEY_LOCAL_MACHINE where the counter names
1923
# of typeperf are registered
2024
COUNTER_REGISTRY_KEY = (r"SOFTWARE\Microsoft\Windows NT\CurrentVersion"
@@ -30,10 +34,10 @@ class WindowsLoadTracker():
3034
"""
3135

3236
def __init__(self):
33-
self.load = 0.0
34-
self.counter_name = ''
37+
self._values = []
38+
self._load = None
3539
self._buffer = ''
36-
self.popen = None
40+
self._popen = None
3741
self.start()
3842

3943
def start(self):
@@ -65,7 +69,7 @@ def start(self):
6569
# Spawn off the load monitor
6670
counter_name = self._get_counter_name()
6771
command = ['typeperf', counter_name, '-si', str(SAMPLING_INTERVAL)]
68-
self.popen = subprocess.Popen(' '.join(command), stdout=command_stdout, cwd=support.SAVEDCWD)
72+
self._popen = subprocess.Popen(' '.join(command), stdout=command_stdout, cwd=support.SAVEDCWD)
6973

7074
# Close our copy of the write end of the pipe
7175
os.close(command_stdout)
@@ -85,12 +89,16 @@ def _get_counter_name(self):
8589
process_queue_length = counters_dict['44']
8690
return f'"\\{system}\\{process_queue_length}"'
8791

88-
def close(self):
89-
if self.popen is None:
92+
def close(self, kill=True):
93+
if self._popen is None:
9094
return
91-
self.popen.kill()
92-
self.popen.wait()
93-
self.popen = None
95+
96+
self._load = None
97+
98+
if kill:
99+
self._popen.kill()
100+
self._popen.wait()
101+
self._popen = None
94102

95103
def __del__(self):
96104
self.close()
@@ -109,7 +117,7 @@ def _parse_line(self, line):
109117
value = value[1:-1]
110118
return float(value)
111119

112-
def read_lines(self):
120+
def _read_lines(self):
113121
overlapped, _ = _winapi.ReadFile(self.pipe, BUFSIZE, True)
114122
bytes_read, res = overlapped.GetOverlappedResult(False)
115123
if res != 0:
@@ -135,7 +143,21 @@ def read_lines(self):
135143
return lines
136144

137145
def getloadavg(self):
138-
for line in self.read_lines():
146+
if self._popen is None:
147+
return None
148+
149+
returncode = self._popen.poll()
150+
if returncode is not None:
151+
self.close(kill=False)
152+
return None
153+
154+
try:
155+
lines = self._read_lines()
156+
except BrokenPipeError:
157+
self.close()
158+
return None
159+
160+
for line in lines:
139161
line = line.rstrip()
140162

141163
# Ignore the initial header:
@@ -148,15 +170,21 @@ def getloadavg(self):
148170
continue
149171

150172
try:
151-
load = self._parse_line(line)
173+
processor_queue_length = self._parse_line(line)
152174
except ValueError:
153175
print_warning("Failed to parse typeperf output: %a" % line)
154176
continue
155177

156178
# We use an exponentially weighted moving average, imitating the
157179
# load calculation on Unix systems.
158180
# https://en.wikipedia.org/wiki/Load_(computing)#Unix-style_load_calculation
159-
new_load = self.load * LOAD_FACTOR_1 + load * (1.0 - LOAD_FACTOR_1)
160-
self.load = new_load
161-
162-
return self.load
181+
# https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
182+
if self._load is not None:
183+
self._load = (self._load * LOAD_FACTOR_1
184+
+ processor_queue_length * (1.0 - LOAD_FACTOR_1))
185+
elif len(self._values) < NVALUE:
186+
self._values.append(processor_queue_length)
187+
else:
188+
self._load = sum(self._values) / len(self._values)
189+
190+
return self._load

Lib/test/test_regrtest.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
Py_DEBUG = hasattr(sys, 'gettotalrefcount')
2626
ROOT_DIR = os.path.join(os.path.dirname(__file__), '..', '..')
2727
ROOT_DIR = os.path.abspath(os.path.normpath(ROOT_DIR))
28+
LOG_PREFIX = r'[0-9]+:[0-9]+:[0-9]+ (?:load avg: [0-9]+\.[0-9]{2} )?'
2829

2930
TEST_INTERRUPTED = textwrap.dedent("""
3031
from signal import SIGINT, raise_signal
@@ -388,8 +389,8 @@ def check_line(self, output, regex):
388389
self.assertRegex(output, regex)
389390

390391
def parse_executed_tests(self, output):
391-
regex = (r'^[0-9]+:[0-9]+:[0-9]+ (?:load avg: [0-9]+\.[0-9]{2} )?\[ *[0-9]+(?:/ *[0-9]+)*\] (%s)'
392-
% self.TESTNAME_REGEX)
392+
regex = (r'^%s\[ *[0-9]+(?:/ *[0-9]+)*\] (%s)'
393+
% (LOG_PREFIX, self.TESTNAME_REGEX))
393394
parser = re.finditer(regex, output, re.MULTILINE)
394395
return list(match.group(1) for match in parser)
395396

@@ -449,9 +450,10 @@ def list_regex(line_format, tests):
449450
if rerun:
450451
regex = list_regex('%s re-run test%s', rerun)
451452
self.check_line(output, regex)
452-
self.check_line(output, "Re-running failed tests in verbose mode")
453+
regex = LOG_PREFIX + r"Re-running failed tests in verbose mode"
454+
self.check_line(output, regex)
453455
for test_name in rerun:
454-
regex = f"Re-running {test_name} in verbose mode"
456+
regex = LOG_PREFIX + f"Re-running {test_name} in verbose mode"
455457
self.check_line(output, regex)
456458

457459
if no_test_ran:
@@ -1232,9 +1234,9 @@ def test_format_duration(self):
12321234
self.assertEqual(utils.format_duration(10e-3),
12331235
'10 ms')
12341236
self.assertEqual(utils.format_duration(1.5),
1235-
'1 sec 500 ms')
1237+
'1.5 sec')
12361238
self.assertEqual(utils.format_duration(1),
1237-
'1 sec')
1239+
'1.0 sec')
12381240
self.assertEqual(utils.format_duration(2 * 60),
12391241
'2 min')
12401242
self.assertEqual(utils.format_duration(2 * 60 + 1),

0 commit comments

Comments
 (0)