diff --git a/.github/workflows/PR.yml b/.github/workflows/PR.yml index d4cfaca..6d3ef74 100644 --- a/.github/workflows/PR.yml +++ b/.github/workflows/PR.yml @@ -36,6 +36,9 @@ jobs: - name: Benchmark compiler (report only) if: matrix.os == 'ubuntu-latest' && matrix.python == '3.13' run: python benchmarks/compiler.py --blocks 5000 --repeat 5 + - name: Benchmark runtime (report only) + if: matrix.os == 'ubuntu-latest' && matrix.python == '3.13' + run: python benchmarks/runtime.py --repeat 7 --number 200 Build: runs-on: ubuntu-latest steps: diff --git a/benchmarks/runtime.py b/benchmarks/runtime.py new file mode 100644 index 0000000..7fe7db3 --- /dev/null +++ b/benchmarks/runtime.py @@ -0,0 +1,101 @@ +"""Synthetic gateway-like runtime workloads. No network or customer data.""" +import argparse +import json +import random +import statistics +import timeit +import warnings + +import restructuredpython as repy + +REPY = """ + +def count_chars(messages: list[str]) -> int { + total = 0 + for message in messages { + total += len(message) + } + return total +} + +def contains_keyword(text: str, keywords: list[str]) -> bool { + for keyword in keywords { + if keyword in text { + return True + } + } + return False +} + +def total_usage(tokens: list[int]) -> int { + total = 0 + for count in tokens { + total += count + } + return total +} +""" + + +def baseline_chars(messages): + total = 0 + for message in messages: + total += len(message) + return total + + +def baseline_keywords(text, keywords): + for keyword in keywords: + if keyword in text: + return True + return False + + +def baseline_usage(tokens): + total = 0 + for count in tokens: + total += count + return total + + +def workloads(): + rng = random.Random(42) + messages = ["synthetic prompt 😀 你好 " * rng.randrange(1, 20) for _ in range(4096)] + tokens = [rng.randrange(1, 16000) for _ in messages] + prompt = "synthetic query text " * 40 + "target" + keywords = [f"keyword_{i}" for i in range(200)] + ["target"] + return [ + ("message_character_reduction", baseline_chars, "count_chars", (messages,)), + ("routing_keyword_scan", baseline_keywords, "contains_keyword", (prompt, keywords)), + ("integer_usage_aggregation", baseline_usage, "total_usage", (tokens,)), + ] + + +def benchmark(*, repeat=7, number=200): + if not 1 <= repeat <= 30 or not 1 <= number <= 100000: + raise ValueError("repeat and number outside supported limits") + namespace = {} + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + exec(repy.parse(REPY), namespace) + results = [] + for name, baseline, function, args in workloads(): + optimized = namespace[function] + assert optimized(*args) == baseline(*args), name + original = statistics.median(timeit.repeat(lambda: baseline(*args), repeat=repeat, number=number)) / number + native = statistics.median(timeit.repeat(lambda: optimized(*args), repeat=repeat, number=number)) / number + results.append({"workload": name, "python_seconds": original, "repy_seconds": native, + "speedup": original / native, "native_dispatch": hasattr(optimized, "__repy_native_kernel__")}) + return results + + +def main(): + cli = argparse.ArgumentParser() + cli.add_argument("--repeat", type=int, default=7) + cli.add_argument("--number", type=int, default=200) + args = cli.parse_args() + print(json.dumps(benchmark(repeat=args.repeat, number=args.number), indent=2)) + + +if __name__ == "__main__": + main() diff --git a/docs/profiling.md b/docs/profiling.md new file mode 100644 index 0000000..c7b6a7f --- /dev/null +++ b/docs/profiling.md @@ -0,0 +1,32 @@ +# Runtime profiling and benchmarks + +Profile trusted REPY code locally: + +```bash +repy-profile record --output profile.json server_workload.repy +repy-profile plan profile.json --min-calls 100 --limit 20 +``` + +The report excludes compilation and records project-relative function names, +call counts and timings (not arguments, request payloads or source text). +Function names/paths themselves can be sensitive; keep the file private. +The report is capped at 1,000 rows and 2 MiB, never uploaded and never +overwrites an existing file. Reports are created exclusively with private POSIX permissions (Windows uses directory ACLs); the output is reserved before execution. A failed run removes its reservation, though abrupt process termination can leave an empty reservation. Use a trusted output directory. + +This is explicitly a **calling-thread Python baseline profiler**: worker threads are not included, and active cProfile hooks intentionally cause REPY's native wrappers to execute their original Python implementation. Native runtime benchmarks are separate. Source locations refer to generated Python; expanded header functions can be attributed to the entrypoint rather than their original header. cProfile reports timing rather than pure CPU samples and can affect performance; don't use it for production request profiling without review. + +The plan ranks optimization candidates by self time and call count. +It is a profile-guided selection tool, not automatic PGO or automatic +native compilation. Review the function's types, side effects, correctness +and benchmarks before opting into native compilation. + +```bash +python benchmarks/runtime.py --repeat 7 --number 200 +REPY_PURE_PYTHON=1 python benchmarks/runtime.py +``` + +The synthetic workload models message length estimation, routing keyword +search and integer usage aggregation. It uses no customer data, no network, +and checks results before timing. CI prints report-only benchmark results +with native dispatch status. Benchmark ratios vary by platform and workload; +they do not predict gateway end-to-end latency or financial correctness. diff --git a/pyproject.toml b/pyproject.toml index 5bcd7fc..b736429 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,6 +23,7 @@ dependencies = [] [project.scripts] repy = "restructuredpython.restructuredpython:main" repycl = "restructuredpython.restructuredpython:launch" +repy-profile = "restructuredpython.profiling:main" [tool.setuptools.packages.find] include = ["restructuredpython*"] diff --git a/restructuredpython/profiling.py b/restructuredpython/profiling.py new file mode 100644 index 0000000..6b92cd6 --- /dev/null +++ b/restructuredpython/profiling.py @@ -0,0 +1,196 @@ +"""Local, opt-in profiling and hotspot selection for trusted REPY programs.""" +import argparse +import cProfile +import json +import math +import os +import tempfile +import pstats +import sys +from pathlib import Path + +from .restructuredpython import _prepare_run, _source_root +from .tempload import execute_code_temporarily + +MAX_REPORT_ROWS = 1000 +MAX_REPORT_BYTES = 2 * 1024 * 1024 + + +def _project_rows(stats, root): + rows = [] + root = Path(root).resolve() + for (filename, line, name), (primitive, calls, self_time, cumulative, _) in stats.stats.items(): + if filename.startswith("<") or not filename: + continue + path = Path(filename) + if not path.is_absolute(): + # Do not resolve relative interpreter or stdlib pseudo-paths. + continue + path = path.resolve() + if not path.is_relative_to(root) or path.suffix.lower() not in {".py", ".repy"}: + continue + rows.append({ + "file": path.relative_to(root).as_posix(), "line": line, + "function": name, "calls": calls, "primitive_calls": primitive, + "self_seconds": self_time, "cumulative_seconds": cumulative, + }) + rows.sort(key=lambda row: (-row["self_seconds"], -row["calls"], + row["file"], row["line"], row["function"])) + return rows[:MAX_REPORT_ROWS] + + +def _record_profile(filename, args=()): + if sys.getprofile() is not None: + raise RuntimeError("Cannot record a profile while another profiler is active") + source, compiled = _prepare_run(filename) + root = _source_root(source.parent) + profiler = cProfile.Profile() + script_exit = None + try: + profiler.runcall(execute_code_temporarily, compiled, source, args) + except SystemExit as error: + script_exit = error + stats = pstats.Stats(profiler) + return { + "schema_version": 1, + "scope": "calling_thread", + "execution_backend": "python_fallback_for_repy_native_kernels", + "locations": "generated_python_in_entrypoint_or_imported_file", + "total_seconds": stats.total_tt, + "functions": _project_rows(stats, root), + }, script_exit + + +def record_profile(filename, args=()): + """Profile execution, not compilation; only run trusted local programs.""" + report, script_exit = _record_profile(filename, args) + if script_exit is not None: + raise script_exit + return report + + +def select_hotspots(report, *, limit=20, min_calls=1): + """Return a deterministic profile-guided selection of CPU hotspots. + + The report measures profiled wall time, not exclusive on-CPU samples. + Selection never rewrites code or automatically enables native mode. + """ + if type(limit) is not int or not 1 <= limit <= MAX_REPORT_ROWS: + raise ValueError("limit must be between 1 and 1000") + if type(min_calls) is not int or min_calls < 1: + raise ValueError("min_calls must be positive") + if not isinstance(report, dict) or report.get("schema_version") != 1: + raise ValueError("Unsupported profile schema") + rows = report.get("functions") + if not isinstance(rows, list) or len(rows) > MAX_REPORT_ROWS: + raise ValueError("Invalid profile function list") + valid = [] + for row in rows: + if not isinstance(row, dict): + raise ValueError("Invalid profile row") + file, name = row.get("file"), row.get("function") + calls, line = row.get("calls"), row.get("line") + elapsed = row.get("self_seconds") + if (not isinstance(file, str) or not file or Path(file).is_absolute() + or "\\" in file or ":" in file or ".." in Path(file).parts + or not isinstance(name, str) + or type(calls) is not int or calls < 0 + or type(line) is not int or line < 0 + or type(elapsed) not in {int, float} or not math.isfinite(elapsed) or elapsed < 0): + raise ValueError("Invalid profile row fields") + if calls >= min_calls and name != "": + valid.append({"file": file, "function": name, "line": line, + "calls": calls, "self_seconds": elapsed}) + return sorted(valid, key=lambda row: (-row["self_seconds"], -row["calls"], + row["file"], row["line"], row["function"]))[:limit] + + +def write_profile(path, report): + payload = json.dumps(report, ensure_ascii=True, allow_nan=False, indent=2) + "\n" + if len(payload.encode("utf-8")) > MAX_REPORT_BYTES: + raise ValueError("Profile report exceeds size limit") + path = Path(path).absolute() + _claim_profile(path) + try: + _publish_profile(path, payload) + except BaseException: + path.unlink(missing_ok=True) + raise + + +def _claim_profile(path): + # Exclusive creation prevents concurrent profiling invocations from running + # the same workload. Mode 0600 is enforced on POSIX; Windows uses directory ACLs. + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + os.close(fd) + + +def _publish_profile(path, payload): + # The destination is our exclusively created reservation. Prepare the + # complete report before replacing it; assume a trusted output directory. + fd, temporary = tempfile.mkstemp(prefix=".repy-profile-", dir=path.parent) + try: + with os.fdopen(fd, "w", encoding="utf-8") as file: + file.write(payload) + file.flush() + os.fsync(file.fileno()) + os.replace(temporary, path) + finally: + Path(temporary).unlink(missing_ok=True) + + +def _record_to_path(filename, args, path): + _claim_profile(path) + try: + report, script_exit = _record_profile(filename, args) + payload = json.dumps(report, ensure_ascii=True, allow_nan=False, indent=2) + "\n" + if len(payload.encode("utf-8")) > MAX_REPORT_BYTES: + raise ValueError("Profile report exceeds size limit") + _publish_profile(path, payload) + except BaseException: + path.unlink(missing_ok=True) + raise + return script_exit + + +def read_profile(path): + with Path(path).open("rb") as file: + data = file.read(MAX_REPORT_BYTES + 1) + if len(data) > MAX_REPORT_BYTES: + raise ValueError("Profile report exceeds size limit") + return json.loads(data) + + +def main(argv=None): + cli = argparse.ArgumentParser(prog="repy-profile") + sub = cli.add_subparsers(dest="command", required=True) + record = sub.add_parser("record", help="Run a trusted script and record local function timings") + record.add_argument("--output", required=True) + record.add_argument("filename") + record.add_argument("args", nargs=argparse.REMAINDER) + plan = sub.add_parser("plan", help="Rank optimization candidates from a saved profile") + plan.add_argument("profile") + plan.add_argument("--limit", type=int, default=20) + plan.add_argument("--min-calls", type=int, default=1) + args = cli.parse_args(argv) + if args.command == "record": + output = Path(args.output).absolute() + # Report filesystem/setup errors with their tracebacks as well as + # application errors; never swallow the application's failing frame. + script_exit = _record_to_path(args.filename, args.args, output) + print(output) + if script_exit is not None: + raise script_exit + else: + try: + candidates = select_hotspots(read_profile(args.profile), limit=args.limit, + min_calls=args.min_calls) + print(json.dumps(candidates, ensure_ascii=True, allow_nan=False, indent=2)) + except (OSError, ValueError, SyntaxError, RuntimeError) as error: + print(f"repy-profile: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_profiling.py b/tests/test_profiling.py new file mode 100644 index 0000000..e27757e --- /dev/null +++ b/tests/test_profiling.py @@ -0,0 +1,100 @@ +import tempfile +import os +import sys +from unittest.mock import patch +import unittest +from pathlib import Path + +from restructuredpython.profiling import record_profile, select_hotspots, write_profile, read_profile, main + + +class ProfilingTests(unittest.TestCase): + def test_local_profile_and_selection(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / "example.repy" + source.write_text( + "def hot() {\n total = 0\n for i in range(100) {\n total += i\n }\n return total\n}\n" + "for i in range(5) {\n hot()\n}\n", encoding="utf-8") + report = record_profile(source) + rows = select_hotspots(report, min_calls=5) + self.assertTrue(any(row["function"] == "hot" and row["calls"] == 5 for row in rows)) + self.assertTrue(all(row["file"] == "example.repy" for row in rows)) + path = root / "profile.json" + write_profile(path, report) + self.assertEqual(read_profile(path), report) + self.assertNotIn(directory, path.read_text(encoding="utf-8")) + with self.assertRaises(FileExistsError): + write_profile(path, report) + + def test_report_validation(self): + for bad in ({}, {"schema_version": 1, "functions": [{}]}, + {"schema_version": 1, "functions": [ + {"file": "../outside.py", "function": "f", "line": 1, "calls": 3, "self_seconds": 1.0}]}): + with self.assertRaises(ValueError): + select_hotspots(bad) + + def test_deterministic_sorting(self): + rows = [{"file": "b.py", "function": "f", "line": 1, "calls": 3, "self_seconds": 1.0}, + {"file": "a.py", "function": "g", "line": 2, "calls": 3, "self_seconds": 1.0}] + self.assertEqual(select_hotspots({"schema_version": 1, "functions": rows}, limit=1)[0]["file"], "a.py") + + + def test_profile_reservation_and_script_exit(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / "example.REPY" + output = root / "profile.json" + marker = root / "ran" + source.write_text( + "from pathlib import Path\n" + f"Path({str(marker)!r}).write_text('ran')\n" + "def hot():\n return 1\nhot()\nraise SystemExit(3)\n", + encoding="utf-8", + ) + output.write_text("reserved", encoding="utf-8") + with self.assertRaises(FileExistsError): + main(["record", "--output", str(output), str(source)]) + self.assertFalse(marker.exists()) + output.unlink() + with self.assertRaises(SystemExit) as error: + main(["record", "--output", str(output), str(source)]) + self.assertEqual(error.exception.code, 3) + self.assertTrue(marker.exists()) + report = read_profile(output) + self.assertEqual(report["scope"], "calling_thread") + self.assertTrue(any(r["function"] == "hot" for r in report["functions"])) + if os.name != "nt": + self.assertEqual(output.stat().st_mode & 0o077, 0) + + def test_failed_execution_cleans_claim_and_preserves_traceback(self): + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "bad.repy" + output = Path(directory) / "profile.json" + source.write_text("raise ValueError('script failure')\n", encoding="utf-8") + with self.assertRaisesRegex(ValueError, "script failure"): + main(["record", "--output", str(output), str(source)]) + self.assertFalse(output.exists()) + + def test_existing_profile_hook_is_not_removed(self): + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "script.repy" + source.write_text("pass", encoding="utf-8") + def hook(*args): + pass + sys.setprofile(hook) + try: + with self.assertRaisesRegex(RuntimeError, "another profiler"): + record_profile(source) + self.assertIs(sys.getprofile(), hook) + finally: + sys.setprofile(None) + + def test_failed_publication_removes_claim(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "report.json" + with patch("restructuredpython.profiling.os.replace", side_effect=OSError("failed")): + with self.assertRaises(OSError): + write_profile(path, {"schema_version": 1}) + self.assertFalse(path.exists()) + self.assertEqual(list(Path(directory).iterdir()), [])