cmvr-visual/inference/llm_services/scheduling.py

137 lines
6.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Admission-only night policy. An admitted runner is never stopped by this clock."""
from datetime import date, datetime, timedelta, timezone
import json
import math
from pathlib import Path
SHANGHAI = timezone(timedelta(hours=8), "Asia/Shanghai")
FIELDS = {"execution_mode", "principal_id", "batch_id", "run_id", "step_key", "policy_version",
"gpu_window_enabled"}
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 not isinstance(mode, str) or 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")
# 缺字段的历史原包不补默认值,避免改变已持久化请求的幂等hash。
if "gpu_window_enabled" in value:
if type(value["gpu_window_enabled"]) is not bool:
raise ValueError("Expected boolean GPU window switch")
result["gpu_window_enabled"] = value["gpu_window_enabled"]
json.dumps(result, allow_nan=False)
return result
def read_runtime_policy(policy_file=None):
"""Read the same operator schema as the web API; never read job payloads."""
result = {"batch_window_enabled": True, "workflow_max_shots": 120,
"configuration_error": None}
if policy_file is None:
return result
try:
with Path(policy_file).open("rb") as stream:
raw = stream.read(65537)
except FileNotFoundError:
return result
except OSError:
return {**result, "configuration_error": "runtime_policy_unavailable"}
try:
if len(raw) > 65536:
raise ValueError("Policy too large")
value = json.loads(raw.decode("utf-8"))
if not isinstance(value, dict) or set(value) - {
"schema_version", "batch_window_enabled", "workflow_max_shots"}:
raise ValueError("Unknown policy fields")
if type(value.get("schema_version")) is not int or value["schema_version"] != 1:
raise ValueError("Unsupported schema")
if type(value.get("batch_window_enabled")) is not bool:
raise ValueError("Expected boolean switch")
max_shots = value.get("workflow_max_shots", 120)
if type(max_shots) is not int or not 1 <= max_shots <= 1000:
raise ValueError("Invalid shot limit")
except (ValueError, TypeError, UnicodeError):
return {**result, "configuration_error": "runtime_policy_invalid"}
return {"batch_window_enabled": value["batch_window_enabled"],
"workflow_max_shots": max_shots, "configuration_error": None}
def _window_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": opened,
"reason": None if opened else "waiting_batch_window",
"next_eligible_at": None if opened else next_start.timestamp()}
def _configured_eligibility(mode, now, policy):
if mode not in {"interactive", "batch"}:
raise ValueError("Invalid execution mode")
if policy["configuration_error"]:
return {"eligible": False, "reason": policy["configuration_error"], "next_eligible_at": None}
if not policy["batch_window_enabled"]:
return {"eligible": True, "reason": None, "next_eligible_at": None}
return _window_eligibility(mode, now)
def eligibility(mode, now, *, policy_file=None):
return _configured_eligibility(mode, now, read_runtime_policy(policy_file))
def policy_status(now, *, policy_file=None):
policy=read_runtime_policy(policy_file)
batch = _configured_eligibility("batch", now, policy)
return {"timezone": "Asia/Shanghai", "start": "21:00", "end": "08:00",
"batch_window_enabled": policy["batch_window_enabled"],
"configuration_error": policy["configuration_error"],
"batch_open": batch["eligible"], "next_batch_at": batch["next_eligible_at"],
"close_behavior": "finish_current"}
def guarded_eligibility(now, max_seen=0, closed_through="", *, policy_file=None,
gpu_window_enabled=None):
"""Persist returned watermark and closed date before admitting a new runner."""
policy=read_runtime_policy(policy_file)
if gpu_window_enabled is not None:
if type(gpu_window_enabled) is not bool:
raise ValueError("Expected boolean GPU window switch")
# 任务快照只覆盖窗口开关;宿主配置损坏仍须阻止启动。
policy = {**policy, "batch_window_enabled": gpu_window_enabled}
if policy["configuration_error"] or not policy["batch_window_enabled"]:
# Keep clock evidence unchanged while development mode bypasses it.
return _configured_eligibility("batch", now, policy),max_seen,closed_through
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 = _window_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