cmvr-visual/inference/llm_services/gpu_reservation.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

83 lines
3.6 KiB
Python

"""只约束新任务准入的跨容器交接;预约不能使正在执行的任务让卡。"""
from __future__ import annotations
import json
import os
from pathlib import Path
import re
class GpuReservation:
def __init__(self, path=None, gpu_uuid=None):
self.path = Path(path) if path else None
self.gpu_uuid = gpu_uuid or ''
self._token = None
self._quiesced = False
@classmethod
def from_env(cls):
return cls(os.environ.get('LLM_QWEN_RESERVATION_PATH'),
os.environ.get('LLM_QWEN_GPU_UUID'))
def read(self):
if self.path is None:
return None, None
try:
if not self.path.is_absolute() or not self.gpu_uuid:
raise ValueError('Absolute reservation path and GPU UUID are required')
with self.path.open('rb') as handle:
raw = handle.read(4097)
if len(raw) > 4096:
raise ValueError('Reservation exceeds size limit')
value = json.loads(raw)
if (not isinstance(value, dict) or set(value) != {
'schema_version', 'gpu_uuid', 'token', 'hold', 'queue_seq_cutoff'}
or type(value['schema_version']) is not int or value['schema_version'] != 1
or value['gpu_uuid'] != self.gpu_uuid
or not isinstance(value['token'], str)
or re.fullmatch(r'[0-9a-f]{32}', value['token']) is None
or type(value['hold']) is not bool
or type(value['queue_seq_cutoff']) is not int or value['queue_seq_cutoff'] < 0):
raise ValueError('Invalid GPU reservation')
if self._token != value['token']:
self._token, self._quiesced = value['token'], False
return value, None
except (OSError, ValueError, TypeError, RecursionError) as exc:
# 配置启用后读取失败只封锁目标卡;不能因文件消失而自动放行。
return None, str(exc)
def allows(self, lease, job):
if self.path is None or lease['uuid'].lower() != self.gpu_uuid.lower():
return True
value, error = self.read()
if error:
return False
if not value['hold']:
return True
return not self._quiesced and job['queue_seq'] <= value['queue_seq_cutoff']
def acknowledgement(self, store, now, *, unsafe=False, is_eligible=None):
value, error = self.read()
if self.path is None:
return {'enabled': False, 'quiesced': False}
status = {'enabled': True, 'gpu_uuid': self.gpu_uuid, 'token': None,
'hold': True, 'quiesced': False, 'reason': error}
if error:
return status
status.update(token=value['token'], hold=value['hold'], queue_seq_cutoff=value['queue_seq_cutoff'])
if not value['hold']:
self._quiesced = False
return status
running = any((job.get('gpu_uuid') or '').lower() == self.gpu_uuid.lower()
for job in store.running())
earlier = store.peek_next(now=now, is_eligible=lambda job:
job['queue_seq'] <= value['queue_seq_cutoff']
and (is_eligible is None or is_eligible(job)))
if unsafe or running:
self._quiesced = False
elif earlier is None:
# 同 token 一旦确认就保持封锁,防止稍后开放的批次重新领取此卡。
self._quiesced = True
status['quiesced'] = self._quiesced and not unsafe and not running
return status