207 lines
11 KiB
Python
207 lines
11 KiB
Python
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):
|
|
wf.settings.max_interactive_gpu_jobs=8
|
|
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_default_limit_feeds_twenty_shots_across_ticks_without_completions(wf):
|
|
d=await wf.client.post('/api/workflows',json={'spec':story(20)});assert d.status_code==201,d.text
|
|
rid=(await run(wf,d.json()))['run']['id']
|
|
for expected in (8,16,20):
|
|
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,Job.id))).all()
|
|
assert len(jobs)==expected
|
|
assert [j.step_key for j in jobs]==[f'shot_{i}' for i in range(1,expected+1)]
|
|
assert all(j.state not in {'succeeded','failed','cancelled','timed_out'} for j in jobs)
|
|
snapshot=(await wf.client.get('/api/workflow-runs/'+rid)).json()
|
|
assert 'quota' not in snapshot['run']['hold_reasons']
|
|
assert not any(j.step_key=='compose' for j in jobs)
|
|
assert not wf.provider.accepted
|
|
|
|
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)
|