-
Notifications
You must be signed in to change notification settings - Fork 7
feat(tracing): Add background queue for async span processing #303
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
Show all changes
6 commits
Select commit
Hold shift + click to select a range
97bcaf4
fix(tracing): Fix memory leak in SGP tracing processors
smoreinis 26402d0
feat(tracing): Add background queue for async span processing
smoreinis 67ed156
fix(tests): Use context manager patches for sync processor tests
smoreinis 8afd5d4
Merge branch 'main' into stas/async-span-queue
smoreinis 84b3bca
fix(tests): Satisfy pyright type check for span output assignment
smoreinis 1a4f0b7
fix(tracing): Deep-copy spans before enqueuing to background queue
smoreinis 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,19 @@ | ||
| from agentex.types.span import Span | ||
| from agentex.lib.core.tracing.trace import Trace, AsyncTrace | ||
| from agentex.lib.core.tracing.tracer import Tracer, AsyncTracer | ||
| from agentex.lib.core.tracing.span_queue import ( | ||
| AsyncSpanQueue, | ||
| get_default_span_queue, | ||
| shutdown_default_span_queue, | ||
| ) | ||
|
|
||
| __all__ = ["Trace", "AsyncTrace", "Span", "Tracer", "AsyncTracer"] | ||
| __all__ = [ | ||
| "Trace", | ||
| "AsyncTrace", | ||
| "Span", | ||
| "Tracer", | ||
| "AsyncTracer", | ||
| "AsyncSpanQueue", | ||
| "get_default_span_queue", | ||
| "shutdown_default_span_queue", | ||
| ] |
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,111 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| from enum import Enum | ||
| from dataclasses import dataclass | ||
|
|
||
| from agentex.types.span import Span | ||
| from agentex.lib.utils.logging import make_logger | ||
| from agentex.lib.core.tracing.processors.tracing_processor_interface import ( | ||
| AsyncTracingProcessor, | ||
| ) | ||
|
|
||
| logger = make_logger(__name__) | ||
|
|
||
|
|
||
| class SpanEventType(str, Enum): | ||
| START = "start" | ||
| END = "end" | ||
|
|
||
|
|
||
| @dataclass | ||
| class _SpanQueueItem: | ||
| event_type: SpanEventType | ||
| span: Span | ||
| processors: list[AsyncTracingProcessor] | ||
|
|
||
|
|
||
| class AsyncSpanQueue: | ||
| """Background FIFO queue for async span processing. | ||
|
|
||
| Span events are enqueued synchronously (non-blocking) and processed | ||
| sequentially by a background drain task. This keeps tracing HTTP calls | ||
| off the critical request path while preserving start-before-end ordering. | ||
| """ | ||
|
|
||
| def __init__(self) -> None: | ||
| self._queue: asyncio.Queue[_SpanQueueItem] = asyncio.Queue() | ||
| self._drain_task: asyncio.Task[None] | None = None | ||
| self._stopping = False | ||
|
|
||
| def enqueue( | ||
| self, | ||
| event_type: SpanEventType, | ||
| span: Span, | ||
| processors: list[AsyncTracingProcessor], | ||
| ) -> None: | ||
| if self._stopping: | ||
| logger.warning("Span queue is shutting down, dropping %s event for span %s", event_type.value, span.id) | ||
| return | ||
| self._ensure_drain_running() | ||
| self._queue.put_nowait(_SpanQueueItem(event_type=event_type, span=span, processors=processors)) | ||
|
|
||
| def _ensure_drain_running(self) -> None: | ||
| if self._drain_task is None or self._drain_task.done(): | ||
| self._drain_task = asyncio.create_task(self._drain_loop()) | ||
|
|
||
| async def _drain_loop(self) -> None: | ||
| while True: | ||
| item = await self._queue.get() | ||
| try: | ||
| if item.event_type == SpanEventType.START: | ||
| coros = [p.on_span_start(item.span) for p in item.processors] | ||
| else: | ||
| coros = [p.on_span_end(item.span) for p in item.processors] | ||
| results = await asyncio.gather(*coros, return_exceptions=True) | ||
| for result in results: | ||
| if isinstance(result, Exception): | ||
| logger.error( | ||
| "Tracing processor error during %s for span %s", | ||
| item.event_type.value, | ||
| item.span.id, | ||
| exc_info=result, | ||
| ) | ||
| except Exception: | ||
| logger.exception("Unexpected error in span queue drain loop for span %s", item.span.id) | ||
| finally: | ||
| self._queue.task_done() | ||
|
|
||
| async def shutdown(self, timeout: float = 30.0) -> None: | ||
| self._stopping = True | ||
| if self._queue.empty() and (self._drain_task is None or self._drain_task.done()): | ||
| return | ||
| try: | ||
| await asyncio.wait_for(self._queue.join(), timeout=timeout) | ||
| except asyncio.TimeoutError: | ||
| logger.warning( | ||
| "Span queue shutdown timed out after %.1fs with %d items remaining", timeout, self._queue.qsize() | ||
| ) | ||
| if self._drain_task is not None and not self._drain_task.done(): | ||
| self._drain_task.cancel() | ||
| try: | ||
| await self._drain_task | ||
| except asyncio.CancelledError: | ||
| pass | ||
|
|
||
|
|
||
| _default_span_queue: AsyncSpanQueue | None = None | ||
|
|
||
|
|
||
| def get_default_span_queue() -> AsyncSpanQueue: | ||
| global _default_span_queue | ||
| if _default_span_queue is None: | ||
| _default_span_queue = AsyncSpanQueue() | ||
| return _default_span_queue | ||
|
|
||
|
|
||
| async def shutdown_default_span_queue(timeout: float = 30.0) -> None: | ||
| global _default_span_queue | ||
| if _default_span_queue is not None: | ||
| await _default_span_queue.shutdown(timeout=timeout) | ||
| _default_span_queue = None |
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
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.
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.
Uh oh!
There was an error while loading. Please reload this page.