Skip to content

Bug: @agent leaks gen_ai.agent.name into subsequent spans #4378

Description

@yaodong-shen

Which component is this bug for?

Traceloop SDK

Description

After a function decorated with @agent returns, the gen_ai.agent.name context value remains active. Later spans that are unrelated to the completed agent are therefore tagged with that agent name.

This affects both:

  • a standalone task executed after a completed bare agent
  • a task executed inside the same workflow after a nested agent has completed

The second case makes sibling work appear to belong to the preceding agent even though the agent scope has ended.

This is reproducible on current main@93429cfb and traceloop-sdk==0.62.1.

Reproduction

from traceloop.sdk.decorators import agent, task, workflow

@agent(name="planner")
def planner_agent():
    pass

@task(name="after_agent")
def task_after_agent():
    pass

@workflow(name="rag")
def rag_workflow():
    planner_agent()
    task_after_agent()

rag_workflow()

The after_agent.task span incorrectly contains:

gen_ai.agent.name = "planner"

A bare completed_agent(); standalone_task() sequence produces the same leak, and the standalone task is incorrectly tagged with the completed agent name.

Expected behavior

Agent metadata should be scoped to the decorated agent invocation and its descendants. When the agent exits, the previous OpenTelemetry context should be restored. A task after the agent should retain an enclosing workflow name when present, but should not inherit the completed agent name.

Root cause

_setup_span() calls set_agent_name(entity_name) before it attaches the span context. The context token returned by that attach is discarded. Cleanup only detaches the later span token, which restores the already-modified context containing the agent name.

Proposed fix

Add the agent name to the span context before attaching that context, so the existing cleanup token restores the prior context in one operation. Add regression tests for a completed bare agent followed by an independent task and for an agent followed by a sibling task inside a workflow.

Python Version

3.11

Duplicate check

I searched open Issues and PRs for agent-name context leaks and agent decorator context restoration and found no existing report or implementation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions