cmvr-visual/inference/llm_services/worker.py

544 lines
27 KiB
Python

"""Linux-only singleton FIFO dispatcher with independent per-GPU execution monitors. Run with ``python -m llm_services.worker``.
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
import threading
from .store import (Settings, atomic_json, confined_path, initialize_store,
open_confined_file, validate_request)
from .scheduling import policy_status as execution_policy_status
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
if b"llm_services.runner" in args:
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
self.clock = clock or time.time
self._lock_fd = None
self.stop_requested = False
self._scheduler_snapshot = None
self._scheduler_written_at = 0
self._coordinator_thread = threading.get_ident()
self._active_lock = threading.RLock()
self._active = {}
self._threads = {}
self._errors = []
from .resources import MemoryAdmission
self.memory_admission = MemoryAdmission(self.settings)
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()
marker_exists = bool(self.settings.active_markers())
residual = existing_runners()
if unresolved or marker_exists or residual:
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):
self.shutdown()
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):
# 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'),
'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']}
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()]
try:
policy_status = self.gpu_policy.describe() if self.gpu_policy is not None else {'enabled': False}
except Exception as exc:
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),
'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),
'execution_policy': execution_policy_status(self.clock(), policy_file=self.settings.runtime_policy_file)}
snapshot = json.dumps(payload, sort_keys=True, allow_nan=False)
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()})
self._scheduler_snapshot = snapshot
self._scheduler_written_at = time.monotonic()
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
# 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:
queued = self.store.peek_next(now=self.clock())
if queued is None:
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()
occupied = {j['gpu_uuid'].lower() for j in running if j['gpu_uuid']}
lease = next((item for item in eligible if item['uuid'].lower() not in occupied), None)
if lease is None:
reason = 'No eligible GPU; busy or stale status'
break
reservations = [self.settings.memory_estimates_gib[j['task_type']] for j in running]
reason = self.memory_admission.check(queued['task_type'], reservations)
if reason:
break
job = self.store.claim_next(gpu_uuid=lease['uuid'], now=self.clock(),
max_gpu_jobs=self.settings.max_gpu_jobs, expected_job_id=queued['id'])
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')
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")
if self.stop_requested:
return False
queued = self.store.peek_next(now=self.clock())
if queued is None:
waiting = self.store.waiting_summary(now=self.clock())
self._publish_scheduler("waiting" if waiting["queued"] else "idle",
reason="Waiting for batch window or manual resume" if waiting["queued"] else None)
return False
lease = None
if self.gpu_policy is not None:
try:
lease = self.gpu_policy.choose()
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
job = self.store.claim_next(gpu_uuid=lease["uuid"] if lease else None, now=self.clock())
if job is None:
return False
return self._execute(job, lease)
def _execute(self, job, lease, launched=None):
marker = self.settings.runner_markers / f"{job['id']}-{job['attempt_count']}.json"
process = None
pgid = None
clean = False
state, error, result = "failed", None, None
preempt_reason = None
deferred_reason = None
try:
# Claim is FULL-synchronous and committed BEFORE spawn. A crash in
# spawn->PID persistence leaves running/launching and fails closed.
atomic_json(marker, {"job_id": job["id"], "phase": "launching",
"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()
for name in ('OMP_NUM_THREADS', 'MKL_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'NUMEXPR_NUM_THREADS'):
environment[name] = str(self.settings.cpu_threads_per_job)
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)
admission = self.store.admission(job['id'], now=self.clock())
if not admission['eligible']:
raise AdmissionDeferred(admission['reason'])
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)
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",
"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"]})
self._publish_scheduler('running', lease=lease, job=self.store.get(job['id']))
if launched is not None:
launched.set()
deadline = time.monotonic() + job["timeout_seconds"]
while True:
current = self.store.get(job["id"])
if current is None or current["state"] != "running" or current["attempt_count"] != job["attempt_count"]:
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)
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:
self.store.requeue_preempted(job["id"], preempt_reason, attempt_count=job["attempt_count"])
else:
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)
self._publish_scheduler('idle', reason=preempt_reason or error)
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:
if not self.dispatch_once():
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())