-
Notifications
You must be signed in to change notification settings - Fork 805
asyncio: fix duplicate instrumentation #3408
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 15 commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
53f05e0
#3383 fix duplicate instrument
allen-k1m 6acef29
Merge branch 'main' into bugfig/memory-leak
bourbonkk 964c861
#3383 fix duplicate instrument
bourbonkk a102e47
Merge remote-tracking branch 'origin/bugfig/memory-leak' into bugfig/…
allen-k1m da3d617
feedback
allen-k1m dfd7713
feat(asyncio): add weakref-based tracking for instrumented objects
allen-k1m aba1f57
Use WeakKeyDictionary to safely track instrumented objects
allen-k1m 2678389
Merge branch 'main' into bugfig/memory-leak
bourbonkk 5413f60
feedback
allen-k1m c13e3c4
Merge remote-tracking branch 'origin/bugfig/memory-leak' into bugfig/…
allen-k1m 787e31e
feedback
allen-k1m e48d655
feedback
allen-k1m deee6f9
Merge branch 'main' into bugfig/memory-leak
bourbonkk e620541
Merge branch 'main' into bugfig/memory-leak
bourbonkk 5099ba4
Merge branch 'main' into bugfig/memory-leak
bourbonkk 893d5fd
Update instrumentation/opentelemetry-instrumentation-asyncio/src/open…
aabmass File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
66 changes: 66 additions & 0 deletions
66
...nstrumentation-asyncio/src/opentelemetry/instrumentation/asyncio/instrumentation_state.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| # Copyright The OpenTelemetry Authors | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """ | ||
bourbonkk marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| Instrumentation State Tracker | ||
| This module provides helper functions to safely track whether a coroutine, | ||
| Future, or function has already been instrumented by the OpenTelemetry | ||
| asyncio instrumentation layer. | ||
| Some Python objects (like coroutines or functions) may not support setting | ||
| custom attributes or weak references. To avoid memory leaks and runtime | ||
| errors, this module uses a WeakKeyDictionary to safely track instrumented | ||
| objects. | ||
| If an object cannot be weak-referenced, it is silently skipped. | ||
| Usage: | ||
| if not _is_instrumented(obj): | ||
| _mark_instrumented(obj) | ||
| # instrument the object... | ||
| """ | ||
|
|
||
| import weakref | ||
| from typing import Any | ||
|
|
||
| # A global WeakKeyDictionary to track instrumented objects. | ||
aabmass marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| # Entries are automatically removed when the objects are garbage collected. | ||
| _instrumented_tasks = weakref.WeakSet() | ||
|
|
||
|
|
||
| def _is_instrumented(obj: Any) -> bool: | ||
| """ | ||
| Check whether the object has already been instrumented. | ||
| If not, mark it as instrumented (only if weakref is supported). | ||
| Args: | ||
| obj: A coroutine, function, or Future. | ||
| Returns: | ||
| True if the object was already instrumented. | ||
| False if the object is not trackable (no weakref support), or just marked now. | ||
| Note: | ||
| In Python 3.12+, some internal types like `async_generator_asend` | ||
| raise TypeError when weakref is attempted. | ||
| """ | ||
| try: | ||
| if obj in _instrumented_tasks: | ||
| return True | ||
| _instrumented_tasks.add(obj) | ||
| return False | ||
| except TypeError: | ||
| # Object doesn't support weak references → can't track instrumentation | ||
| return False | ||
70 changes: 70 additions & 0 deletions
70
...entation/opentelemetry-instrumentation-asyncio/tests/test_asyncio_duplicate_instrument.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| # Copyright The OpenTelemetry Authors | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| """ | ||
| A general test verifying that when the same Future objects (or coroutines) are | ||
| repeatedly instrumented (for example, via `trace_future`), callback references | ||
| do not leak. In this example, we mimic a typical scenario where a small set of | ||
| Futures might be reused throughout an application's lifecycle. | ||
| """ | ||
|
|
||
| import asyncio | ||
|
|
||
| from opentelemetry.instrumentation.asyncio import AsyncioInstrumentor | ||
| from opentelemetry.test.test_base import TestBase | ||
|
|
||
|
|
||
| class TestAsyncioDuplicateInstrument(TestBase): | ||
| """ | ||
| Tests whether repeated instrumentation of the same Futures leads to | ||
| exponential callback growth (potential memory leak). | ||
| """ | ||
|
|
||
| def setUp(self): | ||
| super().setUp() | ||
| self.loop = asyncio.new_event_loop() | ||
| asyncio.set_event_loop(self.loop) | ||
|
|
||
| self.instrumentor = AsyncioInstrumentor() | ||
| self.instrumentor.instrument() | ||
|
|
||
| def tearDown(self): | ||
| self.instrumentor.uninstrument() | ||
| self.loop.close() | ||
| asyncio.set_event_loop(None) | ||
| super().tearDown() | ||
|
|
||
| def test_duplicate_instrumentation_of_futures(self): | ||
| """ | ||
| If instrumentor.trace_future is called multiple times on the same Future, | ||
| we should NOT see an unbounded accumulation of callbacks. | ||
| """ | ||
| fut1 = asyncio.Future() | ||
| fut2 = asyncio.Future() | ||
|
|
||
| num_iterations = 10 | ||
| for _ in range(num_iterations): | ||
| self.instrumentor.trace_future(fut1) | ||
| self.instrumentor.trace_future(fut2) | ||
|
|
||
| self.assertLessEqual( | ||
| len(fut1._callbacks), | ||
| 1, | ||
| f"fut1 has {len(fut1._callbacks)} callbacks. Potential leak!", | ||
| ) | ||
| self.assertLessEqual( | ||
| len(fut2._callbacks), | ||
| 1, | ||
| f"fut2 has {len(fut2._callbacks)} callbacks. Potential leak!", | ||
| ) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.