199 lines
8.9 KiB
Python
199 lines
8.9 KiB
Python
"""SQLite tables for plan usage: every observed /usage % point, every
|
|
calibration fit, the plan each account was on (plans.py), and the side-call
|
|
ledger. Shares ai-agent.db with the main
|
|
Store (own connection; WAL lets both write).
|
|
|
|
**Side calls** are the one-shot ``claude -p --no-session-persistence`` asks
|
|
the hub makes for itself (naming a scheduled conversation, a subagent's short
|
|
title — sidecar ``/title``). They leave no transcript, so the parser never
|
|
prices them: each one is booked here instead, priced with the same book
|
|
(``pricing.usage_cost`` / ``plan_units``), and ``calibrate.meters`` adds them
|
|
to the account's plan meter like any run's ``meterBins``."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
|
|
_SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS usage_limits (
|
|
account TEXT NOT NULL,
|
|
window TEXT NOT NULL, -- five_hour | seven_day | seven_day_<model>
|
|
t REAL NOT NULL, -- epoch secs the % was observed
|
|
pct REAL NOT NULL,
|
|
resets_at REAL, -- when that window frees up (a change = a reset)
|
|
source TEXT NOT NULL DEFAULT 'live', -- live | ha (backfill)
|
|
PRIMARY KEY (account, window, t)
|
|
);
|
|
CREATE TABLE IF NOT EXISTS usage_calibration (
|
|
account TEXT NOT NULL,
|
|
fitted_at REAL NOT NULL, -- end of the fitted window
|
|
data_json TEXT NOT NULL, -- the Calibration dict
|
|
PRIMARY KEY (account, fitted_at)
|
|
);
|
|
CREATE TABLE IF NOT EXISTS side_calls (
|
|
t REAL NOT NULL, -- epoch secs
|
|
kind TEXT NOT NULL, -- scheduled-title | short-title
|
|
ref TEXT, -- what it was for (a conversation id…)
|
|
account TEXT NOT NULL,
|
|
model TEXT,
|
|
cost REAL NOT NULL, -- list $
|
|
units REAL NOT NULL, -- plan units
|
|
usage_json TEXT
|
|
);
|
|
CREATE INDEX IF NOT EXISTS side_calls_account ON side_calls (account, t);
|
|
CREATE TABLE IF NOT EXISTS usage_plans (
|
|
account TEXT NOT NULL,
|
|
since REAL NOT NULL, -- epoch the plan was first seen (plans.py)
|
|
tier TEXT, -- the login's rate-limit tier; NULL = unknown
|
|
windows TEXT NOT NULL, -- JSON fit names it enforces: ["week", "h5"]
|
|
source TEXT NOT NULL, -- detected | assumed (the backfilled past) | manual
|
|
data_json TEXT, -- the login's plan info, why it changed
|
|
PRIMARY KEY (account, since)
|
|
);
|
|
"""
|
|
|
|
|
|
class UsageStore:
|
|
def __init__(self, path: str):
|
|
self._lock = threading.Lock()
|
|
self._db = sqlite3.connect(path, check_same_thread=False)
|
|
self._db.execute("PRAGMA journal_mode=WAL")
|
|
self._db.execute("PRAGMA synchronous=NORMAL")
|
|
self._db.execute("PRAGMA busy_timeout=5000")
|
|
self._db.execute("PRAGMA journal_size_limit=16777216")
|
|
self._db.executescript(_SCHEMA)
|
|
self.version = 0 # bumped on every write; memo keys read it
|
|
self.side_version = 0 # the side-call ledger's own (meters key on it)
|
|
self._plans: dict[str, list[dict]] = {}
|
|
|
|
def add_points(self, rows: list[tuple]) -> int:
|
|
"""rows = (account, window, t, pct, resets_at, source); duplicates ignored."""
|
|
if not rows:
|
|
return 0
|
|
with self._lock:
|
|
cur = self._db.executemany(
|
|
"INSERT OR IGNORE INTO usage_limits VALUES (?,?,?,?,?,?)", rows)
|
|
self._db.commit()
|
|
n = cur.rowcount
|
|
if n:
|
|
self.version += 1
|
|
return n
|
|
|
|
def last_point(self, account: str, window: str) -> tuple | None:
|
|
with self._lock:
|
|
return self._db.execute(
|
|
"SELECT t, pct, resets_at FROM usage_limits WHERE account=? AND window=?"
|
|
" ORDER BY t DESC LIMIT 1", (account, window)).fetchone()
|
|
|
|
def series(self, account: str, since: float, until: float | None = None
|
|
) -> dict[str, list[tuple[float, float, float | None]]]:
|
|
q = ("SELECT window, t, pct, resets_at FROM usage_limits WHERE account=?"
|
|
" AND t>=?" + (" AND t<=?" if until else "") + " ORDER BY t")
|
|
args = (account, since, until) if until else (account, since)
|
|
out: dict[str, list] = {}
|
|
with self._lock:
|
|
rows = self._db.execute(q, args).fetchall()
|
|
for w, t, p, r in rows:
|
|
out.setdefault(w, []).append((t, p, r))
|
|
return out
|
|
|
|
def first_t(self, account: str) -> float | None:
|
|
with self._lock:
|
|
row = self._db.execute("SELECT MIN(t) FROM usage_limits WHERE account=?",
|
|
(account,)).fetchone()
|
|
return row[0] if row else None
|
|
|
|
def window_spans(self, account: str) -> dict[str, tuple[float, float]]:
|
|
"""``{window: (first t, last t)}`` of an account's recorded points."""
|
|
with self._lock:
|
|
rows = self._db.execute(
|
|
"SELECT window, MIN(t), MAX(t) FROM usage_limits WHERE account=?"
|
|
" GROUP BY window", (account,)).fetchall()
|
|
return {w: (a, b) for w, a, b in rows}
|
|
|
|
def plans(self, account: str) -> list[dict]:
|
|
"""The account's plan segments, oldest first (memoized)."""
|
|
with self._lock:
|
|
hit = self._plans.get(account)
|
|
if hit is None:
|
|
rows = self._db.execute(
|
|
"SELECT since, tier, windows, source, data_json FROM usage_plans"
|
|
" WHERE account=? ORDER BY since", (account,)).fetchall()
|
|
hit = [{"account": account, "since": t, "tier": tier,
|
|
"windows": json.loads(w), "source": src,
|
|
"data": json.loads(d) if d else {}}
|
|
for t, tier, w, src, d in rows]
|
|
self._plans[account] = hit
|
|
return hit
|
|
|
|
def add_plan(self, seg: dict) -> None:
|
|
with self._lock:
|
|
self._db.execute(
|
|
"INSERT OR REPLACE INTO usage_plans VALUES (?,?,?,?,?,?)",
|
|
(seg["account"], seg["since"], seg.get("tier"), json.dumps(seg["windows"]),
|
|
seg.get("source") or "detected", json.dumps(seg.get("data") or {})))
|
|
self._db.commit()
|
|
self._plans.pop(seg["account"], None)
|
|
self.version += 1
|
|
|
|
def update_plan(self, account: str, since: float, tier: str | None,
|
|
data: dict | None) -> None:
|
|
"""Fill in a segment's tier (unknown when it began) in place; ``data``
|
|
is merged into what it holds (its ``reason`` stays)."""
|
|
with self._lock:
|
|
row = self._db.execute(
|
|
"SELECT data_json FROM usage_plans WHERE account=? AND since=?",
|
|
(account, since)).fetchone()
|
|
merged = {**(json.loads(row[0]) if row and row[0] else {}), **(data or {})}
|
|
self._db.execute(
|
|
"UPDATE usage_plans SET tier=?, data_json=? WHERE account=? AND since=?",
|
|
(tier, json.dumps(merged), account, since))
|
|
self._db.commit()
|
|
self._plans.pop(account, None)
|
|
self.version += 1
|
|
|
|
def delete_plan(self, account: str, since: float) -> int:
|
|
with self._lock:
|
|
n = self._db.execute("DELETE FROM usage_plans WHERE account=? AND since=?",
|
|
(account, since)).rowcount
|
|
self._db.commit()
|
|
self._plans.pop(account, None)
|
|
self.version += 1
|
|
return n
|
|
|
|
def add_calibration(self, cal: dict) -> None:
|
|
with self._lock:
|
|
self._db.execute("INSERT OR REPLACE INTO usage_calibration VALUES (?,?,?)",
|
|
(cal["account"], cal["fittedAt"], json.dumps(cal)))
|
|
self._db.commit()
|
|
self.version += 1
|
|
|
|
def calibrations(self, account: str) -> list[dict]:
|
|
with self._lock:
|
|
rows = self._db.execute(
|
|
"SELECT data_json FROM usage_calibration WHERE account=? ORDER BY fitted_at",
|
|
(account,)).fetchall()
|
|
return [json.loads(r[0]) for r in rows]
|
|
|
|
def add_side_call(self, kind: str, ref: str | None, account: str, model: str | None,
|
|
cost: float, units: float, usage: dict | None,
|
|
t: float | None = None) -> None:
|
|
with self._lock:
|
|
self._db.execute(
|
|
"INSERT INTO side_calls VALUES (?,?,?,?,?,?,?,?)",
|
|
(t if t is not None else time.time(), kind, ref, account, model,
|
|
cost, units, json.dumps(usage) if usage else None))
|
|
self._db.commit()
|
|
self.side_version += 1
|
|
|
|
def side_call_bins(self, account: str) -> dict[int, list[float]]:
|
|
"""``{epoch hour: [list $, plan units]}`` — ``meterBins``' shape."""
|
|
with self._lock:
|
|
rows = self._db.execute(
|
|
"SELECT CAST(t / 3600 AS INTEGER), SUM(cost), SUM(units) FROM side_calls"
|
|
" WHERE account=? GROUP BY 1", (account,)).fetchall()
|
|
return {h: [c or 0.0, u or 0.0] for h, c, u in rows}
|