Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(costs): Codex cache hits were billed twice at full rate and forks counted their parent again

rubenluetke10-beepaa938da8834c
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 5548cd5223..4f6b0f822a 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -12436,3 +12436,59 @@ a recovery tears down a response, whatever the replacement must be grounded in
has to be re-supplied by the side that still holds it — and the request has to
name its evidence as complete, or the model will quietly widen it. "Use the
result already in this conversation" is a promise about someone else's memory.
+
+---
+
+## BUG-177: the Costs section bills Agentic IDE at 37 000 USD and the speech area is empty — Codex cache hits priced twice at full rate, forks counted again, and the speech meter had not run yet (HIGH, FIXED 2026-08-24)
+
+**Symptom (maintainer, 2026-08-24).** The Costs section's Agentic IDE area
+showed a subscription-equivalent of ~40 000 USD, 17.6 BILLION input tokens on
+`codex-cli`, and a 3.7-billion-token bucket with no model name. The speech
+area (`jarvis-voice`) showed nothing at all.
+
+**Evidence.** Straight from the index (`data/cli_usage_index.db`):
+
+* The biggest Codex row: `tokens_in=334 298, tokens_cached=332 544`. OpenAI's
+ usage object reports cache hits INSIDE `input_tokens`; Anthropic reports them
+ BESIDE it. One rule for both meant Codex input was counted at full price
+ including the 99 % that was a cache hit, and the cached share was then
+ ignored by the pricer on top.
+* One forked Codex thread: 1 787 `token_count` records written within 100 ms
+ of the fork, all before any `turn_context` (hence no model). A fork or
+ resume starts a NEW rollout file and replays the parent's entire history.
+ The dedup key was the byte offset in the file, which is new for a copy, so
+ every fork counted its parent's whole bill again.
+* `SpeechUsageRecorded` rows in `sessions.db`: 0. The meter shipped at 16:34;
+ the desktop app had been running since 09:58. Not a defect — the code had
+ never executed. It also only ever fills from the classic STT → brain → TTS
+ path; a speech-to-speech realtime model has no separate ears or mouth.
+
+**Fix.**
+
+* `jarvis/costs/cli_usage_index.py` — Codex `tokens_in` is
+ `input_tokens - cached_input_tokens`; the dedup key is
+ `session_id + total_token_usage` (the running total is monotonic within a
+ lineage, and a fork keeps its parent's `session_id`), so a replay collapses
+ onto the original; the insert lets a row with a model fill one indexed
+ without. `PRAGMA user_version` = 2 drops an index built under the old rule
+ and rebuilds it from the transcripts (~2 minutes for 3 300 files here).
+* `jarvis/brain/cost.py` — `calculate_cost_usd` takes `tokens_cached` and
+ bills it at `cache_read_fraction(model)` of the input rate (10 %, Gemini
+ 25 %). Before, cache reads were priced at zero — which also hid most of a
+ Claude Code bill (7.9 billion cached tokens on this machine).
+* `jarvis/costs/model.py` / `sources.py` — `price_entry` carries the cached
+ count through for the CLI and agent-chat readers.
+* Result on the same data: Codex 37 687 → 2 901 USD, the model-less bucket
+ 3.7 billion → 0.4 million tokens, Claude 2 535 → 4 278 USD (cache reads now
+ counted). Agentic IDE total 7 623 USD API-equivalent over the seat's life.
+* `costFormat.ts` — the areas are regrouped the way the maintainer reads
+ them: "{name}" is the assistant (every brain, whichever channel: realtime,
+ tool model, pipeline, agent chat, missions), "{name} Voice" is the speech
+ layer alone (STT + TTS), Agentic IDE unchanged. Order: Overall · {name} ·
+ {name} Voice · Agentic IDE.
+
+**Lesson.** Two vendors, one word, two meanings. "input tokens" is a superset
+of cache hits at one vendor and disjoint from them at the other, and a reader
+that normalises both into one column has to know which it is holding. And a
+dedup key that is a position in a file is only an identity for that file —
+anything a tool can copy needs a key made from the content.
diff --git a/jarvis/brain/cost.py b/jarvis/brain/cost.py
index 94e517968f..0d56ce4607 100644
--- a/jarvis/brain/cost.py
+++ b/jarvis/brain/cost.py
@@ -150,31 +150,65 @@ PRICING_USD_PER_MTOK: dict[str, tuple[float, float]] = {
}
+# What a prompt-cache READ costs relative to a fresh input token. Every
+# vendor bills cache hits at a flat discount off its own input rate, so the
+# fraction — not a second price table — is what has to be known per family:
+# Anthropic, OpenAI and xAI charge 10 %, Google's implicit caching 25 %.
+# Cache WRITES are not here: they are counted as plain input by every reader
+# (``cache_creation_input_tokens`` sits in ``tokens_in``), which under-prices
+# Anthropic's 1.25x write premium slightly rather than inventing a rate.
+CACHE_READ_FRACTION_DEFAULT = 0.10
+CACHE_READ_FRACTION_BY_PREFIX: tuple[tuple[str, float], ...] = (
+ ("gemini", 0.25),
+ ("google/", 0.25),
+)
+
+
+def cache_read_fraction(model: str | None) -> float:
+ """The share of the input rate a cached input token bills at."""
+ key = (model or "").strip().casefold()
+ for prefix, fraction in CACHE_READ_FRACTION_BY_PREFIX:
+ if key.startswith(prefix):
+ return fraction
+ return CACHE_READ_FRACTION_DEFAULT
+
+
def calculate_cost_usd(
model: str | None,
tokens_in: int,
tokens_out: int,
+ tokens_cached: int = 0,
) -> float:
"""Return the cost in USD for a single brain call.
Args:
model: Canonical model ID (e.g. ``"claude-opus-4-7-20251022"``).
``None`` or unknown → 0.0.
- tokens_in: Prompt tokens.
+ tokens_in: Prompt tokens that were NOT served from the prompt cache.
tokens_out: Completion tokens.
+ tokens_cached: Prompt tokens served from the cache, billed at
+ :func:`cache_read_fraction` of the input rate. A coding session
+ re-sends its whole context every turn and nearly all of it is a
+ cache hit, so pricing these at the full rate multiplies a real
+ bill by ten and ignoring them hides most of a Claude Code bill.
Returns:
Cost in USD. 0.0 if the model is not in the pricing table
or if the token counts are non-positive.
"""
- if not model or tokens_in <= 0 and tokens_out <= 0:
+ if not model or (tokens_in <= 0 and tokens_out <= 0 and tokens_cached <= 0):
return 0.0
rates = resolve_rates(model)
if rates is None:
log.debug("Cost pricing missing for model %r — returning 0.0", model)
return 0.0
in_rate, out_rate = rates
- return (max(0, tokens_in) * in_rate + max(0, tokens_out) * out_rate) / 1_000_000
+ cached_rate = in_rate * cache_read_fraction(model)
+ return (
+ max(0, tokens_in) * in_rate
+ + max(0, tokens_cached) * cached_rate
+ + max(0, tokens_out) * out_rate
+ ) / 1_000_000
# ----------------------------------------------------------------------
diff --git a/jarvis/costs/cli_usage_index.py b/jarvis/costs/cli_usage_index.py
index 8d89707ee9..d2f17be6b7 100644
--- a/jarvis/costs/cli_usage_index.py
+++ b/jarvis/costs/cli_usage_index.py
@@ -40,6 +40,24 @@ usage record; it is on ``turn_context`` records and is carried forward within
the file (and across a resumed scan, which is why the resume row stores it).
The session id comes from the ``session_meta`` record, or from the filename.
+Two Codex conventions differ from Claude's and both cost real money when
+missed (a 37 000 USD "bill" on one machine, 2026-08-24):
+
+* ``input_tokens`` INCLUDES ``cached_input_tokens`` — the OpenAI usage
+ object reports cache hits as a breakdown of the input count, whereas
+ Anthropic reports them as a separate field. The cached share is subtracted
+ so ``tokens_in`` means "uncached input" for every agent alike.
+* A forked or resumed thread starts a NEW rollout file and replays its whole
+ parent history into it as fresh ``token_count`` records — thousands of
+ them, stamped with the moment of the fork. Byte offsets are new, so they
+ cannot identify a turn across files. The running total can: within one
+ lineage it is monotonic and unique per real model call, and the lineage is
+ what ``session_meta.session_id`` names (a fork keeps its parent's
+ ``session_id`` and gets its own ``id``). The dedup key is therefore
+ ``session_id + total_token_usage`` and the replay collapses onto the
+ original. A replayed row can arrive BEFORE the parent's ``turn_context``
+ and so carry no model; the insert lets a later row with a model fill it in.
+
**agy** — ``<root>/sessions/**/wire.jsonl``. Two generations ship under one
binary and keep separate roots (``~/.kimi``, ``~/.kimi-code``); both are read,
since a machine can carry both histories. The usage record shape is taken from
@@ -160,6 +178,12 @@ _FILE_BYTE_BUDGET = 48 * 1024 * 1024
#: The trailing UUID of ``rollout-<iso>-<uuid>.jsonl``.
_ROLLOUT_ID = re.compile(r"([0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})$")
+# Bumped whenever a reader's accounting changes so rows already indexed under
+# the old rule would be wrong. An older index is dropped and rebuilt from the
+# transcripts, which are the source of truth; nothing is lost but time.
+# 2 — Codex: cached input subtracted from input; lineage-based dedup.
+_SCHEMA_VERSION = 2
+
_SCHEMA = """
CREATE TABLE IF NOT EXISTS indexed_files (
path TEXT PRIMARY KEY,
@@ -190,11 +214,16 @@ CREATE TABLE IF NOT EXISTS cli_turns (
CREATE INDEX IF NOT EXISTS idx_cli_turns_ts ON cli_turns (ts_ms);
"""
+# A duplicate is ignored except for one field: a row indexed without a model
+# (a Codex replay ahead of its ``turn_context``) takes the model from the copy
+# that knows it. Nothing else may change — the first sighting is the record.
_INSERT_TURN = (
- "INSERT OR IGNORE INTO cli_turns "
+ "INSERT INTO cli_turns "
"(agent, dedup_key, path, session_id, ts_ms, model, "
" tokens_in, tokens_out, tokens_cached, cwd, label) "
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) "
+ "ON CONFLICT(agent, dedup_key) DO UPDATE SET model=excluded.model "
+ "WHERE cli_turns.model = '' AND excluded.model <> ''"
)
_UPSERT_FILE = (
@@ -646,14 +675,15 @@ def _codex_row(
tokens_in, tokens_out, tokens_cached = _usage_totals(usage)
if tokens_in + tokens_out + tokens_cached <= 0:
return None
+ # OpenAI counts cache hits INSIDE ``input_tokens``; the convention here
+ # (and Anthropic's) keeps them apart. See the module docstring.
+ tokens_in = max(0, tokens_in - tokens_cached)
+ session_id = cursor.session_id or _codex_session_id(cand.path)
return (
cand.agent,
- # Codex records carry no id of their own, so the line's place in the
- # file is its identity. A rewritten file has its rows dropped first,
- # so an offset can never mean two different turns.
- f"{cand.key}:{offset}",
+ _codex_dedup_key(session_id, info, cand, offset),
cand.key,
- cursor.session_id or _codex_session_id(cand.path),
+ session_id,
_iso_ms(record.get("timestamp")),
cursor.model,
tokens_in,
@@ -664,6 +694,28 @@ def _codex_row(
)
+def _codex_dedup_key(
+ session_id: str, info: Mapping[str, Any], cand: _Candidate, offset: int
+) -> str:
+ """One key per real model call, the same in every file that replays it.
+
+ The cumulative ``total_token_usage`` after a call is unique within a
+ lineage (it only ever grows), so ``session_id`` plus that total names the
+ call wherever it is written down. Records without a running total fall
+ back to the line's place in the file — a rewritten file has its rows
+ dropped first, so an offset never means two different turns.
+ """
+ total = info.get("total_token_usage")
+ if isinstance(total, Mapping) and session_id:
+ counts = [
+ _int(total.get(k))
+ for k in ("input_tokens", "cached_input_tokens", "output_tokens", "total_tokens")
+ ]
+ if any(counts):
+ return f"{session_id}:" + ":".join(str(c) for c in counts)
+ return f"{cand.key}:{offset}"
+
+
def _codex_session_id(path: Path) -> str:
match = _ROLLOUT_ID.search(path.stem)
return match.group(1) if match else path.stem
@@ -836,6 +888,19 @@ def _open_rw(path: Path) -> sqlite3.Connection | None:
# fsyncs. A lost tail after a crash costs a re-read, never a wrong sum.
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
+ version = _int(conn.execute("PRAGMA user_version").fetchone()[0])
+ if version < _SCHEMA_VERSION:
+ # Rows counted under an older rule are wrong, not stale. Rebuild.
+ if _has_rows(conn):
+ log.info(
+ "cli usage index: schema %d < %d, rebuilding from the transcripts",
+ version,
+ _SCHEMA_VERSION,
+ )
+ conn.executescript(
+ "DROP TABLE IF EXISTS cli_turns; DROP TABLE IF EXISTS indexed_files;"
+ )
+ conn.execute(f"PRAGMA user_version={_SCHEMA_VERSION}")
conn.executescript(_SCHEMA)
conn.commit()
return conn
@@ -844,6 +909,19 @@ def _open_rw(path: Path) -> sqlite3.Connection | None:
return None
+def _has_rows(conn: sqlite3.Connection) -> bool:
+ """Whether an index holds any turn at all (decides if a rebuild is news)."""
+ try:
+ table = conn.execute(
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name='cli_turns'"
+ ).fetchone()
+ if table is None:
+ return False
+ return conn.execute("SELECT 1 FROM cli_turns LIMIT 1").fetchone() is not None
+ except sqlite3.Error:
+ return False
+
+
def _open_ro(path: Path) -> sqlite3.Connection | None:
"""Open the index read-only, or ``None`` when there is nothing to read."""
if not path.exists():
diff --git a/jarvis/costs/model.py b/jarvis/costs/model.py
index 9f0f2b76a0..b34c7b5bbb 100644
--- a/jarvis/costs/model.py
+++ b/jarvis/costs/model.py
@@ -187,6 +187,7 @@ def price_entry(
tokens_out: int,
recorded_usd: float,
subscription: bool = False,
+ tokens_cached: int = 0,
) -> tuple[float, PriceSource]:
"""Settle what a call actually cost and how confident that number is.
@@ -201,8 +202,13 @@ def price_entry(
like any other call. What changes is the label, so a report can show the
worth of the work without claiming the money moved. A seat whose model has
no rate anywhere is still a gap: the tokens are real and unpriced.
+
+ ``tokens_cached`` are prompt tokens the vendor served from its cache. They
+ are priced at the cache-read discount (:func:`jarvis.brain.cost.
+ cache_read_fraction`), never at the full input rate and never at zero —
+ for a coding agent they are nine tenths of every bill.
"""
- tokens = max(0, tokens_in) + max(0, tokens_out)
+ tokens = max(0, tokens_in) + max(0, tokens_out) + max(0, tokens_cached)
if subscription and tokens > 0:
if recorded_usd > 0:
return float(recorded_usd), "subscription"
@@ -211,7 +217,10 @@ def price_entry(
from jarvis.brain.cost import calculate_cost_usd, resolve_rates
if model and resolve_rates(model) is not None:
- return calculate_cost_usd(model, tokens_in, tokens_out), "subscription"
+ return (
+ calculate_cost_usd(model, tokens_in, tokens_out, tokens_cached),
+ "subscription",
+ )
return 0.0, "unknown"
if recorded_usd > 0:
@@ -233,4 +242,4 @@ def price_entry(
if not model or resolve_rates(model) is None:
return 0.0, "unknown"
- return calculate_cost_usd(model, tokens_in, tokens_out), "derived"
+ return calculate_cost_usd(model, tokens_in, tokens_out, tokens_cached), "derived"
diff --git a/jarvis/costs/sources.py b/jarvis/costs/sources.py
index 6f9ded55d5..6680852898 100644
--- a/jarvis/costs/sources.py
+++ b/jarvis/costs/sources.py
@@ -385,6 +385,7 @@ def _agent_chat_entries(path: Path | None, since_ms: int, until_ms: int) -> Iter
tokens_out=tokens_out,
recorded_usd=recorded,
subscription=start.get("runner", "") in SUBSCRIPTION_RUNNERS,
+ tokens_cached=tokens_cached,
)
yield CostEntry(
ts_ms=_int(row["ts_ms"]),
@@ -603,6 +604,7 @@ def _cli_entries(
tokens_out=turn.tokens_out,
recorded_usd=0.0,
subscription=True,
+ tokens_cached=turn.tokens_cached,
)
yield CostEntry(
ts_ms=turn.ts_ms,
diff --git a/jarvis/ui/web/frontend/src/components/costs/costFormat.ts b/jarvis/ui/web/frontend/src/components/costs/costFormat.ts
index 7fccc27cd7..21efc261ec 100644
--- a/jarvis/ui/web/frontend/src/components/costs/costFormat.ts
+++ b/jarvis/ui/web/frontend/src/components/costs/costFormat.ts
@@ -201,18 +201,23 @@ export interface SurfaceGroup {
export const SURFACE_GROUPS: SurfaceGroup[] = [
{ id: "all", surfaces: [], roles: ROLE_ORDER },
- // Talking. Everything a spoken turn costs, whichever path served it: the
- // realtime model, the tool model it delegated to, the classic pipeline
- // brain, and the ears and mouth around them. Naming this area after the
- // speech layer alone would leave it nearly empty while the feature it is
- // named after is the biggest spender in the app.
+ // The assistant itself — every model that thinks on its behalf, whichever
+ // channel the turn came in on: the realtime model and the tool model it
+ // delegated to, the classic pipeline brain, the agent chat and the
+ // missions it hands off to. "{name}" IS the assistant, so this area is
+ // named after it (maintainer decision 2026-08-24).
{
- id: "jarvis-voice",
- surfaces: ["voice", "jarvis-voice"],
- roles: ["realtime", "tool", "pipeline", "stt", "tts"],
+ id: "jarvis",
+ surfaces: ["voice", "agent-chat", "mission"],
+ roles: ["realtime", "tool", "pipeline", "agent", "worker"],
},
- // Typing — the agent chat and the missions it hands off to.
- { id: "jarvis", surfaces: ["agent-chat", "mission"], roles: ["agent", "worker"] },
+ // The assistant's voice — the speech layer built around the brain: the
+ // ears (speech to text) and the mouth (text to speech). Bills by audio
+ // second and by character, never by token, which is why it is its own
+ // surface. A speech-to-speech realtime model has no separate ears or
+ // mouth, so a machine that only talks through one keeps this area empty —
+ // and that empty is the truth, not a gap.
+ { id: "jarvis-voice", surfaces: ["jarvis-voice"], roles: ["stt", "tts"] },
// Coding — the workspaces, billed through vendor CLI seats.
{ id: "agentic-ide", surfaces: ["agentic-ide"], roles: ["agent", "worker"] },
];
diff --git a/jarvis/ui/web/frontend/src/views/CostsView.tsx b/jarvis/ui/web/frontend/src/views/CostsView.tsx
index 53ddb25e0c..10f5af9b77 100644
--- a/jarvis/ui/web/frontend/src/views/CostsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/CostsView.tsx
@@ -547,7 +547,7 @@ const AREA_ICONS = {
} as const;
/**
- * Overall · Jarvis · Agentic IDE · Jarvis Voice.
+ * Overall · Jarvis · Jarvis Voice · Agentic IDE.
*
* The same pill the front page uses for Voice/Chat (`home/SurfaceSwitch`) —
* one shape for "which area am I in", wherever the question appears.
diff --git a/tests/unit/costs/test_cli_usage_index.py b/tests/unit/costs/test_cli_usage_index.py
index 6d72a5f488..52c8d60bd6 100644
--- a/tests/unit/costs/test_cli_usage_index.py
+++ b/tests/unit/costs/test_cli_usage_index.py
@@ -103,7 +103,14 @@ def _codex_token_line(
ts: str = "2026-08-13T15:05:55.557Z",
last: dict[str, int] | None = None,
total: dict[str, int] | None = None,
+ turn: int = 1,
) -> str:
+ """One ``token_count`` record.
+
+ ``turn`` moves the running total the way a real session does — it only
+ ever grows — because the total is what identifies a call across files.
+ Two records with the same total ARE the same call.
+ """
return json.dumps(
{
"timestamp": ts,
@@ -113,12 +120,12 @@ def _codex_token_line(
"info": {
"total_token_usage": total
or {
- "input_tokens": 900_000,
- "cached_input_tokens": 400_000,
+ "input_tokens": 900_000 + 100 * turn,
+ "cached_input_tokens": 400_000 + 40 * turn,
"cache_write_input_tokens": 0,
- "output_tokens": 90_000,
+ "output_tokens": 90_000 + 30 * turn,
"reasoning_output_tokens": 40_000,
- "total_tokens": 990_000,
+ "total_tokens": 990_000 + 130 * turn,
},
"last_token_usage": last
or {
@@ -382,7 +389,7 @@ def test_codex_uses_last_token_usage_and_ignores_the_running_total(tmp_path: Pat
session = "019ffba8-3748-7652-bf9d-f3b54697b10a"
_write(
_codex_path(tmp_path, session),
- [*_codex_prelude(session), _codex_token_line(), _codex_token_line()],
+ [*_codex_prelude(session), _codex_token_line(turn=1), _codex_token_line(turn=2)],
)
refresh(data_dir=data, home=tmp_path)
@@ -390,8 +397,9 @@ def test_codex_uses_last_token_usage_and_ignores_the_running_total(tmp_path: Pat
turns = _all(data)
assert len(turns) == 2
assert {t.agent for t in turns} == {AGENT_CODEX}
- # last_token_usage only: 100 input + 5 cache write, 30 output, 40 cached.
- assert [t.tokens_in for t in turns] == [105, 105]
+ # last_token_usage only. OpenAI reports the 40 cache hits INSIDE the 100
+ # input tokens, so uncached input is 100 - 40 + 5 cache write = 65.
+ assert [t.tokens_in for t in turns] == [65, 65]
assert [t.tokens_out for t in turns] == [30, 30]
assert [t.tokens_cached for t in turns] == [40, 40]
# The model lives on turn_context and is carried forward to the usage rows.
@@ -430,16 +438,96 @@ def test_codex_turns_are_not_recounted_after_an_append(tmp_path: Path) -> None:
data = tmp_path / "data"
session = "019ffba8-3748-7652-bf9d-f3b54697b10a"
path = _codex_path(tmp_path, session)
- _write(path, [*_codex_prelude(session), _codex_token_line()])
+ _write(path, [*_codex_prelude(session), _codex_token_line(turn=1)])
refresh(data_dir=data, home=tmp_path)
- _append(path, [_codex_token_line(ts="2026-08-13T15:09:00.000Z")])
+ _append(path, [_codex_token_line(ts="2026-08-13T15:09:00.000Z", turn=2)])
result = refresh(data_dir=data, home=tmp_path)
assert result.turns_added == 1
assert len(_all(data)) == 2
+def test_codex_fork_replays_its_parent_but_is_counted_once(tmp_path: Path) -> None:
+ """A fork writes the whole parent history into a new file (2026-08-24).
+
+ Real shape: 1 787 ``token_count`` records inside 100 ms, all stamped
+ with the moment of the fork, before any ``turn_context`` — so no model.
+ The running total identifies each call, so the replay collapses onto the
+ parent's rows, and the parent's model fills the rows the replay lacked.
+ """
+ data = tmp_path / "data"
+ parent = "019fb38d-0077-7823-a306-c7c256d64efe"
+ fork = "019fb88c-ebde-7d11-b851-5ae72a0885cb"
+ fork_meta = json.dumps(
+ {
+ "timestamp": "2026-07-31T14:21:11.072Z",
+ "type": "session_meta",
+ "payload": {
+ "session_id": parent,
+ "id": fork,
+ "forked_from_id": parent,
+ "cwd": "/work/downloads",
+ },
+ }
+ )
+ replay = [
+ _codex_token_line(ts="2026-07-31T14:21:11.389Z", turn=1),
+ _codex_token_line(ts="2026-07-31T14:21:11.389Z", turn=2),
+ ]
+ # The fork is the NEWER file, so it is scanned first — with no model.
+ fork_path = tmp_path / ".codex" / "sessions" / "2026" / "07" / "31" / (
+ f"rollout-2026-07-31T16-21-11-{fork}.jsonl"
+ )
+ _write(fork_path, [fork_meta, *replay, _codex_token_line(turn=3)])
+ parent_path = tmp_path / ".codex" / "sessions" / "2026" / "07" / "30" / (
+ f"rollout-2026-07-30T17-03-10-{parent}.jsonl"
+ )
+ _write(
+ parent_path,
+ [*_codex_prelude(parent), _codex_token_line(turn=1), _codex_token_line(turn=2)],
+ )
+ import os
+
+ os.utime(parent_path, ns=(1, 1))
+
+ refresh(data_dir=data, home=tmp_path)
+
+ turns = _all(data)
+ # Two real calls in the parent, one new call in the fork. Not five.
+ assert len(turns) == 3
+ assert {t.session_id for t in turns} == {parent}
+ # The replayed rows had no model; the parent's copy supplied it.
+ assert sum(1 for t in turns if t.model == "gpt-5.6-terra") == 2
+ assert sum(1 for t in turns if t.model == "") == 1
+
+
+def test_an_index_built_under_an_older_rule_is_rebuilt(tmp_path: Path) -> None:
+ """A schema bump throws the old rows away rather than mixing two rules."""
+ import sqlite3
+
+ from jarvis.costs.cli_usage_index import index_db_path
+
+ data = tmp_path / "data"
+ session = "019ffba8-3748-7652-bf9d-f3b54697b10a"
+ _write(_codex_path(tmp_path, session), [*_codex_prelude(session), _codex_token_line()])
+ refresh(data_dir=data, home=tmp_path)
+ assert len(_all(data)) == 1
+
+ db = index_db_path(data)
+ with sqlite3.connect(db) as conn:
+ conn.execute(
+ "UPDATE cli_turns SET tokens_in = 999999"
+ ) # a number the old rule produced
+ conn.execute("PRAGMA user_version=1")
+
+ refresh(data_dir=data, home=tmp_path)
+
+ turns = _all(data)
+ assert len(turns) == 1
+ assert turns[0].tokens_in == 65
+
+
# ---------------------------------------------------------------------------
# agy
# ---------------------------------------------------------------------------
diff --git a/tests/unit/costs/test_cost_read_model.py b/tests/unit/costs/test_cost_read_model.py
index 5ec09ea6fb..83b16b49df 100644
--- a/tests/unit/costs/test_cost_read_model.py
+++ b/tests/unit/costs/test_cost_read_model.py
@@ -360,6 +360,42 @@ def test_known_model_is_re_derived() -> None:
assert cost > 0
+def test_cached_tokens_bill_at_the_cache_read_rate() -> None:
+ """A coding session is nine tenths cache hits — neither free nor full price."""
+ fresh, _ = price_entry(
+ provider="anthropic",
+ model="claude-opus-4-7-20251022",
+ tokens_in=1_000_000,
+ tokens_out=0,
+ recorded_usd=0.0,
+ )
+ cached, source = price_entry(
+ provider="anthropic",
+ model="claude-opus-4-7-20251022",
+ tokens_in=0,
+ tokens_out=0,
+ recorded_usd=0.0,
+ tokens_cached=1_000_000,
+ )
+ assert source == "derived"
+ assert 0 < cached < fresh
+ assert cached == pytest.approx(fresh * 0.10)
+
+
+def test_a_seat_with_only_cached_tokens_is_still_priced() -> None:
+ cost, source = price_entry(
+ provider="claude-cli",
+ model="claude-opus-4-7-20251022",
+ tokens_in=0,
+ tokens_out=0,
+ recorded_usd=0.0,
+ subscription=True,
+ tokens_cached=1_000_000,
+ )
+ assert source == "subscription"
+ assert cost > 0
+
+
def test_no_tokens_no_gap() -> None:
"""A 0.0 with nothing consumed is not a pricing hole."""
assert price_entry(