Every Python operator eventually meets the same 3 a.m. incident: a worker process is pegged at 100% CPU, requests are timing out, and nobody can say which function is burning the cores. If that worker is part of a django deployment, the instinctive moves — sprinkle print statements, bump log levels, redeploy with a debugger wired in — all change the system you are trying to observe, and the slow request may never reproduce on your laptop. The GIL makes it worse: thread dumps from inside the process tell you a thread “holds the GIL”, not what it is executing underneath.

py-spy, Ben Frederickson’s sampling profiler, takes the opposite approach. You run py-spy dump --pid 12345 and get every thread’s current stack, instantly, with zero code changes. Run py-spy record --pid 12345 and it writes a flamegraph SVG while your program keeps running at full speed. Run py-spy top and you get a live, sortable view of every function’s own time and total time, refreshed every second. There is no instrumentation step, no restart, no handler to install — the profiler reads the target’s memory from the outside and reconstructs stacks from raw bytes.

That promise raises an obvious engineering question: how can a separate process reliably turn memory bytes of a running interpreter into coherent Python call stacks, across CPython versions from 2.7.15 to 3.15, on Linux, macOS, Windows, and FreeBSD? The answer is a small, layered rust codebase — 39 source files under src/ at version 0.4.4 per the Cargo manifest — that this tour walks end to end, following one sample from command-line parse to flamegraph pixel. Everything cited below links to the real master tree, so you can verify each claim yourself.

py-spy overview architecture: CLI, sampling engine, process attachment, interpreter model, and output writers

Overview of py-spy: the CLI layer feeds a background sampling engine that attaches to the target process, resolves interpreter layout through version-specialized bindings, and streams traces into four output writers.

Reading the overview from left to right:

  • pyspy_main, L393 is the single entry point: it parses the command line, demands root on macOS, and hands a PID to the command dispatcher.
  • Config, L11 carries every knob — locking strategy, sampling rate, GIL-only filtering, output format — shared by the CLI and the library API.
  • Sampler, L19 owns a background thread that yields Sample values over an mpsc channel, decoupling collection from rendering.
  • Timer, L13 spaces samples with an exponential distribution instead of a fixed interval, deliberately avoiding aliasing with the target’s own scheduling.
  • PythonSpy, L23 is the attach object: it opens the process, fingerprints the interpreter, and caches thread-id and thread-name lookups.
  • PythonProcessInfo, L30 collects virtual memory maps and locates the python (or libpython) binary plus its symbol table.
  • parse_binary, L63 uses goblin to parse ELF, Mach-O, and PE binaries into a flat address-to-symbol map.
  • InterpreterState, L20 defines the trait family — thread state, frame object, code object — that abstracts over fifteen CPython struct layouts.
  • get_stack_trace, L118 walks the remote frame linked list and materializes StackTrace values with line numbers and optional locals.
py-spy detail architecture with dispatch macro, memory scanning, native unwinding, and each output format

The detail view expands each layer: the version dispatch macro, the BSS scan that finds the interpreter, native-frame merging, core dump support, and the four record formats plus the top console.

Three Subcommands, One Sampler

The CLI surface is tiny and honest. run_spy_command, L374 matches the configured command string and routes dump, record, and top to three functions; anything else is a programming error. top streams into the console viewer, dump calls dump::print_traces once, and record enters record_samples, L158, the loop that turns the sampler’s stream into a file.

That loop is deliberately dumb: it picks one boxed Recorder, L89 based on the requested FileFormat, then for each sample it filters idle threads unless --idle was passed, drops non-GIL threads unless --gil was passed, optionally injects thread-id and thread-name pseudo-frames, and finally calls increment. A ctrlc handler flips an atomic bool so the loop can finish gracefully and still write its file. Timestamped default filenames are built by output_filename, L133, whose unit tests assert the name contains no colons — a Windows-filesystem constraint made testable.

The dump path shows the same shape with less machinery: dump.rs opens its own PythonSpy, prints the process line, python version line, then one block per thread, newest first. With --json, write_traces, L18 instead serializes the whole Vec<StackTrace> with serde_json. With --subprocesses, it recurses through child PIDs, guarded so grandchildren are printed exactly once.

The Attach Layer: Maps, Symbols, and a BSS Scan

Attaching starts at PythonSpy::new, L41: open the process through remoteprocess, gather PythonProcessInfo, L53, detect the interpreter version, then build the layout. Because a freshly spawned py-spy record -- python script.py may target a process that has not imported anything yet, retry_new, L91 retries up to twenty times with 20-millisecond sleeps before giving up.

Symbol discovery is platform work. parse_binary, L63 memory-maps the candidate binary and lets goblin dispatch: Mach-O parsing checks the running CPU type so Rosetta-translated processes report the right architecture; the ELF branch harvests both symtab and dynsyms while honoring PT_LOAD offsets; the PE branch reads export tables. Which binary is “the python one” is decided per OS by is_python_lib overloads near L1268, and a dockerized target is detected by inspecting /proc/<pid>/cgroup at is_dockerized, L1226.

The runtime version itself is found by brute honesty: Version::scan_bytes, L16 scans process memory with a regex for the 3.x.y version string CPython embeds, then parses major, minor, patch, and pre-release flags. Finally, scan_memory_for_python_interpreter, L1031 reads the BSS section word by word, treating each word as a candidate interpreter pointer. A candidate survives only if its threads head lands in a valid map, the thread state points back to the same interpreter address, and a trial stack walk succeeds — three escalating sanity checks before trusting an address.

From cfg Flags to a 65,536-Entry Symbol Cache: Build Facts

The Cargo manifest is the map to the whole design. Feature cli pulls clap 4.6.1, indicatif, and the output crates; feature unwind simply forwards to remoteprocess/unwind (Cargo.toml lines 2-4), so native-frame profiling is an opt-in compile-time switch. The heavy dependencies are few and purposeful: goblin 0.10.7 for binary formats (L33), inferno 0.12.6 for flamegraph rendering (L32), remoteprocess 0.5.5 as the cross-platform process/memory abstraction (L50), and lru 0.17 for caching (L37).

That LRU cache is where native frames get fast: NativeStack, L15 holds an unwinder, a symbolicator, and a symbol_cache, L48 capped at 65,536 entries, and merge_native_thread splices native frames between the Python ones. Cython users get their own layer: cython.rs demangles compiled function names and maps them back to .pyx source lines via SourceMaps, L10.

Two more numbers deserve attention. The sampling clock in Timer, L20 draws gaps from Exp::new(rate) — an exponential distribution, so the mean rate is exact but no harmonic lock-on with the target is possible — and on Windows it calls timeBeginPeriod(1) because the default 15.6-millisecond timer resolution would otherwise make anything above 64 Hz impossible. And the thread walk carries a hard visited > 4096, L174 guard: if BSS scanning ever points at garbage, the loop errors out instead of spinning forever.

Reading Frames Across Fifteen CPython Layouts

This is the part that cannot be improvised. Each CPython release reshuffles private struct fields, so py-spy commits one module per version under src/python_bindings/ — fifteen modules from v2_7_15.rs through v3_15_0t.rs, where the _t suffix covers the free-threaded builds of 3.14 and 3.15 (module list at python_bindings/mod.rs, L1). The offsets that cannot live in a version module — like the interpreter head inside PyRuntime, which differs by architecture and release (32 bytes for x86-64 CPython 3.8-3.10, 40 for 3.11-3.12, 24 otherwise, per pyruntime, L24) — are hand-tabulated match arms. If you want the deep background on why these structs look the way they do, the cpython source is the ground truth.

Above the raw offsets sits a trait layer in InterpreterState, L20: ThreadState exposes frame_address() — the extra indirection CPython 3.11 introduced — FrameObject exposes code pointer, last instruction, and back link, and a family of if_python_3_12_or_later-style macros lets one implementation serve many versions. The dispatch_by_version! macro, L560 monomorphizes a generic handler into a per-version call, which is how get_stack_traces in python_spy.rs picks the right types with zero runtime overhead. Stack assembly itself lives in get_stack_trace, L118: it marks entry and shim frames (the interpreter-level frames 3.12 inserts), resolves line numbers, and optionally pulls local variables through format_variable, whose reads are policed by the TypeChecks mode in config.rs, L73 so a racing target cannot make the profiler dereference a string as an int.

Four Output Formats, One increment Loop

Every writer implements the same two-method trait, and the differences are instructive. The flamegraph writer in Flamegraph::increment, L49 folds each trace into a single ;-joined string and bumps a HashMap counter; write then feeds those folded lines to inferno’s from_lines with Direction::Inverted and min_width = 0.1, producing the SVG. The raw format is the same accumulator with write_raw, L94, emitting text compatible with the classic flamegraph.pl.

The speedscope writer is the most structured: Stats, L193 interns frames into an indexed table (deduplicated through frame_to_index), accumulates per-thread sample index vectors, and SpeedscopeFile, L60 serializes sampled profiles with weights scaled by the sampling rate, stamped with an exporter: py-spy@<version> field. The chrome writer takes a different tack entirely: Chrometrace::increment, L70 diffs the current stack against the previous one per thread and emits only begin/end (“B”/”E”) phase events for changed frames, which keeps timelines small. And the top console runs a background stdin thread (ConsoleViewer::new, L28) so hotkeys keep working while samples stream in: r resets stats, l toggles line numbers, 1-4 switch sort columns.

Honest Limits

Reading another process’s memory is inherently racy. In nonblocking mode the docstring on Config, L12 warns outright that you can get partial stacks or higher sampling error; blocking mode suspends the target for every tick, which is why native profiling requires it — you cannot unwind a process that keeps moving. Platform privileges are a hard wall too: macOS exits unless root, and Linux in Docker needs the SYS_PTRACE capability, a case the error path in main.rs detects by reading the container’s cgroup and explains specifically.

Coverage is the other honest constraint. Fifteen hand-maintained binding modules track CPython releases; a future beta that reshuffles PyThreadState needs a new module before it works, though generate_bindings.py in the repo root automates most of that chore. The BSS scan, for all its back-pointer validation, remains a heuristic over memory that might legitimately contain decoy values, and the exponential jitter means sample counts are statistical rather than exact. Finally, if you would rather own the loop yourself, the crate publishes a library API — lib.rs opens with a runnable example of embedding PythonSpy::new(pid, &config) into your own Rust tooling, which is the cleanest escape hatch from every limitation above.

Watch PyShine on YouTube

Contents