Files
ai-agent/backend/test_usage_plans.py
gabrielvidalandClaude Opus 5.5 ef5c40c3d5 fix(usage): a tier read after the first reading fills the assumed past
The tracker's first reading can land before the login-health poll has the
tier; it then wrote the backfilled past with no tier, and the later fill-in
patched only the latest segment — and replaced its data, losing its reason.
Assumed segments now take the tier once it is known, update_plan merges the
data, history derives a missing reason from the segment before, and a
ChatGPT tier reads as words.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 21:32:34 +01:00

192 lines
9.8 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.
"""Plan tracking (usage/plans.py) and the per-plan calibration it drives
(``python3 -m unittest test_usage_plans`` from ``backend/``)."""
import pathlib
import tempfile
import types
import unittest
from usage import calibrate, plans
from usage.store import UsageStore
H = 3600
NOW = 1_800_000_000.0
class _Store(unittest.TestCase):
def setUp(self):
self._d = tempfile.TemporaryDirectory()
self.store = UsageStore(str(pathlib.Path(self._d.name) / "x.db"))
def tearDown(self):
self._d.cleanup()
class Describe(unittest.TestCase):
def test_max_tiers_carry_their_multiple(self):
self.assertEqual(plans.describe("default_claude_max_20x"),
{"label": "Max 20×", "multiplier": 20.0})
self.assertEqual(plans.describe("default_claude_max_5x")["multiplier"], 5.0)
self.assertEqual(plans.describe("default_claude_pro")["label"], "Pro")
self.assertIsNone(plans.describe("default_raven")["multiplier"])
self.assertEqual(plans.ratio("default_claude_max_5x", "default_claude_max_20x"), 4.0)
self.assertEqual(plans.ratio("default_raven", "default_claude_max_20x"), 1.0)
def test_windows_of_a_snapshot(self):
snap = {"updatedAt": NOW, "windows": {"seven_day": {}, "seven_day_opus": {}}}
self.assertEqual(plans.windows_of(snap, NOW), ["week"])
self.assertIsNone(plans.windows_of(snap, NOW + plans.FRESH_S + 1)) # stale
self.assertIsNone(plans.windows_of({"updatedAt": NOW, "windows": {}}, NOW))
def test_tier_of_a_login_row(self):
self.assertEqual(plans.tier_of({"plan": {"tier": "default_claude_max_20x"}}),
"default_claude_max_20x")
self.assertEqual(plans.tier_of({"harness": "opencode", "subscriptionType": "pro"}),
"chatgpt_pro")
self.assertIsNone(plans.tier_of({}))
class Tracker(_Store):
def test_first_reading_backfills_and_splits_on_a_gone_window(self):
self.store.add_points([
("personal", "five_hour", NOW - 30 * 86400, 1, None, "live"),
("personal", "seven_day", NOW - 30 * 86400, 1, None, "live"),
("personal", "five_hour", NOW - 10 * H, 0, None, "live"),
("personal", "seven_day", NOW - 60, 40, None, "live")])
tr = plans.PlanTracker(self.store)
tr.observe("personal", "default_claude_max_20x", ["week"], now=NOW)
segs = plans.history(self.store, "personal")
self.assertEqual([s["windows"] for s in segs], [["week", "h5"], ["week"]])
self.assertEqual([s["source"] for s in segs], ["assumed", "detected"])
self.assertEqual(segs[0]["since"], NOW - 30 * 86400)
self.assertEqual(segs[1]["since"], NOW - 10 * H + 1)
self.assertEqual(segs[1]["reason"], "5-hour window gone")
self.assertEqual(segs[0]["until"], segs[1]["since"])
def test_a_change_must_hold_before_it_is_a_new_plan(self):
seen = []
tr = plans.PlanTracker(self.store, notify=lambda a, o, n: seen.append(n))
tr.observe("personal", "default_claude_max_5x", ["week", "h5"], now=NOW)
self.assertEqual(len(plans.history(self.store, "personal")), 1)
tr.observe("personal", "default_claude_max_20x", ["week", "h5"], now=NOW + 60)
tr.observe("personal", "default_claude_max_5x", ["week", "h5"], now=NOW + 120) # flicker
tr.observe("personal", "default_claude_max_20x", ["week", "h5"], now=NOW + 180)
tr.observe("personal", "default_claude_max_20x", ["week", "h5"], now=NOW + 1000)
self.assertEqual(len(plans.history(self.store, "personal")), 1)
tr.observe("personal", "default_claude_max_20x", ["week", "h5"],
now=NOW + 180 + plans.CONFIRM_S)
segs = plans.history(self.store, "personal")
self.assertEqual(len(segs), 2)
self.assertEqual(segs[-1]["since"], NOW + 180) # dated from first seen
self.assertEqual(segs[-1]["label"], "Max 20×")
self.assertEqual(seen[0]["data"]["reason"], "Max 5× → Max 20×")
def test_a_tier_read_late_fills_the_assumed_past_and_keeps_the_reason(self):
self.store.add_points([
("personal", "five_hour", NOW - 30 * 86400, 1, None, "live"),
("personal", "five_hour", NOW - 10 * H, 0, None, "live"),
("personal", "seven_day", NOW - 60, 40, None, "live")])
tr = plans.PlanTracker(self.store)
tr.observe("personal", None, ["week"], now=NOW) # the login not read yet
tr.observe("personal", "default_claude_max_20x", ["week"],
info={"displayName": "Ultra"}, now=NOW + 20)
segs = plans.history(self.store, "personal")
self.assertEqual([s["tier"] for s in segs], ["default_claude_max_20x"] * 2)
self.assertEqual(segs[1]["reason"], "5-hour window gone")
self.assertEqual(segs[1]["displayName"], "Ultra")
# a reason lost by an older build is derived from the segment before
self.store.update_plan("personal", segs[1]["since"], "default_claude_max_20x",
{"reason": None})
self.assertEqual(plans.history(self.store, "personal")[1]["reason"],
"5-hour window gone")
def test_unknown_readings_keep_the_plan(self):
tr = plans.PlanTracker(self.store)
self.assertIsNone(tr.observe("work", None, None, now=NOW)) # nothing to go on
tr.observe("work", None, ["week", "h5"], now=NOW)
tr.observe("work", "default_claude_max_5x", None, now=NOW + 60) # tier filled in
segs = plans.history(self.store, "work")
self.assertEqual(len(segs), 1)
self.assertEqual(segs[0]["tier"], "default_claude_max_5x")
tr.observe("work", None, None, now=NOW + 2 * plans.CONFIRM_S)
self.assertEqual(len(plans.history(self.store, "work")), 1)
def _fit(account, fitted_at, week, h5=None, plan=None, trusted=True):
c = {"account": account, "fittedAt": fitted_at, "days": 14, "source": "fit",
"trusted": trusted,
"week": {"unitsPerPct": week, "usdPerPct": week / 2, "r2": 0.9, "n": 100}}
if h5:
c["h5"] = {"unitsPerPct": h5, "usdPerPct": h5 / 2, "r2": 0.9, "n": 100}
if plan:
c["plan"] = plan
return c
class PerPlanCalibration(_Store):
def setUp(self):
super().setUp()
self.deps = types.SimpleNamespace(usage_store=self.store)
calibrate._current_cache.clear()
def test_before_any_plan_it_is_the_old_behaviour(self):
self.store.add_calibration(_fit("personal", NOW - 86400, 56.0, 15.0))
cal = calibrate.current(self.deps, "personal")
self.assertEqual(cal["source"], "fit")
self.assertEqual(cal["h5"]["unitsPerPct"], 15.0)
def test_a_gone_window_carries_the_week_over(self):
tr = plans.PlanTracker(self.store)
self.store.add_points([("personal", "five_hour", NOW - 30 * 86400, 1, None, "live"),
("personal", "five_hour", NOW - 10 * H, 0, None, "live"),
("personal", "seven_day", NOW - 60, 40, None, "live")])
# the morning fit, after the window went: its data are the old plan's
self.store.add_calibration(_fit("personal", NOW - 7 * H, 56.0, 15.0))
tr.observe("personal", "default_claude_max_20x", ["week"], now=NOW)
cal = calibrate.current(self.deps, "personal")
self.assertEqual(cal["source"], "carried")
self.assertEqual(cal["week"]["unitsPerPct"], 56.0)
self.assertNotIn("h5", cal)
self.assertEqual(cal["plan"]["windows"], ["week"])
pct = calibrate.plan_pct(self.deps, "personal", 56.0)
self.assertAlmostEqual(pct["week"], 1.0)
self.assertIsNone(pct["h5"])
def test_a_new_tier_is_scaled_then_fitted_independently(self):
self.store.add_plan({"account": "personal", "since": NOW - 60 * 86400,
"tier": "default_claude_max_5x", "windows": ["week", "h5"],
"source": "assumed"})
self.store.add_calibration(_fit("personal", NOW - 20 * 86400, 12.0, 3.0))
self.store.add_plan({"account": "personal", "since": NOW - 3 * 86400,
"tier": "default_claude_max_20x", "windows": ["week", "h5"],
"source": "detected"})
seed = calibrate.current(self.deps, "personal")
self.assertEqual(seed["source"], "scaled")
self.assertEqual(seed["scale"], 4.0)
self.assertEqual(seed["week"]["unitsPerPct"], 48.0)
self.assertEqual(seed["h5"]["unitsPerPct"], 12.0)
# A fit straddling the change belongs to the old plan; one stamped
# with the new one replaces the seed.
self.store.add_calibration(_fit("personal", NOW - 2 * 86400, 13.0, 3.1))
self.assertEqual(calibrate.current(self.deps, "personal")["source"], "scaled")
new = plans.public(plans.current(self.store, "personal"))
self.store.add_calibration(_fit("personal", NOW - 86400, 50.0, 12.5, plan=new))
cal = calibrate.current(self.deps, "personal")
self.assertEqual((cal["source"], cal["week"]["unitsPerPct"]), ("fit", 50.0))
# …unless it is implausibly far from the seed (×3)
self.store.add_calibration(_fit("personal", NOW - 3600, 400.0, 12.5, plan=new))
self.assertEqual(calibrate.current(self.deps, "personal")["week"]["unitsPerPct"], 50.0)
def test_without_history_the_default_is_scaled_to_the_tier(self):
self.store.add_plan({"account": "work", "since": NOW - 86400,
"tier": "default_claude_max_20x", "windows": ["week", "h5"],
"source": "assumed"})
cal = calibrate.current(self.deps, "work")
self.assertEqual(cal["source"], "scaled")
self.assertAlmostEqual(cal["week"]["unitsPerPct"],
calibrate.DEFAULTS["work"]["week"][0] * 4)
if __name__ == "__main__":
unittest.main()