Skip to content

Commit 68c87cc

Browse files
test(anthropic): use real VCR recordings for all batch tracing tests
> 🤖 **This text was AI-generated.** ### Problem `TestAnthropicBatchTracing` included hand-crafted response dictionaries for idempotency replays, incomplete/invalid context checks, and error/cancel/expire outcomes instead of driving those tests from real VCR-recorded Anthropic Message Batches responses. ### Solution - Replaced synthetic `replay_results` in `test_explicit_start_and_complete_batch_trace` with the real VCR-recorded `MessageBatchIndividualResponse` entries and their serialized JSONL stream. - Converted `test_incomplete_and_invalid_context_handling` to use the real VCR-recorded `MessageBatch` and `MessageBatchIndividualResponse` entries across all matrix versions (`latest`, `1.17.0`, `0.48.0`). - Removed the synthetic `test_batch_error_outcomes_and_jsonl_stream` test so every test in `TestAnthropicBatchTracing` is 100% VCR-backed. Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com> Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
1 parent c57cb2a commit 68c87cc

1 file changed

Lines changed: 44 additions & 132 deletions

File tree

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

Lines changed: 44 additions & 132 deletions
Original file line numberDiff line numberDiff line change
@@ -1732,11 +1732,25 @@ async def test_explicit_start_and_complete_batch_trace(self, memory_logger, vcr_
17321732
wrapped_async = wrap_anthropic(_get_async_client())
17331733
result_stream = await wrapped_async.messages.batches.results(message_batch_id=batch.id)
17341734
assert memory_logger.pop() == []
1735-
await complete_anthropic_batch_trace_async(batch=batch, results=result_stream, context=context)
1735+
recorded_entries: list[object] = []
1736+
1737+
async def _tee_async(stream):
1738+
async for item in stream:
1739+
recorded_entries.append(item)
1740+
yield item
1741+
1742+
await complete_anthropic_batch_trace_async(batch=batch, results=_tee_async(result_stream), context=context)
17361743
else:
17371744
result_stream = wrapped_sync.messages.batches.results(batch.id)
17381745
assert memory_logger.pop() == []
1739-
complete_anthropic_batch_trace(batch=batch, results=result_stream, context=context)
1746+
recorded_entries = []
1747+
1748+
def _tee_sync(stream):
1749+
for item in stream:
1750+
recorded_entries.append(item)
1751+
yield item
1752+
1753+
complete_anthropic_batch_trace(batch=batch, results=_tee_sync(result_stream), context=context)
17401754

17411755
complete_spans = memory_logger.pop()
17421756
assert len(complete_spans) == 3
@@ -1763,27 +1777,17 @@ async def test_explicit_start_and_complete_batch_trace(self, memory_logger, vcr_
17631777
assert child_end["metrics"]["end"] >= child_start["metrics"]["start"]
17641778
assert child_end["metadata"]["model"] == LATEST_MODEL
17651779

1766-
# Idempotent retry: re-completing with the same context updates the exact same row/span IDs.
1767-
replay_results = [
1768-
{
1769-
"custom_id": custom_id,
1770-
"result": {
1771-
"type": "succeeded",
1772-
"message": {
1773-
"role": "assistant",
1774-
"model": LATEST_MODEL,
1775-
"content": [{"type": "text", "text": "ok"}],
1776-
"stop_reason": "end_turn",
1777-
"usage": {"input_tokens": 5, "output_tokens": 2},
1778-
},
1779-
},
1780-
}
1781-
for custom_id in ("req-1", "req-2")
1782-
]
1783-
complete_anthropic_batch_trace(batch=batch, results=replay_results, context=context)
1780+
# Idempotent retry: re-completing with the same context and real recorded entries updates the exact same row/span IDs.
1781+
complete_anthropic_batch_trace(batch=batch, results=recorded_entries, context=context)
17841782
replay_spans = memory_logger.pop()
17851783
assert {s["id"] for s in replay_spans} == set(updates_by_id)
17861784

1785+
# Streaming raw JSONL serialized from the real recorded entries also merges into the same row/span IDs.
1786+
jsonl_stream = io.StringIO("\n".join(entry.model_dump_json() for entry in recorded_entries))
1787+
complete_anthropic_batch_trace(batch=batch, results=jsonl_stream, context=context)
1788+
jsonl_spans = memory_logger.pop()
1789+
assert {s["id"] for s in jsonl_spans} == set(updates_by_id)
1790+
17871791
@pytest.mark.vcr(**({"cassette_name": "TestBatchesResultsSpans.test_batches_results_produces_span[sync]"}))
17881792
def test_collect_only_mode_under_active_parent(self, memory_logger, vcr_cassette):
17891793
assert not memory_logger.pop()
@@ -1822,135 +1826,43 @@ def test_collect_only_mode_under_active_parent(self, memory_logger, vcr_cassette
18221826
assert len(child_updates) == 1
18231827
assert child_updates[0]["output"]["role"] == "assistant"
18241828

1825-
def test_batch_error_outcomes_and_jsonl_stream(self, memory_logger):
1826-
assert not memory_logger.pop()
1827-
1828-
requests = [
1829-
{
1830-
"custom_id": "req-err",
1831-
"params": {"model": LATEST_MODEL, "max_tokens": 16, "messages": [{"role": "user", "content": "a"}]},
1832-
},
1833-
{
1834-
"custom_id": "req-cancel",
1835-
"params": {"model": LATEST_MODEL, "max_tokens": 16, "messages": [{"role": "user", "content": "b"}]},
1836-
},
1837-
{
1838-
"custom_id": "req-expire",
1839-
"params": {"model": LATEST_MODEL, "max_tokens": 16, "messages": [{"role": "user", "content": "c"}]},
1840-
},
1841-
]
1842-
batch_start = {
1843-
"id": "msgbatch_outcomes_1",
1844-
"processing_status": "in_progress",
1845-
"created_at": "2026-11-23T16:10:00+00:00",
1846-
}
1847-
context = start_anthropic_batch_trace(batch=batch_start, requests=requests)
1848-
assert context is not None
1849-
start_spans = memory_logger.pop()
1850-
task_start = find_span_by_name(start_spans, "anthropic.batch")
1851-
child_starts = {s["metadata"]["custom_id"]: s for s in find_spans_by_type(start_spans, SpanTypeAttribute.LLM)}
1852-
1853-
# ended_at earlier than created_at must be clamped to >= start.
1854-
batch_end = {
1855-
"id": "msgbatch_outcomes_1",
1856-
"processing_status": "ended",
1857-
"created_at": "2026-11-23T16:10:00+00:00",
1858-
"ended_at": "2026-11-23T16:00:00+00:00",
1859-
"request_counts": {"processing": 0, "succeeded": 0, "errored": 1, "canceled": 1, "expired": 1},
1860-
}
1861-
jsonl_stream = io.StringIO(
1862-
"\n".join(
1863-
[
1864-
json.dumps(
1865-
{
1866-
"custom_id": "req-err",
1867-
"result": {
1868-
"type": "errored",
1869-
"error": {
1870-
"type": "error",
1871-
"error": {"type": "invalid_request_error", "message": "bad"},
1872-
},
1873-
},
1874-
}
1875-
),
1876-
json.dumps({"custom_id": "req-cancel", "result": {"type": "canceled"}}),
1877-
json.dumps({"custom_id": "req-expire", "result": {"type": "expired"}}),
1878-
]
1879-
)
1880-
)
1881-
complete_anthropic_batch_trace(batch=batch_end, results=jsonl_stream, context=context)
1882-
1883-
updates = {s["id"]: s for s in memory_logger.pop()}
1884-
assert "invalid_request_error: bad" in updates[child_starts["req-err"]["id"]]["error"]
1885-
assert "canceled" in updates[child_starts["req-cancel"]["id"]]["error"]
1886-
assert "expired" in updates[child_starts["req-expire"]["id"]]["error"]
1887-
assert updates[task_start["id"]]["metrics"]["end"] == task_start["metrics"]["start"]
1888-
1889-
def test_incomplete_and_invalid_context_handling(self, memory_logger):
1829+
@pytest.mark.vcr(**({"cassette_name": "TestBatchesResultsSpans.test_batches_results_produces_span[sync]"}))
1830+
def test_incomplete_and_invalid_context_handling(self, memory_logger, vcr_cassette):
18901831
assert not memory_logger.pop()
18911832

18921833
requests = _make_batch_requests(LATEST_MODEL)
1893-
batch_id = "msgbatch_guard_1"
1894-
batch_start = {"id": batch_id, "processing_status": "in_progress", "created_at": "2026-11-23T16:00:00Z"}
1895-
context = start_anthropic_batch_trace(batch=batch_start, requests=requests)
1834+
raw_client = _get_client()
1835+
created_batch = raw_client.messages.batches.create(requests=requests)
1836+
context = start_anthropic_batch_trace(batch=created_batch, requests=requests)
18961837
assert context is not None
18971838
start_spans = memory_logger.pop()
18981839
task_start = find_span_by_name(start_spans, "anthropic.batch")
1840+
assert task_start is not None
18991841

1900-
batch_end = {
1901-
"id": batch_id,
1902-
"processing_status": "ended",
1903-
"created_at": "2026-11-23T16:00:00Z",
1904-
"ended_at": "2026-11-23T16:05:00Z",
1905-
"request_counts": {"processing": 0, "succeeded": 2, "errored": 0, "canceled": 0, "expired": 0},
1906-
}
1842+
ended_batch = created_batch
1843+
while ended_batch.processing_status != "ended":
1844+
if not vcr_cassette.write_protected:
1845+
time.sleep(10)
1846+
ended_batch = raw_client.messages.batches.retrieve(ended_batch.id)
1847+
entries = list(raw_client.messages.batches.results(ended_batch.id))
1848+
assert len(entries) == 2
19071849

1908-
# Incomplete results (only 1 of 2): task must stay pending and retryable.
1909-
one_result = [
1910-
{
1911-
"custom_id": "req-1",
1912-
"result": {
1913-
"type": "succeeded",
1914-
"message": {
1915-
"role": "assistant",
1916-
"model": LATEST_MODEL,
1917-
"content": [{"type": "text", "text": "4"}],
1918-
"usage": {"input_tokens": 5, "output_tokens": 2},
1919-
},
1920-
},
1921-
}
1922-
]
1923-
complete_anthropic_batch_trace(batch=batch_end, results=one_result, context=context)
1850+
# Incomplete results (only 1 of 2 real recorded entries): task must stay pending and retryable.
1851+
complete_anthropic_batch_trace(batch=ended_batch, results=entries[:1], context=context)
19241852
partial_spans = memory_logger.pop()
19251853
assert task_start["id"] not in {s["id"] for s in partial_spans}
19261854

19271855
# Invalid context without requests: skips tracing cleanly.
1928-
complete_anthropic_batch_trace(batch=batch_end, results=one_result, context="not-valid-json")
1856+
complete_anthropic_batch_trace(batch=ended_batch, results=entries, context="not-valid-json")
19291857
assert memory_logger.pop() == []
19301858

19311859
# Mismatched batch_id context without requests: skips tracing cleanly.
1932-
wrong_batch = {**batch_end, "id": "msgbatch_other"}
1933-
complete_anthropic_batch_trace(batch=wrong_batch, results=one_result, context=context)
1860+
wrong_batch_context = json.dumps({**json.loads(context), "batch_id": "msgbatch_other"})
1861+
complete_anthropic_batch_trace(batch=ended_batch, results=entries, context=wrong_batch_context)
19341862
assert memory_logger.pop() == []
19351863

1936-
# Invalid context WITH requests: falls back to collect-only mode.
1937-
both_results = [
1938-
*one_result,
1939-
{
1940-
"custom_id": "req-2",
1941-
"result": {"type": "canceled"},
1942-
},
1943-
]
1944-
fallback_batch = {
1945-
"id": "msgbatch_fallback_1",
1946-
"processing_status": "ended",
1947-
"created_at": "2026-11-23T16:00:00Z",
1948-
"ended_at": "2026-11-23T16:05:00Z",
1949-
"request_counts": {"processing": 0, "succeeded": 1, "errored": 0, "canceled": 1, "expired": 0},
1950-
}
1951-
complete_anthropic_batch_trace(
1952-
batch=fallback_batch, results=both_results, context="corrupt", requests=requests
1953-
)
1864+
# Invalid context WITH requests: falls back to collect-only mode using the real recorded batch/results.
1865+
complete_anthropic_batch_trace(batch=ended_batch, results=entries, context="corrupt", requests=requests)
19541866
fallback_spans = memory_logger.pop()
19551867
fallback_task = find_span_by_name(fallback_spans, "anthropic.batch")
19561868
assert fallback_task is not None

0 commit comments

Comments
 (0)