627 lines
37 KiB
Python
627 lines
37 KiB
Python
import asyncio
|
|
from datetime import timedelta
|
|
import json
|
|
import logging
|
|
import time
|
|
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, User, utcnow
|
|
|
|
LOG = logging.getLogger(__name__)
|
|
GPU_FENCE_UNSET = object()
|
|
|
|
|
|
class PhaseDeferred(Exception):
|
|
pass
|
|
|
|
|
|
class Coordinator:
|
|
def __init__(self, settings, db, provider):
|
|
self.settings, self.db, self.provider = settings, db, provider
|
|
self._task = None
|
|
self._cpu = {}
|
|
# Bound pending coroutines independently of their current phase/slot.
|
|
# A Qwen quarantine must leave capacity for unrelated media work.
|
|
self._cpu_initial_pool = {}
|
|
self._pools = {name:asyncio.Semaphore(1) for name in ("new_gpu","cpu_media","qwen_http")}
|
|
self._held_pool = {}
|
|
self._blocked_pools = set()
|
|
from .admission_clock import AdmissionClock
|
|
self._admission_clock=AdmissionClock(settings.state_root / "admission-clock.json")
|
|
self._control_sent = {}
|
|
self._run_lock = asyncio.Lock()
|
|
self._wake = asyncio.Event()
|
|
self._file_lock = FileLock(str(settings.state_root / "coordinator.lock"))
|
|
self._closing = False
|
|
self.after_tick = None
|
|
self.last_tick_success = None
|
|
self._cancel_sent = set()
|
|
self._uncertain_cpu = set()
|
|
|
|
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.state.in_(["running","cancelling"])))).all()
|
|
from .v2_models import Execution
|
|
from .artifacts import verify_manifest
|
|
for job in rows:
|
|
execution = await session.get(Execution,job.current_execution_id) if job.current_execution_id else None
|
|
manifest = execution.manifest_json if execution else None
|
|
if not manifest:
|
|
candidates = sorted((self.settings.job_work_root / job.id).glob("attempt-*/result-manifest.json"))
|
|
for candidate in reversed(candidates):
|
|
try:
|
|
found=json.loads(candidate.read_text(encoding="utf-8"))
|
|
if found.get("execution_id")==job.current_execution_id:
|
|
manifest=found;break
|
|
except (ValueError,OSError):pass
|
|
if manifest and execution:
|
|
try:
|
|
paths=verify_manifest(self.settings.job_work_root,manifest)
|
|
if manifest.get("fence_token")!=execution.fence_token:raise ValueError("Fence mismatch")
|
|
job.upstream_result={"cpu_outputs":paths,"cpu_result":manifest["result"],"metadata":manifest["metadata"]}
|
|
job.state,job.phase="collecting","importing_outputs"
|
|
execution.manifest_json=manifest;execution.state="results_ready"
|
|
await emit_job(session,job)
|
|
continue
|
|
except (ValueError,OSError,KeyError):pass
|
|
if execution and (execution.resource_pool == "qwen_http" or job.task_type=="audio.speech"):
|
|
self._blocked_pools.add(execution.resource_pool)
|
|
execution.state="unknown"
|
|
job.state = "cancelled" if job.cancel_requested else "needs_attention"
|
|
job.phase, job.finished_at = job.state, utcnow()
|
|
job.error_json = {"code": "worker_interrupted", "message": "服务重启中断了此任务,可手动重试", "retriable": True}
|
|
await emit_job(session, job)
|
|
blocked=(await session.scalars(select(Execution).where(Execution.resource_pool.in_(["qwen_http","cpu_media"]),Execution.state=="unknown"))).all()
|
|
self._blocked_pools.update(execution.resource_pool for execution in blocked)
|
|
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()
|
|
self.last_tick_success=time.monotonic()
|
|
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, remote_observation=None, **changes):
|
|
async with self.db.session() as session:
|
|
job = await session.get(Job, job_id)
|
|
if job.state in TERMINAL:
|
|
return job
|
|
execution_changed=False
|
|
if remote_observation is not None:
|
|
from .executions import observe_gpu_execution,gpu_result_fence
|
|
from .v2_models import Execution
|
|
previous_execution_id=job.current_execution_id
|
|
accepted,execution=await observe_gpu_execution(session,job,remote_observation)
|
|
if not accepted:return job
|
|
execution_changed=job.current_execution_id!=previous_execution_id or any(isinstance(row,Execution) and session.is_modified(row) for row in session.dirty)
|
|
if remote_observation["state"]=="succeeded" and execution:
|
|
changes["upstream_result"]={**(changes.get("upstream_result") or {}),"_visual_execution":gpu_result_fence(execution)}
|
|
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 = execution_changed
|
|
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)
|
|
from .v2_models import Execution
|
|
async with self.db.session() as session:
|
|
execution=await session.get(Execution,job.current_execution_id) if job.current_execution_id else None
|
|
if execution:
|
|
unknown=(execution.resource_pool=="qwen_http" or job.task_type=="audio.speech") and getattr(exc,"retriable",False)
|
|
execution.state="unknown" if unknown else "exited"
|
|
execution.finished_at=utcnow()
|
|
if unknown:self._blocked_pools.add(execution.resource_pool)
|
|
await session.commit()
|
|
if execution and execution.state=="unknown":
|
|
await self._update(job_id,state="needs_attention",phase="remote_outcome_unknown",error_json={"code":"remote_outcome_unknown","message":"Remote request completion is unconfirmed","retriable":False})
|
|
return
|
|
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, *, gpu_fence=GPU_FENCE_UNSET):
|
|
async with self.db.session() as session:
|
|
job = await session.get(Job, job_id)
|
|
if job.state in TERMINAL:
|
|
return
|
|
if gpu_fence is not GPU_FENCE_UNSET:
|
|
from .executions import gpu_publication_matches
|
|
if not await gpu_publication_matches(session,job,gpu_fence):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 gpu_fence is not GPU_FENCE_UNSET and gpu_fence:
|
|
from .v2_models import AssetReference
|
|
binding=await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==asset.id,AssetReference.ref_kind=="execution",AssetReference.ref_id==gpu_fence["execution_id"]))
|
|
if not binding:raise ValueError("Output belongs to a different execution")
|
|
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()
|
|
|
|
def _clock_allows(self,job):
|
|
if job.execution_mode!="batch":return True
|
|
from .runtime_policy import read_runtime_policy
|
|
from .resource_policy import execution_policy
|
|
policy=read_runtime_policy(self.settings)
|
|
if policy["configuration_error"]:return False
|
|
if not policy["batch_window_enabled"]:return True
|
|
return execution_policy()["batch_open"] and self._admission_clock.observe()
|
|
|
|
async def run_once(self, *, force=False):
|
|
from .runtime_policy import read_runtime_policy
|
|
policy=read_runtime_policy(self.settings)
|
|
if policy["batch_window_enabled"] and not policy["configuration_error"]:
|
|
self._admission_clock.observe()
|
|
async with self._run_lock:
|
|
for job_id, task in list(self._cpu.items()):
|
|
if task.done():
|
|
self._cpu.pop(job_id)
|
|
self._cpu_initial_pool.pop(job_id, None)
|
|
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]
|
|
from .resource_policy import admits
|
|
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
|
|
from .maintenance import maintenance_active
|
|
holds=set(job.hold_reasons or [])
|
|
if maintenance_active(self.settings):holds.add('maintenance')
|
|
else:holds.discard('maintenance')
|
|
if holds!=set(job.hold_reasons or []):
|
|
job=await self._update(job.id,hold_reasons=sorted(holds))
|
|
if job.id in self._cpu:
|
|
if job.cancel_requested and job.state != "collecting":
|
|
held=self._held_pool.get(job.id)
|
|
draining_http=held=="qwen_http" or (job.task_type=="audio.speech" and held=="cpu_media")
|
|
if not draining_http:self._cpu[job.id].cancel()
|
|
continue
|
|
if job.id in self._uncertain_cpu:
|
|
await self._update(job.id,state="needs_attention",phase="outcome_unknown")
|
|
continue
|
|
if job.state == "needs_attention" or (job.state in {"paused","pausing"} and not job.upstream_id):continue
|
|
# Query existing upstream IDs and collect artifacts at all hours.
|
|
# Admission only protects NEW computational phases.
|
|
from .maintenance import maintenance_active
|
|
if job.state != "collecting" and not job.upstream_id and not job.cancel_requested and (not admits(job,settings=self.settings) or not self._clock_allows(job) or maintenance_active(self.settings) or not await self._owner_enabled(job.owner_id)):
|
|
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 job.state in {"submitting","queued","scheduled","cancelling"}:
|
|
from .resource_policy import resource_plan
|
|
initial_pool = resource_plan(job.task_type)[0][1]
|
|
if sum(pool == initial_pool for pool in self._cpu_initial_pool.values()) < 25:
|
|
# This membership stays fixed when the provider moves
|
|
# phases; only _held_pool follows active resource slots.
|
|
self._cpu_initial_pool[job.id] = initial_pool
|
|
self._cpu[job.id] = asyncio.create_task(self._run_cpu(job), name=f"cpu-job-{job.id}")
|
|
|
|
if self.after_tick is not None:
|
|
await self.after_tick()
|
|
|
|
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)
|
|
from .providers import current_phase_callback
|
|
async def prepare_phase(key,pool):
|
|
from .resource_policy import admits
|
|
current=await self._job(job.id)
|
|
if not admits(current,settings=self.settings):raise PhaseDeferred()
|
|
await self._enter_phase(job.id,key,pool,nonblocking=True)
|
|
token=current_phase_callback.set(prepare_phase)
|
|
try:
|
|
payload = await self.provider.prepare_gpu_payload(job.task_type, job.input_json, job.parameters,
|
|
await self._assets(job), work)
|
|
finally:
|
|
current_phase_callback.reset(token)
|
|
held=self._held_pool.pop(job.id,None)
|
|
if held:self._pools[held].release()
|
|
payload["scheduling"] = {"execution_mode": job.execution_mode, "principal_id": job.owner_id,
|
|
"policy_version": job.policy_version,
|
|
**{key:getattr(job,key) for key in ("batch_id","run_id","step_key") if getattr(job,key)}}
|
|
# 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
|
|
from .resource_policy import admits
|
|
if not job.cancel_requested and (not admits(job,settings=self.settings) or not self._clock_allows(job) or not await self._owner_enabled(job.owner_id)):return
|
|
if job.execution_mode == "batch":
|
|
capabilities = await self.provider.upstream_capabilities() if hasattr(self.provider,"upstream_capabilities") else {}
|
|
if capabilities.get("protocol_version",0)<2 or not capabilities.get("admission_policy",False):
|
|
await self._update(job.id,sync_warning="Batch requires upstream scheduling protocol v2")
|
|
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:
|
|
controls = {"manual","batch_pause","admin_suspend","batch_wait","maintenance"}
|
|
desired = "pause" if job.desired_state == "pause" or controls.intersection(job.hold_reasons or []) else "run"
|
|
if job.cancel_requested and job.id not in self._cancel_sent:
|
|
remote = await self.provider.cancel(job.upstream_id)
|
|
self._cancel_sent.add(job.id)
|
|
elif not job.cancel_requested and hasattr(self.provider,"control") and self._control_sent.get(job.id)!=desired:
|
|
remote = await self.provider.control(job.upstream_id,desired,"cmvr:"+job.id+":"+str(job.version)+":"+desired)
|
|
self._control_sent[job.id]=desired
|
|
else:
|
|
remote = 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 PhaseDeferred:
|
|
await self._update(job.id,state="submitting",phase="waiting_phase")
|
|
except asyncio.CancelledError:
|
|
raise
|
|
except Exception as exc:
|
|
if getattr(exc,"code",None) in {"quota_exceeded","storage_insufficient"}:
|
|
await self._failure(job.id,exc)
|
|
elif 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", "paused", "pausing", "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, remote_observation=remote, **changes)
|
|
if job.state == "collecting":
|
|
await self._collect_gpu(job)
|
|
|
|
async def _collect_gpu(self, job):
|
|
fence=(job.upstream_result or {}).get("_visual_execution")
|
|
from .executions import gpu_publication_matches
|
|
async with self.db.session() as session:
|
|
current=await session.get(Job,job.id)
|
|
if not await gpu_publication_matches(session,current,fence):raise ValueError("Stale GPU execution result")
|
|
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 = []
|
|
selected_indices = None
|
|
if job.run_id and job.task_type == "video.generate" and job.step_key != "compose":
|
|
selected_indices = (job.upstream_result.get("metadata") or {}).get("final_output_indices")
|
|
if (not isinstance(selected_indices, list) or not selected_indices or
|
|
any(type(i) is not int or i < 0 or i >= len(outputs) for i in selected_indices)):
|
|
raise ValueError("Workflow requires explicit final enhanced output indices from upstream")
|
|
for index, output in enumerate(outputs):
|
|
if selected_indices is not None and index not in selected_indices:
|
|
continue
|
|
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:
|
|
if fence:
|
|
from .v2_models import AssetReference
|
|
async with self.db.session() as session:
|
|
binding=await session.scalar(select(AssetReference.id).where(AssetReference.asset_id==existing.id,AssetReference.ref_kind=="execution",AssetReference.ref_id==fence["execution_id"]))
|
|
if not binding:raise ValueError("Output belongs to a different execution")
|
|
from .artifacts import digest_file
|
|
path=confined(self.settings.asset_root,existing.storage_key,exists=True)
|
|
if path.stat().st_size!=existing.size_bytes or digest_file(path)!=existing.sha256:
|
|
raise ValueError("Imported artifact is missing or corrupt")
|
|
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, execution_fence=fence))
|
|
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, gpu_fence=fence)
|
|
|
|
async def _owner_enabled(self,owner_id):
|
|
async with self.db.session() as session:
|
|
owner=await session.get(User,owner_id)
|
|
return owner is not None and not owner.disabled
|
|
|
|
async def _enter_phase(self, job_id, phase_key, pool, *, nonblocking=False):
|
|
previous=self._held_pool.pop(job_id,None)
|
|
if previous:self._pools[previous].release()
|
|
from .resource_policy import admits
|
|
from .maintenance import maintenance_active
|
|
while True:
|
|
job=await self._job(job_id)
|
|
if job.cancel_requested:raise asyncio.CancelledError()
|
|
if admits(job,settings=self.settings) and self._clock_allows(job) and pool not in self._blocked_pools and not maintenance_active(self.settings) and await self._owner_enabled(job.owner_id):break
|
|
if nonblocking:raise PhaseDeferred()
|
|
await self._update(job_id,phase="waiting_phase:"+phase_key)
|
|
await asyncio.sleep(min(1,self.settings.poll_seconds))
|
|
if nonblocking and self._pools[pool].locked():raise PhaseDeferred()
|
|
await self._pools[pool].acquire()
|
|
# Recheck after waiting for the slot; no closed-window compute starts.
|
|
job=await self._job(job_id)
|
|
if job.cancel_requested or not admits(job,settings=self.settings) or not self._clock_allows(job) or pool in self._blocked_pools or maintenance_active(self.settings) or not await self._owner_enabled(job.owner_id):
|
|
self._pools[pool].release()
|
|
if nonblocking:raise PhaseDeferred()
|
|
return await self._enter_phase(job_id,phase_key,pool)
|
|
self._held_pool[job_id]=pool
|
|
async with self.db.session() as session:
|
|
current=await session.get(Job,job_id)
|
|
if current.current_execution_id:
|
|
from .v2_models import Execution
|
|
from .executions import begin_execution
|
|
active=await session.get(Execution,current.current_execution_id)
|
|
if active and (active.phase_key!=phase_key or active.resource_pool!=pool):
|
|
active.state="exited";active.finished_at=utcnow()
|
|
await begin_execution(session,job_id,phase_key,pool)
|
|
await session.commit()
|
|
await self._update(job_id,phase="cpu_running")
|
|
|
|
async def _run_cpu(self, job):
|
|
phase_token=None
|
|
try:
|
|
if job.cancel_requested:
|
|
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
|
|
return
|
|
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)
|
|
from .executions import begin_execution
|
|
from .resource_policy import resource_plan
|
|
from .providers import current_phase_callback
|
|
phase_token=current_phase_callback.set(lambda phase,pool:self._enter_phase(job.id,phase,pool))
|
|
initial_pool=resource_plan(job.task_type)[0][1]
|
|
await self._enter_phase(job.id,"execute",initial_pool)
|
|
job = await self._update(job.id, state="running", phase="cpu_running", started_at=utcnow(),
|
|
attempt_count=job.attempt_count + 1)
|
|
if job.cancel_requested or job.state in TERMINAL:
|
|
if job.state not in TERMINAL:
|
|
await self._update(job.id,state="cancelled",phase="cancelled",finished_at=utcnow())
|
|
return
|
|
async with self.db.session() as session:
|
|
execution = await begin_execution(session,job.id,resource_pool=resource_plan(job.task_type)[0][1])
|
|
await session.commit()
|
|
result = await self.provider.run_cpu(job.task_type, job.input_json, job.parameters, await self._assets(job), work)
|
|
# A successful HTTP response proves this request ended. Explicit
|
|
# cancellation drains shared calls, then discards their response.
|
|
from .v2_models import Execution
|
|
async with self.db.session() as session:
|
|
current=await session.get(Job,job.id)
|
|
if current.cancel_requested:
|
|
execution=await session.get(Execution,current.current_execution_id)
|
|
if execution:execution.state="exited";execution.finished_at=utcnow()
|
|
current.state,current.phase,current.finished_at="cancelled","cancelled",utcnow()
|
|
current.result_json=None;current.error_json=None
|
|
await emit_job(session,current)
|
|
await session.commit()
|
|
return
|
|
from .artifacts import write_manifest
|
|
from .v2_models import Execution
|
|
async with self.db.session() as session:
|
|
current=await session.get(Job,job.id)
|
|
execution=await session.get(Execution,current.current_execution_id)
|
|
manifest=write_manifest(self.settings.job_work_root,work,execution.id,execution.fence_token,result.outputs,result.result,result.metadata)
|
|
from .executions import accept_manifest
|
|
async with self.db.session() as session:
|
|
if not await accept_manifest(session,execution.id,execution.fence_token,manifest):
|
|
current=await session.get(Job,job.id)
|
|
if current.cancel_requested:
|
|
execution.state="exited";execution.finished_at=utcnow()
|
|
current.state,current.phase,current.finished_at="cancelled","cancelled",utcnow()
|
|
current.result_json=None;current.error_json=None
|
|
await emit_job(session,current)
|
|
await session.commit()
|
|
return
|
|
await session.commit()
|
|
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:
|
|
held=self._held_pool.get(job.id)
|
|
current=await self._job(job.id)
|
|
if self._closing and not current.cancel_requested and current.current_execution_id is None:
|
|
# A pool/window waiter never allocated a provider execution.
|
|
# Keep its accepted identity queued across an API restart.
|
|
await self._update(job.id,state='queued',phase='waiting_for_resource',
|
|
started_at=None,finished_at=None,error_json=None)
|
|
return
|
|
unknown=held=="qwen_http" or (job.task_type=="audio.speech" and held=="cpu_media")
|
|
if unknown:self._blocked_pools.add(held)
|
|
from .v2_models import Execution
|
|
async with self.db.session() as session:
|
|
current=await session.get(Job,job.id)
|
|
active=await session.get(Execution,current.current_execution_id) if current.current_execution_id else None
|
|
if active and active.state not in {"results_ready","exited"}:
|
|
active.state="unknown" if unknown else "exited"
|
|
active.finished_at=utcnow()
|
|
await session.commit()
|
|
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" and getattr(exc,"code",None) not in {"quota_exceeded","storage_insufficient"}:
|
|
await self._warning(job.id, exc)
|
|
else:
|
|
LOG.exception("CPU job %s failed", job.id)
|
|
try:
|
|
await self._failure(job.id, exc)
|
|
except Exception:
|
|
self._uncertain_cpu.add(job.id)
|
|
LOG.exception("CPU outcome uncertain; execution is quarantined")
|
|
|
|
finally:
|
|
previous=self._held_pool.pop(job.id,None)
|
|
if previous:self._pools[previous].release()
|
|
if phase_token is not None:
|
|
from .providers import current_phase_callback
|
|
current_phase_callback.reset(phase_token)
|
|
|
|
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", {})))
|