Coverage for src/retrospeedlab/runner/lab/limits.py: 98%
62 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-02 22:44 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-02 22:44 +0000
1import re
2from datetime import UTC, datetime, timedelta
3from pathlib import Path
4from typing import Any
5from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
7import msgspec
9PAUSE_FILE = "usage-limit"
10RATE_LIMITED = 429
11LIMIT_TEXT = re.compile(
12 r"\b(weekly|session|usage|daily|5-hour|hourly)\s+limit\b|limit reached|rate.?limit", re.IGNORECASE
13)
14RESET_TEXT = re.compile(
15 r"resets\s+(?:(?P<month>[A-Za-z]{3})\s+(?P<day>\d{1,2}),?\s+)?"
16 r"(?P<hour>\d{1,2})(?::(?P<minute>\d{2}))?\s*(?P<half>am|pm)(?:\s*\((?P<zone>[^)]+)\))?",
17 re.IGNORECASE,
18)
19RESET_EPOCH = re.compile(r"\|(\d{10})\b")
20RESET_MARGIN = timedelta(minutes=5)
21UNKNOWN_RESET_PAUSE = timedelta(hours=1)
22HALF_DAY_HOURS = 12
23RESULT = "result"
26class UsageLimit(Exception):
27 def __init__(self, until: datetime) -> None:
28 super().__init__(f"Claude usage limit until {until:%Y-%m-%d %H:%M} UTC; the lab skips this window")
29 self.until = until
32def last_result(log: Path) -> dict[str, Any] | None:
33 found: dict[str, Any] | None = None
34 for line in log.read_bytes().splitlines():
35 try:
36 event = msgspec.json.decode(line, type=dict[str, Any])
37 except msgspec.DecodeError:
38 continue
39 if "type" in event and event["type"] == RESULT:
40 found = event
41 return found
44def result_text(result: dict[str, Any]) -> str:
45 errors: list[str] = result["errors"] if "errors" in result else []
46 return " ".join([result[RESULT] if RESULT in result else "", *errors])
49def limited(result: dict[str, Any]) -> bool:
50 status = result["api_error_status"] if "api_error_status" in result else None
51 return bool(result["is_error"]) and (status == RATE_LIMITED or bool(LIMIT_TEXT.search(result_text(result))))
54def reset(text: str, now: datetime) -> datetime | None:
55 if epoch := RESET_EPOCH.search(text):
56 return datetime.fromtimestamp(int(epoch[1]), UTC)
57 if (found := RESET_TEXT.search(text)) is None:
58 return None
59 try:
60 zone = ZoneInfo(found["zone"]) if found["zone"] else UTC
61 except ZoneInfoNotFoundError:
62 return None
63 local = now.astimezone(zone)
64 hour = int(found["hour"]) % HALF_DAY_HOURS + (HALF_DAY_HOURS if found["half"].lower() == "pm" else 0)
65 moment = local.replace(hour=hour, minute=int(found["minute"] or 0), second=0, microsecond=0)
66 if found["month"]:
67 moment = moment.replace(month=datetime.strptime(found["month"].title(), "%b").month, day=int(found["day"]))
68 return (moment if moment > local else moment.replace(year=moment.year + 1)).astimezone(UTC)
69 return (moment if moment > local else moment + timedelta(days=1)).astimezone(UTC)
72def usage_limit(log: Path, now: datetime) -> datetime | None:
73 result = last_result(log)
74 if result is None or not limited(result):
75 return None
76 until = reset(result_text(result), now)
77 return now + UNKNOWN_RESET_PAUSE if until is None else until + RESET_MARGIN
80def paused_until(pause: Path, now: datetime) -> datetime | None:
81 if not pause.is_file():
82 return None
83 until = datetime.fromisoformat(pause.read_text(encoding="utf-8"))
84 return until if until > now else None