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.

node: warn when a scan attributes less than half the run to project functions

Brixton Phame80b833b4d68
diff --git a/src/node.rs b/src/node.rs
index b7abcfb..38e2645 100644
--- a/src/node.rs
+++ b/src/node.rs
@@ -3044,4 +3044,78 @@ assert.ok(!same([Number.MAX_VALUE, Infinity], [Number.MAX_VALUE, Number.MAX_VALU
.unwrap_or_else(|| panic!("missing hotspot scoreDoc; got {:?}", scanned.hotspots));
assert!(h.portable() && h.blockers.is_empty(), "scoreDoc should be portable, got {:?}", h.blockers);
}
+
+ #[test]
+ fn profile_warns_when_most_samples_land_outside_named_project_functions() {
+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no node on PATH, skipping");
+ return;
+ }
+ let dir = std::env::temp_dir().join(format!("fa-node-low-attr-{}", std::process::id()));
+ let prof = dir.join("cpuprof");
+ let _ = fs::remove_dir_all(&dir);
+ fs::create_dir_all(&prof).unwrap();
+ let app_file = dir.join("app.mjs");
+ fs::write(&app_file, "export function work(x) {\n return x + 1;\n}\n").unwrap();
+ let pkg_file = dir.join("node_modules/fast-glob/index.js");
+ fs::create_dir_all(pkg_file.parent().unwrap()).unwrap();
+ fs::write(&pkg_file, "module.exports = {};\n").unwrap();
+
+ let file_url = |p: &Path| {
+ let s = p.to_string_lossy().replace('\\', "/");
+ if s.starts_with('/') { format!("file://{s}") } else { format!("file:///{s}") }
+ };
+ let app_url = file_url(&app_file);
+ let pkg_url = file_url(&pkg_file);
+ let nodes = json!([
+ { "id": 1, "callFrame": { "functionName": "(root)", "url": "", "lineNumber": -1, "columnNumber": -1 }, "children": [2, 3, 4, 5] },
+ { "id": 2, "callFrame": { "functionName": "work", "url": app_url, "lineNumber": 0, "columnNumber": 0 }, "children": [] },
+ { "id": 3, "callFrame": { "functionName": "compile", "url": "node:vm", "lineNumber": 10, "columnNumber": 0 }, "children": [] },
+ { "id": 4, "callFrame": { "functionName": "scan", "url": pkg_url, "lineNumber": 0, "columnNumber": 0 }, "children": [] },
+ { "id": 5, "callFrame": { "functionName": "", "url": app_url, "lineNumber": 0, "columnNumber": 0 }, "children": [] }
+ ]);
+ // 200ms in app.mjs:work (20%), 500ms in node:vm (50%), 200ms in fast-glob (20%), 100ms in top-level anonymous (10%)
+ let low_prof = json!({
+ "nodes": nodes,
+ "startTime": 0,
+ "endTime": 1_000_000,
+ "samples": [2, 3, 4, 5],
+ "timeDeltas": [200_000, 500_000, 200_000, 100_000]
+ });
+ fs::write(prof.join("low.cpuprofile"), low_prof.to_string()).unwrap();
+ fs::write(dir.join("runner.mjs"), RUNNER).unwrap();
+ let result = dir.join("profile.json");
+ let job = json!({ "root": dir, "dir": prof, "entry": app_file, "out": result });
+ fs::write(dir.join("job.json"), job.to_string()).unwrap();
+ let out = Command::new("node").args(["runner.mjs", "profile", "job.json"]).current_dir(&dir).output().unwrap();
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ let parsed: Value = serde_json::from_str(&fs::read_to_string(&result).unwrap()).unwrap();
+ let notes = parsed["notes"].as_array().unwrap();
+ assert_eq!(notes.len(), 1, "expected low-attribution note, got {notes:?}");
+ let note = notes[0].as_str().unwrap();
+ assert!(
+ note.contains("only 20.0% of the profiled run landed in your own named functions")
+ && note.contains("node:vm 50%")
+ && note.contains("fast-glob 20%")
+ && note.contains("top-level / anonymous code 10%")
+ && note.contains("V8's sampling profiler doesn't count calls"),
+ "unexpected note: {note}"
+ );
+
+ // When >= 50% of the run lands in named project functions, no low-attribution warning is emitted.
+ let high_prof = json!({
+ "nodes": nodes,
+ "startTime": 0,
+ "endTime": 1_000_000,
+ "samples": [2, 3],
+ "timeDeltas": [800_000, 200_000]
+ });
+ fs::remove_file(prof.join("low.cpuprofile")).unwrap();
+ fs::write(prof.join("high.cpuprofile"), high_prof.to_string()).unwrap();
+ let out = Command::new("node").args(["runner.mjs", "profile", "job.json"]).current_dir(&dir).output().unwrap();
+ let parsed: Value = serde_json::from_str(&fs::read_to_string(&result).unwrap()).unwrap();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ assert!(parsed["notes"].as_array().unwrap().is_empty(), "expected no note when attribution is high");
+ }
}
diff --git a/src/node/runner.mjs b/src/node/runner.mjs
index 617e56a..cba47d0 100644
--- a/src/node/runner.mjs
+++ b/src/node/runner.mjs
@@ -887,6 +887,31 @@ function projectRelative(root, file) {
// ------------------------------------------------------------------ profile
+function bucketLabel(frame, root) {
+ const { url, functionName } = frame;
+ if (!url) {
+ if (functionName === "(idle)" || functionName === "(program)" || functionName === "(root)") return null;
+ if (functionName === "(garbage collector)") return "garbage collection";
+ return "V8 / native";
+ }
+ if (url.startsWith("node:") || url.startsWith("ext:") || url.startsWith("bun:")) {
+ return url.split("/")[0];
+ }
+ if (url.startsWith("file:")) {
+ try {
+ const file = fileURLToPath(url);
+ const rel = path.relative(root, file).split(path.sep);
+ const nm = rel.indexOf("node_modules");
+ if (nm >= 0 && nm + 1 < rel.length) {
+ const pkg = rel[nm + 1];
+ return pkg.startsWith("@") && nm + 2 < rel.length ? `${pkg}/${rel[nm + 2]}` : pkg;
+ }
+ if (!functionName) return "top-level / anonymous code";
+ } catch {}
+ }
+ return null;
+}
+
function profile(job) {
const names = readdirSync(job.dir).filter((f) => f.endsWith(".cpuprofile"));
if (!names.length) throw new Error("the runtime wrote no .cpuprofile (Bun and Deno need a version with --cpu-prof)");
@@ -894,7 +919,9 @@ function profile(job) {
// the longest one, the main thread's.
const key = (n) => `${n.callFrame.url}:${n.callFrame.lineNumber}:${n.callFrame.columnNumber}:${n.callFrame.functionName}`;
const funcs = new Map();
+ const outside = new Map();
let total = 0;
+ let activeUs = 0;
for (const name of names) {
const prof = JSON.parse(readFileSync(path.join(job.dir, name), "utf8"));
total = Math.max(total, (prof.endTime - prof.startTime) / 1e6);
@@ -906,7 +933,20 @@ function profile(job) {
for (const n of prof.nodes) if (!funcs.has(key(n))) funcs.set(key(n), { frame: n.callFrame, self: 0, cum: 0 });
for (const [id, us] of selfUs) {
let node = byId.get(id);
+ if (!node || us <= 0) continue;
+ const fnName = node.callFrame.functionName;
+ if (fnName !== "(idle)" && fnName !== "(root)") activeUs += us;
funcs.get(key(node)).self += us;
+ const { url, functionName } = node.callFrame;
+ const inProject =
+ functionName &&
+ url &&
+ url.startsWith("file:") &&
+ projectRelative(job.root, fileURLToPath(url)) !== null;
+ if (!inProject) {
+ const label = bucketLabel(node.callFrame, job.root);
+ if (label) outside.set(label, (outside.get(label) || 0) + us);
+ }
const seen = new Set();
while (node) {
const k = key(node);
@@ -934,7 +974,21 @@ function profile(job) {
if (info)
functions.push({ ...info, file: r.rel.split(path.sep).join("/"), line: r.line0 + 1, name: r.name, ncalls: 0, tottime: r.self, cumtime: r.cum });
}
- writeFileSync(job.out, JSON.stringify({ wall: total, base: ".", functions }));
+ const notes = [];
+ const attributedSelf = functions.reduce((a, f) => a + f.tottime, 0);
+ const denom = Math.max(total, activeUs / 1e6);
+ const share = denom > 0 ? Math.min(1, attributedSelf / denom) : 0;
+ if (denom > 0 && share < 0.5) {
+ const top = [...outside.entries()]
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
+ .slice(0, 3)
+ .map(([l, us]) => `${l} ${Math.round((us / 1e6 / denom) * 100)}%`);
+ const where = top.length ? ` (the rest went to ${top.join(", ")})` : "";
+ notes.push(
+ `only ${(share * 100).toFixed(1)}% of the profiled run landed in your own named functions${where}; V8's sampling profiler doesn't count calls`,
+ );
+ }
+ writeFileSync(job.out, JSON.stringify({ wall: total, base: ".", functions, notes }));
}
// ------------------------------------------------------------------ verify