grafana / grafana/pyroscope-python

py-spy's short_filenames cache is never evicted (unbounded growth for apps that compile code with fresh filenames)

オープン
#148 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る
主要言語
Rust
スター
4
フォーク
2
平均マージ
2日 4時間
マージ済み PR(30日)
5

説明

> 🤖 **This issue was written by an AI agent** (Claude Code), while investigating
> #37. The code references and measurements below were verified against the
> actual sources and a running container, but a human has not reviewed the
> writeup.

## What

`PythonSpy::shorten_filename` memoizes every filename it has ever seen and
never evicts (`py-spy/src/python_spy.rs`):

```rust
pub short_filenames: HashMap>, // :37, initialized empty at :96

fn shorten_filename(&mut self, filename: &str) -> Option {
if self.config.full_filenames {
return Some(filename.to_string());
}
if let Some(short) = self.short_filenames.get(filename) { // :561
return short.clone();
}
...
self.short_filenames.insert(filename.to_owned(), shortened.clone()); // :596
shortened
}
```

There is no cap and no eviction. By contrast the sibling caches in the same
struct *are* invalidated when a thread exits:

```rust
self.python_thread_ids.clear();
self.python_thread_names.clear(); // :276-277 — but not short_filenames
```

This path is active for pyroscope: `full_filenames` defaults to `false`
(`py-spy/src/config.rs:134`) and the extension builds its config with
`..py_spy::Config::default()`.

## Impact, measured honestly

Growth is bounded by the number of **distinct filenames that appear in sampled
frames**, not by how many code objects the app creates. For a normal app that
is the size of the codebase — a few thousand entries, and effectively bounded.
It becomes unbounded for apps that compile code with fresh filenames *and*
spend CPU inside it: templating engines, notebooks, ORM/dataclass-style
codegen, `eval`/`exec`-heavy code.

A/B in a container (Python 3.11, `pyroscope-io==1.2.1`, `sample_rate=997`,
identical interpreter-side work in both runs, only the filename differs):

```
UNIQUE=1 90s modules= 71616 rss=69 MiB (+50) # fresh filename per module
UNIQUE=0 90s modules= 75132 rss=57 MiB (+38) # one reused filename
```

~12 MiB of the growth is attributable to the ~71k distinct filenames the
sampler observed, i.e. **~175 bytes per distinct filename**, and it is
monotonic. (Most of the shared +38 MiB is interpreter churn and buffered
profile data, not this cache.)

A first attempt at this A/B showed *no* difference (+6 vs +5 MiB) even with 5M
unique filenames, because the generated functions were too short-lived to be
sampled — worth knowing if anyone re-measures.

Secondary cost on the same code path: every cache *miss* does filesystem work
on the sampler thread — `Path::exists()` for `__init__.py` while walking
parents, plus an extra `stat` of `/proc//root` when the process
is detected as dockerized. So a high rate of unique filenames also means a
`stat` storm at sampling frequency.

## Suggested fix

Bound it: an LRU (or a plain cap with a clear-on-overflow, matching how
`python_thread_*` are already handled), or drop the memoization and pay the
`strip_prefix` cost per sample — it is cheap next to the syscalls it currently
guards.

Upstream: this code lives in `benfred/py-spy`, so a fix there plus a pin bump
here.

## Context

Found while investigating #37 (root cause and reproducer in
grafana/pyroscope-python#146). Unrelated to that crash.

コントリビューションガイド

このリポジトリのコントリビューションガイドは索引されていません

調査の方向性

Start in py-spy/src/python_spy.rs, where short_filenames is defined, read, and populated, and compare its lifecycle with the python_thread_ids and python_thread_names caches. Check py-spy/src/config.rs for the full_filenames default, then coordinate the upstream py-spy change and update the dependency pin here; done means filename-cache growth is bounded or removed.

索引モデルが issue の本文から書いたものです。

評価

技術スタック
rust
領域
performance
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
活発
明瞭さ
おおむね明確
初心者へのやさしさ
45/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。