File size: 13,888 Bytes
c199fc6
fef0469
 
 
 
66b1606
fef0469
 
 
 
 
 
 
aef6fef
9ec7973
 
fef0469
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66b1606
fef0469
 
 
 
 
66b1606
 
 
 
 
 
 
 
 
 
 
fef0469
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ec7973
fef0469
 
 
 
 
 
 
 
 
 
 
aef6fef
 
fef0469
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c199fc6
 
fef0469
c199fc6
 
9ec7973
c199fc6
 
 
 
 
fef0469
 
 
 
 
 
 
 
 
 
 
 
 
 
c199fc6
 
 
 
 
 
 
aef6fef
 
 
 
 
c199fc6
 
fef0469
c199fc6
 
 
fef0469
c199fc6
 
fef0469
 
 
c199fc6
 
 
 
 
 
 
 
 
fef0469
c199fc6
fef0469
c199fc6
 
 
 
 
 
 
fef0469
 
 
 
c199fc6
 
fef0469
 
 
 
c199fc6
fef0469
c199fc6
fef0469
 
 
 
 
c199fc6
 
fef0469
 
 
c199fc6
fef0469
 
c199fc6
 
 
fef0469
 
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
"""A persistent GPU worker pool with explicit restart reconciliation."""
import fcntl
import json
import logging
import os
import re
import threading
import time

from app.catalog import Catalog
from app.core.config import Settings
from app.db import Database
from app.jobs import identifier
from app.providers.wan import sha256_file
from app.characters import Characters
from app.providers.talking import TalkingProvider
from app.storage import Storage

log = logging.getLogger('mod.worker')


class Worker:
    def __init__(self, db, storage, catalog, provider, worker_id):
        self.db, self.storage, self.catalog = db, storage, catalog
        self.provider, self.worker_id = provider, worker_id
        self.state, self.current, self.started = 'starting', None, None
        self.lock = threading.Lock()

    def heartbeat(self):
        with self.db.transaction() as c:
            c.execute('''INSERT INTO workers(id,heartbeat,state,loaded_model,details) VALUES(%s,%s,%s,%s,%s)
                      ON CONFLICT(id) DO UPDATE SET heartbeat=excluded.heartbeat,state=excluded.state,
                      loaded_model=excluded.loaded_model,details=excluded.details''',
                      (self.worker_id, time.time(), self.state, self.provider.loaded_mode,
                       json.dumps({'catalog_digest': self.catalog.digest, 'job_id': self.current})))

    def stage(self, job_id, token, value):
        now = time.time()
        with self.db.transaction() as c:
            result = c.execute("UPDATE jobs SET stage=%s,updated_at=%s WHERE id=%s AND execution_token=%s AND status='running'",
                               (value, time.time(), job_id, token))
            if result.rowcount != 1:
                raise RuntimeError('Execution attempt no longer owns this job')
            # Persist step timing with the attempt so reconnects retain progress.
            if value == 'generating':
                c.execute('UPDATE attempts SET details=%s WHERE token=%s',
                          (json.dumps({'denoise_started_at': now}), token))
            match = re.fullmatch(r'generating_(\d+)_of_(\d+)', value)
            if match:
                row = c.execute('SELECT details FROM attempts WHERE token=%s', (token,)).fetchone()
                timing = json.loads(row['details'] or '{}') if row else {}
                timing.update(completed_steps=int(match[1]), total_steps=int(match[2]),
                              step_updated_at=now)
                c.execute('UPDATE attempts SET details=%s WHERE token=%s', (json.dumps(timing), token))

    def fail(self, job_id, token, code, message):
        with self.db.transaction() as c:
            c.execute("UPDATE jobs SET status='failed',stage='failed',error=%s,updated_at=%s WHERE id=%s AND execution_token=%s AND status='running'",
                      (json.dumps({'code': code, 'message': message, 'retryable': False}), time.time(), job_id, token))
            c.execute("UPDATE attempts SET finished_at=%s,outcome='failed',details=%s WHERE token=%s",
                      (time.time(), code, token))

    def complete(self, job, token, key, metadata, checksum):
        with self.db.transaction() as c:
            # Lock the job before publishing; stale attempts may not create a public artifact.
            row = c.execute('SELECT status,execution_token FROM jobs WHERE id=%s' + ('' if c.sqlite else ' FOR UPDATE'), (job['id'],)).fetchone()
            if not row or row['status'] != 'running' or row['execution_token'] != token:
                return
            asset_id = identifier('vid')
            c.execute('INSERT INTO assets VALUES(%s,%s,%s,%s,%s,%s,%s,%s)',
                      (asset_id, job['owner_id'], job['company_id'], 'video', key,
                       json.dumps(metadata), checksum, time.time()))
            c.execute("UPDATE jobs SET status='succeeded',stage='completed',output_id=%s,updated_at=%s WHERE id=%s AND execution_token=%s",
                      (asset_id, time.time(), job['id'], token))
            c.execute("UPDATE attempts SET finished_at=%s,outcome='succeeded',details=%s WHERE token=%s",
                      (time.time(), json.dumps(metadata), token))

    def recover(self):
        """Call only after acquiring exclusive deployment lock; old process must be stopped."""
        with self.db.transaction() as c:
            rows = c.execute("SELECT * FROM jobs WHERE worker_id=%s AND status='running'", (self.worker_id,)).fetchall()
        for row in rows:
            job = dict(row)
            token = job['execution_token']
            key = f"outputs/{job['id']}/{token}.mp4"
            manifest = self.storage.path(key + '.json')
            if manifest.exists():
                try:
                    data = json.loads(manifest.read_text())
                    valid = data['token'] == token and sha256_file(self.storage.path(key)) == data['checksum']
                except (OSError, ValueError, KeyError):
                    valid = False
                if valid:
                    self.complete(job, token, key, data['metadata'], data['checksum'])
                    continue
            self.fail(job['id'], token, 'WORKER_INTERRUPTED', 'The worker restarted before completion. Submit a new generation to retry.')

    def execute(self, job_id):
        with self.lock:
            self._execute(job_id)

    def _execute(self, job_id):
        token = identifier('attempt')
        with self.db.transaction() as c:
            row = c.execute("UPDATE jobs SET status='running',stage='preparing',execution_token=%s,worker_id=%s,attempt=attempt+1,updated_at=%s WHERE id=%s AND status='queued' RETURNING *",
                            (token, self.worker_id, time.time(), job_id)).fetchone()
            if not row:
                return  # Cancelled or already claimed; queue redelivery is harmless.
            job = dict(row)
            c.execute('INSERT INTO attempts(token,job_id,worker_id,started_at) VALUES(%s,%s,%s,%s)',
                      (token, job_id, self.worker_id, time.time()))
        self.state, self.current, self.started = 'busy', job_id, time.monotonic()
        job['effective_settings'] = json.loads(job['settings'])
        try:
            if job['effective_settings']['catalog_digest'] != self.catalog.digest:
                raise ValueError('Catalog changed; resubmit under current settings')
            image_path = None
            if job['input_id']:
                with self.db.transaction() as c:
                    asset = c.execute('SELECT * FROM assets WHERE id=%s AND owner_id=%s AND company_id=%s',
                                      (job['input_id'], job['owner_id'], job['company_id'])).fetchone()
                if asset is None:
                    raise ValueError('Input asset missing')
                image_path = self.storage.path(asset['storage_key'])
                if sha256_file(image_path) != asset['checksum']:
                    raise ValueError('Input integrity failure')
            key = f'outputs/{job_id}/{token}.mp4'
            output = self.storage.path(key)
            metadata = self.provider.generate(job, image_path, output, lambda s: self.stage(job_id, token, s))
            self.stage(job_id, token, 'saving')
            with output.open('rb') as f:
                os.fsync(f.fileno())
            checksum = sha256_file(output)
            metadata['elapsed_seconds'] = time.monotonic() - self.started
            metadata['queue_seconds'] = max(0, job['updated_at'] - job['created_at'])
            metadata['total_seconds'] = time.time() - job['created_at']
            manifest = json.dumps({'token': token, 'metadata': metadata, 'checksum': checksum}).encode()
            # Bounded persistence retries reuse the video; never rerun expensive inference here.
            for attempt in range(3):
                try:
                    self.storage.write(key + '.json', manifest)
                    self.complete(job, token, key, metadata, checksum)
                    break
                except Exception:
                    if attempt == 2:
                        raise
                    time.sleep(2 ** attempt)
            log.info('generation_succeeded job=%s attempt=%s', job_id, token)
        except Exception as exc:
            log.exception('generation_failed job=%s attempt=%s', job_id, token)
            oom = 'OutOfMemory' in type(exc).__name__ or 'out of memory' in str(exc).lower()
            self.fail(job_id, token, 'GPU_OUT_OF_MEMORY' if oom else 'GENERATION_FAILED',
                      'The worker exhausted GPU memory.' if oom else 'Generation failed. An operator can inspect the job diagnostics.')
            if oom:
                self.provider.reset()
        finally:
            self.current, self.started, self.state = None, None, 'ready'



class LocalRuntime:
    """Independent inference workers sharing a durable, atomically claimed queue."""
    def __init__(self, db, storage, catalog, settings, provider=None, provider_factory=None):
        self.db, self.storage, self.settings = db, storage, settings
        if provider is not None and settings.worker_concurrency != 1:
            raise ValueError('Concurrent workers require a provider factory, not a shared provider')
        factory = provider_factory or (lambda: TalkingProvider(catalog, Characters(settings.characters_dir)))
        self.workers = [Worker(db, storage, catalog, provider if provider is not None else factory(),
                               f'gpu-{i + 1}') for i in range(settings.worker_concurrency)]
        self.worker = self.workers[0]
        self.threads = []
        self.startup_lock = threading.Lock()
        self.stop = threading.Event()
        self.lockfile = None
        self.thread = None
        self.monitor = None

    def start(self):
        path = self.storage.path('locks/gpu-0.lock')
        path.parent.mkdir(parents=True, exist_ok=True)
        self.lockfile = path.open('a')
        try:
            fcntl.flock(self.lockfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError:
            self.lockfile.close()
            raise RuntimeError('Only one application process may own this GPU/storage directory') from None
        # Reconcile all historical worker IDs, including slots removed by a config change.
        with self.db.transaction() as c:
            old_ids = [r['worker_id'] for r in c.execute(
                "SELECT DISTINCT worker_id FROM jobs WHERE status='running'").fetchall()]
            c.execute("UPDATE workers SET state='offline'")
        for worker_id in old_ids:
            Worker(self.db, self.storage, self.worker.catalog, self.worker.provider, worker_id).recover()
        with self.db.transaction() as c:
            for row in c.execute("SELECT id,settings FROM jobs WHERE status='queued'").fetchall():
                if json.loads(row['settings']).get('catalog_digest') != self.worker.catalog.digest:
                    c.execute("UPDATE jobs SET status='failed',stage='failed',updated_at=%s,error=%s WHERE id=%s",
                              (time.time(), json.dumps({'code':'MODEL_CHANGED', 'message':'The model was upgraded. Submit a new generation.', 'retryable':False}), row['id']))
        for worker in self.workers:
            worker.heartbeat()
        self.monitor = threading.Thread(target=self._monitor, daemon=True, name='mod-heartbeat')
        self.threads = [threading.Thread(target=self._run, args=(worker,), daemon=True,
                                         name=f'mod-inference-{worker.worker_id}') for worker in self.workers]
        self.thread = self.threads[0]
        self.monitor.start()
        for thread in self.threads:
            thread.start()

    def _monitor(self):
        while not self.stop.wait(5):
            for worker in self.workers:
                if (worker.started is not None and
                        time.monotonic() - worker.started > self.settings.job_timeout_seconds):
                    log.error('generation_timeout worker=%s; terminating process for safe restart', worker.worker_id)
                    os._exit(70)
                try:
                    worker.heartbeat()
                except Exception:
                    log.exception('worker_heartbeat_failed')

    def _run(self, worker):
        try:
            # Avoid overlapping checkpoint deserialization and peak startup RAM.
            with self.startup_lock:
                if self.stop.is_set():
                    return
                worker.provider.preflight()
            worker.state = 'ready'
            worker.heartbeat()
            while not self.stop.is_set():
                with self.db.transaction() as c:
                    row = c.execute("SELECT id FROM jobs WHERE status='queued' ORDER BY created_at,id LIMIT 1").fetchone()
                if row:
                    worker.execute(row['id'])
                    worker.heartbeat()
                else:
                    self.stop.wait(0.5)
        except Exception:
            log.exception('worker_startup_or_queue_failed')
            worker.state = 'failed'
            try:
                worker.heartbeat()
            except Exception:
                log.exception('worker_failure_status_unavailable')

    def close(self):
        self.stop.set()
        for thread in self.threads:
            thread.join(timeout=5)
        if self.monitor:
            self.monitor.join(timeout=6)
        # Never release ownership while a CUDA call remains active in a thread.
        if any(thread.is_alive() for thread in self.threads):
            log.warning('inference still running at shutdown; lock held until process exit')
            return
        for worker in self.workers:
            worker.state = 'offline'
            worker.heartbeat()
        if self.lockfile:
            self.lockfile.close()