"""Usage summary: what the provider calls used, totalled by day, profile and model. Catches: a call whose counts never reach the hourly totals, a failed attempt counted as tokens or not counted at all, a total that shrinks when a session is deleted (the request rows go with it). None of this is visible from one session's request records. The backfill of a store from before the totals is checked on a reference daemon's store in apps/albedo/test/albedo/storage/reference_store_test.gleam. The query half catches a window or selector the route accepts out of range, and a value that a percent-decoded query turns into a different value (a `+` arriving as a space). What a summary counts from the hourly totals (client days, future hours, filters, scopes, the cuts) is compared with a model in apps/albedo/test/albedo/usage/usage_hours_test.gleam. """ import contextlib import json import sqlite3 import time import unittest import urllib.error import urllib.parse from datetime import datetime from harness import Albedo, Provider, Reply, exclusive, latest_user, text, wait_until FIRST = { "input_tokens": 100, "output_tokens": 20, "input_tokens_details": {"cached_tokens": 40}, "output_tokens_details": {"reasoning_tokens": 7}, } SECOND = { "input_tokens": 300, "output_tokens": 40, "input_tokens_details": {"cached_tokens": 120}, "output_tokens_details": {"reasoning_tokens": 3}, } DAY_MS = 86_400_000 ANTHROPIC = "anthropic:https://api.anthropic.com" OPENAI = "responses:https://api.openai.com/v1" GEMINI = "gemini:https://generativelanguage.googleapis.com" def encode(parameters): """A query the daemon reads back unchanged: `+` is a space to its query decoder, so a literal plus travels as `%2B`, never as a form-encoded `+`.""" return "?" + urllib.parse.urlencode(parameters, quote_via=urllib.parse.quote) def reply(request): user = latest_user(request) # A non-retryable error isolates one failed attempt. Upstream now treats # 429 as account rotation/backoff, not an immediate terminal response. if user == "fail this request": return Reply("error", "invalid request", status=400) return text("done", usage=SECOND if user == "second" else FIRST) def instant(timestamp): return datetime.fromisoformat(timestamp.replace("Z", "+00:00")) def millis(timestamp): return int(instant(timestamp).timestamp() * 1000) # exclusive: it reads totals across the whole daemon @exclusive class UsageSummaryTests(unittest.TestCase): def setUp(self): self.provider = Provider(reply) self.addCleanup(self.provider.close) self.app = Albedo(self.provider, protocol="responses") self.app.__enter__() self.addCleanup(self.app.__exit__, None, None, None) def usage(self, query=""): with self.app.api(f"/usage{query}") as response: return json.load(response) def run_prompts(self, *prompts): sessions = [] for prompt in prompts: session = self.app.session(name="usage fixture") self.app.prompt(session, prompt).close() self.app.idle(session) sessions.append(session) return sessions def delete_session(self, session): resource = f"/sessions/{session}/configuration" with self.app.api(resource) as response: validator = response.getheader("ETag") response.read() with self.app.api( resource.removesuffix("/configuration"), method="DELETE", headers={"If-Match": validator}, ) as response: self.assertEqual(json.load(response)["state"], "complete") def seed(self, *rows, hour=None): """Writes one hour of call totals, each row being `(provider, account, model, calls, input_tokens, output_tokens)`. The route reads these totals, never the request rows, and only a provider with an account pool labels a call with an account, which a fixture would need real credentials for. `account` is `""` for a provider without one, which is how the trigger stores it. The hour is the current one unless `hour` says otherwise, so every window covers it. """ if hour is None: hour = int(time.time() * 1000) // 3_600_000 * 3_600_000 with contextlib.closing(sqlite3.connect(self.app.home / "albedo.sqlite")) as db: db.execute("PRAGMA busy_timeout=5000") db.executemany( "INSERT OR REPLACE INTO usage_hours(hour_ms,profile,provider,account," "model,kind,calls,errors,input_tokens,cached_input_tokens," "cache_creation_tokens,output_tokens,reasoning_tokens)" " VALUES(?,'fixture',?,?,?,'turn',?,0,?,0,0,?,0)", [ (hour, provider, account, model, calls, input_tokens, output_tokens) for provider, account, model, calls, input_tokens, output_tokens in rows ], ) db.commit() def totals(self, summary): (line,) = summary["lines"] return { key: line[key] for key in ( "calls", "errors", "input_tokens", "cached_input_tokens", "cache_creation_tokens", "output_tokens", "reasoning_tokens", ) } def test_calls_are_totalled_by_day_and_by_model_and_a_failed_attempt_is_an_error( self, ): self.run_prompts("first", "second", "fail this request") summary = self.usage("?days=3") expected = { "calls": 3, "errors": 1, "input_tokens": 400, "cached_input_tokens": 160, "cache_creation_tokens": 0, "output_tokens": 60, "reasoning_tokens": 10, } self.assertEqual(self.totals(summary), expected) (line,) = summary["lines"] self.assertEqual(line["model"], "fixture-model") # Upstream migrates the fixture key into a labelled account. self.assertEqual(line["account"], self.app.profile) self.assertTrue(line["profile"].startswith("fixture")) # Three days, oldest first, the earlier two empty, and the day of use # holds the same totals as the one line. days = summary["days"] self.assertEqual(len(days), 3) for day in days[:2]: self.assertEqual(day["calls"], 0) self.assertEqual({key: days[2][key] for key in expected}, expected) self.assertEqual( [millis(day["start"]) - millis(days[0]["start"]) for day in days], [0, DAY_MS, 2 * DAY_MS], ) def test_title_generation_counts_alongside_the_main_turn(self): self.provider.title_script = lambda request: text( "Generated title", usage=SECOND ) session = self.app.session() self.app.prompt(session, "first").close() self.app.idle(session) wait_until( lambda: self.totals(self.usage())["calls"] == 2, 10, "the title request was not counted", ) self.assertEqual( self.totals(self.usage()), { "calls": 2, "errors": 0, "input_tokens": 400, "cached_input_tokens": 160, "cache_creation_tokens": 0, "output_tokens": 60, "reasoning_tokens": 10, }, ) def test_a_deleted_session_keeps_what_it_used(self): first, second = self.run_prompts("first", "second") before = self.totals(self.usage()) self.assertEqual(before["calls"], 2) self.delete_session(first) # The premise: the session's own request rows went with it. with sqlite3.connect(self.app.home / "albedo.sqlite") as db: self.assertEqual( db.execute( "SELECT COUNT(*) FROM provider_requests WHERE session=?", (first,) ).fetchone()[0], 0, ) self.assertEqual(self.totals(self.usage()), before) self.delete_session(second) self.assertEqual(self.totals(self.usage()), before) def test_the_window_is_bounded_and_checked(self): self.assertEqual(len(self.usage()["days"]), 7) self.assertEqual(len(self.usage("?days=90")["days"]), 90) for query in ( "?days=0", "?days=91", "?days=x", "?utc_offset_minutes=900", "?utc_offset_minutes=-721", "?hours=1", # An account belongs to a provider, and neither may be empty. "?account=ada%40example.com", "?account=", "?provider=", "?provider=&account=", ): with self.subTest(query=query): with self.assertRaises(urllib.error.HTTPError) as caught: self.usage(query) self.assertEqual(caught.exception.code, 400) caught.exception.close() def test_scope_values_are_matched_exactly_even_with_an_ampersand_a_quote_or_a_plus( self, ): provider = "custom:https://api.example.com/v1?model='a'&flag=x+y" account = "ada+albedo@example.com" self.seed( (provider, account, "odd", 1, 7, 1), (provider, "ada albedo@example.com", "spaced", 1, 11, 1), (provider, "", "none", 1, 13, 1), ) found = self.usage( encode({"days": 1, "provider": provider, "account": account}) ) self.assertEqual( [(line["model"], line["account"]) for line in found["lines"]], [("odd", account)], ) self.assertEqual(found["days"][0]["input_tokens"], 7) # A raw `+` in a query arrives as a space, so a client that escaped its # values reaches the plus account and the space account separately. quoted = urllib.parse.quote(provider, safe="") raw = f"?days=1&provider={quoted}&account=ada+albedo%40example.com" self.assertEqual( [line["model"] for line in self.usage(raw)["lines"]], ["spaced"] ) if __name__ == "__main__": unittest.main()