LangChain callback handler: "benign" cross-context detach is logged at ERROR by OpenTelemetry (the `except ValueError` guard never fires)
Los mantenedores suelen responder en 1 día
Ya se ha fusionado un pull request relacionado.
Evaluación
- Dificultad
- 3/5
- Tiempo estimado
- 1-2 días
- Aptitud para principiantes
- 55/100
- Tipo de issue
- Error
- Claridad
- Bastante claro
- Estado de actividad
- Activo
- Stack tecnológico
- python
- Área
- observability
Línea de trabajo
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.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
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_spaninintegrations/langchain/callbacks.pyandContextManager.unset_current_spaninotel/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:
- In
ContextManager.unset_current_span, skip OTel's publiccontext.detach(which always logs) and reset the token without logging, catchingValueErrorthere. This would use OTel's runtime context directly. - Record which
contextvars.Contexta span was attached in (for example, comparecontextvars.copy_context()identity or a markerContextVarset alongside the attach). Only detach when ending in that same context; otherwise drop the token. - At minimum, remove the dead
except ValueErrorin_end_spanand document the ERROR log, so users know to filteropentelemetry.contextthemselves.
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.
- Lenguaje dominante
- Python
- Estrellas
- 22
- Forks
- 30
- Merge medio
- 9 h
- PR fusionados (30 d)
- 128
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Sin plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de braintrustdata/braintrust-sdk-python
-
Temporal: add `workflow.Info.original_execution_run_id` to workflow span metadataPosiblemente ocupada @Mohith26 la tomó hace 3 días. Abiertofeature python
Dificultad 2/5 1-3 horas Aptitud para principiantes 76/100
braintrustdata/braintrust-sdk-python#868 ·
Los mantenedores suelen responder en 1 día
-
python
Dificultad 4/5 3-5 días Aptitud para principiantes 38/100
braintrustdata/braintrust-sdk-python#1063 ·
Los mantenedores suelen responder en 1 día
-
python
Dificultad 4/5 3-5 días Aptitud para principiantes 25/100
braintrustdata/braintrust-sdk-python#1038 ·
Los mantenedores suelen responder en 1 día
-
new-integration python
Dificultad 5/5 Más de una semana Aptitud para principiantes 35/100
braintrustdata/braintrust-sdk-python#999 ·
Los mantenedores suelen responder en 1 día
-
python
Dificultad 5/5 Más de una semana Aptitud para principiantes 20/100
braintrustdata/braintrust-sdk-python#957 ·
Los mantenedores suelen responder en 1 día
Todos los issues de braintrustdata/braintrust-sdk-python
Issues similares
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
didi/helixharness#18 ·
-
[MOVIE]: Airport '77 (1977)Abiertorequest-theme
Dificultad 1/5 Menos de una hora Aptitud para principiantes 78/100
LizardByte/ThemerrDB#9883 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 75/100
NousResearch/hermes-agent#149885 ·
Los mantenedores suelen responder en 1 día
-
Set cache_ok = True on GUID TypeDecorator to enable SQLAlchemy query cachingPosiblemente ocupada @patelshivani2283-lab la tomó hoy. Abierto
Dificultad 1/5 Menos de una hora Aptitud para principiantes 91/100
fedora-infra/anitya#2157 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
Project-MONAI/MONAI#9258 ·
Los mantenedores suelen responder en 3 días