Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions scripts/run_semantic_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@
`--timeout SECONDS` limits each module subprocess in parallel mode, or the entire discover subprocess with
`-j 1`. The value must be positive and at most 86400 seconds (24 hours), keeping it within platform wait limits.
A timeout fails the run and reports any output already produced; other parallel modules keep running.
The default has no time limit. This stops the direct test subprocess, not any descendants it may have started.
The default has no time limit. On POSIX, timed test subprocesses run in their own sessions: timeout and
cancellation stop their entire process groups, including helpers still holding the output pipes. Untimed
subprocesses stay in the caller's process group. Descendants that leave a timed worker's group are outside
the cleanup boundary.
"""
import argparse
import concurrent.futures
Expand Down Expand Up @@ -60,6 +63,14 @@ def _unregister_process(proc):
_active_processes.discard(proc)


def _start_test_process(cmd, timeout, **kwargs):
# Do not detach untimed jobs from the caller's ordinary process-group signals.
owns_group = os.name == "posix" and timeout is not None
proc = subprocess.Popen(cmd, start_new_session=owns_group, **kwargs)
proc._semantic_owns_group = owns_group
return proc


def _kill_process_tree(proc):
if proc is None:
return
Expand All @@ -69,6 +80,13 @@ def _kill_process_tree(proc):
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except OSError:
pass
elif os.name == "posix" and getattr(proc, "_semantic_owns_group", False):
# A launcher can exit while a helper still owns a copy of its output pipe. The session's group ID is
# the original worker PID even after the launcher exits.
try:
os.killpg(proc.pid, signal.SIGKILL)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Bound the pipe drain after sending the group kill. A helper that deliberately starts its own session can inherit the worker's stdout and stderr. The helper is outside the stated kill scope, but the second, unbounded proc.communicate() still waits for its pipes. A synthetic parallel worker with a detached helper that sleeps 2.5 s took 2.66 s to return for --timeout 0.5. A long-lived helper can hold the runner open indefinitely. Could the timeout path give the pipes a bounded drain without terminating the detached helper?

except (ProcessLookupError, PermissionError):
pass
try:
proc.kill()
except OSError:
Expand Down Expand Up @@ -202,7 +220,7 @@ def run_discover(directory, pattern, verbose, timeout):
args = ["discover", "-s", directory, "-p", pattern, *(["-v"] if verbose else [])]
with tempfile.TemporaryDirectory() as scratch:
path, env = result_environment(scratch)
proc = subprocess.Popen([sys.executable, "-c", CHILD_PROGRAM, *args], env=env)
proc = _start_test_process([sys.executable, "-c", CHILD_PROGRAM, *args], timeout, env=env)
_register_process(proc)
start_time = time.monotonic()
try:
Expand Down Expand Up @@ -245,7 +263,7 @@ def run_module(directory, module, verbose, timeout=None):
cmd = [sys.executable, "-c", CHILD_PROGRAM, *(["-v"] if verbose else []), target]
with tempfile.TemporaryDirectory() as scratch:
result_path, env = result_environment(scratch)
proc = subprocess.Popen(cmd, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
proc = _start_test_process(cmd, timeout, cwd=directory, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, errors="replace")
_register_process(proc)
try:
Expand Down
180 changes: 180 additions & 0 deletions tests/test_bcpack_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,15 @@
"""
from __future__ import annotations

import errno
import io
import json
import os
import struct
import sys
import tempfile
import unittest
from unittest import mock

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TOOLS = os.path.join(ROOT, "tools")
Expand Down Expand Up @@ -61,6 +64,16 @@ def test_profile_stream_synthetic(self) -> None:
self.assertGreaterEqual(h["unique_symbols"], 1)
self.assertGreater(len(h["top_symbols"]), 0)

def test_profile_stream_decodes_lanes_once(self) -> None:
with mock.patch.object(
bcpack_tool.bcpack, "decode_lanes", wraps=bcpack_tool.bcpack.decode_lanes
) as spy:
prof = bcpack_tool.profile_stream(
self.compressed_stream, codec=1, out_size=len(self.original_blocks)
)
self.assertEqual(spy.call_count, 1)
self.assertEqual(len(prof["histograms"]), 12)

def test_decode_file_synthetic(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
in_file = os.path.join(tmp_dir, "test.bcpack")
Expand Down Expand Up @@ -128,6 +141,136 @@ def test_decode_refuses_hardlink_output(self) -> None:
with open(in_file, "rb") as f:
self.assertEqual(f.read(), self.compressed_stream)

def test_decode_refuses_history_file_output(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
in_file = os.path.join(tmp_dir, "sample.bcpack")
hist_file = os.path.join(tmp_dir, "hist.json")
hist_body = json.dumps({"bc1": {"confirmed": {}}})
with open(in_file, "wb") as f:
f.write(self.compressed_stream)
with open(hist_file, "w", encoding="utf-8", newline="\n") as f:
f.write(hist_body)
with self.assertRaises(ValueError) as ctx:
bcpack_tool.decode_file(
in_file, hist_file, codec=1, out_size=len(self.original_blocks), history=hist_file
)
self.assertIn(hist_file, str(ctx.exception))
with open(hist_file, "r", encoding="utf-8") as f:
self.assertEqual(f.read(), hist_body)

def test_decode_refuses_symlink_to_history_file(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
in_file = os.path.join(tmp_dir, "sample.bcpack")
hist_file = os.path.join(tmp_dir, "hist.json")
link_file = os.path.join(tmp_dir, "hist_link.json")
hist_body = json.dumps({"bc1": {"confirmed": {}}})
with open(in_file, "wb") as f:
f.write(self.compressed_stream)
with open(hist_file, "w", encoding="utf-8", newline="\n") as f:
f.write(hist_body)
try:
os.symlink(hist_file, link_file)
except (OSError, NotImplementedError, AttributeError) as e:
self.skipTest(f"symlinks unavailable: {e}")
with self.assertRaises(ValueError) as ctx:
bcpack_tool.decode_file(
in_file, link_file, codec=1, out_size=len(self.original_blocks), history=hist_file
)
self.assertIn(link_file, str(ctx.exception))
with open(hist_file, "r", encoding="utf-8") as f:
self.assertEqual(f.read(), hist_body)

def test_decode_refuses_history_dir_codec_file_output(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
in_file = os.path.join(tmp_dir, "sample.bcpack")
hist_dir = os.path.join(tmp_dir, "hist_dir")
os.makedirs(hist_dir)
hist_file = os.path.join(hist_dir, "bc1.json")
hist_body = json.dumps({"codec": "bc1", "confirmed": {}})
with open(in_file, "wb") as f:
f.write(self.compressed_stream)
with open(hist_file, "w", encoding="utf-8", newline="\n") as f:
f.write(hist_body)
with self.assertRaises(ValueError) as ctx:
bcpack_tool.decode_file(
in_file, hist_file, codec=1, out_size=len(self.original_blocks), history=hist_dir
)
self.assertIn(hist_file, str(ctx.exception))
with open(hist_file, "r", encoding="utf-8") as f:
self.assertEqual(f.read(), hist_body)

def test_decode_allows_dict_history_api(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
in_file = os.path.join(tmp_dir, "sample.bcpack")
out_file = os.path.join(tmp_dir, "sample.raw")
with open(in_file, "wb") as f:
f.write(self.compressed_stream)
written = bcpack_tool.decode_file(
in_file,
out_file,
codec=1,
out_size=len(self.original_blocks),
history={"bc1": {"confirmed": {}}},
)
self.assertEqual(written, len(self.original_blocks))
with open(out_file, "rb") as f:
self.assertEqual(f.read(), self.original_blocks)

def test_decode_atomic_write_preserves_existing_output_on_error(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
in_file = os.path.join(tmp_dir, "sample.bcpack")
out_file = os.path.join(tmp_dir, "out.raw")
with open(in_file, "wb") as f:
f.write(self.compressed_stream)
with open(out_file, "wb") as f:
f.write(b"EXISTING_BYTES")
with mock.patch.object(bcpack_tool.os, "replace", side_effect=OSError("simulated replace failure")):
with self.assertRaises(OSError):
bcpack_tool.decode_file(
in_file, out_file, codec=1, out_size=len(self.original_blocks)
)
with open(out_file, "rb") as f:
self.assertEqual(f.read(), b"EXISTING_BYTES")
leftovers = [name for name in os.listdir(tmp_dir) if name.startswith(".bcpack_tool-")]
self.assertEqual(leftovers, [])

def test_decode_preserves_output_symlink(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
in_file = os.path.join(tmp_dir, "sample.bcpack")
real_out = os.path.join(tmp_dir, "target.raw")
link_out = os.path.join(tmp_dir, "link.raw")
with open(in_file, "wb") as f:
f.write(self.compressed_stream)
try:
os.symlink(real_out, link_out)
except (OSError, NotImplementedError, AttributeError) as e:
self.skipTest(f"symlinks unavailable: {e}")
written = bcpack_tool.decode_file(
in_file, link_out, codec=1, out_size=len(self.original_blocks)
)
self.assertEqual(written, len(self.original_blocks))
self.assertTrue(os.path.islink(link_out))
with open(real_out, "rb") as f:
self.assertEqual(f.read(), self.original_blocks)

def test_decode_refuses_symlink_loop(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
in_file = os.path.join(tmp_dir, "sample.bcpack")
loop_a = os.path.join(tmp_dir, "loop_a.raw")
loop_b = os.path.join(tmp_dir, "loop_b.raw")
with open(in_file, "wb") as f:
f.write(self.compressed_stream)
try:
os.symlink(loop_b, loop_a)
os.symlink(loop_a, loop_b)
except (OSError, NotImplementedError, AttributeError) as e:
self.skipTest(f"symlinks unavailable: {e}")
with self.assertRaises(OSError) as ctx:
bcpack_tool.decode_file(
in_file, loop_a, codec=1, out_size=len(self.original_blocks)
)
self.assertEqual(ctx.exception.errno, errno.ELOOP)

def test_cli_subcommands(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
in_file = os.path.join(tmp_dir, "sample.bcpack")
Expand Down Expand Up @@ -288,6 +431,43 @@ def test_malformed_history_json(self) -> None:
self._assert_one_error_line(rc, err, "hist.json")
self.assertFalse(os.path.exists(out_file))

def test_malformed_history_dir_with_trailing_slash_attributes_file(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
in_file = os.path.join(tmp_dir, "sample.bcpack")
with open(in_file, "wb") as f:
f.write(self.compressed_stream)
hist_dir = os.path.join(tmp_dir, "hist_dir")
os.makedirs(hist_dir)
with open(os.path.join(hist_dir, "bc1.json"), "w", encoding="utf-8", newline="\n") as f:
f.write("{not json")
out_file = os.path.join(tmp_dir, "out.raw")
rc, err, _ = self._cli(
["decode", in_file, out_file, "--codec", "1", "--size", "32",
"--history", hist_dir + os.sep],
tmp_dir, "decode_hist_dir",
)
self._assert_one_error_line(rc, err, "bc1.json")
self.assertIn("hist_dir", err)
self.assertFalse(os.path.exists(out_file))

def test_cli_unsupported_codec_exits_2_without_traceback(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
in_file = os.path.join(tmp_dir, "sample.bcpack")
out_file = os.path.join(tmp_dir, "out.raw")
with open(in_file, "wb") as f:
f.write(self.compressed_stream)
with mock.patch.object(
bcpack_tool.bcpack,
"decode_with_info",
side_effect=bcpack_tool.bcpack.BcpackUnsupportedCodec("codec unsupported"),
):
rc, err, _ = self._cli(
["decode", in_file, out_file, "--codec", "1", "--size", "32"],
tmp_dir, "decode_unsupported",
)
self._assert_one_error_line(rc, err, "codec unsupported")
self.assertFalse(os.path.exists(out_file))

def test_decode_same_input_output_cli_exits_2(self) -> None:
with tempfile.TemporaryDirectory() as tmp_dir:
in_file = os.path.join(tmp_dir, "same.bcpack")
Expand Down
32 changes: 32 additions & 0 deletions tests/test_run_semantic_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,38 @@ def test_serial_timeout_keeps_discover_output_and_names_the_suite(self):
self.assertIn(tmp, result.stderr)
self.assertNotIn("Traceback", result.stdout + result.stderr)

@unittest.skipUnless(os.name == "posix", "POSIX worker process groups")
def test_timeout_stops_helpers_holding_the_output_pipe(self):
child = "import time; time.sleep(6); print('helper-finished-marker', flush=True)"
for jobs, linger in ((1, True), (2, True), (2, False)):
with self.subTest(jobs=jobs, worker_lingers=linger), tempfile.TemporaryDirectory() as tmp:
source = ("import subprocess, sys, time, unittest\n"
"class T(unittest.TestCase):\n"
" def test_helper(self):\n"
f" subprocess.Popen([sys.executable, '-c', {child!r}])\n"
" print('helper-started-marker', flush=True)\n")
if linger:
source += " time.sleep(10)\n"
suite(tmp, {"test_helper.py": source})
result = cli(tmp, "-j", str(jobs), "--timeout", "2")
output = result.stdout + result.stderr
self.assertEqual(result.returncode, 1, output)
self.assertIn("helper-started-marker", output)
self.assertIn("TIMED OUT after 2 s:", output)
self.assertNotIn("helper-finished-marker", output)

@unittest.skipUnless(os.name == "posix", "POSIX worker process groups")
def test_untimed_workers_keep_the_runner_process_group(self):
source = ("import os, unittest\n"
"class T(unittest.TestCase):\n"
" def test_group(self):\n"
" self.assertEqual(os.getpgrp(), os.getpgid(os.getppid()))\n")
for jobs in (1, 2):
with self.subTest(jobs=jobs), tempfile.TemporaryDirectory() as tmp:
suite(tmp, {"test_group.py": source})
result = cli(tmp, "-j", str(jobs))
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)

def test_timeout_requires_positive_finite_seconds(self):
for value in ("0", "-1", "nan", "inf", "-inf"):
with self.subTest(value=value):
Expand Down
Loading
Loading