From 5f462da30f863ef29aec5c1402ad100e848f4954 Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Mon, 23 Nov 2026 18:42:58 -0500 Subject: [PATCH] fix(eval): decode v4 parents for trace scorers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > 🤖 **This text was AI-generated.** Eval trace scorers used a V3 decoder, so a V4 project or playground log parent caused scorers to look for spans in the experiment. ``` V4 log parent -> V3 decoder fails -> experiment fallback V4 log parent -> V4 decoder succeeds -> parent's log destination ``` The V4 decoder also accepts older exports. Malformed parent strings emit a debug log and keep the experiment fallback. W3C context dictionaries bypass slug decoding. Refs: SDK-926 --- py/src/braintrust/framework.py | 31 +++++----- py/src/braintrust/test_framework.py | 93 ++++++++++++++++++++++++++++- 2 files changed, 106 insertions(+), 18 deletions(-) diff --git a/py/src/braintrust/framework.py b/py/src/braintrust/framework.py index 2a3260143..08dc33a30 100644 --- a/py/src/braintrust/framework.py +++ b/py/src/braintrust/framework.py @@ -7,6 +7,7 @@ import dataclasses import inspect import json +import logging import os import re import sys @@ -68,11 +69,15 @@ is_scorer, ) from .serializable_data_class import SerializableDataClass +from .span_identifier_v3 import span_object_type_v3_to_typed_string +from .span_identifier_v4 import SpanComponentsV4 from .span_types import SpanTypeAttribute from .types._eval import EvalCaseDict, EvalCaseDictNoOutput, ExperimentDatasetEvent from .util import bt_iscoroutinefunction, eprint, get_signature, merge_dicts +_logger = logging.getLogger(__name__) + Input = TypeVar("Input") Output = TypeVar("Output") Expected = TypeVar("Expected") @@ -1848,25 +1853,17 @@ async def ensure_spans_flushed(): # The Span interface doesn't expose this but SpanImpl has it root_span_id_value = getattr(root_span, "root_span_id", root_span.id) - # Check if there's a parent in the context to determine object_type and object_id - from braintrust.span_identifier_v3 import SpanComponentsV3, span_object_type_v3_to_typed_string - - parent_str = trace_state.current_parent.get() - parent_components = None - if parent_str: + trace_object_type = "experiment" + trace_object_id = experiment_id or "" + parent = trace_state.current_parent.get() + if isinstance(parent, str) and parent: try: - parent_components = SpanComponentsV3.from_str(parent_str) + parent_components = SpanComponentsV4.from_str(parent) except Exception: - # If parsing fails, parent_components stays None - pass - - # Determine object_type and object_id based on parent or experiment - if parent_components: - trace_object_type = span_object_type_v3_to_typed_string(parent_components.object_type) - trace_object_id = parent_components.object_id or "" - else: - trace_object_type = "experiment" - trace_object_id = experiment_id or "" + _logger.debug("Failed to decode span parent for eval trace", exc_info=True) + else: + trace_object_type = span_object_type_v3_to_typed_string(parent_components.object_type) + trace_object_id = parent_components.object_id or "" trace = LocalTrace( object_type=trace_object_type, diff --git a/py/src/braintrust/test_framework.py b/py/src/braintrust/test_framework.py index 6c4db66f5..2cbf2cbc6 100644 --- a/py/src/braintrust/test_framework.py +++ b/py/src/braintrust/test_framework.py @@ -1,6 +1,7 @@ import asyncio import copy import importlib.util +import logging import re import sys import threading @@ -8,7 +9,14 @@ from unittest.mock import MagicMock, patch import pytest -from braintrust.logger import BraintrustState, Dataset, ObjectMetadata, ProjectDatasetMetadata, parent_context +from braintrust.logger import ( + BraintrustState, + Dataset, + ObjectMetadata, + ProjectDatasetMetadata, + _internal_get_global_state, + parent_context, +) from braintrust.util import LazyValue from .framework import ( @@ -28,6 +36,8 @@ ) from .resource_manager import ResourceManager from .score import Classification, Score, Scorer +from .span_identifier_v3 import SpanComponentsV3, SpanObjectTypeV3 +from .span_identifier_v4 import SpanComponentsV4 from .test_helpers import init_test_exp, with_memory_logger, with_simulate_login # noqa: F401 @@ -287,6 +297,87 @@ def exact_match(input_value, output, expected): assert result.summary.scores["exact_match"].score == 1.0 +@pytest.mark.parametrize("components", [SpanComponentsV3, SpanComponentsV4], ids=["v3", "v4"]) +@pytest.mark.parametrize( + ("object_type", "expected_type"), + [(SpanObjectTypeV3.PROJECT_LOGS, "project_logs"), (SpanObjectTypeV3.PLAYGROUND_LOGS, "playground_logs")], + ids=["project_logs", "playground_logs"], +) +@pytest.mark.asyncio +async def test_eval_trace_scorer_uses_parent_destination(components, object_type, expected_type, with_memory_logger): + parent = components( + object_type=object_type, + object_id="logs-object-id", + row_id="parent-row-id", + span_id="0123456789abcdef", + root_span_id="abcdef01-2345-6789-abcd-ef0123456789", + ) + trace_configs = [] + + def trace_scorer(trace): + trace_configs.append(trace.get_configuration()) + return 1.0 + + await EvalAsync( + "test-trace-scorer", + data=[EvalCase(input=1)], + task=lambda value: value, + scores=[trace_scorer], + parent=parent.to_str(), + state=_internal_get_global_state(), + ) + + assert trace_configs == [ + {"object_type": expected_type, "object_id": parent.object_id, "root_span_id": parent.root_span_id} + ] + + +@pytest.mark.parametrize( + ("parent", "expected_decode_failures"), + [ + ("invalid-parent", [logging.DEBUG]), + ({"traceparent": "00-abcdef0123456789abcdef0123456789-0123456789abcdef-01"}, []), + ], + ids=["malformed-slug", "w3c-context"], +) +@pytest.mark.asyncio +async def test_run_evaluator_trace_parent_fallback( + parent, expected_decode_failures, caplog, with_memory_logger, with_simulate_login +): + experiment = init_test_exp("test-trace-scorer", "test-project") + trace_configs = [] + + def trace_scorer(trace): + trace_configs.append(trace.get_configuration()) + return 1.0 + + evaluator = Evaluator( + project_name="test-project", + eval_name="test-trace-scorer", + data=[EvalCase(input=1)], + task=lambda value: value, + scores=[trace_scorer], + experiment_name=None, + metadata=None, + summarize_scores=False, + ) + with ( + parent_context(parent, experiment.state), + caplog.at_level(logging.DEBUG, logger="braintrust.framework"), + ): + await run_evaluator(experiment=experiment, evaluator=evaluator, position=None, filters=[]) + + assert len(trace_configs) == 1 + assert trace_configs[0]["object_type"] == "experiment" + assert trace_configs[0]["object_id"] == experiment.id + decode_failures = [ + level + for logger_name, level, message in caplog.record_tuples + if logger_name == "braintrust.framework" and message == "Failed to decode span parent for eval trace" + ] + assert decode_failures == expected_decode_failures + + @pytest.mark.parametrize("is_async", [False, True], ids=["Eval", "EvalAsync"]) @pytest.mark.parametrize("data_kind", ["iterator", "factory", "awaitable", "async-factory"]) def test_eval_resolves_awaitable_data(is_async, data_kind):