grafana / grafana/pyroscope-python

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

Ouverte
#148 0 commentaires 0 réactions 0 personnes assignées Voir sur GitHub
Langage dominant
Rust
Étoiles
4
Forks
2
Merge moyen
2 j 4 h
PR mergées (30 j)
5

Description

> 🤖 **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.

Guide de contribution

Aucun guide de contribution indexé pour ce dépôt

Piste de recherche

Commencez dans py-spy/src/python_spy.rs, où short_filenames est défini, lu et alimenté, et comparez son cycle de vie avec les caches python_thread_ids et python_thread_names. Vérifiez la valeur par défaut de full_filenames dans py-spy/src/config.rs, coordonnez ensuite la modification en amont de py-spy et mettez à jour ici le pin de la dépendance ; c’est terminé lorsque la croissance de filename-cache est limitée ou supprimée.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Évaluation

Stack technique
rust
Domaine
performance
Type d'issue
Bug
Difficulté
4/5
Temps estimé
3-5 jours
Activité
Active
Clarté
Plutôt claire
Accessibilité débutants
45/100

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.