import secrets from sqlalchemy import select,func from .models import Job,utcnow from .v2_models import Execution async def begin_execution(session,job_id,phase_key="execute",resource_pool="cpu_media"): job=await session.get(Job,job_id) 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 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 (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,json 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 attempt0 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(json.dumps(result,sort_keys=True,separators=(",",":"),allow_nan=False).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,json 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"} digest=hashlib.sha256(json.dumps(result,sort_keys=True,separators=(",",":"),allow_nan=False).encode()).hexdigest() 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")