Files
ai-agent/backend/test_usage_budget.py
gabrielvidalandClaude Opus 5.5 5670313285 feat(cron): cron jobs leave the core for the cron-jobs plugin
Owner jobs and guests' own scheduled jobs are the cron-jobs live plugin's
(forms move-ai-agent-cron-jobs-into-a-plugin_u0wa6b,
cron-scheduled-in-the-cli-and-mcp_x4nk83). Gone: backend/cron/,
schemas/cron.py, /api/cron*, /api/me/cron*, the cron scheduler thread,
Settings → Cron and the guests' Tâches planifiées pages, `ai-agent cron`
(now a pointer), MCP run_cron_job / set_cron_job / browse cron, the
scheduled-jobs core skill, guestDefaults.cronLimits.

The core keeps thin contracts:
- runs.guest bridge (runs/guestjob.py): a guest's job run as that guest,
  confined by the core from their record; the plugin only names it.
- runs.start's cron stamp → meta.cron.
- delivery of a guest job's result (push, mail, mailHtml) off the stamp.
- « Discuter »: POST /api/cron-runs/discuss.
- runs.cron provider readers (plugins/cron_bridge.py): budget,
  auto-archive, agents catalog, the agents page's Schedule.
- core/cronexpr.py, agents/runconfig.py; context.write create for a new
  agent definition; ui.pages[].unless; setRoute keeps a Settings page
  under /settings/p/.
- carryover.cron_jobs: /data/cron-jobs.json → the plugin's jobs.json,
  cronLimits → limits.json, guests' qwen jobs → sonnet (PR #23's
  decision, superseded).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 17:57:41 +01:00

129 lines
6.4 KiB
Python

"""What is left of the week and what is due before its reset
(``python3 -m unittest test_usage_budget`` from ``backend/``)."""
import datetime as dt
import types
import unittest
from unittest import mock
from conversations import cards
from plugins import cron_bridge, schedule_bridge
from usage import budget, calibrate, plans
H = 3600
def _iso(t: float) -> str:
return dt.datetime.fromtimestamp(t, dt.timezone.utc).isoformat().replace("+00:00", "Z")
def _summary(sid, start, hours, units, model="claude-opus-5-5", turns=1, tokens=None,
sidechain=False):
return {"sessionId": sid, "startedAt": _iso(start), "endedAt": _iso(start + hours * H),
"messages": 10, "userTurns": turns, "model": model, "planUnits": units,
"isSidechain": sidechain,
"byModel": {model: {"planUnits": units, "tokens": tokens or int(units * 1.5e6)}}}
class _Deps:
def __init__(self, now, rows, meta=None, jobs=(), scheduled=(), series=()):
self.usage_poller = types.SimpleNamespace(limits=lambda: {"personal": {
"windows": {"seven_day": {"pct": 48.0, "resetsAt": now + 19 * H}},
"stale": False}})
self.usage_store = types.SimpleNamespace(
series=lambda acct, since, until=None: {"seven_day": [p for p in series if p[0] >= since]})
# what the runs.cron provider (the cron-jobs plugin) answers to {"op": "list"}
self.jobs = [{"runConfig": {"model": "sonnet"}, **j} for j in jobs]
# what the runs.schedule provider answers to {"op": "upcoming"}
self.upcoming = list(scheduled)
self.worker_store = types.SimpleNamespace(get=lambda wid: {"account": "work"})
self.meta_store = types.SimpleNamespace(peek=lambda sid: (meta or {}).get(sid, {}))
self.rows = rows
class Firings(unittest.TestCase):
def test_counts_the_firings_before_the_end(self):
start = dt.datetime(2026, 11, 1, 0, 30).timestamp()
self.assertEqual(len(budget.firings("15 * * * *", start, start + 10 * H)), 10)
self.assertEqual(len(budget.firings("0 9 * * *", start, start + 19 * H)), 1)
self.assertEqual(budget.firings("0 9 * * *", start, start + 2 * H), [])
self.assertEqual(budget.firings("not a schedule", start, start + H), [])
class Budget(unittest.TestCase):
def setUp(self):
self.now = dt.datetime(2026, 11, 1, 0, 0).timestamp()
cal = {"source": "carried", "trusted": True,
"week": {"unitsPerPct": 50.0, "usdPerPct": 25.0}}
self._patches = [mock.patch.object(calibrate, "current", lambda deps, a: cal),
mock.patch.object(plans, "current", lambda store, a: None),
mock.patch.object(cron_bridge, "jobs",
lambda deps: list(getattr(deps, "jobs", []))),
mock.patch.object(schedule_bridge, "upcoming",
lambda deps: list(getattr(deps, "upcoming", [])))]
for p in self._patches:
p.start()
def tearDown(self):
for p in self._patches:
p.stop()
def _run(self, deps):
rows = [(f"/t/{s['sessionId']}{'-sub' if s['isSidechain'] else ''}.jsonl", s, a)
for s, a in deps.rows]
with mock.patch.object(cards, "_summaries_with_account", lambda d: rows):
return budget.budget(deps, "personal", now=self.now)
def test_free_part_after_the_crons_due_before_the_reset(self):
now = self.now
rows = [(_summary(f"c{i}", now - (i + 1) * 86400, 0.1, u, "claude-sonnet-5-5"), "personal")
for i, u in enumerate((0.2, 0.4, 0.3))]
rows += [(_summary(f"r{i}", now - 2 * 86400 - i * H, 2.0, 66.0), "personal")
for i in range(4)]
rows += [(_summary("r0", now - 2 * 86400, 1.0, 10.0, sidechain=True), "personal"),
(_summary("w", now - H, 1.0, 999.0), "work")]
meta = {f"c{i}": {"cron": {"id": "radar"}} for i in range(3)}
jobs = [{"id": "radar", "name": "Radar", "schedule": "0 8 * * *", "enabled": True},
{"id": "off", "name": "Off", "schedule": "* * * * *", "enabled": False},
{"id": "mac", "name": "Mac", "schedule": "0 * * * *", "enabled": True,
"worker": "w1"}]
sch = [{"id": "sch_1", "title": "Later",
"shouldStartAt": _iso(now + 2 * H), "model": "opus"},
{"id": "sch_2", "title": "After",
"shouldStartAt": _iso(now + 30 * H)}]
series = [(now - 6 * H, 42.0, now + 19 * H), (now - 60, 48.0, now + 19 * H)]
out = self._run(_Deps(now, rows, meta, jobs, sch, series))
self.assertAlmostEqual(out["hoursLeft"], 19.0)
self.assertAlmostEqual(out["left"]["units"], 52 * 50.0)
items = {i["id"]: i for i in out["upcoming"]["items"]}
# the Mac job bills the work seat; the disabled one never fires
self.assertEqual(set(items), {"radar", "sch_1"})
self.assertEqual((items["radar"]["runs"], items["radar"]["unitsPerRun"],
items["radar"]["sampled"]), (1, 0.3, 3))
# a scheduled Opus conversation = a typical single-prompt Opus run
# (r0 carries its subagent: 76 units, the others 66)
self.assertAlmostEqual(items["sch_1"]["unitsPerRun"], 66.0)
self.assertAlmostEqual(out["free"]["units"], 2600 - 66.3)
self.assertAlmostEqual(out["free"]["usd"], (2600 - 66.3) / 50 * 25)
opus = out["families"]["opus"]
self.assertAlmostEqual(opus["unitsPerHour"], 33.0) # median of 38, 33, 33, 33
self.assertEqual(opus["rateRuns"], 4)
self.assertAlmostEqual(opus["streams"], (2600 - 66.3) / (33 * 19))
self.assertEqual(out["families"]["fable"]["unitsPerHour"], budget.DEFAULT_RATE["fable"])
self.assertAlmostEqual(out["pace"]["last6h"], 1.0, places=2)
self.assertAlmostEqual(out["pace"]["projected"], min(100.0, 48 + out["pace"]["last6h"] * 19))
self.assertAlmostEqual(out["pace"]["needed"], out["free"]["pct"] / 19)
def test_pace_is_unknown_across_a_reset(self):
now = self.now
series = [(now - 6 * H, 90.0, now - 2 * H), (now - 60, 48.0, now + 19 * H)]
out = self._run(_Deps(now, [], series=series))
self.assertIsNone(out["pace"]["last6h"])
self.assertIsNone(out["pace"]["projected"])
self.assertEqual(out["upcoming"]["items"], [])
if __name__ == "__main__":
unittest.main()