Skip to content

fix(langchain): _create_llm_span() overwrites SpanHolder causing potential context token loss #3956

@coderabbitai

Description

@coderabbitai

Summary

In packages/opentelemetry-instrumentation-langchain/opentelemetry/instrumentation/langchain/callback_handler.py, the _create_llm_span() method overwrites an existing SpanHolder entry in the span registry without first detaching the context tokens stored in the previous holder. This is pre-existing behavior that predates PR #3807.

Problem

When _create_llm_span() is called for a run ID that already has a SpanHolder in the registry, it replaces that entry directly. The old holder's token (and now association_properties_token introduced in #3807) are lost without being detached, which could silently corrupt the OpenTelemetry context stack in certain execution flows.

Impact

Related

Suggested Fix

Before overwriting a SpanHolder entry in _create_llm_span(), check if an existing holder is present and detach its context tokens (token and association_properties_token) before replacing it.

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