Files
ai-agent/backend/test_pi_cost_repeat.py
gabrielvidalandClaude Opus 5.5 e0d9dc42e4 fix(parse): a provider-billed cost counts once per API call
A repeated record of an already-priced call (one per content block) had its
costUSD added to the total again, so the total ran ahead of the per-tool
breakdown. The legacy reader no longer puts it on the call, the fold reads the
cost only off a counted usage, and call.cost leaves the v1 vocabulary.
Latent: the parser A/B is zero on all 111 pi transcripts and on the default
500-file corpus (chunked too). test_pi_cost_repeat pins it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 17:33:33 +01:00

70 lines
2.4 KiB
Python

"""A provider-billed cost (pi's ``costUSD``) is counted once per API call.
Claude Code's format writes one record per content block of a reply, each
carrying the reply's usage; the fold counts the call's usage once. Its
``costUSD`` used to be added again for every repeat — the total then ran ahead
of the per-tool breakdown. Now a repeat adds nothing."""
import json
import os
import pathlib
import tempfile
import unittest
import conversations as c
SID = "3f0c2a4e-6b1d-4c7a-9e2f-5a8b7c6d1e0f"
MODEL = "openai/gpt-6-mini"
def _user(text, ts):
return {"type": "user", "sessionId": SID, "timestamp": ts,
"message": {"role": "user", "content": text}}
def _block(ts, block, cost=0.25):
return {"type": "assistant", "sessionId": SID, "timestamp": ts, "costUSD": cost,
"requestId": "req_1",
"message": {"id": "msg_1", "role": "assistant", "model": MODEL,
"stop_reason": "end_turn",
"usage": {"input_tokens": 100, "output_tokens": 20},
"content": [block]}}
def _parse(records):
fd, path = tempfile.mkstemp(suffix=".jsonl")
try:
with os.fdopen(fd, "w") as f:
f.write("\n".join(json.dumps(r) for r in records) + "\n")
return c.parse_conversation(pathlib.Path(path))
finally:
os.unlink(path)
class ProviderCostOncePerCall(unittest.TestCase):
def test_repeated_records_bill_the_call_once(self):
s = _parse([
_user("hi", "2026-11-24T10:00:00Z"),
_block("2026-11-24T10:00:02Z", {"type": "thinking", "thinking": "…"}),
_block("2026-11-24T10:00:03Z", {"type": "text", "text": "Hello"}),
_block("2026-11-24T10:00:04Z", {"type": "text", "text": "again"}),
])
self.assertEqual(s["assistantTurns"], 1)
self.assertAlmostEqual(s["cost"], 0.25)
def test_two_calls_bill_twice(self):
second = _block("2026-11-24T10:00:09Z", {"type": "text", "text": "two"})
second["requestId"] = "req_2"
second["message"]["id"] = "msg_2"
s = _parse([
_user("hi", "2026-11-24T10:00:00Z"),
_block("2026-11-24T10:00:02Z", {"type": "text", "text": "one"}),
second,
])
self.assertEqual(s["assistantTurns"], 2)
self.assertAlmostEqual(s["cost"], 0.5)
if __name__ == "__main__":
unittest.main()