from copy import deepcopy import pytest from sqlalchemy import select from app.models import Job, Asset from app.models import Execution, AssetReference from app.services.orchestration.coordinator import Coordinator async def queued_job(system): import asyncio from app.domain.tasks import TERMINAL response = await system.client.post( "/api/jobs", json={"task_type": "image.generate", "input": {"prompt": "x"}} ) assert response.status_code == 202, response.text job_id = response.json()["jobs"][0]["id"] observed = None try: async with asyncio.timeout(10): while True: await system.app.state.coordinator.run_once(force=True) async with system.app.state.db.session() as session: job = await session.get(Job, job_id) assert job is not None observed = (job.state, job.phase) if job.upstream_id: return job_id, job.upstream_id assert job.state not in TERMINAL, (observed, job.error_json) # 准备在后台运行,一轮tick只观察100ms;等持久化ID而不是假定一轮即可提交。 await asyncio.sleep(0) except TimeoutError: pytest.fail(f"Job {job_id} did not persist upstream_id within 10 seconds: {observed}") @pytest.mark.asyncio async def test_gpu_attempt_observation_preempt_restart_stale_counter_and_publication(system): job_id, upstream = await queued_job(system) c = system.app.state.coordinator running = { "id": upstream, "execution_id": upstream + ":1", "attempt_count": 1, "state": "running", "stage": "executing", "runner_pid": 77, } await c._apply_remote(job_id, running) async with system.app.state.db.session() as session: first = (await session.scalars(select(Execution).where(Execution.job_id == job_id))).one() assert first.state == "running" and first.manifest_json["upstream_attempt"] == 1 first_id = first.id # A queued state without a cleanup ACK cannot claim the runner is gone. await c._apply_remote(job_id, {**running, "state": "queued", "stage": "queued"}) async with system.app.state.db.session() as session: assert (await session.get(Execution, first_id)).state == "running" await c._apply_remote( job_id, {**running, "state": "queued", "stage": "queued", "runner_pid": None, "preemptions": 1}, ) async with system.app.state.db.session() as session: assert (await session.get(Execution, first_id)).state == "exited" # Same closed attempt cannot be revived by a late running callback. await c._apply_remote(job_id, running) async with system.app.state.db.session() as session: assert (await session.get(Job, job_id)).state == "queued" running2 = {**running, "execution_id": upstream + ":2", "attempt_count": 2, "runner_pid": 88} await c._apply_remote(job_id, running2) restarted = Coordinator(system.settings, system.app.state.db, system.provider) await restarted._apply_remote(job_id, running2) stale = {**running, "state": "succeeded", "result": {"outputs": [{"path": "old-attempt.png"}]}} await restarted._apply_remote(job_id, stale) assert system.provider.download_count == 0 success = { **running2, "state": "succeeded", "result": {"outputs": [{"path": "attempt-2/image.png"}], "metadata": {}}, } await restarted._apply_remote(job_id, success) async with system.app.state.db.session() as session: job = await session.get(Job, job_id) rows = list( ( await session.scalars( select(Execution).where(Execution.job_id == job_id).order_by(Execution.ordinal) ) ).all() ) assert len(rows) == 2 and [row.state for row in rows] == ["exited", "results_ready"] assert job.state == "succeeded" and job.current_execution_id == rows[1].id assert rows[1].manifest_json["upstream_execution_id"] == upstream + ":2" asset = (await session.scalars(select(Asset).where(Asset.source_job_id == job_id))).one() assert asset.ready binding = await session.scalar( select(AssetReference).where( AssetReference.asset_id == asset.id, AssetReference.ref_kind == "execution" ) ) assert binding.ref_id == rows[1].id @pytest.mark.asyncio async def test_unlaunched_deferred_claim_does_not_invent_execution(system): job_id, upstream = await queued_job(system) c = system.app.state.coordinator claim = { "id": upstream, "execution_id": upstream + ":1", "attempt_count": 1, "state": "running", "stage": "launching", "runner_pid": None, "started_at": 123, } await c._apply_remote(job_id, claim) await c._apply_remote( job_id, {**claim, "state": "queued", "stage": "batch_window_closed", "started_at": None} ) await c._apply_remote( job_id, {**claim, "state": "cancelled", "stage": "cancelled", "started_at": None} ) async with system.app.state.db.session() as session: assert not ( await session.scalars(select(Execution).where(Execution.job_id == job_id)) ).all() @pytest.mark.asyncio async def test_gpu_collection_rechecks_current_fence_before_asset_commit(system, monkeypatch): from app.services.orchestration.executions import begin_execution job_id, upstream = await queued_job(system) c = system.app.state.coordinator download = system.provider.download async def late_download(*args): await download(*args) async with system.app.state.db.session() as session: await begin_execution(session, job_id, "gpu:2", "new_gpu") await session.commit() monkeypatch.setattr(system.provider, "download", late_download) remote = { "id": upstream, "execution_id": upstream + ":1", "attempt_count": 1, "state": "succeeded", "result": {"outputs": [{"path": "attempt-1.png"}]}, } with pytest.raises(ValueError, match="Stale GPU result import"): await c._apply_remote(job_id, remote) async with system.app.state.db.session() as session: assert not (await session.scalars(select(Asset).where(Asset.source_job_id == job_id))).all() assert (await session.get(Job, job_id)).state != "succeeded" @pytest.mark.asyncio async def test_gpu_terminal_observation_does_not_fabricate_missed_attempts(system): job_id, upstream = await queued_job(system) await system.app.state.coordinator._apply_remote( job_id, {"id": upstream, "execution_id": upstream + ":3", "attempt_count": 3, "state": "failed"}, ) async with system.app.state.db.session() as session: rows = list( (await session.scalars(select(Execution).where(Execution.job_id == job_id))).all() ) assert ( len(rows) == 1 and rows[0].ordinal == 1 and rows[0].manifest_json["upstream_attempt"] == 3 ) assert rows[0].state == "exited" @pytest.mark.asyncio async def test_gpu_final_publication_rechecks_fence_after_import(system, monkeypatch): from app.services.orchestration.executions import begin_execution job_id, upstream = await queued_job(system) c = system.app.state.coordinator complete = c._complete async def replaced_before_publish(job_id, result, **kwargs): async with system.app.state.db.session() as session: await begin_execution(session, job_id, "gpu:2", "new_gpu") await session.commit() await complete(job_id, result, **kwargs) monkeypatch.setattr(c, "_complete", replaced_before_publish) await c._apply_remote( job_id, { "id": upstream, "execution_id": upstream + ":1", "attempt_count": 1, "state": "succeeded", "result": {"outputs": [{"path": "attempt-1.png"}]}, }, ) async with system.app.state.db.session() as session: assets = list( (await session.scalars(select(Asset).where(Asset.source_job_id == job_id))).all() ) assert assets and all(not asset.ready for asset in assets) assert (await session.get(Job, job_id)).state != "succeeded" @pytest.mark.asyncio async def test_gpu_same_attempt_wrong_remote_fence_cannot_publish(system): job_id, upstream = await queued_job(system) c = system.app.state.coordinator running = { "id": upstream, "execution_id": upstream + ":1", "attempt_count": 1, "state": "running", "stage": "executing", "fence_token": "current", } await c._apply_remote(job_id, running) await c._apply_remote( job_id, { **running, "fence_token": "stale", "state": "succeeded", "result": {"outputs": [{"path": "wrong.png"}]}, }, ) assert system.provider.download_count == 0 async with system.app.state.db.session() as session: assert (await session.get(Job, job_id)).state == "running" def _mysql_float_roundtrip(value): """MySQL实测的相邻double变化;JSON字符串中的数字不会被数据库重编码。""" if isinstance(value, dict): return {key: _mysql_float_roundtrip(child) for key, child in value.items()} if isinstance(value, list): return [_mysql_float_roundtrip(child) for child in value] if type(value) is float: return { 0.9935344827586207: 0.9935344827586208, 0.24646226415094338: 0.24646226415094336, }.get(value, value) return value def _real_analysis_result(): import json from pathlib import Path return json.loads( (Path(__file__).parent / "fixtures/video_analysis_gpu_result.json").read_text( encoding="utf-8" ) ) @pytest.mark.asyncio async def test_exact_gpu_result_survives_mysql_double_roundtrip(system): from app.services.orchestration.executions import gpu_publication_matches job_id, upstream = await queued_job(system) coordinator = system.app.state.coordinator remote = { "id": upstream, "execution_id": upstream + ":1", "attempt_count": 1, "state": "succeeded", "result": _real_analysis_result(), } await coordinator._update( job_id, remote_observation=remote, state="collecting", phase="importing_outputs", attempt_count=1, upstream_result=remote["result"], ) async with system.app.state.db.session() as session: job = await session.get(Job, job_id) job.upstream_result = _mysql_float_roundtrip(job.upstream_result) await session.commit() async with system.app.state.db.session() as session: job = await session.get(Job, job_id) assert await gpu_publication_matches(session, job, job.upstream_result["_visual_execution"]) await coordinator._collect_gpu(job) async with system.app.state.db.session() as session: assert (await session.get(Job, job_id)).state == "succeeded" assert len(system.provider.submitted_payloads) == 1 @pytest.mark.asyncio @pytest.mark.parametrize( "tamper", [None, "path", "attempt", "upstream_fence", "id", "state", "execution", "hash"] ) async def test_legacy_mysql_result_recovers_same_job_only_from_original_hash(system, tamper): from app.services.orchestration.executions import gpu_publication_matches job_id, upstream = await queued_job(system) coordinator = system.app.state.coordinator remote = { "id": upstream, "execution_id": upstream + ":1", "attempt_count": 1, "state": "succeeded", "result": _real_analysis_result(), } await coordinator._update( job_id, remote_observation=remote, state="collecting", phase="importing_outputs", attempt_count=1, upstream_result=remote["result"], ) async with system.app.state.db.session() as session: job = await session.get(Job, job_id) job.upstream_result = { **_mysql_float_roundtrip(remote["result"]), "_visual_execution": job.upstream_result["_visual_execution"], } await session.commit() queried = deepcopy(remote) if tamper == "path": queried["result"]["outputs"][0]["path"] = "different.png" elif tamper == "attempt": queried["attempt_count"] = 2 queried["execution_id"] = upstream + ":2" if tamper == "upstream_fence": queried["fence_token"] = "different-fence" elif tamper == "id": queried["id"] = "different-upstream" elif tamper == "state": queried["state"] = "failed" elif tamper == "execution": queried["execution_id"] = upstream + ":different" elif tamper == "hash": async with system.app.state.db.session() as session: current = await session.get(Job, job_id) payload = deepcopy(current.upstream_result) payload["_visual_execution"]["result_hash"] = "0" * 64 current.upstream_result = payload await session.commit() system.provider.remote[upstream] = queried async with system.app.state.db.session() as session: job = await session.get(Job, job_id) assert not await gpu_publication_matches( session, job, job.upstream_result["_visual_execution"] ) if tamper: with pytest.raises(ValueError): await coordinator._collect_gpu(job) assert system.provider.download_count == 0 else: await coordinator._collect_gpu(job) async with system.app.state.db.session() as session: restored = await session.get(Job, job_id) assert restored.state == "succeeded" and restored.id == job_id assert len(system.provider.submitted_payloads) == 1 @pytest.mark.asyncio async def test_exact_result_envelope_rejects_json_string_tampering(system): from app.services.orchestration.executions import gpu_publication_matches import json job_id, upstream = await queued_job(system) coordinator = system.app.state.coordinator remote = { "id": upstream, "execution_id": upstream + ":1", "attempt_count": 1, "state": "succeeded", "result": _real_analysis_result(), } await coordinator._update( job_id, remote_observation=remote, state="collecting", phase="importing_outputs", attempt_count=1, upstream_result=remote["result"], ) async with system.app.state.db.session() as session: job = await session.get(Job, job_id) payload = deepcopy(job.upstream_result) parsed = json.loads(payload["_visual_result_json"]) parsed["outputs"][0]["path"] = "tampered.png" payload["_visual_result_json"] = json.dumps( parsed, sort_keys=True, separators=(",", ":"), allow_nan=False ) job.upstream_result = payload await session.commit() async with system.app.state.db.session() as session: job = await session.get(Job, job_id) assert not await gpu_publication_matches( session, job, job.upstream_result["_visual_execution"] ) with pytest.raises(ValueError): await coordinator._collect_gpu(job) assert system.provider.download_count == 0 @pytest.mark.asyncio async def test_queued_job_waits_for_durable_upstream_after_slow_prepare(system, monkeypatch): import asyncio coordinator = system.app.state.coordinator original_prepare = system.provider.prepare_gpu_payload original_tick = coordinator.run_once release = asyncio.Event() ticks = 0 async def deferred_prepare(*args, **kwargs): await release.wait() return await original_prepare(*args, **kwargs) async def observed_tick(*args, **kwargs): nonlocal ticks ticks += 1 # 第一轮的100ms准备观察窗自然到期;只有后续tick才放行,确定性模拟慢I/O。 if ticks == 2: release.set() await original_tick(*args, **kwargs) monkeypatch.setattr(system.provider, "prepare_gpu_payload", deferred_prepare) monkeypatch.setattr(coordinator, "run_once", observed_tick) try: job_id, upstream = await asyncio.wait_for(queued_job(system), timeout=10) finally: release.set() assert isinstance(upstream, str) and upstream assert ticks >= 2 async with system.app.state.db.session() as session: job = await session.get(Job, job_id) assert job.upstream_id == upstream assert len(system.provider.submitted_payloads) == 1