From e1fd5654e520023533c17a6cc6cbf13bcb093fb7 Mon Sep 17 00:00:00 2001 From: IlyassRS Date: Wed, 25 Nov 2026 00:50:44 +0100 Subject: [PATCH 1/2] bcpack_tool: single-pass profile, history overwrite guard, and atomic output (BCPACK-TOOL-HARDENING) --- tests/test_bcpack_tool.py | 180 ++++++++++++++++++++++++++++++++++++++ tools/bcpack_tool.py | 105 ++++++++++++++++++---- 2 files changed, 270 insertions(+), 15 deletions(-) diff --git a/tests/test_bcpack_tool.py b/tests/test_bcpack_tool.py index 8f89216efc..4662fbdd89 100644 --- a/tests/test_bcpack_tool.py +++ b/tests/test_bcpack_tool.py @@ -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") @@ -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") @@ -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") @@ -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") diff --git a/tools/bcpack_tool.py b/tools/bcpack_tool.py index d127250c41..785dac80fc 100644 --- a/tools/bcpack_tool.py +++ b/tools/bcpack_tool.py @@ -11,17 +11,21 @@ from __future__ import annotations import argparse +from contextlib import suppress +import errno import json import os import sys +import tempfile sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import bcpack +from file_mode import published_mode from report_paths import same_report_path -def inspect_stream(raw: bytes, codec: int, out_size: int) -> dict: - """Analyze stream structure, compression ratio and per-lane statistics.""" +def _inspect_decoded_lanes(raw: bytes, codec: int, out_size: int) -> tuple[dict, list[list[int]]]: + """Decode lanes once and build the inspection report alongside the decoded lanes.""" if codec not in bcpack.ALL_CODECS: raise ValueError(f"unsupported BCPack codec id: {codec}") @@ -61,7 +65,7 @@ def inspect_stream(raw: bytes, codec: int, out_size: int) -> dict: trailing_bytes = len(raw) - used ratio = round(len(raw) / out_size, 4) if out_size else 0.0 - return { + info = { "codec": bcpack.CODEC_NAMES[codec], "codec_id": codec, "compressed_bytes": len(raw), @@ -73,12 +77,18 @@ def inspect_stream(raw: bytes, codec: int, out_size: int) -> dict: "total_symbols": total_symbols, "lanes": lane_reports, } + return info, lanes + + +def inspect_stream(raw: bytes, codec: int, out_size: int) -> dict: + """Analyze stream structure, compression ratio and per-lane statistics.""" + info, _ = _inspect_decoded_lanes(raw, codec, out_size) + return info def profile_stream(raw: bytes, codec: int, out_size: int) -> dict: """Generate symbol frequency distribution profile across all lanes.""" - info = inspect_stream(raw, codec, out_size) - lanes, _ = bcpack.decode_lanes(raw, codec, out_size) + info, lanes = _inspect_decoded_lanes(raw, codec, out_size) histograms = [] for idx, lane in enumerate(lanes): @@ -96,6 +106,57 @@ def profile_stream(raw: bytes, codec: int, out_size: int) -> dict: return info +def _history_paths(history: object, codec: int) -> tuple[str | None, list[str]]: + """Return `(display_path, protected_paths)` for an on-disk `history` argument, or `(None, [])`.""" + if history is None or isinstance(history, dict): + return None, [] + hist_path = os.fsdecode(os.fspath(history)) + protected = [hist_path] + display = os.path.normpath(hist_path) + if os.path.isdir(hist_path): + codec_name = bcpack.CODEC_NAMES.get(codec) + if codec_name is not None: + candidate = os.path.join(display, f"{codec_name.lower()}.json") + if os.path.exists(candidate): + protected.append(candidate) + if os.path.isfile(candidate): + display = candidate + return display, protected + + +def _write_output_atomic(destination: str, data: bytes) -> None: + """Publish decoded bytes to `destination` without truncating an existing file on error.""" + parent = os.path.dirname(os.path.abspath(destination)) + if parent: + os.makedirs(parent, exist_ok=True) + + # Special non-regular files (e.g. /dev/null or NUL) cannot be replaced by rename. + if os.path.exists(destination) and not os.path.isfile(destination): + with open(destination, "wb") as f: + f.write(data) + return + + staged = None + try: + with tempfile.NamedTemporaryFile( + mode="wb", + dir=parent or ".", + prefix=".bcpack_tool-", + suffix=".tmp", + delete=False, + ) as f: + staged = f.name + f.write(data) + os.chmod(staged, published_mode(destination)) + os.replace(staged, destination) + staged = None + finally: + if staged is not None: + with suppress(OSError): + os.chmod(staged, 0o600) + os.unlink(staged) + + def decode_file( in_path: str, out_path: str, @@ -111,6 +172,20 @@ def decode_file( f"refusing to overwrite it" ) + hist_label, hist_protected = _history_paths(history, codec) + for target in hist_protected: + if same_report_path(target, out_path): + raise ValueError( + f"output path '{out_path}' names the history path '{target}'; " + f"refusing to overwrite it" + ) + + destination = os.path.realpath(out_path) + if os.path.islink(destination): + raise OSError(errno.ELOOP, os.strerror(errno.ELOOP), out_path) + if os.path.isdir(destination): + raise IsADirectoryError(errno.EISDIR, os.strerror(errno.EISDIR), out_path) + with open(in_path, "rb") as f: raw = f.read() @@ -123,16 +198,13 @@ def decode_file( except ValueError as e: # json.JSONDecodeError from a --history file carries no filename; attribute it, # but do not double-prefix messages that already name the history path. - if history is not None and os.path.basename(str(history)) not in str(e): - raise ValueError(f"{history}: {e}") from e + if hist_label is not None: + base = os.path.basename(os.path.normpath(hist_label)) + if not base or base not in str(e): + raise ValueError(f"{hist_label}: {e}") from e raise - parent = os.path.dirname(os.path.abspath(out_path)) - if parent: - os.makedirs(parent, exist_ok=True) - - with open(out_path, "wb") as f: - f.write(data) + _write_output_atomic(destination, data) return len(data) @@ -220,7 +292,7 @@ def main(argv: list[str] | None = None) -> int: src = args.in_file if args.command == "decode" else args.file try: return _run(args) - except (ValueError, OSError) as e: + except (ValueError, OSError, bcpack.BcpackUnsupportedCodec) as e: print(f"ERROR: {src}: {e}", file=sys.stderr) return 2 @@ -267,5 +339,8 @@ def _run(args: argparse.Namespace) -> int: return 1 if __name__ == "__main__": - sys.stdout.reconfigure(errors="replace") + try: + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass sys.exit(main()) From db8d971c9e6714c10c4b42d36e9e80e027d5a2b8 Mon Sep 17 00:00:00 2001 From: EdenBendheim Date: Thu, 26 Nov 2026 00:24:52 -0500 Subject: [PATCH 2/2] tests: bound POSIX semantic helper lifetime on timeout (SEMANTIC-RUNNER-POSIX-CHILD-TIMEOUT) --- scripts/run_semantic_tests.py | 25 ++++++++++++++++++++++--- tests/test_run_semantic_tests.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/scripts/run_semantic_tests.py b/scripts/run_semantic_tests.py index 514e781330..de9387cd36 100644 --- a/scripts/run_semantic_tests.py +++ b/scripts/run_semantic_tests.py @@ -23,7 +23,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 @@ -33,6 +36,7 @@ import math import os import re +import signal import subprocess import sys import tempfile @@ -56,6 +60,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 @@ -65,6 +77,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) + except (ProcessLookupError, PermissionError): + pass try: proc.kill() except OSError: @@ -159,7 +178,7 @@ def run_module(directory, module, verbose, timeout=None): with tempfile.TemporaryDirectory() as scratch: count_path = os.path.join(scratch, "count.json") env = dict(os.environ, LEONIDA_TEST_COUNT=count_path) - 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: @@ -208,7 +227,7 @@ def main(argv=None): if a.jobs <= 1: cmd = [sys.executable, "-m", "unittest", "discover", "-s", directory, "-p", a.pattern, *(["-v"] if a.verbose else [])] - proc = subprocess.Popen(cmd) + proc = _start_test_process(cmd, a.timeout) _register_process(proc) start_time = time.monotonic() try: diff --git a/tests/test_run_semantic_tests.py b/tests/test_run_semantic_tests.py index 7fc75e3722..5b546658b7 100644 --- a/tests/test_run_semantic_tests.py +++ b/tests/test_run_semantic_tests.py @@ -119,6 +119,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):