Skip to content

Conversation

@tdryer
Copy link

@tdryer tdryer commented Jul 29, 2025

py-spy uses a cache to minimize the overhead of looking up Python thread names during sampling. If looking up a thread name fails, the entire cache is rebuilt. However, if a failure is persistent, this causes the cache to be rebuilt during every sample (potentially more than once), creating excessive overhead.

Two cases when persistent thread name lookup failures can occur are:

  • When the threading module has not been imported
  • When a thread was created outside of the threading module, such as through _thread.start_new_thread

Fix this by modifying the cache to store a negative response (None) if the thread name is still not found after rebuilding the cache. To prevent negative responses from being lost when more than one thread name lookup fails, add a flag preventing the cache from being rebuilt more than once per sample.

One disadvantage of this approach is that in nonblocking mode, a spurious negative response can be cached for an extended duration. This happens if the thread is created during a sample and after the single allowed thread name lookup happens.

py-spy uses a cache to minimize the overhead of looking up Python thread
names during sampling. If looking up a thread name fails, the entire
cache is rebuilt. However, if a failure is persistent, this causes the
cache to be rebuilt during every sample (potentially more than once),
creating excessive overhead.

Two cases when persistent thread name lookup failures can occur are:

* When the `threading` module has not been imported
* When a thread was created outside of the `threading` module, such as
  through `_thread.start_new_thread`

Fix this by modifying the cache to store a negative response (`None`) if
the thread name is still not found after rebuilding the cache. To
prevent negative responses from being lost when more than one thread
name lookup fails, add a flag preventing the cache from being rebuilt
more than once per sample.

One disadvantage of this approach is that in nonblocking mode, a
spurious negative response can be cached for an extended duration. This
happens if the thread is created during a sample and after the single
allowed thread name lookup happens.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant