diff --git a/README.md b/README.md index ce805d4..3244f4e 100644 --- a/README.md +++ b/README.md @@ -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仍只控制其已支持的时段/工作流字段。 diff --git a/backend/app/batches.py b/backend/app/batches.py index e136e93..a33d015 100644 --- a/backend/app/batches.py +++ b/backend/app/batches.py @@ -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'))) diff --git a/backend/app/coordinator.py b/backend/app/coordinator.py index e445ede..94afb2f 100644 --- a/backend/app/coordinator.py +++ b/backend/app/coordinator.py @@ -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") diff --git a/backend/app/gpu_summary.py b/backend/app/gpu_summary.py new file mode 100644 index 0000000..c296d25 --- /dev/null +++ b/backend/app/gpu_summary.py @@ -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()} diff --git a/backend/app/providers.py b/backend/app/providers.py index 43a15ac..2052bba 100644 --- a/backend/app/providers.py +++ b/backend/app/providers.py @@ -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 diff --git a/backend/app/workflow_engine.py b/backend/app/workflow_engine.py index 7b7cd56..2cfd9a4 100644 --- a/backend/app/workflow_engine.py +++ b/backend/app/workflow_engine.py @@ -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): diff --git a/backend/tests/test_jobs.py b/backend/tests/test_jobs.py index ec92675..13c9ab5 100644 --- a/backend/tests/test_jobs.py +++ b/backend/tests/test_jobs.py @@ -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" diff --git a/backend/tests/test_parallel_feeder.py b/backend/tests/test_parallel_feeder.py new file mode 100644 index 0000000..44fbcdc --- /dev/null +++ b/backend/tests/test_parallel_feeder.py @@ -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) diff --git a/backend/tests/test_parallel_resource_status.py b/backend/tests/test_parallel_resource_status.py new file mode 100644 index 0000000..7e6f329 --- /dev/null +++ b/backend/tests/test_parallel_resource_status.py @@ -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 diff --git a/backend/tests/test_record_deletion.py b/backend/tests/test_record_deletion.py index 61efde1..ad67795 100644 --- a/backend/tests/test_record_deletion.py +++ b/backend/tests/test_record_deletion.py @@ -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() diff --git a/backend/tests/test_workflow_review_repairs.py b/backend/tests/test_workflow_review_repairs.py index 7bd5716..1c2a9db 100644 --- a/backend/tests/test_workflow_review_repairs.py +++ b/backend/tests/test_workflow_review_repairs.py @@ -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 diff --git a/backend/tests/test_workflows_v2.py b/backend/tests/test_workflows_v2.py index dc3a2fa..fe344da 100644 --- a/backend/tests/test_workflows_v2.py +++ b/backend/tests/test_workflows_v2.py @@ -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): diff --git a/docs/superpowers/plans/2026-11-11-multi-gpu-fifo.md b/docs/superpowers/plans/2026-11-11-multi-gpu-fifo.md new file mode 100644 index 0000000..5666b6b --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-multi-gpu-fifo.md @@ -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. diff --git a/docs/superpowers/plans/2026-11-11-multi-gpu-progress.md b/docs/superpowers/plans/2026-11-11-multi-gpu-progress.md new file mode 100644 index 0000000..29a768b --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-multi-gpu-progress.md @@ -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. diff --git a/docs/superpowers/specs/2026-11-11-multi-gpu-fifo-design.md b/docs/superpowers/specs/2026-11-11-multi-gpu-fifo-design.md new file mode 100644 index 0000000..20ac5f0 --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-multi-gpu-fifo-design.md @@ -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验证,再上线真实三卡验收。旧版本只允许在没有活动执行时回退;数据库中的任务和结果不得回退成重复执行的旧状态。仓库当前有其他功能的未提交改动,实施须隔离修改并保留它们,部署前协调共同修改的应用文件。 diff --git a/docs/操作手册_20261111.md b/docs/操作手册_20261111.md index bc6e860..7c75ef9 100644 --- a/docs/操作手册_20261111.md +++ b/docs/操作手册_20261111.md @@ -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. 批量与开发/生产配置 diff --git a/frontend/public/help/manual.html b/frontend/public/help/manual.html index 217871d..6a97216 100644 --- a/frontend/public/help/manual.html +++ b/frontend/public/help/manual.html @@ -1,4 +1,4 @@ -操作手册 · CMVR Visual
CMVR Visual · 使用帮助

CMVR Visual 操作手册

适用版本:2026-11-11的可配置时段、多镜头、私有内容删除与共享素材版本。模型在192.168.28.10运行,项目在E:\workspace\hybrid\cmvr-visual。本手册描述已实现的功能;原始技术方案中的远期能力不能当作当前按钮功能。

1. 登录与基本流程

现有访问入口为 http://127.0.0.1:8000 ,依赖本机至服务器的SSH隧道。服务器网页端口只监听127.0.0.1:18193。网页打不开时先检查隧道;不能把这个地址直接发给另一台电脑访问,也不要直接开放数据库或模型端口。

使用分配的账号登录。默认管理员名为admin,初始密码以私有部署配置为准;到“账户”修改密码。新密码至少12位,修改后需要重新登录。服务器重启不会把已有密码重置。

一次创作的通用流程:填写提示词或选择素材 → 提交任务 → 到“任务”查看排队/运行 → 到“素材”预览、下载或进入下一步处理。图像、视频、声音、字幕属于不同素材,需要明确选择和关联。

网页负责提交和查看,服务器负责持久执行。关闭网页、切换页面、断开HTTP/SSE不会取消任务,也不会停止共享Qwen。网络异常时先同步或恢复原提交,不要反复点击生成。

2. 功能入口

入口用途输入与输出
创作:图片Qwen-Image文生图提示词、尺寸、种子等 → 图片
创作:视频Wan单镜头文生/图生视频提示词、可选参考首帧 → 约5秒以内无声片段,可选增强
创作:条件样本SDXL+Canny ControlNet参考图片、提示词、控制强度 → 合成图及Canny控制图
工作流多镜头故事自动逐镜生成并合成每镜头提示词/参考图/选用时长 → 一部多镜头影片
声音中文配音、Whisper转写文本 → WAV;音频/有声视频 → 转写结果
推演复用共享Qwen做文本推演问题 → 文本解答
理解图片理解、视频抽帧分析素材 → 场景、主体、OCR、标签等
成片编辑已有视频素材排序、裁切、单音轨、人工字幕 → MP4
批量混合提交任务或已保存工作流任务清单 → 持久批次,运行时段服从配置
素材 / 任务 / 账户管理结果、进度、用户和令牌见下文

3. 图片、短视频和条件样本

图片

  1. 进入“创作”,切换到图片。
  2. 描述主体、场景、构图、光线和画风;首次测试先生成一张。
  3. 在参数面板选择尺寸、步数和种子。相同种子只能提高可复现性,不保证不同提示词生成同一角色。
  4. 点击生成,在“任务”查看结果。完成后到“素材”预览/下载,或作为工作流的参考图片使用。

单镜头视频

  1. 切换视频模式,写一个镜头中的主体动作与镜头运动。
  2. 可选择参考图片作为首帧;文生视频可不选图。
  3. 根据当前能力选择参数和1080p画质增强。当前单次接口最多121帧、24fps,约5秒;增加提示词长度不会自动延长单镜头。
  4. 需要更长故事时进入“工作流”,增加镜头;已有视频可到“成片”拼接。

2026-11-11已完成一次原生单镜头15秒验证:Wan2.2-TI2V-5B在1280×704、50步、24fps下一次生成361帧(15.041667秒),执行约817秒,完整解码通过;另提供只去掉末帧的360帧、精确15秒版本。帆船测试画面连续,但位移较小,不能据此保证复杂变形与强动作的效果。这是模型容量验证,网页仍开放121帧、约5秒源片段,尚未把单镜头15秒接入普通提交入口;多镜头合成时长也不等同于单镜头长度。详见同目录《存储隔离共享与15秒验证_20261111.md》。

条件样本

选择参考图,填写缺陷或目标画面描述,调整Canny阈值和控制强度后生成。返回的控制图是边缘约束,不是缺陷真值mask;不能直接当作精确缺陷标注训练集。

4. 多镜头工作流

新建、编辑和保存

  1. 打开“工作流”,点击“新建”,填写故事名称。
  2. 每个镜头填写提示词,选择种子和可选参考图片。
  3. 使用“添加镜头”增加段落;前移、后移改变顺序;删除不需要的镜头。镜头编号随当前顺序更新。
  4. 每镜头选择1–5秒的选用时长。模型当前仍按121帧生成短片段,合成只取选用帧数;缩短选用时长主要影响剪辑,不承诺同比减少GPU推理耗时。
  5. 选择横屏1920×1080或竖屏1080×1920。“完整画面”保留内容并留边;“填满画面”会裁切超出画布的部分。
  6. 点击“保存草稿”。刷新后可从下拉框重新打开服务器草稿。本地编辑与服务器草稿分开,导入示例不会自动保存或运行。

总时长由镜头选用时长相加,24fps下总秒数=总帧数÷24。例如4个5秒镜头为20秒,20个为100秒;不再固定为15秒。

默认每工作流允许最多120镜头,可由管理员配置到1–1000。这个数量是可调整的资源保护上限,不是模型的上下文长度。磁盘、输出大小、任务数量、执行超时等限制仍有效;不承诺无限长或无限显存。

音轨和字幕

工作流当前支持一条外部音轨。先在“声音”生成配音,或在素材库上传WAV/MP3;返回工作流后点击“选择音频素材”。

人工字幕的开始/结束是整片帧号,区间为[开始帧,结束帧)。例如第5–10秒填120至240;20镜头100秒影片的范围为0至2400。字幕随时间显示,不等于自动转写对齐。更换镜头顺序或时长后要复核字幕和音频时间。

运行、复用与恢复

点击“保存并运行”。服务器冻结本次参数和修订,逐镜串行生成,然后合成。每个镜头完成后会归档;运行期间继续编辑草稿不会改变已开始的运行。

JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本地新草稿;含素材编号的文件只能引用当前账号有权访问的素材。文件中不能写本机/服务器任意路径。

5. 声音、推演与理解

“声音”选择“配音生成”,输入不超过2000字,选择zf_xiaobei或zm_yunxi,速度0.5–2,点击“生成配音”。先试听,记录实际秒数,再设计视频时间。较长文本分段生成后,当前没有自动拼接多条音频按钮,可使用一条完整配音或外部音频工具合成后上传。

转写时选择音频或有声视频,Whisper输出文本及分块时间。时间戳不是逐词精准对齐;人工字幕仍需检查。推演可用于文案与镜头规划,但没有自动把回答变成工作流的功能,也不保证专业数学结论正确。

“理解”选择图片或视频,视频按配置均匀抽帧后调用视觉服务。只代表抽到画面的观察,不代表完整镜头切分或对全片每一帧的分析。

6. 成片、素材与任务管理

“成片”适合已经有视频片段的情况:添加片段 → 拖动或前移/后移 → 调整每段入点/出点 → 选择单一外部音轨、添加按秒人工字幕 → 导出成片。当前采用直切拼接,不是带转场和多轨混音的完整剪辑软件。原片段的裁剪范围必须在真实媒体范围内。

我的素材与共享素材库

普通账号和admin在“我的素材”、任务、工作流和批量记录中都只看到自己的私有内容;管理员的用户管理权限不会开放其他账号的私有内容。登录用户显式切换到“共享素材库”后,才能浏览其他用户主动发布的共享素材。

“我的素材”可上传、预览、下载、收藏,按类型、来源、标签、关键词查找,也可修改名称和标签。“共享库导入”来源用于查找从共享库取得的个人副本。

  1. 分享时,在自己的素材卡片或预览中点击“发布到共享库”,阅读并确认发布范围。系统复制原件和当前名称、标签等信息,生成一份独立的共享副本;所有已登录用户均可查看、下载和导入。
  2. 在“共享素材库”预览的内容是只读共享副本。点击“导入我的素材库”后,会创建属于当前账号的独立私有副本,可再编辑、删除或用于创作。创作中的素材选择器也可切到“共享素材”,选择后先导入,再将个人副本用于当前输入。
  3. 发布者可通过“我发布的”筛选并打开预览,点击“撤回共享”。撤回后其他用户无法继续查看或导入该发布,已经导入的个人副本仍然保留。删除私有原件也不会删除已发布的共享副本或他人的导入副本;要停止共享,需要单独撤回。

共享发布需要实际复制文件,占用发布者的磁盘额度;每次导入的独立副本占用导入者的磁盘额度。发布后的共享副本不会随原件修改自动更新。

删除素材和记录

自己的素材卡片/预览、任务卡片/详情、工作流草稿、运行卡片和批量记录均提供删除入口。删除记录属于软归档:成功后从日常列表和详情中消失,后台保留必要审计记录,不提供网页撤销恢复。

素材删除和共享撤回不会立即释放磁盘或额度。物理垃圾回收(GC)默认只做dry-run盘点;默认保留期为14天,超过保留期后仍需运维显式开启维护并执行物理清理(purge),再次检查引用后才可能删除文件。仅真正清理掉的文件释放相应占用,不能把“删除成功”当作即时腾出磁盘。

“任务”可查看叶任务和工作流进度、队列原因、历史执行和错误。新GPU推理全局仅一个;配音/媒体CPU和Qwen HTTP各有独立单槽。llmuser可选择四张GPU的空闲资源,外部用户占卡时优先让行并重排本应用作业,等待排队本身不是故障。

7. 批量与开发/生产配置

“批量”可以每行一个提示词生成清单,也可加入已经保存的工作流;提交前先“校验与预览”。需要参考素材的类型须补全本账号素材编号。一个批次最多100项,既有创建频率和账号额度继续生效。暂停批次同样只关闭后续准入。

权威配置位于容器内:

/workspace/projects/llm-services/config/runtime-policy.json

服务器宿主机对应:

/data/llmusers/llmuser/workspace/projects/llm-services/config/runtime-policy.json

开发模式:

{"schema_version":1,"batch_window_enabled":false,"workflow_max_shots":120}

正式环境启用时段限制:

{"schema_version":1,"batch_window_enabled":true,"workflow_max_shots":120}

API与GPU worker热读取同一个文件,不需要重启模型或共享Qwen。建议用同目录临时文件写完后原子替换,避免编辑中的半个JSON短暂触发保护。true/false是JSON布尔,不能加引号;不要在任务JSON或网页上添加绕过字段。

在网页右上角“创作服务状态”刷新检查生效状态。开发全天与数据库运行模式、公网发布是不同配置;关闭夜间限制不会开放互联网。

若通过SFTP维护配置,可从本机执行以下操作(按提示输入llmuser密码,不把密码写进命令):

sftp llmuser@192.168.28.10
+操作手册 · CMVR Visual
CMVR Visual · 使用帮助

CMVR Visual 操作手册

适用版本:2026-11-11的可配置时段、多镜头、私有内容删除与共享素材版本。模型在192.168.28.10运行,项目在E:\workspace\hybrid\cmvr-visual。本手册描述已实现的功能;原始技术方案中的远期能力不能当作当前按钮功能。

1. 登录与基本流程

现有访问入口为 http://127.0.0.1:8000 ,依赖本机至服务器的SSH隧道。服务器网页端口只监听127.0.0.1:18193。网页打不开时先检查隧道;不能把这个地址直接发给另一台电脑访问,也不要直接开放数据库或模型端口。

使用分配的账号登录。默认管理员名为admin,初始密码以私有部署配置为准;到“账户”修改密码。新密码至少12位,修改后需要重新登录。服务器重启不会把已有密码重置。

一次创作的通用流程:填写提示词或选择素材 → 提交任务 → 到“任务”查看排队/运行 → 到“素材”预览、下载或进入下一步处理。图像、视频、声音、字幕属于不同素材,需要明确选择和关联。

网页负责提交和查看,服务器负责持久执行。关闭网页、切换页面、断开HTTP/SSE不会取消任务,也不会停止共享Qwen。网络异常时先同步或恢复原提交,不要反复点击生成。

2. 功能入口

入口用途输入与输出
创作:图片Qwen-Image文生图提示词、尺寸、种子等 → 图片
创作:视频Wan单镜头文生/图生视频提示词、可选参考首帧 → 约5秒以内无声片段,可选增强
创作:条件样本SDXL+Canny ControlNet参考图片、提示词、控制强度 → 合成图及Canny控制图
工作流多镜头故事自动逐镜生成并合成每镜头提示词/参考图/选用时长 → 一部多镜头影片
声音中文配音、Whisper转写文本 → WAV;音频/有声视频 → 转写结果
推演复用共享Qwen做文本推演问题 → 文本解答
理解图片理解、视频抽帧分析素材 → 场景、主体、OCR、标签等
成片编辑已有视频素材排序、裁切、单音轨、人工字幕 → MP4
批量混合提交任务或已保存工作流任务清单 → 持久批次,运行时段服从配置
素材 / 任务 / 账户管理结果、进度、用户和令牌见下文

3. 图片、短视频和条件样本

图片

  1. 进入“创作”,切换到图片。
  2. 描述主体、场景、构图、光线和画风;首次测试先生成一张。
  3. 在参数面板选择尺寸、步数和种子。相同种子只能提高可复现性,不保证不同提示词生成同一角色。
  4. 点击生成,在“任务”查看结果。完成后到“素材”预览/下载,或作为工作流的参考图片使用。

单镜头视频

  1. 切换视频模式,写一个镜头中的主体动作与镜头运动。
  2. 可选择参考图片作为首帧;文生视频可不选图。
  3. 根据当前能力选择参数和1080p画质增强。当前单次接口最多121帧、24fps,约5秒;增加提示词长度不会自动延长单镜头。
  4. 需要更长故事时进入“工作流”,增加镜头;已有视频可到“成片”拼接。

2026-11-11已完成一次原生单镜头15秒验证:Wan2.2-TI2V-5B在1280×704、50步、24fps下一次生成361帧(15.041667秒),执行约817秒,完整解码通过;另提供只去掉末帧的360帧、精确15秒版本。帆船测试画面连续,但位移较小,不能据此保证复杂变形与强动作的效果。这是模型容量验证,网页仍开放121帧、约5秒源片段,尚未把单镜头15秒接入普通提交入口;多镜头合成时长也不等同于单镜头长度。详见同目录《存储隔离共享与15秒验证_20261111.md》。

条件样本

选择参考图,填写缺陷或目标画面描述,调整Canny阈值和控制强度后生成。返回的控制图是边缘约束,不是缺陷真值mask;不能直接当作精确缺陷标注训练集。

4. 多镜头工作流

新建、编辑和保存

  1. 打开“工作流”,点击“新建”,填写故事名称。
  2. 每个镜头填写提示词,选择种子和可选参考图片。
  3. 使用“添加镜头”增加段落;前移、后移改变顺序;删除不需要的镜头。镜头编号随当前顺序更新。
  4. 每镜头选择1–5秒的选用时长。模型当前仍按121帧生成短片段,合成只取选用帧数;缩短选用时长主要影响剪辑,不承诺同比减少GPU推理耗时。
  5. 选择横屏1920×1080或竖屏1080×1920。“完整画面”保留内容并留边;“填满画面”会裁切超出画布的部分。
  6. 点击“保存草稿”。刷新后可从下拉框重新打开服务器草稿。本地编辑与服务器草稿分开,导入示例不会自动保存或运行。

总时长由镜头选用时长相加,24fps下总秒数=总帧数÷24。例如4个5秒镜头为20秒,20个为100秒;不再固定为15秒。

默认每工作流允许最多120镜头,可由管理员配置到1–1000。这个数量是可调整的资源保护上限,不是模型的上下文长度。磁盘、输出大小、任务数量、执行超时等限制仍有效;不承诺无限长或无限显存。

音轨和字幕

工作流当前支持一条外部音轨。先在“声音”生成配音,或在素材库上传WAV/MP3;返回工作流后点击“选择音频素材”。

  • 源入点/出点单位是毫秒,表示取音频的哪一段。
  • 偏移单位是帧,表示从成片的哪一帧开始播放。24帧=1秒。
  • 选段长度加偏移必须放得进成片,源出点不能超过音频真实时长。过长不会被悄悄截断;应增加镜头、缩短旁白或重新配音。
  • 旁白比成片短时,尾部补静音。当前不提供多音轨混音、自动配乐或自动对齐旁白。

人工字幕的开始/结束是整片帧号,区间为[开始帧,结束帧)。例如第5–10秒填120至240;20镜头100秒影片的范围为0至2400。字幕随时间显示,不等于自动转写对齐。更换镜头顺序或时长后要复核字幕和音频时间。

运行、复用与恢复

点击“保存并运行”。服务器冻结本次参数和修订,独立镜头按就绪顺序分配到空闲GPU并行生成,全部完成后再按镜头顺序合成。每个镜头完成后会归档;运行期间继续编辑草稿不会改变已开始的运行。

  • “暂停后续阶段”:当前阶段完成,下一阶段暂停;“继续”恢复后续准入。
  • “取消”:取消本次后续工作,不能靠继续把已取消运行恢复。
  • “重试此阶段”:仅用于允许安全重试的失败步骤;其他成功镜头保留。
  • 修改草稿后再次运行,可在复用下拉框选择旧Run。只有生成输入一致、产物仍存在且校验通过的成功镜头可复用。提示词、参考图、种子、画幅变更会使对应镜头重新生成;单纯选用时长变更可复用原始生成片段再剪辑。
  • “同步”重新读取后台状态。结果未知/需人工确认表示远端执行结果未确认,不应靠反复提交规避。

JSON导入导出用于保存和批量编辑分镜。导入新模板会建立本地新草稿;含素材编号的文件只能引用当前账号有权访问的素材。文件中不能写本机/服务器任意路径。

5. 声音、推演与理解

“声音”选择“配音生成”,输入不超过2000字,选择zf_xiaobei或zm_yunxi,速度0.5–2,点击“生成配音”。先试听,记录实际秒数,再设计视频时间。较长文本分段生成后,当前没有自动拼接多条音频按钮,可使用一条完整配音或外部音频工具合成后上传。

转写时选择音频或有声视频,Whisper输出文本及分块时间。时间戳不是逐词精准对齐;人工字幕仍需检查。推演可用于文案与镜头规划,但没有自动把回答变成工作流的功能,也不保证专业数学结论正确。

“理解”选择图片或视频,视频按配置均匀抽帧后调用视觉服务。只代表抽到画面的观察,不代表完整镜头切分或对全片每一帧的分析。

6. 成片、素材与任务管理

“成片”适合已经有视频片段的情况:添加片段 → 拖动或前移/后移 → 调整每段入点/出点 → 选择单一外部音轨、添加按秒人工字幕 → 导出成片。当前采用直切拼接,不是带转场和多轨混音的完整剪辑软件。原片段的裁剪范围必须在真实媒体范围内。

我的素材与共享素材库

普通账号和admin在“我的素材”、任务、工作流和批量记录中都只看到自己的私有内容;管理员的用户管理权限不会开放其他账号的私有内容。登录用户显式切换到“共享素材库”后,才能浏览其他用户主动发布的共享素材。

“我的素材”可上传、预览、下载、收藏,按类型、来源、标签、关键词查找,也可修改名称和标签。“共享库导入”来源用于查找从共享库取得的个人副本。

  1. 分享时,在自己的素材卡片或预览中点击“发布到共享库”,阅读并确认发布范围。系统复制原件和当前名称、标签等信息,生成一份独立的共享副本;所有已登录用户均可查看、下载和导入。
  2. 在“共享素材库”预览的内容是只读共享副本。点击“导入我的素材库”后,会创建属于当前账号的独立私有副本,可再编辑、删除或用于创作。创作中的素材选择器也可切到“共享素材”,选择后先导入,再将个人副本用于当前输入。
  3. 发布者可通过“我发布的”筛选并打开预览,点击“撤回共享”。撤回后其他用户无法继续查看或导入该发布,已经导入的个人副本仍然保留。删除私有原件也不会删除已发布的共享副本或他人的导入副本;要停止共享,需要单独撤回。

共享发布需要实际复制文件,占用发布者的磁盘额度;每次导入的独立副本占用导入者的磁盘额度。发布后的共享副本不会随原件修改自动更新。

删除素材和记录

自己的素材卡片/预览、任务卡片/详情、工作流草稿、运行卡片和批量记录均提供删除入口。删除记录属于软归档:成功后从日常列表和详情中消失,后台保留必要审计记录,不提供网页撤销恢复。

  • 删除独立Job只删除任务记录,已经生成的素材继续保留在“我的素材”。要清理这些素材,需要再逐项删除素材。
  • 删除工作流草稿会级联归档其运行和子任务;删除一次运行会级联归档该运行的子任务,保留草稿;删除批量记录会级联归档该批次的运行和任务,保留关联草稿。生成素材仍保留。
  • 工作流子任务或批量成员不能单独删除,按页面提示到父运行或批次管理;草稿仍有关联批次时,先删除所属批次。旧任务仍被其他运行复用时,先删除依赖它的运行。
  • 活跃记录须先取消,等待执行退出及资源清理确认后再删。点过“取消”不表示已完成清理,仍显示排队、执行中或取消中时不能直接删除。
  • 删除素材若返回409引用冲突,先从草稿解除引用并保存;冻结运行中的引用需要删除相关运行或父批次。活动任务使用中的素材应先取消任务、等待退出,再按依赖关系处理。不要直接去磁盘删除文件。

素材删除和共享撤回不会立即释放磁盘或额度。物理垃圾回收(GC)默认只做dry-run盘点;默认保留期为14天,超过保留期后仍需运维显式开启维护并执行物理清理(purge),再次检查引用后才可能删除文件。仅真正清理掉的文件释放相应占用,不能把“删除成功”当作即时腾出磁盘。

“任务”可查看叶任务和工作流进度、队列原因、历史执行和错误。GPU任务按就绪入队顺序派发,每张空闲卡同时一个任务,最多四卡并行;配音/媒体CPU和Qwen HTTP仍有独立单槽。llmuser可选择四张GPU的空闲资源,外部用户占卡时优先让出对应卡并重排该任务,其他卡上的任务继续,等待排队本身不是故障。

7. 批量与开发/生产配置

“批量”可以每行一个提示词生成清单,也可加入已经保存的工作流;提交前先“校验与预览”。需要参考素材的类型须补全本账号素材编号。一个批次最多100项,既有创建频率和账号额度继续生效。暂停批次同样只关闭后续准入。

权威配置位于容器内:

/workspace/projects/llm-services/config/runtime-policy.json

服务器宿主机对应:

/data/llmusers/llmuser/workspace/projects/llm-services/config/runtime-policy.json

开发模式:

{"schema_version":1,"batch_window_enabled":false,"workflow_max_shots":120}

正式环境启用时段限制:

{"schema_version":1,"batch_window_enabled":true,"workflow_max_shots":120}

API与GPU worker热读取同一个文件,不需要重启模型或共享Qwen。建议用同目录临时文件写完后原子替换,避免编辑中的半个JSON短暂触发保护。true/false是JSON布尔,不能加引号;不要在任务JSON或网页上添加绕过字段。

  • false:批量也可全天等待空闲资源;手动暂停、维护、账号禁用、容量限额和其他用户优先仍生效。
  • true:批量的新镜头/处理阶段只在北京时间21:00–08:00启动。08:00时当前阶段自然完成,后续排队到下一窗口。交互仍全天可用。
  • 文件不存在:使用生产默认限制。文件错误:关闭新批量准入并显示配置错误;不要为解决此问题删除时钟水位文件。
  • 上限降低只限制新提交/草稿保存,不会截断已经接受的长视频运行。

在网页右上角“创作服务状态”刷新检查生效状态。开发全天与数据库运行模式、公网发布是不同配置;关闭夜间限制不会开放互联网。

若通过SFTP维护配置,可从本机执行以下操作(按提示输入llmuser密码,不把密码写进命令):

sftp llmuser@192.168.28.10
 put E:/workspace/hybrid/cmvr-visual/deploy/runtime-policy.production.json /workspace/projects/llm-services/config/runtime-policy.next.json
 rename /workspace/projects/llm-services/config/runtime-policy.next.json /workspace/projects/llm-services/config/runtime-policy.json
 bye

切回开发模式时把上传源文件改为runtime-policy.development.json,其余步骤相同。这些示例的镜头上限为120;如已自定义上限,先修改本机JSON保留该值再上传。容器内路径与SFTP路径相同,不能把Windows的E盘路径直接当作服务器路径。

8. 账号、令牌和未确认提交

在“账户”修改密码;管理员可创建、停用用户。停用用户不代表去停止共享模型服务。包括admin在内,每位用户的私有内容均按账号隔离;其他账号主动发布的内容只通过共享素材入口查看。

机器令牌用于外部系统调用,创建时按用途选择权限,令牌仅显示一次,立即安全保存;撤销后失效。不要把令牌放进截图、公共仓库或浏览器地址。

“未确认提交”表示客户端没有确认服务器是否已接受。先查询原提交键,确认后再恢复;不要换一个键重复创建。接口细节见docs/api-contract.md和FastAPI接口文档。

记录删除后,原幂等提交的恢复或重放会返回410 resource_purged,表示原结果已归档,不能通过重放把已删除记录恢复。只有确实要创建一项新工作时,才发起新的提交。

9. 数据存放在哪里

数据实际位置与用途
网站业务数据MySQL 192.168.28.10:3306/cmvr-visual,保存用户、素材元数据、任务、工作流、批次、共享发布和审计等网站业务记录
媒体文件服务器宿主机/data/llmusers/llmuser/workspace/cmvr-visual/assets,保存上传、生成、共享发布和导入副本的媒体原件/缩略图;容器内对应/workspace/cmvr-visual/assets
GPU调度恢复推理服务自己的SQLite,仅负责独立GPU执行队列与恢复,不是网站业务数据库,也不保存网站的用户、工作流和共享素材业务

网页所见的素材列表来自MySQL元数据,视频、图片、音频文件在上述媒体目录。备份和迁移需要同时保留业务数据库与媒体文件,不能只备份GPU调度SQLite;数据库记录、网页删除和媒体磁盘占用应分别检查。

10. 常见问题

现象处理
一直等待窗口在状态面板检查开关;开发模式需要API和GPU实际使用同一配置文件
等待GPU/外部用户使用等待空闲资源,不要停止他人的任务
音轨放不进影片先测实际音频长度,增加镜头或缩短旁白;检查毫秒与帧单位
草稿版本冲突保留本地内容,重新载入服务器版本后再决定合并,不反复覆盖
角色变形、鲲鹏不一致统一形象描述、使用参考首帧,分镜小步验证,人工挑选重做
转写没有声音检查源视频是否有音轨;模型生成片段默认无声
结果未知/需要人工确认运维核对远端执行结果后再恢复,不假定HTTP断开等于远端停止
删除返回409检查活动执行、父级控制和引用依赖,先取消并等待退出,或解除引用/删除相关父记录后重试
删除后磁盘没有立即下降软删除保留文件;GC默认dry-run,默认14天保留期后仍需运维维护清理
找不到其他账号的旁白或参考图请原作者发布到共享素材库,再导入自己的私有副本;管理员也不能直接读取他人的私有素材
输出过大或空间不足减少镜头/分辨率/中间副本,按引用规则清理;不要删除模型或上游队列

完整案例见鲲鹏长视频制作指南。模板在frontend/public/examples/kunpeng-storyboard.json,原文旁白在同目录的kunpeng-narration.txt。

另提供kunpeng-storyboard-45s.json,适配本次实测44.425秒完整旁白的初始剪辑;100秒模板用于更舒缓的扩写/停顿版本,均需试听校准字幕。

版本:2026-11-11 · 文档随本项目发布。浏览器可打印为PDF。
\ No newline at end of file diff --git a/frontend/public/help/manual.md b/frontend/public/help/manual.md index bc6e860..7c75ef9 100644 --- a/frontend/public/help/manual.md +++ b/frontend/public/help/manual.md @@ -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. 批量与开发/生产配置 diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 657f917..d2bde57 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -27,6 +27,6 @@ onMounted(()=>window.addEventListener('cmvr:unauthorized',expired));onBeforeUnmo
CMVR Visual/{{ route.meta.title }}
{{ caps.environment === 'production' ? '本地创作空间' : caps.environment ? '验收环境' : '环境待确认' }}
连接恢复中,任务状态待同步。
请先到 账户设置 修改初始密码。
-
LOCAL CREATIVE ENGINE

让算力,为灵感留白。

GPU 任务串行执行,外部使用优先。抢占后自动让行并重新排队。

刷新状态
{{ caps.error }}

连接与调度

推理服务:{{ caps.inferenceOnline===null?"待确认":caps.inferenceOnline?"在线":"离线" }}

模型能力配置

{{ cap.label }}{{ cap.model }}

{{ cap.description }}

{{ cap.available?'就绪':'未配置' }}

算力资源

{{ caps.scheduler?.reason||caps.scheduler?.state||'尚未读取调度状态' }}

GPU {{ gpu.index }}{{ gpu.eligible?'可用':gpu.busy?'占用中':'等待确认' }}{{ gpu.free_gib===null?'—':`${gpu.free_gib.toFixed(1)} GiB 空闲` }}
+
LOCAL CREATIVE ENGINE

让算力,为灵感留白。

空闲 GPU 可并行执行任务,每卡一个,按就绪顺序派发。外部使用优先,占卡时只让出对应卡。

刷新状态
{{ caps.error }}

连接与调度

推理服务:{{ caps.inferenceOnline===null?"待确认":caps.inferenceOnline?"在线":"离线" }}

模型能力配置

{{ cap.label }}{{ cap.model }}

{{ cap.description }}

{{ cap.available?'就绪':'未配置' }}

算力资源

{{ caps.scheduler.running_count }} 项运行中 · {{ caps.scheduler.available_count ?? 0 }} 张卡可接任务

{{ caps.scheduler?.reason||caps.scheduler?.state||'尚未读取调度状态' }}

GPU {{ gpu.index }}{{ ({external:'其他业务占用',running:'本项目执行中',launching:'正在启动',preempting:'正在让卡',blocked:'需要检查',ready:'可接任务',waiting:'等待资源'} as Record)[gpu.state||''] || (gpu.eligible?'可用':gpu.busy?'占用中':'等待确认') }}{{ gpu.free_gib===null?'—':`${gpu.free_gib.toFixed(1)} GiB 空闲` }}
diff --git a/frontend/src/types.ts b/frontend/src/types.ts index 73250e0..3699cf4 100644 --- a/frontend/src/types.ts +++ b/frontend/src/types.ts @@ -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 { diff --git a/frontend/src/views/TasksView.vue b/frontend/src/views/TasksView.vue index db6c852..b02a0a3 100644 --- a/frontend/src/views/TasksView.vue +++ b/frontend/src/views/TasksView.vue @@ -32,7 +32,7 @@ onMounted(()=>{void load();void loadRuns()}); onBeforeUnmount(() => { generation diff --git a/inference/admin/gpu_guard.py b/inference/admin/gpu_guard.py index ba53287..36cdd4b 100644 --- a/inference/admin/gpu_guard.py +++ b/inference/admin/gpu_guard.py @@ -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: diff --git a/inference/llm_services/adapters.py b/inference/llm_services/adapters.py index e137c0c..af7236a 100644 --- a/inference/llm_services/adapters.py +++ b/inference/llm_services/adapters.py @@ -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", diff --git a/inference/llm_services/api.py b/inference/llm_services/api.py index 39b67ab..50442dd 100644 --- a/inference/llm_services/api.py +++ b/inference/llm_services/api.py @@ -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(): diff --git a/inference/llm_services/resources.py b/inference/llm_services/resources.py new file mode 100644 index 0000000..6c4a0d3 --- /dev/null +++ b/inference/llm_services/resources.py @@ -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 diff --git a/inference/llm_services/store.py b/inference/llm_services/store.py index fab81b3..7fedf9f 100644 --- a/inference/llm_services/store.py +++ b/inference/llm_services/store.py @@ -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) diff --git a/inference/llm_services/worker.py b/inference/llm_services/worker.py index d7bded0..4c5c433 100644 --- a/inference/llm_services/worker.py +++ b/inference/llm_services/worker.py @@ -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(): diff --git a/inference/scripts/service.py b/inference/scripts/service.py index 6c7172b..55b8f65 100644 --- a/inference/scripts/service.py +++ b/inference/scripts/service.py @@ -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 diff --git a/inference/tests/test_gpu_guard.py b/inference/tests/test_gpu_guard.py index 7ad20b6..82faa55 100644 --- a/inference/tests/test_gpu_guard.py +++ b/inference/tests/test_gpu_guard.py @@ -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() diff --git a/inference/tests/test_multi_gpu.py b/inference/tests/test_multi_gpu.py new file mode 100644 index 0000000..c4b79db --- /dev/null +++ b/inference/tests/test_multi_gpu.py @@ -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() 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' diff --git a/inference/tests/test_parallel_cpu_threads.py b/inference/tests/test_parallel_cpu_threads.py new file mode 100644 index 0000000..6bb1134 --- /dev/null +++ b/inference/tests/test_parallel_cpu_threads.py @@ -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] diff --git a/inference/tests/test_queue.py b/inference/tests/test_queue.py index a4ff669..07d38ba 100644 --- a/inference/tests/test_queue.py +++ b/inference/tests/test_queue.py @@ -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 diff --git a/inference/tests/test_scheduling_v2.py b/inference/tests/test_scheduling_v2.py index dbe24c6..ff3ba81 100644 --- a/inference/tests/test_scheduling_v2.py +++ b/inference/tests/test_scheduling_v2.py @@ -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')])