Repository navigation
feat(anthropic)!: replace batch auto-instrumentation with explicit trace apis - #1200
Conversation
|
I'll fix CI failures and address comments from users with write access that start with 'Devin'.
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1e06e972dd
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "Codex (@codex) review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "Codex (@codex) address that feedback".
| if message is None: | ||
| log.debug("Anthropic batch completion paused: missing message for succeeded result %r", custom_id) | ||
| return False | ||
| update_span(exported=exported, **_build_succeeded_update(message, end_time)) |
There was a problem hiding this comment.
Apply provider privacy to completion updates
When a provider_content_allowed policy permits submission but is tightened before batch completion, this direct update_span call bypasses _start_span_impl and therefore never attaches the _ProviderPrivacyCustomizer used by anthropic-auto spans. The initial request rows can consequently be redacted while the successful message output is still emitted, leaking the provider content the policy now disallows; completion updates need to preserve or reapply the provider privacy policy.
Useful? React with 👍 / 👎.
| if known_ids is not None and custom_id not in known_ids: | ||
| log.debug("Anthropic batch completion paused: unknown custom_id %r", custom_id) | ||
| return False |
There was a problem hiding this comment.
Reject unknown result IDs before writing updates
When completion uses the normal persisted context, _prepare_completion leaves known_ids as None, so this guard accepts every custom_id. Each result is then written immediately, and the request-ID digest is checked only after the stream is exhausted; passing results from the wrong batch or a malformed stream therefore creates update-only child rows for unknown IDs before the task is left pending. Validate membership before emitting any child update, rather than relying solely on the final digest.
Useful? React with 👍 / 👎.
[Medium impact] The PR appears safe to merge, with a non-blocking test coverage gap remaining.
|
| @pytest.mark.vcr(**({"cassette_name": "TestBatchesResultsSpans.test_batches_results_produces_span[sync]"})) | ||
| def test_incomplete_and_invalid_context_handling(self, memory_logger, vcr_cassette): |
There was a problem hiding this comment.
Failed results lose test coverage
Removing test_batch_error_outcomes_and_jsonl_stream drops the only checks for errored, canceled, and expired results and for an ended_at earlier than the start. The replacement cassette contains only successful results, so regressions in these paths can now pass the tests. Keep focused checks for these cases alongside the recorded success tests.
Prompt To Fix With AI
This is a comment left during a code review.
Path: py/src/braintrust/integrations/anthropic/test_anthropic.py
Line: 1829-1830
Comment:
**Failed results lose test coverage**
Removing `test_batch_error_outcomes_and_jsonl_stream` drops the only checks for `errored`, `canceled`, and `expired` results and for an `ended_at` earlier than the start. The replacement cassette contains only successful results, so regressions in these paths can now pass the tests. Keep focused checks for these cases alongside the recorded success tests.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
## Summary Follow-up to #1944. Brainstore's `select_billing_rate` only uses a row with `endpoints` when the span's `metadata.api_host` matches. Batch also never falls back to standard prices, so SDK-instrumented Anthropic batch spans with no `api_host` (e.g. [sdk-python#1200](braintrustdata/braintrust-sdk-python#1200)) still got no cost. This drops `endpoints: ["api.anthropic.com"]` from all 36 `pricing.anthropic.batch` rows across 20 entries. Nothing else changes. Per Anthropic's docs, the batch prices hold for any `anthropic` host: - [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing#pricing): "All usage is charged at 50 percent of the standard API prices." - [Claude Platform on AWS](https://platform.claude.com/docs/en/about-claude/pricing#claude-platform-on-aws-pricing) and [Microsoft Foundry](https://platform.claude.com/docs/en/about-claude/pricing#claude-in-microsoft-foundry-pricing) bill tokens "at standard per-model, per-feature rates (same as Model pricing)". - Bedrock and Google-managed Vertex have their own prices, but the catalog keeps those under `bedrock`/`vertex`. `fast` rows keep their endpoint scope. Link to Devin session: https://braintrust.devinenterprise.com/sessions/653764559c404a7f9e4ba2ec78526230 Open in Devin Desktop: https://braintrust.devinenterprise.com/desktop/session/653764559c404a7f9e4ba2ec78526230?variant=devin Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com> Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…ace apis
> 🤖 **This text was AI-generated.**
Previously, `wrap_anthropic()` and `AnthropicIntegration.setup()` auto-instrumented
`messages.batches.create()` and `messages.batches.results()` (including `beta.messages.batches`),
emitting two disconnected, immediately-ended `task` spans with no child `llm` spans and
no per-request inputs, outputs, usage metrics, or resumable correlation:
```
task (anthropic.messages.batches.create) # ended immediately, custom_ids only
task (anthropic.messages.batches.results) # ended immediately, {"type": "jsonl_stream"}
```
This violated the Braintrust Batch APIs instrumentation spec, which forbids auto-instrumenting
asynchronous batch lifecycle methods and requires explicit start/collect APIs that produce a
parent `task` span with one child `llm` span per batch request.
1. Removed `Batches` / `AsyncBatches` wrappers from `Messages` and `AsyncMessages` so
`messages.batches` and `beta.messages.batches` pass through untouched under both
`wrap_anthropic()` and `AnthropicIntegration.setup()`.
2. Extended `_internal_start_span_with_initial_merge` in `logger.py` to accept `start_time`,
optional `root_span_id`, and `internal` options while routing directly through
`SpanComponentsV4` without colliding with an active `current_span`.
3. Added explicit, caller-owned Anthropic batch capture APIs exported from both
`braintrust` and `braintrust.integrations.anthropic`:
- `start_anthropic_batch_trace(batch=..., requests=...) -> str | None`
- `complete_anthropic_batch_trace(batch=..., results=..., context=..., requests=...) -> None`
- `complete_anthropic_batch_trace_async(batch=..., results=..., context=..., requests=...) -> None`
```
task (anthropic.batch)
├── llm (anthropic.messages.create) [custom_id: req-1]
└── llm (anthropic.messages.create) [custom_id: req-2]
```
```python
batch = client.messages.batches.create(requests=requests)
context = start_anthropic_batch_trace(batch=batch, requests=requests)
results = client.messages.batches.results(batch.id)
complete_anthropic_batch_trace(batch=batch, results=results, context=context)
```
The returned context is versioned, constant-size (stores a SHA-256 digest of request IDs
rather than per-item payloads), strips `propagated_event`, and supports idempotent retries,
streaming JSONL/iterables/async iterables, and collect-only mode when `requests` is supplied
without a prior `start_anthropic_batch_trace` call.
BREAKING CHANGE: `messages.batches.create()` and `messages.batches.results()` are no longer
auto-instrumented by `wrap_anthropic()` or `AnthropicIntegration.setup()`. Use
`start_anthropic_batch_trace()` and `complete_anthropic_batch_trace()` /
`complete_anthropic_batch_trace_async()` instead.
Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
> 🤖 **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>
…outcomes > 🤖 **This text was AI-generated.** ### Problem The existing Anthropic batch cassettes only covered `succeeded` batch results, leaving `errored` and `canceled` batch result handling without recorded VCR integration coverage. ### Solution - Added `test_errored_batch_outcome` (mixed `succeeded` + `errored` requests via a real `not_found_error` response) and `test_canceled_batch_outcome` (via `messages.batches.cancel`) to `TestAnthropicBatchTracing`. - Recorded and checked in real VCR cassettes for both tests across all matrix versions (`latest`, `1.17.0`, `0.48.0`), verified in `--vcr-record=none` replay mode. Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com> Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
… 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>
…ng 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>
3c72960 to
47cab3b
Compare
…and drop logger.py diff
> 🤖 **This text was AI-generated.**
### Changes
- Removed `start_anthropic_batch_trace`, `complete_anthropic_batch_trace`, and
`complete_anthropic_batch_trace_async` re-exports from `py/src/braintrust/__init__.py`
so provider batch tracing helpers live solely under `braintrust.integrations.anthropic`.
- Documented the batch export rule in `.agents/skills/sdk-integrations/SKILL.md`.
- Reverted the unnecessary `py/src/braintrust/logger.py` change by calling `start_span`
directly with `set_current=False` and `internal={...}` in `batch.py`.
Co-authored-by: Abhijeet Prasad <abhijeet@braintrustdata.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Summary
Removes Anthropic batch lifecycle auto-instrumentation and replaces it with explicit, spec-compliant Anthropic Message Batch tracing APIs modeled after the Braintrust JS SDK (
groq-batch/ai-sdk-batch) andbatch-apis.md.What changed & why
Removed Anthropic batch auto-instrumentation (
py/src/braintrust/integrations/anthropic/tracing.py)Batches,AsyncBatches, and thebatchesproperty overrides onMessages/AsyncMessages.client.messages.batches.create/resultsandclient.beta.messages.batches.create/resultsnow pass through untouched under bothwrap_anthropic()andAnthropicIntegration.setup().TestBatchesCreateSpanscassettes acrosslatest,1.17.0, and0.48.0.Added explicit Anthropic batch trace APIs (
py/src/braintrust/integrations/anthropic/batch.py, exported frombraintrust.integrations.anthropic)start_anthropic_batch_trace(*, batch, requests) -> str | Nonecomplete_anthropic_batch_trace(*, batch, results=None, context=None, requests=None) -> Nonecomplete_anthropic_batch_trace_async(*, batch, results=None, context=None, requests=None) -> Nonetaskspan (anthropic.batch) and one childllmspan (anthropic.messages.create) per valid request viastart_span(..., set_current=False, internal={"initial_span_write_as_merge": True, ...}), with deterministic span/row IDs (anthropic:batchandanthropic:batch:request) so start + collect merge idempotently without holding live spans in memory.version=1) storing onlybatch_id,taskslug (withpropagated_eventstripped),start_time,request_count, and a SHA-256 digest of sortedcustom_ids.tempfile.SpooledTemporaryFileuntilrequest_ids_digestvalidates so invalid/unknown results emit zero stray rows without buffering large batches in RAM; enforcesprovider_content_allowedredaction on completion updates; supports collect-only mode whenrequestsis supplied without prior start context.processing_status != "ended"or results are incomplete, rejects duplicate/unknowncustom_ids, clampsend >= start, and handlessucceeded,errored,canceled, andexpiredoutcomes.Tests & skill rule (
py/src/braintrust/integrations/anthropic/test_anthropic.py,.agents/skills/sdk-integrations/SKILL.md)TestBatchesCreateSpanswith 100% VCR-backedTestAnthropicBatchTracingacrosslatest,1.17.0, and0.48.0, including newly recordederroredandcanceledoutcome cassettes..agents/skills/sdk-integrations/SKILL.mdthat explicit provider batch helpers export frombraintrust.integrations.<provider>rather than top-levelbraintrust.Breaking change:
messages.batches.create()andmessages.batches.results()are no longer auto-instrumented. Callers should switch tostart_anthropic_batch_trace()andcomplete_anthropic_batch_trace()/complete_anthropic_batch_trace_async()frombraintrust.integrations.anthropic.Link to Devin session: https://braintrust.devinenterprise.com/sessions/f12a57f6efe44a68b370bd5896079b41
Open in Devin Desktop: https://braintrust.devinenterprise.com/desktop/session/f12a57f6efe44a68b370bd5896079b41?variant=devin