"""Artifact-owned bounded CPU route job on the existing Worker reservation.""" import hashlib import json import logging import os import re import shutil import subprocess import time from contextlib import suppress from pathlib import Path from urllib.parse import quote from local_state import write_json from model_stack import ROOT from worker import terminate_episode def sha(path): with path.open('rb') as stream: return hashlib.file_digest(stream,'sha256').hexdigest() def prepare_route(client, request, state, isaac, job): if not re.fullmatch(r"[a-f0-9]{64}", request["key"]): raise ValueError("Invalid route preparation identity") endpoint='/worker/route-preparations/'+request['key'] last_pulse=-float('inf') def pulse(): nonlocal last_pulse if time.monotonic()-last_pulse>=1: client.request('/worker/heartbeat',{'instance_id':client.instance}) last_pulse=time.monotonic() target=state.parent/'assets/route-preparations'/request['key'] target.mkdir(parents=True,exist_ok=True) def execute(command, limit): with (target/'preparation.log').open('ab') as log: child=subprocess.Popen(command,stdout=log,stderr=subprocess.STDOUT, env={**os.environ,"OPENBLAS_NUM_THREADS":"2","OMP_NUM_THREADS":"2"}) job.assign(child) deadline=time.monotonic()+limit try: while child.poll() is None: pulse() if time.monotonic()>deadline: raise TimeoutError('Route preparation timed out') time.sleep(.5) if child.returncode: raise RuntimeError('Route preparation process failed') finally: if child.poll() is None: terminate_episode(child) try: world=request['world'] package=client.request('/worker/worlds/'+world['world_id']+'/project-assets') if package['world_sha256']!=world['sha256']: raise ValueError('Route world changed') item=next(a for a in package['artifacts'] if a['logical_path']==package['collision_path']) if item['sha256']!=request['identity']['collider_sha256']: raise ValueError('Route collider changed') sources=state.parent/'assets/route-sources' sources.mkdir(parents=True,exist_ok=True) packed=sources/(item['sha256']+'.glb') if not packed.exists() or sha(packed)!=item['sha256']: if shutil.disk_usage(sources).free < item['byte_length']+512*1024**2: raise RuntimeError('Insufficient route preparation space') client.download_asset('/api/v1/simulation-worlds/projects/'+package['project_id']+ '/artifacts/'+quote(item['logical_path'],safe='/'),item,packed,pulse=pulse) decoder=ROOT/'decode_collision.cjs' decoded=sources/(digest_name(item['sha256'],sha(decoder))+'.decoded.glb') receipt=decoded.with_suffix('.json') if not (decoded.exists() and receipt.exists() and json.loads(receipt.read_text())['sha256']==sha(decoded)): temporary=decoded.with_suffix('.part.glb') execute([shutil.which('node'),str(decoder),str(packed),str(temporary)],60) temporary.replace(decoded) write_json(receipt,{'sha256':sha(decoded),'source_sha256':item['sha256'],'decoder_sha256':sha(decoder)}) request_file=target/'request.json' write_json(request_file,request) result_file=target/'result.json' execute([str(isaac/'python.bat'),str(ROOT/'scene_route_field.py'), '--request',str(request_file),'--collider',str(decoded), '--output',str(result_file),'--field-cache',str(state.parent/'assets/route-fields')],480) if result_file.stat().st_size>4*1024**2: raise ValueError('Route artifact exceeds transport budget') result=json.loads(result_file.read_text(encoding='utf-8')) client.request(endpoint,{'action':'complete','result':result}) except Exception: logging.exception('Route preparation failed') with suppress(Exception): client.request(endpoint,{'action':'fail'}) def digest_name(*parts): return hashlib.sha256(':'.join(parts).encode()).hexdigest()