78 lines
3.0 KiB
Python
78 lines
3.0 KiB
Python
"""Hot-read, operator-owned policy. Client job data never selects this file."""
|
|
|
|
import json
|
|
import math
|
|
from pathlib import Path
|
|
import time
|
|
|
|
|
|
def _read_file_policy(settings=None):
|
|
result = {"batch_window_enabled": True, "workflow_max_shots": 120, "configuration_error": None}
|
|
path = getattr(settings, "runtime_policy_file", None)
|
|
if path is None:
|
|
return result
|
|
try:
|
|
with Path(path).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 read_runtime_policy(settings=None):
|
|
policy = _read_file_policy(settings)
|
|
# 远端策略文件仍校验镜头上限与读取错误,但不能覆盖本环境的可信开关。
|
|
# 旧调用替身不含该字段时保留原文件语义。
|
|
if hasattr(settings, "gpu_window_enabled"):
|
|
enabled = settings.gpu_window_enabled
|
|
if enabled is None:
|
|
enabled = getattr(settings, "mode", "production") == "production"
|
|
if type(enabled) is not bool:
|
|
policy = {**policy, "configuration_error": "runtime_policy_invalid"}
|
|
else:
|
|
policy = {**policy, "batch_window_enabled": enabled}
|
|
if not getattr(settings, "inference_remote_files", False):
|
|
return policy
|
|
error = getattr(settings, "_remote_policy_error", None)
|
|
observed = getattr(settings, "_remote_policy_observed_at", None)
|
|
if error is not None:
|
|
error = (
|
|
"runtime_policy_invalid"
|
|
if error == "runtime_policy_invalid"
|
|
else "runtime_policy_unavailable"
|
|
)
|
|
elif (
|
|
type(observed) not in (int, float)
|
|
or not math.isfinite(observed)
|
|
or not 0 <= time.monotonic() - observed <= 5
|
|
):
|
|
error = "runtime_policy_unavailable"
|
|
if error:
|
|
return {**policy, "configuration_error": error}
|
|
return policy
|