import secrets from sqlalchemy import select, func from app.models import Job, utcnow from app.models import Execution async def begin_execution(session, job_id, phase_key="execute", resource_pool="cpu_media"): job = await session.get(Job, job_id) if not job or job.deleted_at is not None: raise ValueError("Job is unavailable") ordinal = ( await session.scalar(select(func.max(Execution.ordinal)).where(Execution.job_id == job_id)) or 0 ) + 1 row = Execution( job_id=job_id, ordinal=ordinal, phase_key=phase_key, resource_pool=resource_pool, fence_token=secrets.token_hex(24), state="running", started_at=utcnow(), ) session.add(row) await session.flush() job.current_execution_id = row.id return row async def accept_manifest(session, execution_id, fence_token, manifest): row = await session.get(Execution, execution_id) if not row or row.fence_token != fence_token: return False job = await session.get(Job, row.job_id) if ( not job or job.deleted_at is not None or job.current_execution_id != execution_id or job.cancel_requested ): return False row.manifest_json = manifest row.state = "results_ready" row.finished_at = utcnow() return True async def request_control(session, job_id, desired_state, expected_execution_id=None): job = await session.get(Job, job_id) if ( not job or job.deleted_at is not None or (expected_execution_id and job.current_execution_id != expected_execution_id) ): return {"accepted": False} if job.state in {"succeeded", "failed", "cancelled", "timed_out"}: return {"accepted": False, "state": job.state} if job.desired_state != "cancel": job.desired_state = desired_state if desired_state == "cancel": job.cancel_requested = True return { "accepted": True, "execution_id": job.current_execution_id, "desired_state": job.desired_state, } async def observe_gpu_execution(session, job, remote): """Observe real upstream attempts without fabricating missed/queued claims. Return (accepted_snapshot, current_observed_execution). This runs inside the same transaction as the Job update/event, under the database unit lock. """ import hashlib if not job or job.deleted_at is not None: return (False, None) if remote.get("id") and remote["id"] != job.upstream_id: return (False, None) attempt = int(remote.get("attempt_count", job.attempt_count)) if attempt < 0: raise ValueError("Invalid upstream attempt") rows = list( ( await session.scalars( select(Execution) .where(Execution.job_id == job.id, Execution.phase_key.like("gpu:%")) .order_by(Execution.ordinal) ) ).all() ) highest = max( [job.attempt_count] + [(row.manifest_json or {}).get("upstream_attempt", 0) for row in rows] ) if attempt < highest: return (False, None) state = remote["state"] identity = f"{job.upstream_id}:{attempt}" if remote.get("execution_id") and remote["execution_id"] != identity: raise ValueError("Upstream execution identity mismatch") execution = next( (row for row in rows if (row.manifest_json or {}).get("upstream_execution_id") == identity), None, ) if ( execution and remote.get("fence_token") and ((execution.manifest_json or {}).get("upstream_fence") != remote["fence_token"]) ): return (False, None) if execution and execution.state in {"exited", "results_ready"}: if execution.state == "exited" and state in {"running", "succeeded"}: return (False, None) if execution.state == "results_ready" and state != "succeeded": return (False, None) unlaunched = remote.get("stage") == "launching" or ( "runner_pid" in remote and remote["runner_pid"] is None and ("started_at" in remote) and (remote["started_at"] is None) ) actual = attempt > 0 and ( state == "running" and (not unlaunched) or ( state in {"succeeded", "failed", "timed_out", "cancelled"} and (not unlaunched or execution is not None) ) ) if execution is None and actual: previous = ( await session.get(Execution, job.current_execution_id) if job.current_execution_id else None ) if previous and previous.state == "running": previous.state = "exited" previous.finished_at = utcnow() previous.manifest_json = {**(previous.manifest_json or {}), "superseded_by": identity} execution = await begin_execution(session, job.id, f"gpu:{attempt}", "new_gpu") execution.manifest_json = { "schema": 1, "kind": "upstream_gpu", "upstream_id": job.upstream_id, "upstream_execution_id": identity, "upstream_attempt": attempt, "upstream_fence": remote.get("fence_token") or identity, "local_fence": execution.fence_token, } if execution is None: no_runner = ( "runner_pid" in remote and remote["runner_pid"] is None or remote.get("cleanup_ack") is True ) if no_runner and state in {"queued", "paused", "cancelled"} and job.current_execution_id: previous = await session.get(Execution, job.current_execution_id) if previous and previous.phase_key.startswith("gpu:") and (previous.state == "running"): previous.state = "exited" previous.finished_at = utcnow() previous.manifest_json = { **(previous.manifest_json or {}), "cleanup_ack": True, "ack_observed_attempt": attempt, } return (True, None) manifest = dict(execution.manifest_json or {}) manifest["observed_state"] = state if state == "succeeded": result = remote.get("result") or {} digest = hashlib.sha256(canonical_gpu_result(result).encode()).hexdigest() if execution.state == "results_ready" and manifest.get("result_hash") != digest: return (False, None) manifest["result_hash"] = digest execution.state = "results_ready" execution.finished_at = utcnow() elif state in {"failed", "cancelled", "timed_out"}: execution.state = "exited" execution.finished_at = utcnow() elif state in {"queued", "paused"}: no_runner = ( "runner_pid" in remote and remote["runner_pid"] is None or remote.get("cleanup_ack") is True ) if no_runner: execution.state = "exited" execution.finished_at = utcnow() manifest["cleanup_ack"] = True execution.manifest_json = manifest return (True, execution) def gpu_result_fence(execution): manifest = execution.manifest_json or {} return { "execution_id": execution.id, "fence_token": execution.fence_token, "upstream_execution_id": manifest.get("upstream_execution_id"), "upstream_attempt": manifest.get("upstream_attempt"), "result_hash": manifest.get("result_hash"), } async def gpu_publication_matches(session, job, fence): import hashlib if not job or job.deleted_at is not None: return False if not fence: return job.current_execution_id is None if job.current_execution_id != fence.get("execution_id"): return False execution = await session.get(Execution, job.current_execution_id) if ( not execution or execution.job_id != job.id or execution.state != "results_ready" or (execution.fence_token != fence.get("fence_token")) ): return False manifest = execution.manifest_json or {} result = { key: value for key, value in (job.upstream_result or {}).items() if key != "_visual_execution" } try: serialized = result.get("_visual_result_json") if serialized is not None: if set(result) != {"_visual_result_json"}: return False gpu_result(job) else: serialized = canonical_gpu_result(result) digest = hashlib.sha256(serialized.encode()).hexdigest() except (ValueError, TypeError, AttributeError): return False return ( manifest.get("upstream_execution_id") == fence.get("upstream_execution_id") and manifest.get("upstream_attempt") == job.attempt_count == fence.get("upstream_attempt") and (manifest.get("result_hash") == digest == fence.get("result_hash")) ) def canonical_gpu_result(result): import json if not isinstance(result, dict) or {"_visual_execution", "_visual_result_json"} & result.keys(): raise ValueError("Invalid upstream result envelope") return json.dumps(result, sort_keys=True, separators=(",", ":"), allow_nan=False) def packed_gpu_result(result, fence): # MySQL JSON会将某些double重编码为相邻值。将摘要覆盖的原JSON保存为字符串, # 恢复时仍逐字节校验原SHA,不对数值舍入,也不削弱attempt/fence约束。 return {"_visual_result_json": canonical_gpu_result(result), "_visual_execution": dict(fence)} def gpu_result(job): import json value = job.upstream_result or {} if "_visual_result_json" not in value: return {key: child for key, child in value.items() if key != "_visual_execution"} if set(value) != {"_visual_result_json", "_visual_execution"} or not isinstance( value["_visual_result_json"], str ): raise ValueError("Invalid persisted GPU result envelope") result = json.loads(value["_visual_result_json"]) if canonical_gpu_result(result) != value["_visual_result_json"]: raise ValueError("Noncanonical persisted GPU result") return result async def recover_legacy_gpu_result(session, job, remote, fence): import hashlib if ( not job or job.deleted_at is not None or job.cancel_requested or "_visual_result_json" in (job.upstream_result or {}) ): return False if not fence or job.current_execution_id != fence.get("execution_id"): return False execution = await session.get(Execution, job.current_execution_id) if ( not execution or execution.state != "results_ready" or execution.job_id != job.id or execution.fence_token != fence.get("fence_token") ): return False manifest = execution.manifest_json or {} if ( remote.get("id") != job.upstream_id or remote.get("state") != "succeeded" or type(remote.get("attempt_count")) is not int ): return False if not ( remote["attempt_count"] == job.attempt_count == fence.get("upstream_attempt") == manifest.get("upstream_attempt") ): return False identity = f"{job.upstream_id}:{job.attempt_count}" if not ( remote.get("execution_id") == identity == fence.get("upstream_execution_id") == manifest.get("upstream_execution_id") ): return False if manifest.get("upstream_fence") != (remote.get("fence_token") or identity): return False result = remote.get("result") digest = hashlib.sha256(canonical_gpu_result(result).encode()).hexdigest() if not (digest == manifest.get("result_hash") == fence.get("result_hash")): return False job.upstream_result = packed_gpu_result(result, fence) return await gpu_publication_matches(session, job, fence)