Skip to content

feat(anthropic)!: replace batch auto-instrumentation with explicit trace apis - #1200

Merged
Abhijeet Prasad (AbhiPrasad) merged 6 commits into
mainfrom
devin/1795810177-anthropic-batch-trace
Nov 30, 2026
Merged

Abhijeet Prasad (AbhiPrasad) merged 6 commits into
mainfrom
devin/1795810177-anthropic-batch-trace

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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) and batch-apis.md.

What changed & why

  1. Removed Anthropic batch auto-instrumentation (py/src/braintrust/integrations/anthropic/tracing.py)

    • Deleted Batches, AsyncBatches, and the batches property overrides on Messages / AsyncMessages.
    • client.messages.batches.create / results and client.beta.messages.batches.create / results now pass through untouched under both wrap_anthropic() and AnthropicIntegration.setup().
    • Deleted 6 now-unused TestBatchesCreateSpans cassettes across latest, 1.17.0, and 0.48.0.
  2. Added explicit Anthropic batch trace APIs (py/src/braintrust/integrations/anthropic/batch.py, exported from braintrust.integrations.anthropic)

    • start_anthropic_batch_trace(*, batch, requests) -> str | None
    • complete_anthropic_batch_trace(*, batch, results=None, context=None, requests=None) -> None
    • complete_anthropic_batch_trace_async(*, batch, results=None, context=None, requests=None) -> None
    from braintrust.integrations.anthropic import (
        complete_anthropic_batch_trace,
        start_anthropic_batch_trace,
    )
    
    batch = client.messages.batches.create(requests=requests)
    context = start_anthropic_batch_trace(batch=batch, requests=requests)
    
    # Later (including in a different process) once batch.processing_status == "ended":
    results = client.messages.batches.results(batch.id)
    complete_anthropic_batch_trace(batch=batch, results=results, context=context)
    • Span tree: emits one parent task span (anthropic.batch) and one child llm span (anthropic.messages.create) per valid request via start_span(..., set_current=False, internal={"initial_span_write_as_merge": True, ...}), with deterministic span/row IDs (anthropic:batch and anthropic:batch:request) so start + collect merge idempotently without holding live spans in memory.
    • Resumable bounded context: versioned JSON string (version=1) storing only batch_id, task slug (with propagated_event stripped), start_time, request_count, and a SHA-256 digest of sorted custom_ids.
    • Collect-only, streaming & privacy: accepts JSONL strings/bytes, file-like streams, sync iterables, and async iterables; spools saved-context child updates via tempfile.SpooledTemporaryFile until request_ids_digest validates so invalid/unknown results emit zero stray rows without buffering large batches in RAM; enforces provider_content_allowed redaction on completion updates; supports collect-only mode when requests is supplied without prior start context.
    • Terminal & partial-result handling: keeps spans pending when processing_status != "ended" or results are incomplete, rejects duplicate/unknown custom_ids, clamps end >= start, and handles succeeded, errored, canceled, and expired outcomes.
  3. Tests & skill rule (py/src/braintrust/integrations/anthropic/test_anthropic.py, .agents/skills/sdk-integrations/SKILL.md)

    • Replaced TestBatchesCreateSpans with 100% VCR-backed TestAnthropicBatchTracing across latest, 1.17.0, and 0.48.0, including newly recorded errored and canceled outcome cassettes.
    • Documented the rule in .agents/skills/sdk-integrations/SKILL.md that explicit provider batch helpers export from braintrust.integrations.<provider> rather than top-level braintrust.

Breaking change: messages.batches.create() and messages.batches.results() are no longer auto-instrumented. Callers should switch to start_anthropic_batch_trace() and complete_anthropic_batch_trace() / complete_anthropic_batch_trace_async() from braintrust.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

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

I'll fix CI failures and address comments from users with write access that start with 'Devin'.

  • Disable automatic comment, CI, and merge conflict monitoring

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T20:23:26.610683Z 1e06e97 PR opened
ℹ️ About Codex in GitHub

Your 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +462 to +464
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The PR appears safe to merge, with a non-blocking test coverage gap remaining.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with a non-blocking test coverage gap remaining.

FindingsFix All in CursorFindings

  1. P2 Failed results lose test coverage ▶
Fix with agent prompt
### Issue 1
py/src/braintrust/integrations/anthropic/test_anthropic.py:1834-1835
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.

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!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Replaces automatic Anthropic batch tracing with explicit start and completion helpers.

  • Anthropic batch traces can now span submission and result collection.
  • Anthropic batch API calls now pass through without automatic spans.

Diagram

sequenceDiagram
    participant App as Application
    participant Anthropic
    participant BT as Braintrust
    App->>Anthropic: Create batch
    Anthropic-->>App: Batch
    App->>BT: Start batch trace with requests
    BT-->>App: Saved context
    Note over App: Persist context for later collection
    App->>Anthropic: Retrieve finished batch results
    Anthropic-->>App: Result stream
    App->>BT: Complete trace with results and context
    BT->>BT: Check request IDs and update matching spans
Loading

Reviews (7) · Last reviewed commit: "refactor(anthropic): keep batch exports ..." · Reviewed by Greptile

Comment on lines +1829 to +1830
@pytest.mark.vcr(**({"cassette_name": "TestBatchesResultsSpans.test_batches_results_produces_span[sync]"}))
def test_incomplete_and_invalid_context_handling(self, memory_logger, vcr_cassette):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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!

Fix in Cursor Fix in Claude Code Fix in Codex Fix in Devin

Abhijeet Prasad (AbhiPrasad) added a commit to braintrustdata/braintrust-proxy that referenced this pull request Nov 29, 2026
## 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>
@devin-ai-integration
devin-ai-integration Bot force-pushed the devin/1795810177-anthropic-batch-trace branch from 3c72960 to 47cab3b Compare November 30, 2026 16:07
…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>
@AbhiPrasad
Abhijeet Prasad (AbhiPrasad) merged commit 01b0ac6 into main Nov 30, 2026
99 checks passed
@AbhiPrasad
Abhijeet Prasad (AbhiPrasad) deleted the devin/1795810177-anthropic-batch-trace branch November 30, 2026 16:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant