"""Linux-only single execution slot. 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 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 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 = self.settings.runner_marker.exists() or self.settings.runner_marker.is_symlink() 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): 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): 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}"} payload = {"state": state, "lease": lease, "job_id": job["id"] if job else None, "attempt_count": job["attempt_count"] if job else None, "reason": reason, "policy": policy_status, "worker_pid": os.getpid(), "execution_policy": execution_policy_status(self.clock())} snapshot = json.dumps(payload, sort_keys=True, allow_nan=False) if snapshot != self._scheduler_snapshot: atomic_json(confined_path(self.settings.state_dir / "gpu-scheduler.json", self.settings.workspace_root), {**payload, "updated_at": time.time()}) self._scheduler_snapshot = snapshot 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 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(self.settings.runner_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() 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) atomic_json(self.settings.runner_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"]}) deadline = time.monotonic() + job["timeout_seconds"] while True: current = self.store.get(job["id"]) if current is None or current["state"] != "running": 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) else: self.store.finish(job["id"], state, result=result, error=error) self.settings.runner_marker.unlink(missing_ok=True) current = self.store.get(job["id"]) self._publish_scheduler(current["state"], job=current, 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.run_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())