LangChain callback handler: "benign" cross-context detach is logged at ERROR by OpenTelemetry (the `except ValueError` guard never fires)

Đã đóng
#1,062 0 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Một pull request liên quan đã được merge.

  • #1064 của @sushan5140 — đã đóng, không merge
  • #1065 của @pcbeingused333 — đã đóng, không merge
  • #1071 của @AbhiPrasad — đã merge

Đánh giá

Độ khó
3/5
Thời gian dự kiến
1-2 ngày
Mức phù hợp với người mới
55/100
Loại issue
Lỗi
Độ rõ ràng
Khá rõ ràng
Mức độ hoạt động
Sôi nổi
Công nghệ
python
Lĩnh vực
observability

Hướng nghiên cứu

Start in braintrust/otel/context.py at ContextManager.unset_current_span, then read _end_span in braintrust/integrations/langchain/callbacks.py, where the dead except ValueError sits. Run the reproduction script in the issue and confirm the opentelemetry.context ERROR appears. Done when that log no longer appears, span parenting is unchanged, and the existing tests pass. Choose one of the three suggested fixes with a maintainer before writing code.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

Summary

With BRAINTRUST_OTEL_COMPAT=true, BraintrustCallbackHandler sets each run's span as the current OTel context when the run starts and unsets it when the run ends. In LangGraph's async runtime, a run can start in one asyncio task and end in another. The OTel token then belongs to a different contextvars.Context, and every such run logs this at ERROR with a traceback:

ERROR:opentelemetry.context:Failed to detach context
Traceback (most recent call last):
  File ".../opentelemetry/context/__init__.py", line 155, in detach
    _RUNTIME_CONTEXT.detach(token)
  File ".../opentelemetry/context/contextvars_context.py", line 53, in detach
    self._current_context.reset(token)
ValueError: <Token var=<ContextVar name='current_context' ...> at 0x...> was created in a different Context

The handler already anticipates this. In braintrust/integrations/langchain/callbacks.py, _end_span:

# Async callbacks may unset from a different context; span state is
# tracked in self.spans, so this ValueError is benign.
try:
    span.unset_current()
except ValueError as e:
    if "was created in a different Context" in str(e):
        pass
    else:
        raise

But that except can never catch the error. span.unset_current() reaches opentelemetry.context.detach(token) (via braintrust/otel/context.py, ContextManager.unset_current_span). OTel's detach catches the ValueError itself and logs it with logger.exception("Failed to detach context"). Nothing is raised to Braintrust, so the guard is dead code and the "benign" error reaches the logs at ERROR.

We agree it's benign. Span parenting in our traces is correct. But in production it was 100% of the ERROR lines on our agent service for a week. That breaks "no ERRORs after deploy" checks and buries real errors.

Reproduction (no network)
import contextvars
import logging
import os
import uuid

os.environ["BRAINTRUST_OTEL_COMPAT"] = "true"
logging.basicConfig(level=logging.INFO)

from braintrust import logger as bt
from braintrust.test_helpers import init_test_logger, simulate_login
from braintrust.integrations.langchain import BraintrustCallbackHandler

# In-memory logger, no network.
simulate_login()
with bt._internal_with_memory_background_logger():
    handler = BraintrustCallbackHandler(logger=init_test_logger("repro"))
    run_id = uuid.uuid4()
    # LangGraph's async runtime can fire start and end for one run in different tasks.
    contextvars.copy_context().run(handler.on_chain_start, {"name": "node"}, {}, run_id=run_id)
    contextvars.copy_context().run(handler.on_chain_end, {}, run_id=run_id)
    # -> ERROR:opentelemetry.context:Failed to detach context
    #    ValueError: <Token ...> was created in a different Context

A real async LangGraph run shows the same thing with no manual context juggling. A two-node StateGraph of async nodes, run with await graph.ainvoke(..., config={"callbacks": [handler]}), logs 3 of these errors per invocation.

Versions
  • braintrust 0.31.0. The relevant code (_end_span in integrations/langchain/callbacks.py and ContextManager.unset_current_span in otel/context.py) is unchanged in 0.49.2.
  • opentelemetry-api 1.37.0
  • langchain-core 1.5.3, langgraph 1.2.10
  • Python 3.12
Suggested fix

Handle the mismatch where the token is actually reset, rather than relying on OTel to raise. Some options:

  1. In ContextManager.unset_current_span, skip OTel's public context.detach (which always logs) and reset the token without logging, catching ValueError there. This would use OTel's runtime context directly.
  2. Record which contextvars.Context a span was attached in (for example, compare contextvars.copy_context() identity or a marker ContextVar set alongside the attach). Only detach when ending in that same context; otherwise drop the token.
  3. At minimum, remove the dead except ValueError in _end_span and document the ERROR log, so users know to filter opentelemetry.context themselves.
Workaround we use

A logging.Filter on the opentelemetry.context logger. It drops a record only when all three hold: the message is Failed to detach context, the exception is this ValueError, and braintrust/integrations/langchain/callbacks.py:_end_span is on the live call stack. Any other detach failure still logs. It works, but every Braintrust + LangGraph + OTel user will hit this, so it would be better fixed in the SDK.

Related

#7 was the same ValueError in the Claude Agent SDK wrapper, where it was raised (fixed in 0.9.0). This one is in the LangChain integration, and OpenTelemetry logs it rather than raising it, so a try/except around unset_current() cannot catch it.

Ngôn ngữ chính
Python
Star
22
Fork
30
Merge trung bình
9 giờ
Pull request đã merge (30 ngày)
128

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của braintrustdata/braintrust-sdk-python

Tất cả issue của braintrustdata/braintrust-sdk-python

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.