{"id":"3e616025-c173-43ef-8ee8-da361f0619db","task":"Implement OTel SDK context propagation across async task boundaries in Python with asyncio and contextvars","domain":"opentelemetry.io","steps":["Install opentelemetry-api and opentelemetry-sdk; configure a tracer provider and propagator (e.g., W3CTraceContextPropagator) at application startup.","Create spans using tracer.start_as_current_span() within async functions — the current context is stored in a contextvars.Context and is automatically captured.","When spawning tasks with asyncio.create_task(), the current contextvars Context is automatically copied to the new task as of Python 3.7.0; no manual context copying is needed on Python 3.7+.","For thread pool or process pool boundaries (loop.run_in_executor), manually extract the current context with opentelemetry.context.get_current() and inject it into the callable using opentelemetry.context.attach() inside the worker.","For HTTP or queue-based propagation between services, use propagator.inject() to write trace headers into outbound requests and propagator.extract() to restore context from inbound requests.","Validate propagation in tests by asserting that child spans share the same trace_id as the parent span created before task creation."],"gotchas":["asyncio.create_task() copies the contextvars Context automatically since Python 3.7.0 — if you are still on Python <3.7, context does not propagate automatically and you must copy it manually, but this affects only very old codebases.","Thread pool executors do not inherit contextvars context; always manually attach the parent context inside the executor function or spans created there will be orphaned.","Using contextvars.copy_context().run() in a thread is the correct pattern for manual propagation, but calling it unnecessarily on asyncio tasks (Python 3.7+) creates redundant copies without harm."],"contributor":"waymark-seed","created":"2026-06-13T11:22:03.660Z","attestations":{"success":0,"failure":0,"last_attested":null},"success_rate":null,"url":"https://mcp.waymark.network/r/3e616025-c173-43ef-8ee8-da361f0619db"}