2026-11-10 21:36:09 +08:00
import asyncio
from datetime import timedelta
import json
import logging
2026-11-10 23:56:50 +08:00
import time
2026-11-10 21:36:09 +08:00
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
2026-11-10 23:56:50 +08:00
from . models import Asset , Job , JobAsset , User , utcnow
2026-11-10 21:36:09 +08:00
LOG = logging . getLogger ( __name__ )
2026-11-10 23:56:50 +08:00
GPU_FENCE_UNSET = object ( )
class PhaseDeferred ( Exception ) :
pass
2026-11-10 21:36:09 +08:00
class Coordinator :
def __init__ ( self , settings , db , provider ) :
self . settings , self . db , self . provider = settings , db , provider
self . _task = None
self . _cpu = { }
2026-11-11 10:59:33 +08:00
self . _preparing = { }
self . _collecting = { }
2026-11-10 23:56:50 +08:00
# 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 = { }
2026-11-10 21:36:09 +08:00
self . _run_lock = asyncio . Lock ( )
self . _wake = asyncio . Event ( )
self . _file_lock = FileLock ( str ( settings . state_root / " coordinator.lock " ) )
self . _closing = False
2026-11-10 23:56:50 +08:00
self . after_tick = None
self . last_tick_success = None
self . _cancel_sent = set ( )
self . _uncertain_cpu = set ( )
2026-11-10 21:36:09 +08:00
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 :
2026-11-11 10:29:01 +08:00
rows = ( await session . scalars ( select ( Job ) . where ( Job . deleted_at . is_ ( None ) , Job . state . notin_ ( TERMINAL ) ,
2026-11-10 23:56:50 +08:00
Job . task_type . notin_ ( GPU_TYPES ) , Job . state . in_ ( [ " running " , " cancelling " ] ) ) ) ) . all ( )
from . v2_models import Execution
from . artifacts import verify_manifest
2026-11-10 21:36:09 +08:00
for job in rows :
2026-11-10 23:56:50 +08:00
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 "
2026-11-10 21:36:09 +08:00
job . phase , job . finished_at = job . state , utcnow ( )
job . error_json = { " code " : " worker_interrupted " , " message " : " 服务重启中断了此任务,可手动重试 " , " retriable " : True }
await emit_job ( session , job )
2026-11-10 23:56:50 +08:00
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 )
2026-11-10 21:36:09 +08:00
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 )
2026-11-11 10:59:33 +08:00
background = [ * self . _cpu . values ( ) , * self . _preparing . values ( ) , * self . _collecting . values ( ) ]
for task in background : task . cancel ( )
await asyncio . gather ( * background , return_exceptions = True )
2026-11-10 21:36:09 +08:00
if self . _file_lock . is_locked :
self . _file_lock . release ( )
async def _loop ( self ) :
while True :
try :
await self . run_once ( )
2026-11-10 23:56:50 +08:00
self . last_tick_success = time . monotonic ( )
2026-11-10 21:36:09 +08:00
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 )
2026-11-10 23:56:50 +08:00
async def _update ( self , job_id , * , fresh_dispatch = False , remote_observation = None , * * changes ) :
2026-11-10 21:36:09 +08:00
async with self . db . session ( ) as session :
job = await session . get ( Job , job_id )
2026-11-11 10:29:01 +08:00
if job is None or job . deleted_at is not None or job . state in TERMINAL :
2026-11-10 21:36:09 +08:00
return job
2026-11-10 23:56:50 +08:00
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 ) }
2026-11-10 21:36:09 +08:00
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 "
2026-11-10 23:56:50 +08:00
changed = execution_changed
2026-11-10 21:36:09 +08:00
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 )
2026-11-11 10:29:01 +08:00
. where ( JobAsset . job_id == job . id , Asset . owner_id == job . owner_id ,
Asset . library_scope == ' private ' , Asset . ready . is_ ( True ) , Asset . deleted_at . is_ ( None ) ) ) ) . all ( )
2026-11-10 21:36:09 +08:00
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 )
2026-11-11 10:29:01 +08:00
if job is None or job . deleted_at is not None : return
2026-11-10 23:56:50 +08:00
from . v2_models import Execution
async with self . db . session ( ) as session :
2026-11-11 10:29:01 +08:00
job = await session . get ( Job , job_id )
if job is None or job . deleted_at is not None : return
2026-11-10 23:56:50 +08:00
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
2026-11-10 21:36:09 +08:00
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 ) ) } )
2026-11-10 23:56:50 +08:00
async def _complete ( self , job_id , result , * , gpu_fence = GPU_FENCE_UNSET ) :
2026-11-10 21:36:09 +08:00
async with self . db . session ( ) as session :
job = await session . get ( Job , job_id )
2026-11-11 10:29:01 +08:00
if job is None or job . deleted_at is not None or job . state in TERMINAL :
2026-11-10 21:36:09 +08:00
return
2026-11-10 23:56:50 +08:00
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
2026-11-10 21:36:09 +08:00
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
2026-11-11 10:29:01 +08:00
outputs = ( await session . scalars ( select ( Asset ) . where ( Asset . source_job_id == job_id ,
Asset . owner_id == job . owner_id , Asset . library_scope == ' private ' , Asset . deleted_at . is_ ( None ) )
2026-11-10 21:36:09 +08:00
. order_by ( Asset . source_output_index ) ) ) . all ( )
if not outputs :
raise ValueError ( " Completed job has no imported artifacts " )
for asset in outputs :
2026-11-10 23:56:50 +08:00
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 " )
2026-11-10 21:36:09 +08:00
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 ( )
2026-11-10 23:56:50 +08:00
def _clock_allows ( self , job ) :
2026-11-11 00:36:30 +08:00
if job . execution_mode != " batch " : return True
2026-11-11 10:59:33 +08:00
return self . _batch_clock_allows ( )
def _batch_clock_allows ( self ) :
2026-11-11 00:36:30 +08:00
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 ( )
2026-11-10 23:56:50 +08:00
2026-11-10 21:36:09 +08:00
async def run_once ( self , * , force = False ) :
2026-11-11 00:36:30 +08:00
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 ( )
2026-11-10 21:36:09 +08:00
async with self . _run_lock :
for job_id , task in list ( self . _cpu . items ( ) ) :
if task . done ( ) :
self . _cpu . pop ( job_id )
2026-11-10 23:56:50 +08:00
self . _cpu_initial_pool . pop ( job_id , None )
2026-11-10 21:36:09 +08:00
await asyncio . gather ( task , return_exceptions = True )
2026-11-11 10:59:33 +08:00
for pending in ( self . _preparing , self . _collecting ) :
for jid , task in list ( pending . items ( ) ) :
if task . done ( ) :
pending . pop ( jid )
await asyncio . gather ( task , return_exceptions = True )
2026-11-10 21:36:09 +08:00
async with self . db . session ( ) as session :
2026-11-11 10:29:01 +08:00
query = select ( Job ) . where ( Job . deleted_at . is_ ( None ) , Job . state . notin_ ( TERMINAL ) )
2026-11-10 21:36:09 +08:00
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 ( ) )
2026-11-11 10:59:33 +08:00
# New dispatch FIFO is separate from observation/retry backoff.
fresh = select ( Job ) . join ( User , User . id == Job . owner_id ) . where ( User . disabled . is_ ( False ) , Job . deleted_at . is_ ( None ) , Job . state . notin_ ( TERMINAL ) ,
Job . task_type . in_ ( GPU_TYPES ) , Job . upstream_id . is_ ( None ) ,
Job . desired_state == " run " , or_ ( Job . hold_reasons == [ ] , Job . hold_reasons == [ " window " ] ) ,
Job . state . in_ ( [ " submitting " , " queued " , " scheduled " ] ) ,
( or_ ( Job . sync_failures == 0 , Job . next_action_at < = utcnow ( ) ) if not force else True ) ,
or_ ( Job . scheduled_at . is_ ( None ) , Job . scheduled_at < = utcnow ( ) ) )
if not self . _batch_clock_allows ( ) : fresh = fresh . where ( Job . execution_mode != " batch " )
ready = list ( ( await session . scalars ( fresh . order_by ( Job . created_at , Job . batch_index , Job . id ) . limit ( 25 ) ) ) . all ( ) )
ready_ids = { j . id for j in ready }
jobs = ready + [ j for j in jobs if j . id not in ready_ids ]
2026-11-10 21:36:09 +08:00
# 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 ]
2026-11-10 23:56:50 +08:00
from . resource_policy import admits
2026-11-11 10:59:33 +08:00
# Media preparation is bounded independently of the dispatch loop.
for job in jobs :
if job . task_type not in GPU_TYPES or job . upstream_id or job . upstream_payload is not None or job . state in { " collecting " , " needs_attention " , " paused " , " pausing " } or job . cancel_requested : continue
if job . scheduled_at and job . scheduled_at > utcnow ( ) : continue
if not admits ( job , settings = self . settings ) or not self . _clock_allows ( job ) or not await self . _owner_enabled ( job . owner_id ) : continue
from . maintenance import maintenance_active
if maintenance_active ( self . settings ) : continue
if job . id not in self . _preparing and len ( self . _preparing ) < 4 :
self . _preparing [ job . id ] = asyncio . create_task ( self . _gpu ( job , prepare_only = True ) , name = f " prepare- { job . id } " )
if self . _preparing :
await asyncio . wait ( list ( self . _preparing . values ( ) ) , timeout = .1 )
# Preparation candidates are not the submission queue. Re-read
# persisted ready payloads after bounded preparation, including
# payloads beyond a prefix of unfinished media jobs.
async with self . db . session ( ) as session :
ready = list ( ( await session . scalars ( fresh . where ( Job . upstream_payload . is_not ( None ) ) . order_by ( Job . created_at , Job . batch_index , Job . id ) . limit ( 25 ) ) ) . all ( ) )
ready = [ j for j in ready if j . id not in self . _preparing or self . _preparing [ j . id ] . done ( ) ]
ready_ids = { j . id for j in ready }
jobs = ready + [ j for j in jobs if j . id not in ready_ids ]
if cpu is not None : jobs = [ cpu ] + [ j for j in jobs if j . id != cpu . id ]
2026-11-10 21:36:09 +08:00
for job in jobs :
2026-11-11 10:59:33 +08:00
job = await self . _job ( job . id )
2026-11-10 21:36:09 +08:00
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
2026-11-10 23:56:50 +08:00
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 ) )
2026-11-10 21:36:09 +08:00
if job . id in self . _cpu :
if job . cancel_requested and job . state != " collecting " :
2026-11-10 23:56:50 +08:00
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
2026-11-11 00:36:30 +08:00
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 ) ) :
2026-11-10 21:36:09 +08:00
continue
2026-11-11 10:59:33 +08:00
if job . id in self . _collecting : continue
# A persisted payload is not dispatchable until preparation's
# final cancellation check has finished. Otherwise it could
# locally cancel while a concurrent POST loses its remote ID.
if job . id in self . _preparing and not self . _preparing [ job . id ] . done ( ) : continue
2026-11-10 21:36:09 +08:00
if job . task_type in GPU_TYPES :
2026-11-11 10:59:33 +08:00
if job . state == " collecting " :
if len ( self . _collecting ) < 2 : self . _collecting [ job . id ] = asyncio . create_task ( self . _gpu ( job ) , name = f " collect- { job . id } " )
elif job . upstream_id or job . upstream_payload is not None or job . cancel_requested :
# Observation overflow is a polling cursor, never a
# second submit queue. Only the FIFO prefix dispatches.
if not job . upstream_id and not job . cancel_requested and job . id not in ready_ids : continue
await self . _gpu ( job )
2026-11-10 21:36:09 +08:00
elif job . state == " collecting " :
2026-11-11 10:59:33 +08:00
if len ( self . _collecting ) < 2 :
self . _collecting [ job . id ] = asyncio . create_task ( self . _collect_cpu_background ( job ) , name = f " collect- { job . id } " )
2026-11-10 23:56:50 +08:00
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 } " )
2026-11-11 10:59:33 +08:00
if self . _collecting :
await asyncio . wait ( list ( self . _collecting . values ( ) ) , timeout = .1 )
2026-11-10 23:56:50 +08:00
if self . after_tick is not None :
await self . after_tick ( )
2026-11-10 21:36:09 +08:00
2026-11-11 10:59:33 +08:00
async def _collect_cpu_background ( self , job ) :
try : await self . _collect_cpu ( job )
except Exception as exc : await self . _warning ( job . id , exc )
async def _gpu ( self , job , * , prepare_only = False ) :
2026-11-10 21:36:09 +08:00
try :
2026-11-11 10:29:01 +08:00
job = await self . _job ( job . id )
if job is None or job . deleted_at is not None or job . state in TERMINAL : return
2026-11-10 21:36:09 +08:00
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 )
2026-11-10 23:56:50 +08:00
from . providers import current_phase_callback
async def prepare_phase ( key , pool ) :
from . resource_policy import admits
current = await self . _job ( job . id )
2026-11-11 00:36:30 +08:00
if not admits ( current , settings = self . settings ) : raise PhaseDeferred ( )
2026-11-10 23:56:50 +08:00
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 ) } }
2026-11-10 21:36:09 +08:00
# 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
2026-11-11 10:59:33 +08:00
if prepare_only : return
2026-11-10 23:56:50 +08:00
from . resource_policy import admits
2026-11-11 00:36:30 +08:00
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
2026-11-10 23:56:50 +08:00
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
2026-11-10 21:36:09 +08:00
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 :
2026-11-10 23:56:50 +08:00
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 )
2026-11-10 21:36:09 +08:00
# A cancellation arriving while POST was in flight is persisted and
# sent against the same recovered ID on the next tick.
2026-11-11 10:59:33 +08:00
await self . _apply_remote ( job . id , remote , defer_collection = True )
2026-11-10 23:56:50 +08:00
except PhaseDeferred :
await self . _update ( job . id , state = " submitting " , phase = " waiting_phase " )
2026-11-10 21:36:09 +08:00
except asyncio . CancelledError :
raise
except Exception as exc :
2026-11-10 23:56:50 +08:00
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 " :
2026-11-10 21:36:09 +08:00
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 )
2026-11-11 10:59:33 +08:00
async def _apply_remote ( self , job_id , remote , * , defer_collection = False ) :
2026-11-10 21:36:09 +08:00
state = remote . get ( " state " )
2026-11-10 23:56:50 +08:00
if state not in { " queued " , " running " , " paused " , " pausing " , " succeeded " , " failed " , " cancelled " , " timed_out " } :
2026-11-10 21:36:09 +08:00
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 }
2026-11-10 23:56:50 +08:00
job = await self . _update ( job_id , remote_observation = remote , * * changes )
2026-11-10 21:36:09 +08:00
if job . state == " collecting " :
2026-11-11 10:59:33 +08:00
if defer_collection :
if job . id not in self . _collecting and len ( self . _collecting ) < 2 :
self . _collecting [ job . id ] = asyncio . create_task ( self . _gpu ( job ) , name = f " collect- { job . id } " )
else :
await self . _collect_gpu ( job )
2026-11-10 21:36:09 +08:00
async def _collect_gpu ( self , job ) :
2026-11-10 23:56:50 +08:00
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 " )
2026-11-10 21:36:09 +08:00
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 = [ ]
2026-11-10 23:56:50 +08:00
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 " )
2026-11-10 21:36:09 +08:00
for index , output in enumerate ( outputs ) :
2026-11-10 23:56:50 +08:00
if selected_indices is not None and index not in selected_indices :
continue
2026-11-10 21:36:09 +08:00
async with self . db . session ( ) as session :
existing = await session . scalar ( select ( Asset ) . where ( Asset . source_job_id == job . id ,
2026-11-11 10:29:01 +08:00
Asset . owner_id == job . owner_id ,
Asset . library_scope == ' private ' ,
2026-11-10 21:36:09 +08:00
Asset . source_output_index == index ) )
if existing :
2026-11-10 23:56:50 +08:00
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 " )
2026-11-10 21:36:09 +08:00
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 )
2026-11-10 23:56:50 +08:00
assets . append ( await import_output ( self . db , self . settings , job , destination , index , execution_fence = fence ) )
2026-11-10 21:36:09 +08:00
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
2026-11-10 23:56:50 +08:00
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 )
2026-11-11 10:29:01 +08:00
if job is None or job . deleted_at is not None or job . state in TERMINAL : raise asyncio . CancelledError ( )
2026-11-10 23:56:50 +08:00
if job . cancel_requested : raise asyncio . CancelledError ( )
2026-11-11 00:36:30 +08:00
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
2026-11-10 23:56:50 +08:00
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 )
2026-11-11 10:29:01 +08:00
if job . deleted_at is not None or job . state in TERMINAL or 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 ) :
2026-11-10 23:56:50 +08:00
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 " )
2026-11-10 21:36:09 +08:00
async def _run_cpu ( self , job ) :
2026-11-10 23:56:50 +08:00
phase_token = None
2026-11-10 21:36:09 +08:00
try :
2026-11-11 10:29:01 +08:00
job = await self . _job ( job . id )
if job is None or job . deleted_at is not None : return
2026-11-10 21:36:09 +08:00
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 )
2026-11-10 23:56:50 +08:00
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 ( )
2026-11-10 21:36:09 +08:00
result = await self . provider . run_cpu ( job . task_type , job . input_json , job . parameters , await self . _assets ( job ) , work )
2026-11-10 23:56:50 +08:00
# 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 ( )
2026-11-10 21:36:09 +08:00
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 :
2026-11-10 23:56:50 +08:00
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 ( )
2026-11-10 21:36:09 +08:00
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 )
2026-11-10 23:56:50 +08:00
if job . state == " collecting " and getattr ( exc , " code " , None ) not in { " quota_exceeded " , " storage_insufficient " } :
2026-11-10 21:36:09 +08:00
await self . _warning ( job . id , exc )
else :
LOG . exception ( " CPU job %s failed " , job . id )
2026-11-10 23:56:50 +08:00
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 )
2026-11-10 21:36:09 +08:00
async def _collect_cpu ( self , job ) :
2026-11-11 10:29:01 +08:00
job = await self . _job ( job . id )
if job is None or job . deleted_at is not None or job . state in TERMINAL : return
2026-11-10 21:36:09 +08:00
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 " , { } ) ) )