Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 29 additions & 9 deletions hermes/deploy/pool_sizing.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,16 @@


def parse_days(spec: str) -> set[int]:
"""'Mon-Fri' or 'Mon,Wed,Fri' to weekday numbers."""
"""'Mon-Fri', 'Sun-Thu', or 'Mon,Wed,Fri' to weekday numbers (Mon=0..Sun=6)."""
out: set[int] = set()
for part in spec.split(","):
part = part.strip()
if "-" in part:
a, b = (DAYS[x.strip()] for x in part.split("-"))
out |= set(range(a, b + 1))
if a <= b:
out |= set(range(a, b + 1))
else:
out |= set(range(a, 7)) | set(range(0, b + 1))
elif part:
out.add(DAYS[part])
return out
Expand Down Expand Up @@ -105,9 +108,20 @@ def cron_minutes(expr: str, tz: ZoneInfo, day0: datetime, days: int) -> list[flo
for part in dow.split(","):
if "-" in part:
a, b = (int(x) for x in part.split("-"))
want |= set(range(a, b + 1))
a = 0 if a == 7 else a
b = 0 if b == 7 else b
if not (0 <= a <= 6 and 0 <= b <= 6):
raise ValueError(f"cron {expr!r}: weekday {part!r} out of range 0-7")
if a <= b:
want |= set(range(a, b + 1))
else:
want |= set(range(a, 7)) | set(range(0, b + 1))
else:
want.add(int(part))
d_val = int(part)
d_val = 0 if d_val == 7 else d_val
if not (0 <= d_val <= 6):
raise ValueError(f"cron {expr!r}: weekday {part!r} out of range 0-7")
want.add(d_val)
# cron counts Sunday as 0; Python counts Monday as 0.
want = {(d - 1) % 7 for d in want}
out = []
Expand Down Expand Up @@ -145,6 +159,8 @@ def need(field: str) -> str:
# Only the gaps reading uses this. Requiring it in both is how a fleet file
# that states counts and no gaps gets refused for a field it never needed.
gap_min = 0.0 if uniform else float(need("median_gap_minutes"))
if not uniform and gap_min <= 0:
raise ValueError(f"{agent['id']}: median_gap_minutes must be > 0, got {gap_min}")

starts: list[float] = []
for d in range(days):
Expand All @@ -155,7 +171,8 @@ def need(field: str) -> str:
window_start = (local + timedelta(minutes=start_m)).astimezone(
day0.tzinfo) - day0
t0 = window_start.total_seconds()
span = (end_m - start_m) * 60.0
span_min = (end_m - start_m) if end_m > start_m else (end_m + 1440 - start_m)
span = span_min * 60.0
if uniform:
# The count is fixed and the placement is random. This is the reading
# that trusts messages_per_workday.
Expand Down Expand Up @@ -284,10 +301,13 @@ def main() -> int:
print(f" recommended WorkerPool.replicas: {rec} ({worst} + {a.headroom} headroom)")
held = statistics.mean(base["means"])
print(f" mean workers held across the week: {held:.1f} of {n} agents")
print(f" so the pool has to be sized for {worst} and is used for {held:.1f}. "
f"Peak is {worst / held:.0f}x the mean,")
print(" which is the density result: suspension pays on cost, not on the "
"ceiling.")
if held > 0:
print(f" so the pool has to be sized for {worst} and is used for {held:.1f}. "
f"Peak is {worst / held:.0f}x the mean,")
print(" which is the density result: suspension pays on cost, not on the "
"ceiling.")
else:
print(f" so the pool has to be sized for {worst} and mean occupancy is 0.0.")
if rec >= n:
print(f" {rec} is the whole fleet or more. At these idle timeouts "
"suspension buys")
Expand Down
25 changes: 25 additions & 0 deletions hermes/deploy/test_pool_sizing.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ def check(label, cond, extra=""):

# ---- day and time parsing ----
check("Mon-Fri is five weekdays", ps.parse_days("Mon-Fri") == {0, 1, 2, 3, 4})
check("Sun-Thu wraps cleanly for Sun..Thu workweeks",
ps.parse_days("Sun-Thu") == {6, 0, 1, 2, 3})
check("Fri-Mon wraps across weekend",
ps.parse_days("Fri-Mon") == {4, 5, 6, 0})
check("a comma list is taken literally", ps.parse_days("Mon,Wed,Fri") == {0, 2, 4})
check("hh:mm is minutes past midnight", ps.parse_hhmm("08:45") == 525)

Expand All @@ -47,6 +51,10 @@ def check(label, cond, extra=""):
abs((b - a) - 86400) < 1 for a, b in zip(fires, fires[1:])))

check("'*' fires every day", len(ps.cron_minutes("0 9 * * *", UTC, DAY0, 7)) == 7)
check("wrap-around cron dow 5-0 fires Fri, Sat, Sun",
len(ps.cron_minutes("0 9 * * 5-0", UTC, DAY0, 7)) == 3)
check("cron dow 7 alias matches Sunday",
ps.cron_minutes("0 9 * * 7", UTC, DAY0, 7) == ps.cron_minutes("0 9 * * 0", UTC, DAY0, 7))

# cron counts Sunday as 0, Python counts Monday as 0. Getting this off by one
# puts a Monday brief on a Sunday, where it wakes an agent nobody is reading.
Expand Down Expand Up @@ -116,6 +124,23 @@ def check(label, cond, extra=""):
check("but the gaps reading says which field is missing, and whose",
"median_gap_minutes" in str(e) and "a:" in str(e), str(e))

# Overnight active hours (e.g., 22:00-06:00) and non-positive median gaps.
overnight = {"id": "night-ops", "idle_tier": "short", "timezone": "UTC",
"duty_cycle": {"messages_per_workday": 3, "median_gap_minutes": 120,
"active_hours": "22:00-06:00", "active_days": "Sun-Thu"}}
night_iv = ps.agent_intervals(overnight, {}, DAY0, 7, 45.0, rng, True)
check("overnight active_hours on Sun-Thu produces intervals", len(night_iv) > 0, night_iv)

try:
ps.agent_intervals(
{"id": "bad-gap", "idle_tier": "short", "timezone": "UTC",
"duty_cycle": {"median_gap_minutes": 0, "active_hours": "09:00-18:00",
"active_days": "Mon-Fri"}},
{}, DAY0, 7, 45.0, rng, False)
check("median_gap_minutes <= 0 is refused", False)
except ValueError:
check("median_gap_minutes <= 0 is refused", True)

# ---- peak ----
check("no intervals is a peak of zero", ps.peak([]) == 0)
check("disjoint intervals never stack", ps.peak([(0, 10), (20, 30), (40, 50)]) == 1)
Expand Down