Skip to content

Commit 3baceb0

Browse files
fix(pydantic-ai): limit harness decision span capture
> 🤖 **This text was AI-generated.** A guardrail reason can quote content the policy blocked. Keep the direction and outcome on the span, but leave the reason in the application exception. Allowlist the router's mode, step, probability, and error type so new upstream attributes are not captured implicitly. Skip compaction decision spans when the result was retrieved from detached background work. Foreground compaction still reports the message counts. Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com>
1 parent 6c20268 commit 3baceb0

2 files changed

Lines changed: 44 additions & 9 deletions

File tree

‎py/src/braintrust/integrations/pydantic_ai/_harness.py‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111

1212

1313
async def _compact_messages(wrapped, _instance, args, kwargs):
14+
background = kwargs.get("background")
15+
if background == "used":
16+
return await wrapped(*args, **kwargs)
1417
messages = kwargs["messages"]
1518
before = len(messages)
1619
compacted = await wrapped(*args, **kwargs)
@@ -19,8 +22,8 @@ async def _compact_messages(wrapped, _instance, args, kwargs):
1922
metadata = {"strategy": kwargs["strategy"]}
2023
if kwargs.get("model_requested"):
2124
metadata["model_requested"] = True
22-
if kwargs.get("background") is not None:
23-
metadata["background"] = kwargs["background"]
25+
if background is not None:
26+
metadata["background"] = background
2427
start_span(
2528
name="compact_messages",
2629
type=SpanTypeAttribute.TASK,
@@ -62,13 +65,19 @@ def _trace_guardrail_block(wrapped, _instance, args, kwargs):
6265
name=f"guardrail blocked {direction}",
6366
type=SpanTypeAttribute.TASK,
6467
input={"direction": direction},
65-
output={"action": "block", "reason": kwargs["message"]},
68+
output={"action": "block"},
6669
metadata={"tool_name": tool_name} if tool_name is not None else None,
6770
).end()
6871
return result
6972

7073

7174
_router_span = ContextVar[Span | None]("pydantic_ai_harness_router_span", default=None)
75+
_ROUTER_METADATA_FIELDS = {
76+
"model_router.mode": "mode",
77+
"model_router.run_step": "run_step",
78+
"model_router.probability": "probability",
79+
"model_router.error.type": "error.type",
80+
}
7281

7382

7483
async def _select_model(wrapped, instance, args, kwargs):
@@ -92,10 +101,9 @@ def _record_model_selection(wrapped, _instance, args, kwargs):
92101
span = _router_span.get()
93102
if span is not None:
94103
_, attributes, choice, fallback_reason = args
95-
prefix = "model_router."
96104
span.log(
97105
output={"choice": choice, "fallback_reason": fallback_reason},
98-
metadata={key.removeprefix(prefix): value for key, value in attributes.items() if key.startswith(prefix)},
106+
metadata={field: attributes[key] for key, field in _ROUTER_METADATA_FIELDS.items() if key in attributes},
99107
)
100108
return result
101109

‎py/src/braintrust/integrations/pydantic_ai/harness/test_decisions.py‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
from braintrust import setup_pydantic_ai
55
from braintrust.span_types import SpanTypeAttribute
66
from braintrust.test_helpers import init_test_logger
7-
from pydantic_ai import Agent, ModelSettings
7+
from pydantic_ai import Agent, ModelSettings, RunContext
8+
from pydantic_ai.messages import ModelRequest, UserPromptPart
9+
from pydantic_ai.models import ModelRequestContext, ModelRequestParameters, infer_model
10+
from pydantic_ai.usage import RunUsage
811

912

1013
MODEL = "openai-chat:gpt-4.1-mini"
@@ -61,6 +64,28 @@ def add(x: int, y: int) -> int:
6164
)
6265

6366

67+
@pytest.mark.asyncio
68+
async def test_harness_background_compaction_retrieval_is_not_traced(decision_spans):
69+
compaction = import_module("pydantic_ai_harness.compaction")
70+
model = infer_model(MODEL)
71+
messages = [ModelRequest(parts=[UserPromptPart(prompt)]) for prompt in ("older context " * 10, "current request")]
72+
ctx = RunContext(deps=None, model=model, usage=RunUsage(), messages=messages, conversation_id="background")
73+
request = ModelRequestContext(
74+
model=model, messages=messages.copy(), model_settings=None, model_request_parameters=ModelRequestParameters()
75+
)
76+
fallback = compaction.FallbackCompaction(
77+
[compaction.SlidingWindowCompaction(keep_messages=1, preserve_first_user_message=False)],
78+
max_tokens=100,
79+
background_start=0.1,
80+
)
81+
82+
assert await fallback.before_model_request(ctx, request) is request
83+
compacted = await fallback.take_background_compaction(messages, model=model, conversation_id="background")
84+
85+
assert compacted == messages[-1:]
86+
assert not decision_spans.pop()
87+
88+
6489
@pytest.mark.asyncio
6590
@pytest.mark.vcr
6691
async def test_harness_memory_injection_decision(decision_spans):
@@ -92,7 +117,7 @@ async def test_harness_guardrail_block_decision(decision_spans):
92117

93118
async def check_output(_ctx, output):
94119
if "restricted" in output.lower():
95-
return guardrails.GuardrailResult.block("blocked by test policy")
120+
return guardrails.GuardrailResult.block(f"blocked by test policy: {output}")
96121
return guardrails.GuardrailResult.allow()
97122

98123
agent = Agent(
@@ -102,12 +127,13 @@ async def check_output(_ctx, output):
102127
capabilities=[guardrails.OutputGuardrail(check_output)],
103128
)
104129

105-
with pytest.raises(guardrails.OutputBlocked, match="blocked by test policy"):
130+
with pytest.raises(guardrails.OutputBlocked, match="blocked by test policy: restricted"):
106131
await agent.run("Reply with only the word 'restricted'.")
107132

108133
decision = _decision_span(decision_spans.pop(), "guardrail blocked output")
109134
assert decision["input"] == {"direction": "output"}
110-
assert decision["output"] == {"action": "block", "reason": "blocked by test policy"}
135+
assert decision["output"] == {"action": "block"}
136+
assert "blocked by test policy" not in str(decision)
111137
assert not decision.get("error")
112138

113139

@@ -141,6 +167,7 @@ async def test_harness_model_router_decision(decision_spans, instrument):
141167
decision = _decision_span(spans, "model_router.select")
142168
assert decision["input"] == {"choices": ["default", "alternate"], "default": "default"}
143169
assert decision["metadata"]["mode"] == "once"
170+
assert set(decision["metadata"]) <= {"mode", "run_step", "probability", "error.type"}
144171
assert decision["output"] == {"choice": "alternate", "fallback_reason": "none"}
145172
(router_agent,) = (span for span in spans if span["span_attributes"]["name"] == "agent_run [model_router]")
146173
assert router_agent["span_parents"] == [decision["span_id"]]

0 commit comments

Comments
 (0)