cmvr-visual/inference/llm_services/scheduling.py

70 lines
3.4 KiB
Python

"""Admission-only night policy. An admitted runner is never stopped by this clock."""
from datetime import date, datetime, timedelta, timezone
import json
import math
SHANGHAI = timezone(timedelta(hours=8), "Asia/Shanghai")
FIELDS = {"execution_mode", "principal_id", "batch_id", "run_id", "step_key", "policy_version"}
def normalize_scheduling(value):
if value is None:
return None # Preserve the exact v1 hash for old persisted submissions.
if not isinstance(value, dict) or set(value) - FIELDS:
raise ValueError("Unknown scheduling fields")
mode = value.get("execution_mode", "interactive")
if mode not in {"interactive", "batch"}:
raise ValueError("Invalid execution mode")
result = {"execution_mode": mode, "principal_id": value.get("principal_id", "legacy"),
"policy_version": value.get("policy_version", "night-v1")}
for key in ("batch_id", "run_id", "step_key"):
if value.get(key) is not None:
result[key] = value[key]
if result["policy_version"] != "night-v1":
raise ValueError("Unsupported admission policy")
if any(not isinstance(v, str) or not 1 <= len(v) <= 128 or any(ord(c) < 32 for c in v)
for v in result.values()):
raise ValueError("Invalid scheduling identity")
json.dumps(result, allow_nan=False)
return result
def eligibility(mode, now):
if mode not in {"interactive", "batch"}:
raise ValueError("Invalid execution mode")
local = datetime.fromtimestamp(float(now), timezone.utc).astimezone(SHANGHAI)
opened = local.hour >= 21 or local.hour < 8
next_start = local.replace(hour=21, minute=0, second=0, microsecond=0)
return {"eligible": mode == "interactive" or opened,
"reason": None if mode == "interactive" or opened else "waiting_batch_window",
"next_eligible_at": None if mode == "interactive" or opened else next_start.timestamp()}
def policy_status(now):
batch = eligibility("batch", now)
return {"timezone": "Asia/Shanghai", "start": "21:00", "end": "08:00",
"batch_open": batch["eligible"], "next_batch_at": batch["next_eligible_at"],
"close_behavior": "finish_current"}
def guarded_eligibility(now, max_seen=0, closed_through=""):
"""Persist returned watermark and closed date before admitting a new runner."""
try:
watermark=float(max_seen)
if not math.isfinite(watermark) or not 0<=watermark<=253402300799:raise ValueError()
if closed_through:date.fromisoformat(closed_through)
except (ValueError,TypeError,OverflowError):
return {"eligible":False,"reason":"clock_state_invalid","next_eligible_at":None},max_seen,closed_through
now = float(now)
local = datetime.fromtimestamp(now, timezone.utc).astimezone(SHANGHAI)
latest_closed = local.date() if local.hour >= 8 else local.date() - timedelta(days=1)
closed_through = max(closed_through, latest_closed.isoformat())
result = eligibility("batch", now)
if now < float(max_seen) - 5:
result.update(eligible=False, reason="clock_rollback", next_eligible_at=float(max_seen))
elif result["eligible"]:
window_end = local.date() + timedelta(days=1) if local.hour >= 21 else local.date()
if window_end.isoformat() <= closed_through:
result.update(eligible=False, reason="window_already_closed", next_eligible_at=None)
return result, max(now, float(max_seen)), closed_through