Skip to content

Bug: Tracer's BaseProvider declares in_subsegment_async as a synchronous context manager #8365

Description

@tibbe

Expected Behaviour

The type checker accepts async with tracer.provider.in_subsegment_async(...).

The abstract method in_subsegment_async in
aws_lambda_powertools/tracing/base.py returns an asynchronous context
manager. Its annotation shows this:
-> AbstractAsyncContextManager[BaseSegment]. The declaration does not
have the @contextmanager decorator.

Current Behaviour

The abstract method has the @contextmanager decorator. Its return
annotation is Generator[BaseSegment, None, None]. These declarations
tell the type checker that the method returns a synchronous context
manager.

This declaration does not agree with three parts of Powertools:

  1. Tracer._decorate_async_function enters the result with async with.
  2. The capture_method documentation shows in_subsegment_async with
    async with as the escape hatch for concurrent asynchronous functions.
  3. The default provider is the recorder from aws-xray-sdk. Its
    in_subsegment_async returns an asynchronous context manager.

Thus correct code causes a type error. The user must add a cast to
remove the error.

Code snippet

from aws_lambda_powertools import Tracer

tracer = Tracer()


async def handler_body() -> None:
    async with tracer.provider.in_subsegment_async(name="## example"):
        ...

mypy reports:

error: "_GeneratorContextManager[BaseSegment, None, None]" has no attribute "__aenter__"  [attr-defined]
error: "_GeneratorContextManager[BaseSegment, None, None]" has no attribute "__aexit__"; maybe "__exit__"?  [attr-defined]

Possible Solution

Change the declaration in BaseProvider:

  1. Remove the @contextmanager decorator from the abstract method.
  2. Change the return annotation to
    AbstractAsyncContextManager[BaseSegment].

This change makes the interface agree with _decorate_async_function,
with the documentation, and with the shipped X-Ray provider.

Steps to Reproduce

  1. Save the code snippet above to a file.
  2. Run mypy on the file.
  3. See the two errors above.

Powertools for AWS Lambda (Python) version

3.22.0

AWS Lambda function runtime

3.14

Packaging format used

PyPi

Debugging logs

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingtriagePending triage from maintainers

    Type

    No type

    Projects

    Status
    Triage

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions