Repository navigation
Description
Expected Behaviour
@tracer.capture_method on an async generator function (async def with yield), including one used with @contextlib.asynccontextmanager, keeps the subsegment open while the generator runs and records an exception raised inside it. This is how sync generators and context managers already work. The Tracer docs say asynchronous functions and generator functions, including context managers, are supported.
Current Behaviour
capture_method doesn't detect async generators, so they go through the sync path. The subsegment opens and closes when the generator object is created (0 ms), the generator object is stored as the response metadata, and an exception raised while iterating isn't recorded.
Code snippet
import asyncio
import contextlib
import time
from aws_lambda_powertools import Tracer
from aws_lambda_powertools.tracing.base import BaseProvider
class RecordingProvider(BaseProvider):
"""Prints how long each subsegment stays open and what is recorded on it."""
@contextlib.contextmanager
def in_subsegment(self, name=None, **kwargs):
yield from self._record(name)
@contextlib.asynccontextmanager
async def in_subsegment_async(self, name=None, **kwargs):
record = self._record(name)
try:
yield next(record)
finally:
record.close()
def _record(self, name):
start = time.monotonic()
recorded = []
class Subsegment:
def put_metadata(self, key, value, namespace=None):
recorded.append(f"{key.split('.')[-1]}={type(value).__name__}")
def put_annotation(self, key, value): ...
try:
yield Subsegment()
finally:
print(f"{name.split('.')[-1]}: open {(time.monotonic() - start) * 1000:.0f} ms, recorded {recorded}")
def put_annotation(self, key, value): ...
def put_metadata(self, key, value, namespace="default"): ...
def patch(self, modules): ...
def patch_all(self): ...
tracer = Tracer(provider=RecordingProvider(), disabled=False, auto_patch=False)
@tracer.capture_method
def sync_pages():
yield 1
time.sleep(0.05)
yield 2
@tracer.capture_method
async def async_pages():
yield 1
await asyncio.sleep(0.05)
yield 2
raise ValueError("page 3 failed")
async def main():
list(sync_pages())
try:
[page async for page in async_pages()]
except ValueError:
pass
asyncio.run(main())Possible Solution
Detect inspect.isasyncgenfunction and keep the subsegment open with in_subsegment_async while forwarding values and exceptions to the generator. Mirror the existing sync context-manager path for @asynccontextmanager. I have this ready with tests and will open the PR right after this issue.
Steps to Reproduce
Run the snippet. Output on develop (0bbc252), the same on 3.41.0:
sync_pages: open 52 ms, recorded []
async_pages: open 0 ms, recorded ['async_pages response=async_generator']
Did you run the reproduction yourself?
Yes, I ran it and saw the failure. An AI assistant helped me find this, and I ran the snippet on 3.41.0 and develop myself.
Powertools for AWS Lambda (Python) version
3.41.0 and develop @ 0bbc252
AWS Lambda function runtime
3.12
Packaging format used
PyPi
Debugging logs
N/A, the output is shown above.Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsTriage
Activity