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
9 changes: 6 additions & 3 deletions src/inferrsi/harness/manager/_parallel_round.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@
advance,
empty_ledger,
ensure_open,
parse_deadline,
seconds_remaining,
)
from ._runner import run_experiment as run_experiment_loop
Expand Down Expand Up @@ -520,8 +521,10 @@ def prepare_parallel_round(spec: dict, incumbent: Path, round_dir: Path) -> dict
raise RoundPlanError("a lane needs path globs")
if type(lane.get("cap")) is not int or type(lane.get("per_attempt_worst_case")) is not int:
raise RoundPlanError("cap and per-attempt cost must come from the plan")
if not isinstance(lane.get("deadline_utc"), str):
raise RoundPlanError("each lane needs a deadline")
try:
parse_deadline(lane.get("deadline_utc"))
except BudgetError as exc:
raise RoundPlanError("each lane needs a timezone-aware deadline") from exc
count = lane.get("device_count", 1)
if type(count) is not int or count < 1:
raise RoundPlanError(f"{lane_id} device_count must be a positive integer")
Expand Down Expand Up @@ -1736,8 +1739,8 @@ def finish(**fields) -> dict:

composed = [{"ticket": body["ticket"], "lane_id": body["lane_id"]} for body in selected]
lanes = [_lane(plan, body["lane_id"]) for body in selected]
deadline_utc = min(lane["deadline_utc"] for lane in lanes)
try:
deadline_utc = min((lane["deadline_utc"] for lane in lanes), key=parse_deadline)
ensure_open(deadline_utc, current())
except BudgetError as exc:
return finish(reason=str(exc), composed=composed)
Expand Down
32 changes: 24 additions & 8 deletions src/inferrsi/harness/manager/_round_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,18 @@

import hashlib
import json
import re
from dataclasses import dataclass, replace
from datetime import datetime
from pathlib import Path

_DEADLINE = re.compile(
r"(?P<base>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})"
r"(?:\.(?P<fraction>\d{1,9}))?"
r"(?P<zone>Z|[+-](?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?)",
re.ASCII,
)


class BudgetError(ValueError):
"""Invalid, exhausted, expired, or unsafe lane-budget state."""
Expand Down Expand Up @@ -167,21 +175,29 @@ def advance(
raise BudgetError("No exact reservation for this plan/run")


def _deadline(deadline_utc: str, now: datetime) -> datetime:
if type(deadline_utc) is not str or now.tzinfo is None:
raise BudgetError("deadline and now must be timezone-aware")
def parse_deadline(deadline_utc: str) -> datetime:
"""Parse an extended ISO-8601 timezone-aware deadline consistently across Python 3.10+."""
match = _DEADLINE.fullmatch(deadline_utc) if type(deadline_utc) is str else None
if match is None:
raise BudgetError("deadline must be a timezone-aware timestamp")
fraction = match.group("fraction")
micros = "." + fraction[:6].ljust(6, "0") if fraction is not None else ""
zone = "+00:00" if match.group("zone") == "Z" else match.group("zone")
try:
deadline = datetime.fromisoformat(deadline_utc)
return datetime.fromisoformat(match.group("base") + micros + zone)
except ValueError as exc:
raise BudgetError("deadline must be a timezone-aware timestamp") from exc
if deadline.tzinfo is None:


def _deadline(deadline_utc: str, now: datetime) -> datetime:
if not isinstance(now, datetime) or now.tzinfo is None or now.utcoffset() is None:
raise BudgetError("deadline and now must be timezone-aware")
return deadline
return parse_deadline(deadline_utc)


def ensure_open(deadline_utc: str, now: datetime) -> None:
"""Refuse a new attempt after the lane deadline. Reservation does not check time."""
if now > _deadline(deadline_utc, now):
"""Refuse a new attempt at or after the lane deadline. Reservation does not check time."""
if now >= _deadline(deadline_utc, now):
raise BudgetError("lane deadline passed")


Expand Down
94 changes: 94 additions & 0 deletions tests/harness/test_parallel_round.py
Original file line number Diff line number Diff line change
Expand Up @@ -3029,3 +3029,97 @@ def test_close_promotes_huge_finite_pairs_without_json_inf(tmp_path):
body = json.loads((round_dir / "close.json").read_text(encoding="utf-8"))
assert body["incumbent"] == 1.7e308
assert body["candidate"] == 1.6e308


@requires_posix_round_storage
def test_prepare_validates_lane_deadlines(tmp_path):
incumbent = tmp_path / "incumbent"
_tree(incumbent, "10")
for invalid in (
None,
"",
"not-a-timestamp",
"2099-01-01T00:00:00",
"2099-02-30T00:00:00Z",
"20991030T000000+0000",
):
bad = _spec()
bad["lanes"][0]["deadline_utc"] = invalid
with pytest.raises(RoundPlanError, match="deadline"):
prepare(bad, incumbent, tmp_path / "round-bad-deadline")
spec = _spec()
spec["lanes"][0]["deadline_utc"] = "2099-01-01T00:00:00Z"
plan = prepare(spec, incumbent, tmp_path / "round-z-deadline")
assert plan["lanes"][0]["deadline_utc"] == "2099-01-01T00:00:00Z"


@requires_posix_round_storage
@pytest.mark.parametrize(
("l1_deadline", "l2_deadline", "close_at"),
[
(
"2099-10-30T01:00:00+08:00",
"2099-10-30T00:00:00+00:00",
datetime(2099, 10, 29, 20, 0, tzinfo=timezone.utc),
),
(
"2099-10-29T17:00:00Z",
"2099-10-29T17:00:00.5Z",
datetime(2099, 10, 29, 17, 0, 0, 250000, tzinfo=timezone.utc),
),
],
)
def test_close_enforces_earliest_chronological_lane_deadline(
tmp_path, l1_deadline, l2_deadline, close_at
):
incumbent = tmp_path / "incumbent"
_sum_tree(incumbent, "10", "10")
spec = _sum_spec()
spec["lanes"][0]["deadline_utc"] = l1_deadline
spec["lanes"][1]["deadline_utc"] = l2_deadline
round_dir = tmp_path / "round"
prepare(spec, incumbent, round_dir)
before = datetime(2099, 10, 29, 16, 0, tzinfo=timezone.utc)
for lane_id, a, b in (("L1", "5", "10"), ("L2", "10", "5")):
work = tmp_path / f"work-{lane_id}"
_sum_tree(work, a, b)
ticket = submit(round_dir, lane_id, incumbent, work, now=before)["ticket"]
served = serve_ticket(
round_dir, ticket, incumbent, backend=FixtureBackend(), clock=lambda: before
)
assert served["verdict"] == "PASS"

closed = close_round(
round_dir, incumbent, backend=FixtureBackend(), clock=lambda: close_at
)
assert closed["status"] == "closed"
assert closed["accepted"] is False
assert closed["reason"] == "lane deadline passed"
assert closed["successor"] is None


@requires_posix_round_storage
def test_serve_at_exact_deadline_rejects_without_charging_budget(tmp_path):
incumbent = tmp_path / "incumbent"
_tree(incumbent, "10")
spec = _spec()
spec["lanes"][0]["deadline_utc"] = "2099-10-30T00:00:00Z"
round_dir = tmp_path / "round"
prepare(spec, incumbent, round_dir)
work = tmp_path / "work"
_tree(work, "8")
before = datetime(2099, 10, 29, 23, 59, 59, tzinfo=timezone.utc)
cutoff = datetime(2099, 10, 30, 0, 0, tzinfo=timezone.utc)
ticket = submit(round_dir, "L1", incumbent, work, now=before)["ticket"]

moments = [before, cutoff]
rejected = serve_ticket(
round_dir,
ticket,
incumbent,
backend=FixtureBackend(),
clock=lambda: moments.pop(0) if len(moments) > 1 else moments[0],
)
assert rejected["status"] == "rejected"
assert rejected["reason"] == "lane deadline passed"
assert not (round_dir / "ledgers" / "L1.json").exists()
70 changes: 69 additions & 1 deletion tests/harness/test_round_budget.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Lane attempt budgets. Costs in these tests are plan fields, not campaign gates."""

import json
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone

import pytest

Expand All @@ -11,6 +11,9 @@
advance,
attempt_plan_digest,
empty_ledger,
ensure_open,
parse_deadline,
seconds_remaining,
)

ROUND = "a" * 64
Expand Down Expand Up @@ -66,3 +69,68 @@ def test_past_deadline_rejects_even_when_budget_remains(tmp_path):
reloaded = json.loads(plan_path.read_text(encoding="utf-8"))
assert reloaded["lanes"][0]["deadline_utc"].startswith("2020-")
assert ledger.charged == before


@pytest.mark.parametrize(
("raw", "expected"),
[
("2099-10-30T00:00:00Z", datetime(2099, 10, 30, 0, 0, tzinfo=timezone.utc)),
("2099-10-30T00:00:00.5Z", datetime(2099, 10, 30, 0, 0, 0, 500000, tzinfo=timezone.utc)),
(
"2099-10-30T00:00:00.123456789Z",
datetime(2099, 10, 30, 0, 0, 0, 123456, tzinfo=timezone.utc),
),
("2099-10-30T01:00:00+08:00", datetime(2099, 10, 29, 17, 0, tzinfo=timezone.utc)),
(
"2099-10-30T01:00:00.5+08:00",
datetime(2099, 10, 29, 17, 0, 0, 500000, tzinfo=timezone.utc),
),
],
)
def test_parse_deadline_handles_utc_z_fractional_seconds_and_offsets(raw, expected):
assert parse_deadline(raw) == expected


@pytest.mark.parametrize(
"invalid",
[
None,
123,
"",
"not-a-timestamp",
"2099-10-30",
"2099-10-30T00:00:00",
"2099-02-30T00:00:00Z",
"20991030T000000+0000",
"20991030T000000Z",
"2099-10-30T00:00:00+0000",
"2099-10-30 00:00:00+00:00",
"2099-10-30T00:00Z",
"2099-10-30T00:00:00z",
"2099-W44-5T00:00:00Z",
"2099-10-30T00:00:00+00:60",
],
)
def test_parse_deadline_rejects_naive_and_invalid_values(invalid):
with pytest.raises(BudgetError, match="timezone-aware"):
parse_deadline(invalid)


@pytest.mark.parametrize("deadline", ["2099-10-30T00:00:00Z", "2099-10-30T08:00:00+08:00"])
def test_exact_deadline_is_closed_for_ensure_open_and_seconds_remaining(tmp_path, deadline):
cutoff = datetime(2099, 10, 30, 0, 0, tzinfo=timezone.utc)
just_before = cutoff - timedelta(microseconds=1)
ensure_open(deadline, just_before)
assert seconds_remaining(deadline, just_before) == pytest.approx(1e-6)

with pytest.raises(BudgetError, match="lane deadline passed"):
ensure_open(deadline, cutoff)
with pytest.raises(BudgetError, match="lane deadline passed"):
seconds_remaining(deadline, cutoff)

plan_path = tmp_path / "round-plan.json"
_plan(plan_path, cap=2, worst=1, deadline=deadline)
ledger = empty_ledger(ROUND, "L1", cap=2)
with pytest.raises(BudgetError, match="lane deadline passed"):
admit_from_path(plan_path, ledger, "L1", cutoff)
assert ledger.charged == 0
Loading