import json import asyncio from datetime import datetime, timedelta, timezone from sqlalchemy import select async def submit(system, **changes): body = {"task_type": "image.generate", "input": {"prompt": "a blue cup"}, "parameters": {}} body.update(changes) response = await system.client.post("/api/jobs", json=body) assert response.status_code == 202, response.text return response.json()["jobs"] async def test_batch_idempotency_and_scheduled_jobs_do_not_dispatch_early(system): future = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat() body = {"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {}, "count": 3, "scheduled_at": future} first = await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"}) second = await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"}) assert first.status_code == 202 and second.json() == first.json() assert len(first.json()["jobs"]) == 3 assert [job["parameters"]["seed"] for job in first.json()["jobs"]] == [42, 43, 44] assert {job["state"] for job in first.json()["jobs"]} == {"scheduled"} body["input"]["prompt"] = "changed" assert (await system.client.post("/api/jobs", json=body, headers={"Idempotency-Key": "batch-one"})).status_code == 409 await system.app.state.coordinator.run_once(force=True) assert not system.provider.accepted async def test_lost_submit_response_recovers_same_id_and_known_id_never_resubmits(system): job = (await submit(system))[0] system.provider.lost_response = True await system.app.state.coordinator.run_once(force=True) await system.app.state.coordinator.run_once(force=True) current = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert current["upstream_id"] == "remote-1" and len(system.provider.accepted) == 1 assert system.provider.submitted_payloads[0] == system.provider.submitted_payloads[1] submitted = len(system.provider.submitted_payloads) system.provider.remote["remote-1"].update(state="running", attempt_count=1) await system.app.state.coordinator.run_once(force=True) running = (await system.client.get(f"/api/jobs/{job['id']}")).json() system.provider.remote["remote-1"].update(state="queued", attempt_count=1, preemptions=1, last_preempted_reason="External user arrived") await system.app.state.coordinator.run_once(force=True) queued = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert queued["state"] == "queued" and queued["version"] > running["version"] assert queued["preemptions"] == 1 and queued["upstream_id"] == "remote-1" assert len(system.provider.submitted_payloads) == submitted async def test_output_import_retry_does_not_generate_again_or_duplicate_assets(system): job = (await submit(system))[0] await system.app.state.coordinator.run_once(force=True) system.provider.remote["remote-1"].update(state="succeeded", attempt_count=1, result={"outputs": [{"path": "/workspace/private/should-not-leak.png"}], "metadata": {"engine": "real"}}) system.provider.fail_download_once = True await system.app.state.coordinator.run_once(force=True) collecting = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert collecting["state"] == "collecting" await system.app.state.coordinator.run_once(force=True) completed = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert completed["state"] == "succeeded" and len(completed["result_assets"]) == 1 assert "/workspace/" not in json.dumps(completed) await system.app.state.coordinator.run_once(force=True) assets = (await system.client.get("/api/assets")).json() assert assets["total"] == 1 and len(system.provider.accepted) == 1 async def test_partial_outputs_remain_private_until_every_output_is_imported(system): job = (await submit(system))[0] await system.app.state.coordinator.run_once(force=True) system.provider.remote["remote-1"].update(state="succeeded", result={"outputs": [{"path": "one.png"}, {"path": "two.png"}]}) system.provider.fail_download_at = 1 await system.app.state.coordinator.run_once(force=True) assert (await system.client.get(f"/api/jobs/{job['id']}")).json()["state"] == "collecting" assert (await system.client.get("/api/assets")).json()["total"] == 0 await system.app.state.coordinator.run_once(force=True) completed = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert completed["state"] == "succeeded" and len(completed["result_assets"]) == 2 assert (await system.client.get("/api/assets")).json()["total"] == 2 async def test_owner_isolation_cancel_and_explicit_retry(system, other_client): job = (await submit(system))[0] for method, path in (("get", f"/api/jobs/{job['id']}"), ("post", f"/api/jobs/{job['id']}/cancel"), ("post", f"/api/jobs/{job['id']}/retry")): assert (await getattr(other_client, method)(path)).status_code == 404 cancelled = await system.client.post(f"/api/jobs/{job['id']}/cancel") assert cancelled.json()["state"] == "cancelled" retried = await system.client.post(f"/api/jobs/{job['id']}/retry") assert retried.status_code == 202 and retried.json()["jobs"][0]["id"] != job["id"] async def test_unsupported_parameters_are_rejected_before_job_creation(system): response = await system.client.post("/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "cup"}, "parameters": {"steps": 1}}) assert response.status_code == 400 assert (await system.client.get("/api/jobs")).json()["total"] == 0 async def test_definitive_upstream_input_rejection_is_terminal_not_retried_forever(system): job = (await submit(system))[0] system.provider.reject_submission = True 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" count = len(system.provider.submitted_payloads) await system.app.state.coordinator.run_once(force=True) assert len(system.provider.submitted_payloads) == count async def test_coordinator_restart_recovers_id_and_cancel_unknown_submit(system): from app.coordinator import Coordinator job = (await submit(system))[0] system.provider.lost_response = True await system.app.state.coordinator.run_once(force=True) cancelled = await system.client.post(f"/api/jobs/{job['id']}/cancel") assert cancelled.json()["state"] == "cancelling" restarted = Coordinator(system.settings, system.app.state.db, system.provider) await restarted.run_once(force=True) await restarted.run_once(force=True) current = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert current["state"] == "cancelled" and current["upstream_id"] == "remote-1" assert len(system.provider.accepted) == 1 async def test_cpu_provider_results_are_real_assets_and_cancelled_stale_job_never_runs(system): job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0] coordinator = system.app.state.coordinator await coordinator.run_once(force=True) await asyncio.gather(*list(coordinator._cpu.values())) completed = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert completed["state"] == "succeeded" and completed["result"]["text"] == "The answer is 5" content = await system.client.get(completed["result_assets"][0]["preview_url"]) assert content.content == b"The answer is 5" stale_job = (await submit(system, task_type="math.solve", input={"prompt": "next"}))[0] stale = await coordinator._job(stale_job["id"]) await system.client.post(f"/api/jobs/{stale_job['id']}/cancel") before = system.provider.cpu_runs await coordinator._run_cpu(stale) assert system.provider.cpu_runs == before async def test_running_cpu_cancellation_waits_provider_task(system): job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0] system.provider.cpu_wait = True coordinator = system.app.state.coordinator await coordinator.run_once(force=True) for _ in range(100): if system.provider.cpu_runs: break await asyncio.sleep(.01) await system.client.post(f"/api/jobs/{job['id']}/cancel") tasks = list(coordinator._cpu.values()) await coordinator.run_once(force=True) await asyncio.gather(*tasks, return_exceptions=True) current = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert current["state"] == "cancelled" async def test_cancel_during_gpu_preparation_never_starts_new_upstream_job(system): job = (await submit(system))[0] entered, release = asyncio.Event(), asyncio.Event() original = system.provider.prepare_gpu_payload async def blocked_prepare(*args, **kwargs): entered.set() await release.wait() return await original(*args, **kwargs) system.provider.prepare_gpu_payload = blocked_prepare task = asyncio.create_task(system.app.state.coordinator.run_once(force=True)) try: await asyncio.wait_for(entered.wait(), 2) response = await system.client.post(f"/api/jobs/{job['id']}/cancel") assert response.json()["state"] == "cancelling" release.set() await asyncio.wait_for(task, 3) finally: release.set() await asyncio.gather(task, return_exceptions=True) final = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert final["state"] == "cancelled" assert not system.provider.accepted and not system.provider.submitted_payloads async def test_cpu_cancel_after_result_read_wins_collection_and_publication(system): job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0] coordinator = system.app.state.coordinator entered, release = asyncio.Event(), asyncio.Event() original = coordinator._update async def blocked_collect(job_id, **changes): if changes.get("state") == "collecting": entered.set() await release.wait() return await original(job_id, **changes) coordinator._update = blocked_collect try: await coordinator.run_once(force=True) await asyncio.wait_for(entered.wait(), 2) response = await system.client.post(f"/api/jobs/{job['id']}/cancel") assert response.json()["state"] == "cancelling" release.set() await asyncio.gather(*list(coordinator._cpu.values())) finally: release.set() current = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert current["state"] == "cancelled" and not current["result_assets"] assert (await system.client.get("/api/assets")).json()["total"] == 0 async def test_final_publication_reloads_committed_cancel_and_keeps_pending_private(system): from app.models import Job job = (await submit(system, task_type="math.solve", input={"prompt": "2+3?"}))[0] coordinator = system.app.state.coordinator entered, release = asyncio.Event(), asyncio.Event() original = coordinator._complete async def blocked_complete(*args, **kwargs): entered.set() await release.wait() return await original(*args, **kwargs) coordinator._complete = blocked_complete await coordinator.run_once(force=True) try: await asyncio.wait_for(entered.wait(), 2) # Simulates a previously committed cancellation surviving a stale # collection transition; _complete must defend publication itself. async with system.app.state.db.session() as session: saved = await session.get(Job, job["id"]) saved.cancel_requested, saved.state = True, "cancelling" await session.commit() release.set() await asyncio.gather(*list(coordinator._cpu.values())) finally: release.set() final = (await system.client.get(f"/api/jobs/{job['id']}")).json() assert final["state"] == "cancelled" and not final["result_assets"] assert (await system.client.get("/api/assets")).json()["total"] == 0 async def test_large_waiting_gpu_queue_does_not_starve_later_cpu_or_cancel(system): ids = [] for _ in range(13): 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) 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" last = (await system.client.get(f"/api/jobs/{ids[-1]}")).json() assert last["upstream_id"] await system.client.post(f"/api/jobs/{ids[-1]}/cancel") await coordinator.run_once(force=True) assert (await system.client.get(f"/api/jobs/{ids[-1]}" )).json()["state"] == "cancelled"