Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

python: profile forked workers on Python 3.12+

Mohit Mishrad8c587f36c74
diff --git a/src/python.rs b/src/python.rs
index 9d53d88..90b8847 100644
--- a/src/python.rs
+++ b/src/python.rs
@@ -1834,6 +1834,19 @@ sys.exit(1 if fails else 0)
);
}
+ #[cfg(unix)]
+ #[test]
+ fn forked_pool_workers_are_profiled_and_recorded() {
+ // a forked worker starts with the parent's profiler still on (fork isn't the default
+ // everywhere: macOS and Python 3.14 use spawn or forkserver)
+ assert_workers_profiled_and_recorded(
+ "pool-fork-test",
+ "from multiprocessing import get_context\nfrom work import sq\n\nif __name__ == \"__main__\":\n\
+ \x20 with get_context(\"fork\").Pool(2) as pool:\n\
+ \x20 print(sum(pool.map(sq, range(20))))\n",
+ );
+ }
+
#[test]
fn pool_terminate_does_not_run_queued_tasks_or_hang() {
let tasks = "import pathlib, time\n\n\
diff --git a/src/python/runner.py b/src/python/runner.py
index 3af372f..5b5adcd 100644
--- a/src/python/runner.py
+++ b/src/python/runner.py
@@ -736,7 +736,7 @@ def cmd_profile(job, argv):
entry, base = prepare_path(kind, target)
root = job["root"]
prof = cProfile.Profile()
- sys.modules["_fast_anything_state"] = ChildState("profile", os.environ.get("FAST_ANYTHING_CHILDREN", ""))
+ sys.modules["_fast_anything_state"] = ChildState("profile", os.environ.get("FAST_ANYTHING_CHILDREN", ""), inherited=prof)
stopped = stop_after(job["duration"]) if job.get("duration") else None
start = time.perf_counter()
prof.enable()
@@ -880,14 +880,19 @@ class ChildState:
"""What a multiprocessing worker does while fast-anything profiles or records the app: its own
profiler or recorder, written to `out_dir` when the worker ends."""
- def __init__(self, mode, out_dir, recorder=None):
+ def __init__(self, mode, out_dir, recorder=None, inherited=None):
self.mode, self.out_dir, self.recorder, self.profiler = mode, out_dir, recorder, None
+ self.inherited = inherited # the parent's profiler, which a forked worker has a copy of
def start(self):
if self.mode == "profile":
import cProfile
- sys.setprofile(None) # a forked worker inherits the parent's profiler
+ # a forked worker inherits the parent's profiler, still on: since 3.12 it holds
+ # sys.monitoring's profiler slot, and a second one can't start until it's off
+ if self.inherited is not None:
+ self.inherited.disable()
+ sys.setprofile(None)
self.profiler = cProfile.Profile()
self.profiler.enable()
elif self.recorder is not None: