File size: 13,538 Bytes
25e4412
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
"""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')}"


@dataclass(frozen=True)
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)

    @property
    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

    @staticmethod
    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

    @staticmethod
    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

    @staticmethod
    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()

    @staticmethod
    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()