Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 14 additions & 17 deletions py/src/braintrust/framework.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import dataclasses
import inspect
import json
import logging
import os
import re
import sys
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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,
Expand Down
93 changes: 92 additions & 1 deletion py/src/braintrust/test_framework.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
import asyncio
import copy
import importlib.util
import logging
import re
import sys
import threading
from concurrent.futures import ThreadPoolExecutor
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 (
Expand All @@ -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


Expand Down Expand Up @@ -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):
Expand Down