cmvr-visual/backend/app/adapters/provider/runtime.py
zhanghao 88cf14d794 feat: consolidate story studio and editable automatic production
Restructure backend and frontend modules; add story, library, and editor schema migrations.

Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews.

Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
2026-11-14 14:07:26 +08:00

314 lines
13 KiB
Python

"""运行状态白名单、短缓存与远程调度策略镜像。"""
from __future__ import annotations
import asyncio
import json
import os
from pathlib import Path
import re
import time
import uuid
from app.adapters.media import confined
from app.domain.errors import MediaError as ProviderError
from .contracts import _int, _float
from .transport import _url
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .client import Provider
_UUID = re.compile(r"GPU-[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\Z")
async def health(provider: Provider):
try:
value = await provider._json(
"GET",
_url(provider.settings.inference_base_url, "/health"),
headers=provider._headers(),
)
return value.get("status") == "ok"
except ProviderError:
return False
def _runtime_value(value):
"""Validate and whitelist operator telemetry before retaining it locally."""
try:
if type(value["schema_version"]) is not int or value["schema_version"] != 1:
raise ValueError
policy = value["runtime_policy"]
if type(policy["batch_window_enabled"]) is not bool:
raise ValueError
shots = _int(policy["workflow_max_shots"], 1, 1000)
error = policy.get("configuration_error")
if error not in {None, "runtime_policy_invalid", "runtime_policy_unavailable"}:
raise ValueError
policy = {
"batch_window_enabled": policy["batch_window_enabled"],
"workflow_max_shots": shots,
"configuration_error": error,
}
monitor = value["monitor"]
if type(monitor["schema_version"]) is not int or monitor["schema_version"] != 1:
raise ValueError
if monitor.get("error") is not None:
monitor = {
"schema_version": 1,
"generated_at": None,
"error": "gpu_monitor_unavailable",
"gpus": [],
}
else:
now = time.time()
stamp = _float(monitor["generated_at"], 0, now + 1)
entries = monitor["gpus"]
if not isinstance(entries, list) or len(entries) > 1024:
raise ValueError
gpus, seen_indexes, seen_uuids = [], set(), set()
for row in entries:
index, gpu_uuid = _int(row["index"], 0, 1024), row["uuid"]
if (
not isinstance(gpu_uuid, str)
or not _UUID.fullmatch(gpu_uuid)
or index in seen_indexes
or gpu_uuid.lower() in seen_uuids
):
raise ValueError
seen_indexes.add(index)
seen_uuids.add(gpu_uuid.lower())
total = _float(row["total_gib"], 0.001, 100000)
free = _float(row["free_gib"], 0, total)
idle = row.get("idle_since")
if idle is not None:
idle = _float(idle, 0, now + 1)
if type(row["external_busy"]) is not bool or type(row["own_busy"]) is not bool:
raise ValueError
gpus.append(
{
"index": index,
"uuid": gpu_uuid,
"total_gib": total,
"free_gib": free,
"idle_since": idle,
"external_busy": row["external_busy"],
"own_busy": row["own_busy"],
}
)
monitor = {"schema_version": 1, "generated_at": stamp, "error": None, "gpus": gpus}
scheduler = value.get("scheduler")
if scheduler is not None:
if not isinstance(scheduler, dict):
raise ValueError
if type(scheduler.get("schema_version")) is not int or scheduler[
"schema_version"
] not in {1, 2}:
raise ValueError
# 只保留摘要所需的租约与计数,不暴露任务 ID、进程或诊断路径。
clean = {
key: scheduler[key]
for key in ("schema_version", "updated_at", "state", "queued_count")
if key in scheduler
}
if clean.get("state") not in {"idle", "waiting", "running", "blocked", "leased"}:
raise ValueError
clean["updated_at"] = _float(scheduler["updated_at"], 0, time.time() + 1)
if "queued_count" in clean and clean["queued_count"] is not None:
clean["queued_count"] = _int(clean["queued_count"], 0, 10000000)
clean["reason"] = (
"memory" if "memory" in str(scheduler.get("reason", "")).lower() else None
)
if scheduler.get("schema_version") == 2:
rows = scheduler.get("active_jobs", [])
if not isinstance(rows, list) or len(rows) > 1024:
raise ValueError
active = []
for row in rows:
index, gpu_uuid = _int(row["gpu_index"], 0, 1024), row["gpu_uuid"]
if not isinstance(gpu_uuid, str) or not _UUID.fullmatch(gpu_uuid):
raise ValueError
state, stage = row.get("state"), row.get("stage")
if state not in {"running", "launching", "preempting", "blocked"}:
raise ValueError
stage = (
stage
if stage
in {"launching", "executing", "cleanup", "model", "upscale", "collecting"}
else None
)
active.append(
{"gpu_index": index, "gpu_uuid": gpu_uuid, "state": state, "stage": stage}
)
clean["active_jobs"] = active
elif scheduler.get("state") == "leased":
lease = scheduler.get("lease") or {}
index, gpu_uuid = _int(lease["index"], 0, 1024), lease["uuid"]
if not isinstance(gpu_uuid, str) or not _UUID.fullmatch(gpu_uuid):
raise ValueError
clean["lease"] = {"index": index, "uuid": gpu_uuid}
scheduler = clean
return {
"schema_version": 1,
"monitor": monitor,
"scheduler": scheduler,
"runtime_policy": policy,
}
except (ValueError, TypeError, KeyError, AttributeError, ProviderError, OverflowError):
raise ProviderError(
"invalid_upstream_response", "模型服务返回了无效运行状态。", True
) from None
async def runtime_status(provider: Provider):
cached = getattr(provider, "_runtime_cache", None)
if cached and time.monotonic() - cached[0] < 1:
return json.loads(json.dumps(cached[1]))
async with provider._runtime_lock:
cached = getattr(provider, "_runtime_cache", None)
if cached and time.monotonic() - cached[0] < 1:
return json.loads(json.dumps(cached[1]))
try:
value = await provider._json(
"GET",
_url(provider.settings.inference_base_url, "/runtime/status"),
headers=provider._headers(),
)
result = provider._runtime_value(value)
provider._mirror_runtime_policy(result["runtime_policy"])
observed = time.monotonic()
if getattr(provider.settings, "inference_remote_files", False):
provider.settings._remote_policy_error = result["runtime_policy"][
"configuration_error"
]
if provider.settings._remote_policy_error is None:
provider.settings._remote_policy_observed_at = observed
provider._runtime_cache = (observed, result)
return json.loads(json.dumps(result))
except (ProviderError, asyncio.CancelledError) as exc:
if getattr(provider.settings, "inference_remote_files", False):
provider.settings._remote_policy_error = (
"runtime_policy_invalid"
if isinstance(exc, ProviderError) and exc.code == "invalid_upstream_response"
else "runtime_policy_unavailable"
)
raise
def _mirror_runtime_policy(provider: Provider, policy):
if (
not getattr(provider.settings, "inference_remote_files", False)
or policy["configuration_error"] is not None
):
return
path = confined(
getattr(provider.settings, "runtime_policy_file", None), provider.settings, exists=False
)
payload = {
"schema_version": 1,
"batch_window_enabled": policy["batch_window_enabled"],
"workflow_max_shots": policy["workflow_max_shots"],
}
temporary = path.with_name(path.name + ".part-" + uuid.uuid4().hex)
try:
path.parent.mkdir(parents=True, exist_ok=True)
try:
if path.stat().st_size <= 65536 and json.loads(path.read_bytes()) == payload:
return
except (OSError, ValueError, UnicodeError):
pass
with temporary.open("xb") as handle:
handle.write(json.dumps(payload, allow_nan=False).encode("utf-8"))
handle.flush()
os.fsync(handle.fileno())
os.replace(temporary, path)
except OSError:
raise ProviderError("provider_not_configured", "无法同步模型服务运行策略。", True) from None
finally:
temporary.unlink(missing_ok=True)
async def scheduler_status(provider: Provider):
unavailable = {
"available": False,
"state": "unavailable",
"reason": "GPU状态暂时不可用。",
"gpus": [],
"updated_at": None,
}
try:
remote = bool(getattr(provider.settings, "inference_remote_files", False))
if remote:
runtime = await provider.runtime_status()
data, scheduler = runtime["monitor"], runtime["scheduler"]
else:
path = Path(provider.settings.gpu_status_path)
if path.stat().st_size > 1024 * 1024:
return unavailable
data = json.loads(path.read_bytes())
scheduler = None
now = time.time()
generated = _float(data["generated_at"], 0, now + 1)
if data["schema_version"] != 1 or data.get("error") is not None or now - generated > 5:
return unavailable
seen, gpus = set(), []
for gpu in data["gpus"]:
index = _int(gpu["index"], 0, 1024)
if (
index in seen
or not isinstance(gpu["uuid"], str)
or not _UUID.fullmatch(gpu["uuid"])
):
return unavailable
seen.add(index)
total = _float(gpu["total_gib"], 0.001, 100000)
free = _float(gpu["free_gib"], 0, total)
if remote:
external, own = gpu["external_busy"], gpu["own_busy"]
else:
external, own = gpu["external_pids"], gpu["own_pids"]
if not all(
isinstance(values, list) and all(type(pid) is int and pid > 0 for pid in values)
for values in (external, own)
):
return unavailable
idle = gpu.get("idle_since")
if idle is not None:
idle = _float(idle, 0, now + 1)
busy = bool(external or own)
eligible = not busy and free >= 76 and idle is not None and now - idle >= 15
gpus.append(
{
"index": index,
"name": f"GPU {index}",
"busy": busy,
"eligible": eligible,
"free_gib": free,
"_uuid": gpu["uuid"],
"_own": bool(own),
"state": "external"
if external
else "running"
if own
else "ready"
if eligible
else "waiting",
"stage": None,
}
)
if not remote:
try:
scheduler_path = Path(provider.settings.gpu_scheduler_path)
if scheduler_path.stat().st_size <= 1024 * 1024:
scheduler = json.loads(scheduler_path.read_bytes())
except (OSError, ValueError, TypeError, AttributeError):
pass
from app.domain.gpu_summary import summarize
return summarize(gpus, scheduler, now, generated)
except (OSError, ValueError, TypeError, KeyError, AttributeError, ProviderError, OverflowError):
return unavailable