cmvr-visual/backend/app/coordinator.py

341 lines
18 KiB
Python
Raw Normal View History

import asyncio
from datetime import timedelta
import json
import logging
from pathlib import Path
import re
from filelock import FileLock
from sqlalchemy import case, or_, select
from .assets import confined, import_output, safe_file
from .dto import asset_dto, public_value
from .events import emit_asset, emit_job
from .jobs import GPU_TYPES, TERMINAL
from .models import Asset, Job, JobAsset, utcnow
LOG = logging.getLogger(__name__)
class Coordinator:
def __init__(self, settings, db, provider):
self.settings, self.db, self.provider = settings, db, provider
self._task = None
self._cpu = {}
self._run_lock = asyncio.Lock()
self._wake = asyncio.Event()
self._file_lock = FileLock(str(settings.state_root / "coordinator.lock"))
self._closing = False
def wake(self):
self._wake.set()
async def start(self):
self._file_lock.acquire(timeout=0)
try:
# CPU calls cannot be replayed after an unknown crash. GPU IDs and
# persisted submit payload/key are resumed by their normal branches.
async with self.db.session() as session:
rows = (await session.scalars(select(Job).where(Job.state.notin_(TERMINAL),
Job.task_type.notin_(GPU_TYPES), Job.phase == "cpu_running"))).all()
for job in rows:
job.state = "cancelled" if job.cancel_requested else "failed"
job.phase, job.finished_at = job.state, utcnow()
job.error_json = {"code": "worker_interrupted", "message": "服务重启中断了此任务,可手动重试", "retriable": True}
await emit_job(session, job)
await session.commit()
self._task = asyncio.create_task(self._loop(), name="cmvr-coordinator")
except BaseException:
self._file_lock.release()
raise
async def close(self):
self._closing = True
if self._task:
self._task.cancel()
await asyncio.gather(self._task, return_exceptions=True)
for task in self._cpu.values():
task.cancel()
await asyncio.gather(*list(self._cpu.values()), return_exceptions=True)
if self._file_lock.is_locked:
self._file_lock.release()
async def _loop(self):
while True:
try:
await self.run_once()
except asyncio.CancelledError:
raise
except Exception:
LOG.exception("Coordinator tick failed; persisted work remains recoverable")
self._wake.clear()
try:
await asyncio.wait_for(self._wake.wait(), timeout=self.settings.poll_seconds)
except asyncio.TimeoutError:
pass
async def _job(self, job_id):
async with self.db.session() as session:
return await session.get(Job, job_id)
async def _update(self, job_id, *, fresh_dispatch=False, **changes):
async with self.db.session() as session:
job = await session.get(Job, job_id)
if job.state in TERMINAL:
return job
if job.cancel_requested:
if fresh_dispatch or changes.get("state") in {"collecting", "succeeded", "failed", "timed_out", "cancelled"}:
# Cancellation is arbitrated against the authoritative row
# in the same transaction as any outcome/publication phase.
changes = {"state": "cancelled", "phase": "cancelled", "finished_at": utcnow(),
"result_json": None, "error_json": None, "sync_warning": None}
elif changes.get("state") in {"queued", "running", "submitting"}:
changes["state"], changes["phase"] = "cancelling", "cancellation_pending"
changed = False
for key, value in changes.items():
if getattr(job, key) != value:
setattr(job, key, value)
if key not in {"next_action_at", "sync_failures"}:
changed = True
if changed:
await emit_job(session, job)
await session.commit()
return job
async def _assets(self, job):
async with self.db.session() as session:
assets = (await session.scalars(select(Asset).join(JobAsset, JobAsset.asset_id == Asset.id)
.where(JobAsset.job_id == job.id, Asset.owner_id == job.owner_id))).all()
return {asset.id: confined(self.settings.asset_root, asset.storage_key, exists=True) for asset in assets}
async def _workdir(self, job):
job = await self._update(job.id, work_attempt=job.work_attempt + 1)
path = confined(self.settings.job_work_root, Path(job.id) / f"attempt-{job.work_attempt:04d}")
path.mkdir(parents=True, exist_ok=False)
return job, path
async def _warning(self, job_id, error):
job = await self._job(job_id)
await self._update(job_id, sync_warning="上游连接或结果导入暂不可用,正在恢复同步",
sync_failures=job.sync_failures + 1,
next_action_at=utcnow() + timedelta(seconds=min(30, 2 ** min(job.sync_failures, 5))))
LOG.warning("Job %s external boundary unavailable: %s", job_id, type(error).__name__)
async def _failure(self, job_id, exc):
job = await self._job(job_id)
code = getattr(exc, "code", "processing_failed")
message = getattr(exc, "message", "任务处理失败,请联系管理员查看服务日志")
await self._update(job_id, state="cancelled" if job.cancel_requested else "failed",
phase="cancelled" if job.cancel_requested else "failed", finished_at=utcnow(),
error_json={"code": code, "message": message, "retriable": bool(getattr(exc, "retriable", False))})
async def _complete(self, job_id, result):
async with self.db.session() as session:
job = await session.get(Job, job_id)
if job.state in TERMINAL:
return
if job.cancel_requested:
job.state, job.phase = "cancelled", "cancelled"
job.result_json, job.error_json, job.sync_warning = None, None, None
job.finished_at = utcnow()
await emit_job(session, job)
await session.commit()
return
outputs = (await session.scalars(select(Asset).where(Asset.source_job_id == job_id)
.order_by(Asset.source_output_index))).all()
if not outputs:
raise ValueError("Completed job has no imported artifacts")
for asset in outputs:
if not asset.ready:
asset.ready = True
emit_asset(session, job.owner_id, "asset.created", {"asset": asset_dto(asset)})
job.state, job.phase = "succeeded", "completed"
job.result_json, job.finished_at, job.sync_warning = result, utcnow(), None
await emit_job(session, job)
await session.commit()
async def run_once(self, *, force=False):
async with self._run_lock:
for job_id, task in list(self._cpu.items()):
if task.done():
self._cpu.pop(job_id)
await asyncio.gather(task, return_exceptions=True)
async with self.db.session() as session:
query = select(Job).where(Job.state.notin_(TERMINAL))
if not force:
query = query.where(Job.next_action_at <= utcnow())
ordering = (case((Job.cancel_requested.is_(True), 0), else_=1),
Job.next_action_at, Job.created_at, Job.batch_index, Job.id)
jobs = list((await session.scalars(query.order_by(*ordering).limit(50))).all())
# Reserve one CPU candidate independently of a large GPU or
# cancellation backlog; network/GPU waiting cannot consume its slot.
cpu = await session.scalar(query.where(Job.task_type.notin_(GPU_TYPES),
or_(Job.scheduled_at.is_(None), Job.scheduled_at <= utcnow())).order_by(*ordering).limit(1))
if cpu is not None:
# Start/cancel the independent CPU task before potentially
# slow GPU HTTP calls, rather than merely adding a tail slot.
jobs = [cpu] + [job for job in jobs if job.id != cpu.id]
for job in jobs:
if job.scheduled_at and job.scheduled_at > utcnow():
continue
# Every inspected candidate moves forward, even when CPU is
# busy. This durable timestamp rotates bounded batches fairly.
job = await self._update(job.id, next_action_at=utcnow() + timedelta(seconds=self.settings.poll_seconds))
if job.state in TERMINAL:
continue
if job.id in self._cpu:
if job.cancel_requested and job.state != "collecting":
self._cpu[job.id].cancel()
continue
if job.task_type in GPU_TYPES:
await self._gpu(job)
elif job.state == "collecting":
try:
await self._collect_cpu(job)
except Exception as exc:
await self._warning(job.id, exc)
elif not self._cpu:
self._cpu[job.id] = asyncio.create_task(self._run_cpu(job), name=f"cpu-job-{job.id}")
async def _gpu(self, job):
try:
if job.state == "collecting":
await self._collect_gpu(job)
return
if not job.upstream_id:
if job.cancel_requested and job.upstream_payload is None:
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
return
if job.upstream_payload is None:
job = await self._update(job.id, phase="preparing", state="submitting")
job, work = await self._workdir(job)
payload = await self.provider.prepare_gpu_payload(job.task_type, job.input_json, job.parameters,
await self._assets(job), work)
# This commit precedes POST; retries must reuse both values.
job = await self._update(job.id, upstream_payload=payload, phase="dispatching", fresh_dispatch=True)
if job.state in TERMINAL:
return
# This invocation knows no POST has started yet. An existing
# persisted payload on restart is instead ambiguous and must
# still recover its upstream ID using the same key below.
job = await self._job(job.id)
if job.cancel_requested:
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
return
remote = await self.provider.submit(job.upstream_payload, job.upstream_key)
remote_id = remote.get("id")
if not isinstance(remote_id, str) or not remote_id:
raise ValueError("Upstream omitted its job ID")
job = await self._update(job.id, upstream_id=remote_id)
else:
remote = await self.provider.cancel(job.upstream_id) if job.cancel_requested else await self.provider.query(job.upstream_id)
# A cancellation arriving while POST was in flight is persisted and
# sent against the same recovered ID on the next tick.
await self._apply_remote(job.id, remote)
except asyncio.CancelledError:
raise
except Exception as exc:
if not job.upstream_id and getattr(exc, "code", None) == "upstream_rejected":
await self._failure(job.id, exc)
elif getattr(exc, "retriable", False) or job.upstream_payload is not None or job.upstream_id:
await self._warning(job.id, exc)
else:
LOG.exception("Job %s preparation failed", job.id)
await self._failure(job.id, exc)
async def _apply_remote(self, job_id, remote):
state = remote.get("state")
if state not in {"queued", "running", "succeeded", "failed", "cancelled", "timed_out"}:
raise ValueError("Invalid upstream job state")
job = await self._job(job_id)
changes = {"state": state, "phase": remote.get("stage") or state,
"attempt_count": int(remote.get("attempt_count", job.attempt_count)),
"preemptions": int(remote.get("preemptions", job.preemptions)),
"last_preempted_reason": public_value(remote.get("last_preempted_reason")),
"sync_warning": None, "sync_failures": 0,
"next_action_at": utcnow() + timedelta(seconds=self.settings.poll_seconds)}
if state == "running" and not job.started_at:
changes["started_at"] = utcnow()
if state == "succeeded":
changes.update(state="collecting", phase="importing_outputs", upstream_result=remote.get("result") or {})
elif state in TERMINAL:
changes["finished_at"] = utcnow()
if state in {"failed", "timed_out"}:
changes["error_json"] = {"code": "upstream_" + state, "message": "模型任务未完成,请检查参数或重试", "retriable": True}
job = await self._update(job_id, **changes)
if job.state == "collecting":
await self._collect_gpu(job)
async def _collect_gpu(self, job):
outputs = (job.upstream_result or {}).get("outputs")
if not isinstance(outputs, list) or not outputs:
raise ValueError("Succeeded upstream job has no outputs")
directory = confined(self.settings.job_work_root, Path(job.id) / "imports")
directory.mkdir(parents=True, exist_ok=True)
assets = []
for index, output in enumerate(outputs):
async with self.db.session() as session:
existing = await session.scalar(select(Asset).where(Asset.source_job_id == job.id,
Asset.source_output_index == index))
if existing:
assets.append(existing)
continue
raw = output.get("path", "") if isinstance(output, dict) else str(output)
suffix = Path(raw).suffix.lower()
if not re.fullmatch(r"\.[a-z0-9]{1,10}", suffix):
suffix = ".bin"
destination = directory / f"output-{index:04d}{suffix}"
await self.provider.download(job.upstream_id, index, destination)
assets.append(await import_output(self.db, self.settings, job, destination, index))
result = public_value((job.upstream_result or {}).get("metadata", {}))
if job.task_type == "audio.transcribe":
for asset in assets:
if asset.kind == "json" and asset.size_bytes <= 5 * 1024 * 1024:
with safe_file(self.settings.asset_root, asset.storage_key) as stream:
transcript = json.load(stream)
result = {"text": transcript.get("text", ""), "segments": transcript.get("segments", [])}
break
await self._complete(job.id, result)
async def _run_cpu(self, job):
try:
if job.cancel_requested:
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
return
job = await self._update(job.id, state="running", phase="cpu_running", started_at=utcnow(),
attempt_count=job.attempt_count + 1)
if job.state in TERMINAL or job.cancel_requested:
if job.state not in TERMINAL:
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
return
job, work = await self._workdir(job)
result = await self.provider.run_cpu(job.task_type, job.input_json, job.parameters, await self._assets(job), work)
job = await self._job(job.id)
if job.cancel_requested:
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
return
if not isinstance(result.outputs, list) or not result.outputs:
raise ValueError("CPU provider returned no artifacts")
private = {"cpu_outputs": [str(confined(self.settings.job_work_root, p, exists=True)) for p in result.outputs],
"cpu_result": result.result, "metadata": result.metadata}
job = await self._update(job.id, state="collecting", phase="importing_outputs", upstream_result=private)
if job.state not in TERMINAL:
await self._collect_cpu(job)
except asyncio.CancelledError:
job = await self._job(job.id)
if job.state != "collecting":
await self._update(job.id, state="cancelled" if job.cancel_requested else "failed",
phase="cancelled" if job.cancel_requested else "interrupted", finished_at=utcnow(),
error_json=None if job.cancel_requested else {"code": "worker_interrupted", "message": "任务因服务停止而中断", "retriable": True})
except Exception as exc:
job = await self._job(job.id)
if job.state == "collecting":
await self._warning(job.id, exc)
else:
LOG.exception("CPU job %s failed", job.id)
await self._failure(job.id, exc)
async def _collect_cpu(self, job):
private = job.upstream_result or {}
for index, source in enumerate(private.get("cpu_outputs", [])):
await import_output(self.db, self.settings, job, Path(source), index)
await self._complete(job.id, public_value(private.get("cpu_result", {})))