UnisKB/apps/system_manage/mcp_scheduler.py

234 lines
12 KiB
Python

"""Durable priority admission shared by inline workflow nodes and hub workers.
Capacity is an administrator configured execution slot count, not GPU telemetry.
The existing settings row serializes admission across processes and workspaces.
"""
import time
import threading
from weakref import WeakValueDictionary
from collections import Counter
from datetime import timedelta
from django.db import transaction, close_old_connections
from django.utils import timezone
from rest_framework.exceptions import ValidationError
from system_manage.models.ai_hub import AITask
from system_manage import mcp_registry as registry
ACTIVE = ['PENDING', 'RUNNING']
_parent_locks = WeakValueDictionary()
_parent_locks_guard = threading.Lock()
def resources(task):
return task.snapshot.get('resources', registry.pipeline_resources(task.snapshot.get('nodes', [])))
def resource_slots(task, key):
return max(1, task.snapshot.get('resource_slots', {}).get(key, 1))
def execution_slots(task):
return max([1, *[resource_slots(task, key) for key in resources(task)]])
def summary_model_keys(task):
"""Workbench/hub document summarization; heading repair and workflows differ."""
snapshot = task.snapshot or {}
if snapshot.get('engine'):
return []
return list(dict.fromkeys('model:' + str(node['model_id']) for node in snapshot.get('nodes', [])
if node.get('type') == 'organize' and node.get('operation') != 'heading_repair' and node.get('model_id')))
def summary_slots(task):
# Nodes in a document task run sequentially, while batches within one node
# can run in parallel using the model slots reserved in the task snapshot.
return max((resource_slots(task, key) for key in summary_model_keys(task)), default=0)
def priority(task):
# Aging prevents an endless stream of high-priority jobs starving older work.
age = max(0, (timezone.now() - task.created_at).total_seconds())
return min(20, int(task.snapshot.get('priority', 5)) + int(age // 300))
@transaction.atomic
def admit(dispatch='worker', task_id=None):
row = registry.settings_row(lock=True)
from system_manage.workbench_defaults import summary_concurrency_limit
summary_limit = summary_concurrency_limit()
running = list(AITask.objects.filter(status='RUNNING').only('snapshot'))
summary_occupied = sum(summary_slots(task) for task in running)
if sum(execution_slots(task) for task in running) >= row.meta.get('capacity', 4):
return None
# Keep an execution slot for interactive calls when capacity allows it.
capacity = row.meta.get('capacity', 4)
reserve = min(row.meta.get('interactive_reserve', 1), max(0, capacity - 1))
worker_occupied = sum(execution_slots(item) for item in running if item.snapshot.get('dispatch', 'worker') == 'worker')
if dispatch == 'worker' and worker_occupied >= capacity - reserve:
return None
occupied = Counter()
for task in running:
for key in resources(task):
occupied[key] += resource_slots(task, key)
pending = list(AITask.objects.filter(status='PENDING').only('id', 'snapshot', 'created_at', 'owner_id', 'workspace_id'))
pending.sort(key=lambda item: (-priority(item), item.created_at, str(item.id)))
from users.models import User
for item in pending:
keys_to_limit = summary_model_keys(item)
if keys_to_limit:
# Existing queued tasks may have been submitted before the limit
# was reduced. Use the currently available slots instead of
# leaving capacity idle; do not alter their saved input.
available = summary_limit - summary_occupied
if available < 1:
continue
snapshot = {**item.snapshot, 'resource_slots': dict(item.snapshot.get('resource_slots') or {})}
for key in keys_to_limit:
snapshot['resource_slots'][key] = min(resource_slots(item, key), available)
item.snapshot = snapshot
if sum(execution_slots(task) for task in running) + execution_slots(item) > capacity:
continue
if item.snapshot.get('dispatch', 'worker') == 'worker' and worker_occupied + execution_slots(item) > capacity - reserve:
continue
if item.snapshot.get('dispatch') == 'inline' and (timezone.now() - item.created_at).total_seconds() > item.snapshot.get('queue_timeout', 30) + 5:
AITask.objects.filter(pk=item.id, status='PENDING').update(status='FAILED', error='等待调用进程超时,请重新运行流程', finished_at=timezone.now())
continue
keys = resources(item)
try:
user = User.objects.get(pk=item.owner_id, is_active=True)
states = [registry.resolve(item.workspace_id, user, key)[0] for key in keys]
except Exception as exc:
from rest_framework.exceptions import APIException
if isinstance(exc, APIException) or isinstance(exc, User.DoesNotExist):
AITask.objects.filter(pk=item.id, status='PENDING').update(status='FAILED',
error='组件不可用或授权已变更,请检查后重新提交', finished_at=timezone.now())
continue
raise
if any(occupied[state['id']] + resource_slots(item, state['id']) > state['capacity'] for state in states):
continue
if item.snapshot.get('dispatch', 'worker') != dispatch:
return None
if task_id is not None and str(item.id) != str(task_id):
# Another inline caller owns the first eligible reservation.
return None
if AITask.objects.filter(pk=item.id, status='PENDING').update(status='RUNNING', snapshot=item.snapshot, started_at=timezone.now(), updated_at=timezone.now()):
return AITask.objects.get(pk=item.id)
return None
def finish(task, status, result=None, error=''):
values = {'status': status, 'error': error[:512], 'finished_at': timezone.now(), 'updated_at': timezone.now()}
if result is not None:
values['result'] = result
AITask.objects.filter(pk=task.id, attempt=task.attempt, status='RUNNING').update(**values)
def inline(workspace, user, component, invoke, *, parent=None, priority_value=5, wait_seconds=30, trace=None, task_context=False):
registry.resolve(workspace, user, component, check=not bool(parent))
if parent:
task = AITask.objects.filter(id=parent, workspace_id=workspace, owner_id=user.id, status='RUNNING').first()
if not task or component not in resources(task):
raise ValidationError('组件未纳入当前任务的资源预留')
# One workflow reserves one slot per resource. Parallel nodes sharing
# that reservation must serialize; unrelated resources still run in parallel.
with _parent_locks_guard:
key = (str(task.id), component)
lock = _parent_locks.get(key)
if lock is None:
lock = threading.Lock()
_parent_locks[key] = lock
with lock:
import uuid
call_id = str(uuid.uuid4())
def record(status, value=None):
with transaction.atomic():
current = AITask.objects.select_for_update().get(pk=task.id)
calls = current.result.get('calls', [])
entry = {'id': call_id, 'component_id': component, 'status': status,
'at': timezone.now().isoformat(), **safe_trace(trace)}
if value:
entry.update({key: value[key] for key in ('artifact_id', 'artifact_url') if key in value})
current.result = {**current.result, 'calls': [*filter(lambda row: row['id'] != call_id, calls), entry][-200:]}
current.save(update_fields=['result', 'updated_at'])
record('RUNNING')
try:
value = invoke(str(task.id)) if task_context else invoke()
record('SUCCESS', value)
return {**value, 'task_id': str(task.id)}
except Exception:
record('FAILED')
raise
with transaction.atomic():
from users.models import User
User.objects.select_for_update().get(pk=user.id)
if AITask.objects.filter(owner_id=user.id, status__in=ACTIVE).count() >= 10:
raise ValidationError('待处理任务已达上限')
task = AITask.objects.create(workspace_id=workspace, owner_id=user.id, name='组件调用',
snapshot={'engine': True, 'dispatch': 'inline', 'resources': [component], 'priority': priority_value,
'queue_timeout': wait_seconds, 'trace': safe_trace(trace)})
deadline = time.monotonic() + wait_seconds
try:
while not admit('inline', task.id):
task.refresh_from_db(fields=['status'])
if task.status != 'PENDING':
raise ValidationError('任务已取消或组件不可用')
if time.monotonic() >= deadline:
AITask.objects.filter(pk=task.id, status='PENDING').update(status='FAILED', error='等待资源超时', finished_at=timezone.now())
raise ValidationError('等待组件资源超时,请稍后重试')
time.sleep(.2)
close_old_connections()
stop = threading.Event()
def pulse():
while not stop.wait(5):
close_old_connections()
try:
AITask.objects.filter(pk=task.id, attempt=task.attempt, status='RUNNING').update(updated_at=timezone.now())
finally:
close_old_connections()
monitor = threading.Thread(target=pulse, daemon=True)
monitor.start()
try:
result = invoke(str(task.id)) if task_context else invoke()
task.refresh_from_db(fields=['result'])
result = {**task.result, **result}
finish(task, 'SUCCESS', result)
return {**result, 'task_id': str(task.id)}
finally:
stop.set()
monitor.join(timeout=6)
except Exception:
finish(task, 'FAILED', error='组件调用失败,请查看流程执行记录')
raise
def safe_trace(trace):
# Associations only: never persist connection config, headers or tool inputs.
return {key: str(value)[:160] for key, value in (trace or {}).items() if value is not None and key in (
'application_id', 'chat_id', 'chat_record_id', 'node_id', 'source', 'tool', 'server', 'viewer_id')}
@transaction.atomic
def cancel(task):
# Running work drains cooperatively; never release a slot while external work may continue.
if not AITask.objects.filter(pk=task.id, status='PENDING').update(status='CANCELLED', finished_at=timezone.now()):
raise ValidationError('仅排队任务可取消;运行中的任务等待当前执行结束')
def recover():
return AITask.objects.filter(status='RUNNING', updated_at__lt=timezone.now() - timedelta(minutes=30)).update(
status='FAILED', error='执行中断或长时间无心跳,请核对后重试', finished_at=timezone.now())
def heartbeat():
from system_manage.models import SystemSetting
SystemSetting.objects.update_or_create(type=11028, defaults={'meta': {'seen_at': timezone.now().isoformat()}})
def worker_online():
from datetime import datetime
from system_manage.models import SystemSetting
row = SystemSetting.objects.filter(pk=11028).first()
try: return bool(row and (timezone.now() - datetime.fromisoformat(row.meta['seen_at'])).total_seconds() < 20)
except (KeyError, ValueError, TypeError): return False