fix(storage,api): usage cost as per-turn delta of the sdk running total, backfill

This commit is contained in:
hh committed 2026-09-01 15:37:53 +02:00
1 parent 3406e2e178
commit 63014a487d
6 files changed
+304 -5

No files matched your search

+19 -1
View File
@@ -287,7 +287,17 @@ class TranscriptEntry(SQLModel, table=True):
class Usage(SQLModel, table=True):
"""Per-turn token accounting from ``ResultMessage.usage``."""
"""Per-turn token accounting from ``ResultMessage``.
Token columns come from ``ResultMessage.usage`` and are sums over the
turn's API calls. ``cost_usd`` and ``model_usage`` are **per-turn deltas**:
the SDK reports ``total_cost_usd`` and ``model_usage`` cumulatively for
the claude process (growing across the turns of a session, reset when
the process is respawned), so :func:`append_usage` stores the raw values
in ``cost_usd_total`` / ``model_usage_total`` and the difference against
the previous row of the same session here. Summing ``cost_usd`` over rows
is therefore meaningful; summing ``cost_usd_total`` is not.
"""
__tablename__ = "usage"
@@ -311,6 +321,14 @@ class Usage(SQLModel, table=True):
default=None,
sa_column=Column(JSON().with_variant(JSONB(), "postgresql"), nullable=True),
)
"""Per-model tokens, cost and web searches - per-turn delta (see class doc)."""
cost_usd_total: float | None = Field(default=None)
"""``ResultMessage.total_cost_usd`` verbatim: cumulative for the claude process."""
model_usage_total: dict[str, Any] | None = Field(
default=None,
sa_column=Column(JSON().with_variant(JSONB(), "postgresql"), nullable=True),
)
"""``ResultMessage.model_usage`` verbatim: cumulative for the claude process."""
class RateLimit(SQLModel, table=True):