Skip to content

fix(tracing): preserve subagent trace context - #904

Open
linhongyu510 wants to merge 2 commits into
volcengine:mainfrom
linhongyu510:fix/preserve-subagent-trace-context
Open

fix(tracing): preserve subagent trace context#904
linhongyu510 wants to merge 2 commits into
volcengine:mainfrom
linhongyu510:fix/preserve-subagent-trace-context

Conversation

@linhongyu510

@linhongyu510 linhongyu510 commented Aug 15, 2026

Copy link
Copy Markdown

Summary

Fixes #549.

The in-memory span processor attached custom invocation and agent values to the OpenTelemetry context, but did not set the started span as the current span. A nested agent could therefore start without the parent agent span and receive an independent trace ID.

This change:

  • places invocation and agent spans into the attached OTel context with set_span_in_context
  • stores context tokens by span ID because on_end receives a ReadableSpan
  • detaches the matching token when each span ends, restoring the parent context
  • cleans up tokens for RECORD_ONLY spans even though they are not exported
  • keeps cleanup in finally so exporter failures cannot leak context

Validation

tests/tracing/test_inmemory_exporter.py now covers:

  • invocation → parent agent → child agent trace inheritance
  • concurrent asyncio task isolation
  • exceptional agent termination
  • nested non-agent spans
  • ReadableSpan cleanup in on_end
  • unsampled RECORD_ONLY cleanup

Results:

  • target tests — 6 passed
  • Ruff check and format check
  • git diff --check

AI assistance

This change was developed with AI assistance. I reviewed the ContextVar lifecycle, verified the patch with real OpenTelemetry spans, and ran the checks above.

@linhongyu510
linhongyu510 force-pushed the fix/preserve-subagent-trace-context branch from 01286b6 to 73b9eec Compare August 18, 2026 02:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant