304 lines
15 KiB
Python
304 lines
15 KiB
Python
import asyncio
|
|
import pytest
|
|
from app.models import Job
|
|
from app.artifacts import write_manifest,verify_manifest
|
|
from app.executions import begin_execution,accept_manifest
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stale_fence_and_corrupt_manifest_rejected(system):
|
|
row=(await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}})).json()["jobs"][0]
|
|
async with system.app.state.db.session() as s:
|
|
first=await begin_execution(s,row["id"])
|
|
second=await begin_execution(s,row["id"])
|
|
assert not await accept_manifest(s,first.id,first.fence_token,{})
|
|
assert not await accept_manifest(s,second.id,"old-fence",{})
|
|
await s.commit()
|
|
root=system.settings.job_work_root
|
|
source=root/"output.txt";source.write_text("good")
|
|
manifest=write_manifest(root,root,second.id,second.fence_token,[source],{}, {})
|
|
source.write_text("changed")
|
|
with pytest.raises(ValueError,match="hash mismatch"):verify_manifest(root,manifest)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cpu_failed_state_db_write_failure_does_not_replay(system,monkeypatch):
|
|
c=system.app.state.coordinator
|
|
response=await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}})
|
|
calls=0
|
|
async def fail_provider(*args):
|
|
nonlocal calls
|
|
calls+=1
|
|
raise ValueError("provider failed after possible execution")
|
|
async def fail_persist(*args):raise RuntimeError("database unavailable")
|
|
monkeypatch.setattr(system.provider,"run_cpu",fail_provider)
|
|
original=c._failure
|
|
monkeypatch.setattr(c,"_failure",fail_persist)
|
|
await c.run_once(force=True)
|
|
await asyncio.gather(*c._cpu.values())
|
|
monkeypatch.setattr(c,"_failure",original)
|
|
await c.run_once(force=True)
|
|
assert calls==1
|
|
async with system.app.state.db.session() as s:
|
|
assert (await s.get(Job,response.json()["jobs"][0]["id"])).state=="needs_attention"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_soft_window_blocks_next_batch_but_queries_running(system,monkeypatch):
|
|
from app import resource_policy
|
|
c=system.app.state.coordinator
|
|
response=await system.client.post("/api/jobs",json={"task_type":"image.generate","input":{"prompt":"x"}})
|
|
job_id=response.json()["jobs"][0]["id"]
|
|
await c.run_once(force=True)
|
|
async with system.app.state.db.session() as s:
|
|
job=await s.get(Job,job_id);job.execution_mode="batch";upstream=job.upstream_id;await s.commit()
|
|
system.provider.remote[upstream]["state"]="running"
|
|
monkeypatch.setattr(resource_policy,"execution_policy",lambda now=None:{"batch_open":False})
|
|
await c.run_once(force=True)
|
|
async with system.app.state.db.session() as s:assert (await s.get(Job,job_id)).state=="running"
|
|
assert system.provider.remote[upstream]["state"]=="running"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pool_concurrency_and_phase_window_recheck(system,monkeypatch):
|
|
from app import resource_policy
|
|
from app.providers import enter_phase
|
|
from types import SimpleNamespace
|
|
c=system.app.state.coordinator
|
|
opened=True;entered=[];sampled=asyncio.Event()
|
|
monkeypatch.setattr(resource_policy,"execution_policy",lambda now=None:{"batch_open":opened})
|
|
async def phased(task_type,inputs,params,assets,work):
|
|
nonlocal opened
|
|
await enter_phase("sample_frames","cpu_media")
|
|
entered.append("sample")
|
|
sampled.set()
|
|
opened=False
|
|
await enter_phase("describe_frames","qwen_http")
|
|
entered.append("describe")
|
|
out=work/"answer.txt";out.write_text("done")
|
|
return SimpleNamespace(outputs=[out],result={},metadata={})
|
|
monkeypatch.setattr(system.provider,"run_cpu",phased)
|
|
response=await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}})
|
|
async with system.app.state.db.session() as session:
|
|
job=await session.get(Job,response.json()["jobs"][0]["id"]);job.execution_mode="batch";await session.commit()
|
|
await c.run_once(force=True)
|
|
await asyncio.wait_for(sampled.wait(),5)
|
|
assert entered==["sample"]
|
|
assert c._pools["cpu_media"]._value==1 and c._pools["qwen_http"]._value==1
|
|
# Reopening admits the next phase; current phase was allowed to finish.
|
|
opened=True
|
|
await asyncio.wait_for(asyncio.gather(*c._cpu.values()),3)
|
|
assert entered==["sample","describe"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_lost_asset_commit_ack_preserves_file_and_imports_once(system,monkeypatch):
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
from app.models import Asset
|
|
c=system.app.state.coordinator
|
|
response=await system.client.post("/api/jobs",json={"task_type":"image.generate","input":{"prompt":"x"}})
|
|
job_id=response.json()["jobs"][0]["id"]
|
|
await c.run_once(force=True)
|
|
upstream=next(iter(system.provider.remote))
|
|
system.provider.remote[upstream].update(state="succeeded",result={"outputs":[{"path":"image.png"}]})
|
|
original=AsyncSession.commit;lost=False
|
|
async def uncertain(session):
|
|
nonlocal lost
|
|
trigger=not lost and any(isinstance(row,Asset) and not row.ready for row in session.identity_map.values())
|
|
await original(session)
|
|
if trigger:
|
|
lost=True
|
|
raise RuntimeError("commit succeeded; ACK lost")
|
|
monkeypatch.setattr(AsyncSession,"commit",uncertain)
|
|
await c.run_once(force=True)
|
|
assert lost
|
|
await c.run_once(force=True)
|
|
async with system.app.state.db.session() as session:
|
|
assets=(await session.scalars(select(Asset).where(Asset.source_job_id==job_id))).all()
|
|
assert len(assets)==1 and assets[0].ready
|
|
assert (system.settings.asset_root/assets[0].storage_key).exists()
|
|
assert (await session.get(Job,job_id)).state=="succeeded"
|
|
assert system.provider.download_count==1
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cancel_is_sent_once_until_ack(system,monkeypatch):
|
|
c=system.app.state.coordinator
|
|
response=await system.client.post("/api/jobs",json={"task_type":"image.generate","input":{"prompt":"x"}})
|
|
job_id=response.json()["jobs"][0]["id"]
|
|
await c.run_once(force=True)
|
|
calls=[]
|
|
async def delayed_cancel(remote_id):
|
|
calls.append(remote_id)
|
|
return {**system.provider.remote[remote_id],"state":"running"}
|
|
monkeypatch.setattr(system.provider,"cancel",delayed_cancel)
|
|
await system.client.post("/api/jobs/"+job_id+"/cancel")
|
|
await c.run_once(force=True);await c.run_once(force=True);await c.run_once(force=True)
|
|
assert len(calls)==1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cancel_committed_after_slot_claim_never_calls_provider(system,monkeypatch):
|
|
c=system.app.state.coordinator
|
|
response=await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}})
|
|
job_id=response.json()["jobs"][0]["id"]
|
|
enter=c._enter_phase
|
|
async def race(job_id,phase,pool):
|
|
await enter(job_id,phase,pool)
|
|
async with system.app.state.db.session() as session:
|
|
job=await session.get(Job,job_id);job.cancel_requested=True;job.state="cancelling";await session.commit()
|
|
monkeypatch.setattr(c,"_enter_phase",race)
|
|
await c.run_once(force=True)
|
|
await asyncio.gather(*c._cpu.values())
|
|
assert system.provider.cpu_runs==0
|
|
async with system.app.state.db.session() as session:assert (await session.get(Job,job_id)).state=="cancelled"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_waiting_qwen_job_rechecks_unknown_pool_after_acquire(system,monkeypatch):
|
|
from conftest import BoundaryError
|
|
c=system.app.state.coordinator
|
|
first_started=asyncio.Event();second_waiting=asyncio.Event();calls=[]
|
|
acquire=c._pools["qwen_http"].acquire
|
|
async def tracked_acquire():
|
|
if c._pools["qwen_http"].locked():second_waiting.set()
|
|
return await acquire()
|
|
monkeypatch.setattr(c._pools["qwen_http"],"acquire",tracked_acquire)
|
|
async def unknown(*args):
|
|
calls.append(args[1]["prompt"])
|
|
first_started.set()
|
|
await second_waiting.wait()
|
|
raise BoundaryError("remote compute completion unknown")
|
|
monkeypatch.setattr(system.provider,"run_cpu",unknown)
|
|
for prompt in ("first","second"):
|
|
await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":prompt}})
|
|
await c.run_once(force=True)
|
|
await asyncio.wait_for(second_waiting.wait(),3)
|
|
for _ in range(100):
|
|
if "qwen_http" in c._blocked_pools:break
|
|
await asyncio.sleep(.01)
|
|
await asyncio.sleep(.1)
|
|
assert calls==["first"]
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cpu_media_cancel_records_cleanup_and_allows_explicit_retry(system,monkeypatch):
|
|
from app.v2_models import Execution
|
|
from sqlalchemy import select
|
|
c=system.app.state.coordinator
|
|
started=asyncio.Event();cleaned=asyncio.Event()
|
|
async def cancellable(*args):
|
|
started.set()
|
|
try:await asyncio.Future()
|
|
finally:cleaned.set()
|
|
monkeypatch.setattr(system.provider,"run_cpu",cancellable)
|
|
body={"task_type":"audio.speech","input":{"prompt":"x"}}
|
|
system.settings.tts_base_url="http://private-tts"
|
|
r=await system.client.post("/api/jobs",json=body);assert r.status_code==202,r.text
|
|
job_id=r.json()["jobs"][0]["id"]
|
|
async with system.app.state.db.session() as session:
|
|
job=await session.get(Job,job_id);job.task_type="video.compose";await session.commit()
|
|
await c.run_once(force=True);await asyncio.wait_for(started.wait(),3)
|
|
await system.client.post("/api/jobs/"+job_id+"/cancel")
|
|
await c.run_once(force=True);await asyncio.gather(*c._cpu.values())
|
|
assert cleaned.is_set()
|
|
async with system.app.state.db.session() as session:
|
|
execution=await session.scalar(select(Execution).where(Execution.job_id==job_id))
|
|
assert execution.state=="exited" and execution.finished_at is not None
|
|
async with system.app.state.db.session() as session:
|
|
job=await session.get(Job,job_id);job.task_type="audio.speech";await session.commit()
|
|
retry=await system.client.post("/api/jobs/"+job_id+"/retry",headers={"Idempotency-Key":"after-cleanup"})
|
|
assert retry.status_code==202,retry.text
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_gpu_preparation_does_not_block_tick_behind_media_slot(system,monkeypatch):
|
|
from app.providers import enter_phase
|
|
c=system.app.state.coordinator
|
|
await system.client.post("/api/jobs",json={"task_type":"image.generate","input":{"prompt":"x"}})
|
|
async def prepare(*args):
|
|
await enter_phase("extract_audio","cpu_media")
|
|
raise AssertionError("Extraction must not start behind occupied media pool")
|
|
monkeypatch.setattr(system.provider,"prepare_gpu_payload",prepare)
|
|
await c._pools["cpu_media"].acquire()
|
|
try:
|
|
await asyncio.wait_for(c.run_once(force=True),1)
|
|
assert not system.provider.accepted
|
|
finally:c._pools["cpu_media"].release()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_disabled_owner_cannot_enter_new_phase_after_slot_wait(system,monkeypatch):
|
|
from app.models import User
|
|
from app.coordinator import PhaseDeferred
|
|
c=system.app.state.coordinator
|
|
response=await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}})
|
|
job_id=response.json()["jobs"][0]["id"]
|
|
acquire=c._pools["qwen_http"].acquire
|
|
async def race():
|
|
result=await acquire()
|
|
async with system.app.state.db.session() as session:
|
|
job=await session.get(Job,job_id);owner=await session.get(User,job.owner_id);owner.disabled=True;await session.commit()
|
|
return result
|
|
monkeypatch.setattr(c._pools["qwen_http"],"acquire",race)
|
|
with pytest.raises(PhaseDeferred):await c._enter_phase(job_id,"solve","qwen_http",nonblocking=True)
|
|
assert c._pools["qwen_http"]._value==1
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_generated_output_actual_owner_budget_stops_recollection(system):
|
|
system.settings.max_owner_asset_bytes=1
|
|
c=system.app.state.coordinator
|
|
response=await system.client.post("/api/jobs",json={"task_type":"math.solve","input":{"prompt":"x"}})
|
|
job_id=response.json()["jobs"][0]["id"]
|
|
await c.run_once(force=True);await asyncio.gather(*c._cpu.values())
|
|
async with system.app.state.db.session() as session:
|
|
job=await session.get(Job,job_id)
|
|
assert job.state=="failed" and job.error_json["code"]=="quota_exceeded"
|
|
await c.run_once(force=True)
|
|
assert system.provider.cpu_runs==1
|
|
assert list(system.settings.job_work_root.rglob("result-manifest.json"))
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("task_type",["math.solve","audio.speech"])
|
|
async def test_shared_http_explicit_cancel_drains_response_before_next_call(system,monkeypatch,task_type):
|
|
from types import SimpleNamespace
|
|
from sqlalchemy import select
|
|
from app.v2_models import Execution
|
|
c=system.app.state.coordinator
|
|
system.settings.tts_base_url="http://private-tts"
|
|
started=asyncio.Event();finish=asyncio.Event();calls=[]
|
|
async def http_phase(task,inputs,params,assets,work):
|
|
calls.append(inputs["prompt"])
|
|
if inputs["prompt"]=="first":
|
|
started.set();await finish.wait()
|
|
output=work/"answer.txt";output.write_text("response completed")
|
|
return SimpleNamespace(outputs=[output],result={},metadata={})
|
|
monkeypatch.setattr(system.provider,"run_cpu",http_phase)
|
|
first=await system.client.post("/api/jobs",json={"task_type":task_type,"input":{"prompt":"first"}})
|
|
job_id=first.json()["jobs"][0]["id"]
|
|
await c.run_once(force=True);await asyncio.wait_for(started.wait(),3)
|
|
await system.client.post("/api/jobs",json={"task_type":task_type,"input":{"prompt":"second"}})
|
|
await system.client.post("/api/jobs/"+job_id+"/cancel")
|
|
await c.run_once(force=True);await asyncio.sleep(.05)
|
|
assert calls==["first"] and not c._cpu[job_id].done()
|
|
finish.set();await asyncio.wait_for(asyncio.gather(*c._cpu.values()),5)
|
|
assert calls==["first","second"]
|
|
async with system.app.state.db.session() as session:
|
|
first=await session.get(Job,job_id)
|
|
execution=await session.scalar(select(Execution).where(Execution.job_id==job_id))
|
|
assert first.state=="cancelled" and first.result_json is None
|
|
assert execution.state=="exited"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_speech_transport_unknown_quarantines_media_pool(system,monkeypatch):
|
|
from conftest import BoundaryError
|
|
from sqlalchemy import select
|
|
from app.v2_models import Execution
|
|
c=system.app.state.coordinator
|
|
system.settings.tts_base_url="http://private-tts"
|
|
async def failed(*args):raise BoundaryError("speech server completion unknown")
|
|
monkeypatch.setattr(system.provider,"run_cpu",failed)
|
|
response=await system.client.post("/api/jobs",json={"task_type":"audio.speech","input":{"prompt":"x"}})
|
|
await c.run_once(force=True);await asyncio.gather(*c._cpu.values())
|
|
async with system.app.state.db.session() as session:
|
|
job=await session.get(Job,response.json()["jobs"][0]["id"])
|
|
execution=await session.scalar(select(Execution).where(Execution.job_id==job.id))
|
|
assert job.state=="needs_attention" and execution.state=="unknown"
|
|
assert "cpu_media" in c._blocked_pools
|