From 6be20301cd7880f05fe69f8cbfe58f533c808e04 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 12:06:38 +0000 Subject: [PATCH 1/2] feat: a sampling CPU profile of the run, with the cpu-profile feature Moved from instagram-rs. `cpu_profile::start_from_env` (`PROFILE_CPU=1`) or `cpu_profile::start` profiles every thread with pprof; `cpu_profile::save` writes a flamegraph (`CPU_PROFILE.svg`) and a pprof profile (`CPU_PROFILE.pb`) to the default key-value store and logs the share of each group of crates and the top functions by self time. The Actor names its own crate, which is a group of its own. Linux only, behind the `cpu-profile` feature; CI checks and tests it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0148RYR4BTGyCYHENSRZjC3S --- .github/workflows/ci.yml | 2 + Cargo.lock | 474 +++++++++++++++++++++- Cargo.toml | 6 + README.md | 1 + src/cpu_profile.rs | 829 +++++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 + 6 files changed, 1305 insertions(+), 9 deletions(-) create mode 100644 src/cpu_profile.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8b572e8..366a512 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,8 @@ jobs: - uses: Swatinem/rust-cache@v2 - run: cargo fmt --check - run: cargo clippy --all-targets + - run: cargo clippy --all-targets --features cpu-profile + - run: cargo test --lib --features cpu-profile cpu_profile - run: cargo test msrv: diff --git a/Cargo.lock b/Cargo.lock index eb74a6d..4572004 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "addr2line" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e567177890eb1617b1f774005b66b26b2377afd138a2ca37aae7d8f0c81429d4" +dependencies = [ + "gimli 0.34.0", +] + [[package]] name = "adler2" version = "2.0.1" @@ -43,6 +52,19 @@ dependencies = [ "subtle", ] +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "aho-corasick" version = "1.1.5" @@ -52,6 +74,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + [[package]] name = "alloc-no-stdlib" version = "2.0.4" @@ -114,6 +145,7 @@ dependencies = [ "async-trait", "aws-lc-rs", "axum", + "backtrace", "base64 0.22.1", "bytes", "cbc", @@ -125,6 +157,7 @@ dependencies = [ "lru", "md-5", "parking_lot", + "pprof", "rand 0.9.5", "regex", "reqwest 0.13.5", @@ -163,6 +196,12 @@ dependencies = [ "url", ] +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + [[package]] name = "async-compression" version = "0.4.50" @@ -274,6 +313,21 @@ dependencies = [ "tracing", ] +[[package]] +name = "backtrace" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f4220217f3288537b83684130f42fad43320b1c3b805f1910d683d52ded24f" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object 0.40.0", + "rustc-demangle", + "windows-link", +] + [[package]] name = "base64" version = "0.22.1" @@ -286,6 +340,12 @@ version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.2" @@ -368,6 +428,12 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + [[package]] name = "bytes" version = "1.12.1" @@ -689,7 +755,7 @@ dependencies = [ "globset", "lol_html", "psl", - "quick-xml", + "quick-xml 0.42.0", "regex", "serde", "thiserror", @@ -779,6 +845,15 @@ version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" +[[package]] +name = "debugid" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" +dependencies = [ + "uuid", +] + [[package]] name = "deranged" version = "0.5.8" @@ -873,6 +948,12 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b04dc5a38e4f151a79d9f2451ae6037fb6eaf5cba34771f44781f80e508498e3" +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + [[package]] name = "encoding_rs" version = "0.8.42" @@ -887,6 +968,26 @@ dependencies = [ "simdutf8", ] +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -903,6 +1004,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + [[package]] name = "fastrand" version = "2.5.0" @@ -915,6 +1022,24 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "findshlibs" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40b9e59cd0f7e0806cca4be089683ecb6434e602038df21fe6bf6711b2f07f64" +dependencies = [ + "cc", + "lazy_static", + "libc", + "winapi", +] + +[[package]] +name = "fixedbitset" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" + [[package]] name = "flate2" version = "1.1.10" @@ -947,6 +1072,20 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "framehop" +version = "0.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09a5a3f0acb82df800ca3aa50c0d60d286c5d13d4cfc3114b3a9663f13b032fe" +dependencies = [ + "arrayvec", + "cfg-if", + "fallible-iterator", + "gimli 0.31.1", + "macho-unwind-info", + "pe-unwind-info", +] + [[package]] name = "fs_extra" version = "1.3.0" @@ -1109,6 +1248,22 @@ dependencies = [ "polyval", ] +[[package]] +name = "gimli" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f" +dependencies = [ + "fallible-iterator", + "stable_deref_trait", +] + +[[package]] +name = "gimli" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10" + [[package]] name = "globset" version = "0.4.20" @@ -1163,6 +1318,18 @@ dependencies = [ "foldhash", ] +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + [[package]] name = "hmac" version = "0.12.1" @@ -1428,6 +1595,24 @@ dependencies = [ "serde_core", ] +[[package]] +name = "inferno" +version = "0.11.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "232929e1d75fe899576a3d5c7416ad0d88dbfbb3c3d6aa00873a7408a50ddb88" +dependencies = [ + "ahash", + "indexmap", + "is-terminal", + "itoa", + "log", + "num-format", + "once_cell", + "quick-xml 0.26.0", + "rgb", + "str_stack", +] + [[package]] name = "inout" version = "0.1.4" @@ -1444,6 +1629,26 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[package]] +name = "is-terminal" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" +dependencies = [ + "hermit-abi", + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" @@ -1571,7 +1776,7 @@ version = "3.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5adbb62638edf7e6bc88835cd3ea388bdd53382af42045da0e414ea78aa0c91a" dependencies = [ - "bitflags", + "bitflags 2.13.2", "cfg-if", "cssparser 0.36.0", "encoding_rs", @@ -1599,6 +1804,17 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" +[[package]] +name = "macho-unwind-info" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4bdc8b0ce69932332cf76d24af69c3a155242af95c226b2ab6c2e371ed1149" +dependencies = [ + "thiserror", + "zerocopy", + "zerocopy-derive", +] + [[package]] name = "markup5ever" version = "0.39.0" @@ -1632,6 +1848,24 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memmap2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83faa42c0a078c393f6b29d5db232d8be22776a891f8f56e5284faee4a20b327" +dependencies = [ + "libc", +] + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + [[package]] name = "mime" version = "0.3.17" @@ -1659,6 +1893,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "multimap" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" + [[package]] name = "multiversion_no_op" version = "1.0.0" @@ -1671,6 +1911,17 @@ version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" +[[package]] +name = "nix" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "libc", +] + [[package]] name = "ntapi" version = "0.4.3" @@ -1695,6 +1946,16 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-format" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a652d9771a63711fd3c3deb670acfbe5c30a4072e664d7a3bf5a9e1056ac72c3" +dependencies = [ + "arrayvec", + "itoa", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -1710,7 +1971,7 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" dependencies = [ - "bitflags", + "bitflags 2.13.2", ] [[package]] @@ -1723,6 +1984,25 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "object" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21158b2c33aa6d4561f1c0a6ea283ca92bc54802a93b263e910746d679a7eb53" +dependencies = [ + "flate2", + "memchr", +] + +[[package]] +name = "object" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -1764,12 +2044,35 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pe-unwind-info" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "500fa4cdeacd98997c5865e3d0d1cb8fe7e9d7d75ecc775e07989a433a9a9a59" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "thiserror", + "zerocopy", + "zerocopy-derive", +] + [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "petgraph" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" +dependencies = [ + "fixedbitset", + "indexmap", +] + [[package]] name = "phf" version = "0.13.1" @@ -1862,6 +2165,35 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +[[package]] +name = "pprof" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a01da47675efa7673b032bf8efd8214f1917d89685e07e395ab125ea42b187" +dependencies = [ + "aligned-vec", + "backtrace", + "cfg-if", + "findshlibs", + "framehop", + "inferno", + "libc", + "log", + "memmap2 0.5.10", + "nix", + "object 0.29.0", + "once_cell", + "prost", + "prost-build", + "prost-derive", + "sha2", + "smallvec", + "spin", + "symbolic-demangle", + "tempfile", + "thiserror", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1877,6 +2209,16 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -1886,6 +2228,59 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "prost" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "deb1435c188b76130da55f17a466d252ff7b1418b2ad3e037d127b94e3411f29" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-build" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4" +dependencies = [ + "bytes", + "heck", + "itertools", + "log", + "multimap", + "once_cell", + "petgraph", + "prettyplease", + "prost", + "prost-types", + "regex", + "syn 2.0.119", + "tempfile", +] + +[[package]] +name = "prost-derive" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81bddcdb20abf9501610992b6759a4c888aef7d1a7247ef75e2404275ac24af1" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "prost-types" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9091c90b0a32608e984ff2fa4091273cbdd755d54935c51d520887f4a1dbd5b0" +dependencies = [ + "prost", +] + [[package]] name = "psl" version = "2.1.238" @@ -1911,6 +2306,15 @@ dependencies = [ "psl-types", ] +[[package]] +name = "quick-xml" +version = "0.26.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f50b1c63b38611e7d4d7f68b82d3ad0cc71a2ad2e7f61fc10f1328d917c93cd" +dependencies = [ + "memchr", +] + [[package]] name = "quick-xml" version = "0.42.0" @@ -2068,7 +2472,7 @@ version = "0.5.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" dependencies = [ - "bitflags", + "bitflags 2.13.2", ] [[package]] @@ -2171,6 +2575,15 @@ dependencies = [ "web-sys", ] +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + [[package]] name = "ring" version = "0.17.14" @@ -2185,6 +2598,12 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + [[package]] name = "rustc-hash" version = "2.1.3" @@ -2206,7 +2625,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" dependencies = [ - "bitflags", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys", @@ -2345,7 +2764,7 @@ version = "3.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" dependencies = [ - "bitflags", + "bitflags 2.13.2", "core-foundation", "core-foundation-sys", "libc", @@ -2368,7 +2787,7 @@ version = "0.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2cfaaa6035167f0e604e42723c7650d59ee269ef220d7bbe0565602c8a0173b9" dependencies = [ - "bitflags", + "bitflags 2.13.2", "cssparser 0.36.0", "derive_more", "log", @@ -2387,7 +2806,7 @@ version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d" dependencies = [ - "bitflags", + "bitflags 2.13.2", "cssparser 0.37.0", "derive_more", "log", @@ -2579,12 +2998,27 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spin" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" +dependencies = [ + "lock_api", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" +[[package]] +name = "str_stack" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f446288b699d66d0fd2e30d1cfe7869194312524b3b9252594868ed26ef056a" + [[package]] name = "string_cache" version = "0.9.0" @@ -2615,6 +3049,28 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" +[[package]] +name = "symbolic-common" +version = "12.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "332615d90111d8eeaf86a84dc9bbe9f65d0d8c5cf11b4caccedc37754eb0dcfd" +dependencies = [ + "debugid", + "memmap2 0.9.12", + "stable_deref_trait", + "uuid", +] + +[[package]] +name = "symbolic-demangle" +version = "12.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "912017718eb4d21930546245af9a3475c9dccf15675a5c215664e76621afc471" +dependencies = [ + "rustc-demangle", + "symbolic-common", +] + [[package]] name = "syn" version = "2.0.119" @@ -2859,7 +3315,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ "async-compression", - "bitflags", + "bitflags 2.13.2", "bytes", "futures-core", "futures-util", diff --git a/Cargo.toml b/Cargo.toml index 808cf5a..a952aa7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ aes-gcm = "0.10" anyhow = "1" async-trait = "0.1" aws-lc-rs = "1" +backtrace = { version = "0.3", optional = true } base64 = "0.22" bytes = "1" cbc = "0.1" @@ -30,6 +31,7 @@ futures-util = { version = "0.3", default-features = false, features = ["sink", indexmap = "2" lru = "0.16" md-5 = "0.10" +pprof = { version = "0.15", default-features = false, features = ["flamegraph", "framehop-unwinder", "prost-codec"], optional = true } parking_lot = "0.12" rand = "0.9" regex = "1" @@ -43,6 +45,10 @@ tokio-tungstenite = { version = "0.28", default-features = false, features = ["c tracing = "0.1" url = "2" +[features] +# A sampling CPU profile of the run, saved to the default key-value store (`cpu_profile`, Linux). +cpu-profile = ["dep:pprof", "dep:backtrace"] + [dev-dependencies] axum = "0.8" tempfile = "3" diff --git a/README.md b/README.md index e938c47..de13784 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ input schema. Copy it and `apify push`. | **Platform API** | `call` (the run's log redirected into this one's), `start`, `call_task`, `start_task`, `resurrect`, `abort`, `metamorph`, `add_webhook`, `set_status_message` (crawler status forwarded), `get_env`, `use_state`; named child runs (`run_name`, `child_runs`) that survive a migration or resurrection | | **Proxy** | Apify Proxy (groups, country, password from the account, access check) and custom proxies, for crawlers | | **Charging** | Pay-per-event: budget limits, the `apify-default-dataset-item` event charged as items are stored, `push_data_and_charge`, the local charging log | +| **CPU profile** | With the `cpu-profile` feature (Linux): a sampling profile of every thread (`PROFILE_CPU=1`, or `cpu_profile::start`), saved as a flamegraph and a pprof file to the default key-value store, with the share of each group of crates in the log | | **URL filters** | Globs and pseudo-URLs with request options, as Actor inputs send them | | **Autoscaling** | Platform system info drives the CPU and memory signals. Rate-limited API calls are counted by attempt as in the JS client (`ApifyStorageBackend::rate_limits`) but, as in the JS SDK, not reported to the storage load signal | diff --git a/src/cpu_profile.rs b/src/cpu_profile.rs new file mode 100644 index 0000000..79c8b3e --- /dev/null +++ b/src/cpu_profile.rs @@ -0,0 +1,829 @@ +//! A sampling CPU profile of the run, for finding where the CPU time goes (HTTP, TLS, parsing, +//! extraction...), with the `cpu-profile` feature (Linux). [`start_from_env`] starts it at the +//! start of the process when `PROFILE_CPU=1`, and [`start`] from anywhere (when the Actor's input +//! asks for it, say); [`save`] at the end of the run saves it. `PROFILE_CPU_HZ` sets the sampling +//! frequency (997 by default, an upper bound: the kernel's scheduler tick, often 250 Hz, limits +//! it). +//! +//! At the end of the run, the default key-value store gets: +//! - `CPU_PROFILE.svg`: a flamegraph of all threads, to open in a browser. +//! - `CPU_PROFILE.pb`: the profile in pprof's format, for `go tool pprof` or https://pprof.me. +//! +//! The log gets the share of the samples of each group of crates (TLS, HTTP, decompression, JSON, +//! HTML, the Actor's own crate...) and the functions with the most samples of their own (self time). +//! +//! The stacks are unwound from the unwind tables (`.eh_frame`) without allocating, so that taking +//! a sample is safe in a signal handler, and named from the symbol table: functions inlined into +//! another count as part of it. The release build has no debug info, whose parsing at the end of +//! the run would need more memory than the smallest runs have; for inlined functions, profile a +//! build with debug info locally. +//! +//! The profiler keeps every distinct stack of every thread with its full depth, which grows +//! without bound in a long run. So every [`FLUSH_INTERVAL`] its stacks move to [`Stacks`], which +//! keeps a code address once, merges threads of the same name and names each address once, and +//! the profiler starts over. + +use std::collections::{BTreeSet, HashMap}; +use std::time::{Duration, SystemTime}; + +use bytes::Bytes; +use crawlee::{KeyValueStore, StorageIdentifier}; +use pprof::protos::Message; + +use crate::Actor; + +/// Samples are taken per CPU time, not wall time, and a run mostly waits on the network: 99 Hz +/// leaves a short run with too few samples. 997 rather than 1000 not to sample in lockstep with +/// periodic work. +const DEFAULT_FREQUENCY_HZ: i32 = 997; +const FLUSH_INTERVAL: Duration = Duration::from_secs(15); +/// The flamegraph folds call paths with a smaller share of the samples into their caller: they +/// would be too narrow to see, and a long run has many. +const MIN_FLAMEGRAPH_SHARE: f64 = 0.0005; +/// How many functions the log lists by self time. +const TOP_FUNCTIONS: usize = 20; +/// How many crates the log names in each group. +const CRATES_PER_GROUP: usize = 4; + +struct Profiler { + /// The Actor's own crate, a group of its own. + actor_crate: String, + /// `None` when restarting it failed: the stacks so far are still saved. + guard: Option>, + frequency: i32, + started: SystemTime, + cpu_time_at_start: Option, + stacks: Stacks, +} + +/// The running profile, saved by [`save`] at the end of the run. +static PROFILE: parking_lot::Mutex> = parking_lot::Mutex::new(None); + +/// Starts profiling when `PROFILE_CPU` is set (to anything but `0` or `false`), to cover the whole +/// run from its start. Call it before the runtime starts its threads (see [`warm_up`]). +/// `actor_crate` is the Actor's own crate (`env!("CARGO_PKG_NAME")`), whose samples the log +/// counts apart. +pub fn start_from_env(actor_crate: &str) { + let enabled = std::env::var("PROFILE_CPU").is_ok_and(|value| !matches!(value.as_str(), "" | "0" | "false")); + if enabled { + start(actor_crate); + } +} + +/// Starts profiling all threads, unless a profile is running already. Started once the Actor's +/// input is read, the runtime's threads exist, but they are mostly idle, so the samples of +/// [`warm_up`] still land on this thread. +pub fn start(actor_crate: &str) { + let mut profile = PROFILE.lock(); + if profile.is_some() { + return; + } + let frequency = + std::env::var("PROFILE_CPU_HZ").ok().and_then(|value| value.parse().ok()).unwrap_or(DEFAULT_FREQUENCY_HZ); + let Some(guard) = new_guard(frequency) else { return }; + warm_up(frequency); + *profile = Some(Profiler { + actor_crate: actor_crate.to_owned(), + guard: Some(guard), + frequency, + started: SystemTime::now(), + cpu_time_at_start: process_cpu_time(), + stacks: Stacks::default(), + }); + drop(profile); + let flusher = std::thread::Builder::new().name("cpu-profile".to_owned()).spawn(|| { + loop { + std::thread::sleep(FLUSH_INTERVAL); + match PROFILE.lock().as_mut() { + Some(profiler) => profiler.flush(true), + None => return, + } + } + }); + if let Err(err) = flusher { + tracing::warn!("Failed to start the CPU profile's flushing: {err}"); + } + tracing::info!("CPU profiling at {frequency} Hz"); +} + +/// Stops the running profile, if any, and saves it. Failures are logged, not returned: the +/// profile must not fail the run. +pub async fn save() { + let profiler = PROFILE.lock().take(); + let Some(mut profiler) = profiler else { return }; + profiler.flush(false); + let stacks = &profiler.stacks; + tracing::info!("CPU profile: {} distinct stacks of {} functions", stacks.counts.len(), stacks.names.len()); + let cpu_time = profiler.cpu_time_at_start.zip(process_cpu_time()).map(|(start, end)| end.saturating_sub(start)); + let period = sampling_period(stacks.samples(), cpu_time, profiler.frequency); + log_summary(stacks, &profiler.actor_crate, cpu_time, period); + + let svg = flamegraph(stacks).unwrap_or_else(|err| { + tracing::warn!("Failed to render the CPU flamegraph: {err}"); + Vec::new() + }); + let pb = pprof_profile(stacks, period, profiler.started).encode_to_vec(); + if let Err(err) = store(svg, pb).await { + tracing::warn!("Failed to save the CPU profile: {err}"); + } +} + +/// The CPU time of the process so far, user and system, from `/proc/self/stat` (Linux). +fn process_cpu_time() -> Option { + // Clock ticks of `/proc` (`USER_HZ`), 100 on Linux. + const TICKS_PER_SECOND: u64 = 100; + let stat = std::fs::read_to_string("/proc/self/stat").ok()?; + // After the command name, which is in parentheses and can hold spaces, come the fields from + // the 3rd (state); utime and stime are the 14th and 15th. + let mut fields = stat.get(stat.rfind(')')? + 1..)?.split_whitespace().skip(11); + let user: u64 = fields.next()?.parse().ok()?; + let system: u64 = fields.next()?.parse().ok()?; + Some(Duration::from_millis((user + system) * 1000 / TICKS_PER_SECOND)) +} + +/// The CPU time a sample stands for. The profiler's timer only fires on the kernel's scheduler +/// tick (often 250 Hz), so the frequency asked for is an upper bound: the CPU time the samples +/// were taken over gives the real period. +fn sampling_period(samples: u64, cpu_time: Option, frequency: i32) -> Duration { + match cpu_time { + Some(cpu_time) if samples > 0 && !cpu_time.is_zero() => cpu_time / samples.min(u64::from(u32::MAX)) as u32, + _ => Duration::from_secs(1) / frequency.max(1).unsigned_abs(), + } +} + +fn new_guard(frequency: i32) -> Option> { + match pprof::ProfilerGuardBuilder::default().frequency(frequency).build() { + Ok(guard) => Some(guard), + Err(err) => { + tracing::warn!("Failed to start CPU profiling: {err}"); + None + } + } +} + +/// The unwinder loads the unwind tables of the binary and the libraries on the first sample, in +/// the signal handler, which allocates. Spinning (without allocating) for a few sampling periods +/// makes the first samples land here, on a thread that holds no lock, rather than in another +/// thread's `malloc`. So profiling must start while the other threads are idle: before the +/// runtime starts, or before the crawl. The tables stay loaded when the profiler restarts. +fn warm_up(frequency: i32) { + let period_ms = 1000 / u64::from(frequency.max(1).unsigned_abs()); + let duration = Duration::from_millis((3 * period_ms).clamp(10, 1000)); + let start = std::time::Instant::now(); + while start.elapsed() < duration { + std::hint::spin_loop(); + } +} + +impl Profiler { + /// Moves the profiler's stacks to [`Stacks`] and, with `restart`, starts the profiler over. + fn flush(&mut self, restart: bool) { + let Some(guard) = self.guard.take() else { return }; + let report = guard.report().build_unresolved(); + drop(guard); + if restart { + self.guard = new_guard(self.frequency); + } + match report { + Ok(report) => self.stacks.add(&report), + Err(err) => tracing::warn!("Failed to collect the CPU profile's samples: {err}"), + } + } +} + +/// The samples so far, compactly: each code address is named once, a location is the list of +/// functions at an address (the functions inlined there, the innermost first and the function +/// the code belongs to last; without debug info, only that one), and a stack is a list of +/// locations, the leaf first. Threads of the same name (the runtime's workers) are merged. +#[derive(Default)] +struct Stacks { + /// Function and thread names. + names: Vec, + name_ids: HashMap, + locations: Vec>, + location_ids: HashMap, u32>, + location_of_address: HashMap, + /// The mapped files, for naming the addresses that have no symbol. + modules: Vec, + /// Sample counts by thread name and stack. + counts: HashMap<(u32, Box<[u32]>), u64>, +} + +impl Stacks { + fn add(&mut self, report: &pprof::UnresolvedReport) { + for (frames, &count) in &report.data { + let thread = String::from_utf8_lossy(&frames.thread_name[..frames.thread_name_length]).into_owned(); + let thread = self.name_id(&thread); + let stack: Box<[u32]> = frames.frames.iter().map(|frame| self.location_of(frame.ip)).collect(); + *self.counts.entry((thread, stack)).or_default() += count.unsigned_abs() as u64; + } + } + + fn name_id(&mut self, name: &str) -> u32 { + if let Some(&id) = self.name_ids.get(name) { + return id; + } + let id = self.names.len() as u32; + self.names.push(name.to_owned()); + self.name_ids.insert(name.to_owned(), id); + id + } + + fn location_of(&mut self, address: usize) -> u32 { + if let Some(&id) = self.location_of_address.get(&address) { + return id; + } + let mut names = Vec::new(); + backtrace::resolve(address as *mut std::ffi::c_void, |symbol| { + names.push(symbol.name().map_or_else(|| "Unknown".to_owned(), |name| format!("{name:#}"))); + }); + if names.is_empty() { + // No symbol: code of a library that exports none for it (libc's `memcpy` and + // `memset` variants), or of the vDSO. Named by its file, it still passes its time to + // its caller in the summary's groups. + names.push(format!("[{}]", self.module_of(address).unwrap_or("unknown"))); + } + let functions: Box<[u32]> = names.iter().map(|name| self.name_id(name)).collect(); + let next = self.locations.len() as u32; + let id = *self.location_ids.entry(functions.clone()).or_insert(next); + if id == next { + self.locations.push(functions); + } + self.location_of_address.insert(address, id); + id + } + + fn module_of(&mut self, address: usize) -> Option<&str> { + let find = |modules: &[Module]| modules.iter().position(|module| module.range.contains(&address)); + let index = match find(&self.modules) { + Some(index) => index, + None => { + // Mapped since the last read (a library loaded later), or not mapped. + self.modules = modules(); + find(&self.modules)? + } + }; + Some(&self.modules[index].name) + } + + /// The function the code of a location belongs to. + fn function_at(&self, location: u32) -> Option<&str> { + let function = *self.locations[location as usize].last()?; + Some(&self.names[function as usize]) + } + + fn samples(&self) -> u64 { + self.counts.values().sum() + } +} + +struct Module { + range: std::ops::Range, + /// The file name, or the kernel's name (`[vdso]`). + name: String, +} + +/// The mapped files of the process, from `/proc/self/maps` (Linux). +fn modules() -> Vec { + let maps = std::fs::read_to_string("/proc/self/maps").unwrap_or_default(); + maps.lines().filter_map(module_of_maps_line).collect() +} + +/// `start-end perms offset dev inode path`, with a path. +fn module_of_maps_line(line: &str) -> Option { + let mut fields = line.split_whitespace(); + let (start, end) = fields.next()?.split_once('-')?; + let path = fields.nth(4)?; + Some(Module { + range: usize::from_str_radix(start, 16).ok()?..usize::from_str_radix(end, 16).ok()?, + name: path.rsplit('/').next().unwrap_or(path).to_owned(), + }) +} + +/// A flamegraph of the stacks, by thread name, with the call paths of less than +/// [`MIN_FLAMEGRAPH_SHARE`] of the samples folded into their caller. +fn flamegraph(stacks: &Stacks) -> anyhow::Result> { + /// A node of the call tree. Few children each, so a list (by name) is smaller than a map; + /// a long run has many nodes. + #[derive(Default)] + struct Node { + children: Vec<(u32, u32)>, + samples: u64, + own_samples: u64, + } + fn fold(nodes: &[Node], node: usize, path: &mut Vec, min: u64, names: &[String], lines: &mut Vec) { + let mut own_samples = nodes[node].own_samples; + for &(name, child) in &nodes[node].children { + let child = child as usize; + if nodes[child].samples < min { + own_samples += nodes[child].samples; + continue; + } + path.push(name); + fold(nodes, child, path, min, names, lines); + path.pop(); + } + if own_samples > 0 && !path.is_empty() { + // `;` separates the frames of a line; Rust names have it in array types. + let frames: Vec = path.iter().map(|&name| names[name as usize].replace(';', ":")).collect(); + lines.push(format!("{} {own_samples}", frames.join(";"))); + } + } + + // The call tree, by thread name and then from the root of the stacks. + let mut nodes = vec![Node::default()]; + for ((thread, stack), &count) in &stacks.counts { + let path = std::iter::once(*thread) + .chain(stack.iter().rev().flat_map(|&location| stacks.locations[location as usize].iter().rev().copied())); + let mut node = 0; + nodes[node].samples += count; + for name in path { + let child = nodes[node].children.iter().find(|(child_name, _)| *child_name == name); + node = match child { + Some(&(_, child)) => child as usize, + None => { + nodes.push(Node::default()); + let child = nodes.len() - 1; + nodes[node].children.push((name, child as u32)); + child + } + }; + nodes[node].samples += count; + } + nodes[node].own_samples += count; + } + let min = ((nodes[0].samples as f64 * MIN_FLAMEGRAPH_SHARE) as u64).max(1); + let mut lines = Vec::new(); + fold(&nodes, 0, &mut Vec::new(), min, &stacks.names, &mut lines); + if lines.is_empty() { + return Ok(Vec::new()); + } + let mut options = pprof::flamegraph::Options::default(); + options.title = "CPU profile".to_owned(); + options.count_name = "samples".to_owned(); + let mut svg = Vec::new(); + pprof::flamegraph::from_lines(&mut options, lines.iter().map(String::as_str), &mut svg)?; + Ok(svg) +} + +/// The stacks in pprof's format, laid out as pprof's own reports: a location per function, and +/// the thread name as a label of each sample. +fn pprof_profile(stacks: &Stacks, period: Duration, started: SystemTime) -> pprof::protos::Profile { + use pprof::protos::{Function, Label, Line, Location, Profile, Sample, ValueType}; + + // The names, after the empty string that must come first, then the profile's own strings. + let id = |name: u32| u64::from(name) + 1; + let mut string_table = vec![String::new()]; + string_table.extend(stacks.names.iter().cloned()); + let mut string = |value: &str| { + string_table.push(value.to_owned()); + string_table.len() as i64 - 1 + }; + let (samples, count, cpu, nanoseconds, thread) = + (string("samples"), string("count"), string("cpu"), string("nanoseconds"), string("thread")); + + let functions: BTreeSet = stacks.locations.iter().flatten().copied().collect(); + let period = period.as_nanos() as i64; + let time = ValueType { ty: cpu, unit: nanoseconds }; + Profile { + sample_type: vec![ValueType { ty: samples, unit: count }, time.clone()], + sample: stacks + .counts + .iter() + .map(|((thread_name, stack), &samples)| Sample { + location_id: stack + .iter() + .flat_map(|&location| stacks.locations[location as usize].iter().map(|&name| id(name))) + .collect(), + value: vec![samples as i64, samples as i64 * period], + label: vec![Label { key: thread, str: id(*thread_name) as i64, ..Default::default() }], + }) + .collect(), + function: functions + .iter() + .map(|&name| Function { + id: id(name), + name: id(name) as i64, + system_name: id(name) as i64, + ..Default::default() + }) + .collect(), + location: functions + .iter() + .map(|&name| Location { + id: id(name), + line: vec![Line { function_id: id(name), line: 0 }], + ..Default::default() + }) + .collect(), + string_table, + time_nanos: started.duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default().as_nanos() as i64, + duration_nanos: started.elapsed().unwrap_or_default().as_nanos() as i64, + period_type: Some(time), + period, + ..Default::default() + } +} + +async fn store(svg: Vec, pb: Vec) -> anyhow::Result<()> { + let store: KeyValueStore = Actor::open_key_value_store(&StorageIdentifier::Default, Default::default()).await?; + if !svg.is_empty() { + store.set_bytes("CPU_PROFILE.svg", Bytes::from(svg), Some("image/svg+xml")).await?; + } + if !pb.is_empty() { + store.set_bytes("CPU_PROFILE.pb", Bytes::from(pb), Some("application/octet-stream")).await?; + } + tracing::info!( + "Saved the CPU profile to the CPU_PROFILE.svg and CPU_PROFILE.pb records of the default key-value store" + ); + Ok(()) +} + +/// The groups of crates of the summary. A sample counts for the crate of the innermost function +/// on its stack that has one: the standard library, libc and the kernel pass their time to their +/// caller, so that `malloc` called by serde_json counts as JSON. Code inlined into a function +/// counts for that function's crate. +const GROUPS: &[(&str, &[&str])] = &[ + ( + "TLS", + &[ + "rustls", + "aws-lc-rs", + "aws-lc-sys", + "ring", + "rustls-webpki", + "rustls-pki-types", + "rustls-native-certs", + "rustls-platform-verifier", + "webpki-roots", + ], + ), + ( + "HTTP", + &[ + "hyper", + "hyper-util", + "h2", + "h3", + "h3-quinn", + "quinn", + "quinn-proto", + "quinn-udp", + "http", + "http-body", + "http-body-util", + "httparse", + "reqwest", + "impit", + "tower", + "tower-http", + "hickory-proto", + "hickory-resolver", + "socket2", + "crawlee-http-client", + "crawlee-impit", + "cookie_store", + "cookie", + "url", + "idna", + "percent-encoding", + "form_urlencoded", + "bytes", + ], + ), + ( + "Decompression", + &[ + "brotli", + "brotli-decompressor", + "flate2", + "miniz_oxide", + "zstd", + "zstd-safe", + "zstd-sys", + "async-compression", + "compression-codecs", + "alloc-no-stdlib", + "alloc-stdlib", + ], + ), + ("JSON", &["serde_json", "serde", "serde_core", "indexmap"]), + ( + "HTML", + &[ + "html5ever", + "markup5ever", + "scraper", + "selectors", + "cssparser", + "lol_html", + "tendril", + "string_cache", + "ego-tree", + ], + ), + ( + "Crawlee & SDK", + &[ + "crawlee", + "crawlee-core", + "crawlee-basic", + "crawlee-http", + "crawlee-utils", + "crawlee-storage", + "apify", + "apify-sdk-rs", + "apify-client", + "apify-client-rust", + ], + ), + ( + "Async runtime", + &[ + "tokio", + "tokio-util", + "mio", + "futures-util", + "futures-core", + "futures-channel", + "parking_lot", + "parking_lot_core", + ], + ), + ("Logging", &["tracing", "tracing-core", "tracing-subscriber"]), +]; +/// The group of the Actor's own crate. +const THIS_ACTOR: &str = "This Actor"; +const OTHER: &str = "Other"; +const UNATTRIBUTED: &str = "Unattributed (standard library, libc, kernel)"; + +/// Prefixes of the C and assembly functions of crates, which have no Rust path. aws-lc's +/// functions carry its version in the prefix (`aws_lc_0_45_0_aes_gcm_decrypt_avx512`). +const C_PREFIXES: &[(&str, &str)] = &[ + ("aws_lc_", "aws_lc_sys"), + ("jent_", "aws_lc_sys"), + ("ZSTD_", "zstd_sys"), + ("HUF_", "zstd_sys"), + ("FSE_", "zstd_sys"), +]; + +/// The crate of a function, from the root of its demangled path (` +/// as serde::de::Deserializer>::deserialize_any` is serde_json's), or the prefix of a C function. +/// `None` for the standard library and for C functions it does not know (libc's `malloc`, +/// `memcpy`), whose time goes to their caller. +fn crate_of(function: &str) -> Option { + static ROOT: std::sync::LazyLock = + std::sync::LazyLock::new(|| regex::Regex::new(r"([A-Za-z_][A-Za-z0-9_]*)::").unwrap()); + let Some(root) = ROOT.captures(function) else { + return C_PREFIXES + .iter() + .find(|(prefix, _)| function.starts_with(prefix)) + .map(|(_, krate)| (*krate).to_owned()); + }; + match &root[1] { + "core" | "alloc" | "std" => None, + krate => Some(krate.to_owned()), + } +} + +/// The group of a crate, by its name as in Cargo.toml or as in paths (`-` as `_`). +fn group_of(krate: &str, actor_crate: &str) -> &'static str { + let normalize = |name: &str| name.replace('-', "_"); + let krate = normalize(krate); + if krate == normalize(actor_crate) { + return THIS_ACTOR; + } + GROUPS + .iter() + .find(|(_, crates)| crates.iter().any(|name| normalize(name) == krate)) + .map_or(OTHER, |(group, _)| group) +} + +/// The share of the samples of each group and crate, and of the functions by self time, largest +/// first. +struct GroupShare { + group: &'static str, + share: f64, + /// The crates of the group with their shares. + crates: Vec<(String, f64)>, +} + +struct Summary { + samples: u64, + groups: Vec, + functions: Vec<(String, f64)>, +} + +fn summarize(stacks: &Stacks, actor_crate: &str) -> Summary { + let mut groups: HashMap<&'static str, GroupCount> = HashMap::new(); + let mut functions: HashMap<&str, u64> = HashMap::new(); + let all = stacks.samples(); + for ((_, stack), &count) in &stacks.counts { + // Self time goes to the function the leaf's code belongs to, as the innermost function + // inlined there is often a helper (`black_box`, an iterator's `next`). + if let Some(function) = stack.first().and_then(|&leaf| stacks.function_at(leaf)) { + *functions.entry(function).or_default() += count; + } + let krate = stack.iter().filter_map(|&location| stacks.function_at(location)).find_map(crate_of); + let group = + groups.entry(krate.as_deref().map_or(UNATTRIBUTED, |krate| group_of(krate, actor_crate))).or_default(); + group.samples += count; + if let Some(krate) = krate { + *group.crates.entry(krate).or_default() += count; + } + } + let share = |count: u64| count as f64 * 100.0 / all.max(1) as f64; + let largest_first = |counts: Vec<(String, u64)>| { + let mut counts = counts; + counts.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + counts + }; + + let mut groups: Vec<_> = groups.into_iter().collect(); + groups.sort_by(|a, b| b.1.samples.cmp(&a.1.samples).then_with(|| a.0.cmp(b.0))); + let groups = groups + .into_iter() + .map(|(group, count)| GroupShare { + group, + share: share(count.samples), + crates: largest_first(count.crates.into_iter().collect()) + .into_iter() + .map(|(krate, count)| (krate, share(count))) + .collect(), + }) + .collect(); + let mut functions = largest_first(functions.into_iter().map(|(name, count)| (name.to_owned(), count)).collect()); + functions.truncate(TOP_FUNCTIONS); + Summary { + samples: all, + groups, + functions: functions.into_iter().map(|(name, count)| (name, share(count))).collect(), + } +} + +#[derive(Default)] +struct GroupCount { + samples: u64, + crates: HashMap, +} + +fn log_summary(stacks: &Stacks, actor_crate: &str, cpu_time: Option, period: Duration) { + let summary = summarize(stacks, actor_crate); + let cpu_time = cpu_time.map_or_else(|| "unknown".to_owned(), |time| format!("{:.1}", time.as_secs_f64())); + tracing::info!( + "CPU profile: {} samples over {cpu_time} CPU-seconds, one per {:.1} ms of CPU time", + summary.samples, + period.as_secs_f64() * 1000.0 + ); + if summary.samples == 0 { + return; + } + let groups: Vec = summary + .groups + .iter() + .map(|GroupShare { group, share, crates }| { + let crates: Vec = + crates.iter().take(CRATES_PER_GROUP).map(|(krate, share)| format!("{krate} {share:.1}%")).collect(); + if crates.is_empty() { + format!("{share:5.1}% {group}") + } else { + format!("{share:5.1}% {group} ({})", crates.join(", ")) + } + }) + .collect(); + tracing::info!("CPU profile by group of crates:\n{}", groups.join("\n")); + let functions: Vec = + summary.functions.iter().map(|(name, share)| format!("{share:5.1}% {name}")).collect(); + tracing::info!("CPU profile, top functions by self time:\n{}", functions.join("\n")); +} + +#[cfg(test)] +mod tests { + use std::hint::black_box; + use std::time::Instant; + + use super::*; + + #[inline(never)] + fn hot_function_for_the_profile(seed: u64) -> u64 { + (0..10_000u64).fold(seed, |acc, i| black_box(acc.wrapping_mul(31).wrapping_add(i))) + } + + fn spin_in_the_hot_function(duration: Duration) { + let start = Instant::now(); + let mut value = 0; + while start.elapsed() < duration { + value = hot_function_for_the_profile(value); + } + black_box(value); + } + + /// Sampled and flushed twice (as the flushing thread does), then summarized, drawn and encoded. + #[test] + fn the_hot_function_leads_and_counts_for_this_actor() { + let mut profiler = Profiler { + actor_crate: env!("CARGO_PKG_NAME").to_owned(), + guard: new_guard(1000), + frequency: 1000, + started: SystemTime::now(), + cpu_time_at_start: process_cpu_time(), + stacks: Stacks::default(), + }; + warm_up(1000); + spin_in_the_hot_function(Duration::from_millis(300)); + profiler.flush(true); + spin_in_the_hot_function(Duration::from_millis(300)); + profiler.flush(false); + assert!(profiler.guard.is_none()); + + let summary = summarize(&profiler.stacks, &profiler.actor_crate); + // At least a 100 Hz scheduler tick, over 0.6 s, from both rounds. + assert!(summary.samples > 40, "{}", summary.samples); + // In a debug build the loop's iterator functions are not inlined, so they lead by self + // time (and their names carry no generic arguments); the standard library still passes + // their samples to the hot function's crate in the groups. + if !cfg!(debug_assertions) { + let (leader, share) = &summary.functions[0]; + assert!(leader.ends_with("hot_function_for_the_profile"), "{:#?}", summary.functions); + assert!(*share > 50.0, "{:#?}", summary.functions); + } + let GroupShare { group, share, .. } = &summary.groups[0]; + assert_eq!(*group, THIS_ACTOR); + assert!(*share > 50.0, "{share}"); + + let svg = String::from_utf8(flamegraph(&profiler.stacks).unwrap()).unwrap(); + assert!(svg.contains("hot_function_for_the_profile")); + let profile = pprof::protos::Profile::decode( + pprof_profile(&profiler.stacks, Duration::from_millis(1), profiler.started).encode_to_vec().as_slice(), + ) + .unwrap(); + let samples: i64 = profile.sample.iter().map(|sample| sample.value[0]).sum(); + assert_eq!(samples as u64, summary.samples); + let named = profile + .function + .iter() + .any(|function| profile.string_table[function.name as usize].contains("hot_function_for_the_profile")); + assert!(named); + } + + #[test] + fn modules_of_maps_lines() { + let module = module_of_maps_line( + "7f3a1c200000-7f3a1c3a8000 r-xp 00028000 08:01 1835 /usr/lib/x86_64-linux-gnu/libc.so.6", + ) + .unwrap(); + assert_eq!(module.range, 0x7f3a1c200000..0x7f3a1c3a8000); + assert_eq!(module.name, "libc.so.6"); + let vdso = module_of_maps_line("7ffd5a3f2000-7ffd5a3f4000 r-xp 00000000 00:00 0 [vdso]").unwrap(); + assert_eq!(vdso.name, "[vdso]"); + assert!(module_of_maps_line("7f3a1c3a8000-7f3a1c3ac000 rw-p 00000000 00:00 0").is_none()); + + // An address of this binary is in one of its modules. + let mut stacks = Stacks::default(); + let address = modules_of_maps_lines as fn() as usize; + assert!(stacks.module_of(address).is_some()); + } + + #[test] + fn cpu_time_and_sampling_period() { + let before = process_cpu_time().unwrap(); + spin_in_the_hot_function(Duration::from_millis(100)); + let spent = process_cpu_time().unwrap() - before; + assert!(spent >= Duration::from_millis(50), "{spent:?}"); + + let period = sampling_period(250, Some(Duration::from_secs(1)), 997); + assert_eq!(period, Duration::from_millis(4)); + assert_eq!(sampling_period(0, Some(Duration::from_secs(1)), 1000), Duration::from_millis(1)); + assert_eq!(sampling_period(10, None, 1000), Duration::from_millis(1)); + } + + #[test] + fn crates_of_functions() { + let cases = [ + ( + " as serde_core::de::Deserializer>::deserialize_any", + Some("serde_json"), + ), + ("<&mut serde_json::ser::Serializer>::serialize_str", Some("serde_json")), + ("tokio::runtime::scheduler::multi_thread::worker::Context::run", Some("tokio")), + (">::poll_read_head", Some("hyper")), + ("my_actor::extractors::extract_profile", Some("my_actor")), + ("::clone", None), + (" as core::future::Future>::poll", None), + ("std::sys::pal::unix::time::Timespec::now", None), + ("aws_lc_0_45_0_aes_gcm_decrypt_avx512", Some("aws_lc_sys")), + ("ZSTD_decompressStream", Some("zstd_sys")), + ("malloc", None), + ("__memmove_avx512_unaligned_erms", None), + ]; + for (function, krate) in cases { + assert_eq!(crate_of(function).as_deref(), krate, "{function}"); + } + assert_eq!(group_of("aws_lc_sys", "my_actor"), "TLS"); + assert_eq!(group_of("tower_http", "my_actor"), "HTTP"); + assert_eq!(group_of("serde_json", "my_actor"), "JSON"); + assert_eq!(group_of("my-actor", "my-actor"), THIS_ACTOR); + assert_eq!(group_of("apify", "my_actor"), "Crawlee & SDK"); + assert_eq!(group_of("chrono", "my_actor"), OTHER); + } +} diff --git a/src/lib.rs b/src/lib.rs index 37816ad..1730f95 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,6 +8,8 @@ pub mod charging; pub mod child_runs; pub mod client; pub mod configuration; +#[cfg(feature = "cpu-profile")] +pub mod cpu_profile; pub mod events; pub mod input; pub mod input_secrets; From 964797b9b628d90429cfd12044aa015f2751d8bb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 10 Nov 2026 22:00:34 +0000 Subject: [PATCH 2/2] fix: storage tests that #28 left failing on master - The in-process re-open of a deleted alias went through `Services`, which hands back the instance it already opened (as `StorageInstanceManager` does in JS), so the backend never resolved it again. Ask the backend. - The replaced declared storage is remembered on the platform, so the off-platform check now asserts the mapping is unchanged instead of absent. - The deleted default dataset is no longer the storage expected to exist. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_0148RYR4BTGyCYHENSRZjC3S (cherry picked from commit 519338ea8000edcf34e89b3363c89e017458bf50) --- tests/storage.rs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/tests/storage.rs b/tests/storage.rs index 276d5da..a6abfde 100644 --- a/tests/storage.rs +++ b/tests/storage.rs @@ -103,15 +103,18 @@ async fn names_and_aliases_resolve_to_platform_storages() { // Unless the storage was deleted in the meantime. api.delete_dataset(&scratch_id); - let fresh = Services::new(Arc::new(ApifyStorageBackend::new(configuration(&api, true)))); + let fresh_backend = Arc::new(ApifyStorageBackend::new(configuration(&api, true))); + let fresh = Services::new(fresh_backend.clone()); let recreated = fresh.open_dataset(&StorageIdentifier::alias("scratch")).await.unwrap(); assert_ne!(recreated.get_info().await.unwrap().id, scratch_id); - // Also when it was deleted after this process resolved it. + // Also when it was deleted after this process resolved it. `Services` hands back the instance it + // already opened, as `StorageInstanceManager` does in JS, so ask the backend. + use crawlee::core::StorageBackend as _; let recreated_id = recreated.get_info().await.unwrap().id; api.delete_dataset(&recreated_id); - let reopened = fresh.open_dataset(&StorageIdentifier::alias("scratch")).await.unwrap(); - assert_ne!(reopened.get_info().await.unwrap().id, recreated_id); + let reopened = fresh_backend.create_dataset_backend(&StorageIdentifier::alias("scratch")).await.unwrap(); + assert_ne!(reopened.get_metadata().await.unwrap().id, recreated_id); // `__default__` is the default storage. let default = fresh.open_dataset(&StorageIdentifier::alias("__default__")).await.unwrap(); @@ -166,17 +169,19 @@ async fn aliases_declared_in_the_actor_schema_and_off_the_platform() { ..(*configuration(&api, true)).clone() })))); let replacement = replaced.open_dataset(&StorageIdentifier::alias("products")).await.unwrap(); - assert_ne!(replacement.get_info().await.unwrap().id, DEFAULT_DATASET); + let replacement_id = replacement.get_info().await.unwrap().id; + assert_ne!(replacement_id, DEFAULT_DATASET); // Off the platform (a `force_cloud` storage), aliases are not remembered. + let mapping = api.record(DEFAULT_STORE, "__STORAGE_ALIASES_MAPPING"); let local = Services::new(Arc::new(ApifyStorageBackend::new(configuration(&api, false)))); local.open_dataset(&StorageIdentifier::alias("scratch")).await.unwrap(); - assert!(api.record(DEFAULT_STORE, "__STORAGE_ALIASES_MAPPING").is_none()); + assert_eq!(api.record(DEFAULT_STORE, "__STORAGE_ALIASES_MAPPING"), mapping); let backend = ApifyStorageBackend::new(configuration(&api, false)); use crawlee::core::StorageBackend as _; - assert!(backend.storage_exists(DEFAULT_DATASET, StorageKind::Dataset).await.unwrap()); - assert!(!backend.storage_exists("nope", StorageKind::Dataset).await.unwrap()); + assert!(backend.storage_exists(&replacement_id, StorageKind::Dataset).await.unwrap()); + assert!(!backend.storage_exists(DEFAULT_DATASET, StorageKind::Dataset).await.unwrap()); } #[tokio::test]