Skip to content

Commit af9c720

Browse files
committed
fix(fastapi-instrumentation): fix tests and finalize memory leak fix
1 parent 0a74f67 commit af9c720

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

instrumentation/opentelemetry-instrumentation-fastapi/src/opentelemetry/instrumentation/fastapi/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,11 @@ def _instrument(self, **kwargs):
392392
fastapi.FastAPI = _InstrumentedFastAPI
393393

394394
def _uninstrument(self, **kwargs):
395-
for instance in _InstrumentedFastAPI._instrumented_fastapi_apps:
395+
# Create a copy of the set to avoid RuntimeError during iteration
396+
instances_to_uninstrument = list(
397+
_InstrumentedFastAPI._instrumented_fastapi_apps
398+
)
399+
for instance in instances_to_uninstrument:
396400
self.uninstrument_app(instance)
397401
_InstrumentedFastAPI._instrumented_fastapi_apps.clear()
398402
fastapi.FastAPI = self._original_fastapi

instrumentation/opentelemetry-instrumentation-fastapi/tests/test_fastapi_memory_leak.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,20 @@
1919

2020
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
2121

22+
# Check if sys.getrefcount is available (not available in PyPy)
23+
HAS_GETREFCOUNT = hasattr(sys, "getrefcount")
24+
2225

2326
class TestFastAPIMemoryLeak(unittest.TestCase):
2427
"""Test for memory leak in FastAPIInstrumentor.uninstrument_app()"""
2528

2629
def test_refcount_after_uninstrument(self):
2730
"""Test that refcount is restored after uninstrument_app()"""
31+
if not HAS_GETREFCOUNT:
32+
self.skipTest(
33+
"sys.getrefcount not available in this Python implementation"
34+
)
35+
2836
app = fastapi.FastAPI()
2937

3038
# Instrument the app
@@ -53,6 +61,11 @@ def test_refcount_after_uninstrument(self):
5361

5462
def test_multiple_instrument_uninstrument_cycles(self):
5563
"""Test that multiple instrument/uninstrument cycles don't leak memory"""
64+
if not HAS_GETREFCOUNT:
65+
self.skipTest(
66+
"sys.getrefcount not available in this Python implementation"
67+
)
68+
5669
app = fastapi.FastAPI()
5770

5871
initial_refcount = sys.getrefcount(app)
@@ -84,6 +97,11 @@ def test_multiple_instrument_uninstrument_cycles(self):
8497

8598
def test_multiple_apps_instrument_uninstrument(self):
8699
"""Test that multiple apps can be instrumented and uninstrumented without leaks"""
100+
if not HAS_GETREFCOUNT:
101+
self.skipTest(
102+
"sys.getrefcount not available in this Python implementation"
103+
)
104+
87105
apps = [fastapi.FastAPI() for _ in range(3)]
88106
initial_refcounts = [sys.getrefcount(app) for app in apps]
89107

0 commit comments

Comments
 (0)