Skip to content

fix: tolerate malformed token usage values#6

Open
royalpinto007 wants to merge 1 commit into
traceroot-ai:mainfrom
royalpinto007:fix/malformed-usage-token-counts
Open

fix: tolerate malformed token usage values#6
royalpinto007 wants to merge 1 commit into
traceroot-ai:mainfrom
royalpinto007:fix/malformed-usage-token-counts

Conversation

@royalpinto007

Copy link
Copy Markdown

Fixes #5

Summary

Makes token usage parsing defensive so malformed usage values from Claude Code transcripts default to 0 instead of raising and breaking trace emission.

Details

  • Adds a small _usage_int(...) helper for token usage coercion.
  • Applies it to input, output, cache read, and cache creation token fields.
  • Adds a regression test covering string/object malformed values while preserving the assistant text output.

Why

Transcript data is external input. A single malformed usage field should not prevent the plugin from emitting an otherwise valid trace.

Testing

  • uv run pytest tests/test_tokens.py
  • uv run pytest

@royalpinto007

Copy link
Copy Markdown
Author
# Before fix
PYTHONPATH=. python /tmp/repro_traceroot_plugin_bad_usage.py
Traceback (most recent call last):
  File "/tmp/repro_traceroot_plugin_bad_usage.py", line 20, in <module>
    calls = tokens.llm_calls([msg])
            ^^^^^^^^^^^^^^^^^^^^^^^
  File "traceroot_observability/tokens.py", line 121, in llm_calls
    inp = int(u.get("input_tokens") or 0)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'unknown'
# After fix
PYTHONPATH=. python /tmp/repro_traceroot_plugin_bad_usage.py
parsed successfully
prompt 0
completion 0
cache_read 0
cache_creation 0
text ok

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.

Malformed token usage values can break trace emission

1 participant