feat: enable multi-GPU FIFO task execution

This commit is contained in:
Codex 2026-11-11 10:59:33 +08:00
parent 5909e384fd
commit 89dcec1c3b
34 changed files with 1528 additions and 166 deletions

View File

@ -241,3 +241,9 @@ docker compose up -d api
- `/api/live` 为进程活性,`/api/ready` 检查数据库、协调器心跳、上游协议与维护状态;GPU繁忙不判为应用故障。
- 公网发布前在私有入口改掉初始管理员密码、改用本库专用MySQL业务账号,再配置HTTPS、`COOKIE_SECURE=true`和`PUBLIC_ACCESS=true`;服务端拒绝公开运行仍使用初始密码或MySQL root的配置。当前私有验收保持用户指定的数据库root配置。Nginx登录入口已有限流,不信任客户端任意X-Forwarded-For。
- `needs_attention`或未知HTTP执行需要运维确认远端请求已结束;不能仅清除数据库状态来恢复,更不能重启共享Qwen服务作为处理办法。
## 多GPU FIFO调度
每张符合条件的空闲GPU同时运行一个任务,最多四卡并行。就绪任务按持久入队顺序派发,完成顺序可不同;独立分镜和批次成员有界补队,合成等待全部选定输出。外部用户占用某张卡时,只让出该卡并重排对应任务。
工作容器内存上限为384 GiB(内存加swap总上限同为384 GiB);派发同时检查主存和共享内存预算。单卡68 GiB分配预算、8 GiB空闲预留和连续空闲15秒准入保持有效。管理员设置放在推理服务config/settings.json;修改runtime-policy.json仍只控制其已支持的时段/工作流字段。

View File

@ -1,4 +1,4 @@
"""Persistent mixed workflow/job batches with one eligible member at a time."""
"""Persistent mixed workflow/job batches with independently eligible members."""
from typing import Literal
from fastapi import APIRouter, Depends, Header, Request, HTTPException
from pydantic import Field
@ -34,7 +34,7 @@ class BatchControl(Strict):
expected_version:int|None=Field(default=None,ge=1)
def batch_dto(b,items):
return dict(id=b.id,name=b.name,state=b.state,desired_state=b.desired_state,hold_reasons=b.hold_reasons or [],version=b.version,created_at=iso(b.created_at),finished_at=iso(b.finished_at),total_items=len(items),completed_items=sum(i.state=='succeeded' for i in items),current_item_index=next((i.item_index for i in items if i.state=='running'),None))
return dict(id=b.id,name=b.name,state=b.state,desired_state=b.desired_state,hold_reasons=b.hold_reasons or [],version=b.version,created_at=iso(b.created_at),finished_at=iso(b.finished_at),total_items=len(items),completed_items=sum(i.state=='succeeded' for i in items),current_item_index=next((i.item_index for i in items if i.state=='running'),None),active_item_indices=[i.item_index for i in items if i.state in {'running','cleanup_pending'}],active_item_count=sum(i.state in {'running','cleanup_pending'} for i in items))
async def snapshot_batch(s,owner,id):
b=await owned(s,Batch,id,owner)
items=(await s.scalars(select(BatchItem).where(BatchItem.batch_id==b.id).order_by(BatchItem.item_index))).all()
@ -69,9 +69,7 @@ def member_holds(holds,b,waiting):
async def run_member_holds(s,r):
b=await s.get(Batch,r.batch_id)
if b is None or b.deleted_at is not None:return set(r.hold_reasons or [])|{'batch_wait'}
items=(await s.scalars(select(BatchItem).where(BatchItem.batch_id==b.id).order_by(BatchItem.item_index))).all()
active=await active_member(s,items)
return member_holds(r.hold_reasons,b,active is not None and active.target_id!=r.id)
return member_holds(r.hold_reasons,b,False)
async def advance_batches(s,settings):
batches=(await s.scalars(select(Batch).where(Batch.deleted_at.is_(None),Batch.state.not_in({'succeeded','cancelled','completed_with_errors'})).order_by(Batch.created_at,Batch.id).with_for_update())).all()
@ -94,15 +92,19 @@ async def advance_batches(s,settings):
for item in items:
if item.target_kind=='run':
target=await s.get(WorkflowRun,item.target_id)
holds=sorted(member_holds(target.hold_reasons,b,item!=active))
holds=sorted(member_holds(target.hold_reasons,b,False))
if target.hold_reasons!=holds:
target.hold_reasons=holds;await emit_run(s,target)
jobs=(await s.scalars(select(Job).where(Job.run_id==item.target_id,Job.state.not_in(TERMINAL)))).all()
else:
jobs=(await s.scalars(select(Job).where(Job.batch_id==b.id,Job.batch_item_index==item.item_index,Job.state.not_in(TERMINAL)))).all()
for j in jobs:
holds=member_holds(j.hold_reasons,b,item!=active)
if item.target_kind=='run':holds|=set(target.hold_reasons or [])
holds=member_holds(j.hold_reasons,b,False)
if item.target_kind=='run':
# Parent admission pressure must not stop accepted children
# from completing and freeing the very quota it waits for.
holds-= {'quota','storage'}
holds|=set(target.hold_reasons or [])-{'quota','storage'}
holds=sorted(holds)
if j.hold_reasons!=holds:
j.hold_reasons=holds;await emit_job(s,j)
@ -144,7 +146,6 @@ async def post_batch(body:BatchCreate,request:Request,idempotency_key:str|None=H
jobs=await create_jobs(s,Submit(task_type=item.task_type,input=item.input,parameters=item.parameters,count=item.count,execution_mode='batch'),actor,request.app.state.settings,key=f'batch:{b.id}:{idx}',internal=True)
for j in jobs:
j.batch_id=b.id;j.batch_item_index=idx
if idx:j.hold_reasons=['batch_wait']
await emit_job(s,j)
kind,target='job',jobs[0].id
s.add(BatchItem(batch_id=b.id,item_index=idx,target_kind=kind,target_id=target,spec_json=item.model_dump(mode='json')))

View File

@ -26,6 +26,8 @@ class Coordinator:
self.settings, self.db, self.provider = settings, db, provider
self._task = None
self._cpu = {}
self._preparing = {}
self._collecting = {}
# Bound pending coroutines independently of their current phase/slot.
# A Qwen quarantine must leave capacity for unrelated media work.
self._cpu_initial_pool = {}
@ -98,9 +100,9 @@ class Coordinator:
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)
background=[*self._cpu.values(),*self._preparing.values(),*self._collecting.values()]
for task in background:task.cancel()
await asyncio.gather(*background, return_exceptions=True)
if self._file_lock.is_locked:
self._file_lock.release()
@ -235,6 +237,9 @@ class Coordinator:
def _clock_allows(self,job):
if job.execution_mode!="batch":return True
return self._batch_clock_allows()
def _batch_clock_allows(self):
from .runtime_policy import read_runtime_policy
from .resource_policy import execution_policy
policy=read_runtime_policy(self.settings)
@ -253,6 +258,11 @@ class Coordinator:
self._cpu.pop(job_id)
self._cpu_initial_pool.pop(job_id, None)
await asyncio.gather(task, return_exceptions=True)
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)
async with self.db.session() as session:
query = select(Job).where(Job.deleted_at.is_(None), Job.state.notin_(TERMINAL))
if not force:
@ -260,6 +270,17 @@ class Coordinator:
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())
# 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]
# 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),
@ -269,7 +290,28 @@ class Coordinator:
# 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
# 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]
for job in jobs:
job=await self._job(job.id)
if job.scheduled_at and job.scheduled_at > utcnow():
continue
# Every inspected candidate moves forward, even when CPU is
@ -298,13 +340,22 @@ class Coordinator:
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.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
if job.task_type in GPU_TYPES:
await self._gpu(job)
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)
elif job.state == "collecting":
try:
await self._collect_cpu(job)
except Exception as exc:
await self._warning(job.id, exc)
if len(self._collecting)<2:
self._collecting[job.id]=asyncio.create_task(self._collect_cpu_background(job),name=f"collect-{job.id}")
elif job.state in {"submitting","queued","scheduled","cancelling"}:
from .resource_policy import resource_plan
initial_pool = resource_plan(job.task_type)[0][1]
@ -314,10 +365,16 @@ class Coordinator:
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._collecting:
await asyncio.wait(list(self._collecting.values()),timeout=.1)
if self.after_tick is not None:
await self.after_tick()
async def _gpu(self, job):
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):
try:
job = await self._job(job.id)
if job is None or job.deleted_at is not None or job.state in TERMINAL:return
@ -359,6 +416,7 @@ class Coordinator:
if job.cancel_requested:
await self._update(job.id, state="cancelled", phase="cancelled", finished_at=utcnow())
return
if prepare_only: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":
@ -384,7 +442,7 @@ class Coordinator:
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)
await self._apply_remote(job.id, remote, defer_collection=True)
except PhaseDeferred:
await self._update(job.id,state="submitting",phase="waiting_phase")
except asyncio.CancelledError:
@ -400,7 +458,7 @@ class Coordinator:
LOG.exception("Job %s preparation failed", job.id)
await self._failure(job.id, exc)
async def _apply_remote(self, job_id, remote):
async def _apply_remote(self, job_id, remote, *, defer_collection=False):
state = remote.get("state")
if state not in {"queued", "running", "paused", "pausing", "succeeded", "failed", "cancelled", "timed_out"}:
raise ValueError("Invalid upstream job state")
@ -421,7 +479,11 @@ class Coordinator:
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)
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)
async def _collect_gpu(self, job):
fence=(job.upstream_result or {}).get("_visual_execution")

View File

@ -0,0 +1,68 @@
"""Public GPU summary. Never expose scheduler job IDs or host PID details."""
import math
from datetime import datetime, timezone
def summarize(gpus, scheduler, now, generated):
active, queued = [], None
try:
stamp = scheduler['updated_at']
if type(stamp) not in (int, float) or not math.isfinite(stamp) or not now - 5 <= stamp <= now + 1:
raise ValueError('Stale scheduler')
if scheduler.get('schema_version') == 2:
entries = scheduler.get('active_jobs', [])
if not isinstance(entries, list) or len(entries) > len(gpus):
raise ValueError('Invalid active list')
indexes = set()
for entry in entries:
index = entry['gpu_index']
if type(index) is not int or index in indexes or not any(
row['index'] == index and row['_uuid'] == entry['gpu_uuid'] for row in gpus
):
raise ValueError('Invalid lease')
indexes.add(index)
count = scheduler.get('queued_count')
if count is not None and (type(count) is not int or not 0 <= count <= 10000000):
raise ValueError('Invalid queue count')
active, queued = entries, count
elif scheduler.get('state') == 'leased':
lease = scheduler.get('lease') or {}
active = [{'gpu_index': lease.get('index'), 'gpu_uuid': lease.get('uuid'), 'state': 'running'}]
except (KeyError, TypeError, ValueError):
scheduler, active, queued = None, [], None
active_indexes = set()
for entry in active:
gpu = next((row for row in gpus if row['index'] == entry.get('gpu_index')
and row['_uuid'] == entry.get('gpu_uuid')), None)
if gpu is None:
continue
active_indexes.add(gpu['index'])
state = entry.get('state')
gpu.update(busy=True, eligible=False,
state=state if state in {'preempting', 'blocked', 'launching'} else 'running',
stage=entry.get('stage') if entry.get('stage') in
{'launching', 'executing', 'cleanup', 'model', 'upscale', 'collecting'} else None)
running = sum(row['index'] in active_indexes or row['_own'] for row in gpus)
available = sum(row['eligible'] for row in gpus)
state = 'running' if running else 'ready' if available else 'waiting'
reason = (f'正在运行{running}个GPU任务,{available}张卡可接新任务。' if running
else None if available else '等待可用GPU,外部任务优先。')
dispatch_blocked = bool(scheduler and scheduler.get('state') == 'blocked')
if dispatch_blocked:
reason = '执行器需要管理员检查,新任务暂停派发。'
if not running:
state = 'blocked'
available = 0
for gpu in gpus:
gpu['eligible'] = False
if gpu['state'] == 'ready':
gpu['state'] = 'waiting'
elif scheduler and 'memory' in str(scheduler.get('reason', '')).lower():
reason = '共享内存不足,任务按入队顺序等待资源。'
for gpu in gpus:
gpu.pop('_uuid')
gpu.pop('_own')
return {'available': True, 'state': state, 'reason': reason, 'gpus': gpus,
'running_count': running, 'available_count': available, 'queued_count': queued,
'dispatch_blocked': dispatch_blocked,
'updated_at': datetime.fromtimestamp(generated, timezone.utc).isoformat()}

View File

@ -381,23 +381,20 @@ class Provider:
if idle is not None:
idle = _float(idle, 0, now + 1)
busy = bool(external or own)
eligible = not busy and free >= 76 and idle is not None and now - idle >= 15
gpus.append({'index': index, 'name': f'GPU {index}', 'busy': busy,
'eligible': not busy and free >= 76 and idle is not None and now - idle >= 15, 'free_gib': free})
state = 'ready' if any(gpu['eligible'] for gpu in gpus) else 'waiting'
reason = None if state == 'ready' else '等待可用GPU,外部任务优先。'
'eligible': eligible, 'free_gib': free, '_uuid': gpu['uuid'], '_own': bool(own),
'state': 'external' if external else 'running' if own else 'ready' if eligible else 'waiting',
'stage': None})
scheduler = None
try:
scheduler_path = Path(self.settings.gpu_scheduler_path)
if scheduler_path.stat().st_size <= 1024 * 1024:
scheduler = json.loads(scheduler_path.read_bytes())
if scheduler.get('state') in {'blocked', 'preempting'}:
state = scheduler['state']
reason = '正在释放GPU并等待重新排队。' if state == 'preempting' else '执行器需要管理员检查。'
elif scheduler.get('state') == 'leased' and any(gpu['busy'] for gpu in gpus):
state, reason = 'running', '模型任务正在执行。'
except (OSError, ValueError, TypeError, AttributeError):
pass
return {'available': True, 'state': state, 'reason': reason, 'gpus': gpus,
'updated_at': datetime.fromtimestamp(generated, timezone.utc).isoformat()}
from .gpu_summary import summarize
return summarize(gpus, scheduler, now, generated)
except (OSError, ValueError, TypeError, KeyError, AttributeError, ProviderError, OverflowError):
return unavailable

View File

@ -1,16 +1,26 @@
"""Durable orchestration only: never execute a model or a media process here."""
import logging
from fastapi import HTTPException
from sqlalchemy import select
from sqlalchemy import select, func
from .models import Job, utcnow
from .v2_models import WorkflowRun, WorkflowStep, AssetReference
from .jobs import TERMINAL
from .jobs import TERMINAL, GPU_TYPES
from .workflows import RUN_TERMINAL, create_child, emit_run, selected_output
from .timeline import ordered_step_keys
log=logging.getLogger(__name__)
AUTOMATIC_HOLDS={'quota','storage'}
async def child_capacity(session, r, step, settings):
active=Job.state.not_in(TERMINAL)
own=await session.scalar(select(func.count()).select_from(Job).where(Job.owner_id==r.owner_id,active))
total=await session.scalar(select(func.count()).select_from(Job).where(active))
if own>=settings.max_owner_jobs or total>=settings.max_global_jobs:return False
if r.execution_mode=='interactive' and step.kind in GPU_TYPES:
gpu=await session.scalar(select(func.count()).select_from(Job).where(Job.owner_id==r.owner_id,active,Job.execution_mode=='interactive',Job.task_type.in_(GPU_TYPES)))
if gpu>=settings.max_interactive_gpu_jobs:return False
return True
async def advance_run(session,run_id,settings):
r=await session.scalar(select(WorkflowRun).where(WorkflowRun.id==run_id,WorkflowRun.deleted_at.is_(None)).with_for_update())
if not r or r.state in RUN_TERMINAL:return
@ -52,6 +62,7 @@ async def advance_run(session,run_id,settings):
r.state='paused'
else:
r.state='running';r.started_at=r.started_at or utcnow()
admitted=0
for key in ordered_step_keys(r.spec_snapshot):
step=bykey[key]
if step.state=='succeeded':continue
@ -62,8 +73,26 @@ async def advance_run(session,run_id,settings):
if maintenance_active(settings):
r.state='queued'
break
await create_child(session,r,step,settings);changed=True
break
if admitted>=8:break
if not await child_capacity(session,r,step,settings):
r.hold_reasons=sorted(set(r.hold_reasons or [])|{'quota'})
r.error_json={'code':'quota_exceeded','admission_pending':True}
break
try:
# An individual rejected leaf cannot roll back siblings
# already accepted in this run's transaction.
async with session.begin_nested():
await create_child(session,r,step,settings)
except HTTPException as exc:
code=exc.detail.get('code') if isinstance(exc.detail,dict) else None
if code not in {'quota_exceeded','storage_insufficient'}:raise
await session.refresh(step)
await session.refresh(r)
hold='quota' if code=='quota_exceeded' else 'storage'
r.hold_reasons=sorted(set(r.hold_reasons or [])|{hold})
r.error_json={'code':code,'admission_pending':True}
break
admitted+=1;changed=True
if changed or before!=(r.state,r.current_output_asset_id,r.error_json,tuple(r.hold_reasons or [])):await emit_run(session,r)
async def advance_workflows(db,settings,provider):

View File

@ -101,6 +101,13 @@ async def test_unsupported_parameters_are_rejected_before_job_creation(system):
async def test_definitive_upstream_input_rejection_is_terminal_not_retried_forever(system):
job = (await submit(system))[0]
system.provider.reject_submission = True
# Exercise definitive POST rejection with an already-ready payload;
# independent background preparation need not finish within one tick.
from app.models import Job
async with system.app.state.db.session() as session:
row=await session.get(Job,job['id'])
row.upstream_payload={'task_type':row.task_type,'input':row.input_json,'parameters':row.parameters,'timeout_seconds':3600}
await session.commit()
await system.app.state.coordinator.run_once(force=True)
current = (await system.client.get(f"/api/jobs/{job['id']}")).json()
assert current["state"] == "failed" and current["error"]["code"] == "upstream_rejected"
@ -245,8 +252,9 @@ async def test_large_waiting_gpu_queue_does_not_starve_later_cpu_or_cancel(syste
ids.extend(job["id"] for job in await submit(system, count=4))
cpu = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0]
coordinator = system.app.state.coordinator
await coordinator.run_once(force=True)
await coordinator.run_once(force=True)
for _ in range(15):
await coordinator.run_once(force=True)
if len(system.provider.accepted)==52:break
await asyncio.gather(*list(coordinator._cpu.values()))
assert system.provider.cpu_runs == 1 and len(system.provider.accepted) == 52
assert (await system.client.get(f"/api/jobs/{cpu['id']}")).json()["state"] == "succeeded"

View File

@ -0,0 +1,190 @@
import asyncio
from datetime import timedelta
from sqlalchemy import select
from app.models import Job, utcnow
from test_workflows_v2 import wf, draft, run, publish_video
from test_timeline_v2 import spec
from test_multishot_v3 import story
import pytest
from test_jobs import submit
async def tick(wf):
from app.workflow_engine import advance_workflows
await advance_workflows(wf.app.state.db,wf.settings,wf.provider)
async def test_three_ready_shots_and_compose_waits_all(wf):
rid=(await run(wf,await draft(wf)))['run']['id']
await tick(wf)
async with wf.app.state.db.session() as s:
jobs=(await s.scalars(select(Job).where(Job.run_id==rid).order_by(Job.created_at))).all()
assert [j.step_key for j in jobs]==['shot_1','shot_2','shot_3']
for j in jobs[:2]: await publish_video(wf,j.id)
await tick(wf)
async with wf.app.state.db.session() as s:
assert not await s.scalar(select(Job.id).where(Job.run_id==rid,Job.step_key=='compose'))
await publish_video(wf,jobs[2].id)
await tick(wf)
async with wf.app.state.db.session() as s:
assert await s.scalar(select(Job.id).where(Job.run_id==rid,Job.step_key=='compose'))
@pytest.mark.parametrize('count',[12,20])
async def test_many_ready_shots_replenish_eight_slot_quota(wf,count):
body=story(count)
d=await wf.client.post('/api/workflows',json={'spec':body});assert d.status_code==201,d.text
rid=(await run(wf,d.json()))['run']['id']
for expected in ([8,4] if count==12 else [8,8,4]):
await tick(wf)
async with wf.app.state.db.session() as s:
jobs=(await s.scalars(select(Job).where(Job.run_id==rid,Job.state!='succeeded'))).all()
assert len(jobs)==expected
for j in jobs: await publish_video(wf,j.id)
async def test_two_batch_members_admitted_together(wf):
response=await wf.client.post('/api/batches',json={'items':[{'kind':'job','task_type':'image.generate','input':{'prompt':p}} for p in ('a','b')]},headers={'Idempotency-Key':'pair'})
assert response.status_code==202,response.text
await tick(wf)
async with wf.app.state.db.session() as s:
jobs=(await s.scalars(select(Job))).all()
assert len(jobs)==2 and all('batch_wait' not in j.hold_reasons for j in jobs)
async def test_ready_fifo_ignores_poll_retry_timestamps(system):
first=(await submit(system,input={'prompt':'first'}))[0]; second=(await submit(system,input={'prompt':'second'}))[0]
async with system.app.state.db.session() as s:
a=await s.get(Job,first['id']);b=await s.get(Job,second['id'])
# Both payloads are already ready; preparation completion is independent
# and intentionally does not define this FIFO assertion.
for j in (a,b):
j.upstream_payload={'task_type':j.task_type,'input':j.input_json,'parameters':j.parameters,'timeout_seconds':3600}
a.next_action_at=utcnow()+timedelta(hours=1);b.next_action_at=utcnow()-timedelta(hours=1)
await s.commit()
await system.app.state.coordinator.run_once()
assert [p[1]['input']['prompt'] for p in system.provider.submitted_payloads]==['first','second']
async def test_slow_preparation_does_not_starve_ready_or_existing(system,monkeypatch):
first=(await submit(system))[0]
c=system.app.state.coordinator
for _ in range(10):
await c.run_once(force=True)
existing=await c._job(first['id'])
if existing.upstream_id:break
assert existing.upstream_id,'Fixture must have an accepted remote execution'
await submit(system,input={'prompt':'slow'})
ready=(await submit(system,input={'prompt':'ready'}))[0]
# The contender is explicitly ready before measuring dispatch starvation.
async with system.app.state.db.session() as s:
row=await s.get(Job,ready['id'])
row.upstream_payload={'task_type':row.task_type,'input':row.input_json,'parameters':row.parameters,'timeout_seconds':3600}
await s.commit()
original=system.provider.prepare_gpu_payload
gate=asyncio.Event();queries=[];query=system.provider.query
async def prepare(task_type,inputs,*args):
if inputs['prompt']=='slow':await gate.wait()
return await original(task_type,inputs,*args)
async def observed(remote): queries.append(remote);return await query(remote)
monkeypatch.setattr(system.provider,'prepare_gpu_payload',prepare)
monkeypatch.setattr(system.provider,'query',observed)
try:
await asyncio.wait_for(system.app.state.coordinator.run_once(force=True),1)
assert existing.upstream_id in queries
assert any(p[1]['input']['prompt']=='ready' for p in system.provider.submitted_payloads)
finally:gate.set()
async def test_slow_collection_does_not_starve_ready_submission(system,monkeypatch):
await submit(system)
await system.app.state.coordinator.run_once(force=True)
await submit(system,input={'prompt':'ready'})
system.provider.remote['remote-1'].update(state='succeeded',result={'outputs':[{'path':'one.png'}]})
gate=asyncio.Event();original=system.provider.download
async def download(*args):
await gate.wait()
return await original(*args)
monkeypatch.setattr(system.provider,'download',download)
try:
await asyncio.wait_for(system.app.state.coordinator.run_once(force=True),1)
assert len(system.provider.accepted)==2
finally:gate.set()
async def test_cancelling_one_child_preserves_sibling_executions(wf):
rid=(await run(wf,await draft(wf)))['run']['id']
await tick(wf)
for _ in range(10):
await wf.app.state.coordinator.run_once(force=True)
if len(wf.provider.accepted)==3:break
assert len(wf.provider.accepted)==3
async with wf.app.state.db.session() as s:
jobs=(await s.scalars(select(Job).where(Job.run_id==rid).order_by(Job.created_at))).all()
assert len(jobs)==3
response=await wf.client.post('/api/jobs/'+jobs[0].id+'/cancel',json={})
assert response.status_code==200,response.text
await wf.app.state.coordinator.run_once(force=True)
async with wf.app.state.db.session() as s:
assert (await s.get(Job,jobs[0].id)).state=='cancelled'
assert all([(await s.get(Job,j.id)).state=='queued' for j in jobs[1:]])
async def test_due_submit_retry_keeps_creation_fifo(system):
await submit(system,input={'prompt':'first'})
system.provider.lost_response=True
await system.app.state.coordinator.run_once(force=True)
await submit(system,input={'prompt':'second'})
async with system.app.state.db.session() as s:
first=await s.scalar(select(Job).where(Job.input_json['prompt'].as_string()=='first'))
first.next_action_at=utcnow()-timedelta(seconds=1)
await s.commit()
await system.app.state.coordinator.run_once()
assert [p[1]['input']['prompt'] for p in system.provider.submitted_payloads]==['first','first','second']
async def test_held_prefix_cannot_hide_ready_fifo(system):
from app.models import new_id
system.settings.max_interactive_gpu_jobs=100
first=(await submit(system,input={'prompt':'first'}))[0]
await submit(system,input={'prompt':'second'})
async with system.app.state.db.session() as s:
owner=(await s.get(Job,first['id'])).owner_id
for _ in range(25):
jid=new_id()
s.add(Job(id=jid,owner_id=owner,task_type='image.generate',state='submitting',phase='waiting_dispatch',input_json={'prompt':'held'},parameters={},request_hash='fixture',upstream_key=jid,hold_reasons=['manual'],created_at=utcnow()-timedelta(days=1),next_action_at=utcnow()+timedelta(hours=1)))
for j in (await s.scalars(select(Job).where(Job.owner_id==owner,Job.hold_reasons==[]))).all():
j.upstream_payload={'task_type':j.task_type,'input':j.input_json,'parameters':j.parameters,'timeout_seconds':3600}
(await s.get(Job,first['id'])).next_action_at=utcnow()+timedelta(hours=1)
await s.commit()
await system.app.state.coordinator.run_once()
assert [p[1]['input']['prompt'] for p in system.provider.submitted_payloads]==['first','second']
async def test_prepared_overflow_never_inherits_poll_order(system):
from app.models import new_id
owner=(await system.client.get('/api/auth/me')).json()['user']['id']
expected=[f'ready-{i}' for i in range(27)]
base=utcnow()-timedelta(days=1)
async with system.app.state.db.session() as s:
for i,prompt in enumerate(expected):
jid=new_id();payload={'task_type':'image.generate','input':{'prompt':prompt},'parameters':{},'timeout_seconds':3600}
s.add(Job(id=jid,owner_id=owner,task_type='image.generate',state='submitting',phase='dispatching',input_json={'prompt':prompt},parameters={},request_hash='fixture',upstream_key=jid,upstream_payload=payload,created_at=base+timedelta(microseconds=i),next_action_at=utcnow()-timedelta(seconds=i+1)))
await s.commit()
for _ in range(2):
await system.app.state.coordinator.run_once()
submitted=[p[1]['input']['prompt'] for p in system.provider.submitted_payloads]
assert submitted==expected[:len(submitted)]
assert len(submitted)==27
async def test_preparing_payload_cannot_race_dispatch_and_orphan_cancel(system,monkeypatch):
job=(await submit(system))[0];c=system.app.state.coordinator
entered=asyncio.Event();release=asyncio.Event();original=c._job
async def gated(job_id):
current=await original(job_id)
if asyncio.current_task().get_name().startswith('prepare-') and current.upstream_payload is not None:
entered.set();await release.wait()
return await original(job_id)
return current
monkeypatch.setattr(c,'_job',gated)
task=asyncio.create_task(c.run_once(force=True))
try:
await asyncio.wait_for(entered.wait(),2)
await asyncio.wait_for(task,2)
await system.client.post('/api/jobs/'+job['id']+'/cancel')
release.set()
await asyncio.gather(*list(c._preparing.values()))
assert not system.provider.accepted
current=await original(job['id'])
assert current.state=='cancelled' and current.upstream_id is None
finally:
release.set();await asyncio.gather(task,return_exceptions=True)

View File

@ -0,0 +1,104 @@
import json
import time
from types import SimpleNamespace
import pytest
from app.providers import Provider
@pytest.fixture
def resource_files(tmp_path):
settings = SimpleNamespace(gpu_status_path=tmp_path / 'status.json',
gpu_scheduler_path=tmp_path / 'scheduler.json')
now = time.time()
status = {'schema_version': 1, 'generated_at': now, 'error': None,
'container_id': 'b' * 64, 'gpus': []}
for index in range(4):
status['gpus'].append({'index': index,
'uuid': f'GPU-00000000-0000-0000-0000-{index:012d}',
'total_gib': 79.6, 'free_gib': 79.0, 'idle_since': now - 30,
'own_pids': [], 'external_pids': [], 'baseline_pids': [2880]})
settings.gpu_status_path.write_text(json.dumps(status))
provider = Provider.__new__(Provider)
provider.settings = settings
return provider, settings, status
@pytest.mark.asyncio
async def test_parallel_running_and_preempting_are_reported_per_card(resource_files):
provider, settings, status = resource_files
status['gpus'][0]['external_pids'] = [99991]
status['gpus'][0]['free_gib'] = 10
for index in (1, 2):
status['gpus'][index]['own_pids'] = [77770 + index]
status['gpus'][index]['free_gib'] = 30
settings.gpu_status_path.write_text(json.dumps(status))
settings.gpu_scheduler_path.write_text(json.dumps({
'schema_version': 2, 'state': 'running', 'updated_at': time.time(),
'queued_count': 2, 'running_count': 2,
'active_jobs': [
{'job_id': 'PRIVATE-OWNER-JOB-A', 'gpu_index': 1,
'gpu_uuid': status['gpus'][1]['uuid'], 'state': 'running',
'stage': 'executing', 'attempt_count': 1, 'reason': None},
{'job_id': 'PRIVATE-OWNER-JOB-B', 'gpu_index': 2,
'gpu_uuid': status['gpus'][2]['uuid'], 'state': 'preempting',
'stage': 'cleanup', 'attempt_count': 1, 'reason': 'external user'}]}))
result = await provider.scheduler_status()
assert result['state'] == 'running'
assert result['running_count'] == 2
assert result['available_count'] == 1
assert result['queued_count'] == 2
assert [gpu['state'] for gpu in result['gpus']] == ['external', 'running', 'preempting', 'ready']
assert 'PRIVATE-OWNER' not in json.dumps(result)
assert '99991' not in json.dumps(result)
assert '77771' not in json.dumps(result)
@pytest.mark.asyncio
async def test_lease_reserves_card_before_cuda_process_appears(resource_files):
provider, settings, status = resource_files
settings.gpu_scheduler_path.write_text(json.dumps({
'schema_version': 2, 'state': 'running', 'updated_at': time.time(),
'queued_count': 0, 'active_jobs': [
{'gpu_index': 1, 'gpu_uuid': status['gpus'][1]['uuid'],
'state': 'launching', 'stage': 'launching'}]}))
result = await provider.scheduler_status()
assert result['running_count'] == 1
assert result['gpus'][1]['busy'] is True
assert result['gpus'][1]['eligible'] is False
assert result['available_count'] == 3
@pytest.mark.asyncio
async def test_old_scheduler_schema_and_stale_aggregate_are_compatible(resource_files):
provider, settings, status = resource_files
settings.gpu_scheduler_path.write_text(json.dumps({'state': 'leased',
'updated_at': time.time(), 'lease': {'index': 2, 'uuid': status['gpus'][2]['uuid']}}))
result = await provider.scheduler_status()
assert result['running_count'] == 1
assert result['gpus'][2]['state'] == 'running'
settings.gpu_scheduler_path.write_text(json.dumps({'schema_version': 2,
'state': 'blocked', 'updated_at': time.time() - 120, 'active_jobs': [], 'queued_count': 4}))
result = await provider.scheduler_status()
assert result['available'] is True
assert result['state'] == 'ready'
assert result['queued_count'] is None
@pytest.mark.asyncio
async def test_executor_failure_pauses_dispatch_without_hiding_other_running_card(resource_files):
provider, settings, status = resource_files
settings.gpu_scheduler_path.write_text(json.dumps({
'schema_version': 2, 'state': 'blocked', 'updated_at': time.time(),
'queued_count': 1, 'active_jobs': [
{'gpu_index': 1, 'gpu_uuid': status['gpus'][1]['uuid'], 'state': 'blocked'},
{'gpu_index': 2, 'gpu_uuid': status['gpus'][2]['uuid'], 'state': 'running'}]}))
result = await provider.scheduler_status()
assert result['dispatch_blocked'] is True
assert '管理员' in result['reason']
assert result['running_count'] == 2
assert result['available_count'] == 0
assert result['gpus'][1]['state'] == 'blocked'
assert result['gpus'][2]['state'] == 'running'
assert result['gpus'][0]['eligible'] is False

View File

@ -96,13 +96,16 @@ async def test_run_delete_cascades_jobs_clears_draft_pointer_and_releases_refs(s
rid = snapshot['run']['id']
await cancel_workflow(system, rid)
snapshot = (await system.client.get('/api/workflow-runs/' + rid)).json()
jid = snapshot['jobs'][0]['id']
jids = sorted(j['id'] for j in snapshot['jobs'])
assert len(jids)==3
jid = jids[0]
child_delete = await system.client.delete('/api/jobs/' + jid)
assert child_delete.status_code == 409
assert child_delete.json()['detail']['code'] == 'parent_control_required'
response = await system.client.delete('/api/workflow-runs/' + rid)
assert response.status_code == 200, response.text
assert response.json()['deleted'] == {'job_ids': [jid], 'run_ids': [rid], 'draft_ids': [], 'batch_ids': []}
deleted=response.json()['deleted']
assert {**deleted,'job_ids':sorted(deleted['job_ids'])} == {'job_ids': jids, 'run_ids': [rid], 'draft_ids': [], 'batch_ids': []}
current = (await system.client.get('/api/workflows/' + draft['id'])).json()
assert current['current_run_id'] is None
assert (await system.client.get('/api/workflow-runs')).json()['total'] == 0
@ -110,7 +113,7 @@ async def test_run_delete_cascades_jobs_clears_draft_pointer_and_releases_refs(s
assert (await system.client.post(f"/api/workflows/{draft['id']}/runs", json=body,
headers={'Idempotency-Key': 'run'})).status_code == 410
async with system.app.state.db.session() as session:
assert not (await session.scalars(select(JobAsset).where(JobAsset.job_id == jid))).all()
assert not (await session.scalars(select(JobAsset).where(JobAsset.job_id.in_(jids)))).all()
assert not (await session.scalars(select(AssetReference).where(
AssetReference.ref_kind == 'run', AssetReference.ref_id == rid))).all()

View File

@ -76,7 +76,7 @@ async def test_retry_inherits_pause_manual_and_admin_holds(wf):
@pytest.mark.asyncio
async def test_retry_old_batch_member_waits_for_later_active_member(wf):
async def test_retry_old_batch_member_can_coexist_with_later_member(wf):
batch=await workflow_batch(wf,extra=[{'kind':'job','task_type':'image.generate','input':{'prompt':'later'}}])
rid=batch['items'][0]['target_id']; later_id=batch['items'][1]['target_id']
await tick(wf)
@ -91,7 +91,7 @@ async def test_retry_old_batch_member_waits_for_later_active_member(wf):
for _ in range(2):
await tick(wf)
async with wf.app.state.db.session() as s:
assert 'batch_wait' in (await s.get(Job,new_id)).hold_reasons
assert 'batch_wait' not in (await s.get(Job,new_id)).hold_reasons
assert 'batch_wait' not in (await s.get(Job,later_id)).hold_reasons
async with wf.app.state.db.session() as s:
later=await s.get(Job,later_id);later.state='succeeded';await s.commit()
@ -114,11 +114,13 @@ async def test_two_accepted_batches_preserve_first_child_and_retry_quota_hold(wf
await tick(wf)
async with wf.app.state.db.session() as s:
assert await s.scalar(select(Job.id).where(Job.run_id==two['items'][0]['target_id']))
assert 'quota' not in (await s.get(WorkflowRun,two['items'][0]['target_id'])).hold_reasons
assert 'quota' in (await s.get(WorkflowRun,two['items'][0]['target_id'])).hold_reasons
admitted=await s.scalar(select(Job).where(Job.run_id==two['items'][0]['target_id']))
assert 'quota' not in admitted.hold_reasons
@pytest.mark.asyncio
async def test_retry_waits_for_active_sibling_when_batch_representative_finished_held(wf):
async def test_retry_coexists_with_active_sibling_when_representative_finished(wf):
batch=await workflow_batch(wf,extra=[{'kind':'job','task_type':'image.generate','input':{'prompt':'pair'},'count':2}])
rid=batch['items'][0]['target_id'];bid=batch['batch']['id']
await tick(wf)
@ -134,7 +136,7 @@ async def test_retry_waits_for_active_sibling_when_batch_representative_finished
retried=next(x['selected_job_id'] for x in response.json()['steps'] if x['step_key']=='shot_1')
await tick(wf)
async with wf.app.state.db.session() as s:
assert 'batch_wait' in (await s.get(Job,retried)).hold_reasons
assert 'batch_wait' not in (await s.get(Job,retried)).hold_reasons
sibling=await s.scalar(select(Job).where(Job.batch_id==bid,Job.batch_item_index==1,Job.state!='cancelled'))
assert 'batch_wait' not in sibling.hold_reasons

View File

@ -35,18 +35,18 @@ async def test_snapshot_version_idempotency_owner(wf,other_client):
row = await s.get(WorkflowRun,a['run']['id']); assert row.spec_snapshot['shots'][0]['prompt'] != 'new prompt'
@pytest.mark.asyncio
async def test_engine_durable_sequential_cancel_and_no_new_job(wf):
async def test_engine_durable_parallel_cancel_and_no_new_job(wf):
from app.workflow_engine import advance_workflows
d = await draft(wf); snap = await run(wf,d)
await advance_workflows(wf.app.state.db,wf.settings,wf.provider)
await advance_workflows(wf.app.state.db,wf.settings,wf.provider)
snap = (await wf.client.get('/api/workflow-runs/'+snap['run']['id'])).json()
assert len(snap['jobs']) == 1 and snap['jobs'][0]['step_key'] == 'shot_1'
assert len(snap['jobs']) == 3 and snap['jobs'][0]['step_key'] == 'shot_1'
r = await wf.client.post('/api/workflow-runs/'+snap['run']['id']+'/cancel',json={},headers={'Idempotency-Key':'cancel'})
assert r.status_code == 200,r.text
await advance_workflows(wf.app.state.db,wf.settings,wf.provider)
snap = (await wf.client.get('/api/workflow-runs/'+snap['run']['id'])).json()
assert snap['run']['state'] == 'cancelled' and len(snap['jobs']) == 1
assert snap['run']['state'] == 'cancelled' and len(snap['jobs']) == 3
assert wf.provider.submitted_payloads == []
@pytest.mark.asyncio
@ -58,12 +58,12 @@ async def test_failed_step_explicit_retry_only_and_old_target_rejected(wf):
old = await s.scalar(select(Job).where(Job.run_id==rid)); old.state='failed'; old.phase='failed'; oid=old.id; await s.commit()
await advance_workflows(wf.app.state.db,wf.settings,wf.provider)
snap=(await wf.client.get('/api/workflow-runs/'+rid)).json()
assert snap['run']['state']=='blocked' and len(snap['jobs'])==1
assert snap['run']['state']=='blocked' and len(snap['jobs'])==3
body={'expected_run_version':snap['run']['version'],'target_job_id':oid}
r=await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry',json=body,headers={'Idempotency-Key':'redo'})
assert r.status_code==202,r.text
again=await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry',json=body,headers={'Idempotency-Key':'redo'})
assert again.status_code==202 and len(again.json()['jobs'])==2
assert again.status_code==202 and len(again.json()['jobs'])==4
r=await wf.client.post(f'/api/workflow-runs/{rid}/steps/shot_1/retry',json={**body,'expected_run_version':again.json()['run']['version']},headers={'Idempotency-Key':'stale'})
assert r.status_code==409
@ -94,7 +94,7 @@ async def test_old_result_after_retry_cannot_advance_selected_step(wf):
old=await s.get(Job,oid);old.state='succeeded';await s.commit()
await advance_workflows(wf.app.state.db,wf.settings,wf.provider)
snap=(await wf.client.get('/api/workflow-runs/'+rid)).json()
assert len(snap['jobs'])==2
assert len(snap['jobs'])==4
shot=next(s for s in snap['steps'] if s['step_key']=='shot_1')
assert shot['state']!='succeeded' and shot['selected_job_id']!=oid
@ -203,7 +203,7 @@ async def test_cancel_with_inflight_child_waits_and_success_late_does_not_publis
snap=(await wf.client.get('/api/workflow-runs/'+rid)).json();assert snap['run']['state']=='cancelling'
await publish_video(wf,jid)
await advance_workflows(wf.app.state.db,wf.settings,wf.provider)
snap=(await wf.client.get('/api/workflow-runs/'+rid)).json();assert snap['run']['state']=='cancelled' and snap['run']['result_assets']==[] and len(snap['jobs'])==1
snap=(await wf.client.get('/api/workflow-runs/'+rid)).json();assert snap['run']['state']=='cancelled' and snap['run']['result_assets']==[] and len(snap['jobs'])==3
@pytest.mark.asyncio
async def test_parallel_run_and_patch_versions_accept_one(wf):
@ -218,7 +218,7 @@ async def test_parallel_run_and_patch_versions_accept_one(wf):
assert sorted(r.status_code for r in responses)==[202,409]
@pytest.mark.asyncio
async def test_batch_does_not_advance_while_previous_cleanup_unknown(wf):
async def test_batch_retains_unknown_cleanup_while_other_member_progresses(wf):
from app.workflow_engine import advance_workflows
from app.v2_models import Execution
r=await wf.client.post('/api/batches',json={'items':[{'kind':'job','task_type':'image.generate','input':{'prompt':p}} for p in ('one','two')]},headers={'Idempotency-Key':'batch'})
@ -228,7 +228,7 @@ async def test_batch_does_not_advance_while_previous_cleanup_unknown(wf):
s.add(Execution(job_id=j.id,ordinal=1,phase_key='execute',resource_pool='new_gpu',fence_token='f',state='unknown'));await s.commit()
await advance_workflows(wf.app.state.db,wf.settings,wf.provider)
async with wf.app.state.db.session() as s:
j=await s.get(Job,items[1]['target_id']);assert 'batch_wait' in j.hold_reasons
j=await s.get(Job,items[1]['target_id']);assert 'batch_wait' not in j.hold_reasons
snap=(await wf.client.get('/api/batches/'+bid)).json();assert snap['items'][0]['state']=='cleanup_pending'
@pytest.mark.asyncio
@ -240,7 +240,7 @@ async def test_missing_selected_output_blocks_only_affected_run(wf):
j=await s.scalar(select(Job).where(Job.run_id==rid));j.state='succeeded';await s.commit()
await advance_workflows(wf.app.state.db,wf.settings,wf.provider)
snap=(await wf.client.get('/api/workflow-runs/'+rid)).json()
assert snap['run']['state']=='blocked' and len(snap['jobs'])==1
assert snap['run']['state']=='blocked' and len(snap['jobs'])==3
@pytest.mark.asyncio
async def test_maintenance_keeps_existing_run_queued_without_creating_children(wf):

View File

@ -0,0 +1,79 @@
# Multi GPU FIFO Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development or superpowers:executing-plans. Complete each task's RED/GREEN checks and record evidence.
**Goal:** Dispatch ready jobs FIFO across idle GPUs and run the workspace with 384 GiB RAM.
**Architecture:** One scheduler owns FIFO claims and persistent per-GPU leases, while independent execution monitors own task process groups. Business orchestration feeds independent ready leaves into that queue within quotas. Aggregated resource state drives the web UI.
**Tech Stack:** Python/SQLite/Linux processes, FastAPI/SQLAlchemy, Vue/Pinia, Docker.
**Spec:** `docs/superpowers/specs/2026-11-11-multi-gpu-fifo-design.md` (approved; 384 GiB supplement).
## Global Constraints
- One job per GPU UUID, max_gpu_jobs=4; 68 GiB allocator, 8 GiB GPU reserve, 15-second idle admission.
- Global FIFO for eligible tasks; retain pauses, windows, quotas, output/attempt fencing and external-user priority.
- No replay of hard-crashed execution; preserve queue/model files and unrelated working-copy edits.
- Workspace RAM=384 GiB; total memory+swap limit=384 GiB (no swap allowance). Keep other services intact.
- Source baseline is isolated commit `18701ee`; integrate only this feature's delta into the current canonical checkout.
## Review Focus
- Delayed GPU telemetry must not allocate one physical GPU twice.
- Cancelling/preempting one runner must not stop or finalize another attempt.
- More than eight independent workflow leaves must make progress without quota transaction rollback.
- Old API/worker initialization must not silently restore the singleton index.
- Cgroup/SHM pressure and normal PID exit must not create OOM or preemption retry storms.
### Task 1: Inference FIFO scheduler, per-GPU leases and memory admission
Files: `inference/llm_services/{store,worker,gpu_policy,api}.py`, `inference/scripts/service.py`, new scheduler/resource helpers if useful, related inference tests.
Interfaces: scheduler JSON schema_version=2; `active_jobs` entries carry `job_id`, `attempt_count`, `gpu_index`, `gpu_uuid`, `stage`, `state`, `reason`; top-level `running_count`, `queued_count`, `state`, `policy`, `updated_at`. States `running/waiting/idle/blocked`, with per-entry preempting allowed. Settings keys live in worker config/settings.json, never runtime-policy.json. `max_gpu_jobs=4`, `cpu_threads_per_job=2`, initial host-memory estimates GiB: image=88, video=64, defect=24, audio=12; global headroom=16. These conservative estimates are configurable and updated by real measurements. Admission accounts for current cgroup working memory, active reservations and SHM, without counting reclaimable inactive file cache as permanently consumed.
- [ ] Write and run failing tests: three UUIDs launch A/B/C FIFO while D waits; concurrent claims never duplicate UUID/job; mixed modes use eligible queue_seq; old-attempt writes rejected; one cancellation or external preemption leaves other runners alive; multiple markers block unsafe recovery; old schema migration preserves jobs; memory shortage queues head job.
- [ ] Replace singleton index/claim guard with atomic GPU lease uniqueness; schema compatibility rejects legacy singleton re-creation.
- [ ] Implement one event dispatcher with per-job monitors and markers. Claims/spawns ordered, monitor/cleanup independent, status single writer. Keep `run_once` compatibility for meaningful legacy fixtures or update callers deliberately.
- [ ] Add attempt CAS to terminal and requeue writes, bounded all-runner shutdown, per-runner env/CPU threads, max slot and memory admission.
- [ ] Run inference suite on Windows for portable parts, then complete Linux process/guard/service suite in isolated server scratch. Record RED/GREEN and commit scoped files after review.
### Task 2: Application FIFO, parallel workflow/batch feeder
Files: `backend/app/{coordinator,workflow_engine,batches,workflows,jobs}.py` as needed and corresponding backend tests. Do not edit providers.py (Task 4 owner).
Interfaces: reuse existing upstream scheduling protocol/job IDs and attempt fences. Independent ready steps enqueue in stable step order within remaining per-owner quota (8 interactive GPU jobs). Multiple active batch members allowed; preserve existing current_item_index compatibility while providing active item list/count if needed. Separate new-submit FIFO from next_action_at retry polling. Bound background preparation/collection and continue querying existing upstream executions.
- [ ] Write RED tests for three independent shot submissions, 12/20-shot quota replenishment, two batch members in flight, compose waiting all chosen outputs, cancelling one child, stable FIFO ready submission despite polling timestamps.
- [ ] Implement bounded per-leaf persistence and replenish; remove only unique-active-member gate, preserve run/user quotas, hold controls, permissions and dependencies.
- [ ] Ensure long preparation/result imports do not starve ready submissions; retain CPU/Qwen pool limits and persisted outcomes.
- [ ] Run full backend tests, report any baseline unrelated failures separately; scoped review/commit.
### Task 3: GPU monitor disappearing-PID handling and diagnostics
Files: `inference/admin/gpu_guard.py`, `inference/tests/test_gpu_guard.py` (and only narrowly related tests).
Interfaces: preserve guard status schema v1, ownership and global failure behavior. A missing PID can be dropped only after one fresh NVIDIA sample confirms disappearance; permission/identity ambiguity stays fail-closed. Logs record failed PID, stage, error category without dumping command/env/secrets.
- [ ] RED tests: sampled PID exits before /proc read then absent on bounded resample -> no global error; still-present unknown PID/permission failure -> fail closed; new external process in refreshed sample is retained; sample retry bounded and existing watchdog identity tests pass.
- [ ] Implement one bounded resample and structured diagnostics; retain root-only policy and pidfd signaling.
- [ ] Run guard suite portable then Linux, review and scoped commit. Root deploys root-owned script only after full verification.
### Task 4: Aggregated UI resources, documentation and integration
Files: `backend/app/providers.py`, `backend/tests/test_resource_status*.py` or existing resource tests, frontend resource types/components/text/tests, help manuals, README and deployment checks. Root owns these files.
- [ ] RED tests for multiple active_jobs, single-card preemption with another card running/ready, schema-v1 compatibility, no sensitive process detail in public resource state.
- [ ] Adapt provider resource summary and frontend types/counts/card information; remove current single-task wording, preserve history reports.
- [ ] Run backend full suite, frontend full tests/typecheck/build, inference full Linux suite; independently review integration. Resolve important findings with focused RED/GREEN checks.
### Task 5: 384 GiB deployment, selective source integration and real three-card validation
Files: scoped deploy script, new QA evidence/README; remote backup and deployment records.
- [ ] Recheck host available RAM and target container identity; save old configuration; docker update memory and memory-swap to384g; verify exact cgroup limit412316860416 and unchanged container start time.
- [ ] Compare canonical files to baseline manifest; integrate only this feature's delta with three-way preservation of concurrent edits, then retest combined source. Do not stage or deploy unrelated incomplete work.
- [ ] Drain existing jobs before coordinated API/worker schema switch; retain queued jobs. Back up SQLite using backup API, configurations, service identities and touched source.
- [ ] Deploy consistent inference/API/UI versions, root guard source and operator config; check readiness and Qwen/other container identity.
- [ ] Submit four low-cost real GPU jobs across three free cards; prove FIFO starts, overlapping execution, fourth waiting then filling a released card, outputs decoded, per-card cleanup, single-card controlled external preemption, RAM/SHM peaks, no duplicate attempts or unexplained requeue. Do not consume GPU0 external service.
- [ ] Restore prior test-only inputs/policy after validation; leave production concurrency enabled and384 GiB. Record final tests, changed service bindings, source commit and limitations.

View File

@ -0,0 +1,32 @@
# SDD ledger — plan: docs/superpowers/plans/2026-11-11-multi-gpu-fifo.md
- Approved design and384 GiB supplement: latest user message.
- Isolation: native create_worktree tool did not return and was terminated; independent local clone plus current dirty source snapshot preserves canonical checkout. Baseline18701ee.
- Task5 memory step: 2026-11-11 10:16:52 hot update verified memory.max=412316860416, memory+swap384GiB, container identity/start unchanged. Backup /root/gpu-fifo-upgrade-20261111-101652/container-before.json. Host available427.03GiB, CPUs128.
| Pre-flight | Producer/consumer | Finding |
|---|---|---|
| Task1 / Task4 | scheduler schema2 active_jobs -> provider/UI | Exact fields declared in plan; guard stays schema1. |
| Task1 / Task3 | monitor ownership -> per-runner yield | Global unavailable status remains protective; confirmed external occupancy affects one lease. |
| Task1 / Task2 | upstream FIFO -> application ready FIFO | Both preserve eligibility and attempt fences; prepare not ready yet can be skipped. |
| Task2 / Task4 | coordinator workflow changes / provider status | Separate owned files; public DTO additions backward compatible. |
| Task1 / Task5 | schema/markers -> coordinated switch | Drain before migration, consistent API/worker code, old singleton index cannot return. |
| Each task | Tests/code/files | RED/GREEN and full affected suite required; test ownership avoids simultaneous writes. |
Ruling: execution continues under the approved design without a second plan approval, as user explicitly requested implementation. Runtime384 GiB supersedes design's undecided memory cap.
Ruling: unrelated source changes are captured only as a private baseline; final transfer/deployment includes feature delta and current canonical source after conflict checks, not an overwrite with the snapshot.
## Integration progress
- Task1: Linux RED7 expected failures observed on baseline; initial Linux GREEN176 passed/123subtests. Latest portable156passed25skipped123subtests; final Linux in progress. Fresh review memory underestimate reproduced and fixed with conservative observed+active+new reservations. Per-card blocked metadata follow-up in progress.
- Task2: ready feeder/batch/FIFO/preparation changes stable. First Linux full224passed20subtests and1 obsolete single-child deletion assertion (updated to all3 children+refs). Fresh review caught >25-ready FIFO overflow and orphan-on-cancel during post-payload preparation; both RED reproduced and fixed, final regressions running.
- Task3: initial45tests GREEN; review caught lost continuous-idle credit on occupied->empty refresh; RED reproduced, fixed46/46. Final Linux verification pending latest aggregate package.
- Task4: resource summary initial3RED ->17provider pass2skip20subtests; executor-global-blocked visibility RED ->4focusedpass. Frontend103tests pass and productionbuild/typecheck pass; final build after last UI refinement pending.
- Canonical source advanced independently to5909e38 (v4 private/shared assets release), deployed by its own chat. Its non-overlapping changes copied into this private clone; current manuals merged, generatedHTML regenerated. No application source overlap with our3ownedappfiles. Original source still untouched by this feature.
Ruling: use conservative whole-container working memory plus all active reservations when process attribution is unavailable; double-counting can reduce heavy-image concurrency, but prevents known background-growth underestimation. Three expected64GiB Wan jobs remain admissible under384GiB.
Ruling: generated manual.html textual conflict is resolved by regenerating from the three-way-merged current Markdown manual, preserving v4 help additions and new parallel scheduling rules.
Remote sessions: rootSSH20909, SFTP5325; scratch/root records /root/cmvr-gpu-fifo-20261111; user test source /workspace/projects/cmvr-visual-fifo-qa/green. Deployment helper .deploy/deploy_parallel_remote.py is prepared but NOT executed. Production still serial as of this entry; only RAM cap is live384GiB.

View File

@ -0,0 +1,83 @@
# 多 GPU 并发与 FIFO 调度设计
状态:用户已确认并要求实施;另明确批准将项目容器内存从128 GiB提高至384 GiB。
## 目标和依据
用户要求:只要存在空闲 GPU,就允许多个 GPU 同时运行任务,并遵守先到先运行。此前“全项目最多一个 GPU 任务”的约束由此替换。
2026-11-11 10:02 的只读检查:GPU0 被共享 Qwen 快速服务占用;GPU1 正运行本项目视频任务;GPU2、GPU3 空闲,队列另有视频等待。主机内存约503 GiB、可用约427 GiB;工作容器限额为8 CPU、128 GiB内存、512个进程。主机空闲内存不等于容器可分配内存。
## 用户可见规则
1. 每张符合准入条件的 GPU 同时运行一个任务;最多使用四张卡。有三张合格空闲卡和至少三个就绪任务时,同时运行三个任务。
2. FIFO 指派发顺序:满足依赖、暂停控制和运行时段要求的任务,按持久化入队序号递增领取。不同任务耗时不同,允许后启动的先完成。
3. 不再使用交互任务插队、用户轮询或批次轮询决定 GPU 队列先后顺序。未到预约时间、手动暂停或不在允许时段的任务暂不属于就绪队列;恢复后仍保留原入队顺序。
4. 已经运行的本项目任务不因更早任务重新入队而被终止。外部用户占用某张卡时,只终止该卡上本项目的任务组;清理完成后原任务按原队列位置重排,其他卡继续执行。
5. 每个任务绑定一张 GPU UUID,继续遵守68 GiB分配预算、8 GiB空闲预留及连续空闲15秒规则。不把模型拆到多张卡,也不在同一卡上堆叠多个本项目任务。
6. 独立分镜和其他依赖已经满足的步骤允许进入队列;生成、增强等有依赖的阶段,以及最终合成,继续等待各自前置结果。多个批次成员不再因单个活动成员指针而无法提交就绪任务。原有配额、权限、审核和素材归属规则保留。
7. 网页显示每张卡的任务与阶段,以及运行数、等待数和等待原因。CPU媒体处理、语音服务和共享Qwen HTTP调用继续使用各自资源控制,不因为GPU数量增加而无条件扩容。
例:A、B、C、D依次就绪,GPU1/2/3空闲:依次把A、B、C分别分配到三张卡,D等待。B先完成时,D使用B释放的卡;不必等待A、C结束。
## 实现方案比较
- **建议采用:一个调度器管理多个独立执行进程。** 唯一调度器按FIFO原子领取、预留设备并依次启动,各任务独立监控和清理;最容易沿用现有锁、队列和容器隔离。
- 每张卡各启动一个worker:也能并发,但FIFO派发、全局暂停、崩溃恢复和状态汇总需要额外协调,现有全局锁和恢复协议也不支持直接启动多个worker。
实现方式由本设计建议,尚不视为用户已选择。此次不引入集群调度平台,不重建共享Qwen,不停止其他用户服务。
## 调度、持久化和恢复
保留一个service supervisor和一个调度器的全局flock;取消“全局唯一运行任务”的含义。
- 在一次schema迁移事务中删除`one_running_job`索引。以规范化的GPU UUID约束运行中的设备唯一占用;生产claim必须携带设备UUID。领取任务、设置attempt和占用GPU在同一SQLite事务提交,覆盖从launching到进程组清理结束的全过程。不能只依赖有采样延迟的GPU监控判断本卡是否已分配。
- `_select_next`改为符合准入条件任务的全局`queue_seq`排序;幂等提交、取消、时段开关及批次暂停继续生效。
- 调度器先处理终态、取消和让卡,再为未被本地租约占用的合格GPU依次领取任务。每个任务使用独立进程组、输出目录及attempt目录;不在线程中修改全局`os.environ`。
- 单一`active-runner.json`改为按job/attempt分别记录身份的集合;调度状态由唯一写入者汇总为`active_jobs`和每卡状态。API健康检查、停止服务和管理员诊断同步支持多个活动执行。
- `set_runner`、完成、失败和重排等写入增加attempt/execution fencing;旧轮次的回调不能改变新轮次状态或释放新租约。
- 服务停止时停止新派发并清理所有属于自身的任务组;只有确认退出后才释放对应设备。进程无法清理时保留该执行的恢复证据,禁止复用该设备。监督进程意外退出或残留标记不明时,不自动重放运行任务,先进入需要管理员检查的恢复状态。
- 旧版API与worker不能在迁移后继续初始化旧索引;发布需要一致切换。保留旧标记检测和明确的schema版本校验,禁止旧程序静默回写。
## 监控与抢占
当前guard按容器cgroup识别自身进程,本身可以容纳同一容器在多卡上的多个进程;逐卡外部占用检查按对应租约执行。
09:55的保护性重排记录为`process_inspection_failed`,不是已确认的外部抢占。并发后进程结束更频繁,需要增加失败PID、检查步骤及异常类别的日志。针对进程在采样后正常消失的情况,设计一次有界重采样确认:只有确认该PID已不在GPU采样中,才将它作为已退出处理;仍无法核验、权限异常、身份冲突、状态过期或整体监控不可用时继续保守保护,不能直接忽略错误或关闭其他用户优先规则。
确认的单卡外部占用只影响该卡;整体监控失效仍可能暂停多张卡,不承诺所有故障都局限于一张卡。
## 应用层和共享资源
应用层不能以一个GPU任务未完成为由阻止其他就绪任务提交。工作流按既定步骤顺序,为所有依赖已满足的步骤有界补队;最终合成等待全部所需输出。当前每用户最多8个未终态交互GPU任务,不能在同一事务中创建20个分镜后因第9个超额而将全部回滚。补队应预判剩余配额并分别持久化已接受的子任务,任务结束释放额度后再补充后续步骤。批次的成员状态从“唯一活动成员”改为可跟踪多个在途成员,保持取消、暂停、幂等和配额检查。每用户活动工作流数量限制不在本次自动取消范围内;一个活动工作流的独立分镜已能并行。
业务API的新GPU任务提交顺序应使用持久化业务入队时间和确定的同刻次序;不能拿`next_action_at`轮询/退避水位冒充FIFO。素材准备尚未完成的任务暂不就绪;为已就绪任务提交时按FIFO处理。耗时准备和结果导入采用有界后台处理,不能在一次调度循环中抽音或下载几分钟,阻止其他空卡收到任务;既有任务的取消、状态同步和结果归档继续推进。
`providers.py`的资源摘要必须读取聚合状态,单卡让行不能把全部卡显示为正在释放。前端继续按job.id处理多个running任务,更新资源计数、每卡信息和旧串行文案;无需增加API副本或扩容独立的TTS服务。
同步更新当前操作手册和网页帮助,历史验收报告保留原状,另增真实并发验收记录,不能把旧串行测试改写成已通过并发。
共享内存是并发上线的实际约束。CPU offload使每个模型使用主存,不能认为四张卡显存各自足够就必然能在128 GiB容器内运行四个模型。实施时需要:
- 最大GPU任务数配置为4,实际并发随合格空闲卡和就绪任务数变化,不另加固定单任务限制。
- 测量图像、视频、缺陷生成、转写的主存峰值及混合并发峰值;据此设置每类任务主存预留和容器总预算,预留覆盖加载和清理阶段。
- 有空卡但共享内存不足时,队首任务保持等待并显示原因;不跳过较早的就绪任务启动后来的轻任务。
- 若128 GiB不足,在复核主机余量后调整本项目容器上限并再次验证;容器上限和模型预留的最终数值由实测决定,不凭权重体积估算成安全承诺。限制每任务CPU线程,检查共享内存、PID额度和编译缓存并发写入。
- 实测和入场检查读取工作容器自身的cgroup `memory.current/max/events`以及`/dev/shm`占用,不能拿主机`MemAvailable`或API容器4 GiB额度替代。额度不足保持排队,不进入失败自动重试循环。
- 并发上限和内存参数置于worker管理员配置`config/settings.json`,保持字段校验;不直接向有严格双端白名单的`runtime-policy.json`塞入新字段,以免使现有时段策略整体失效。
## 验收
1. 三张合格GPU、四个独立任务:前三个按FIFO启动并在时间上重叠;第四个等待任何一张卡完成清理后启动。
2. 高频并发提交与快速连续派发:同一任务不重复领取,同一GPU不重复租用;跨用户和批次也遵循就绪任务FIFO。
3. 单卡外部抢占、取消、超时、失败、暂停和重试:只有对应任务停止,其他卡继续;清理和attempt fencing正确。
4. 独立分镜/批次成员可以同时进入推理队列,合成和有依赖步骤不会提前执行;12/20分镜超过一次补队配额时仍能持续推进,不能全事务回滚而饿死;配额和素材隔离保持有效。
5. worker崩溃、API与worker同时初始化、残留进程组及旧版启动:无重复执行、无设备误复用,恢复提示可操作。
6. 进程退出时监控采样变化:不会因已确认消失的PID反复重做任务;未知身份与真实外部占用仍能触发保护。
7. 在Linux上通过队列、进程清理、调度、工作流、批次与资源状态回归;真实三卡并发完成输出、解码和逐卡显存核验,记录CPU/主存峰值。共享Qwen身份与健康状态保持正常。
## 发布与回退
当前正在执行的任务先自然完成;暂停新派发并确认全部在途任务和进程组清理完毕,再备份队列、配置、程序及部署身份,进行一致升级。现有排队任务保留,不删除数据库、锁文件或模型。
先完成可复核代码与Linux验证,再上线真实三卡验收。旧版本只允许在没有活动执行时回退;数据库中的任务和结果不得回退成重复执行的旧状态。仓库当前有其他功能的未提交改动,实施须隔离修改并保留它们,部署前协调共同修改的应用文件。

View File

@ -77,7 +77,7 @@
### 运行、复用与恢复
点击“保存并运行”。服务器冻结本次参数和修订,逐镜串行生成,然后合成。每个镜头完成后会归档;运行期间继续编辑草稿不会改变已开始的运行。
点击“保存并运行”。服务器冻结本次参数和修订,独立镜头按就绪顺序分配到空闲GPU并行生成,全部完成后再按镜头顺序合成。每个镜头完成后会归档;运行期间继续编辑草稿不会改变已开始的运行。
- “暂停后续阶段”:当前阶段完成,下一阶段暂停;“继续”恢复后续准入。
- “取消”:取消本次后续工作,不能靠继续把已取消运行恢复。
@ -123,7 +123,7 @@ JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本
素材删除和共享撤回不会立即释放磁盘或额度。物理垃圾回收(GC)默认只做`dry-run`盘点;默认保留期为14天,超过保留期后仍需运维显式开启维护并执行物理清理(purge),再次检查引用后才可能删除文件。仅真正清理掉的文件释放相应占用,不能把“删除成功”当作即时腾出磁盘。
“任务”可查看叶任务和工作流进度、队列原因、历史执行和错误。新GPU推理全局仅一个;配音/媒体CPU和Qwen HTTP各有独立单槽。llmuser可选择四张GPU的空闲资源,外部用户占卡时优先让行并重排本应用作业,等待排队本身不是故障。
“任务”可查看叶任务和工作流进度、队列原因、历史执行和错误。GPU任务按就绪入队顺序派发,每张空闲卡同时一个任务,最多四卡并行;配音/媒体CPU和Qwen HTTP仍有独立单槽。llmuser可选择四张GPU的空闲资源,外部用户占卡时优先让出对应卡并重排该任务,其他卡上的任务继续,等待排队本身不是故障。
## 7. 批量与开发/生产配置

File diff suppressed because one or more lines are too long

View File

@ -77,7 +77,7 @@
### 运行、复用与恢复
点击“保存并运行”。服务器冻结本次参数和修订,逐镜串行生成,然后合成。每个镜头完成后会归档;运行期间继续编辑草稿不会改变已开始的运行。
点击“保存并运行”。服务器冻结本次参数和修订,独立镜头按就绪顺序分配到空闲GPU并行生成,全部完成后再按镜头顺序合成。每个镜头完成后会归档;运行期间继续编辑草稿不会改变已开始的运行。
- “暂停后续阶段”:当前阶段完成,下一阶段暂停;“继续”恢复后续准入。
- “取消”:取消本次后续工作,不能靠继续把已取消运行恢复。
@ -123,7 +123,7 @@ JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本
素材删除和共享撤回不会立即释放磁盘或额度。物理垃圾回收(GC)默认只做`dry-run`盘点;默认保留期为14天,超过保留期后仍需运维显式开启维护并执行物理清理(purge),再次检查引用后才可能删除文件。仅真正清理掉的文件释放相应占用,不能把“删除成功”当作即时腾出磁盘。
“任务”可查看叶任务和工作流进度、队列原因、历史执行和错误。新GPU推理全局仅一个;配音/媒体CPU和Qwen HTTP各有独立单槽。llmuser可选择四张GPU的空闲资源,外部用户占卡时优先让行并重排本应用作业,等待排队本身不是故障。
“任务”可查看叶任务和工作流进度、队列原因、历史执行和错误。GPU任务按就绪入队顺序派发,每张空闲卡同时一个任务,最多四卡并行;配音/媒体CPU和Qwen HTTP仍有独立单槽。llmuser可选择四张GPU的空闲资源,外部用户占卡时优先让出对应卡并重排该任务,其他卡上的任务继续,等待排队本身不是故障。
## 7. 批量与开发/生产配置

View File

@ -27,6 +27,6 @@ onMounted(()=>window.addEventListener('cmvr:unauthorized',expired));onBeforeUnmo
<RouterView v-if="route.path==='/login'" />
<div v-else class="app-shell"><aside class="sidebar"><router-link to="/create/image" class="brand" aria-label="CMVR Visual 创作首页"><span class="brand-glyph">V</span><span class="brand-caption">CMVR</span></router-link><nav class="side-nav"><router-link v-for="item in nav" :key="item.path" :to="item.path" :class="{selected:item.path==='/create/image'?route.path.startsWith('/create'):route.path.startsWith(item.path)}"><el-icon><component :is="item.icon" /></el-icon><span>{{ item.label }}</span><i v-if="item.path==='/tasks'&&jobs.active.length" class="nav-notification"/></router-link></nav><div class="sidebar-bottom"><el-tooltip content="服务状态" placement="right"><button aria-label="服务状态" @click="systemOpen=true"><el-icon><Connection /></el-icon></button></el-tooltip><el-dropdown trigger="click" placement="right-end"><button class="avatar-button" :aria-label="auth.user?.display_name||'账户'">{{ (auth.user?.display_name||auth.user?.username||'U').slice(0,1) }}</button><template #dropdown><el-dropdown-menu><el-dropdown-item disabled>{{ auth.user?.display_name||auth.user?.username }}</el-dropdown-item><el-dropdown-item divided :icon="SwitchButton" @click="logout">退出登录</el-dropdown-item></el-dropdown-menu></template></el-dropdown></div></aside>
<div class="app-main"><header class="app-header"><div class="header-breadcrumb"><span>CMVR Visual</span><span class="breadcrumb-separator">/</span><strong>{{ route.meta.title }}</strong></div><div class="header-actions"><button class="connection-status" :class="jobs.connection" @click="systemOpen=true"><span class="live-dot"/>{{ connectionLabel }}</button><span class="header-divider"/><span class="local-label">{{ caps.environment === 'production' ? '本地创作空间' : caps.environment ? '验收环境' : '环境待确认' }}<template v-if="caps.environment && caps.environment !== 'production'"> · {{ caps.databaseBackend === 'mysql' ? 'MySQL' : 'SQLite' }}</template></span></div></header><div v-if="jobs.connection==='reconnecting'" class="connection-banner"><el-icon><Warning /></el-icon>连接恢复中,任务状态待同步。<button @click="jobs.refresh().catch(()=>undefined)">重新同步</button></div><main class="page-content"><div v-if="auth.user?.must_change_password" class="notice warning">请先到 <router-link to="/account">账户设置</router-link> 修改初始密码。</div><RouterView :key="auth.user?.id" /></main><button v-if="ongoing" class="global-queue-bar" @click="router.push({path:'/tasks',query:{job:ongoing.id}})"><span class="queue-spinner"/><strong>{{ stateLabel(ongoing) }}</strong><span>{{ phaseLabel(ongoing) }}</span><small v-if="jobs.active.length>1">另有 {{ jobs.active.length-1 }} 项活动任务</small><el-icon><ArrowRight /></el-icon></button></div>
<el-drawer v-model="systemOpen" title="创作服务状态" size="400px"><div class="system-status"><span class="eyebrow">LOCAL CREATIVE ENGINE</span><h2>让算力,为灵感留白。</h2><p>GPU 任务串行执行,外部使用优先。抢占后自动让行并重新排队。</p><el-button :icon="RefreshRight" :loading="caps.loading" @click="caps.load">刷新状态</el-button><div v-if="caps.error" class="notice warning">{{ caps.error }}</div><h3>连接与调度</h3><p>推理服务:{{ caps.inferenceOnline===null?"待确认":caps.inferenceOnline?"在线":"离线" }}</p><template v-if="caps.executionPolicy"><p v-if="caps.executionPolicy.configuration_error" class="notice warning">调度配置异常,批量任务等待配置恢复。请联系管理员。</p><p v-else-if="caps.executionPolicy.batch_window_enabled===false">时段限制已关闭:开发测试可全天执行批量任务,仍需等待空闲资源。</p><p v-else>批量窗口:{{ caps.executionPolicy.timezone }} {{ caps.executionPolicy.start }}–{{ caps.executionPolicy.end }} · {{ caps.executionPolicy.batch_open?"开放":"等待下一窗口" }}<br/>{{ caps.executionPolicy.end }} 后当前阶段继续完成,新阶段等待下一窗口。<br/><template v-if="caps.executionPolicy.next_batch_at">下次窗口 {{ caps.executionPolicy.next_batch_at }}</template></p></template><h3>模型能力配置</h3><div v-for="cap in caps.items" :key="cap.task_type" class="system-model"><span class="status-dot" :class="cap.available?'succeeded':'failed'"/><div><strong>{{ cap.label }}</strong><small>{{ cap.model }}</small><p>{{ cap.description }}</p></div><span>{{ cap.available?'就绪':'未配置' }}</span></div><h3>算力资源</h3><p class="muted">{{ caps.scheduler?.reason||caps.scheduler?.state||'尚未读取调度状态' }}</p><div v-for="gpu in caps.scheduler?.gpus||[]" :key="gpu.index" class="gpu-status"><strong>GPU {{ gpu.index }}</strong><span>{{ gpu.eligible?'可用':gpu.busy?'占用中':'等待确认' }}</span><small>{{ gpu.free_gib===null?'—':`${gpu.free_gib.toFixed(1)} GiB 空闲` }}</small></div></div></el-drawer>
<el-drawer v-model="systemOpen" title="创作服务状态" size="400px"><div class="system-status"><span class="eyebrow">LOCAL CREATIVE ENGINE</span><h2>让算力,为灵感留白。</h2><p>空闲 GPU 可并行执行任务,每卡一个,按就绪顺序派发。外部使用优先,占卡时只让出对应卡。</p><el-button :icon="RefreshRight" :loading="caps.loading" @click="caps.load">刷新状态</el-button><div v-if="caps.error" class="notice warning">{{ caps.error }}</div><h3>连接与调度</h3><p>推理服务:{{ caps.inferenceOnline===null?"待确认":caps.inferenceOnline?"在线":"离线" }}</p><template v-if="caps.executionPolicy"><p v-if="caps.executionPolicy.configuration_error" class="notice warning">调度配置异常,批量任务等待配置恢复。请联系管理员。</p><p v-else-if="caps.executionPolicy.batch_window_enabled===false">时段限制已关闭:开发测试可全天执行批量任务,仍需等待空闲资源。</p><p v-else>批量窗口:{{ caps.executionPolicy.timezone }} {{ caps.executionPolicy.start }}–{{ caps.executionPolicy.end }} · {{ caps.executionPolicy.batch_open?"开放":"等待下一窗口" }}<br/>{{ caps.executionPolicy.end }} 后当前阶段继续完成,新阶段等待下一窗口。<br/><template v-if="caps.executionPolicy.next_batch_at">下次窗口 {{ caps.executionPolicy.next_batch_at }}</template></p></template><h3>模型能力配置</h3><div v-for="cap in caps.items" :key="cap.task_type" class="system-model"><span class="status-dot" :class="cap.available?'succeeded':'failed'"/><div><strong>{{ cap.label }}</strong><small>{{ cap.model }}</small><p>{{ cap.description }}</p></div><span>{{ cap.available?'就绪':'未配置' }}</span></div><h3>算力资源</h3><p v-if="caps.scheduler?.running_count!=null">{{ caps.scheduler.running_count }} 项运行中 · {{ caps.scheduler.available_count ?? 0 }} 张卡可接任务<template v-if="caps.scheduler.queued_count!=null"> · {{ caps.scheduler.queued_count }} 项排队</template></p><p :class="caps.scheduler?.dispatch_blocked?'notice warning':'muted'">{{ caps.scheduler?.reason||caps.scheduler?.state||'尚未读取调度状态' }}</p><div v-for="gpu in caps.scheduler?.gpus||[]" :key="gpu.index" class="gpu-status"><strong>GPU {{ gpu.index }}</strong><span>{{ ({external:'其他业务占用',running:'本项目执行中',launching:'正在启动',preempting:'正在让卡',blocked:'需要检查',ready:'可接任务',waiting:'等待资源'} as Record<string,string>)[gpu.state||''] || (gpu.eligible?'可用':gpu.busy?'占用中':'等待确认') }}</span><small>{{ gpu.free_gib===null?'—':`${gpu.free_gib.toFixed(1)} GiB 空闲` }}</small></div></div></el-drawer>
</div>
</template>

View File

@ -24,7 +24,8 @@ export interface Capability {
}
export interface Scheduler {
available: boolean; state: string; reason: string | null
gpus: { index: number; name: string; busy: boolean; eligible: boolean; free_gib: number | null }[]
gpus: { index: number; name: string; busy: boolean; eligible: boolean; free_gib: number | null; state?: string; stage?: string | null }[]
dispatch_blocked?: boolean; running_count?: number | null; available_count?: number | null; queued_count?: number | null
updated_at: string | null
}
export interface Job {

View File

@ -32,7 +32,7 @@ onMounted(()=>{void load();void loadRuns()}); onBeforeUnmount(() => { generation
</script>
<template>
<div class="tasks-page"><header class="page-heading split-heading"><div><span class="eyebrow">EVERY IDEA HAS A JOURNEY</span><h1>每次创作,都有迹可循。</h1><p>查看排队、生成与自动让行记录,让长时间创作也保持清晰。</p></div><el-button :icon="RefreshRight" :loading="loading" @click="load">同步任务</el-button></header>
<div class="task-policy-note"><span class="live-dot" /> GPU任务串行执行,外部使用优先。让行后保留任务身份,等待空闲算力自动重试。</div>
<div class="task-policy-note"><span class="live-dot" /> 空闲GPU并行执行,每卡一个任务,按就绪顺序派发。外部占卡时只让出对应卡,任务保留身份重新排队。</div>
<RunCard v-for="snapshot in runItems" :key="snapshot!.run.id" :snapshot="snapshot!"/><el-pagination v-if="runTotal>10" v-model:current-page="runPage" :page-size="10" :total="runTotal" layout="prev,pager,next" @current-change="loadRuns"/>
<div class="library-toolbar"><div class="filter-tabs"><button v-for="option in [{value:'',label:'全部任务'},{value:'queued',label:'排队中'},{value:'running',label:'创作中'},{value:'succeeded',label:'已完成'},{value:'failed',label:'失败'}]" :key="option.value" :class="{active:state===option.value}" @click="state=option.value;filter()">{{ option.label }}</button></div><div class="task-filter-selects"><el-select v-model="taskType" placeholder="全部类型" clearable @change="filter"><el-option v-for="(label,key) in taskLabels" :key="key" :label="label" :value="key" /></el-select><el-select v-model="state" placeholder="全部状态" clearable @change="filter"><el-option v-for="(label,key) in {scheduled:'预约中',submitting:'提交中',queued:'排队中',running:'执行中',collecting:'归档中',cancelling:'取消中',succeeded:'已完成',failed:'失败',cancelled:'已取消',timed_out:'已超时'}" :key="key" :label="label" :value="key" /></el-select></div></div>
<div class="task-list" v-loading="loading"><article v-for="job in items" :key="job.id" class="task-row"><button class="task-thumb" @click="detailId=job.id"><img v-if="job.result_assets.find(a=>a.kind==='image'||a.thumbnail_url)" :src="job.result_assets.find(a=>a.kind==='image'||a.thumbnail_url)?.thumbnail_url || job.result_assets.find(a=>a.kind==='image'||a.thumbnail_url)?.preview_url" :alt="job.prompt" /><el-icon v-else :size="24"><VideoCamera v-if="job.task_type.includes('video')" /><Picture v-else-if="job.task_type.includes('image')||job.task_type.includes('defect')" /><Document v-else /></el-icon></button><div class="task-main"><div class="task-title-line"><span class="task-type">{{ taskLabels[job.task_type] }}</span><span class="status-pill" :class="job.state">{{ stateLabel(job) }}</span><small v-if="job.attempt_count>1">第 {{ job.attempt_count }} 次尝试</small></div><button class="task-title" @click="detailId=job.id">{{ job.prompt || taskLabels[job.task_type] }}</button><p :class="{'warning-text':job.sync_warning||job.preemptions}">{{ phaseLabel(job) }}</p><small>{{ formatDate(job.created_at) }} <span v-if="job.preemptions"> · 已让行 {{ job.preemptions }} 次</span></small></div><div class="task-row-actions"><el-button v-if="isActive(job)" text :icon="Close" :loading="pendingId===job.id" :disabled="job.cancel_requested" @click="cancel(job)">{{ job.cancel_requested?'正在取消':'取消' }}</el-button><el-button v-else-if="!job.run_id" text :icon="RefreshRight" :loading="pendingId===job.id" @click="retry(job)">{{ job.state==='succeeded'?'再生成':'重试' }}</el-button><el-button text :icon="ArrowRight" @click="detailId=job.id">详情</el-button><DeleteRecordButton kind="job" :record="job" /></div></article><div v-if="!loading&&!items.length" class="empty-state full-empty"><el-icon :size="42"><Collection /></el-icon><h3>这里还没有符合条件的任务</h3><p>去工作台提交一次创作,进度和最终结果都会在这里同步。</p><router-link to="/create/image" class="el-button el-button--primary">开始第一项创作</router-link></div></div>

View File

@ -79,9 +79,9 @@ onMounted(() => { void jobs.refresh().catch(() => undefined); void importReferen
<el-popover placement="top-start" :width="310" trigger="click"><template #reference><button class="parameter-chip">{{ draft.parameters.width || '—' }} × {{ draft.parameters.height || '—' }}</button></template><div class="parameter-form"><h3>画面尺寸</h3><div v-if="mode !== 'video'" class="ratio-options"><button @click="ratio(1024, 1024)">1:1</button><button @click="ratio(1280, 720)">16:9</button><button @click="ratio(720, 1280)">9:16</button></div><label>宽度<el-input-number v-model="draft.parameters.width" :min="bound('width','min',256)" :max="bound('width','max',2048)" :step="bound('width','step',16)" /></label><label>高度<el-input-number v-model="draft.parameters.height" :min="bound('height','min',256)" :max="bound('height','max',2048)" :step="bound('height','step',16)" /></label></div></el-popover>
<span v-if="mode === 'video'" class="parameter-chip">约 5 秒 · 121 帧 · 24 fps</span><el-select v-else v-model="draft.count" class="count-select" aria-label="生成数量"><el-option v-for="count in bound('count','max',4)" :key="count" :value="count" :label="`${count} 张`" /></el-select>
<el-popover trigger="click" placement="top" :width="340"><template #reference><button class="parameter-chip"><el-icon><Setting /></el-icon>参数</button></template><div class="parameter-form"><h3>生成参数</h3><label>步数<el-input-number v-model="draft.parameters.num_inference_steps" :min="bound('num_inference_steps','min',1)" :max="bound('num_inference_steps','max',100)" /></label><label v-if="draft.parameters.seed !== undefined">随机种子<el-input-number v-model="draft.parameters.seed" :min="0" :max="4294967295" :controls="false" /></label><label v-if="draft.parameters.guidance_scale !== undefined">引导强度<el-input-number v-model="draft.parameters.guidance_scale" :min="bound('guidance_scale','min',1)" :max="bound('guidance_scale','max',20)" :step="0.5" /></label><template v-if="mode === 'defect'"><label>结构控制强度<el-input-number v-model="draft.parameters.controlnet_conditioning_scale" :min="0" :max="2" :step="0.1" /></label><label>Canny低阈值<el-input-number v-model="draft.parameters.canny_low" :min="0" :max="254" /></label><label>Canny高阈值<el-input-number v-model="draft.parameters.canny_high" :min="1" :max="255" /></label></template><label v-if="mode === 'video'">1080p 画质增强<el-switch v-model="draft.parameters.upscale" /></label><label class="vertical-label">不希望出现的内容<el-input v-model="draft.negative_prompt" maxlength="8000" type="textarea" :rows="2" placeholder="可选,例如模糊、变形" /></label><small v-if="mode === 'defect'">输出合成图和 Canny 控制图,不提供缺陷真值掩膜。</small><small v-if="mode === 'video'">单镜头最长约 5 秒;较长故事请前往工作流添加多个镜头。</small></div></el-popover>
<el-popover trigger="click" placement="top" :width="300"><template #reference><button class="parameter-chip" :class="{ highlighted: draft.scheduledAt }"><el-icon><Clock /></el-icon>{{ draft.scheduledAt ? '已预约' : '预约' }}</button></template><div class="parameter-form"><h3>预约创作</h3><el-date-picker v-model="draft.scheduledAt" type="datetime" placeholder="选择开始时间" value-format="YYYY-MM-DDTHH:mm:ss" clearable /><small>按当前浏览器时区选择。到达时间后进入串行队列。</small></div></el-popover>
<el-popover trigger="click" placement="top" :width="300"><template #reference><button class="parameter-chip" :class="{ highlighted: draft.scheduledAt }"><el-icon><Clock /></el-icon>{{ draft.scheduledAt ? '已预约' : '预约' }}</button></template><div class="parameter-form"><h3>预约创作</h3><el-date-picker v-model="draft.scheduledAt" type="datetime" placeholder="选择开始时间" value-format="YYYY-MM-DDTHH:mm:ss" clearable /><small>按当前浏览器时区选择。到达时间后按就绪顺序等待空闲GPU。</small></div></el-popover>
</div><el-button class="generate-button" type="primary" :loading="busy" :disabled="!capability?.available" :icon="MagicStick" @click="submit">{{ draft.scheduledAt ? '预约生成' : '开始生成' }} <el-icon v-if="!busy"><ArrowRight /></el-icon></el-button></div>
</div><div class="composer-footnote"><span>{{ capability?.available ? '空闲算力串行执行 · 被占用时自动让行与重试' : capability?.description || '正在连接本地创作服务' }}</span><span>Ctrl + Enter 生成</span></div></section>
</div><div class="composer-footnote"><span>{{ capability?.available ? '空闲GPU并行执行 · 先到先派发 · 外部占卡时让行' : capability?.description || '正在连接本地创作服务' }}</span><span>Ctrl + Enter 生成</span></div></section>
<AssetPreview v-model:asset="selectedAsset" /><JobDetail v-model:job-id="detailId" />
</div>
</template>

View File

@ -318,6 +318,73 @@ class GpuGuard:
if self.emit_event:
self.emit_event({"event": event, "count": 1})
def _inspection_failure(self, pid, stage, exc):
if isinstance(exc, (FileNotFoundError, ProcessLookupError)):
category = "not_found"
elif isinstance(exc, PermissionError):
category = "permission_denied"
elif isinstance(exc, GuardError):
category = "identity_invalid"
else:
category = "os_error"
if self.emit_event:
self.emit_event({"event": "process_inspection_failed", "count": 1,
"pid": pid, "stage": stage, "category": category})
# A missing exe/status/cgroup alone is not proof of process exit.
# Only kernel disappearance errors AND an absent PID directory qualify.
if category == "not_found":
try:
(self.proc_root / str(pid)).stat()
except (FileNotFoundError, ProcessLookupError):
return True
except OSError:
pass
return False
def _inspect_sample(self, raw_gpus, policy, forced_external=frozenset()):
identities, failed, missing, ambiguous = {}, set(), set(), set()
for pid in sorted({row["pid"] for gpu in raw_gpus for row in gpu["processes"]}):
try:
identities[pid] = read_process_identity(pid, self.proc_root)
except (OSError, GuardError) as exc:
identities[pid] = None
failed.add(pid)
if self._inspection_failure(pid, "identity", exc):
missing.add(pid)
else:
ambiguous.add(pid)
baselines = {item.pid: item for item in policy.baseline_processes}
inspected = []
for raw in raw_gpus:
own, external, baseline = [], [], []
by_pid = {}
for row in raw["processes"]:
by_pid.setdefault(row["pid"], []).append(row)
for pid, rows in by_pid.items():
identity = identities[pid]
try:
if identity is None or pid in forced_external:
external.append(pid)
elif pid in baselines:
(baseline if self._baseline_ok(identity, rows, baselines[pid]) else external).append(pid)
elif self._dynamic_baseline_ok(identity, rows, policy.baseline_rules):
baseline.append(pid)
elif identity.owned_by(policy.container_id):
own.append(pid)
else:
external.append(pid)
except (OSError, GuardError) as exc:
external.append(pid)
failed.add(pid)
if self._inspection_failure(pid, "baseline", exc):
missing.add(pid)
else:
ambiguous.add(pid)
inspected.append({key: raw[key] for key in ("index", "uuid", "total_gib", "free_gib")}
| {"external_pids": sorted(external), "own_pids": sorted(own),
"baseline_pids": sorted(baseline)})
return inspected, identities, failed, missing - ambiguous
def _baseline_ok(self, identity, rows, baseline):
if identity.start != baseline.start or any(row["type"] != "G" or row["used_memory_mib"] is None
or row["used_memory_mib"] > baseline.max_memory_mib for row in rows):
@ -385,47 +452,32 @@ class GpuGuard:
raise
xml = self.query() # One retry; leave the old snapshot untouched.
raw_gpus = parse_gpu_xml(xml)
inspected, identities, failed, missing = self._inspect_sample(raw_gpus, policy)
if missing:
# Occupancy in the first sample breaks continuous idle time,
# even when the confirming sample finds that process gone.
for gpu in inspected:
if gpu["own_pids"] or gpu["external_pids"]:
self.idle.pop(gpu["uuid"], None)
# One fresh full sample, with no timeout retry here. Reinspect
# every PID so new external users cannot be lost in the race.
raw_gpus = parse_gpu_xml(self.query())
present = {row["pid"] for gpu in raw_gpus for row in gpu["processes"]}
inspected, identities, fresh_failed, _ = self._inspect_sample(raw_gpus, policy, failed)
failed = (failed - (missing - present)) | fresh_failed
if failed:
error = "process_inspection_failed"
now, epoch = self.monotonic(), self.wall_time()
if self.last_sample is not None and (now < self.last_sample or now - self.last_sample > 5):
self._reset() # No idle credit across a paused/missing observer.
self.last_sample = now
identities = {}
for pid in {row["pid"] for gpu in raw_gpus for row in gpu["processes"]}:
try:
identities[pid] = read_process_identity(pid, self.proc_root)
except (OSError, GuardError):
identities[pid] = None
error = "process_inspection_failed"
baselines = {item.pid: item for item in policy.baseline_processes}
for raw in raw_gpus:
own, external, baseline = [], [], []
by_pid = {}
for row in raw["processes"]:
by_pid.setdefault(row["pid"], []).append(row)
for pid, rows in by_pid.items():
identity = identities[pid]
try:
if identity is None:
external.append(pid)
elif pid in baselines:
(baseline if self._baseline_ok(identity, rows, baselines[pid]) else external).append(pid)
elif self._dynamic_baseline_ok(identity, rows, policy.baseline_rules):
baseline.append(pid)
elif identity.owned_by(policy.container_id):
own.append(pid)
else:
external.append(pid)
except (OSError, GuardError):
external.append(pid)
error = "process_inspection_failed"
uuid = raw["uuid"]
if own or external:
for gpu in inspected:
uuid = gpu["uuid"]
if gpu["own_pids"] or gpu["external_pids"]:
self.idle.pop(uuid, None)
else:
self.idle.setdefault(uuid, epoch)
gpus.append({key: raw[key] for key in ("index", "uuid", "total_gib", "free_gib")}
| {"idle_since": self.idle.get(uuid), "external_pids": sorted(external),
"own_pids": sorted(own), "baseline_pids": sorted(baseline)})
gpus.append(gpu | {"idle_since": self.idle.get(uuid)})
if self.stop_requested:
raise GuardError("guard_stopped")
if error is None:

View File

@ -82,7 +82,7 @@ def configure_gpu_budget() -> None:
raise RuntimeError("Runner requires exactly one visible CUDA device, mapped to its selected GPU")
total = torch.cuda.get_device_properties(0).total_memory
torch.cuda.set_per_process_memory_fraction(memory_fraction(total), device=0)
torch.set_num_threads(min(8, os.cpu_count() or 1))
torch.set_num_threads(min(int(os.environ.get('OMP_NUM_THREADS', '8')), os.cpu_count() or 1))
def rpc_base_path() -> Path:
@ -118,11 +118,12 @@ def budgeted_child_environment(runtime: Path) -> dict[str, str]:
" sys.stderr.flush()\n"
" os._exit(78)\n", encoding="utf-8")
env = dict(os.environ)
env.setdefault('OMP_NUM_THREADS', '8')
project = str(Path(__file__).resolve().parent.parent)
env["PYTHONPATH"] = os.pathsep.join(filter(None, (str(bootstrap), project, env.get("PYTHONPATH"))))
temporary = runtime / "tmp"
temporary.mkdir()
env.update(VLLM_WORKER_MULTIPROC_METHOD="spawn", OMP_NUM_THREADS="8", TOKENIZERS_PARALLELISM="false",
env.update(VLLM_WORKER_MULTIPROC_METHOD="spawn", TOKENIZERS_PARALLELISM="false",
VLLM_RPC_BASE_PATH=str(rpc_base_path()),
HF_HUB_OFFLINE="1", TRANSFORMERS_OFFLINE="1", HF_HOME="/workspace/.cache/huggingface",
XDG_CACHE_HOME="/workspace/.cache", TORCH_HOME="/workspace/.cache/torch",

View File

@ -77,7 +77,7 @@ def create_app(settings=None):
configuration = application.state.settings
unresolved = application.state.store.running()
return {"status": "ok", "running_jobs": len(unresolved),
"runner_marker_present": configuration.runner_marker.exists()}
"runner_marker_present": bool(configuration.active_markers())}
@application.get("/capabilities", dependencies=secured)
def capabilities():

View File

@ -0,0 +1,50 @@
"""Conservative cgroup-v2 admission; reservations include model loading/offload.
Working memory excludes reclaimable inactive file cache. Without reliable per-job
attribution, observed memory cannot be credited against model reservations: other
container-local workloads may grow during execution. Add active reservations in
full to observed working memory, then reserve the next job and global headroom.
This deliberately overcounts already-loaded model memory and can reduce slots.
SHM pages are already charged to memory.current, but full SHM independently blocks
admission. Unreadable/unlimited production budgets fail closed.
"""
from pathlib import Path
import shutil
GIB = 1024 ** 3
class MemoryAdmission:
def __init__(self, settings, *, cgroup=Path('/sys/fs/cgroup'), shm_usage=None):
self.settings = settings
self.cgroup = Path(cgroup)
self.last_sample = None
self.shm_usage = shm_usage or self._shm
@staticmethod
def _shm():
usage = shutil.disk_usage('/dev/shm')
return usage.used, usage.total
def check(self, task_type, reservations):
try:
maximum = int((self.cgroup / 'memory.max').read_text().strip())
current = int((self.cgroup / 'memory.current').read_text().strip())
stats = dict(line.split() for line in (self.cgroup / 'memory.stat').read_text().splitlines())
working = max(0, current - int(stats.get('inactive_file', 0)))
used, total = self.shm_usage()
events_path = self.cgroup / 'memory.events'
events = dict(line.split() for line in events_path.read_text().splitlines()) if events_path.exists() else {}
required = (working + sum(reservations) * GIB
+ (self.settings.memory_estimates_gib[task_type] + self.settings.memory_headroom_gib) * GIB)
self.last_sample = {'memory_current_bytes': current, 'memory_max_bytes': maximum,
'working_bytes': working, 'reserved_bytes': sum(reservations) * GIB,
'admission_required_bytes': required, 'shm_used_bytes': used, 'shm_total_bytes': total,
'memory_events': {name: int(value) for name, value in events.items()}}
if total <= 0 or total - used < min(GIB, total * .05):
return 'Shared memory pressure; waiting for /dev/shm capacity'
if required > maximum:
return 'Container memory budget insufficient; FIFO head waiting'
except (OSError, ValueError, KeyError, TypeError):
return 'Container memory budget unavailable; dispatch blocked'
return None

View File

@ -4,7 +4,7 @@ The runner is untrusted input-wise, but is managed code: it must not daemonize
or move children into another process group. No model libraries are imported.
"""
from contextlib import contextmanager
from dataclasses import dataclass
from dataclasses import dataclass, field
import hashlib
import json
import math
@ -87,6 +87,11 @@ class Settings:
terminate_grace_seconds: float = 5.0
kill_wait_seconds: float = 10.0
runtime_policy_file: Path | None = None
max_gpu_jobs: int = 4
cpu_threads_per_job: int = 2
memory_headroom_gib: float = 16
memory_estimates_gib: dict = field(default_factory=lambda: {
"image.generate": 88, "video.generate": 64, "defect.generate": 24, "audio.transcribe": 12})
def __post_init__(self):
self.workspace_root = Path(self.workspace_root).resolve()
@ -97,6 +102,15 @@ class Settings:
self.runtime_policy_file.relative_to(self.workspace_root)
except ValueError as exc:
raise ValueError("APP_ROOT must be below WORKSPACE_ROOT") from exc
for name, maximum in (("max_gpu_jobs", 4), ("cpu_threads_per_job", 64)):
value = getattr(self, name)
if type(value) is not int or not 1 <= value <= maximum:
raise ValueError(name + " must be a positive bounded integer")
if not isinstance(self.memory_estimates_gib, dict) or set(self.memory_estimates_gib) != TASK_TYPES:
raise ValueError("memory_estimates_gib must cover every task type")
for value in [self.memory_headroom_gib, *self.memory_estimates_gib.values()]:
if isinstance(value, bool) or not isinstance(value, (float, int)) or not math.isfinite(value) or value <= 0:
raise ValueError("Memory reservations must be positive finite GiB")
for field in ("poll_seconds", "terminate_grace_seconds", "kill_wait_seconds"):
value = float(getattr(self, field))
if not math.isfinite(value) or value <= 0:
@ -131,6 +145,14 @@ class Settings:
def runner_marker(self):
return self.state_dir / "active-runner.json"
@property
def runner_markers(self):
return self.state_dir / "active-runners"
def active_markers(self):
return ([self.runner_marker] if self.runner_marker.exists() or self.runner_marker.is_symlink() else []) + (
list(self.runner_markers.iterdir()) if self.runner_markers.exists() else [])
@classmethod
def from_env(cls):
root = Path(os.environ.get("APP_ROOT", "/workspace/projects/llm-services"))
@ -145,6 +167,11 @@ class Settings:
break
return cls(root, workspace,
runner_python=os.environ.get("LLM_RUNNER_PYTHON", data.get("runner_python", cls.runner_python)),
max_gpu_jobs=data.get("max_gpu_jobs", 4),
cpu_threads_per_job=data.get("cpu_threads_per_job", 2),
memory_headroom_gib=data.get("memory_headroom_gib", 16),
memory_estimates_gib=data.get("memory_estimates_gib", {
"image.generate": 88, "video.generate": 64, "defect.generate": 24, "audio.transcribe": 12}),
poll_seconds=data.get("poll_seconds", .2),
terminate_grace_seconds=data.get("terminate_grace_seconds", 5),
kill_wait_seconds=data.get("kill_wait_seconds", 10),
@ -211,12 +238,15 @@ class Store:
result_json TEXT
);
CREATE INDEX IF NOT EXISTS jobs_state_queue ON jobs(state, queue_seq);
CREATE UNIQUE INDEX IF NOT EXISTS one_running_job ON jobs(state) WHERE state='running';
""")
# API and worker may initialize together. Serialize schema changes
# and inspect columns again while holding the migration transaction.
connection.execute("BEGIN IMMEDIATE")
try:
version = connection.execute("PRAGMA user_version").fetchone()[0]
if version > 2:
raise RuntimeError("Unsupported queue schema version")
columns = {row["name"] for row in connection.execute("PRAGMA table_info(jobs)")}
additions = {"attempt_count": "INTEGER NOT NULL DEFAULT 0",
"preemptions": "INTEGER NOT NULL DEFAULT 0", "gpu_uuid": "TEXT",
@ -231,6 +261,12 @@ class Store:
connection.execute("CREATE TABLE IF NOT EXISTS scheduler_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
connection.execute("CREATE TABLE IF NOT EXISTS control_commands (id TEXT PRIMARY KEY, job_id TEXT NOT NULL, request_hash TEXT NOT NULL)")
connection.execute("CREATE INDEX IF NOT EXISTS jobs_admission ON jobs(state,admission_paused,execution_mode,queue_seq)")
connection.execute("DROP INDEX IF EXISTS one_running_job")
# A table with the legacy index name makes old binaries fail explicitly
# before they can recreate the singleton constraint, even with zero jobs.
connection.execute("CREATE TABLE IF NOT EXISTS one_running_job (schema_version INTEGER NOT NULL CHECK(schema_version=2))")
connection.execute("CREATE UNIQUE INDEX IF NOT EXISTS one_running_gpu ON jobs(lower(COALESCE(gpu_uuid,'legacy-unbound'))) WHERE state='running'")
connection.execute("PRAGMA user_version=2")
connection.commit()
except BaseException:
connection.rollback()
@ -328,26 +364,10 @@ class Store:
def _select_next(self, connection, now):
opened = self._batch_eligibility(connection, now)["eligible"]
streak = int(self._state(connection, "interactive_streak", "0"))
modes = ["batch", "interactive"] if opened and streak >= 4 else ["interactive", "batch"]
for mode in modes:
if mode == "batch" and not opened:
continue
principals = [row[0] for row in connection.execute("""SELECT DISTINCT principal_id FROM jobs
WHERE state='queued' AND admission_paused=0 AND execution_mode=? ORDER BY principal_id""", (mode,))]
if not principals:
continue
previous = self._state(connection, "last_principal_" + mode)
owner = next((p for p in principals if p > previous), principals[0])
groups = [row[0] for row in connection.execute("""SELECT DISTINCT COALESCE(batch_id,'') FROM jobs
WHERE state='queued' AND admission_paused=0 AND execution_mode=? AND principal_id=?
ORDER BY COALESCE(batch_id,'')""", (mode, owner))]
old_group = self._state(connection, "last_batch_" + mode + "_" + owner)
group = next((p for p in groups if p > old_group), groups[0])
return connection.execute("""SELECT * FROM jobs WHERE state='queued' AND admission_paused=0
AND execution_mode=? AND principal_id=? AND COALESCE(batch_id,'')=?
ORDER BY queue_seq LIMIT 1""", (mode, owner, group)).fetchone()
return None
return connection.execute("""SELECT * FROM jobs WHERE state='queued'
AND admission_paused=0 AND cancel_requested=0
AND (execution_mode='interactive' OR ?)
ORDER BY queue_seq LIMIT 1""", (int(opened),)).fetchone()
def peek_next(self, *, now=None):
with self._connection() as connection:
@ -387,20 +407,21 @@ class Store:
connection.rollback()
raise
def claim_next(self, *, gpu_uuid=None, now=None):
def claim_next(self, *, gpu_uuid=None, now=None, max_gpu_jobs=4, expected_job_id=None):
with self._connection() as connection:
connection.execute("BEGIN IMMEDIATE")
try:
if connection.execute("SELECT 1 FROM jobs WHERE state='running' LIMIT 1").fetchone():
if (connection.execute("SELECT COUNT(*) FROM jobs WHERE state='running'").fetchone()[0] >= max_gpu_jobs
or connection.execute("SELECT 1 FROM jobs WHERE state='running' AND lower(COALESCE(gpu_uuid,'legacy-unbound'))=lower(?)", (gpu_uuid or 'legacy-unbound',)).fetchone()):
connection.commit()
return None
now = time.time() if now is None else now
row = self._select_next(connection, now)
if row is None:
if row is None or (expected_job_id is not None and row["id"] != expected_job_id):
connection.commit()
return None
connection.execute("""UPDATE jobs SET state='running',stage='launching',started_at=?,
updated_at=?,attempt_count=attempt_count+1,gpu_uuid=? WHERE id=?""",
updated_at=?,attempt_count=attempt_count+1,gpu_uuid=?,runner_pid=NULL,runner_start=NULL,runner_pgid=NULL WHERE id=?""",
(now, now, gpu_uuid, row["id"]))
self._set_state(connection, "last_principal_" + row["execution_mode"], row["principal_id"])
self._set_state(connection, "last_batch_" + row["execution_mode"] + "_" + row["principal_id"], row["batch_id"] or "")
@ -469,11 +490,11 @@ class Store:
raise
return self.get(job_id)
def set_runner(self, job_id, pid, start, pgid):
def set_runner(self, job_id, pid, start, pgid, *, attempt_count=None):
with self._connection() as connection:
count = connection.execute("""UPDATE jobs SET runner_pid=?,runner_start=?,runner_pgid=?,
stage='executing',updated_at=? WHERE id=? AND state='running'""",
(pid, start, pgid, time.time(), job_id)).rowcount
stage='executing',updated_at=? WHERE id=? AND state='running' AND ((? IS NULL AND attempt_count=1) OR attempt_count=?)""",
(pid, start, pgid, time.time(), job_id, attempt_count, attempt_count)).rowcount
if count != 1:
raise RuntimeError("Job no longer owns the execution slot")
@ -487,7 +508,7 @@ class Store:
updated_at=? WHERE id=? AND state IN ('queued','running')""", (now, now, job_id))
return self.get(job_id)
def requeue_preempted(self, job_id, reason):
def requeue_preempted(self, job_id, reason, *, attempt_count=None):
"""Worker-only: call after proving the entire runner process group gone.
Keep queue_seq/id so the interrupted request retains its original place.
@ -498,8 +519,8 @@ class Store:
with self._connection() as connection:
connection.execute("BEGIN IMMEDIATE")
try:
row = connection.execute("SELECT state,cancel_requested FROM jobs WHERE id=?", (job_id,)).fetchone()
if row is None or row["state"] != "running":
row = connection.execute("SELECT state,cancel_requested,attempt_count FROM jobs WHERE id=?", (job_id,)).fetchone()
if row is None or row["state"] != "running" or (row["attempt_count"] != (1 if attempt_count is None else attempt_count)):
raise RuntimeError("Only the running attempt may be requeued")
state = "cancelled" if row["cancel_requested"] else "queued"
now = time.time()
@ -516,14 +537,14 @@ class Store:
raise
return self.get(job_id)
def finish(self, job_id, state, *, result=None, error=None):
def finish(self, job_id, state, *, result=None, error=None, attempt_count=None):
if state not in TERMINAL_STATES:
raise ValueError("Invalid terminal state")
with self._connection() as connection:
connection.execute("BEGIN IMMEDIATE")
try:
row = connection.execute("SELECT state,cancel_requested FROM jobs WHERE id=?", (job_id,)).fetchone()
if row is None or row["state"] != "running":
row = connection.execute("SELECT state,cancel_requested,attempt_count FROM jobs WHERE id=?", (job_id,)).fetchone()
if row is None or row["state"] != "running" or (row["attempt_count"] != (1 if attempt_count is None else attempt_count)):
raise RuntimeError("Cannot finish a job outside its running attempt")
if row["cancel_requested"]:
state, result, error = "cancelled", None, "Cancellation requested before completion"
@ -540,7 +561,7 @@ class Store:
def initialize_store(settings):
settings.workspace_root.mkdir(parents=True, exist_ok=True)
for directory in (settings.app_root, settings.state_dir, settings.jobs_dir, settings.outputs_dir):
for directory in (settings.app_root, settings.state_dir, settings.jobs_dir, settings.outputs_dir, settings.runner_markers):
confined_path(directory, settings.workspace_root).mkdir(parents=True, exist_ok=True)
confined_path(settings.db_path, settings.workspace_root)
return Store(settings.db_path, policy_file=settings.runtime_policy_file)

View File

@ -1,4 +1,4 @@
"""Linux-only single execution slot. Run with ``python -m llm_services.worker``.
"""Linux-only singleton FIFO dispatcher with independent per-GPU execution monitors. Run with ``python -m llm_services.worker``.
Never auto-requeue a hard-crashed job. Cooperative GPU preemption requeues only
after the entire runner group is proven stopped. If a previous running row or runner
@ -13,6 +13,7 @@ import signal
import subprocess
import sys
import time
import threading
from .store import (Settings, atomic_json, confined_path, initialize_store,
open_confined_file, validate_request)
@ -92,6 +93,14 @@ class Worker:
self._lock_fd = None
self.stop_requested = False
self._scheduler_snapshot = None
self._scheduler_written_at = 0
self._coordinator_thread = threading.get_ident()
self._active_lock = threading.RLock()
self._active = {}
self._threads = {}
self._errors = []
from .resources import MemoryAdmission
self.memory_admission = MemoryAdmission(self.settings)
def __enter__(self):
if not sys.platform.startswith("linux"):
@ -106,7 +115,7 @@ class Worker:
raise WorkerBusy("Another worker owns the execution slot") from exc
self._lock_fd = fd
unresolved = self.store.running()
marker_exists = self.settings.runner_marker.exists() or self.settings.runner_marker.is_symlink()
marker_exists = bool(self.settings.active_markers())
residual = existing_runners()
if unresolved or marker_exists or residual:
details = [{"job_id": job["id"], "runner_pid": job["runner_pid"],
@ -122,6 +131,7 @@ class Worker:
raise
def __exit__(self, exc_type, exc, traceback):
self.shutdown()
if self._lock_fd is not None:
os.close(self._lock_fd)
self._lock_fd = None
@ -152,19 +162,115 @@ class Worker:
raise UnsafeRecovery("Runner process group did not stop; leaving running record and blocking dispatch")
def _publish_scheduler(self, state, *, lease=None, job=None, reason=None):
# Monitors update their own entry; only the dispatcher writes the file.
with self._active_lock:
if job is not None:
key = (job['id'], job['attempt_count'])
if job['state'] == 'running':
self._active[key] = {'job_id': job['id'], 'attempt_count': job['attempt_count'],
'gpu_index': lease.get('index') if lease else None,
'gpu_uuid': lease.get('uuid') if lease else job.get('gpu_uuid'),
'stage': job['stage'], 'state': state if state in {'preempting', 'blocked'} else
'launching' if job['stage'] == 'launching' else 'running',
'reason': reason, 'task_type': job['task_type']}
else:
self._active.pop(key, None)
if threading.get_ident() != self._coordinator_thread:
return
entries = [{k:v for k,v in item.items() if k != 'task_type'} for item in self._active.values()]
try:
policy_status = self.gpu_policy.describe() if self.gpu_policy is not None else {"enabled": False}
policy_status = self.gpu_policy.describe() if self.gpu_policy is not None else {'enabled': False}
except Exception as exc:
policy_status = {"error": f"{type(exc).__name__}: {exc}"}
payload = {"state": state, "lease": lease, "job_id": job["id"] if job else None,
"attempt_count": job["attempt_count"] if job else None,
"reason": reason, "policy": policy_status, "worker_pid": os.getpid(),
"execution_policy": execution_policy_status(self.clock(), policy_file=self.settings.runtime_policy_file)}
policy_status = {'error': f'{type(exc).__name__}: {exc}'}
waiting = self.store.waiting_summary(now=self.clock())
payload = {'schema_version': 2, 'active_jobs': entries, 'running_count': len(entries),
'queued_count': waiting['queued'], 'state': 'blocked' if self._errors or state == 'blocked' else
'running' if entries else 'waiting' if waiting['queued'] else 'idle',
'reason': reason, 'policy': policy_status, 'worker_pid': os.getpid(),
'memory': getattr(self.memory_admission, 'last_sample', None),
'execution_policy': execution_policy_status(self.clock(), policy_file=self.settings.runtime_policy_file)}
snapshot = json.dumps(payload, sort_keys=True, allow_nan=False)
if snapshot != self._scheduler_snapshot:
atomic_json(confined_path(self.settings.state_dir / "gpu-scheduler.json",
self.settings.workspace_root), {**payload, "updated_at": time.time()})
if snapshot != self._scheduler_snapshot or time.monotonic() - self._scheduler_written_at >= 1:
atomic_json(confined_path(self.settings.state_dir / 'gpu-scheduler.json', self.settings.workspace_root),
{**payload, 'updated_at': time.time()})
self._scheduler_snapshot = snapshot
self._scheduler_written_at = time.monotonic()
def dispatch_once(self):
if self._lock_fd is None:
raise RuntimeError('Acquire the worker lock before dispatch')
for key, thread in list(self._threads.items()):
if not thread.is_alive():
thread.join()
del self._threads[key]
if self._errors:
self._publish_scheduler('blocked', reason=str(self._errors[0]))
raise UnsafeRecovery(str(self._errors[0]))
reason = None
dispatched = False
# Refresh eligible telemetry for each claim, then exclude persistent/local leases.
while not self.stop_requested and len(self._threads) < self.settings.max_gpu_jobs:
queued = self.store.peek_next(now=self.clock())
if queued is None:
break
if self.gpu_policy is None:
reason = 'GPU authority is required for parallel dispatch'
break
try:
eligible = self.gpu_policy.describe().get('eligible_gpus', [])
except Exception as exc:
reason = f'GPU policy unavailable: {type(exc).__name__}: {exc}'
break
running = self.store.running()
occupied = {j['gpu_uuid'].lower() for j in running if j['gpu_uuid']}
lease = next((item for item in eligible if item['uuid'].lower() not in occupied), None)
if lease is None:
reason = 'No eligible GPU; busy or stale status'
break
reservations = [self.settings.memory_estimates_gib[j['task_type']] for j in running]
reason = self.memory_admission.check(queued['task_type'], reservations)
if reason:
break
job = self.store.claim_next(gpu_uuid=lease['uuid'], now=self.clock(),
max_gpu_jobs=self.settings.max_gpu_jobs, expected_job_id=queued['id'])
if job is None:
break
key = (job['id'], job['attempt_count'])
launched = threading.Event()
self._publish_scheduler('running', job=job, lease=lease)
thread = threading.Thread(target=self._monitor, args=(job, lease, launched),
name=f'gpu-{job["id"]}-{job["attempt_count"]}', daemon=True)
self._threads[key] = thread
thread.start()
# Spawn order follows claim order. Monitors then execute independently.
while not launched.wait(.05):
self._publish_scheduler('running')
if self.stop_requested:
break
dispatched = True
if self._errors:
break
self._publish_scheduler('waiting', reason=reason)
return dispatched
def _monitor(self, job, lease, launched):
try:
self._execute(job, lease, launched)
except BaseException as exc:
with self._active_lock:
self._errors.append(exc)
LOG.exception('Runner monitor failed; operator recovery required')
finally:
launched.set()
def shutdown(self):
self.stop_requested = True
deadline = time.monotonic() + self.settings.terminate_grace_seconds + self.settings.kill_wait_seconds + 5
for thread in list(self._threads.values()):
thread.join(timeout=max(0, deadline-time.monotonic()))
if any(thread.is_alive() for thread in self._threads.values()):
self._errors.append(UnsafeRecovery('Runner monitors did not stop; retain all recovery evidence'))
self._publish_scheduler('blocked' if self._errors else 'idle')
def _yield_reason(self, lease):
if self.gpu_policy is None:
@ -248,6 +354,10 @@ class Worker:
if job is None:
return False
return self._execute(job, lease)
def _execute(self, job, lease, launched=None):
marker = self.settings.runner_markers / f"{job['id']}-{job['attempt_count']}.json"
process = None
pgid = None
clean = False
@ -257,7 +367,7 @@ class Worker:
try:
# Claim is FULL-synchronous and committed BEFORE spawn. A crash in
# spawn->PID persistence leaves running/launching and fails closed.
atomic_json(self.settings.runner_marker, {"job_id": job["id"], "phase": "launching",
atomic_json(marker, {"job_id": job["id"], "phase": "launching",
"worker_pid": os.getpid(), "lease": lease,
"attempt_count": job["attempt_count"]})
self._publish_scheduler("leased", lease=lease, job=job)
@ -286,6 +396,8 @@ class Worker:
clean = True
else:
environment = os.environ.copy()
for name in ('OMP_NUM_THREADS', 'MKL_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'NUMEXPR_NUM_THREADS'):
environment[name] = str(self.settings.cpu_threads_per_job)
environment["APP_ROOT"] = str(self.settings.app_root)
environment["WORKSPACE_ROOT"] = str(self.settings.workspace_root)
environment["PYTHONPATH"] = str(self.settings.app_root)
@ -302,15 +414,18 @@ class Worker:
start_new_session=True, close_fds=True)
pgid = process.pid
identity = process_identity(process.pid)
self.store.set_runner(job["id"], process.pid, identity["start"] if identity else None, pgid)
atomic_json(self.settings.runner_marker, {"job_id": job["id"], "phase": "executing",
self.store.set_runner(job["id"], process.pid, identity["start"] if identity else None, pgid, attempt_count=job["attempt_count"])
atomic_json(marker, {"job_id": job["id"], "phase": "executing",
"runner_pid": process.pid, "runner_start": identity["start"] if identity else None,
"pgid": pgid, "worker_pid": os.getpid(), "lease": lease,
"attempt_count": job["attempt_count"]})
self._publish_scheduler('running', lease=lease, job=self.store.get(job['id']))
if launched is not None:
launched.set()
deadline = time.monotonic() + job["timeout_seconds"]
while True:
current = self.store.get(job["id"])
if current is None or current["state"] != "running":
if current is None or current["state"] != "running" or current["attempt_count"] != job["attempt_count"]:
raise UnsafeRecovery("Running job state changed outside the worker")
if current["cancel_requested"] or self.stop_requested:
if current["cancel_requested"]:
@ -389,12 +504,15 @@ class Worker:
if deferred_reason:
self.store.defer_unlaunched(job["id"], job["attempt_count"], deferred_reason)
elif preempt_reason:
self.store.requeue_preempted(job["id"], preempt_reason)
self.store.requeue_preempted(job["id"], preempt_reason, attempt_count=job["attempt_count"])
else:
self.store.finish(job["id"], state, result=result, error=error)
self.settings.runner_marker.unlink(missing_ok=True)
current = self.store.get(job["id"])
self._publish_scheduler(current["state"], job=current, reason=preempt_reason or error)
self.store.finish(job["id"], state, result=result, error=error, attempt_count=job["attempt_count"])
marker.unlink(missing_ok=True)
# A freed GPU may already have claimed the next attempt. Remove only
# this monitor's entry; never publish a fresh DB row using an old lease.
with self._active_lock:
self._active.pop((job['id'], job['attempt_count']), None)
self._publish_scheduler('idle', reason=preempt_reason or error)
return True
def run_forever(self):
@ -404,7 +522,7 @@ class Worker:
try:
with self:
while not self.stop_requested:
if not self.run_once():
if not self.dispatch_once():
time.sleep(self.settings.poll_seconds)
finally:
for sig, handler in previous.items():

View File

@ -197,7 +197,8 @@ def status(settings):
running = verified_supervisor(record)
print(json.dumps({"state": "running" if running else "stale" if record else "stopped",
"pid": record.get("pid") if record else None,
"children": record.get("children", {}) if record else {}}))
"children": record.get("children", {}) if record else {},
"runner_marker_count": len(settings.active_markers())}))
return 0 if running else 3

View File

@ -379,6 +379,155 @@ class GpuGuardTests(unittest.TestCase):
self.xml = gpu_xml()
self.assertEqual(self.guard.run_once()["gpus"][0]["idle_since"], self.now)
def test_exited_pid_is_dropped_only_after_fresh_sample(self):
events = []
self.guard.emit_event = events.append
with patch.object(self.guard, "query", side_effect=[gpu_xml({0: [(42, "C", 100)]}), gpu_xml()]) as query:
status = self.guard.run_once()
self.assertEqual(query.call_count, 2)
self.assertIsNone(status["error"])
self.assertEqual(status["schema_version"], 1)
self.assertEqual(status["gpus"][0]["external_pids"], [])
self.assertEqual(status["gpus"][0]["idle_since"], self.now)
self.assertIn({"event": "process_inspection_failed", "count": 1,
"pid": 42, "stage": "identity", "category": "not_found"}, events)
def test_refresh_does_not_preserve_idle_credit_across_initial_sample_occupancy(self):
# Keep observer gaps <= 5 seconds so the sample-gap safeguard does not
# mask loss of the occupied first sample when the refresh is empty.
for sampled_at in (1000.0, 1005.0, 1010.0, 1015.0):
self.now = sampled_at
status = self.guard.run_once()
self.assertTrue(all(gpu["idle_since"] == 1000.0 for gpu in status["gpus"]))
self.process(50)
self.now = 1016.0
first = gpu_xml({0: [(42, "C", 100)], 1: [(50, "C", 100)]})
with patch.object(self.guard, "query", side_effect=[first, gpu_xml()]) as query:
status = self.guard.run_once()
self.assertEqual(query.call_count, 2)
self.assertIsNone(status["error"])
self.assertEqual(status["gpus"][0]["idle_since"], 1016.0)
self.assertEqual(status["gpus"][1]["idle_since"], 1016.0)
self.assertEqual(status["gpus"][2]["idle_since"], 1000.0)
def test_refresh_retains_new_external_pid_and_preempts_only_own(self):
self.process(50)
self.process(84, cid=OTHER_CID)
initial = gpu_xml({0: [(42, "C", 100), (50, "C", 100)]})
fresh = gpu_xml({0: [(50, "C", 100), (84, "C", 200)]})
with patch.object(self.guard, "query", side_effect=[initial, fresh]) as query:
status = self.guard.run_once()
self.assertEqual(query.call_count, 2)
self.assertIsNone(status["error"])
self.assertEqual(status["gpus"][0]["own_pids"], [50])
self.assertEqual(status["gpus"][0]["external_pids"], [84])
self.xml = fresh
self.now += 4
with patch.object(self.module, "signal_owned_process", return_value=True) as send:
self.guard.run_once()
self.assertEqual([call.args[0].pid for call in send.call_args_list], [50])
def test_missing_pid_refresh_is_bounded_even_with_another_missing_pid(self):
with patch.object(self.guard, "query", side_effect=[gpu_xml({0: [(42, "C", 100)]}),
gpu_xml({1: [(84, "C", 100)]})]) as query:
status = self.guard.run_once()
self.assertEqual(query.call_count, 2)
self.assertEqual(status["error"], "process_inspection_failed")
self.assertEqual(status["gpus"][1]["external_pids"], [84])
self.assertTrue(all(gpu["idle_since"] is None for gpu in status["gpus"]))
def test_missing_pid_still_in_refresh_fails_closed(self):
self.xml = gpu_xml({0: [(42, "C", 100)]})
with patch.object(self.guard, "query", return_value=self.xml) as query:
status = self.guard.run_once()
self.assertEqual(query.call_count, 2)
self.assertEqual(status["error"], "process_inspection_failed")
self.assertEqual(status["gpus"][0]["external_pids"], [42])
def test_live_missing_proc_file_permission_and_identity_failures_are_not_dropped(self):
self.process(42)
events = []
self.guard.emit_event = events.append
for failure in (FileNotFoundError("SECRET_COMMAND"), PermissionError("SECRET_COMMAND"),
self.module.GuardError("process_inspection_failed")):
with self.subTest(failure=type(failure).__name__), patch.object(self.module, "read_process_identity", side_effect=failure), patch.object(self.guard, "query", return_value=gpu_xml({0: [(42, "C", 100)]})) as query:
status = self.guard.run_once()
self.assertEqual(query.call_count, 1)
self.assertEqual(status["error"], "process_inspection_failed")
self.assertEqual(status["gpus"][0]["external_pids"], [42])
self.assertEqual({event["category"] for event in events if "pid" in event},
{"not_found", "permission_denied", "identity_invalid"})
self.assertNotIn("SECRET_COMMAND", json.dumps(events))
def test_permission_failure_stays_global_when_another_pid_disappears(self):
self.process(84, cid=OTHER_CID)
original = self.module.read_process_identity
def inspect(pid, root):
if pid == 84:
raise PermissionError("PRIVATE_ENV")
return original(pid, root)
with patch.object(self.module, "read_process_identity", side_effect=inspect), patch.object(self.guard, "query", side_effect=[gpu_xml({0: [(42, "C", 100), (84, "C", 200)]}), gpu_xml()]):
status = self.guard.run_once()
self.assertEqual(status["error"], "process_inspection_failed")
self.assertTrue(all(gpu["idle_since"] is None for gpu in status["gpus"]))
def test_disappearance_refresh_timeout_is_not_retried(self):
with patch.object(self.guard, "query", side_effect=[gpu_xml({0: [(42, "C", 100)]}),
self.module.GuardError("nvidia_query_timeout")]) as query:
status = self.guard.run_once()
self.assertEqual(query.call_count, 2)
self.assertEqual(status["error"], "nvidia_query_timeout")
self.assertEqual(status["gpus"], [])
def test_baseline_exit_during_executable_check_is_confirmed_by_refresh(self):
self.baseline()
events = []
self.guard.emit_event = events.append
def exited(_pid, _root):
directory = self.proc / "2880"
for entry in directory.iterdir():
entry.unlink()
directory.rmdir()
raise FileNotFoundError("PRIVATE_PATH")
with patch.object(self.module, "read_executable", side_effect=exited), patch.object(self.guard, "query", side_effect=[gpu_xml({0: [(2880, "G", 4)]}), gpu_xml()]) as query:
status = self.guard.run_once()
self.assertEqual(query.call_count, 2)
self.assertIsNone(status["error"])
self.assertIn({"event": "process_inspection_failed", "count": 1,
"pid": 2880, "stage": "baseline", "category": "not_found"}, events)
self.assertNotIn("PRIVATE_PATH", json.dumps(events))
def test_permission_failure_on_one_gpu_is_not_erased_by_same_pid_exit_on_another(self):
self.baseline()
calls = []
def inspect_executable(pid, root):
calls.append(pid)
if len(calls) == 1:
raise PermissionError("PRIVATE_ENV")
directory = self.proc / str(pid)
for entry in directory.iterdir():
entry.unlink()
directory.rmdir()
raise FileNotFoundError("PRIVATE_PATH")
with patch.object(self.module, "read_executable", side_effect=inspect_executable), patch.object(self.guard, "query", side_effect=[gpu_xml({0: [(2880, "G", 4)], 1: [(2880, "G", 4)]}), gpu_xml()]):
status = self.guard.run_once()
self.assertEqual(status["error"], "process_inspection_failed")
self.assertTrue(all(gpu["idle_since"] is None for gpu in status["gpus"]))
def test_reused_missing_pid_is_external_and_global_failure_until_next_tick(self):
calls = []
def query():
calls.append(1)
if len(calls) == 2:
self.process(42, start=9999)
return gpu_xml({0: [(42, "C", 100)]})
self.guard.query = query
status = self.guard.run_once()
self.assertEqual(len(calls), 2)
self.assertEqual(status["error"], "process_inspection_failed")
self.assertEqual(status["gpus"][0]["external_pids"], [42])
self.assertEqual(status["gpus"][0]["own_pids"], [])
def test_one_query_timeout_retries_once_without_rewriting_previous_snapshot(self):
self.guard.run_once()
previous = (self.policy / "status.json").read_bytes()

View File

@ -0,0 +1,279 @@
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime
import json
import sqlite3
import sys
import time
import pytest
from llm_services.store import Store, Settings
def test_distinct_gpu_claims_fifo_and_case_insensitive_lease(tmp_path):
store = Store(tmp_path / 'jobs.db')
jobs = [store.submit('image.generate', {}, {}) for _ in range(4)]
claims = [store.claim_next(gpu_uuid=f'GPU-{n}') for n in range(3)]
assert [j['id'] for j in claims] == [j['id'] for j in jobs[:3]]
assert store.claim_next(gpu_uuid='gpu-0') is None
assert store.get(jobs[3]['id'])['state'] == 'queued'
def test_concurrent_claims_unique_gpu_and_job(tmp_path):
store = Store(tmp_path / 'jobs.db')
for _ in range(20): store.submit('image.generate', {}, {})
with ThreadPoolExecutor(max_workers=12) as pool:
claims = list(pool.map(lambda n: store.claim_next(gpu_uuid=f'GPU-{n % 3}'), range(24)))
claims = [j for j in claims if j]
assert len(claims) == 3
assert len({j['id'] for j in claims}) == 3
assert len({j['gpu_uuid'].lower() for j in claims}) == 3
def test_eligible_global_fifo_across_modes_and_owners(tmp_path):
store = Store(tmp_path / 'jobs.db')
jobs = [store.submit('image.generate', {}, {}, scheduling={'execution_mode': mode,
'principal_id': owner, 'policy_version': 'night-v1'}) for mode, owner in
[('batch','z'), ('interactive','z'), ('interactive','a')]]
now = datetime.fromisoformat('2026-11-11T22:00:00+08:00').timestamp()
assert [store.claim_next(gpu_uuid=f'GPU-{n}', now=now)['id'] for n in range(3)] == [j['id'] for j in jobs]
def test_stale_attempt_cannot_finalize_requeue_or_set_runner(tmp_path):
store = Store(tmp_path / 'jobs.db')
j = store.submit('image.generate', {}, {})
store.claim_next(gpu_uuid='GPU-0')
store.requeue_preempted(j['id'], 'external', attempt_count=1)
store.claim_next(gpu_uuid='GPU-1')
for write in [lambda: store.finish(j['id'], 'failed', attempt_count=1),
lambda: store.requeue_preempted(j['id'], 'late', attempt_count=1),
lambda: store.set_runner(j['id'], 9, '1', 9, attempt_count=1)]:
with pytest.raises(RuntimeError): write()
assert store.get(j['id'])['state'] == 'running'
assert store.get(j['id'])['gpu_uuid'] == 'GPU-1'
def test_migration_keeps_jobs_and_blocks_old_singleton_ddl(tmp_path):
store = Store(tmp_path / 'jobs.db')
job = store.submit('image.generate', {}, {})
Store(store.path)
assert store.get(job['id'])['state'] == 'queued'
with sqlite3.connect(store.path) as db:
with pytest.raises(sqlite3.OperationalError):
db.execute("CREATE UNIQUE INDEX IF NOT EXISTS one_running_job ON jobs(state) WHERE state='running'")
def test_memory_working_set_reservations_and_shm(tmp_path):
from llm_services.resources import MemoryAdmission
cg = tmp_path / 'cg'; cg.mkdir()
(cg / 'memory.max').write_text(str(384 * 1024**3))
(cg / 'memory.current').write_text(str(250 * 1024**3))
(cg / 'memory.stat').write_text(f'inactive_file {180 * 1024**3}\n')
admission = MemoryAdmission(Settings(tmp_path/'app', tmp_path), cgroup=cg,
shm_usage=lambda: (0, 64 * 1024**3))
assert admission.check('image.generate', [88, 88]) is None
assert admission.check('image.generate', [88, 88, 88]) is not None
admission.shm_usage = lambda: (64 * 1024**3, 64 * 1024**3)
assert admission.check('audio.transcribe', []) is not None
@pytest.mark.skipif(not sys.platform.startswith('linux'), reason='Linux process groups')
def test_three_runners_overlap_fourth_waits_and_cancel_is_local(tmp_path):
from llm_services.worker import Worker
class Policy:
def describe(self): return {'eligible_gpus':[{'uuid':f'GPU-{n}', 'index':n} for n in range(3)]}
def should_yield(self, lease): return None
def environment(self, lease): return {'CUDA_VISIBLE_DEVICES':lease['uuid']}
class TestWorker(Worker):
def _command(self, request, result):
return [sys.executable, '-c', 'import time; time.sleep(30)']
settings = Settings(tmp_path/'app', tmp_path, poll_seconds=.02, terminate_grace_seconds=.1)
w = TestWorker(settings, gpu_policy=Policy())
w.memory_admission = type('Memory', (), {'check':lambda *args: None})()
jobs = [w.store.submit('image.generate', {}, {}) for _ in range(4)]
with w:
try:
w.dispatch_once()
assert [j['id'] for j in w.store.running()] == [j['id'] for j in jobs[:3]]
assert w.store.get(jobs[3]['id'])['state'] == 'queued'
w.store.cancel(jobs[1]['id'])
deadline = time.monotonic() + 5
while w.store.get(jobs[1]['id'])['state'] == 'running' and time.monotonic() < deadline:
time.sleep(.02)
w.dispatch_once()
assert {j['id'] for j in w.store.running()} == {jobs[n]['id'] for n in (0,2,3)}
status = json.loads((settings.state_dir/'gpu-scheduler.json').read_text())
assert status['schema_version'] == 2 and status['running_count'] == 3
finally:
w.shutdown()
assert not w.store.running()
assert not list(settings.runner_markers.glob('*.json'))
def test_memory_shortage_keeps_fifo_head_and_no_attempt(tmp_path):
from llm_services.worker import Worker
class Policy:
def describe(self): return {'eligible_gpus':[{'uuid':'GPU-0', 'index':0}]}
w = Worker(Settings(tmp_path/'app', tmp_path), gpu_policy=Policy())
w._lock_fd = -1
w.memory_admission = type('Memory', (), {'check':lambda *args: 'memory shortage'})()
jobs = [w.store.submit(kind, {}, {}) for kind in ('image.generate','audio.transcribe')]
w.dispatch_once()
assert all(w.store.get(j['id'])['attempt_count'] == 0 for j in jobs)
status = json.loads((w.settings.state_dir/'gpu-scheduler.json').read_text())
assert status['state'] == 'waiting' and status['reason'] == 'memory shortage'
@pytest.mark.skipif(not sys.platform.startswith('linux'), reason='Linux process groups')
def test_per_attempt_markers_prevent_unsafe_recovery(tmp_path):
from llm_services.worker import Worker, UnsafeRecovery
settings = Settings(tmp_path/'app', tmp_path)
w = Worker(settings, gpu_policy=None)
(settings.runner_markers/'first-1.json').write_text('{}')
(settings.runner_markers/'second-2.json').write_text('{}')
with pytest.raises(UnsafeRecovery):
with w: pass
assert len(settings.active_markers()) == 2
@pytest.mark.skipif(not sys.platform.startswith('linux'), reason='Linux process groups')
def test_external_user_preempts_only_leased_gpu(tmp_path):
from llm_services.worker import Worker
class Policy:
external = set()
def describe(self): return {'eligible_gpus':[{'uuid':f'GPU-{n}', 'index':n}
for n in range(3) if f'GPU-{n}' not in self.external]}
def should_yield(self, lease): return 'external user' if lease['uuid'] in self.external else None
def environment(self, lease): return {}
class TestWorker(Worker):
def _command(self, request, result):
return [sys.executable, '-c', 'import time; time.sleep(30)']
policy = Policy()
settings = Settings(tmp_path/'app', tmp_path, poll_seconds=.02, terminate_grace_seconds=.1)
w = TestWorker(settings, gpu_policy=policy)
w.memory_admission = type('Memory', (), {'check':lambda *args: None})()
jobs = [w.store.submit('image.generate', {}, {}) for _ in range(3)]
with w:
w.dispatch_once()
peers = {j['id']:j['runner_pid'] for j in w.store.running() if j['gpu_uuid'] != 'GPU-1'}
policy.external.add('GPU-1')
deadline = time.monotonic()+5
while w.store.get(jobs[1]['id'])['state'] == 'running' and time.monotonic()<deadline:
time.sleep(.02)
assert w.store.get(jobs[1]['id'])['state'] == 'queued'
assert w.store.get(jobs[1]['id'])['preemptions'] == 1
assert {j['id']:j['runner_pid'] for j in w.store.running()} == peers
w.dispatch_once()
assert w.store.get(jobs[1]['id'])['attempt_count'] == 1
assert not w.store.running()
def test_scheduler_heartbeat_refreshes_unchanged_state(tmp_path, monkeypatch):
from llm_services.worker import Worker
w = Worker(Settings(tmp_path/'app', tmp_path), gpu_policy=None)
w._publish_scheduler('idle')
status_path = w.settings.state_dir/'gpu-scheduler.json'
first = json.loads(status_path.read_text())['updated_at']
w._scheduler_written_at -= 2
w._publish_scheduler('idle')
assert json.loads(status_path.read_text())['updated_at'] > first
@pytest.mark.parametrize('values', [{'max_gpu_jobs':5}, {'max_gpu_jobs':True},
{'cpu_threads_per_job':0}, {'memory_headroom_gib':float('nan')}, {'memory_estimates_gib':{}}])
def test_settings_reject_unsafe_limits(tmp_path, values):
with pytest.raises(ValueError): Settings(tmp_path/'app', tmp_path, **values)
def test_unfenced_legacy_write_cannot_touch_a_retried_execution(tmp_path):
store = Store(tmp_path/'jobs.db')
job = store.submit('image.generate', {}, {})
store.claim_next(gpu_uuid='GPU-0')
store.requeue_preempted(job['id'], 'external', attempt_count=1)
store.claim_next(gpu_uuid='GPU-0')
for operation in (lambda: store.set_runner(job['id'], 1, '1', 1),
lambda: store.requeue_preempted(job['id'], 'unfenced'),
lambda: store.finish(job['id'], 'failed')):
with pytest.raises(RuntimeError): operation()
assert store.get(job['id'])['state'] == 'running'
def test_old_monitor_status_cannot_overwrite_reclaimed_attempt(tmp_path, monkeypatch):
from llm_services.worker import Worker
w = Worker(Settings(tmp_path/'app', tmp_path), gpu_policy=None)
w._lock_fd = -1
w.store.submit('image.generate', {}, {})
job = w.store.claim_next(gpu_uuid='GPU-0')
monkeypatch.setattr(w, '_yield_reason', lambda lease: 'external')
original = w.store.requeue_preempted
def reclaim(*args, **kwargs):
result = original(*args, **kwargs)
next_job = w.store.claim_next(gpu_uuid='GPU-1')
w._publish_scheduler('running', job=next_job, lease={'uuid':'GPU-1','index':1})
return result
monkeypatch.setattr(w.store, 'requeue_preempted', reclaim)
w._execute(job, {'uuid':'GPU-0','index':0})
status = json.loads((w.settings.state_dir/'gpu-scheduler.json').read_text())
assert len(status['active_jobs']) == 1
assert status['active_jobs'][0]['attempt_count'] == 2
assert status['active_jobs'][0]['gpu_index'] == 1
def test_memory_diagnostics_include_cgroup_events_and_shm(tmp_path):
from llm_services.resources import MemoryAdmission
for name, value in {'memory.current':str(10*1024**3), 'memory.max':str(384*1024**3),
'memory.stat':'inactive_file 0\n', 'memory.events':'oom 2\noom_kill 1\n'}.items():
(tmp_path/name).write_text(value)
memory = MemoryAdmission(Settings(tmp_path/'app',tmp_path), cgroup=tmp_path,
shm_usage=lambda:(123,1024**3))
assert memory.check('image.generate',[]) is None
assert memory.last_sample['memory_events']['oom_kill'] == 1
assert memory.last_sample['shm_used_bytes'] == 123
assert memory.last_sample['memory_max_bytes'] == 384*1024**3
def test_memory_rechecks_growth_outside_runner_reservations(tmp_path):
from llm_services.resources import MemoryAdmission
gib = 1024**3
(tmp_path/'memory.max').write_text(str(384*gib))
(tmp_path/'memory.current').write_text(str(20*gib))
(tmp_path/'memory.stat').write_text('inactive_file 0\n')
memory = MemoryAdmission(Settings(tmp_path/'app',tmp_path), cgroup=tmp_path,
shm_usage=lambda:(0,64*gib))
assert memory.check('image.generate', []) is None
# Two models currently use only 20 GiB each, while an unrelated local
# workload grows to 220 GiB. Their remaining reserved allocations still
# need capacity: the cgroup's observed 260 GiB cannot stand in for them.
(tmp_path/'memory.current').write_text(str(260*gib))
assert memory.check('image.generate', [88,88]) is not None
def test_conservative_memory_still_admits_three_expected_wan_jobs(tmp_path):
from llm_services.resources import MemoryAdmission
gib = 1024**3
(tmp_path/'memory.max').write_text(str(384*gib))
(tmp_path/'memory.stat').write_text('inactive_file 0\n')
memory = MemoryAdmission(Settings(tmp_path/'app',tmp_path), cgroup=tmp_path,
shm_usage=lambda:(0,64*gib))
for running in range(3):
(tmp_path/'memory.current').write_text(str((1+37*running)*gib))
assert memory.check('video.generate', [64]*running) is None
def test_scheduler_preserves_blocked_card_alongside_running_peer(tmp_path):
from llm_services.worker import Worker
w = Worker(Settings(tmp_path/'app', tmp_path), gpu_policy=None)
for _ in range(2): w.store.submit('image.generate', {}, {})
blocked = w.store.claim_next(gpu_uuid='GPU-0')
peer = w.store.claim_next(gpu_uuid='GPU-1')
peer['stage'] = 'executing'
w._publish_scheduler('running', job=peer, lease={'uuid':'GPU-1','index':1})
w._publish_scheduler('blocked', job=blocked, lease={'uuid':'GPU-0','index':0},
reason='Cannot prove complete runner exit; operator recovery required')
status = json.loads((w.settings.state_dir/'gpu-scheduler.json').read_text())
entries = {entry['gpu_index']:entry for entry in status['active_jobs']}
assert status['state'] == 'blocked'
assert entries[0]['state'] == 'blocked'
assert 'operator recovery' in entries[0]['reason']
assert entries[1]['state'] == 'running'
def test_scheduler_marks_unspawned_claim_launching(tmp_path):
from llm_services.worker import Worker
w = Worker(Settings(tmp_path/'app', tmp_path), gpu_policy=None)
w.store.submit('image.generate', {}, {})
job = w.store.claim_next(gpu_uuid='GPU-0')
w._publish_scheduler('running', job=job, lease={'uuid':'GPU-0','index':0})
status = json.loads((w.settings.state_dir/'gpu-scheduler.json').read_text())
assert status['active_jobs'][0]['state'] == 'launching'

View File

@ -0,0 +1,25 @@
import os
import sys
from types import SimpleNamespace
from unittest.mock import patch
import pytest
from llm_services import adapters
def test_stage_bootstrap_preserves_per_job_thread_limit(tmp_path):
with patch.dict(os.environ, {'OMP_NUM_THREADS': '2'}), patch.object(adapters, 'rpc_base_path', return_value=tmp_path/'rpc'):
env = adapters.budgeted_child_environment(tmp_path)
assert env['OMP_NUM_THREADS'] == '2'
def test_gpu_budget_bootstrap_uses_per_job_torch_thread_limit():
calls = []
cuda = SimpleNamespace(is_available=lambda: True, device_count=lambda: 1,
get_device_properties=lambda _: SimpleNamespace(total_memory=80*1024**3),
set_per_process_memory_fraction=lambda *args, **kwargs: None)
torch = SimpleNamespace(cuda=cuda, set_num_threads=calls.append)
with patch.dict(os.environ, {'OMP_NUM_THREADS': '2'}), patch.dict(sys.modules, {'torch': torch}):
adapters.configure_gpu_budget()
assert calls == [2]

View File

@ -68,6 +68,7 @@ class QueueTests(QueueFixture, unittest.TestCase):
self.store.finish(job["id"], "succeeded", result={"outputs": ["historic"]})
# Recreate the pre-policy table layout, leaving its completed row intact.
with closing(sqlite3.connect(self.settings.db_path)) as connection:
connection.execute("DROP INDEX one_running_gpu")
for column in ("attempt_count", "preemptions", "gpu_uuid", "last_preempted_at", "last_preempted_reason"):
connection.execute("ALTER TABLE jobs DROP COLUMN " + column)
from llm_services.store import Store
@ -336,7 +337,7 @@ pathlib.Path(a.result).write_text(json.dumps({"outputs":[str(out)]}))
pid = int((self.settings.outputs_dir / job["id"] / "child.pid").read_text())
identity = process_identity(pid)
self.assertTrue(identity is None or identity["state"] == "Z")
self.assertFalse(self.settings.runner_marker.exists())
self.assertFalse(self.settings.active_markers())
self.assertTrue(worker.run_once())
completed = self.store.get(job["id"])
self.assertEqual((completed["state"], completed["attempt_count"]), ("succeeded", 2))
@ -390,7 +391,7 @@ pathlib.Path(a.result).write_text(json.dumps({"outputs":[str(out)]}))
queued = self.store.get(job["id"])
self.assertEqual((queued["state"], queued["preemptions"], queued["attempt_count"]),
("queued", 1, 1))
self.assertFalse(self.settings.runner_marker.exists())
self.assertFalse(self.settings.active_markers())
self.assertFalse(worker.run_once())
policy.busy.unlink()
self.assertTrue(worker.run_once())
@ -458,7 +459,7 @@ pathlib.Path(a.result).write_text(json.dumps({"outputs":[str(out)]}))
self.assertEqual(self.store.get(job["id"])["state"], "running")
self.assertEqual(self.store.get(job["id"])["preemptions"], 0)
self.assertIsNotNone(process_identity(pid))
self.assertTrue(self.settings.runner_marker.exists())
self.assertTrue(self.settings.active_markers())
with self.assertRaises(UnsafeRecovery):
with self.make_worker(policy):
pass

View File

@ -86,13 +86,13 @@ def test_clock_rollback_cannot_reopen_closed_window_after_restart(tmp_path):
assert store.claim_next(now=epoch("2026-11-11T21:00:00+08:00"))['id'] == job['id']
def test_interactive_claims_do_not_reset_batch_round_robin(tmp_path):
def test_global_fifo_replaces_mode_and_batch_round_robin(tmp_path):
store = Store(tmp_path / 'jobs.sqlite3')
now=epoch('2026-11-11T01:00:00+08:00')
for index in range(8):
store.submit('image.generate', {'prompt':str(index)}, {}, scheduling=policy('interactive'))
a=store.submit('image.generate', {'prompt':'a1'}, {}, scheduling={**policy('batch'),'batch_id':'a'})
store.submit('image.generate', {'prompt':'a2'}, {}, scheduling={**policy('batch'),'batch_id':'a'})
a2=store.submit('image.generate', {'prompt':'a2'}, {}, scheduling={**policy('batch'),'batch_id':'a'})
b=store.submit('image.generate', {'prompt':'b1'}, {}, scheduling={**policy('batch'),'batch_id':'b'})
selected=[]
for _ in range(10):
@ -100,7 +100,7 @@ def test_interactive_claims_do_not_reset_batch_round_robin(tmp_path):
current=store.claim_next(now=now)
if current['execution_mode']=='batch':selected.append(current['id'])
store.finish(current['id'],'succeeded',result={})
assert selected==[a['id'],b['id']]
assert selected==[a['id'],a2['id']]
@pytest.mark.parametrize('key,value',[('clock_max_seen','NaN'),('clock_max_seen','not-a-clock'),('closed_window_through','broken')])