Skip to content

Add local profiling, hotspot selection and runtime benchmarks - #140

Open
sharktide wants to merge 1 commit into
optimizer/native-runtimefrom
optimizer/profile-and-benchmarks
Open

sharktide wants to merge 1 commit into
optimizer/native-runtimefrom
optimizer/profile-and-benchmarks

Conversation

@sharktide

@sharktide sharktide commented Dec 6, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #138. Adds repy-profile record/plan for trusted local programs, bounded JSON timings without argument values, deterministic hotspot selection and synthetic Lightning-like benchmark workloads comparing native and original Python with output parity. CI reports runtime speed separately from compiler throughput. Profile-guided selection is implemented; automatic profile-guided IR rewriting is not.

Summary by Sourcery

Add local runtime profiling and hotspot selection, alongside synthetic benchmarks for comparing native and Python execution.

New Features:

  • Add the repy-profile command to record bounded local timing reports for trusted REPY programs and rank deterministic optimization hotspots.

Enhancements:

  • Add synthetic runtime benchmarks for message-length reduction, keyword scanning, and usage aggregation, with output parity checks and native-dispatch reporting.

Build:

  • Register repy-profile as an installed command-line entry point.

CI:

  • Run the runtime benchmark in CI as a report-only job on Ubuntu with Python 3.13.

Documentation:

  • Document local profiling, report privacy and limits, hotspot selection, and how to run the runtime benchmarks.

Tests:

  • Add coverage for profile recording and round-tripping, hotspot selection and ordering, and invalid report rejection.

@sourcery-ai

sourcery-ai Bot commented Dec 6, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Add the repy-profile command and profiling helpers to record bounded local timings and select deterministic hotspots.

  • pyproject.toml L26
  • restructuredpython/profiling.py L1-140

Implementation

Add synthetic runtime workloads that check output parity and compare Python with native execution.

  • benchmarks/runtime.py L1-101

Configuration

Run the runtime benchmark in CI as a report-only step on the designated Ubuntu and Python matrix entry.

  • .github/workflows/PR.yml L39-41

Documentation

Document local profiling, hotspot interpretation, and the scope and limits of the synthetic benchmarks.

  • docs/profiling.md L1-32

Tests

Test profile recording, hotspot selection, report persistence, validation, and deterministic sorting.

  • tests/test_profiling.py L1-37

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 10 issues


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Profile reports expose private paths

When the process uses a permissive umask and other local users can access the output directory, Path.open("x") creates the report using that umask, so other local users can read sensitive project paths and function names despite the privacy warning.

Create the report with private permissions while preserving exclusive creation.

source, compiled = _prepare_run(filename)
root = _source_root(source.parent)
profiler = cProfile.Profile()
profiler.runcall(execute_code_temporarily, compiled, source, args)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Native timings show fallback execution

When the profiled program calls functions with available native kernels, cProfile sets the active profile hook, so native_function uses the Python fallback instead of the native kernel; the report and hotspot plan therefore rank timings from a different execution path than normal native-enabled use.

Profile execution without making the native dispatcher treat the profiler's hook as a reason to use its Python fallback.

source, compiled = _prepare_run(filename)
root = _source_root(source.parent)
profiler = cProfile.Profile()
profiler.runcall(execute_code_temporarily, compiled, source, args)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Worker-thread hotspots are missing

When the profiled program performs work in worker threads, cProfile.Profile.runcall profiles only the calling thread, so worker-thread calls are absent from stats and the hotspot plan ranks an incomplete view of the workload.

Include worker-thread execution in the profile collected for the program.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Failed writes leave partial reports

When the process stops or a write is interrupted after the output file is created, write_profile creates the destination before writing the complete payload, so an interruption or write error leaves a partial report; exclusive creation then rejects retries, and plan cannot parse the file.

Write the complete report atomically, or remove the destination if writing fails.

try:
if args.command == "record":
output = Path(args.output).absolute()
if output.exists() or output.is_symlink():

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Conflicting runs still execute

When two record invocations concurrently target the same output path while it does not yet exist, both main calls pass the existence check and run record_profile; after one writes the report, the other fails to create it. The losing invocation has already run the trusted program, so its external side effects happen despite the command failing.

Atomically claim the output path before running the program, and ensure only the invocation that claims it proceeds.

source, compiled = _prepare_run(filename)
root = _source_root(source.parent)
profiler = cProfile.Profile()
profiler.runcall(execute_code_temporarily, compiled, source, args)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Successful exits skip profile output

When the profiled script terminates with raise SystemExit(...) or sys.exit(...), cProfile.Profile.runcall propagates SystemExit, and main does not catch it, so a REPY command-line script that ends with the conventional raise SystemExit(main()) exits before the report is collected or written. The profiling command therefore produces no profile even when the script exits successfully.

Handle SystemExit from the profiled execution, collect and write the profile, then preserve the script's exit status.

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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Script tracebacks disappear

When the trusted script raises a caught exception such as ValueError, the exception handler covers record_profile, which executes the user's script, so a script raising ValueError, RuntimeError, or OSError is reduced to a one-line CLI message and loses its traceback. The caller cannot see the script's failing frame when diagnosing a profiled workload.

Limit the handler to profile setup and input/output errors, or preserve and print the traceback for exceptions raised during script execution.

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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Included-header hotspots show wrong paths

When a profiled REPY program defines functions in included headers, _generate compiles expanded include contents with the main source path as their filename, so _project_rows labels those functions as belonging to the entry-point file and the plan directs callers to the wrong source path.

Preserve or map included-header source locations so _project_rows reports the defining file.

# 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"}:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Uppercase source files lose hotspots

When the profiled source filename uses an uppercase .REPY suffix, _generate accepts the source, but _project_rows checks Path.suffix case-sensitively and drops its frames, leaving the profile without hotspots.

Compare the suffix case-insensitively when filtering source frames.

source, compiled = _prepare_run(filename)
root = _source_root(source.parent)
profiler = cProfile.Profile()
profiler.runcall(execute_code_temporarily, compiled, source, args)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Caller profiler is removed

When record_profile is called from a thread that already has a profiling hook installed, cProfile.Profile.runcall replaces the current thread’s profile hook and clears it when finished, so the caller’s existing profiler stops receiving events after record_profile returns.

Preserve and restore the caller’s existing profile hook around the profiling run, or reject nested profiling without changing it.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant