Skip to content

Commit 47cab3b

Browse files
fix(anthropic): spool staged batch updates to disk and add test polling deadlines
> 🤖 **This text was AI-generated.** ### Problem 1. In saved-context mode (`known_ids is None`), staging child span updates in an in-memory list kept all response bodies in RAM until stream completion, which could exhaust worker memory on large batches. 2. Two batch lifecycle tests polled `messages.batches.retrieve()` without the 15-minute deadline check when re-recording cassettes. ### Solution - Replaced the in-memory `pending_updates` list in `complete_anthropic_batch_trace` and `complete_anthropic_batch_trace_async` with `tempfile.SpooledTemporaryFile` (spilling to disk above 1 MB and streaming back line-by-line via `bt_dumps` / `json.loads` only after `request_count` and `request_ids_digest` match). - Restored the 15-minute polling deadline in `test_collect_only_mode_under_active_parent` and `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 5694357 commit 47cab3b

2 files changed

Lines changed: 68 additions & 41 deletions

File tree

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

Lines changed: 64 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,15 @@
1010
import json
1111
import logging
1212
import math
13+
import tempfile
1314
import time
1415
import uuid
1516
from collections.abc import AsyncIterable, Iterable, Mapping
1617
from datetime import datetime, timezone
1718
from typing import Any
1819

1920
from braintrust._instrumentation import provider_content_allowed
21+
from braintrust.bt_json import bt_dumps
2022
from braintrust.integrations.anthropic._utils import _try_to_dict, extract_anthropic_usage
2123
from braintrust.integrations.anthropic.tracing import (
2224
_INSTRUMENTATION,
@@ -504,12 +506,15 @@ def _build_child_update_event(
504506
return exported, _apply_provider_privacy(event)
505507

506508

509+
_SPOOL_MAX_BYTES = 1024 * 1024
510+
511+
507512
def _finalize_task_span(
508513
batch: Any,
509514
parsed: dict[str, Any],
510515
seen_ids: set[str],
511516
end_time: float,
512-
pending_updates: list[tuple[str, dict[str, Any]]] | None = None,
517+
staged_updates: "tempfile.SpooledTemporaryFile[str] | None" = None,
513518
) -> None:
514519
if len(seen_ids) != parsed["request_count"] or _request_ids_digest(seen_ids) != parsed["request_ids_digest"]:
515520
log.debug(
@@ -535,8 +540,10 @@ def _finalize_task_span(
535540
)
536541
return
537542

538-
if pending_updates:
539-
for exported, child_event in pending_updates:
543+
if staged_updates is not None:
544+
staged_updates.seek(0)
545+
for line in staged_updates:
546+
exported, child_event = json.loads(line)
540547
update_span(exported=exported, **child_event)
541548

542549
task_metadata: dict[str, Any] = {
@@ -626,26 +633,34 @@ def complete_anthropic_batch_trace(
626633
return
627634

628635
seen_ids: set[str] = set()
629-
pending_updates: list[tuple[str, dict[str, Any]]] | None = [] if known_ids is None else None
630-
for entry in _iter_records(results):
631-
built = _build_child_update_event(
632-
entry,
633-
batch_id=parsed["batch_id"],
634-
task_components=parsed["task_components"],
635-
end_time=end_time,
636-
seen_ids=seen_ids,
637-
known_ids=known_ids,
638-
expected_count=parsed["request_count"],
639-
)
640-
if built is None:
641-
return
642-
if pending_updates is not None:
643-
pending_updates.append(built)
644-
else:
636+
staged_updates = (
637+
tempfile.SpooledTemporaryFile(max_size=_SPOOL_MAX_BYTES, mode="w+", encoding="utf-8")
638+
if known_ids is None
639+
else None
640+
)
641+
try:
642+
for entry in _iter_records(results):
643+
built = _build_child_update_event(
644+
entry,
645+
batch_id=parsed["batch_id"],
646+
task_components=parsed["task_components"],
647+
end_time=end_time,
648+
seen_ids=seen_ids,
649+
known_ids=known_ids,
650+
expected_count=parsed["request_count"],
651+
)
652+
if built is None:
653+
return
645654
exported, child_event = built
646-
update_span(exported=exported, **child_event)
647-
648-
_finalize_task_span(batch, parsed, seen_ids, end_time, pending_updates=pending_updates)
655+
if staged_updates is not None:
656+
staged_updates.write(bt_dumps([exported, child_event], separators=(",", ":")) + "\n")
657+
else:
658+
update_span(exported=exported, **child_event)
659+
660+
_finalize_task_span(batch, parsed, seen_ids, end_time, staged_updates=staged_updates)
661+
finally:
662+
if staged_updates is not None:
663+
staged_updates.close()
649664
except Exception as e:
650665
log.debug("Could not complete Anthropic batch trace: %s", e)
651666

@@ -673,25 +688,33 @@ async def complete_anthropic_batch_trace_async(
673688
return
674689

675690
seen_ids: set[str] = set()
676-
pending_updates: list[tuple[str, dict[str, Any]]] | None = [] if known_ids is None else None
677-
async for entry in _aiter_records(results):
678-
built = _build_child_update_event(
679-
entry,
680-
batch_id=parsed["batch_id"],
681-
task_components=parsed["task_components"],
682-
end_time=end_time,
683-
seen_ids=seen_ids,
684-
known_ids=known_ids,
685-
expected_count=parsed["request_count"],
686-
)
687-
if built is None:
688-
return
689-
if pending_updates is not None:
690-
pending_updates.append(built)
691-
else:
691+
staged_updates = (
692+
tempfile.SpooledTemporaryFile(max_size=_SPOOL_MAX_BYTES, mode="w+", encoding="utf-8")
693+
if known_ids is None
694+
else None
695+
)
696+
try:
697+
async for entry in _aiter_records(results):
698+
built = _build_child_update_event(
699+
entry,
700+
batch_id=parsed["batch_id"],
701+
task_components=parsed["task_components"],
702+
end_time=end_time,
703+
seen_ids=seen_ids,
704+
known_ids=known_ids,
705+
expected_count=parsed["request_count"],
706+
)
707+
if built is None:
708+
return
692709
exported, child_event = built
693-
update_span(exported=exported, **child_event)
694-
695-
_finalize_task_span(batch, parsed, seen_ids, end_time, pending_updates=pending_updates)
710+
if staged_updates is not None:
711+
staged_updates.write(bt_dumps([exported, child_event], separators=(",", ":")) + "\n")
712+
else:
713+
update_span(exported=exported, **child_event)
714+
715+
_finalize_task_span(batch, parsed, seen_ids, end_time, staged_updates=staged_updates)
716+
finally:
717+
if staged_updates is not None:
718+
staged_updates.close()
696719
except Exception as e:
697720
log.debug("Could not complete Anthropic batch trace: %s", e)

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1795,7 +1795,9 @@ def test_collect_only_mode_under_active_parent(self, memory_logger, vcr_cassette
17951795
requests = _make_batch_requests(LATEST_MODEL)
17961796
raw_client = _get_client()
17971797
batch = raw_client.messages.batches.create(requests=requests)
1798+
deadline = time.time() + 15 * 60
17981799
while batch.processing_status != "ended":
1800+
assert time.time() < deadline, f"batch {batch.id} did not end within 15 minutes"
17991801
if not vcr_cassette.write_protected:
18001802
time.sleep(10)
18011803
batch = raw_client.messages.batches.retrieve(batch.id)
@@ -1840,7 +1842,9 @@ def test_incomplete_and_invalid_context_handling(self, memory_logger, vcr_casset
18401842
assert task_start is not None
18411843

18421844
ended_batch = created_batch
1845+
deadline = time.time() + 15 * 60
18431846
while ended_batch.processing_status != "ended":
1847+
assert time.time() < deadline, f"batch {ended_batch.id} did not end within 15 minutes"
18441848
if not vcr_cassette.write_protected:
18451849
time.sleep(10)
18461850
ended_batch = raw_client.messages.batches.retrieve(ended_batch.id)

0 commit comments

Comments
 (0)