Skip to content

Tracing: nested subsegments using trace_method doesn't work across threads, even when setting the trace context #2047

@tibbe

Description

@tibbe

Expected Behaviour

I tried to adapt the recipe for correct tracing in presence of a ThreadPoolExecutor as documented in https://github.com/aws/aws-xray-sdk-python#trace-threadpoolexecutor. I'd expect a function marked with trace_method running on the thread pool to be nested under the function that submited it to the pool, assuming the trace context was set as in the linked docs.

See the code snippet further below for a complete Lambda handler that demonstrates the problem.

Current Behaviour

I'd expect the trace for h() below to nest under f() but it instead shows up as a sibling of the handler itself (i.e. it's technically "above" f()):
Screenshot 2023-03-24 at 12 24 10

Code snippet

from concurrent.futures import ThreadPoolExecutor

from aws_lambda_powertools import Tracer
from aws_xray_sdk.core import xray_recorder

tracer = Tracer()


@tracer.capture_lambda_handler
def handler(event, context):
    del event, context  # Unused.

    with ThreadPoolExecutor() as pool:
        @tracer.capture_method
        def f():
            @tracer.capture_method
            def h():
                pass

            def g(trace_entity):
                xray_recorder.set_trace_entity(trace_entity)
                h()
                xray_recorder.clear_trace_entities()

            curr = xray_recorder.get_trace_entity()
            pool.submit(g, curr)
        f()

Possible Solution

No response

Steps to Reproduce

Create a Lambda containing the above snippet and send it any event.

AWS Lambda Powertools for Python version

latest

AWS Lambda function runtime

3.9

Packaging format used

PyPi

Debugging logs

START RequestId: 210251f5-ee0d-432a-a085-3a8f7c9d529d Version: $LATEST
[WARNING]	2023-03-24T11:17:10.071Z	210251f5-ee0d-432a-a085-3a8f7c9d529d	Removing Segment/Subsugment Name invalid characters from ## benetics.repro.handler.<locals>.f.
[WARNING]	2023-03-24T11:17:10.072Z	210251f5-ee0d-432a-a085-3a8f7c9d529d	Removing Segment/Subsugment Name invalid characters from ## benetics.repro.handler.<locals>.f.<locals>.h.
END RequestId: 210251f5-ee0d-432a-a085-3a8f7c9d529d
REPORT RequestId: 210251f5-ee0d-432a-a085-3a8f7c9d529d	Duration: 6.67 ms	Billed Duration: 2049 ms	Memory Size: 1024 MB	Max Memory Used: 58 MB	Init Duration: 2041.79 ms	
XRAY TraceId: 1-641d86b3-323a174c2c681c082b002ce6	SegmentId: 7058f8f456770f5c	Sampled: true	

Metadata

Metadata

Assignees

Labels

bug-upstreamSomething isn't working in an upstream dependencytracerTracer utility

Type

No type

Projects

Status

Shipped

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions