Skip to content

Commit 5694357

Browse files
fix(anthropic): enforce provider privacy and prevent stray child rows on batch completion
> 🤖 **This text was AI-generated.** ### Problem 1. `complete_anthropic_batch_trace` / `complete_anthropic_batch_trace_async` wrote completion updates via `update_span()` without applying the active `provider_content_allowed` privacy policy, allowing `output`, `error`, and content-bearing `metadata` through when provider content capture is disabled. 2. In saved-context mode (where only `request_count` and `request_ids_digest` are stored), an unknown `custom_id` in `results` wrote a child `update_span` row before `_finalize_task_span` rejected the batch on digest mismatch. ### Solution - Added `_apply_provider_privacy()` to redact `input`, `output`, `error`, and non-`model`/`provider` `metadata` keys on child and task completion updates when `provider_content_allowed` is false. - In saved-context mode (`known_ids is None`), stage validated child update payloads and only flush them once `seen_ids` matches `request_count` and `request_ids_digest`, so unknown/incomplete result sets never emit stray child rows. - Added VCR-backed assertions covering both cases in `test_incomplete_and_invalid_context_handling`. Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com> Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent 3c5721b commit 5694357

2 files changed

Lines changed: 77 additions & 22 deletions

File tree

‎py/src/braintrust/integrations/anthropic/batch.py‎

Lines changed: 54 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from datetime import datetime, timezone
1717
from typing import Any
1818

19+
from braintrust._instrumentation import provider_content_allowed
1920
from braintrust.integrations.anthropic._utils import _try_to_dict, extract_anthropic_usage
2021
from braintrust.integrations.anthropic.tracing import (
2122
_INSTRUMENTATION,
@@ -443,56 +444,72 @@ def _prepare_completion(
443444
return parsed, known_ids, end_time
444445

445446

446-
def _process_result_entry(
447+
def _apply_provider_privacy(event: dict[str, Any]) -> dict[str, Any]:
448+
policy = provider_content_allowed.get()
449+
if policy is None or policy():
450+
return event
451+
redacted = {k: v for k, v in event.items() if k not in ("input", "output", "error")}
452+
metadata = redacted.get("metadata")
453+
if isinstance(metadata, dict):
454+
redacted["metadata"] = {k: metadata[k] for k in ("model", "provider") if k in metadata}
455+
return redacted
456+
457+
458+
def _build_child_update_event(
447459
entry: Any,
448460
*,
449461
batch_id: str,
450462
task_components: SpanComponentsV4,
451463
end_time: float,
452464
seen_ids: set[str],
453465
known_ids: set[str] | None,
454-
) -> bool:
466+
expected_count: int,
467+
) -> tuple[str, dict[str, Any]] | None:
455468
custom_id = _get_field(entry, "custom_id")
456469
if not isinstance(custom_id, str) or not custom_id:
457470
log.debug("Anthropic batch completion paused: malformed result missing custom_id")
458-
return False
471+
return None
459472
if custom_id in seen_ids:
460473
log.debug("Anthropic batch completion paused: duplicate custom_id %r", custom_id)
461-
return False
474+
return None
462475
if known_ids is not None and custom_id not in known_ids:
463476
log.debug("Anthropic batch completion paused: unknown custom_id %r", custom_id)
464-
return False
477+
return None
478+
if len(seen_ids) >= expected_count:
479+
log.debug("Anthropic batch completion paused: result count exceeds started request count (%d)", expected_count)
480+
return None
465481

466482
result = _get_field(entry, "result")
467483
result_type = _get_field(result, "type")
468484
if result_type not in _VALID_RESULT_TYPES:
469485
log.debug("Anthropic batch completion paused: invalid result type %r for %r", result_type, custom_id)
470-
return False
486+
return None
471487

472488
exported = _child_slug(task_components, batch_id, custom_id)
473489
if result_type == "succeeded":
474490
message = _get_field(result, "message")
475491
if message is None:
476492
log.debug("Anthropic batch completion paused: missing message for succeeded result %r", custom_id)
477-
return False
478-
update_span(exported=exported, **_build_succeeded_update(message, end_time))
493+
return None
494+
event = _build_succeeded_update(message, end_time)
479495
elif result_type == "errored":
480496
error_msg = _extract_error_message(_get_field(result, "error"), "Anthropic batch request errored")
481-
update_span(exported=exported, error=error_msg, metrics={"end": end_time})
497+
event = {"error": error_msg, "metrics": {"end": end_time}}
482498
elif result_type == "canceled":
483-
update_span(exported=exported, error="Anthropic batch request canceled", metrics={"end": end_time})
499+
event = {"error": "Anthropic batch request canceled", "metrics": {"end": end_time}}
484500
else:
485-
update_span(exported=exported, error="Anthropic batch request expired", metrics={"end": end_time})
501+
event = {"error": "Anthropic batch request expired", "metrics": {"end": end_time}}
486502

487503
seen_ids.add(custom_id)
488-
return True
504+
return exported, _apply_provider_privacy(event)
489505

490506

491507
def _finalize_task_span(
492508
batch: Any,
493509
parsed: dict[str, Any],
494510
seen_ids: set[str],
495511
end_time: float,
512+
pending_updates: list[tuple[str, dict[str, Any]]] | None = None,
496513
) -> None:
497514
if len(seen_ids) != parsed["request_count"] or _request_ids_digest(seen_ids) != parsed["request_ids_digest"]:
498515
log.debug(
@@ -518,6 +535,10 @@ def _finalize_task_span(
518535
)
519536
return
520537

538+
if pending_updates:
539+
for exported, child_event in pending_updates:
540+
update_span(exported=exported, **child_event)
541+
521542
task_metadata: dict[str, Any] = {
522543
"provider": "anthropic",
523544
"batch_id": parsed["batch_id"],
@@ -547,7 +568,7 @@ def _finalize_task_span(
547568
}
548569
if task_error is not None:
549570
event["error"] = task_error
550-
update_span(exported=parsed["task_slug"], **event)
571+
update_span(exported=parsed["task_slug"], **_apply_provider_privacy(event))
551572

552573

553574
def start_anthropic_batch_trace(
@@ -605,19 +626,26 @@ def complete_anthropic_batch_trace(
605626
return
606627

607628
seen_ids: set[str] = set()
629+
pending_updates: list[tuple[str, dict[str, Any]]] | None = [] if known_ids is None else None
608630
for entry in _iter_records(results):
609-
ok = _process_result_entry(
631+
built = _build_child_update_event(
610632
entry,
611633
batch_id=parsed["batch_id"],
612634
task_components=parsed["task_components"],
613635
end_time=end_time,
614636
seen_ids=seen_ids,
615637
known_ids=known_ids,
638+
expected_count=parsed["request_count"],
616639
)
617-
if not ok:
640+
if built is None:
618641
return
642+
if pending_updates is not None:
643+
pending_updates.append(built)
644+
else:
645+
exported, child_event = built
646+
update_span(exported=exported, **child_event)
619647

620-
_finalize_task_span(batch, parsed, seen_ids, end_time)
648+
_finalize_task_span(batch, parsed, seen_ids, end_time, pending_updates=pending_updates)
621649
except Exception as e:
622650
log.debug("Could not complete Anthropic batch trace: %s", e)
623651

@@ -645,18 +673,25 @@ async def complete_anthropic_batch_trace_async(
645673
return
646674

647675
seen_ids: set[str] = set()
676+
pending_updates: list[tuple[str, dict[str, Any]]] | None = [] if known_ids is None else None
648677
async for entry in _aiter_records(results):
649-
ok = _process_result_entry(
678+
built = _build_child_update_event(
650679
entry,
651680
batch_id=parsed["batch_id"],
652681
task_components=parsed["task_components"],
653682
end_time=end_time,
654683
seen_ids=seen_ids,
655684
known_ids=known_ids,
685+
expected_count=parsed["request_count"],
656686
)
657-
if not ok:
687+
if built is None:
658688
return
689+
if pending_updates is not None:
690+
pending_updates.append(built)
691+
else:
692+
exported, child_event = built
693+
update_span(exported=exported, **child_event)
659694

660-
_finalize_task_span(batch, parsed, seen_ids, end_time)
695+
_finalize_task_span(batch, parsed, seen_ids, end_time, pending_updates=pending_updates)
661696
except Exception as e:
662697
log.debug("Could not complete Anthropic batch trace: %s", e)

‎py/src/braintrust/integrations/anthropic/test_anthropic.py‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1847,10 +1847,14 @@ def test_incomplete_and_invalid_context_handling(self, memory_logger, vcr_casset
18471847
entries = list(raw_client.messages.batches.results(ended_batch.id))
18481848
assert len(entries) == 2
18491849

1850-
# Incomplete results (only 1 of 2 real recorded entries): task must stay pending and retryable.
1850+
# Incomplete results (only 1 of 2 real recorded entries): task and children stay pending and retryable.
18511851
complete_anthropic_batch_trace(batch=ended_batch, results=entries[:1], context=context)
1852-
partial_spans = memory_logger.pop()
1853-
assert task_start["id"] not in {s["id"] for s in partial_spans}
1852+
assert memory_logger.pop() == []
1853+
1854+
# Unknown custom_id in saved-context mode: writes zero stray child rows and leaves task pending.
1855+
unknown_entries = [entries[0], entries[1].model_copy(update={"custom_id": "req-unknown"})]
1856+
complete_anthropic_batch_trace(batch=ended_batch, results=unknown_entries, context=context)
1857+
assert memory_logger.pop() == []
18541858

18551859
# Invalid context without requests: skips tracing cleanly.
18561860
complete_anthropic_batch_trace(batch=ended_batch, results=entries, context="not-valid-json")
@@ -1861,6 +1865,22 @@ def test_incomplete_and_invalid_context_handling(self, memory_logger, vcr_casset
18611865
complete_anthropic_batch_trace(batch=ended_batch, results=entries, context=wrong_batch_context)
18621866
assert memory_logger.pop() == []
18631867

1868+
# Provider privacy policy redacts output/error/content-bearing metadata on completion updates.
1869+
from braintrust._instrumentation import provider_content_allowed
1870+
1871+
token = provider_content_allowed.set(lambda: False)
1872+
try:
1873+
complete_anthropic_batch_trace(batch=ended_batch, results=entries, context=context)
1874+
finally:
1875+
provider_content_allowed.reset(token)
1876+
redacted_spans = memory_logger.pop()
1877+
assert len(redacted_spans) == 3
1878+
for span in redacted_spans:
1879+
assert "output" not in span
1880+
assert "error" not in span
1881+
if "metadata" in span:
1882+
assert set(span["metadata"]).issubset({"model", "provider"})
1883+
18641884
# Invalid context WITH requests: falls back to collect-only mode using the real recorded batch/results.
18651885
complete_anthropic_batch_trace(batch=ended_batch, results=entries, context="corrupt", requests=requests)
18661886
fallback_spans = memory_logger.pop()

0 commit comments

Comments
 (0)