Skip to content

Commit 8491ff8

Browse files
fix(metrics): add free-tier config support, stale pricing warnings, and legacy row re-pricing
1 parent d651e37 commit 8491ff8

7 files changed

Lines changed: 110 additions & 39 deletions

File tree

‎src/gitmate/cli.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -252,12 +252,12 @@ def config_set(field: str, value: str) -> None:
252252
setattr(cfg, field, int_val)
253253
elif field == "cache_dir":
254254
cfg.cache_dir = None if value in ("", "none") else value.strip() or None
255-
elif field == "allow_noninteractive_commit":
255+
elif field in ("allow_noninteractive_commit", "free_tier"):
256256
val_clean = value.strip().lower()
257257
if val_clean == "true":
258-
cfg.allow_noninteractive_commit = True
258+
setattr(cfg, field, True)
259259
elif val_clean == "false":
260-
cfg.allow_noninteractive_commit = False
260+
setattr(cfg, field, False)
261261
else:
262262
raise typer.BadParameter(f"'{field}' must be 'true' or 'false'.")
263263
elif field in ("model", "commit_style"):

‎src/gitmate/config.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ class GitmateConfig:
6464
template_overhead: int = DEFAULT_TEMPLATE_OVERHEAD
6565
cache_dir: str | None = None
6666
allow_noninteractive_commit: bool = False
67+
free_tier: bool = False
6768

6869

6970
class SecretStore(Protocol):
@@ -209,6 +210,11 @@ def load_config(path: Path | None = None) -> GitmateConfig:
209210
)
210211
allow_noninteractive = allow_noninteractive_raw
211212

213+
free_tier_raw = raw.get("free_tier", False)
214+
if not isinstance(free_tier_raw, bool):
215+
raise ConfigError(f"cannot parse {resolved}: 'free_tier' must be a boolean")
216+
free_tier = free_tier_raw
217+
212218
return GitmateConfig(
213219
model=model,
214220
commit_style=style,
@@ -219,6 +225,7 @@ def load_config(path: Path | None = None) -> GitmateConfig:
219225
template_overhead=overhead,
220226
cache_dir=cache_dir,
221227
allow_noninteractive_commit=allow_noninteractive,
228+
free_tier=free_tier,
222229
)
223230

224231

@@ -241,4 +248,6 @@ def save_config(cfg: GitmateConfig, path: Path | None = None) -> None:
241248
data["cache_dir"] = cfg.cache_dir
242249
if cfg.allow_noninteractive_commit:
243250
data["allow_noninteractive_commit"] = cfg.allow_noninteractive_commit
251+
if cfg.free_tier:
252+
data["free_tier"] = cfg.free_tier
244253
resolved.write_text(tomli_w.dumps(data), encoding="utf-8")

‎src/gitmate/fallback.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,7 @@ def generate_commit_message(
308308
tokens_out=chunk_out or None,
309309
cache_hit=False,
310310
fallback_used=False,
311+
free_tier=cfg.free_tier,
311312
)
312313

313314
summary_note = (
@@ -344,6 +345,7 @@ def generate_commit_message(
344345
tokens_out=resp.output_tokens,
345346
cache_hit=cache_hit,
346347
fallback_used=False,
348+
free_tier=cfg.free_tier,
347349
)
348350
cost = round(chunk_cost + final_cost, 6)
349351

‎src/gitmate/metrics.py‎

Lines changed: 42 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
METRICS_DIR_ENV_VAR = "GITMATE_METRICS_DIR"
1818

1919
#: Model pricing in USD per 1,000,000 tokens (input_rate, output_rate).
20+
#: NOTE: Upstream rates change over time. Verify against https://ai.google.dev/pricing
21+
#: and https://docs.anthropic.com/pricing before relying on this for real financial reports.
2022
MODEL_PRICING: dict[str, tuple[float, float]] = {
2123
"gemini-3.5-flash-lite": (0.30, 2.50),
2224
"gemini-flash-lite": (0.30, 2.50),
@@ -102,12 +104,13 @@ def calculate_cost(
102104
tokens_out: int | None,
103105
cache_hit: bool = False,
104106
fallback_used: bool = False,
107+
free_tier: bool = False,
105108
) -> float:
106109
"""Calculate estimated cost in USD based on model pricing table.
107110
108-
Cache hits and template fallbacks consume zero billed API tokens ($0.00).
111+
Cache hits, template fallbacks, and free-tier Gemini usage consume zero billed API tokens ($0.00).
109112
"""
110-
if cache_hit or fallback_used:
113+
if cache_hit or fallback_used or (free_tier and model.startswith("gemini")):
111114
return 0.0
112115
in_tokens = tokens_in or 0
113116
out_tokens = tokens_out or 0
@@ -178,6 +181,7 @@ def record_invocation(
178181
estimated_cost_usd: float | None = None,
179182
db_path: Path | str | None = None,
180183
timestamp: str | None = None,
184+
free_tier: bool = False,
181185
) -> None:
182186
"""Record an invocation into SQLite database at db_path or default.
183187
@@ -197,6 +201,7 @@ def record_invocation(
197201
tokens_out=tokens_out,
198202
cache_hit=cache_hit,
199203
fallback_used=fallback_used,
204+
free_tier=free_tier,
200205
)
201206
)
202207

@@ -251,21 +256,38 @@ def get_invocations(
251256
cursor = conn.cursor()
252257
cursor.execute(query)
253258
rows = cursor.fetchall()
254-
return [
255-
InvocationRecord(
256-
id=row["id"],
257-
timestamp=row["timestamp"],
258-
command=row["command"],
259-
model=row["model"],
260-
tokens_in=row["tokens_in"],
261-
tokens_out=row["tokens_out"],
262-
cache_hit=bool(row["cache_hit"]),
263-
latency_ms=row["latency_ms"],
264-
fallback_used=bool(row["fallback_used"]),
265-
estimated_cost_usd=float(row["estimated_cost_usd"]),
259+
records: list[InvocationRecord] = []
260+
for row in rows:
261+
raw_cost = float(row["estimated_cost_usd"])
262+
# If an older row had tokens but $0.00 was recorded (and not cache hit or fallback),
263+
# recalculate it at read-time against current pricing table:
264+
if (
265+
raw_cost == 0.0
266+
and not bool(row["cache_hit"])
267+
and not bool(row["fallback_used"])
268+
and ((row["tokens_in"] or 0) > 0 or (row["tokens_out"] or 0) > 0)
269+
):
270+
raw_cost = calculate_cost(
271+
model=row["model"],
272+
tokens_in=row["tokens_in"],
273+
tokens_out=row["tokens_out"],
274+
)
275+
276+
records.append(
277+
InvocationRecord(
278+
id=row["id"],
279+
timestamp=row["timestamp"],
280+
command=row["command"],
281+
model=row["model"],
282+
tokens_in=row["tokens_in"],
283+
tokens_out=row["tokens_out"],
284+
cache_hit=bool(row["cache_hit"]),
285+
latency_ms=row["latency_ms"],
286+
fallback_used=bool(row["fallback_used"]),
287+
estimated_cost_usd=raw_cost,
288+
)
266289
)
267-
for row in rows
268-
]
290+
return records
269291
except Exception as exc: # noqa: BLE001
270292
logger.warning("Failed to retrieve invocations from metrics DB: %s", exc)
271293
return []
@@ -283,26 +305,11 @@ def get_monthly_spend(
283305
now = datetime.now(UTC)
284306
y = year if year is not None else now.year
285307
m = month if month is not None else now.month
286-
prefix = f"{y:04d}-{m:02d}%"
308+
prefix = f"{y:04d}-{m:02d}"
287309

288-
try:
289-
target = get_metrics_db_path(db_path)
290-
if not target.exists():
291-
return 0.0
292-
conn = sqlite3.connect(target, timeout=5.0)
293-
with contextlib.closing(conn):
294-
_ensure_schema(conn)
295-
cursor = conn.cursor()
296-
cursor.execute(
297-
"SELECT COALESCE(SUM(estimated_cost_usd), 0.0) FROM invocations WHERE timestamp LIKE ?",
298-
(prefix,),
299-
)
300-
row = cursor.fetchone()
301-
val = float(row[0]) if row and row[0] is not None else 0.0
302-
return round(val, 6)
303-
except Exception as exc: # noqa: BLE001
304-
logger.warning("Failed to calculate monthly spend: %s", exc)
305-
return 0.0
310+
records = get_invocations(db_path=db_path)
311+
month_spend = sum(r.estimated_cost_usd for r in records if r.timestamp.startswith(prefix))
312+
return round(month_spend, 6)
306313

307314

308315
def _build_breakdown(records: list[InvocationRecord]) -> BreakdownStats:

‎tests/test_cli.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,11 +288,24 @@ def test_config_set_allow_noninteractive_commit(tmp_config_dir: Path) -> None:
288288
assert "must be 'true' or 'false'" in res.output
289289

290290

291+
def test_config_set_free_tier(tmp_config_dir: Path) -> None:
292+
# Set True
293+
res = runner.invoke(cli.app, ["config", "set", "free_tier", "true"])
294+
assert res.exit_code == 0
295+
assert load_config().free_tier is True
296+
297+
# Set False
298+
res = runner.invoke(cli.app, ["config", "set", "free_tier", "false"])
299+
assert res.exit_code == 0
300+
assert load_config().free_tier is False
301+
302+
291303
def test_config_show_displays_allow_noninteractive_commit(tmp_config_dir: Path) -> None:
292304
res = runner.invoke(cli.app, ["config", "show"])
293305
assert res.exit_code == 0
294306
assert "allow_noninteractive_commit" in res.output
295307
assert "False" in res.output
308+
assert "free_tier" in res.output
296309

297310

298311
def test_stats_cli_empty_database(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:

‎tests/test_config.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,3 +234,35 @@ def test_allow_noninteractive_commit_invalid_types_raise(
234234
config_path().write_text(f"allow_noninteractive_commit = {bad_val}\n", encoding="utf-8")
235235
with pytest.raises(ConfigError, match="'allow_noninteractive_commit' must be a boolean"):
236236
load_config()
237+
238+
239+
def test_free_tier_default_false(tmp_config_dir: Path) -> None:
240+
assert GitmateConfig().free_tier is False
241+
assert load_config().free_tier is False
242+
243+
244+
def test_free_tier_save_load_round_trip(tmp_config_dir: Path) -> None:
245+
cfg = GitmateConfig(free_tier=True)
246+
save_config(cfg)
247+
248+
content = config_path().read_text(encoding="utf-8")
249+
assert "free_tier = true" in content
250+
251+
loaded = load_config()
252+
assert loaded.free_tier is True
253+
254+
255+
def test_free_tier_omitted_when_false(tmp_config_dir: Path) -> None:
256+
cfg = GitmateConfig(free_tier=False)
257+
save_config(cfg)
258+
259+
content = config_path().read_text(encoding="utf-8")
260+
assert "free_tier" not in content
261+
262+
263+
@pytest.mark.parametrize("bad_val", ['"true"', '"false"', "1", "0", "1.5", "[true]"])
264+
def test_free_tier_invalid_types_raise(tmp_config_dir: Path, bad_val: str) -> None:
265+
config_path().parent.mkdir(parents=True, exist_ok=True)
266+
config_path().write_text(f"free_tier = {bad_val}\n", encoding="utf-8")
267+
with pytest.raises(ConfigError, match="'free_tier' must be a boolean"):
268+
load_config()

‎tests/test_metrics.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,13 @@ def test_calculate_cost() -> None:
278278
cost_claude = calculate_cost("claude-3-5-sonnet", 10_000, 1_000)
279279
assert cost_claude == 0.045
280280

281+
# Free tier: Gemini models calculate as $0.0
282+
cost_free_gemini = calculate_cost("gemini-3.5-flash-lite", 100_000, 10_000, free_tier=True)
283+
assert cost_free_gemini == 0.0
284+
# Free tier: Non-Gemini models remain billed
285+
cost_free_claude = calculate_cost("claude-3-5-sonnet", 10_000, 1_000, free_tier=True)
286+
assert cost_free_claude == 0.045
287+
281288

282289
def test_schema_migration_adds_estimated_cost_column(tmp_path: Path) -> None:
283290
db_file = tmp_path / "legacy_metrics.db"
@@ -306,7 +313,8 @@ def test_schema_migration_adds_estimated_cost_column(tmp_path: Path) -> None:
306313
init_db(db_file)
307314
records = get_invocations(db_file)
308315
assert len(records) == 1
309-
assert records[0].estimated_cost_usd == 0.0
316+
# Read-time re-pricing recalculates legacy row: 100 in ($0.00003) + 20 out ($0.00005) = 0.00008
317+
assert records[0].estimated_cost_usd == 0.00008
310318

311319
# Record a new invocation on the migrated DB
312320
record_invocation(

0 commit comments

Comments
 (0)