| 1 | """Provider-reported charges for a scoped watchlist subprocess.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import math |
| 6 | import os |
| 7 | import sqlite3 |
| 8 | import sys |
| 9 | import threading |
| 10 | import time |
| 11 | import uuid |
| 12 | from contextlib import contextmanager |
| 13 | from contextvars import ContextVar |
| 14 | from pathlib import Path |
| 15 | from urllib.parse import urlsplit |
| 16 | |
| 17 | from . import log |
| 18 | |
| 19 | JOURNAL_ENV = "LAST30DAYS_USAGE_JOURNAL" |
| 20 | NONCE_ENV = "LAST30DAYS_USAGE_NONCE" |
| 21 | UNKNOWN_COST_MARKER = "[last30days:usage-cost-unknown]" |
| 22 | _JOURNAL_TIMEOUT_SECONDS = 5.0 |
| 23 | _BUSY_TIMEOUT_MS = 5_000 |
| 24 | _WRITE_LOCK = threading.Lock() |
| 25 | _STATE_LOCK = threading.Lock() |
| 26 | _BEGIN_FAILED_JOURNALS: set[str] = set() |
| 27 | _ACTIVE_DEADLINE: ContextVar[float | None] = ContextVar("last30days_usage_deadline", default=None) |
| 28 | |
| 29 | _PAID_HOSTS = { |
| 30 | "openrouter.ai": "openrouter", |
| 31 | "api.perplexity.ai": "perplexity", |
| 32 | "api.openai.com": "openai", |
| 33 | "api.x.ai": "xai", |
| 34 | "generativelanguage.googleapis.com": "gemini", |
| 35 | "api.scrapecreators.com": "scrapecreators", |
| 36 | "api.search.brave.com": "brave", |
| 37 | "api.tavily.com": "tavily", |
| 38 | "api.exa.ai": "exa", |
| 39 | "google.serper.dev": "serper", |
| 40 | "api.parallel.ai": "parallel", |
| 41 | "api.x.com": "x", |
| 42 | "api.twitter.com": "x", |
| 43 | "xquik.com": "xquik", |
| 44 | "api.groq.com": "groq", |
| 45 | "code.deepline.com": "deepline", |
| 46 | } |
| 47 | |
| 48 | |
| 49 | def _log_journal_error(operation: str, exc: sqlite3.Error) -> None: |
| 50 | log.source_log( |
| 51 | "Usage", |
| 52 | f"journal {operation} failed: {type(exc).__name__}: {exc}", |
| 53 | tty_only=False, |
| 54 | ) |
| 55 | |
| 56 | |
| 57 | def _journal_key(path: Path | str) -> str: |
| 58 | return os.path.abspath(os.fspath(path)) |
| 59 | |
| 60 | |
| 61 | def _unknown_sentinel_path(path: Path | str) -> Path: |
| 62 | return Path(f"{os.fspath(path)}.unknown") |
| 63 | |
| 64 | |
| 65 | @contextmanager |
| 66 | def with_deadline(deadline_monotonic: float | None): |
| 67 | """Bind a wall-clock deadline to usage journal waits in the current scope.""" |
| 68 | token = _ACTIVE_DEADLINE.set(deadline_monotonic) |
| 69 | try: |
| 70 | yield |
| 71 | finally: |
| 72 | _ACTIVE_DEADLINE.reset(token) |
| 73 | |
| 74 | |
| 75 | def _effective_deadline(deadline_monotonic: float | None) -> float | None: |
| 76 | return deadline_monotonic if deadline_monotonic is not None else _ACTIVE_DEADLINE.get() |
| 77 | |
| 78 | |
| 79 | def _remaining_budget(deadline_monotonic: float | None) -> float: |
| 80 | if deadline_monotonic is None: |
| 81 | return _JOURNAL_TIMEOUT_SECONDS |
| 82 | return min(_JOURNAL_TIMEOUT_SECONDS, max(0.0, deadline_monotonic - time.monotonic())) |
| 83 | |
| 84 | |
| 85 | def unknown_cost_marker(nonce: str | None = None) -> str: |
| 86 | token = os.environ.get(NONCE_ENV) if nonce is None else nonce |
| 87 | return f"{UNKNOWN_COST_MARKER}:{token}" if token else UNKNOWN_COST_MARKER |
| 88 | |
| 89 | |
| 90 | def _mark_begin_failed(path: Path | str) -> None: |
| 91 | """Record a fail-closed unknown-cost marker in-process, on disk, and on stderr.""" |
| 92 | key = _journal_key(path) |
| 93 | sentinel = _unknown_sentinel_path(path) |
| 94 | flags = os.O_CREAT | os.O_WRONLY | getattr(os, "O_NOFOLLOW", 0) |
| 95 | with _STATE_LOCK: |
| 96 | _BEGIN_FAILED_JOURNALS.add(key) |
| 97 | try: |
| 98 | fd = os.open(sentinel, flags, 0o600) |
| 99 | os.close(fd) |
| 100 | except OSError: |
| 101 | pass |
| 102 | try: |
| 103 | sys.stderr.write(f"{unknown_cost_marker()}\n") |
| 104 | sys.stderr.flush() |
| 105 | except OSError: |
| 106 | pass |
| 107 | |
| 108 | |
| 109 | def _has_begin_failed(path: Path | str) -> bool: |
| 110 | key = _journal_key(path) |
| 111 | with _STATE_LOCK: |
| 112 | if key in _BEGIN_FAILED_JOURNALS: |
| 113 | return True |
| 114 | try: |
| 115 | return os.path.lexists(_unknown_sentinel_path(path)) |
| 116 | except OSError: |
| 117 | return False |
| 118 | |
| 119 | |
| 120 | @contextmanager |
| 121 | def _connection(path, *, write: bool = False, deadline_monotonic: float | None = None): |
| 122 | deadline = _effective_deadline(deadline_monotonic) |
| 123 | if deadline is not None and deadline - time.monotonic() <= 0: |
| 124 | raise sqlite3.OperationalError("usage journal deadline exceeded") |
| 125 | acquired = False |
| 126 | if write: |
| 127 | lock_timeout = _remaining_budget(deadline) |
| 128 | acquired = _WRITE_LOCK.acquire(timeout=lock_timeout) |
| 129 | if not acquired: |
| 130 | raise sqlite3.OperationalError("usage journal lock wait timed out") |
| 131 | try: |
| 132 | sql_timeout = _remaining_budget(deadline) |
| 133 | if deadline is not None and sql_timeout <= 0: |
| 134 | raise sqlite3.OperationalError("usage journal deadline exceeded") |
| 135 | busy_ms = max(0, int(sql_timeout * 1000)) |
| 136 | conn = sqlite3.connect( |
| 137 | path, |
| 138 | timeout=sql_timeout, |
| 139 | isolation_level=None, |
| 140 | ) |
| 141 | try: |
| 142 | conn.execute(f"PRAGMA busy_timeout={busy_ms}") |
| 143 | if write: |
| 144 | conn.execute("BEGIN IMMEDIATE") |
| 145 | try: |
| 146 | yield conn |
| 147 | except BaseException: |
| 148 | if write and conn.in_transaction: |
| 149 | try: |
| 150 | conn.execute("ROLLBACK") |
| 151 | except sqlite3.Error: |
| 152 | pass |
| 153 | raise |
| 154 | else: |
| 155 | if write and conn.in_transaction: |
| 156 | conn.execute("COMMIT") |
| 157 | finally: |
| 158 | conn.close() |
| 159 | finally: |
| 160 | if acquired: |
| 161 | _WRITE_LOCK.release() |
| 162 | |
| 163 | |
| 164 | def create_journal(path: Path) -> None: |
| 165 | fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) |
| 166 | os.close(fd) |
| 167 | acquired = _WRITE_LOCK.acquire(timeout=_JOURNAL_TIMEOUT_SECONDS) |
| 168 | if not acquired: |
| 169 | raise sqlite3.OperationalError("usage journal lock wait timed out") |
| 170 | try: |
| 171 | with _STATE_LOCK: |
| 172 | _BEGIN_FAILED_JOURNALS.discard(_journal_key(path)) |
| 173 | try: |
| 174 | _unknown_sentinel_path(path).unlink(missing_ok=True) |
| 175 | except OSError: |
| 176 | pass |
| 177 | conn = sqlite3.connect( |
| 178 | path, |
| 179 | timeout=_JOURNAL_TIMEOUT_SECONDS, |
| 180 | isolation_level=None, |
| 181 | ) |
| 182 | try: |
| 183 | conn.execute(f"PRAGMA busy_timeout={_BUSY_TIMEOUT_MS}") |
| 184 | try: |
| 185 | conn.execute("PRAGMA journal_mode=WAL") |
| 186 | except sqlite3.Error: |
| 187 | pass |
| 188 | conn.execute("BEGIN IMMEDIATE") |
| 189 | try: |
| 190 | conn.execute( |
| 191 | "CREATE TABLE attempts (id TEXT PRIMARY KEY, provider TEXT NOT NULL, " |
| 192 | "cost REAL, unknown INTEGER NOT NULL DEFAULT 1, " |
| 193 | "prompt_tokens INTEGER DEFAULT 0, completion_tokens INTEGER DEFAULT 0)" |
| 194 | ) |
| 195 | conn.execute("COMMIT") |
| 196 | except BaseException: |
| 197 | if conn.in_transaction: |
| 198 | try: |
| 199 | conn.execute("ROLLBACK") |
| 200 | except sqlite3.Error: |
| 201 | pass |
| 202 | raise |
| 203 | finally: |
| 204 | conn.close() |
| 205 | finally: |
| 206 | _WRITE_LOCK.release() |
| 207 | |
| 208 | |
| 209 | def begin( |
| 210 | provider: str, |
| 211 | *, |
| 212 | deadline_monotonic: float | None = None, |
| 213 | ) -> tuple[str, str, str] | None: |
| 214 | path = os.environ.get(JOURNAL_ENV) |
| 215 | if not path: |
| 216 | return None |
| 217 | attempt_id = uuid.uuid4().hex |
| 218 | try: |
| 219 | with _connection(path, write=True, deadline_monotonic=deadline_monotonic) as conn: |
| 220 | conn.execute("INSERT INTO attempts (id, provider) VALUES (?, ?)", (attempt_id, provider)) |
| 221 | except sqlite3.Error as exc: |
| 222 | _log_journal_error("begin", exc) |
| 223 | _mark_begin_failed(path) |
| 224 | return None |
| 225 | return path, attempt_id, provider |
| 226 | |
| 227 | |
| 228 | def begin_http( |
| 229 | url: str, |
| 230 | method: str, |
| 231 | *, |
| 232 | deadline_monotonic: float | None = None, |
| 233 | ) -> tuple[str, str, str] | None: |
| 234 | if not os.environ.get(JOURNAL_ENV): |
| 235 | return None |
| 236 | parts = urlsplit(url) |
| 237 | provider = _PAID_HOSTS.get(parts.hostname) |
| 238 | if provider == "perplexity" and method == "GET": |
| 239 | return None # Retrieving an existing background operation does not start another charge. |
| 240 | if provider is None: |
| 241 | for name in ("OPENAI", "XAI", "OPENROUTER", "SCRAPECREATORS"): |
| 242 | override = os.environ.get(f"{name}_BASE_URL") |
| 243 | if override and urlsplit(override).netloc == parts.netloc: |
| 244 | provider = name.lower() |
| 245 | break |
| 246 | if not provider: |
| 247 | return None |
| 248 | if deadline_monotonic is None: |
| 249 | return begin(provider) |
| 250 | return begin(provider, deadline_monotonic=deadline_monotonic) |
| 251 | |
| 252 | |
| 253 | def cancel( |
| 254 | attempt: tuple[str, str, str] | None, |
| 255 | *, |
| 256 | deadline_monotonic: float | None = None, |
| 257 | ) -> None: |
| 258 | """Remove an attempt when the transport provably never started.""" |
| 259 | if attempt is not None: |
| 260 | path, attempt_id, _ = attempt |
| 261 | try: |
| 262 | with _connection(path, write=True, deadline_monotonic=deadline_monotonic) as conn: |
| 263 | conn.execute("DELETE FROM attempts WHERE id = ?", (attempt_id,)) |
| 264 | except sqlite3.Error as exc: |
| 265 | _log_journal_error("cancel", exc) |
| 266 | |
| 267 | |
| 268 | def finish( |
| 269 | attempt: tuple[str, str, str] | None, |
| 270 | payload: object, |
| 271 | *, |
| 272 | deadline_monotonic: float | None = None, |
| 273 | ) -> None: |
| 274 | if attempt is None or not isinstance(payload, dict): |
| 275 | return |
| 276 | path, attempt_id, provider = attempt |
| 277 | usage = payload.get("usage") |
| 278 | if not isinstance(usage, dict): |
| 279 | return |
| 280 | cost = usage.get("cost") |
| 281 | if provider == "perplexity": |
| 282 | if not isinstance(cost, dict) or cost.get("currency") != "USD": |
| 283 | return |
| 284 | cost = cost.get("total_cost") |
| 285 | elif provider != "openrouter": |
| 286 | return |
| 287 | if isinstance(cost, bool) or not isinstance(cost, (int, float)) or not math.isfinite(cost) or cost < 0: |
| 288 | return |
| 289 | # A background response may expose a running subtotal rather than its final bill. |
| 290 | unknown = int(payload.get("status") in {"queued", "in_progress"}) |
| 291 | prompt = usage.get("prompt_tokens", usage.get("input_tokens", 0)) |
| 292 | completion = usage.get("completion_tokens", usage.get("output_tokens", 0)) |
| 293 | prompt = prompt if type(prompt) is int and prompt >= 0 else 0 |
| 294 | completion = completion if type(completion) is int and completion >= 0 else 0 |
| 295 | try: |
| 296 | with _connection(path, write=True, deadline_monotonic=deadline_monotonic) as conn: |
| 297 | conn.execute( |
| 298 | "UPDATE attempts SET cost = ?, unknown = ?, prompt_tokens = ?, completion_tokens = ? WHERE id = ?", |
| 299 | (cost, unknown, prompt, completion, attempt_id), |
| 300 | ) |
| 301 | except sqlite3.Error as exc: |
| 302 | _log_journal_error("finish", exc) |
| 303 | |
| 304 | |
| 305 | def read_journal(path: Path) -> dict: |
| 306 | unknown_from_begin = _has_begin_failed(path) |
| 307 | try: |
| 308 | with _connection(path, write=False) as conn: |
| 309 | row = conn.execute( |
| 310 | "SELECT COALESCE(SUM(cost), 0), COALESCE(SUM(unknown), 0), " |
| 311 | "COALESCE(SUM(prompt_tokens), 0), COALESCE(SUM(completion_tokens), 0) FROM attempts" |
| 312 | ).fetchone() |
| 313 | except sqlite3.Error: |
| 314 | return {"token_cost": 0.0, "cost_unknown": 1, "prompt_tokens": 0, "completion_tokens": 0} |
| 315 | return { |
| 316 | "token_cost": row[0], |
| 317 | "cost_unknown": int(row[1] > 0 or unknown_from_begin), |
| 318 | "prompt_tokens": row[2], |
| 319 | "completion_tokens": row[3], |
| 320 | } |
| 321 |