Skip to content

fix(sdk): read cache buckets via model_dump to fix AttributeError for providers without prompt caching - #5329

Closed
atifnaqvi-jpg wants to merge 1 commit into
OpenHands:mainfrom
atifnaqvi-jpg:fix/normalize-usage-cache-fields-tag
Closed

atifnaqvi-jpg wants to merge 1 commit into
OpenHands:mainfrom
atifnaqvi-jpg:fix/normalize-usage-cache-fields-tag

Conversation

@atifnaqvi-jpg

@atifnaqvi-jpg atifnaqvi-jpg commented Sep 25, 2026 •

Copy link
Copy Markdown

HUMAN:

Reproduced this on my self hosted Agent Canvas where profile saves were blocked while using ollama cloud models specifically deepseek flash 4.1 . Patch is now verified locally; the AttributeError no longer occurs and profile saves now succeed.


AGENT:

Why

normalize_usage() reads prompt_tokens_details.cache_creation_tokens directly, guarded only by membership in model_fields_set:

cache_write = 0
if (
    prompt_details is not None
    and "cache_creation_tokens" in prompt_details.model_fields_set
):
    cache_write = int(prompt_details.cache_creation_tokens or 0)

LiteLLM's PromptTokensDetailsWrapper.__init__ deletes unset optional fields, while its __setattr__ mirroring keeps the name in model_fields_set. The guard therefore passes and the read raises AttributeError.

Summary

  • Read both cache namings (cache_creation_tokens, cache_write_tokens) through model_dump() instead of a direct attribute read, so a deleted optional field defaults to 0 with no dynamic attribute access.
  • Replace the MagicMock-based cache-read test with a real PromptTokensDetailsWrapper, and add tests covering the deleted-field shape and the cache_write_tokens naming.

Issue Number

Fixes #5168.

How to Test

Reproduced and verified on a self-hosted Agent Canvas (@openhands/agent-canvas 1.24.0, agent-server 1.49.6, litellm on the OpenAI-compatible route).

1. Reproduce the crash on unmodified source. Building a Usage with a PromptTokensDetailsWrapper that omits cache fields, then calling normalize_usage(), raises before the fix:

AttributeError: 'PromptTokensDetailsWrapper' object has no attribute 'cache_creation_tokens'

Shape used (raises on the unfixed code at any litellm version):

Usage(
    prompt_tokens=100,
    completion_tokens=50,
    total_tokens=150,
    prompt_tokens_details=PromptTokensDetailsWrapper(
        cached_tokens=25, cache_creation_tokens=None
    ),
)

Note that a cached_tokens-only wrapper does not reproduce under the litellm version pinned in uv.lock — the name stays out of model_fields_set there, so the old guard returns early. That is why the earlier regression test did not guard this bug in CI.

2. End-to-end on the Canvas UI. Saving an LLM profile for a provider that reports no cache fields previously failed validation. After the fix:

  • The profile saves successfully (settings persist with the chosen model and base URL).
  • No AttributeError appears in the agent-server log for the profile-validation path.
  • A conversation starts and runs.

3. Commands run.

uv run pytest tests/sdk/llm/test_llm_telemetry.py     # 49 passed
uv run pre-commit run --files openhands-sdk/openhands/sdk/llm/utils/telemetry.py \
                                tests/sdk/llm/test_llm_telemetry.py

All hooks pass, including Forbid dynamic attribute access in SDK (no getattr introduced), Ruff format, Ruff lint and pyright.

The new naming test fails on unmodified source (assert 0 == 5) and passes with the fix.

normalize_usage() read prompt_tokens_details.cache_creation_tokens
directly, guarded only by membership in model_fields_set. LiteLLM's
PromptTokensDetailsWrapper deletes unset optional fields while leaving
the name in model_fields_set, so the guard passes and the read raises
AttributeError, failing LLM profile validation.

Read the details through model_dump() instead: a deleted field is
absent from the dump and defaults to 0, with no dynamic attribute
access. Also read the cache_write_tokens naming, which was previously
ignored, and add regression tests covering the deleted-field shape and
that naming.
@all-hands-bot

Copy link
Copy Markdown
Collaborator

⏳ Review waiting on checks

The current head 4305d13cd628 still has checks that have not finished, so no review conversation was started:

  • Agent Server
  • Check Docstrings
  • Create GitHub Release
  • Deprecation deadlines
  • Persisted settings compatibility checks
  • Pre-commit checks
  • REST API breakage checks
  • Review Thread Gate
  • Run tests
  • TypeScript client CI
  • TypeScript client endpoint audit
  • TypeScript client integration tests
  • Version bump guard

No action is needed. The scheduled scan retries once every check on the head reports a conclusion.

This is an automated check - no AI was used to generate this comment.

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This review was posted by an AI agent (OpenHands).

Scope

This change belongs in this repository: it fixes normalize_usage() in openhands-sdk/openhands/sdk/llm/utils/telemetry.py, which is SDK-owned, and the linked issue #5168 carries ready-for-dev. No cross-repository move is needed.

What I verified on head 4305d13c

  • The AttributeError is real and the fix addresses it. Against the pinned litellm 1.93.0 I reproduced the failing shape: PromptTokensDetailsWrapper(cached_tokens=25, cache_creation_tokens=None) keeps cache_creation_tokens in model_fields_set while hasattr(..., "cache_creation_tokens") is False, so the old guard passed and the attribute read raised. The new model_dump() read returns cache_creation_tokens: 30 for the Anthropic naming and cache_write_tokens: 5 for the OpenAI naming, and cached_tokens is read correctly.
  • uv run --frozen pytest tests/sdk/llm/test_llm_telemetry.py -q -> 49 passed on this head, and the new tests use real PromptTokensDetailsWrapper objects instead of mocks, matching the repo's "prefer real code paths over mocks" guidance.
  • Head SHA is still 4305d13cd6288059dafb0ac031102ed1b7dd581d. The only PR comment is the automation's "Review waiting on checks" note; there are no reviews or review comments on this head yet. Issue #5168 is still open with bug, llm, priority:medium, sdk, ready-for-dev.

Findings

1. This change is already superseded on main (and now conflicts with it)

main has moved since this branch was cut: base.sha is fcc102a, and the PR is currently mergeable: false / mergeable_state: dirty. The conflict is exactly this hunk. PR #5327 ("fix(sdk): tolerate null cache_creation_tokens in usage telemetry (minimax-m3 crash)") merged to main on 2026-09-28 as commit 71612374a8, and main's normalize_usage() now reads:

if (
    prompt_details is not None
    and "cache_creation_tokens" in prompt_details.model_fields_set
    and hasattr(prompt_details, "cache_creation_tokens")
):
    cache_write = int(prompt_details.cache_creation_tokens or 0)

So the AttributeError described here is already fixed on main, and rebasing this PR would drop that fix (git merge-tree reports a content conflict in telemetry.py between fcc102a and this head). Two consequences for the merge decision:

  • Linked issue #5168 is already resolved on main by #5327; the description's note that a cached_tokens-only wrapper "does not reproduce under the litellm version pinned in uv.lock" describes main before #5327, not current main.
  • Sibling PRs #5169 and #5335 target the same hunk. Merging a third variant of the same guard is redundant; the incremental value here (also reading the OpenAI cache_write_tokens naming via model_dump()) should be rebased onto main and de-duplicated, or folded into the surviving PR.

2. Live production evidence is missing for a production-facing bug fix

The repository review guide requires authentic before/after evidence through the real supported entry point for bug fixes whose failure occurs on a runtime or integration path. The PR reports manual local reproduction and "verified locally" but includes no logs, API responses, or persisted artifacts from the profile-validation path. The new tests forge the failing state directly, which is valid regression protection but does not show that production reaches it.

3. CI on this head is not green

Every pull_request workflow run on 4305d13c (latest at 2026-09-25T18:19Z) reports conclusion: action_required, including Run tests and Pre-commit checks. The checks reporting success (PR Description Check, PR Artifacts) are pull_request_target runs. The "49 passed" in the description is a local run, not this head's CI result. Combined with the dirty merge state above, this is not an approvable head.

Verdict

The fix itself contains no code defect, but this head cannot be approved: it is superseded by the merged #5327, now conflicts with main, and its required CI has not passed. Recommend closing this PR in favor of the change already on main (or rebasing onto main and de-duplicating against #5169/#5335), with a maintainer decision on which PR survives.

🔄 CHANGES REQUESTED

@atifnaqvi-jpg

Copy link
Copy Markdown
Author

Closing this in favour of #5327, which merged to main on 2026-09-28 and fixes the same crash (the cache_creation_tokens guard in normalize_usage()).

Confirmed by the review on this head: main now carries #5327's guard, and this branch conflicts with it — rebasing would drop that fix rather than add to it.

For the record, the one increment this branch had over #5327 is reading both cache-write namings (cache_creation_tokens and cache_write_tokens) via model_dump(), which avoids dynamic attribute access entirely. That was already raised on #5169, so the maintainers have it.

Thanks for the review.

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.

AttributeError in Telemetry._cache_buckets for providers without prompt caching

2 participants