Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/copilot_usage/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"""

import builtins
import math
from datetime import UTC, datetime
from enum import StrEnum
from pathlib import Path
Expand Down Expand Up @@ -220,6 +221,7 @@ def parse_token_int(raw: object) -> int | None:
Rules:

- ``bool`` / ``str`` → ``None`` (invalid, not coerced)
- IEEE 754 special ``float`` (``inf``, ``-inf``, ``nan``) → ``None``
- non-whole ``float`` → ``None``
- zero or negative ``int`` / ``float`` → ``None``
- positive whole-number ``float`` → coerced to ``int``
Expand All @@ -229,6 +231,8 @@ def parse_token_int(raw: object) -> int | None:
if isinstance(raw, (bool, str)):
return None
if isinstance(raw, float):
if not math.isfinite(raw):
return None
if not raw.is_integer():
return None
tokens = int(raw)
Expand Down
8 changes: 8 additions & 0 deletions tests/copilot_usage/test_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -4948,6 +4948,11 @@ def test_returns_none_for_missing_key(self) -> None:
)
assert _extract_output_tokens(ev) is None

@pytest.mark.parametrize("special", [float("inf"), float("nan"), float("-inf")])
def test_returns_none_for_ieee_special_floats(self, special: float) -> None:
"""IEEE 754 special floats (inf, nan, -inf) are not valid token counts."""
assert _extract_output_tokens(_make_assistant_event(special)) is None


_EXTRACT_TOKENS_CASES: list[tuple[str, object, int | None]] = [
("valid_int", 42, 42),
Expand Down Expand Up @@ -5021,6 +5026,9 @@ def test_missing_key_no_pydantic(self) -> None:
("large_positive_int", 1234),
("whole_float", 1234.0),
("fractional_float", 3.14),
("float_inf", float("inf")),
("float_neg_inf", float("-inf")),
("float_nan", float("nan")),
]


Expand Down
Loading