From 7d5ab14041d6e2ec9e83e7be5acbfcb0a564b666 Mon Sep 17 00:00:00 2001 From: Rihaan Meher Date: Sun, 6 Dec 2026 17:25:06 -0500 Subject: [PATCH] Add local profile-guided hotspot selection and gateway runtime benchmarks --- .github/workflows/PR.yml | 3 + benchmarks/runtime.py | 101 +++++++++++++++++++++++ docs/profiling.md | 32 ++++++++ pyproject.toml | 1 + restructuredpython/profiling.py | 140 ++++++++++++++++++++++++++++++++ tests/test_profiling.py | 37 +++++++++ 6 files changed, 314 insertions(+) create mode 100644 benchmarks/runtime.py create mode 100644 docs/profiling.md create mode 100644 restructuredpython/profiling.py create mode 100644 tests/test_profiling.py 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..adf2362 --- /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. Generated-code line numbers may differ from REPY +source. 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..84c9a59 --- /dev/null +++ b/restructuredpython/profiling.py @@ -0,0 +1,140 @@ +"""Local, opt-in profiling and hotspot selection for trusted REPY programs.""" +import argparse +import cProfile +import json +import math +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 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=()): + """Profile execution, not compilation. Only run trusted local programs.""" + source, compiled = _prepare_run(filename) + root = _source_root(source.parent) + profiler = cProfile.Profile() + profiler.runcall(execute_code_temporarily, compiled, source, args) + stats = pstats.Stats(profiler) + return { + "schema_version": 1, + "total_seconds": stats.total_tt, + "functions": _project_rows(stats, root), + } + + +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") + # Never replace an existing report or follow an existing symbolic link. + with Path(path).open("x", encoding="utf-8") as file: + file.write(payload) + + +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) + try: + if args.command == "record": + output = Path(args.output).absolute() + if output.exists() or output.is_symlink(): + raise FileExistsError(f"Profile already exists: {output}") + if not output.parent.is_dir(): + raise ValueError("Profile output parent must exist") + report = record_profile(args.filename, args.args) + write_profile(output, report) + print(output) + else: + 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..5173c9c --- /dev/null +++ b/tests/test_profiling.py @@ -0,0 +1,37 @@ +import tempfile +import unittest +from pathlib import Path + +from restructuredpython.profiling import record_profile, select_hotspots, write_profile, read_profile + + +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")