Files
ai-agent/backend/usage/calibrate.py
gabrielvidalandClaude Opus 5.5 acda5ecc30 refactor: retire core leftovers the plugins replaced
- frontend: drop the dead Conversations dashboard code (costAnalysis,
  DashboardFilters, ConversationsDashboard), the unused analytics /
  footprint / pricing helpers, the orphan api.ts comment and the dead
  mocks (perf dashboard, storage dashboard, telemetry hub/usage,
  usage daily/history/calibration); their French strings
- backend: drop look.parse_action (the conversation-labels plugin has its
  own) and UsersStore.emails() (no caller)
- routes: drop GET /api/usage/daily|history|calibration,
  GET /api/telemetry/usage, GET /api/goals, POST /api/goal-work — the
  plugin bridges call daily_usage, calibrate.history, views.usage,
  goals_list and goal_work directly; authz table + golden matrix updated;
  openapi.json re-dumped, src/generated regenerated
- FALLBACK_ACCOUNTS: one neutral Claude seat instead of a stale copy of
  the providers' profiles (the full list moves to mock/accounts.ts)
- notify CLI: no local PRICES estimate — the line is
  "Claude Code · 78k tokens · 8m" and the hub's restate_cost puts the
  run's exact list price in (an older CLI's $ line is still restated)
- CLAUDE.md / docs / docstrings: scheduled/, templates/, sidecar
  *_usage.py, the clarifier (now the plugin's agents[] + prefs),
  runs/extras.py, sidecar/routes_chrome.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 11:53:15 +01:00

435 lines
19 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Calibrate the plan meter: how many plan units (pricing.plan_units — what the
subscription's limits count) make 1 % of the 5h and week windows.
Inputs, both already hourly: the official % series (``usage_limits``: live
rate-limits.json points + the HA backfill) and every run's ``meterBins``
(epoch hour → [list $, plan units], from the parser). Per hour, the rise of a
window's % is the usage spent in it; hours that contain a reset, sit above
100 % (overage) or have no fresh reading on either side are dropped. The fit is
``Δ% = units / k + c`` by least squares — ``k`` = units per 1 %, ``c`` ≥ 0 the
usage the archive can't see (claude.ai, the desktop app, an unpaired machine).
A fit only replaces the current rate when it is trustworthy (enough hours, a
good R²), and a jump of more than ``SHIFT`` against the previous one pushes a
notification: that is what a model launch or a limits change looks like.
An account fits the windows its plan has: the windows its rate-limits.json
reports, recorded per plan segment (plans.py) — the work seat a 5h and a week
window, the personal Max a week only since 2026-10-31, the opencode ChatGPT
seat a week only (its plan units are plain list $, ``pricing.plan_units``, so
its rate *is* the list price of 1 % of its week); ``accounts.plan_windows``
before any plan is recorded.
**Per plan.** Each plan segment (a tier, a set of windows — plans.py) is
fitted on its own hours only, so the rate of a new tier is measured
independently of the old one. Until it has a trustworthy fit of its own, a
segment runs on its **seed**: the last trusted fit of the segment before it
(``carried``), scaled by the tiers' multipliers when the tier changed
(``scaled``: Max 5× → Max 20× = ×4), else the account's ``DEFAULTS``.
"""
from __future__ import annotations
import datetime as dt
import re
import threading
import time
import accounts as accounts_mod
from . import plans
HOUR = 3600
# Seed rates (2026-10-12 fit, docs/usage-calibration.md): window → (plan units
# per 1 %, list $ per 1 %), measured on ``tier``. Used until the first
# trustworthy fit lands (scaled when the account is on another tier).
DEFAULTS = {
"personal": {"tier": "default_claude_max_20x", "week": (45.3, 22.2), "h5": (11.5, 5.6)},
"work": {"tier": "default_claude_max_5x", "week": (22.3, 11.5), "h5": (3.5, 1.9)},
# A guess until the first fit: ≈ $500 of list-price GPT work a week.
"chatgpt-work": {"week": (5.0, 5.0)},
# A guess until the first fit (Google publishes no numbers): ≈ $100 of
# list-price Gemini work a week, $25 per 5 hours, on AI Pro.
"google-personal": {"week": (1.0, 1.0), "h5": (0.25, 0.25)},
}
WINDOWS = plans.WINDOWS
def windows(account: str, plan: dict | None = None) -> dict[str, str]:
"""The fit names → usage_limits window keys an account's plan has: the
plan segment's (what its rate-limits.json reports), else the declared ones."""
names = (plan or {}).get("windows") or accounts_mod.plan_windows(account)
return {n: WINDOWS[n] for n in names if n in WINDOWS}
def _seed(account: str) -> dict:
return DEFAULTS.get(account) or DEFAULTS["personal"]
FIT_DAYS = 14
MIN_N = 24 # hours with spend needed for a fit to count
MIN_R2 = 0.5 # a fit below this never replaces the current rate
SHIFT = 0.2 # |new/old - 1| above this (on the week) = a rate shift
FRESH_S = 2 * HOUR # a level reading older than this at an hour's end = unknown
_meter_cache: dict = {}
_meter_lock = threading.Lock()
def meters(deps, account: str) -> dict[int, list[float]]:
"""``{epoch hour: [list $, plan units]}`` summed over every run of
``account`` (subagents included; a session resumed into several files
counted once), plus the hub's own side calls (``side_calls``: Haiku
titles, which leave no transcript). Memoized on the store/meta/ledger
versions."""
from conversations.cards import _summaries_with_account
key = (deps.store.summaries_version, deps.meta_store.version,
deps.usage_store.side_version, account)
with _meter_lock:
hit = _meter_cache.get(account)
if hit and hit[0] == key:
return hit[1]
best: dict[str, tuple] = {}
rows = []
for path, s, a in _summaries_with_account(deps):
if a != account:
continue
sid = s.get("sessionId")
if s.get("isSidechain") or not sid:
rows.append(s)
continue
rank = (s.get("endedAt") or "", s.get("messages") or 0, path)
if sid not in best or rank > best[sid][0]:
best[sid] = (rank, s)
rows += [s for _, s in best.values()]
out: dict[int, list[float]] = {}
bins = [s.get("meterBins") or {} for s in rows]
bins.append(deps.usage_store.side_call_bins(account))
for mb in bins:
for h, v in mb.items():
b = out.setdefault(int(h), [0.0, 0.0])
b[0] += v[0]
b[1] += v[1]
with _meter_lock:
_meter_cache[account] = (key, out)
return out
def hourly_increments(points: list[tuple], h0: int, h1: int) -> dict[int, float]:
"""``{hour: Δ%}`` for every hour in [h0, h1) whose rise is measurable.
``points`` are (t, pct, resets_at) sorted by t. The level at an hour's end
is the last reading before it; the hour counts when both its end and its
start have a reading fresher than ``FRESH_S``, the window did not reset in
between (``resets_at`` moved or the level dropped) and the level is ≤ 100."""
out: dict[int, float] = {}
if not points:
return out
i = 0
prev = None # (t, pct, resets_at) at the previous hour's end
for h in range(h0, h1 + 1):
end = (h + 1) * HOUR
while i < len(points) and points[i][0] < end:
i += 1
cur = points[i - 1] if i else None
if cur is not None and end - cur[0] > FRESH_S:
cur = None
if cur is not None and prev is not None and h < h1:
reset = (cur[1] < prev[1] - 0.5
or (cur[2] and prev[2] and abs(cur[2] - prev[2]) > 120))
if not reset and cur[1] <= 100:
out[h] = cur[1] - prev[1]
prev = cur
return out
def _lsq(xs: list[float], ys: list[float]) -> tuple[float, float, float] | None:
"""y = a·x + c, c ≥ 0 → (a, c, R²); None when x carries no signal."""
n = len(xs)
if n < 3:
return None
mx, my = sum(xs) / n, sum(ys) / n
sxx = sum((x - mx) ** 2 for x in xs)
if sxx <= 0:
return None
a = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sxx
c = my - a * mx
if c < 0: # no negative "untracked" usage: refit through the origin
sx2 = sum(x * x for x in xs)
a, c = sum(x * y for x, y in zip(xs, ys)) / sx2, 0.0
if a <= 0:
return None
ss = sum((y - my) ** 2 for y in ys)
res = sum((y - a * x - c) ** 2 for x, y in zip(xs, ys))
return a, c, (1 - res / ss) if ss > 0 else 0.0
def fit(deps, account: str, end: float | None = None, days: int = FIT_DAYS) -> dict | None:
"""One calibration over the ``days`` before ``end`` — never before the
start of the plan segment in force at ``end`` — or None when a window has
too little signal. Not stored — see ``run``."""
end = end or time.time()
h1 = int(end // HOUR)
h0 = h1 - days * 24
seg = plans.at(deps.usage_store, account, end)
if seg and seg["since"] > h0 * HOUR:
h0 = -int(-seg["since"] // HOUR) # the first whole hour of the segment
m = meters(deps, account)
series = deps.usage_store.series(account, h0 * HOUR - FRESH_S, end)
cal = {"account": account, "fittedAt": end, "days": days, "source": "fit",
"plan": plans.public(seg)}
for name, win in windows(account, seg).items():
inc = hourly_increments(series.get(win, []), h0, h1)
xs, ys, cost = [], [], 0.0
for h, d in inc.items():
c, u = m.get(h, (0.0, 0.0))
xs.append(u)
ys.append(d)
cost += c
units = sum(xs)
r = _lsq(xs, ys)
busy = sum(1 for x in xs if x > 0)
if r is None or busy < MIN_N:
return None
a, c, r2 = r
k = 1 / a
cal[name] = {"unitsPerPct": k, "usdPerPct": k * cost / units if units else None,
"r2": r2, "n": busy, "interceptPct": c}
cal["trusted"] = _trusted(cal, seed_for(deps, account, seg))
return cal
def default_calibration(account: str) -> dict:
d = _seed(account)
return {"account": account, "fittedAt": 0.0, "days": 0, "source": "default",
"trusted": True,
**{w: {"unitsPerPct": d[w][0], "usdPerPct": d[w][1], "r2": None, "n": 0,
"interceptPct": None} for w in windows(account) if w in d}}
def segment_of(deps, account: str, cal: dict) -> float | None:
"""The ``since`` of the plan segment a fit measured: its stamp, else (a fit
from before plans were tracked) the segment its data window began in."""
p = cal.get("plan")
if p and p.get("since") is not None:
return p["since"]
seg = plans.at(deps.usage_store, account,
(cal.get("fittedAt") or 0) - (cal.get("days") or 0) * 86400)
return seg["since"] if seg else None
def seed_for(deps, account: str, seg: dict | None) -> dict:
"""The rate a plan segment starts from before its own first trusted fit:
the last trusted fit of an earlier segment (``carried``), else the
account's DEFAULTS (``default``) — scaled by the tiers' multipliers when the
tier differs (``scaled``)."""
if seg is None:
return default_calibration(account)
d = _seed(account)
base = {w: d[w] for w in WINDOWS if w in d}
base_tier, src, based_on = d.get("tier"), "default", None
prev = next((c for c in reversed(deps.usage_store.calibrations(account))
if c.get("source") == "fit" and c.get("trusted")
and (segment_of(deps, account, c) or 0) < seg["since"]), None)
if prev:
for w in WINDOWS:
if prev.get(w):
base[w] = (prev[w]["unitsPerPct"], prev[w].get("usdPerPct"))
prev_seg = plans.at(deps.usage_store, account, segment_of(deps, account, prev) or 0)
base_tier = (prev.get("plan") or {}).get("tier") or (prev_seg or {}).get("tier")
src, based_on = "carried", prev["fittedAt"]
k = plans.ratio(base_tier, seg.get("tier")) if base_tier else 1.0
if abs(k - 1) > 1e-9:
src = "scaled"
cal = {"account": account, "fittedAt": based_on or 0.0, "days": 0, "source": src,
"trusted": True, "scale": k, "basedOn": based_on, "plan": plans.public(seg)}
for w in windows(account, seg):
if w in base:
units, usd = base[w]
cal[w] = {"unitsPerPct": units * k, "usdPerPct": usd * k if usd else None,
"r2": None, "n": 0, "interceptPct": None}
return cal
# A fit more than this far off the seed is implausible however good its R²:
# usage the archive can't see that happens in the *same* hours as archived work
# (Sep 2026: Orus work on the personal seat from an unpaired Mac) fits cleanly
# at a rate 10× off. A real rate change (a model launch) is tens of percent.
PLAUSIBLE = 3.0
def _trusted(cal: dict, seed: dict | None = None) -> bool:
"""Enough hours, a good R², and within ×``PLAUSIBLE`` of ``seed`` (the
plan segment's; unset — the account's default)."""
seed = seed or default_calibration(cal["account"])
return all(w in cal and (cal[w].get("r2") or 0) >= MIN_R2 and cal[w].get("n", 0) >= MIN_N
and 1 / PLAUSIBLE <= cal[w]["unitsPerPct"] / seed[w]["unitsPerPct"] <= PLAUSIBLE
for w in windows(cal["account"], cal.get("plan")) if seed.get(w))
_current_cache: dict = {}
def current(deps, account: str) -> dict:
"""The rate in force: the latest trustworthy fit of the current plan
segment, else that segment's seed."""
key = deps.usage_store.version
hit = _current_cache.get(account)
if hit and hit[0] == key:
return hit[1]
seg = plans.current(deps.usage_store, account)
seed = seed_for(deps, account, seg)
cal = next((c for c in reversed(deps.usage_store.calibrations(account))
if c.get("source") == "fit"
and (seg is None or segment_of(deps, account, c) == seg["since"])
and _trusted(c, seed)), None)
if cal is not None and seg is not None and not cal.get("plan"):
cal = {**cal, "plan": plans.public(seg)}
cal = cal or seed
_current_cache[account] = (key, cal)
return cal
def plan_pct(deps, account: str, units: float | None) -> dict | None:
if units is None:
return None
cal = current(deps, account)
out = {w: (units / cal[w]["unitsPerPct"] if cal.get(w) else None) for w in WINDOWS}
return {**out, "account": account, "calibratedAt": cal["fittedAt"] or None}
def run(deps, account: str, notify=None) -> tuple[dict | None, bool]:
"""Fit now, store it, and report whether the week rate shifted."""
before = current(deps, account)
cal = fit(deps, account)
if cal is None:
return None, False
deps.usage_store.add_calibration(cal)
shifted = False
# A new plan segment is news of its own (service.plan_changed): only a
# move within one segment is a rate shift.
if (cal["trusted"] and before.get("source") == "fit"
and segment_of(deps, account, before) == segment_of(deps, account, cal)):
old, new = before["week"]["unitsPerPct"], cal["week"]["unitsPerPct"]
shifted = abs(new / old - 1) > SHIFT
if shifted and notify:
day = dt.datetime.fromtimestamp(before["fittedAt"]).strftime("%b %d")
notify(account, f"1 % of the {account} week was {old:.1f} plan units "
f"(fit of {day}), now {new:.1f} "
f"(≈ ${cal['week']['usdPerPct'] or 0:.1f} list) — limits or "
f"metering changed (a model launch?).")
return cal, shifted
def backfill(deps, account: str, step_days: int = 7) -> int:
"""Weekly fits over the whole recorded history (``$/% over time``)."""
first = deps.usage_store.first_t(account)
if not first:
return 0
n = 0
end = (first // 86400 + FIT_DAYS) * 86400
now = time.time()
while end < now:
cal = fit(deps, account, end=end)
if cal:
deps.usage_store.add_calibration(cal)
n += 1
end += step_days * 86400
return n
def history(deps, account: str, days: int) -> dict:
"""What the Plan usage panel draws: the raw % series, hourly meters with
the measurable rises, and per-day observed / predicted / untracked %."""
now = time.time()
h1 = int(now // HOUR)
h0 = h1 - days * 24
cal = current(deps, account)
m = meters(deps, account)
series = deps.usage_store.series(account, h0 * HOUR - FRESH_S)
inc = {n: hourly_increments(series.get(w, []), h0, h1)
for n, w in WINDOWS.items() if w in series}
hourly, daily = [], {}
for h in range(h0, h1 + 1):
c, u = m.get(h, (0.0, 0.0))
dw, d5 = inc.get("week", {}).get(h), inc.get("h5", {}).get(h)
if c or u or dw or d5:
hourly.append({"t": h * HOUR, "cost": c, "units": u, "dWeek": dw, "d5h": d5})
day = dt.datetime.fromtimestamp(h * HOUR).strftime("%Y-%m-%d")
e = daily.setdefault(day, {"day": day, "cost": 0.0, "units": 0.0,
"observedWeek": 0.0, "predictedWeek": 0.0,
"observed5h": 0.0, "predicted5h": 0.0})
e["cost"] += c
e["units"] += u
if dw is not None and cal.get("week"):
e["observedWeek"] += dw
e["predictedWeek"] += u / cal["week"]["unitsPerPct"]
if d5 is not None and cal.get("h5"):
e["observed5h"] += d5
e["predicted5h"] += u / cal["h5"]["unitsPerPct"]
for e in daily.values():
e["untrackedWeek"] = max(0.0, e["observedWeek"] - e["predictedWeek"])
return {"account": account, "days": days,
"series": {w: [{"t": t, "pct": p, "resetsAt": r} for t, p, r in pts]
for w, pts in series.items()},
"hourly": hourly, "daily": list(daily.values()), "calibration": cal,
"plans": [p for p in plans.history(deps.usage_store, account)
if p["until"] is None or p["until"] >= h0 * HOUR]}
def session_totals(deps, sid: str) -> tuple[float, float, str] | None:
"""(list $, plan units, account) of one session — its main transcript
(the newest copy, if resumed into several files) plus every subagent."""
from conversations.cards import _summaries_with_account
best, cost, units, acct = None, 0.0, 0.0, None
for path, s, a in _summaries_with_account(deps):
if s.get("sessionId") != sid:
continue
acct = acct or a
if s.get("isSidechain"):
cost += s.get("cost") or 0.0
units += s.get("planUnits") or 0.0
continue
rank = (s.get("endedAt") or "", s.get("messages") or 0, path)
if best is None or rank > best[0]:
best = (rank, s)
if best is None:
return None
cost += best[1].get("cost") or 0.0
units += best[1].get("planUnits") or 0.0
return cost, units, acct or "personal"
# The notify CLI appends ``Claude Code · 78k tokens · 8m 38s`` to a push —
# no price: the hub owns pricing, so it puts the run's exact list price
# (subagents included) in, after the harness. An older CLI's line carries its
# own estimate (``Claude Code · $1.57 · 78k tokens · 8m 38s``, main transcript
# only, flat rates): that figure is restated — one cost per push, never two
# that disagree.
_CLI_COST_RE = re.compile(r"^(?P<head>[^\n·$]+ · )\$[\d,]+(?:\.\d+)?(?P<rest>(?: · [^\n]*)?)$",
re.M)
_CLI_TOKENS_RE = re.compile(r"^(?P<head>(?:Claude Code|OpenCode) · )"
r"(?P<rest>[\d.]+[kM]? tokens(?: · [^\n]*)?)$", re.M)
def restate_cost(deps, sid: str, message: str, final: bool) -> str:
"""``message`` with the CLI's cost line re-priced by the backend, and —
on a ``--final`` push — how much of the plan's week the run used:
``Claude Code · $35.46 · ≈1.5% wk · 76.3M tokens · 2h 3m``."""
tot = session_totals(deps, sid) if sid else None
if not tot or tot[0] <= 0:
return message
cost, units, acct = tot
wk = ""
if final:
pct = (plan_pct(deps, acct, units) or {}).get("week") or 0.0
if pct >= 0.05:
wk = f" · ≈{pct:.1f}% wk"
m = _CLI_COST_RE.search(message or "")
if m:
return (message[:m.start()] + f"{m.group('head')}${cost:.2f}{wk}{m.group('rest')}"
+ message[m.end():])
m = _CLI_TOKENS_RE.search(message or "")
if m:
return (message[:m.start()] + f"{m.group('head')}${cost:.2f}{wk} · {m.group('rest')}"
+ message[m.end():])
return (message or "") + (f"\n${cost:.2f}{wk}" if final else "")