Skip to content

Commit 477ef90

Browse files
vstinnerencukou
andauthored
[3.12] gh-83434: Sync libregrtest and test_regrtest with the main branch (#117250)
* gh-115122: Add --bisect option to regrtest (#115123) * test.bisect_cmd now exit with code 0 on success, and code 1 on failure. Before, it was the opposite. * test.bisect_cmd now runs the test worker process with -X faulthandler. * regrtest RunTests: Add create_python_cmd() and bisect_cmd() methods. (cherry picked from commit 1e5719a) * gh-115720: Show number of leaks in huntrleaks progress reports (GH-115726) Instead of showing a dot for each iteration, show: - '.' for zero (on negative) leaks - number of leaks for 1-9 - 'X' if there are more leaks This allows more rapid iteration: when bisecting, I don't need to wait for the final report to see if the test still leaks. Also, show the full result if there are any non-zero entries. This shows negative entries, for the unfortunate cases where a reference is created and cleaned up in different runs. Test *failure* is still determined by the existing heuristic. (cherry picked from commit af5f9d6) * gh-83434: Disable XML in regrtest when -R option is used (#117232) (cherry picked from commit d52bdfb) --------- Co-authored-by: Petr Viktorin <[email protected]>
1 parent 1c72265 commit 477ef90

11 files changed

+249
-43
lines changed

Lib/test/bisect_cmd.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ def python_cmd():
5151
cmd = [sys.executable]
5252
cmd.extend(subprocess._args_from_interpreter_flags())
5353
cmd.extend(subprocess._optim_args_from_interpreter_flags())
54+
cmd.extend(('-X', 'faulthandler'))
5455
return cmd
5556

5657

@@ -77,9 +78,13 @@ def run_tests(args, tests, huntrleaks=None):
7778
write_tests(tmp, tests)
7879

7980
cmd = python_cmd()
80-
cmd.extend(['-m', 'test', '--matchfile', tmp])
81+
cmd.extend(['-u', '-m', 'test', '--matchfile', tmp])
8182
cmd.extend(args.test_args)
8283
print("+ %s" % format_shell_args(cmd))
84+
85+
sys.stdout.flush()
86+
sys.stderr.flush()
87+
8388
proc = subprocess.run(cmd)
8489
return proc.returncode
8590
finally:
@@ -137,8 +142,8 @@ def main():
137142
ntest = max(ntest // 2, 1)
138143
subtests = random.sample(tests, ntest)
139144

140-
print("[+] Iteration %s: run %s tests/%s"
141-
% (iteration, len(subtests), len(tests)))
145+
print(f"[+] Iteration {iteration}/{args.max_iter}: "
146+
f"run {len(subtests)} tests/{len(tests)}")
142147
print()
143148

144149
exitcode = run_tests(args, subtests)
@@ -170,10 +175,10 @@ def main():
170175
if len(tests) <= args.max_tests:
171176
print("Bisection completed in %s iterations and %s"
172177
% (iteration, datetime.timedelta(seconds=dt)))
173-
sys.exit(1)
174178
else:
175179
print("Bisection failed after %s iterations and %s"
176180
% (iteration, datetime.timedelta(seconds=dt)))
181+
sys.exit(1)
177182

178183

179184
if __name__ == "__main__":

Lib/test/libregrtest/cmdline.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ def __init__(self, **kwargs) -> None:
173173
self.fail_rerun = False
174174
self.tempdir = None
175175
self._add_python_opts = True
176+
self.xmlpath = None
176177

177178
super().__init__(**kwargs)
178179

@@ -350,6 +351,8 @@ def _create_parser():
350351
help='override the working directory for the test run')
351352
group.add_argument('--cleanup', action='store_true',
352353
help='remove old test_python_* directories')
354+
group.add_argument('--bisect', action='store_true',
355+
help='if some tests fail, run test.bisect_cmd on them')
353356
group.add_argument('--dont-add-python-opts', dest='_add_python_opts',
354357
action='store_false',
355358
help="internal option, don't use it")
@@ -497,17 +500,28 @@ def _parse_args(args, **kwargs):
497500
ns.randomize = True
498501
if ns.verbose:
499502
ns.header = True
503+
500504
# When -jN option is used, a worker process does not use --verbose3
501505
# and so -R 3:3 -jN --verbose3 just works as expected: there is no false
502506
# alarm about memory leak.
503507
if ns.huntrleaks and ns.verbose3 and ns.use_mp is None:
504-
ns.verbose3 = False
505508
# run_single_test() replaces sys.stdout with io.StringIO if verbose3
506509
# is true. In this case, huntrleaks sees an write into StringIO as
507510
# a memory leak, whereas it is not (gh-71290).
511+
ns.verbose3 = False
508512
print("WARNING: Disable --verbose3 because it's incompatible with "
509513
"--huntrleaks without -jN option",
510514
file=sys.stderr)
515+
516+
if ns.huntrleaks and ns.xmlpath:
517+
# The XML data is written into a file outside runtest_refleak(), so
518+
# it looks like a leak but it's not. Simply disable XML output when
519+
# hunting for reference leaks (gh-83434).
520+
ns.xmlpath = None
521+
print("WARNING: Disable --junit-xml because it's incompatible "
522+
"with --huntrleaks",
523+
file=sys.stderr)
524+
511525
if ns.forever:
512526
# --forever implies --failfast
513527
ns.failfast = True

Lib/test/libregrtest/main.py

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@
66
import sysconfig
77
import time
88

9-
from test import support
10-
from test.support import os_helper, MS_WINDOWS
9+
from test.support import os_helper, MS_WINDOWS, flush_std_streams
1110

1211
from .cmdline import _parse_args, Namespace
1312
from .findtests import findtests, split_test_packages, list_cases
@@ -74,6 +73,7 @@ def __init__(self, ns: Namespace, _add_python_opts: bool = False):
7473
self.want_cleanup: bool = ns.cleanup
7574
self.want_rerun: bool = ns.rerun
7675
self.want_run_leaks: bool = ns.runleaks
76+
self.want_bisect: bool = ns.bisect
7777

7878
self.ci_mode: bool = (ns.fast_ci or ns.slow_ci)
7979
self.want_add_python_opts: bool = (_add_python_opts
@@ -277,6 +277,55 @@ def rerun_failed_tests(self, runtests: RunTests):
277277

278278
self.display_result(rerun_runtests)
279279

280+
def _run_bisect(self, runtests: RunTests, test: str, progress: str) -> bool:
281+
print()
282+
title = f"Bisect {test}"
283+
if progress:
284+
title = f"{title} ({progress})"
285+
print(title)
286+
print("#" * len(title))
287+
print()
288+
289+
cmd = runtests.create_python_cmd()
290+
cmd.extend([
291+
"-u", "-m", "test.bisect_cmd",
292+
# Limit to 25 iterations (instead of 100) to not abuse CI resources
293+
"--max-iter", "25",
294+
"-v",
295+
# runtests.match_tests is not used (yet) for bisect_cmd -i arg
296+
])
297+
cmd.extend(runtests.bisect_cmd_args())
298+
cmd.append(test)
299+
print("+", shlex.join(cmd), flush=True)
300+
301+
flush_std_streams()
302+
303+
import subprocess
304+
proc = subprocess.run(cmd, timeout=runtests.timeout)
305+
exitcode = proc.returncode
306+
307+
title = f"{title}: exit code {exitcode}"
308+
print(title)
309+
print("#" * len(title))
310+
print(flush=True)
311+
312+
if exitcode:
313+
print(f"Bisect failed with exit code {exitcode}")
314+
return False
315+
316+
return True
317+
318+
def run_bisect(self, runtests: RunTests) -> None:
319+
tests, _ = self.results.prepare_rerun(clear=False)
320+
321+
for index, name in enumerate(tests, 1):
322+
if len(tests) > 1:
323+
progress = f"{index}/{len(tests)}"
324+
else:
325+
progress = ""
326+
if not self._run_bisect(runtests, name, progress):
327+
return
328+
280329
def display_result(self, runtests):
281330
# If running the test suite for PGO then no one cares about results.
282331
if runtests.pgo:
@@ -458,7 +507,7 @@ def _run_tests(self, selected: TestTuple, tests: TestList | None) -> int:
458507

459508
setup_process()
460509

461-
if self.hunt_refleak and not self.num_workers:
510+
if (runtests.hunt_refleak is not None) and (not self.num_workers):
462511
# gh-109739: WindowsLoadTracker thread interfers with refleak check
463512
use_load_tracker = False
464513
else:
@@ -478,6 +527,9 @@ def _run_tests(self, selected: TestTuple, tests: TestList | None) -> int:
478527

479528
if self.want_rerun and self.results.need_rerun():
480529
self.rerun_failed_tests(runtests)
530+
531+
if self.want_bisect and self.results.need_rerun():
532+
self.run_bisect(runtests)
481533
finally:
482534
if use_load_tracker:
483535
self.logger.stop_load_tracker()

Lib/test/libregrtest/refleak.py

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,12 @@ def get_pooled_int(value):
8787
rc_before = alloc_before = fd_before = interned_before = 0
8888

8989
if not quiet:
90-
print("beginning", repcount, "repetitions", file=sys.stderr)
91-
print(("1234567890"*(repcount//10 + 1))[:repcount], file=sys.stderr,
92-
flush=True)
90+
print("beginning", repcount, "repetitions. Showing number of leaks "
91+
"(. for 0 or less, X for 10 or more)",
92+
file=sys.stderr)
93+
numbers = ("1234567890"*(repcount//10 + 1))[:repcount]
94+
numbers = numbers[:warmups] + ':' + numbers[warmups:]
95+
print(numbers, file=sys.stderr, flush=True)
9396

9497
results = None
9598
dash_R_cleanup(fs, ps, pic, zdc, abcs)
@@ -110,13 +113,27 @@ def get_pooled_int(value):
110113
rc_after = gettotalrefcount() - interned_after * 2
111114
fd_after = fd_count()
112115

113-
if not quiet:
114-
print('.', end='', file=sys.stderr, flush=True)
115-
116116
rc_deltas[i] = get_pooled_int(rc_after - rc_before)
117117
alloc_deltas[i] = get_pooled_int(alloc_after - alloc_before)
118118
fd_deltas[i] = get_pooled_int(fd_after - fd_before)
119119

120+
if not quiet:
121+
# use max, not sum, so total_leaks is one of the pooled ints
122+
total_leaks = max(rc_deltas[i], alloc_deltas[i], fd_deltas[i])
123+
if total_leaks <= 0:
124+
symbol = '.'
125+
elif total_leaks < 10:
126+
symbol = (
127+
'.', '1', '2', '3', '4', '5', '6', '7', '8', '9',
128+
)[total_leaks]
129+
else:
130+
symbol = 'X'
131+
if i == warmups:
132+
print(' ', end='', file=sys.stderr, flush=True)
133+
print(symbol, end='', file=sys.stderr, flush=True)
134+
del total_leaks
135+
del symbol
136+
120137
alloc_before = alloc_after
121138
rc_before = rc_after
122139
fd_before = fd_after
@@ -152,14 +169,20 @@ def check_fd_deltas(deltas):
152169
]:
153170
# ignore warmup runs
154171
deltas = deltas[warmups:]
155-
if checker(deltas):
172+
failing = checker(deltas)
173+
suspicious = any(deltas)
174+
if failing or suspicious:
156175
msg = '%s leaked %s %s, sum=%s' % (
157176
test_name, deltas, item_name, sum(deltas))
158-
print(msg, file=sys.stderr, flush=True)
159-
with open(filename, "a", encoding="utf-8") as refrep:
160-
print(msg, file=refrep)
161-
refrep.flush()
162-
failed = True
177+
print(msg, end='', file=sys.stderr)
178+
if failing:
179+
print(file=sys.stderr, flush=True)
180+
with open(filename, "a", encoding="utf-8") as refrep:
181+
print(msg, file=refrep)
182+
refrep.flush()
183+
failed = True
184+
else:
185+
print(' (this is fine)', file=sys.stderr, flush=True)
163186
return (failed, results)
164187

165188

Lib/test/libregrtest/results.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ def accumulate_result(self, result: TestResult, runtests: RunTests):
129129
def need_rerun(self):
130130
return bool(self.rerun_results)
131131

132-
def prepare_rerun(self) -> tuple[TestTuple, FilterDict]:
132+
def prepare_rerun(self, *, clear: bool = True) -> tuple[TestTuple, FilterDict]:
133133
tests: TestList = []
134134
match_tests_dict = {}
135135
for result in self.rerun_results:
@@ -140,11 +140,12 @@ def prepare_rerun(self) -> tuple[TestTuple, FilterDict]:
140140
if match_tests:
141141
match_tests_dict[result.test_name] = match_tests
142142

143-
# Clear previously failed tests
144-
self.rerun_bad.extend(self.bad)
145-
self.bad.clear()
146-
self.env_changed.clear()
147-
self.rerun_results.clear()
143+
if clear:
144+
# Clear previously failed tests
145+
self.rerun_bad.extend(self.bad)
146+
self.bad.clear()
147+
self.env_changed.clear()
148+
self.rerun_results.clear()
148149

149150
return (tuple(tests), match_tests_dict)
150151

Lib/test/libregrtest/runtests.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
import dataclasses
33
import json
44
import os
5+
import shlex
56
import subprocess
7+
import sys
68
from typing import Any
79

810
from test import support
@@ -67,6 +69,11 @@ class HuntRefleak:
6769
runs: int
6870
filename: StrPath
6971

72+
def bisect_cmd_args(self) -> list[str]:
73+
# Ignore filename since it can contain colon (":"),
74+
# and usually it's not used. Use the default filename.
75+
return ["-R", f"{self.warmups}:{self.runs}:"]
76+
7077

7178
@dataclasses.dataclass(slots=True, frozen=True)
7279
class RunTests:
@@ -136,6 +143,47 @@ def json_file_use_stdout(self) -> bool:
136143
or support.is_wasi
137144
)
138145

146+
def create_python_cmd(self) -> list[str]:
147+
python_opts = support.args_from_interpreter_flags()
148+
if self.python_cmd is not None:
149+
executable = self.python_cmd
150+
# Remove -E option, since --python=COMMAND can set PYTHON
151+
# environment variables, such as PYTHONPATH, in the worker
152+
# process.
153+
python_opts = [opt for opt in python_opts if opt != "-E"]
154+
else:
155+
executable = (sys.executable,)
156+
cmd = [*executable, *python_opts]
157+
if '-u' not in python_opts:
158+
cmd.append('-u') # Unbuffered stdout and stderr
159+
return cmd
160+
161+
def bisect_cmd_args(self) -> list[str]:
162+
args = []
163+
if self.fail_fast:
164+
args.append("--failfast")
165+
if self.fail_env_changed:
166+
args.append("--fail-env-changed")
167+
if self.timeout:
168+
args.append(f"--timeout={self.timeout}")
169+
if self.hunt_refleak is not None:
170+
args.extend(self.hunt_refleak.bisect_cmd_args())
171+
if self.test_dir:
172+
args.extend(("--testdir", self.test_dir))
173+
if self.memory_limit:
174+
args.extend(("--memlimit", self.memory_limit))
175+
if self.gc_threshold:
176+
args.append(f"--threshold={self.gc_threshold}")
177+
if self.use_resources:
178+
args.extend(("-u", ','.join(self.use_resources)))
179+
if self.python_cmd:
180+
cmd = shlex.join(self.python_cmd)
181+
args.extend(("--python", cmd))
182+
if self.randomize:
183+
args.append(f"--randomize")
184+
args.append(f"--randseed={self.random_seed}")
185+
return args
186+
139187

140188
@dataclasses.dataclass(slots=True, frozen=True)
141189
class WorkerRunTests(RunTests):

Lib/test/libregrtest/worker.py

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import os
44
from typing import Any, NoReturn
55

6-
from test import support
76
from test.support import os_helper
87

98
from .setup import setup_process, setup_test_dir
@@ -19,21 +18,10 @@
1918

2019
def create_worker_process(runtests: WorkerRunTests, output_fd: int,
2120
tmp_dir: StrPath | None = None) -> subprocess.Popen:
22-
python_cmd = runtests.python_cmd
2321
worker_json = runtests.as_json()
2422

25-
python_opts = support.args_from_interpreter_flags()
26-
if python_cmd is not None:
27-
executable = python_cmd
28-
# Remove -E option, since --python=COMMAND can set PYTHON environment
29-
# variables, such as PYTHONPATH, in the worker process.
30-
python_opts = [opt for opt in python_opts if opt != "-E"]
31-
else:
32-
executable = (sys.executable,)
33-
cmd = [*executable, *python_opts,
34-
'-u', # Unbuffered stdout and stderr
35-
'-m', 'test.libregrtest.worker',
36-
worker_json]
23+
cmd = runtests.create_python_cmd()
24+
cmd.extend(['-m', 'test.libregrtest.worker', worker_json])
3725

3826
env = dict(os.environ)
3927
if tmp_dir is not None:

0 commit comments

Comments
 (0)