You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Backport 93aff64 from #14859 to 3.16.
## Description
Fixes a coverage tracking performance issue by leveraging
de-instrumentation after line events, and re-instrumentation between
coverage collection contexts on Python 3.12+.
**Problem:** The coverage tracking wasn't using `sys.monitoring` API's
`DISABLE` for `LINE` events once the line coverage was tracked.
**Solution:** Return `sys.monitoring.DISABLE` once a line is tracked,
and call `sys.monitoring.restart_events()` when entering new coverage
contexts to re-enable monitoring.
## Testing
- New tests covering sequential contexts, nested contexts, dynamic
imports, and nested import chains
- Tests verify that coverage is complete and consistent across multiple
context switches
## Risks
Low - only affects Python 3.12+ coverage, uses `sys.monitoring.DISABLE`
and `sys.monitoring.restart_events()`
[API](https://docs.python.org/3/library/sys.monitoring.html#disabling-events),
extensively tested.
However, if other tool was using this API at the same time, when we call
`sys.monitoring.restart_events()`, we would be re-enabling their
disabled events as well.
## Additional Notes
### Performance Gain Example:
The best performance gains for this PR happen when recursive code or
loops are used heavily in the tested code, for example a recursive
implementation of a fibonacci sequence calculator:
```
# fibonacci.py
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
```
Then running just this test:
```
# test_fibonacci.py
from fibonacci import fibonacci
def test_fibonacci():
assert fibonacci(35) == 9227465
```
Yields the following results:
No coverage:
```
1 passed in 0.98s
```
current coverage (main):
```
1 passed in 24.11s
```
new coverage (this branch):
```
1 passed in 1.01s
```
Co-authored-by: Federico Mon <[email protected]>
0 commit comments