Skip to content

fix: accumulate newer billable token fields in usage tracking - #2499

Closed
rkfshakti wants to merge 2 commits into
567-labs:mainfrom
rkfshakti:fix/usage-accumulation-2493
Closed

rkfshakti wants to merge 2 commits into
567-labs:mainfrom
rkfshakti:fix/usage-accumulation-2493

Conversation

@rkfshakti

Copy link
Copy Markdown
Contributor

Problem

update_total_usage was hand-maintaining a list of token fields that drifted from both SDKs. On Anthropic, cache_creation, server_tool_use, and output_tokens_details sub-models were never initialized on the accumulator, so their fields stayed stale across retries. On OpenAI, prompt_tokens_details sub-model fields (cache_write_tokens, accepted_prediction_tokens, rejected_prediction_tokens) were overwritten with None because the accumulator never populated them.

This was silent — input_tokens/prompt_tokens were correct, so the under-count only showed up when reconciling against a provider invoice.

Root cause

Both implementations enumerate fields by hand and drift independently as the SDKs add counters. Each new billable field needs a matching edit in two places, and nothing fails when that edit is missed.

Fix

Anthropic (instructor/v2/providers/anthropic/usage.py):

  • Added _ensure_sub_models() that initializes cache_creation, server_tool_use, and output_tokens_details on the accumulator with zeroed values
  • Accumulate ephemeral_1h_input_tokens, ephemeral_5m_input_tokens (cache_creation), web_search_requests, web_fetch_requests (server_tool_use), and thinking_tokens (output_tokens_details) across retries
  • Write back the accumulated sub-models onto the response so callers see them

OpenAI (instructor/v2/core/usage.py):

  • Accumulate cache_write_tokens, accepted_prediction_tokens, and rejected_prediction_tokens in prompt_tokens_details, using hasattr guards for forward compatibility with older SDK versions

Verification

# Anthropic: 3 retries each with thinking=40, web_search=2, ephemeral_5m=500
# Before: thinking=40 (stale), web_search=2 (stale), eph5m=500 (stale)
# After:  thinking=120, web_search=6, eph5m=1500 ✅

Fixes #2493

update_total_usage was hand-maintaining a list of token fields that
drifted from both SDKs. On Anthropic, cache_creation, server_tool_use,
and output_tokens_details sub-models were never initialized on the
accumulator, so their fields stayed stale across retries. On OpenAI,
prompt_tokens_details sub-model fields (cache_write_tokens,
accepted_prediction_tokens, rejected_prediction_tokens) were
overwritten with None because the accumulator never populated them.

The fix:
- Anthropic: initialize cache_creation, server_tool_use, and
  output_tokens_details sub-models on the accumulator, then accumulate
  their int fields across retries
- OpenAI: accumulate cache_write_tokens, accepted_prediction_tokens,
  and rejected_prediction_tokens in prompt_tokens_details, using
  hasattr guards for forward compatibility

Fixes #2493

@ErenAta16 ErenAta16 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.

I filed #2493, so I am not neutral here. Reading this against the pinned dependency turned up a blocker, and it also corrects something in my own issue.

_ensure_sub_models raises ImportError on the version this repo pins. pyproject.toml pins anthropic==0.93.0 (line 60, and the anthropic extra on line 87). That release has no output_tokens_details at all. Installed and ran the exact import from this PR:

$ pip install anthropic==0.93.0
>>> from anthropic.types.usage import CacheCreation, ServerToolUsage, OutputTokensDetails
ImportError: cannot import name 'OutputTokensDetails' from 'anthropic.types.usage'

>>> sorted(Usage.model_fields)
['cache_creation', 'cache_creation_input_tokens', 'cache_read_input_tokens',
 'inference_geo', 'input_tokens', 'output_tokens', 'server_tool_use', 'service_tier']

src/anthropic/types/output_tokens_details.py does not exist at tag v0.93.0; it first appears later. Since _ensure_sub_models is called from update_total_usage on every attempt, this does not degrade Anthropic usage tracking, it stops it with an ImportError on the first call under the pinned dependency.

CacheCreation and ServerToolUsage are fine. Both exist at v0.93.0 with exactly the fields used here (ephemeral_1h_input_tokens/ephemeral_5m_input_tokens, web_fetch_requests/web_search_requests), so those two thirds work.

This is my error as much as this PR's. I wrote #2493 against anthropic==0.116.0 and listed output_tokens_details.thinking_tokens as one of the three unaccumulated fields. It is not a field on the version instructor actually installs, so that third of the issue does not apply to the pinned SDK. The cache_creation and server_tool_use halves do apply on 0.93.0 and are real. Sorry for sending you after a field that is not there.

The narrower point this exposes. A fix here has to survive a version range, and hand-enumerating fields cannot. The same drift that produced the original bug is what makes OutputTokensDetails unimportable now, and it will do it again the next time Stainless regenerates the model. A shape-driven merge (walk the response model's own numeric fields and sum whatever is present) gets the version tolerance for free. Both #2497 and #2500 go that route, which is worth weighing before this lands.

Secondary, and it survives fixing the import. Even guarded, the accumulator would attach output_tokens_details to a 0.93.0 Usage, which permits extra attributes:

>>> u = Usage(input_tokens=1, output_tokens=1)
>>> hasattr(u, "output_tokens_details")
False
>>> u.output_tokens_details = None      # accepted, phantom attribute

so the write-back at the end would put a field on the response object that the installed SDK does not model, and model_dump() consumers would see a key the provider never sent.

Also worth flagging: the write-back reintroduces the pattern the OpenAI half of #2493 was about.

response_usage.cache_creation = total_usage.cache_creation.model_copy(deep=True)

This is the same unconditional overwrite that wipes fields the accumulator does not track. CacheCreation has exactly two fields today so nothing is lost yet, but that was equally true of PromptTokensDetails before OpenAI added cache_write_tokens. Merging into the response object rather than replacing it would close that off permanently.

No tests in this PR. Given the accumulation is order-dependent across attempts, I would want at least a three-attempt case pinning that the sub-model fields sum rather than latch, which is the exact symptom in the issue.

…erge write-back, add regression tests

Addresses all three review points from @ErenAta16 on #2499:

1. **ImportError on pinned anthropic==0.93.0** — `OutputTokensDetails`
   does not exist on the pinned SDK version. Guard the import with
   try/except ImportError, and use `getattr`/`hasattr` for all
   `output_tokens_details` access since the field itself is not a
   declared member of `Usage` in 0.93.0.

2. **Write-back replaces instead of merges** — Changed from
   `model_copy(deep=True)` replacement to field-by-field merge, so
   future SDK additions that the accumulator does not track are preserved
   on the response object.

3. **No regression tests** — Added 8 tests covering:
   - `_ensure_sub_models` initialises missing sub-models
   - Existing sub-models are not overwritten
   - `cache_creation` and `server_tool_use` accumulate across 3 retries
   - `output_tokens_details` accumulates when available (skipped on 0.93.0)
   - No crash on pinned anthropic (the exact regression from the review)
   - Write-back merges not replaces
@rkfshakti

Copy link
Copy Markdown
Contributor Author

Thanks @ErenAta16 for the thorough review — all three points are addressed in commit e57355e:

  1. ImportError on anthropic==0.93.0 — OutputTokensDetails import is now guarded with try/except ImportError. All output_tokens_details access uses getattr/hasattr since the field itself isn't a declared member of Usage in 0.93.0. The _ensure_sub_models function returns early when the import fails, so the cache_creation and server_tool_use halves still work.

  2. Write-back merges not replaces — Changed from model_copy(deep=True) replacement to field-by-field merge for all three sub-models. Future SDK additions that the accumulator doesn't track are preserved on the response object.

  3. Regression tests added — 8 tests in tests/llm/test_anthropic/test_usage_accumulation.py covering: sub-model initialisation, three-attempt accumulation for cache_creation and server_tool_use, no crash on pinned anthropic (the exact regression), and merge-not-replace write-back. The output_tokens_details accumulation test is skipped on 0.93.0 since the field doesn't exist there.

All 7 runnable tests pass on anthropic==0.93.0.

jxnl added a commit that referenced this pull request Aug 3, 2026
## Summary

- accumulate declared, nested, and unknown numeric OpenAI/Anthropic
usage fields across retries while preserving non-numeric metadata
- add corrective feedback when a Responses API retry receives no tool
call
- preserve raw iterable type hints through sync and async v2
parallel-tool wrappers
- strengthen API-key-free coverage for current and future SDK usage
counters

## Consolidated and superseded items

- closes #2493
- consolidates contributor work from #2498, #2500, and #2501 with
original commit authorship preserved
- supersedes #2497 because it drops unknown `model_extra` counters
- supersedes #2499 because its hand-maintained provider field lists
would drift as SDKs evolve

## Validation

- focused changed-surface suite: `110 passed`
- broad offline v2/coverage suite: `2368 passed, 91 skipped, 73
deselected`
- Ruff check and format check: passed
- scoped `ty check`: passed
- `uv lock --check`: passed
- pre-commit hooks and `git diff --check`: passed

The 73 deselected tests require live provider credentials. An unfiltered
local run confirmed its 22 failures were provider network connections in
the restricted environment; GitHub provider jobs remain the
authoritative validation for those paths.

## Intentionally skipped

- provider additions or expansions: #2436, #2435, #2423, #2409, #2384,
#2322, #2306, #2298, #2283, #2168, #2086; issues #2408, #2383, #2365,
#2260, #2084, #2076
- broad architecture, product, security, or streaming decisions: #2394,
#2392, #2357, #2356, #2355, #2351, #2321, #2307, #2287, #2263; issues
#2479, #2403, #2393, #2391, #2316, #2272, #2056
- dependency batch: #2433
- nontrivial examples and editorial/resource additions: #2468, #2405,
#2401, #2354, #2346, #2311, #2305; issue #2404

These remain open because they need dedicated product, architecture,
provider, security, dependency, or editorial review and are not required
for the `1.15.5` patch release.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes retry usage totals and reask message content on failure paths;
scope is limited and heavily covered by tests, with no auth or
data-store changes.
> 
> **Overview**
> Bundles three v2 retry and wrapper fixes for a patch release.
> 
> **Retry usage accounting** replaces hand-maintained token field sums
with generic `_accumulate_models` on Pydantic usage objects. Numeric
fields (including nested models and `model_extra` counters) add across
retries; booleans and other non-numeric metadata are not treated as
billable. OpenAI and Anthropic paths share this logic.
> 
> **OpenAI Responses reask** appends a user correction when
`RESPONSES_TOOLS` validation fails but the output has no tool calls
(e.g. reasoning-only), so retries include feedback instead of repeating
the same request.
> 
> **Parallel tools** in `patch_v2` skips `prepare_response_model` and
does not replace `response_model` with the handler’s prepared wrapper
for parallel modes, keeping raw `Iterable[...]` hints so schemas and
parsed results include every member type.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
bbddca1. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
@jxnl

jxnl commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Superseded by #2502, now merged to main. The merged fix uses one recursive provider-agnostic accumulator instead of enumerating SDK fields, avoiding drift and pinned Anthropic SDK import incompatibilities. Closing this overlapping patch in favor of the consolidated implementation.

@jxnl jxnl closed this Aug 3, 2026
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.

Retry usage accumulation drops newer billable token fields (Anthropic stale, OpenAI overwritten with None)

3 participants