Repository navigation
fix(runtime): flush tracing spans after invocations #721
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 all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -22,6 +22,7 @@ | |
| provider after the app is constructed. | ||
| """ | ||
|
|
||
| import asyncio | ||
| import logging | ||
| import threading | ||
| from typing import Optional | ||
|
|
@@ -33,6 +34,7 @@ | |
| # Module-level state for provider-tracking auto-registration. | ||
| _registration_lock = threading.Lock() | ||
| _registered_on: Optional[object] = None # the TracerProvider instance we last registered on | ||
| _flush_lock = threading.Lock() | ||
|
|
||
|
|
||
| def _ensure_baggage_processor_registered() -> None: | ||
|
|
@@ -63,6 +65,35 @@ def _ensure_baggage_processor_registered() -> None: | |
| logger.debug("Could not register BaggageSpanProcessor", exc_info=True) | ||
|
|
||
|
|
||
| def _flush_tracer_provider(timeout_millis: int = 30000) -> None: | ||
| """Flush buffered spans before AgentCore Runtime freezes the microVM.""" | ||
| if not _flush_lock.acquire(blocking=False): | ||
| logger.debug("Tracer provider flush already in progress; skipping duplicate flush") | ||
| return | ||
|
|
||
| try: | ||
| from opentelemetry import trace | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. import should be on top |
||
|
|
||
| trace.get_tracer_provider().force_flush(timeout_millis=timeout_millis) | ||
| except ImportError: | ||
| logger.debug("opentelemetry-api not installed; tracer provider flush skipped") | ||
| except Exception: | ||
| logger.debug("Could not flush tracer provider", exc_info=True) | ||
| finally: | ||
| _flush_lock.release() | ||
|
|
||
|
|
||
| async def _flush_tracer_provider_async(timeout_millis: int = 30000) -> None: | ||
| """Flush buffered spans without blocking the event loop or response indefinitely.""" | ||
| try: | ||
| await asyncio.wait_for( | ||
| asyncio.to_thread(_flush_tracer_provider, timeout_millis), | ||
| timeout=timeout_millis / 1000, | ||
| ) | ||
| except asyncio.TimeoutError: | ||
| logger.debug("Timed out waiting for tracer provider flush after %d ms", timeout_millis) | ||
|
|
||
|
|
||
| def _get_base_class() -> type: | ||
| """Return the OTel SDK SpanProcessor base if available, otherwise object. | ||
|
|
||
|
|
||
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
calls
force_flush()from the async invocation handler; the streaming wrapper does the same at L#899. If an exporter stalls,/pingand other requests cant run while the flush waits. OpenTelemetry’s processor can block during export, and its current implementation does not enforce the timeout. Run the flush off the event loop and bound how long a response waits for itThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Addressed in 1924ef7. Async response paths now run the flush with
asyncio.to_thread()and bound the await withasyncio.wait_for(), so the event loop remains available for/pingand other requests even if an exporter stalls. A non-blocking flush lock also coalesces overlapping flushes so a stuck exporter cannot consume additional worker threads. Added coverage for worker-thread execution, bounded waiting, and duplicate-flush handling; all runtime tests pass.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Current commit after the branch refresh is e15e250 (superseding the hash in my previous reply).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also validated this against a hosted AgentCore Runtime using the PR commit. A test span processor deliberately blocked
force_flush()for 45 seconds while ignoring its timeout. During that blocked flush, a same-process/pingprobe returnedHealthyin 9 ms. The invocation stopped waiting at the 30-second bound, and a second invocation on the same runtime session/process completed in 2.36 seconds while the original flush was still running, confirming overlapping flushes are coalesced. The temporary runtime and stack were deleted after the test.