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.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
python: profile and record inside multiprocessing workers (#51)
chessMance0e3889e774
diff --git a/src/python.rs b/src/python.rsindex 3caf1d9..c56e3db 100644--- a/src/python.rs+++ b/src/python.rs@@ -12,6 +12,7 @@ use std::path::{Path, PathBuf};use std::process::{Command, Output, Stdio};const RUNNER: &str = include_str!("python/runner.py");+const HOOK: &str = include_str!("python/sitecustomize.py");const PYO3: &str = "0.30";/// rust-numpy, for NDArray parameters and results; its versions follow PyO3's.const NUMPY: &str = "0.30";@@ -85,25 +86,47 @@ fn helper(ctx: &Ctx, python: &str, mode: &str, job: Value, app_args: &[String])fs::write(&runner, RUNNER)?;let job_path = ctx.fast.join(format!("job-{mode}.json"));fs::write(&job_path, serde_json::to_vec_pretty(&job)?)?;- let out = output(- Command::new(python)- .arg(&runner)- .arg(mode)- .arg(&job_path)- .arg("--")- .args(app_args)- .current_dir(&ctx.root)- .env("PYTHONIOENCODING", "utf-8")- .env("PYTHONUTF8", "1")- .stdin(Stdio::null()),- "python",- )?;+ let mut cmd = Command::new(python);+ cmd.arg(&runner)+ .arg(mode)+ .arg(&job_path)+ .arg("--")+ .args(app_args)+ .current_dir(&ctx.root)+ .env("PYTHONIOENCODING", "utf-8")+ .env("PYTHONUTF8", "1")+ .stdin(Stdio::null());+ if mode != "verify" {+ watch_workers(ctx, &mut cmd, &runner, &job_path, mode)?;+ }+ let out = output(&mut cmd, "python")?;if !out.status.success() {bail!("the python {mode} run failed ({}):\n{}", out.status, tail(&combined(&out), 30));}Ok(out)}+/// Let the app's multiprocessing workers profile or record too: a sitecustomize first on PYTHONPATH+/// wraps each worker (see python/sitecustomize.py), which leaves its results in .fast/children.+fn watch_workers(ctx: &Ctx, cmd: &mut Command, runner: &Path, job: &Path, mode: &str) -> Result<()> {+ let hook = ctx.fast.join("hook");+ fs::create_dir_all(&hook)?;+ fs::write(hook.join("sitecustomize.py"), HOOK)?;+ let children = ctx.fast.join("children");+ let _ = fs::remove_dir_all(&children);+ fs::create_dir_all(&children)?;+ let mut paths = vec![hook];+ if let Some(existing) = std::env::var_os("PYTHONPATH") {+ paths.extend(std::env::split_paths(&existing));+ }+ cmd.env("PYTHONPATH", std::env::join_paths(paths)?)+ .env("FAST_ANYTHING_CHILDREN", &children)+ .env("FAST_ANYTHING_RUNNER", runner)+ .env("FAST_ANYTHING_JOB", job)+ .env("FAST_ANYTHING_MODE", mode);+ Ok(())+}+pub fn profile(ctx: &Ctx, python: &str, app_args: &[String]) -> Result<Profile> {let out = ctx.fast.join("profile.json");helper(ctx, python, "profile", json!({ "root": ctx.root, "out": out, "max": 40 }), app_args)?;@@ -1129,4 +1152,70 @@ mod tests {assert!(is_python("py"));assert!(!is_python("node"));}++ #[test]+ fn workers_are_profiled_and_recorded() {+ let Some(python) = ["python3", "python"]+ .into_iter()+ .find(|p| Command::new(p).arg("--version").output().is_ok_and(|o| o.status.success()))+ else {+ eprintln!("no python on PATH, skipping");+ return;+ };+ // macOS's temp folder is a symlink and Python reports the files' real paths; on Windows,+ // canonicalize() would give a \\?\ path Python doesn't use+ let tmp = std::env::temp_dir();+ let tmp = if cfg!(windows) { tmp } else { tmp.canonicalize().unwrap() };+ let dir = tmp.join(format!("fa-workers-test-{}", std::process::id()));+ let (hook, children) = (dir.join("hook"), dir.join("children"));+ fs::create_dir_all(&hook).unwrap();+ fs::create_dir_all(&children).unwrap();+ fs::write(hook.join("sitecustomize.py"), HOOK).unwrap();+ fs::write(dir.join("runner.py"), RUNNER).unwrap();+ fs::write(dir.join("work.py"), "def sq(x: int) -> int:\n return x * x\n").unwrap();+ fs::write(+ dir.join("app.py"),+ "from concurrent.futures import ProcessPoolExecutor\nfrom multiprocessing import get_context\n\+ from work import sq\n\nif __name__ == \"__main__\":\n\+ \x20 with ProcessPoolExecutor(2, mp_context=get_context(\"spawn\")) as pool:\n\+ \x20 print(sum(pool.map(sq, range(20))))\n",+ )+ .unwrap();+ let run = |mode: &str, job: Value| {+ let job_path = dir.join(format!("job-{mode}.json"));+ fs::write(&job_path, job.to_string()).unwrap();+ let _ = fs::remove_dir_all(&children);+ fs::create_dir_all(&children).unwrap();+ let out = Command::new(python)+ .args([+ dir.join("runner.py").as_os_str(),+ mode.as_ref(),+ job_path.as_os_str(),+ "--".as_ref(),+ "app.py".as_ref(),+ ])+ .current_dir(&dir)+ .env("PYTHONPATH", &hook)+ .env("FAST_ANYTHING_CHILDREN", &children)+ .env("FAST_ANYTHING_RUNNER", dir.join("runner.py"))+ .env("FAST_ANYTHING_JOB", &job_path)+ .env("FAST_ANYTHING_MODE", mode)+ .output()+ .unwrap();+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));+ };+ run("profile", json!({ "root": dir, "out": dir.join("profile.json"), "max": 40 }));+ let profile: Value = serde_json::from_str(&fs::read_to_string(dir.join("profile.json")).unwrap()).unwrap();+ let sq = profile["functions"].as_array().unwrap().iter().find(|f| f["name"] == "sq").cloned();+ run(+ "record",+ json!({ "module": "work", "func": "sq", "owner": null, "limit": 500,+ "out": dir.join("rec.jsonl"), "meta": dir.join("rec.meta.json") }),+ );+ let meta: Value = serde_json::from_str(&fs::read_to_string(dir.join("rec.meta.json")).unwrap()).unwrap();+ let recorded = fs::read_to_string(dir.join("rec.jsonl")).unwrap().lines().count();+ let _ = fs::remove_dir_all(&dir);+ assert_eq!(sq.map(|f| f["ncalls"].clone()), Some(json!(20)), "sq ran 20 times in the workers");+ assert_eq!((meta["calls"].clone(), recorded), (json!(20), 20));+ }}diff --git a/src/python/runner.py b/src/python/runner.pyindex 86d056d..54caa63 100644--- a/src/python/runner.py+++ b/src/python/runner.py@@ -448,6 +448,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", ""))start = time.perf_counter()prof.enable()try:@@ -455,9 +456,16 @@ def cmd_profile(job, argv):finally:prof.disable()wall = time.perf_counter() - start+ del sys.modules["_fast_anything_state"]+ stats = pstats.Stats(prof)+ for worker in children(".prof"): # what the app's multiprocessing workers ran+ try:+ stats.add(worker)+ except (EOFError, ValueError, TypeError, OSError):+ pass # a worker that died before it finished writingrows = []- for (path, line, name), (_cc, ncalls, tottime, cumtime, _callers) in pstats.Stats(prof).stats.items():+ for (path, line, name), (_cc, ncalls, tottime, cumtime, _callers) in stats.stats.items():if name.startswith("<") or not path or path.startswith("<"):continuerel = project_relative(root, path)@@ -482,74 +490,170 @@ def cmd_profile(job, argv):json.dump({"wall": wall, "base": base_rel, "functions": functions}, f)-def cmd_record(job, argv):- kind, target, rest = parse_target(argv)- prepare_path(kind, target)- os.environ[DISABLE_ENV] = "1" # always record the original Python- limit = int(job["limit"])- rng = random.Random(0xFA57)- kept = []- stats = {"calls": 0, "skipped": 0, "unsupported": set()}+class Recorder:+ """Keeps a uniform sample of up to `limit` calls to the wrapped function (reservoir sampling)."""- def store(slot, case):- if len(kept) < limit:- kept.append(case)+ def __init__(self, limit, seed):+ self.limit, self.rng = limit, random.Random(seed)+ self.reset()++ def reset(self):+ self.kept, self.calls, self.skipped, self.unsupported, self.mutates = [], 0, 0, set(), False++ def store(self, slot, case):+ if len(self.kept) < self.limit:+ self.kept.append(case)else:- kept[slot % limit] = case+ self.kept[slot % self.limit] = case- def wrap(original):+ def wrap(self, original):@functools.wraps(original)def recorder(*args, **kwargs):- stats["calls"] += 1- slot = len(kept) if len(kept) < limit else rng.randrange(stats["calls"])+ self.calls += 1+ slot = len(self.kept) if len(self.kept) < self.limit else self.rng.randrange(self.calls)case = None- if slot < limit:+ if slot < self.limit:try: # encode before the call, in case the function mutates its argumentscase = {"args": enc(list(args)), "kwargs": {k: enc(v) for k, v in kwargs.items()}}except Unsupported as e:- stats["skipped"] += 1- stats["unsupported"].add(str(e))+ self.skipped += 1+ self.unsupported.add(str(e))try:result = original(*args, **kwargs)except Exception as e:if case is not None:case["raises"] = type(e).__name__- store(slot, case)+ self.store(slot, case)raiseif case is not None:try:if enc(list(args)) != case["args"] or {k: enc(v) for k, v in kwargs.items()} != case["kwargs"]:- stats["mutates"] = True+ self.mutates = Trueexcept Unsupported:passtry:case["result"] = enc(result)- store(slot, case)+ self.store(slot, case)except Unsupported as e:- stats["skipped"] += 1- stats["unsupported"].add(str(e))+ self.skipped += 1+ self.unsupported.add(str(e))return resultreturn recorder- if job["module"] == "__main__":- # the entry script wraps the function itself, via a block fast-anything inserted- import builtins+ def install(self, job, main_module=None):+ """Wrap the function where the app looks it up."""+ if job["module"] == "__main__":+ # the entry script wraps the function itself, via a block fast-anything inserted+ import builtins- builtins.__fast_anything_wrap__ = wrap- else:- module = importlib.import_module(job["module"])+ builtins.__fast_anything_wrap__ = self.wrap+ if main_module is None:+ return+ module = main_module # a spawned worker: the entry script is already imported+ else:+ module = importlib.import_module(job["module"])owner = getattr(module, job["owner"]) if job.get("owner") else module- wrapped = wrap(getattr(owner, job["func"]))- setattr(owner, job["func"], staticmethod(wrapped) if job.get("owner") else wrapped)- run_target(kind, target, rest)+ original = getattr(owner, job["func"])+ if not hasattr(original, "__wrapped__"):+ wrapped = self.wrap(original)+ setattr(owner, job["func"], staticmethod(wrapped) if job.get("owner") else wrapped)++ def write(self, out, meta):+ with open(out, "w", encoding="utf-8") as f:+ for case in self.kept:+ f.write(json.dumps(case, ensure_ascii=False) + "\n")+ with open(meta, "w", encoding="utf-8") as f:+ json.dump({"calls": self.calls, "kept": len(self.kept), "skipped": self.skipped,+ "unsupported": sorted(self.unsupported), "mutates": self.mutates}, f)++ def absorb(self, out, meta):+ """Add what a worker recorded, keeping at most `limit` calls, sampled across all processes."""+ with open(meta, encoding="utf-8") as f:+ m = json.load(f)+ with open(out, encoding="utf-8") as f:+ cases = [json.loads(line) for line in f if line.strip()]+ self.calls += m["calls"]+ self.skipped += m["skipped"]+ self.unsupported.update(m["unsupported"])+ self.mutates = self.mutates or m["mutates"]+ self.kept += cases+ if len(self.kept) > self.limit:+ self.kept = self.rng.sample(self.kept, self.limit)+++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):+ self.mode, self.out_dir, self.recorder, self.profiler = mode, out_dir, recorder, None++ def start(self):+ if self.mode == "profile":+ import cProfile++ sys.setprofile(None) # a forked worker inherits the parent's profiler+ self.profiler = cProfile.Profile()+ self.profiler.enable()+ elif self.recorder is not None:+ self.recorder.reset() # a forked worker inherits the parent's calls so far++ def finish(self):+ if os.name == "posix":+ import signal++ signal.signal(signal.SIGTERM, signal.SIG_IGN) # don't stop halfway through writing+ base = os.path.join(self.out_dir, str(os.getpid()))+ # written under a temporary name, then renamed, so the parent never reads half a file+ if self.profiler is not None:+ self.profiler.disable()+ self.profiler.dump_stats(base + ".tmp")+ os.replace(base + ".tmp", base + ".prof")+ elif self.recorder is not None:+ self.recorder.write(base + ".tmp", base + ".meta.tmp")+ os.replace(base + ".tmp", base + ".jsonl")+ os.replace(base + ".meta.tmp", base + ".meta.json")+++def child_state():+ """The ChildState for a worker started as a fresh interpreter (spawn, forkserver)."""+ with open(os.environ["FAST_ANYTHING_JOB"], encoding="utf-8") as f:+ job = json.load(f)+ mode, out_dir = os.environ["FAST_ANYTHING_MODE"], os.environ["FAST_ANYTHING_CHILDREN"]+ recorder = None+ if mode == "record":+ os.environ[DISABLE_ENV] = "1"+ recorder = Recorder(int(job["limit"]), os.getpid())+ recorder.install(job, sys.modules.get("__main__"))+ state = ChildState(mode, out_dir, recorder)+ sys.modules["_fast_anything_state"] = state+ return state+++def children(suffix):+ """Files the app's multiprocessing workers left (see ChildState)."""+ out_dir = os.environ.get("FAST_ANYTHING_CHILDREN")+ if not out_dir or not os.path.isdir(out_dir):+ return []+ return sorted(os.path.join(out_dir, n) for n in os.listdir(out_dir) if n.endswith(suffix))- with open(job["out"], "w", encoding="utf-8") as f:- for case in kept:- f.write(json.dumps(case, ensure_ascii=False) + "\n")- with open(job["meta"], "w", encoding="utf-8") as f:- json.dump({"calls": stats["calls"], "kept": len(kept), "skipped": stats["skipped"],- "unsupported": sorted(stats["unsupported"]), "mutates": stats.get("mutates", False)}, f)++def cmd_record(job, argv):+ kind, target, rest = parse_target(argv)+ prepare_path(kind, target)+ os.environ[DISABLE_ENV] = "1" # always record the original Python+ recorder = Recorder(int(job["limit"]), 0xFA57)+ recorder.install(job)+ sys.modules["_fast_anything_state"] = ChildState("record", os.environ.get("FAST_ANYTHING_CHILDREN", ""), recorder)+ run_target(kind, target, rest)+ del sys.modules["_fast_anything_state"]+ for out in children(".jsonl"):+ try:+ recorder.absorb(out, out[: -len(".jsonl")] + ".meta.json")+ except (OSError, ValueError, KeyError):+ pass # a worker that died before it finished writing+ recorder.write(job["out"], job["meta"])def cmd_verify(job, _argv):diff --git a/src/python/sitecustomize.py b/src/python/sitecustomize.pynew file mode 100644index 0000000..97b9191--- /dev/null+++ b/src/python/sitecustomize.py@@ -0,0 +1,65 @@+"""fast-anything: profile and record inside multiprocessing workers too.++While fast-anything profiles or records an app, it puts the folder with this file first on+PYTHONPATH, so every Python process the app starts loads it. Not meant to be used by hand.+Each multiprocessing worker (fork, spawn or forkserver; Pool and ProcessPoolExecutor included)+gets its own profiler or recorder and leaves its results in FAST_ANYTHING_CHILDREN. The app's own+sitecustomize, if it has one, still runs right after this.+"""++import os+import sys+++def _fast_anything_watch_workers():+ import multiprocessing.process++ original = multiprocessing.process.BaseProcess._bootstrap+ if getattr(original, "_fast_anything", False):+ return++ def _bootstrap(self, *args, **kwargs):+ if os.name == "posix":+ # Pool.terminate() (and with Pool(...) as p) ends workers with SIGTERM: exit normally+ # instead, so the worker still leaves its results. Set first, before anything slow.+ import signal++ signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))+ state = None+ try:+ state = sys.modules.get("_fast_anything_state")+ if state is None: # a fresh interpreter (spawn, forkserver): load the runner+ import importlib.util++ spec = importlib.util.spec_from_file_location("_fast_anything_runner", os.environ["FAST_ANYTHING_RUNNER"])+ runner = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(runner)+ state = runner.child_state()+ state.start()+ except Exception as e: # never break the app's workers+ sys.stderr.write("fast-anything: can't watch this worker: %r\n" % (e,))+ state = None+ try:+ return original(self, *args, **kwargs)+ finally:+ if state is not None:+ state.finish()++ _bootstrap._fast_anything = True+ multiprocessing.process.BaseProcess._bootstrap = _bootstrap+++def _fast_anything_chain():+ """Run the sitecustomize this one hides, if there is one."""+ import importlib.util+ from importlib.machinery import PathFinder++ here = os.path.dirname(os.path.abspath(__file__))+ spec = PathFinder.find_spec("sitecustomize", [p for p in sys.path if os.path.abspath(p or ".") != here])+ if spec is not None and spec.loader is not None:+ spec.loader.exec_module(importlib.util.module_from_spec(spec))+++if os.environ.get("FAST_ANYTHING_CHILDREN"):+ _fast_anything_watch_workers()+_fast_anything_chain()diff --git a/src/state.rs b/src/state.rsindex 81c189e..7c3a6ae 100644--- a/src/state.rs+++ b/src/state.rs@@ -11,7 +11,7 @@ use std::fs;use std::path::{Path, PathBuf};const GITIGNORE: &str = "# fast-anything: commit ports/*/src and Cargo.toml (your Rust ports); skip the rest\n\-target/\nlib/\nbin/\nbackup/\nrunner.*\nrecorder.*\nDescribe.java\n*.txt\njob-*.json\nprofile.*\n*.pprof\nverify.json\n*.jsonl\n*.meta.json\n*.log\n";+target/\nlib/\nbin/\nbackup/\nhook/\nchildren/\nrunner.*\nrecorder.*\nDescribe.java\n*.txt\njob-*.json\nprofile.*\n*.pprof\nverify.json\n*.jsonl\n*.meta.json\n*.log\n";#[derive(Debug, Clone, Default, Serialize, Deserialize)]#[serde(default)]