2026-11-11 10:59:33 +08:00
|
|
|
"""Linux-only singleton FIFO dispatcher with independent per-GPU execution monitors. Run with ``python -m llm_services.worker``.
|
2026-11-10 23:56:50 +08:00
|
|
|
|
|
|
|
|
Never auto-requeue a hard-crashed job. Cooperative GPU preemption requeues only
|
|
|
|
|
after the entire runner group is proven stopped. If a previous running row or runner
|
|
|
|
|
marker remains, verify/stop its processes before an operator repairs state.
|
|
|
|
|
Deleting the lock file or clearing running rows while processes live is unsafe.
|
|
|
|
|
"""
|
|
|
|
|
import json
|
|
|
|
|
import logging
|
|
|
|
|
import os
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
import signal
|
|
|
|
|
import subprocess
|
|
|
|
|
import sys
|
|
|
|
|
import time
|
2026-11-11 10:59:33 +08:00
|
|
|
import threading
|
2026-11-10 23:56:50 +08:00
|
|
|
|
|
|
|
|
from .store import (Settings, atomic_json, confined_path, initialize_store,
|
|
|
|
|
open_confined_file, validate_request)
|
|
|
|
|
from .scheduling import policy_status as execution_policy_status
|
2026-11-14 14:07:26 +08:00
|
|
|
from .reference_profiles import validate_submission as validate_reference_submission
|
2026-11-26 21:06:27 +08:00
|
|
|
from .resources import memory_reservation_gib
|
2026-11-10 23:56:50 +08:00
|
|
|
|
|
|
|
|
LOG = logging.getLogger(__name__)
|
|
|
|
|
_POLICY_FROM_ENV = object()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class WorkerBusy(RuntimeError):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class UnsafeRecovery(RuntimeError):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class AdmissionDeferred(Exception):
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def process_identity(pid):
|
|
|
|
|
"""Linux process start ticks prevent treating a reused PID as the runner."""
|
|
|
|
|
try:
|
|
|
|
|
text = Path(f"/proc/{int(pid)}/stat").read_text()
|
|
|
|
|
except (FileNotFoundError, ProcessLookupError):
|
|
|
|
|
return None
|
|
|
|
|
fields = text[text.rfind(")") + 2:].split()
|
|
|
|
|
if len(fields) < 20:
|
|
|
|
|
raise UnsafeRecovery("Cannot inspect Linux process identity")
|
|
|
|
|
return {"pid": int(pid), "state": fields[0], "pgid": int(fields[2]),
|
|
|
|
|
"start": fields[19]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def group_members(pgid):
|
|
|
|
|
if not Path("/proc/self/stat").is_file():
|
|
|
|
|
raise UnsafeRecovery("A private mounted Linux /proc is required")
|
|
|
|
|
result = []
|
|
|
|
|
for entry in Path("/proc").iterdir():
|
|
|
|
|
if entry.name.isdecimal():
|
|
|
|
|
try:
|
|
|
|
|
identity = process_identity(int(entry.name))
|
|
|
|
|
except PermissionError as exc:
|
|
|
|
|
raise UnsafeRecovery("Cannot verify all runner processes have exited") from exc
|
|
|
|
|
if identity and identity["pgid"] == pgid and identity["state"] not in {"Z", "X"}:
|
|
|
|
|
result.append(identity)
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def existing_runners():
|
|
|
|
|
result = []
|
|
|
|
|
for entry in Path("/proc").iterdir():
|
|
|
|
|
if not entry.name.isdecimal():
|
|
|
|
|
continue
|
|
|
|
|
try:
|
|
|
|
|
args = (entry / "cmdline").read_bytes().split(b"\0")
|
|
|
|
|
except (FileNotFoundError, ProcessLookupError):
|
|
|
|
|
continue
|
|
|
|
|
except PermissionError as exc:
|
|
|
|
|
raise UnsafeRecovery("Cannot inspect existing runner processes") from exc
|
2026-11-26 21:06:27 +08:00
|
|
|
if b"llm_services.runner" in args or b"llm_services.h3_tp2_phase" in args:
|
2026-11-10 23:56:50 +08:00
|
|
|
result.append(int(entry.name))
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Worker:
|
|
|
|
|
def __init__(self, settings=None, *, gpu_policy=_POLICY_FROM_ENV, clock=None):
|
|
|
|
|
self.settings = settings or Settings.from_env()
|
|
|
|
|
self.store = initialize_store(self.settings)
|
|
|
|
|
if gpu_policy is _POLICY_FROM_ENV:
|
|
|
|
|
gpu_policy = None
|
|
|
|
|
if "LLM_GPU_STATUS_PATH" in os.environ:
|
|
|
|
|
from .gpu_policy import GpuPolicy
|
|
|
|
|
gpu_policy = GpuPolicy.from_env()
|
|
|
|
|
self.gpu_policy = gpu_policy
|
2026-11-14 14:07:26 +08:00
|
|
|
from .gpu_reservation import GpuReservation
|
|
|
|
|
self.qwen_reservation = GpuReservation.from_env()
|
2026-11-10 23:56:50 +08:00
|
|
|
self.clock = clock or time.time
|
|
|
|
|
self._lock_fd = None
|
|
|
|
|
self.stop_requested = False
|
|
|
|
|
self._scheduler_snapshot = None
|
2026-11-11 10:59:33 +08:00
|
|
|
self._scheduler_written_at = 0
|
|
|
|
|
self._coordinator_thread = threading.get_ident()
|
|
|
|
|
self._active_lock = threading.RLock()
|
|
|
|
|
self._active = {}
|
2026-11-14 14:07:26 +08:00
|
|
|
self._blocked_jobs = {}
|
2026-11-11 10:59:33 +08:00
|
|
|
self._threads = {}
|
|
|
|
|
self._errors = []
|
|
|
|
|
from .resources import MemoryAdmission
|
|
|
|
|
self.memory_admission = MemoryAdmission(self.settings)
|
2026-11-10 23:56:50 +08:00
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
|
if not sys.platform.startswith("linux"):
|
|
|
|
|
raise RuntimeError("The production worker requires Linux flock and /proc")
|
|
|
|
|
import fcntl
|
|
|
|
|
path = confined_path(self.settings.worker_lock, self.settings.workspace_root)
|
|
|
|
|
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
|
|
|
|
try:
|
|
|
|
|
try:
|
|
|
|
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
|
|
|
except BlockingIOError as exc:
|
|
|
|
|
raise WorkerBusy("Another worker owns the execution slot") from exc
|
|
|
|
|
self._lock_fd = fd
|
|
|
|
|
unresolved = self.store.running()
|
2026-11-11 10:59:33 +08:00
|
|
|
marker_exists = bool(self.settings.active_markers())
|
2026-11-10 23:56:50 +08:00
|
|
|
residual = existing_runners()
|
2026-11-26 21:06:27 +08:00
|
|
|
if unresolved or marker_exists or residual or self.store.active_gpu_uuids():
|
2026-11-10 23:56:50 +08:00
|
|
|
details = [{"job_id": job["id"], "runner_pid": job["runner_pid"],
|
|
|
|
|
"recorded_start": job["runner_start"],
|
|
|
|
|
"current_process": process_identity(job["runner_pid"]) if job["runner_pid"] else None}
|
|
|
|
|
for job in unresolved]
|
|
|
|
|
raise UnsafeRecovery("Interrupted execution; dispatch disabled. Verify old process groups before "
|
|
|
|
|
f"operator recovery: jobs={details}, marker={marker_exists}, runners={residual}")
|
|
|
|
|
return self
|
|
|
|
|
except BaseException:
|
|
|
|
|
self._lock_fd = None
|
|
|
|
|
os.close(fd)
|
|
|
|
|
raise
|
|
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc, traceback):
|
2026-11-11 10:59:33 +08:00
|
|
|
self.shutdown()
|
2026-11-10 23:56:50 +08:00
|
|
|
if self._lock_fd is not None:
|
|
|
|
|
os.close(self._lock_fd)
|
|
|
|
|
self._lock_fd = None
|
|
|
|
|
|
|
|
|
|
def _command(self, request_path, result_path):
|
|
|
|
|
return [self.settings.runner_python, "-m", "llm_services.runner",
|
|
|
|
|
"--request", str(request_path), "--result", str(result_path)]
|
|
|
|
|
|
|
|
|
|
def _terminate_group(self, process, pgid, *, grace_seconds=None):
|
|
|
|
|
# The Popen leader remains unreaped until poll/wait; its PGID cannot be
|
|
|
|
|
# accidentally targeted after reuse while live children are present.
|
|
|
|
|
grace = self.settings.terminate_grace_seconds if grace_seconds is None else min(
|
|
|
|
|
self.settings.terminate_grace_seconds, grace_seconds)
|
|
|
|
|
for sig, wait_seconds in ((signal.SIGTERM, grace),
|
|
|
|
|
(signal.SIGKILL, self.settings.kill_wait_seconds)):
|
|
|
|
|
if group_members(pgid):
|
|
|
|
|
try:
|
|
|
|
|
os.killpg(pgid, sig)
|
|
|
|
|
except ProcessLookupError:
|
|
|
|
|
pass
|
|
|
|
|
deadline = time.monotonic() + wait_seconds
|
|
|
|
|
while time.monotonic() < deadline:
|
|
|
|
|
process.poll()
|
|
|
|
|
if not group_members(pgid):
|
|
|
|
|
process.wait(timeout=self.settings.kill_wait_seconds)
|
|
|
|
|
return
|
|
|
|
|
time.sleep(min(self.settings.poll_seconds, .1, max(0, deadline - time.monotonic())))
|
|
|
|
|
raise UnsafeRecovery("Runner process group did not stop; leaving running record and blocking dispatch")
|
|
|
|
|
|
|
|
|
|
def _publish_scheduler(self, state, *, lease=None, job=None, reason=None):
|
2026-11-11 10:59:33 +08:00
|
|
|
# Monitors update their own entry; only the dispatcher writes the file.
|
|
|
|
|
with self._active_lock:
|
|
|
|
|
if job is not None:
|
|
|
|
|
key = (job['id'], job['attempt_count'])
|
|
|
|
|
if job['state'] == 'running':
|
|
|
|
|
self._active[key] = {'job_id': job['id'], 'attempt_count': job['attempt_count'],
|
|
|
|
|
'gpu_index': lease.get('index') if lease else None,
|
|
|
|
|
'gpu_uuid': lease.get('uuid') if lease else job.get('gpu_uuid'),
|
2026-11-26 21:06:27 +08:00
|
|
|
'gpu_uuids': job.get('gpu_uuids', []),
|
2026-11-11 10:59:33 +08:00
|
|
|
'stage': job['stage'], 'state': state if state in {'preempting', 'blocked'} else
|
|
|
|
|
'launching' if job['stage'] == 'launching' else 'running',
|
|
|
|
|
'reason': reason, 'task_type': job['task_type']}
|
2026-11-26 21:06:27 +08:00
|
|
|
if lease and 'members' in lease:
|
|
|
|
|
self._active[key]['members'] = lease['members']
|
2026-11-11 10:59:33 +08:00
|
|
|
else:
|
|
|
|
|
self._active.pop(key, None)
|
|
|
|
|
if threading.get_ident() != self._coordinator_thread:
|
|
|
|
|
return
|
|
|
|
|
entries = [{k:v for k,v in item.items() if k != 'task_type'} for item in self._active.values()]
|
2026-11-14 14:07:26 +08:00
|
|
|
blocked = [{'job_id': job_id, 'reason': reason}
|
|
|
|
|
for job_id, reason in self._blocked_jobs.items()]
|
2026-11-10 23:56:50 +08:00
|
|
|
try:
|
2026-11-11 10:59:33 +08:00
|
|
|
policy_status = self.gpu_policy.describe() if self.gpu_policy is not None else {'enabled': False}
|
2026-11-10 23:56:50 +08:00
|
|
|
except Exception as exc:
|
2026-11-11 10:59:33 +08:00
|
|
|
policy_status = {'error': f'{type(exc).__name__}: {exc}'}
|
|
|
|
|
waiting = self.store.waiting_summary(now=self.clock())
|
|
|
|
|
payload = {'schema_version': 2, 'active_jobs': entries, 'running_count': len(entries),
|
2026-11-14 14:07:26 +08:00
|
|
|
'blocked_jobs': blocked,
|
2026-11-11 10:59:33 +08:00
|
|
|
'queued_count': waiting['queued'], 'state': 'blocked' if self._errors or state == 'blocked' else
|
|
|
|
|
'running' if entries else 'waiting' if waiting['queued'] else 'idle',
|
|
|
|
|
'reason': reason, 'policy': policy_status, 'worker_pid': os.getpid(),
|
|
|
|
|
'memory': getattr(self.memory_admission, 'last_sample', None),
|
2026-11-14 14:07:26 +08:00
|
|
|
'execution_policy': execution_policy_status(self.clock(), policy_file=self.settings.runtime_policy_file),
|
|
|
|
|
'qwen_reservation': self.qwen_reservation.acknowledgement(
|
|
|
|
|
self.store, self.clock(), unsafe=bool(self._errors) or self.stop_requested,
|
|
|
|
|
is_eligible=self._task_is_eligible)}
|
2026-11-10 23:56:50 +08:00
|
|
|
snapshot = json.dumps(payload, sort_keys=True, allow_nan=False)
|
2026-11-11 10:59:33 +08:00
|
|
|
if snapshot != self._scheduler_snapshot or time.monotonic() - self._scheduler_written_at >= 1:
|
|
|
|
|
atomic_json(confined_path(self.settings.state_dir / 'gpu-scheduler.json', self.settings.workspace_root),
|
|
|
|
|
{**payload, 'updated_at': time.time()})
|
2026-11-10 23:56:50 +08:00
|
|
|
self._scheduler_snapshot = snapshot
|
2026-11-11 10:59:33 +08:00
|
|
|
self._scheduler_written_at = time.monotonic()
|
|
|
|
|
|
2026-11-14 14:07:26 +08:00
|
|
|
def _reference_admission_reason(self, job):
|
|
|
|
|
reason = None
|
2026-11-26 21:06:27 +08:00
|
|
|
if job['task_type'] == 'video.generate':
|
|
|
|
|
try:
|
|
|
|
|
from .video_profiles import validate_submission as validate_generation
|
|
|
|
|
validate_generation(self.settings, job['parameters'])
|
|
|
|
|
except ValueError as exc:
|
|
|
|
|
reason = str(exc)
|
2026-11-14 14:07:26 +08:00
|
|
|
if job['task_type'] == 'image.reference.generate':
|
|
|
|
|
try:
|
|
|
|
|
validate_reference_submission(self.settings, job['input'], job['parameters'])
|
|
|
|
|
except ValueError as exc:
|
|
|
|
|
reason = str(exc)
|
|
|
|
|
if job["task_type"] in {"video.people.analyze", "video.replace"}:
|
|
|
|
|
try:
|
|
|
|
|
from .video_edit.profiles import validate_submission as validate_video
|
|
|
|
|
validate_video(self.settings, job["input"], job["parameters"])
|
|
|
|
|
except (ValueError, OSError) as exc:
|
|
|
|
|
reason = str(exc)
|
|
|
|
|
with self._active_lock:
|
|
|
|
|
if reason:
|
|
|
|
|
self._blocked_jobs[job['id']] = reason
|
|
|
|
|
else:
|
|
|
|
|
self._blocked_jobs.pop(job['id'], None)
|
|
|
|
|
return reason
|
|
|
|
|
|
|
|
|
|
def _task_is_eligible(self, job):
|
|
|
|
|
return self._reference_admission_reason(job) is None
|
|
|
|
|
|
|
|
|
|
def _blocked_reason(self):
|
|
|
|
|
with self._active_lock:
|
|
|
|
|
return next(iter(self._blocked_jobs.values()), None)
|
|
|
|
|
|
2026-11-26 21:06:27 +08:00
|
|
|
@staticmethod
|
|
|
|
|
def _requires_pair(job):
|
|
|
|
|
return (job['task_type'] == 'video.generate'
|
|
|
|
|
and job['parameters'].get('profile') == 'minimax-h3-fl2va-bf16-tp2-v1')
|
|
|
|
|
|
|
|
|
|
def _select_lease(self, queued, eligible):
|
|
|
|
|
size = 2 if self._requires_pair(queued) else 1
|
|
|
|
|
if size == 2 and ((getattr(self.gpu_policy, 'budget_gib', 0) or 0) < 68
|
|
|
|
|
or (getattr(self.gpu_policy, 'reserve_gib', 0) or 0) < 8):
|
|
|
|
|
return None
|
|
|
|
|
occupied = {uuid.lower() for uuid in self.store.active_gpu_uuids()}
|
|
|
|
|
members = []
|
|
|
|
|
for item in eligible:
|
|
|
|
|
uuid = item['uuid'].lower()
|
|
|
|
|
if uuid in occupied or not self.qwen_reservation.allows(item, queued):
|
|
|
|
|
continue
|
|
|
|
|
occupied.add(uuid)
|
|
|
|
|
members.append(item)
|
|
|
|
|
if len(members) == size:
|
|
|
|
|
return dict(members[0], members=members) if size == 2 else members[0]
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _claim_members(lease):
|
|
|
|
|
if lease is None:
|
|
|
|
|
return None
|
|
|
|
|
return [member['uuid'] for member in lease.get('members', [lease])]
|
|
|
|
|
|
2026-11-11 10:59:33 +08:00
|
|
|
def dispatch_once(self):
|
|
|
|
|
if self._lock_fd is None:
|
|
|
|
|
raise RuntimeError('Acquire the worker lock before dispatch')
|
|
|
|
|
for key, thread in list(self._threads.items()):
|
|
|
|
|
if not thread.is_alive():
|
|
|
|
|
thread.join()
|
|
|
|
|
del self._threads[key]
|
|
|
|
|
if self._errors:
|
|
|
|
|
self._publish_scheduler('blocked', reason=str(self._errors[0]))
|
|
|
|
|
raise UnsafeRecovery(str(self._errors[0]))
|
|
|
|
|
reason = None
|
|
|
|
|
dispatched = False
|
2026-11-14 14:07:26 +08:00
|
|
|
with self._active_lock:
|
|
|
|
|
self._blocked_jobs.clear()
|
2026-11-11 10:59:33 +08:00
|
|
|
# Refresh eligible telemetry for each claim, then exclude persistent/local leases.
|
|
|
|
|
while not self.stop_requested and len(self._threads) < self.settings.max_gpu_jobs:
|
2026-11-14 14:07:26 +08:00
|
|
|
queued = self.store.peek_next(now=self.clock(), is_eligible=self._task_is_eligible)
|
2026-11-11 10:59:33 +08:00
|
|
|
if queued is None:
|
2026-11-14 14:07:26 +08:00
|
|
|
reason = self._blocked_reason()
|
2026-11-11 10:59:33 +08:00
|
|
|
break
|
|
|
|
|
if self.gpu_policy is None:
|
|
|
|
|
reason = 'GPU authority is required for parallel dispatch'
|
|
|
|
|
break
|
|
|
|
|
try:
|
|
|
|
|
eligible = self.gpu_policy.describe().get('eligible_gpus', [])
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
reason = f'GPU policy unavailable: {type(exc).__name__}: {exc}'
|
|
|
|
|
break
|
|
|
|
|
running = self.store.running()
|
2026-11-26 21:06:27 +08:00
|
|
|
lease = self._select_lease(queued, eligible)
|
2026-11-11 10:59:33 +08:00
|
|
|
if lease is None:
|
2026-11-26 21:06:27 +08:00
|
|
|
reason = ('TP2 requires two eligible GPUs with the configured memory budget'
|
|
|
|
|
if self._requires_pair(queued) else 'No eligible GPU; busy or stale status')
|
2026-11-11 10:59:33 +08:00
|
|
|
break
|
2026-11-26 21:06:27 +08:00
|
|
|
reservations = [memory_reservation_gib(self.settings, j['task_type'], j['parameters'])
|
|
|
|
|
for j in running]
|
|
|
|
|
reason = self.memory_admission.check(queued['task_type'], reservations,
|
|
|
|
|
parameters=queued['parameters'])
|
2026-11-11 10:59:33 +08:00
|
|
|
if reason:
|
|
|
|
|
break
|
2026-11-26 21:06:27 +08:00
|
|
|
job = self.store.claim_next(gpu_uuids=self._claim_members(lease), now=self.clock(),
|
2026-11-14 14:07:26 +08:00
|
|
|
max_gpu_jobs=self.settings.max_gpu_jobs, expected_job_id=queued['id'],
|
|
|
|
|
is_eligible=self._task_is_eligible)
|
2026-11-11 10:59:33 +08:00
|
|
|
if job is None:
|
|
|
|
|
break
|
|
|
|
|
key = (job['id'], job['attempt_count'])
|
|
|
|
|
launched = threading.Event()
|
|
|
|
|
self._publish_scheduler('running', job=job, lease=lease)
|
|
|
|
|
thread = threading.Thread(target=self._monitor, args=(job, lease, launched),
|
|
|
|
|
name=f'gpu-{job["id"]}-{job["attempt_count"]}', daemon=True)
|
|
|
|
|
self._threads[key] = thread
|
|
|
|
|
thread.start()
|
|
|
|
|
# Spawn order follows claim order. Monitors then execute independently.
|
|
|
|
|
while not launched.wait(.05):
|
|
|
|
|
self._publish_scheduler('running')
|
|
|
|
|
if self.stop_requested:
|
|
|
|
|
break
|
|
|
|
|
dispatched = True
|
|
|
|
|
if self._errors:
|
|
|
|
|
break
|
|
|
|
|
self._publish_scheduler('waiting', reason=reason)
|
|
|
|
|
return dispatched
|
|
|
|
|
|
|
|
|
|
def _monitor(self, job, lease, launched):
|
|
|
|
|
try:
|
|
|
|
|
self._execute(job, lease, launched)
|
|
|
|
|
except BaseException as exc:
|
|
|
|
|
with self._active_lock:
|
|
|
|
|
self._errors.append(exc)
|
|
|
|
|
LOG.exception('Runner monitor failed; operator recovery required')
|
|
|
|
|
finally:
|
|
|
|
|
launched.set()
|
|
|
|
|
|
|
|
|
|
def shutdown(self):
|
|
|
|
|
self.stop_requested = True
|
|
|
|
|
deadline = time.monotonic() + self.settings.terminate_grace_seconds + self.settings.kill_wait_seconds + 5
|
|
|
|
|
for thread in list(self._threads.values()):
|
|
|
|
|
thread.join(timeout=max(0, deadline-time.monotonic()))
|
|
|
|
|
if any(thread.is_alive() for thread in self._threads.values()):
|
|
|
|
|
self._errors.append(UnsafeRecovery('Runner monitors did not stop; retain all recovery evidence'))
|
|
|
|
|
self._publish_scheduler('blocked' if self._errors else 'idle')
|
2026-11-10 23:56:50 +08:00
|
|
|
|
|
|
|
|
def _yield_reason(self, lease):
|
|
|
|
|
if self.gpu_policy is None:
|
|
|
|
|
return None
|
|
|
|
|
try:
|
|
|
|
|
return self.gpu_policy.should_yield(lease)
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
# A stale/unreadable authority cannot justify continuing GPU use.
|
|
|
|
|
return f"GPU policy unavailable: {type(exc).__name__}: {exc}"
|
|
|
|
|
|
|
|
|
|
def _read_manifest(self, result_path):
|
|
|
|
|
confined_path(result_path, self.settings.workspace_root, must_exist=True, file_only=True)
|
|
|
|
|
with open_confined_file(result_path, result_path.parent) as handle:
|
|
|
|
|
raw = handle.read(10 * 1024 * 1024 + 1)
|
|
|
|
|
if len(raw) > 10 * 1024 * 1024:
|
|
|
|
|
raise ValueError("Runner result manifest is too large")
|
|
|
|
|
result = json.loads(raw)
|
|
|
|
|
json.dumps(result, allow_nan=False)
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
def _reported_preemption(self, result_path):
|
|
|
|
|
"""Sticky admission denial survives a subsequently healthy GPU snapshot.
|
|
|
|
|
|
|
|
|
|
Ordinary failures, malformed/oversized files and paths outside this
|
|
|
|
|
attempt are never grounds for automatic retry.
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
result = self._read_manifest(result_path)
|
|
|
|
|
except (OSError, ValueError, TypeError, RecursionError):
|
|
|
|
|
return None
|
|
|
|
|
if not isinstance(result, dict) or result.get("outputs") != []:
|
|
|
|
|
return None
|
|
|
|
|
error, metadata = result.get("error"), result.get("metadata")
|
|
|
|
|
if (not isinstance(error, dict) or error.get("type") != "GpuPreempted"
|
|
|
|
|
or not isinstance(metadata, dict) or metadata.get("completed") is not False):
|
|
|
|
|
return None
|
|
|
|
|
message = error.get("message")
|
|
|
|
|
return message[:2000] if isinstance(message, str) and message.strip() else "Runner reported GPU preemption"
|
|
|
|
|
|
|
|
|
|
def _read_result(self, result_path, output_dir):
|
|
|
|
|
result = self._read_manifest(result_path)
|
|
|
|
|
if not isinstance(result, dict) or not isinstance(result.get("outputs"), list) or not result["outputs"]:
|
|
|
|
|
raise ValueError("Runner must write an object with a nonempty outputs list")
|
|
|
|
|
if result.get("status") in {"failed", "error"}:
|
|
|
|
|
raise ValueError("Runner reported failure")
|
|
|
|
|
outputs = []
|
|
|
|
|
for item in result["outputs"]:
|
|
|
|
|
entry = {"path": item} if isinstance(item, str) else dict(item)
|
|
|
|
|
path = confined_path(entry.get("path", ""), output_dir, must_exist=True, file_only=True)
|
|
|
|
|
with open_confined_file(path, output_dir):
|
|
|
|
|
pass
|
|
|
|
|
entry["path"] = str(path)
|
|
|
|
|
outputs.append(entry)
|
|
|
|
|
result["outputs"] = outputs
|
|
|
|
|
json.dumps(result, allow_nan=False)
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
def run_once(self):
|
|
|
|
|
if self._lock_fd is None:
|
|
|
|
|
raise RuntimeError("Acquire the worker lock before dispatch")
|
2026-11-26 21:06:27 +08:00
|
|
|
if self._errors:
|
|
|
|
|
self._publish_scheduler('blocked', reason=str(self._errors[0]))
|
|
|
|
|
raise UnsafeRecovery(str(self._errors[0]))
|
2026-11-10 23:56:50 +08:00
|
|
|
if self.stop_requested:
|
|
|
|
|
return False
|
2026-11-14 14:07:26 +08:00
|
|
|
with self._active_lock:
|
|
|
|
|
self._blocked_jobs.clear()
|
|
|
|
|
queued = self.store.peek_next(now=self.clock(), is_eligible=self._task_is_eligible)
|
2026-11-10 23:56:50 +08:00
|
|
|
if queued is None:
|
|
|
|
|
waiting = self.store.waiting_summary(now=self.clock())
|
|
|
|
|
self._publish_scheduler("waiting" if waiting["queued"] else "idle",
|
2026-11-14 14:07:26 +08:00
|
|
|
reason=self._blocked_reason() or (
|
|
|
|
|
"Waiting for batch window or manual resume" if waiting["queued"] else None))
|
2026-11-10 23:56:50 +08:00
|
|
|
return False
|
|
|
|
|
lease = None
|
|
|
|
|
if self.gpu_policy is not None:
|
|
|
|
|
try:
|
2026-11-26 21:06:27 +08:00
|
|
|
if self._requires_pair(queued):
|
|
|
|
|
lease = self._select_lease(queued, self.gpu_policy.describe().get('eligible_gpus', []))
|
|
|
|
|
else:
|
|
|
|
|
first = self.gpu_policy.choose()
|
|
|
|
|
lease = self._select_lease(queued, [first]) if first else None
|
|
|
|
|
if first and lease is None:
|
|
|
|
|
lease = self._select_lease(queued, self.gpu_policy.describe().get('eligible_gpus', []))
|
2026-11-10 23:56:50 +08:00
|
|
|
except Exception as exc:
|
|
|
|
|
self._publish_scheduler("waiting", job=queued,
|
|
|
|
|
reason=f"GPU policy unavailable: {type(exc).__name__}: {exc}")
|
|
|
|
|
return False
|
|
|
|
|
if lease is None:
|
|
|
|
|
self._publish_scheduler("waiting", job=queued, reason="No eligible GPU; busy or stale status")
|
|
|
|
|
return False
|
2026-11-26 21:06:27 +08:00
|
|
|
if self._requires_pair(queued):
|
|
|
|
|
if lease is None:
|
|
|
|
|
self._publish_scheduler('waiting', reason='TP2 requires two eligible GPUs')
|
|
|
|
|
return False
|
|
|
|
|
reservations = [memory_reservation_gib(self.settings, j['task_type'], j['parameters'])
|
|
|
|
|
for j in self.store.running()]
|
|
|
|
|
reason = self.memory_admission.check(queued['task_type'], reservations,
|
|
|
|
|
parameters=queued['parameters'])
|
|
|
|
|
if reason:
|
|
|
|
|
self._publish_scheduler('waiting', reason=reason)
|
|
|
|
|
return False
|
|
|
|
|
job = self.store.claim_next(gpu_uuids=self._claim_members(lease), now=self.clock(),
|
|
|
|
|
max_gpu_jobs=self.settings.max_gpu_jobs, expected_job_id=queued['id'], is_eligible=self._task_is_eligible)
|
2026-11-10 23:56:50 +08:00
|
|
|
if job is None:
|
|
|
|
|
return False
|
|
|
|
|
|
2026-11-11 10:59:33 +08:00
|
|
|
return self._execute(job, lease)
|
|
|
|
|
|
|
|
|
|
def _execute(self, job, lease, launched=None):
|
|
|
|
|
marker = self.settings.runner_markers / f"{job['id']}-{job['attempt_count']}.json"
|
2026-11-10 23:56:50 +08:00
|
|
|
process = None
|
|
|
|
|
pgid = None
|
|
|
|
|
clean = False
|
|
|
|
|
state, error, result = "failed", None, None
|
|
|
|
|
preempt_reason = None
|
|
|
|
|
deferred_reason = None
|
|
|
|
|
try:
|
2026-11-14 14:07:26 +08:00
|
|
|
# 最后一个进程入口再验认证,防止选队/claim之后运维关闭或切换版本。
|
|
|
|
|
if reason := self._reference_admission_reason(job):
|
|
|
|
|
raise AdmissionDeferred(reason)
|
2026-11-10 23:56:50 +08:00
|
|
|
# Claim is FULL-synchronous and committed BEFORE spawn. A crash in
|
|
|
|
|
# spawn->PID persistence leaves running/launching and fails closed.
|
2026-11-11 10:59:33 +08:00
|
|
|
atomic_json(marker, {"job_id": job["id"], "phase": "launching",
|
2026-11-10 23:56:50 +08:00
|
|
|
"worker_pid": os.getpid(), "lease": lease,
|
|
|
|
|
"attempt_count": job["attempt_count"]})
|
|
|
|
|
self._publish_scheduler("leased", lease=lease, job=job)
|
|
|
|
|
job_base = self.settings.jobs_dir / job["id"]
|
|
|
|
|
output_base = self.settings.outputs_dir / job["id"]
|
|
|
|
|
suffix = f"attempt-{job['attempt_count']:04d}" if job["attempt_count"] >= 2 else None
|
|
|
|
|
job_dir = confined_path(job_base / suffix if suffix else job_base, self.settings.workspace_root)
|
|
|
|
|
job_dir.mkdir(parents=True, exist_ok=False)
|
|
|
|
|
output_dir = confined_path(output_base / suffix if suffix else output_base, self.settings.workspace_root)
|
|
|
|
|
output_dir.mkdir(parents=True, exist_ok=False)
|
|
|
|
|
inputs, parameters = validate_request(job["task_type"], job["input"], job["parameters"],
|
|
|
|
|
self.settings.workspace_root)
|
|
|
|
|
request_path, result_path = job_dir / "request.json", job_dir / "result.json"
|
|
|
|
|
atomic_json(request_path, {"task_type": job["task_type"], "input": inputs,
|
|
|
|
|
"parameters": parameters, "output_dir": str(output_dir)})
|
|
|
|
|
if self.store.get(job["id"])["cancel_requested"]:
|
|
|
|
|
state, clean = "cancelled", True
|
|
|
|
|
elif not (admission := self.store.admission(job['id'], now=self.clock()))['eligible']:
|
|
|
|
|
# Recheck after IO/validation. No clock check is made once a
|
|
|
|
|
# runner starts: crossing 08:00 drains the existing execution.
|
|
|
|
|
deferred_reason = admission['reason']
|
|
|
|
|
clean = True
|
|
|
|
|
elif (preempt_reason := self._yield_reason(lease)):
|
|
|
|
|
# The authority may change between selection and launch. No
|
|
|
|
|
# runner exists yet, so this attempt is already safe to yield.
|
|
|
|
|
clean = True
|
|
|
|
|
else:
|
|
|
|
|
environment = os.environ.copy()
|
2026-11-26 21:06:27 +08:00
|
|
|
environment.pop("LLM_GPU_LEASE_MEMBERS", None)
|
2026-11-11 10:59:33 +08:00
|
|
|
for name in ('OMP_NUM_THREADS', 'MKL_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'NUMEXPR_NUM_THREADS'):
|
|
|
|
|
environment[name] = str(self.settings.cpu_threads_per_job)
|
2026-11-10 23:56:50 +08:00
|
|
|
environment["APP_ROOT"] = str(self.settings.app_root)
|
|
|
|
|
environment["WORKSPACE_ROOT"] = str(self.settings.workspace_root)
|
|
|
|
|
environment["PYTHONPATH"] = str(self.settings.app_root)
|
|
|
|
|
if self.gpu_policy is not None:
|
|
|
|
|
environment.update(self.gpu_policy.environment(lease))
|
|
|
|
|
with (job_dir / "runner.log").open("xb") as log:
|
|
|
|
|
command = self._command(request_path, result_path)
|
2026-11-26 21:06:27 +08:00
|
|
|
if job['task_type'] == 'video.generate':
|
|
|
|
|
from .video_profiles import is_h3
|
|
|
|
|
if self._requires_pair(job):
|
|
|
|
|
command[0] = self.settings.video_generation_tp2_python
|
|
|
|
|
elif is_h3(parameters):
|
|
|
|
|
command[0] = self.settings.video_generation_python
|
2026-11-14 14:07:26 +08:00
|
|
|
if job["task_type"] in {"video.people.analyze", "video.replace"}:
|
|
|
|
|
from .video_edit.bindings import principal, analysis_manifest
|
|
|
|
|
command[0] = self.settings.video_edit_python
|
|
|
|
|
environment["VIDEO_EDIT_PRINCIPAL"] = principal(self.settings, job.get("scheduling"))
|
|
|
|
|
if job["task_type"] == "video.replace":
|
|
|
|
|
environment["VIDEO_EDIT_MANIFEST"] = analysis_manifest(self.settings, self.store, inputs, parameters, environment["VIDEO_EDIT_PRINCIPAL"])
|
2026-11-10 23:56:50 +08:00
|
|
|
admission = self.store.admission(job['id'], now=self.clock())
|
|
|
|
|
if not admission['eligible']:
|
|
|
|
|
raise AdmissionDeferred(admission['reason'])
|
2026-11-14 14:07:26 +08:00
|
|
|
if reason := self._reference_admission_reason(job):
|
|
|
|
|
raise AdmissionDeferred(reason)
|
2026-11-26 21:06:27 +08:00
|
|
|
if lease and any(not self.qwen_reservation.allows(m, job)
|
|
|
|
|
for m in lease.get('members', [lease])):
|
|
|
|
|
raise AdmissionDeferred("Reserved GPU cannot start this attempt")
|
2026-11-10 23:56:50 +08:00
|
|
|
process = subprocess.Popen(command,
|
|
|
|
|
cwd=self.settings.app_root, env=environment,
|
|
|
|
|
stdin=subprocess.DEVNULL, stdout=log, stderr=log,
|
|
|
|
|
start_new_session=True, close_fds=True)
|
|
|
|
|
pgid = process.pid
|
|
|
|
|
identity = process_identity(process.pid)
|
2026-11-11 10:59:33 +08:00
|
|
|
self.store.set_runner(job["id"], process.pid, identity["start"] if identity else None, pgid, attempt_count=job["attempt_count"])
|
|
|
|
|
atomic_json(marker, {"job_id": job["id"], "phase": "executing",
|
2026-11-10 23:56:50 +08:00
|
|
|
"runner_pid": process.pid, "runner_start": identity["start"] if identity else None,
|
|
|
|
|
"pgid": pgid, "worker_pid": os.getpid(), "lease": lease,
|
|
|
|
|
"attempt_count": job["attempt_count"]})
|
2026-11-11 10:59:33 +08:00
|
|
|
self._publish_scheduler('running', lease=lease, job=self.store.get(job['id']))
|
|
|
|
|
if launched is not None:
|
|
|
|
|
launched.set()
|
2026-11-10 23:56:50 +08:00
|
|
|
deadline = time.monotonic() + job["timeout_seconds"]
|
|
|
|
|
while True:
|
|
|
|
|
current = self.store.get(job["id"])
|
2026-11-11 10:59:33 +08:00
|
|
|
if current is None or current["state"] != "running" or current["attempt_count"] != job["attempt_count"]:
|
2026-11-10 23:56:50 +08:00
|
|
|
raise UnsafeRecovery("Running job state changed outside the worker")
|
|
|
|
|
if current["cancel_requested"] or self.stop_requested:
|
|
|
|
|
if current["cancel_requested"]:
|
|
|
|
|
state, error = "cancelled", "Cancellation requested"
|
|
|
|
|
else:
|
|
|
|
|
state, error = "failed", "Worker stopped during execution"
|
|
|
|
|
self._terminate_group(process, pgid)
|
|
|
|
|
break
|
|
|
|
|
# Check authority even if the process already exited:
|
|
|
|
|
# the host guard may have killed it for external use.
|
|
|
|
|
preempt_reason = self._yield_reason(lease)
|
2026-11-26 21:06:27 +08:00
|
|
|
if not preempt_reason and self._requires_pair(job) and process.poll() is None:
|
|
|
|
|
pressure = self.memory_admission.running_pressure()
|
|
|
|
|
if pressure and process.poll() is None:
|
|
|
|
|
preempt_reason = pressure
|
2026-11-10 23:56:50 +08:00
|
|
|
if preempt_reason:
|
|
|
|
|
self._publish_scheduler("preempting", lease=lease, job=job, reason=preempt_reason)
|
|
|
|
|
self._terminate_group(process, pgid, grace_seconds=2)
|
|
|
|
|
break
|
|
|
|
|
if process.poll() is not None:
|
|
|
|
|
break
|
|
|
|
|
if time.monotonic() >= deadline:
|
|
|
|
|
state, error = "timed_out", "Execution timeout exceeded"
|
|
|
|
|
self._terminate_group(process, pgid)
|
|
|
|
|
break
|
|
|
|
|
time.sleep(min(self.settings.poll_seconds, .2) if self.gpu_policy is not None
|
|
|
|
|
else self.settings.poll_seconds)
|
|
|
|
|
if (not preempt_reason and state != "cancelled" and not self.stop_requested
|
|
|
|
|
and process.poll() is not None and process.returncode != 0):
|
|
|
|
|
# Admission may see a transient foreign process that is
|
|
|
|
|
# already gone by our next policy read. Preserve the
|
|
|
|
|
# runner's explicit typed denial before cleaning children.
|
|
|
|
|
preempt_reason = self._reported_preemption(result_path)
|
|
|
|
|
if group_members(pgid):
|
|
|
|
|
self._terminate_group(process, pgid, grace_seconds=2 if preempt_reason else None)
|
|
|
|
|
if not preempt_reason and error is None:
|
|
|
|
|
state, error = "failed", "Runner exited while child processes were still executing"
|
|
|
|
|
process.wait(timeout=self.settings.kill_wait_seconds)
|
|
|
|
|
clean = not group_members(pgid)
|
|
|
|
|
if error is None and not preempt_reason:
|
|
|
|
|
if self.store.get(job["id"])["cancel_requested"]:
|
|
|
|
|
state, error = "cancelled", "Cancellation requested"
|
|
|
|
|
elif (preempt_reason := self._yield_reason(lease)):
|
|
|
|
|
pass
|
|
|
|
|
elif process.returncode != 0:
|
|
|
|
|
state, error = "failed", f"Runner exited with code {process.returncode}; see runner.log"
|
|
|
|
|
else:
|
|
|
|
|
result = self._read_result(result_path, output_dir)
|
|
|
|
|
state = "succeeded"
|
|
|
|
|
except AdmissionDeferred as exc:
|
|
|
|
|
deferred_reason, clean = str(exc), True
|
|
|
|
|
except BaseException as exc:
|
|
|
|
|
if process is not None:
|
|
|
|
|
if preempt_reason is None:
|
|
|
|
|
preempt_reason = self._yield_reason(lease)
|
|
|
|
|
self._terminate_group(process, pgid, grace_seconds=2 if preempt_reason else None)
|
|
|
|
|
clean = not group_members(pgid)
|
|
|
|
|
else:
|
|
|
|
|
clean = True
|
|
|
|
|
if isinstance(exc, (KeyboardInterrupt, SystemExit, UnsafeRecovery)):
|
|
|
|
|
raise
|
|
|
|
|
state, error = "failed", f"{type(exc).__name__}: {exc}"
|
|
|
|
|
LOG.exception("Job %s failed", job["id"])
|
|
|
|
|
finally:
|
|
|
|
|
if not clean:
|
|
|
|
|
# Including an unexpected Python exception: do not release the
|
|
|
|
|
# slot as healthy while a runner could still be using the GPU.
|
|
|
|
|
LOG.error("Job %s remains unresolved; operator recovery required", job["id"])
|
|
|
|
|
try:
|
|
|
|
|
self._publish_scheduler("blocked", lease=lease, job=job,
|
|
|
|
|
reason="Cannot prove complete runner exit; operator recovery required")
|
|
|
|
|
except Exception:
|
|
|
|
|
LOG.exception("Cannot publish blocked GPU scheduler state")
|
|
|
|
|
if not clean:
|
|
|
|
|
raise UnsafeRecovery("Cannot prove runner exit; stopping worker")
|
|
|
|
|
if process is not None and not preempt_reason and state != "cancelled" and not self.stop_requested:
|
|
|
|
|
# A host guard can race process exit or error-manifest handling.
|
|
|
|
|
# Re-read authority once more before committing any final outcome.
|
|
|
|
|
preempt_reason = self._yield_reason(lease)
|
|
|
|
|
if deferred_reason:
|
|
|
|
|
self.store.defer_unlaunched(job["id"], job["attempt_count"], deferred_reason)
|
|
|
|
|
elif preempt_reason:
|
2026-11-11 10:59:33 +08:00
|
|
|
self.store.requeue_preempted(job["id"], preempt_reason, attempt_count=job["attempt_count"])
|
2026-11-10 23:56:50 +08:00
|
|
|
else:
|
2026-11-11 10:59:33 +08:00
|
|
|
self.store.finish(job["id"], state, result=result, error=error, attempt_count=job["attempt_count"])
|
|
|
|
|
marker.unlink(missing_ok=True)
|
|
|
|
|
# A freed GPU may already have claimed the next attempt. Remove only
|
|
|
|
|
# this monitor's entry; never publish a fresh DB row using an old lease.
|
|
|
|
|
with self._active_lock:
|
|
|
|
|
self._active.pop((job['id'], job['attempt_count']), None)
|
2026-11-14 14:07:26 +08:00
|
|
|
self._publish_scheduler('idle', reason=deferred_reason or preempt_reason or error)
|
2026-11-10 23:56:50 +08:00
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
def run_forever(self):
|
|
|
|
|
def stop(signum, frame):
|
|
|
|
|
self.stop_requested = True
|
|
|
|
|
previous = {sig: signal.signal(sig, stop) for sig in (signal.SIGTERM, signal.SIGINT)}
|
|
|
|
|
try:
|
|
|
|
|
with self:
|
|
|
|
|
while not self.stop_requested:
|
2026-11-11 10:59:33 +08:00
|
|
|
if not self.dispatch_once():
|
2026-11-10 23:56:50 +08:00
|
|
|
time.sleep(self.settings.poll_seconds)
|
|
|
|
|
finally:
|
|
|
|
|
for sig, handler in previous.items():
|
|
|
|
|
signal.signal(sig, handler)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
|
|
|
|
try:
|
|
|
|
|
Worker().run_forever()
|
|
|
|
|
except (WorkerBusy, UnsafeRecovery) as exc:
|
|
|
|
|
LOG.error("%s", exc)
|
|
|
|
|
return 2
|
|
|
|
|
return 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
raise SystemExit(main())
|