Spaces:
Running on Zero
Running on Zero
Download stemdeck/jobrunner.py from AnjaneyaTurai/stemdeck-gpu: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/spaces/AnjaneyaTurai/stemdeck-gpu/resolve/main/stemdeck/jobrunner.py
- Command line
-
hf download hf://spaces/AnjaneyaTurai/stemdeck-gpu/stemdeck/jobrunner.py
-
curl -L -o jobrunner.py https://huggingface.co/spaces/AnjaneyaTurai/stemdeck-gpu/resolve/main/stemdeck/jobrunner.py
13.5 kB
| """Single-slot job queue: one worker process at a time (one GPU), FIFO, cancellable by killing it. | |
| Workers are started detached (see stemdeck.detach), so they keep running when this server restarts or its | |
| terminal closes. Each tick, a runner that is not watching a worker first looks for 'running' jobs: one whose | |
| worker is still alive is adopted and watched as if this runner had started it; one whose worker is gone is | |
| marked interrupted. Only then is the next queued job launched. | |
| """ | |
| from __future__ import annotations | |
| import contextlib | |
| import logging | |
| import os | |
| import sys | |
| import threading | |
| import time | |
| from dataclasses import dataclass | |
| from datetime import UTC, datetime | |
| import psutil | |
| from sqlalchemy.exc import SQLAlchemyError | |
| from sqlmodel import Session, col, select | |
| from stemdeck.db import get_engine | |
| from stemdeck.detach import SpawnError, spawn_detached | |
| from stemdeck.models import TERMINAL_JOB_STATUSES, Job, Song, utcnow | |
| from stemdeck.settings import PROJECT_ROOT, details_hint, get_settings | |
| log = logging.getLogger(__name__) | |
| POLL_INTERVAL_SEC = 0.5 | |
| HUNG_EXIT_GRACE_SEC = 15.0 # a worker that recorded its outcome this long ago but is still alive gets killed | |
| KILL_WAIT_SEC = 10.0 | |
| # A job is claimed ('running', no pid) just before its worker starts; until this has passed, a missing pid means | |
| # "still starting", not "gone". The worker records its own pid within seconds of starting. | |
| STARTUP_GRACE_SEC = 60.0 | |
| # The worker process is created at most this long after its job's recorded start time (pid-reuse guard). | |
| CREATE_TIME_SLACK_SEC = 30.0 | |
| BACKEND_DIR = PROJECT_ROOT / "backend" | |
| WORKER_MODULE = "stemdeck.worker" | |
| INTERRUPTED_ERROR = "Interrupted: the processing worker stopped while the server was restarting. Press Retry." | |
| def crashed_error() -> str: | |
| return f"The processing worker stopped unexpectedly. Please retry. {details_hint('worker.log')}" | |
| def spawn_failed_error() -> str: | |
| return f"Could not start the processing worker. Please retry. {details_hint('server.log')}" | |
| class WorkerHandle: | |
| job_id: str | |
| process: psutil.Process | |
| # ---------------------------------------------------------------------- process helpers | |
| def is_alive(process: psutil.Process) -> bool: | |
| try: | |
| return process.is_running() and process.status() != psutil.STATUS_ZOMBIE | |
| except psutil.NoSuchProcess: | |
| return False | |
| except psutil.AccessDenied: | |
| return True # it exists; we just may not inspect it | |
| def _as_utc(moment: datetime) -> datetime: | |
| return moment if moment.tzinfo else moment.replace(tzinfo=UTC) | |
| def _created_by(process: psutil.Process, started_at: datetime | None) -> bool: | |
| """True when the process existed by the time the job started (so it is not a later, recycled pid).""" | |
| if started_at is None: | |
| return False | |
| try: | |
| return process.create_time() <= _as_utc(started_at).timestamp() + CREATE_TIME_SLACK_SEC | |
| except psutil.Error: | |
| return False | |
| def find_worker(pid: int | None, job_id: str, started_at: datetime | None) -> psutil.Process | None: | |
| """The live worker process for `job_id`, or None. The command line must name the job, so a recycled pid | |
| (an unrelated process after a reboot) is never mistaken for the worker; when the command line cannot be | |
| read, the process's creation time is checked against the job's start instead.""" | |
| if pid is None: | |
| return None | |
| try: | |
| process = psutil.Process(pid) | |
| except psutil.Error: | |
| return None | |
| try: | |
| cmdline = process.cmdline() | |
| except psutil.NoSuchProcess: | |
| return None | |
| except psutil.AccessDenied: | |
| return process if is_alive(process) and _created_by(process, started_at) else None | |
| if WORKER_MODULE in cmdline and job_id in cmdline and is_alive(process): | |
| return process | |
| return None | |
| def _still_starting(job: Job) -> bool: | |
| """Claimed moments ago and its worker has not written a pid yet.""" | |
| if job.pid is not None or job.started_at is None: | |
| return False | |
| return (utcnow() - _as_utc(job.started_at)).total_seconds() < STARTUP_GRACE_SEC | |
| def kill_tree(process: psutil.Process) -> None: | |
| """Kill a worker and everything it started (the SAM runner, ffmpeg, the venv launcher's child).""" | |
| try: | |
| victims = [*process.children(recursive=True), process] | |
| except psutil.NoSuchProcess: | |
| return | |
| for victim in victims: | |
| with contextlib.suppress(psutil.NoSuchProcess): # already gone is fine | |
| victim.kill() | |
| psutil.wait_procs(victims, timeout=KILL_WAIT_SEC) | |
| # ---------------------------------------------------------------------- job row helpers | |
| def _fail_job(session: Session, job: Job, message: str) -> None: | |
| job.status, job.stage = "failed", "failed" | |
| job.error = message | |
| job.eta_sec = None | |
| job.finished_at = utcnow() | |
| session.add(job) | |
| if job.type == "split": | |
| song = session.get(Song, job.song_id) | |
| if song is not None and song.status != "ready": | |
| song.status = "failed" | |
| session.add(song) | |
| def _claim(job_id: str) -> None: | |
| """Mark the job running before its worker exists, so a server restart can never launch it twice.""" | |
| with Session(get_engine()) as session: | |
| job = session.get(Job, job_id) | |
| if job is None: | |
| return | |
| job.status, job.pid, job.started_at, job.error = "running", None, utcnow(), None | |
| session.add(job) | |
| session.commit() | |
| def _record_pid(job_id: str, pid: int) -> None: | |
| with Session(get_engine()) as session: | |
| job = session.get(Job, job_id) | |
| if job is not None and job.pid is None: # the worker may already have written its own pid | |
| job.pid = pid | |
| session.add(job) | |
| session.commit() | |
| class JobRunner: | |
| def __init__(self) -> None: | |
| self._lock = threading.Lock() | |
| self._current: WorkerHandle | None = None | |
| self._stop = threading.Event() | |
| self._thread = threading.Thread(target=self._loop, name="job-runner", daemon=True) | |
| # ------------------------------------------------------------------ lifecycle | |
| def start(self) -> None: | |
| self._thread.start() | |
| def stop(self) -> None: | |
| """Stop watching. A running worker is deliberately left alone: it records its own outcome in the | |
| database, and the next server start adopts it.""" | |
| self._stop.set() | |
| if self._current is not None: | |
| log.info("server stopping; job %s keeps running in pid %s", self._current.job_id, | |
| self._current.process.pid) | |
| def current_job_id(self) -> str | None: | |
| current = self._current | |
| return current.job_id if current else None | |
| # ------------------------------------------------------------------ queue loop | |
| def _loop(self) -> None: | |
| while not self._stop.is_set(): | |
| try: | |
| self._tick() | |
| except Exception: # noqa: BLE001 - keep the runner alive no matter what | |
| log.exception("job runner tick failed") | |
| time.sleep(POLL_INTERVAL_SEC) | |
| def _tick(self) -> None: | |
| with self._lock: | |
| if self._current is not None and not self._reap_current(): | |
| return | |
| if self._adopt_running_job(): | |
| return | |
| job_id = self._next_queued() | |
| if job_id is not None: | |
| self._current = self._launch(job_id) | |
| def _reap_current(self) -> bool: | |
| """True once the watched worker has ended and its job has been finalised.""" | |
| assert self._current is not None | |
| handle = self._current | |
| alive = is_alive(handle.process) | |
| if alive and self._outcome_recorded_long_ago(handle.job_id): | |
| log.warning("worker for job %s finished but did not exit; killing it", handle.job_id) | |
| kill_tree(handle.process) | |
| alive = False | |
| if alive: | |
| return False | |
| self._finish(handle.job_id) | |
| self._current = None | |
| return True | |
| def _adopt_running_job(self) -> bool: | |
| """Watch a 'running' job nobody is watching (left by a previous server) or mark it interrupted. | |
| Returns True while such a job exists, so no second worker is launched next to it.""" | |
| adopted: WorkerHandle | None = None | |
| starting = False | |
| with Session(get_engine()) as session: | |
| jobs = session.exec(select(Job).where(Job.status == "running").order_by(col(Job.started_at))).all() | |
| for job in jobs: | |
| process = find_worker(job.pid, job.id, job.started_at) | |
| if process is not None: | |
| adopted = adopted or WorkerHandle(job.id, process) | |
| elif _still_starting(job): | |
| starting = True # its worker should report a pid shortly; look again next tick | |
| else: | |
| log.warning("job %s was running but its worker (pid %s) is gone", job.id, job.pid) | |
| _fail_job(session, job, INTERRUPTED_ERROR) | |
| session.commit() | |
| if adopted is None: | |
| return starting | |
| log.info("adopted running job %s (worker pid %s)", adopted.job_id, adopted.process.pid) | |
| self._current = adopted | |
| return True | |
| def _outcome_recorded_long_ago(job_id: str) -> bool: | |
| """True when the job already has a terminal status for a while (its worker is hung on exit).""" | |
| with Session(get_engine()) as session: | |
| job = session.get(Job, job_id) | |
| if job is None or job.status not in TERMINAL_JOB_STATUSES or job.finished_at is None: | |
| return False | |
| return (utcnow() - _as_utc(job.finished_at)).total_seconds() > HUNG_EXIT_GRACE_SEC | |
| def _next_queued() -> str | None: | |
| with Session(get_engine()) as session: | |
| job = session.exec(select(Job).where(Job.status == "queued").order_by(col(Job.created_at))).first() | |
| return job.id if job else None | |
| def _launch(self, job_id: str) -> WorkerHandle | None: | |
| settings = get_settings() | |
| env = {**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"} | |
| # First GPU use JIT-compiles kernels for this card (~1-2 min); a larger cache keeps them for later runs. | |
| env.setdefault("CUDA_CACHE_MAXSIZE", str(4 * 1024**3)) | |
| _claim(job_id) | |
| try: | |
| pid = spawn_detached([sys.executable, "-m", WORKER_MODULE, job_id], cwd=BACKEND_DIR, env=env, | |
| log_path=settings.logs_dir / "worker-stdout.log") | |
| except SpawnError: | |
| log.exception("could not start the worker for job %s", job_id) | |
| with Session(get_engine()) as session: | |
| job = session.get(Job, job_id) | |
| if job is not None: | |
| _fail_job(session, job, spawn_failed_error()) | |
| session.commit() | |
| return None | |
| try: | |
| _record_pid(job_id, pid) | |
| except SQLAlchemyError: # the worker writes its own pid too; never lose the handle over this | |
| log.exception("could not record pid %s for job %s", pid, job_id) | |
| log.info("started job %s in pid %s", job_id, pid) | |
| try: | |
| return WorkerHandle(job_id, psutil.Process(pid)) | |
| except psutil.NoSuchProcess: # it already exited; record a crash unless it stored an outcome | |
| self._finish(job_id) | |
| return None | |
| def _finish(job_id: str) -> None: | |
| with Session(get_engine()) as session: | |
| job = session.get(Job, job_id) | |
| if job is None or job.status in TERMINAL_JOB_STATUSES: | |
| return | |
| # The worker died without recording an outcome (hard crash / killed by the OS). | |
| _fail_job(session, job, crashed_error()) | |
| session.commit() | |
| log.warning("job %s worker exited without finishing", job_id) | |
| # ------------------------------------------------------------------ public API | |
| def cancel(self, job_id: str) -> None: | |
| with self._lock: | |
| if self._current is not None and self._current.job_id == job_id: | |
| kill_tree(self._current.process) | |
| self._current = None | |
| with Session(get_engine()) as session: | |
| job = session.get(Job, job_id) | |
| if job is None or job.status in TERMINAL_JOB_STATUSES: | |
| return | |
| if job.status == "running": # a worker this runner has not adopted yet | |
| process = find_worker(job.pid, job.id, job.started_at) | |
| if process is not None: | |
| kill_tree(process) | |
| job.status, job.stage = "cancelled", "cancelled" | |
| job.finished_at = utcnow() | |
| job.eta_sec = None | |
| session.add(job) | |
| if job.type == "split": | |
| song = session.get(Song, job.song_id) | |
| if song is not None and song.status != "ready": | |
| song.status = "failed" | |
| session.add(song) | |
| session.commit() | |
| def queue_position(session: Session, job: Job) -> int: | |
| if job.status != "queued": | |
| return 0 | |
| ahead = session.exec( | |
| select(Job).where(Job.status == "queued", col(Job.created_at) < job.created_at) | |
| ).all() | |
| return len(ahead) + 1 | |
| runner = JobRunner() | |