Repository navigation
Add local profiling, hotspot selection and runtime benchmarks #140
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+433
−0
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 = """ | ||
| <OPTIMIZE native=True> | ||
| def count_chars(messages: list[str]) -> int { | ||
| total = 0 | ||
| for message in messages { | ||
| total += len(message) | ||
| } | ||
| return total | ||
| } | ||
| <OPTIMIZE native=True> | ||
| def contains_keyword(text: str, keywords: list[str]) -> bool { | ||
| for keyword in keywords { | ||
| if keyword in text { | ||
| return True | ||
| } | ||
| } | ||
| return False | ||
| } | ||
| <OPTIMIZE native=True> | ||
| 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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 != "<module>": | ||
| 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()) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.