Files
WoW-Hybrid-gateway/ops/content_batch_jobs.py
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

188 lines
12 KiB
Python

#!/usr/bin/env python3
"""Resume serial offline jobs around existing converters, not another converter.
Blocked/failed groups do not prevent independent jobs. Each command owns a fresh
output directory; installation and client interaction are deliberately separate.
Receipts pin declared inputs and every output. Never run commands through a shell.
"""
import argparse
import fcntl
import hashlib
import json
from pathlib import Path
import re
import subprocess
import sys
import time
ROOT=Path(__file__).resolve().parents[1]
TOOLS={'m2_equipment_convert.py','item_model_assets.py','item_model_resources.py',
'content_package_stage.py','spell_crafting_compat.py','item_source_corrections.py','casc_asset_package.py',
'creature_model_preflight.py'}
def digest(path):
if path.is_symlink() or not path.is_file():raise ValueError('Regular job input/output required')
if path.stat().st_size>536870912:raise ValueError('Job file exceeds512MiB')
h=hashlib.sha256()
with path.open('rb')as stream:
for block in iter(lambda:stream.read(1048576),b''):h.update(block)
return h.hexdigest()
def pins(paths):
if not 1<=len(paths)<=16384:raise ValueError('Bounded complete input/output list required')
return {str(p):digest(p)for p in sorted(set(paths),key=str)}
def atomic(path,value):
temp=path.with_suffix(path.suffix+'.new')
with temp.open('w')as stream:json.dump(value,stream,sort_keys=True,indent=2);stream.write('\n')
temp.replace(path)
def input_paths(job,tool):
paths=[ROOT/'ops/content_batch_jobs.py',tool]+[Path(s)if Path(s).is_absolute()else ROOT/s for s in job['inputs']]
if tool.name=='m2_equipment_convert.py':
# Pin all actual model inputs, not just the list naming them. The
# existing converter independently rechecks their declared hashes.
command=job['command']
if command.count('--source-manifest')!=1:raise ValueError('One model source manifest required')
at=command.index('--source-manifest')+1
if at>=len(command):raise ValueError('Missing model source manifest')
manifest=Path(command[at]);manifest=manifest if manifest.is_absolute()else ROOT/manifest
if manifest.stat().st_size>8388608:raise ValueError('Model source manifest bound')
matches=json.loads(manifest.read_text()).get('matches',[])
if not isinstance(matches,list)or not 1<=len(matches)<=4096:raise ValueError('Model source candidate bound')
paths.append(manifest)
for row in matches:
if not row.get('member','').endswith('.m2'):continue
name=row.get('file','')
if not re.fullmatch('[0-9a-f]{64}\\.m2',name):raise ValueError('Pinned model input filename required')
paths.append(manifest.parent/name)
elif tool.name in('item_model_assets.py','casc_asset_package.py'):
command=job['command']
# This queue uses registration/staging only, never a fresh extraction.
framing=tool.name=='casc_asset_package.py'and command.count('--stage-framed-assets')==1
flags=(('--source-manifest','--native-context','--reuse-directory')if framing else
('--source-manifest','--native-encoding')if tool.name=='casc_asset_package.py'else
('--source-manifest','--conversion-manifest','--baseline-manifest','--native-root'))
if tool.name=='casc_asset_package.py'and not framing and command.count('--verify-native-content')!=1:raise ValueError('Only offline CASC staging or read-only reuse proof is supported')
for flag in flags:
if command.count(flag)!=1:raise ValueError('Complete offline asset-stage inputs required')
at=command.index(flag)+1
if at>=len(command):raise ValueError('Missing asset-stage input')
path=Path(command[at]);path=path if path.is_absolute()else ROOT/path
if flag=='--native-context':
paths.extend(path/name for name in ('target-encoding.bin','target-download.bin','native-tvfs-default.bin','native-vfs-root.bin','download-native-controls.json','tvfs-default-identity.json'))
continue
if flag=='--reuse-directory':
proof=path/'report.json'
if proof.stat().st_size>33554432:raise ValueError('Reuse report byte bound')
paths.append(proof);matches=json.loads(proof.read_text()).get('matches',[])
if not isinstance(matches,list)or len(matches)>4096:raise ValueError('Reuse payload count bound')
for row in matches:
key=row.get('content_key','')
if not isinstance(key,str)or not re.fullmatch('[0-9a-f]{32}',key):raise ValueError('Pinned reuse content key required')
paths.append(path/(key+'.bin'))
continue
paths.append(path)
if flag in('--native-root','--native-encoding'):continue
if path.stat().st_size>67108864:raise ValueError('Asset manifest byte bound')
document=json.loads(path.read_text());rows=[]
if document.get('root')and (path.parent/'root.bin').exists():paths.append(path.parent/'root.bin')
rows.extend(document.get('matches',[]));rows.extend(document.get('assets',[]))
for record in document.get('records',[]):rows.extend(record.get('outputs',[]))
if len(rows)>16384:raise ValueError('Asset input count bound')
for row in rows:
name=row.get('file','')
if not isinstance(name,str)or not name or len(name)>255 or Path(name).name!=name or name in('.','..'):raise ValueError('Flat asset input filename required')
paths.append(path.parent/name)
return paths
def validate(plan):
if plan.get('schema_version')!=1 or not isinstance(plan.get('jobs'),list)or not 1<=len(plan['jobs'])<=128:raise ValueError('Typed bounded batch jobs required')
seen=set()
for job in plan['jobs']:
name=job.get('id','')
if not re.fullmatch('[a-z][a-z0-9-]{0,63}',name)or name in seen:raise ValueError('Unique job ID required')
deps=job.get('depends_on',[])
if not isinstance(deps,list)or len(deps)!=len(set(deps))or not set(deps)<=seen:raise ValueError('Jobs must be in dependency order')
seen.add(name)
if job.get('blocked')or job.get('deferred'):
reason=job.get('blocked')or job.get('deferred')
if not isinstance(reason,str)or job.get('command'):raise ValueError('Unready jobs cannot execute')
continue
cmd=job.get('command',[])
if (not isinstance(cmd,list)or len(cmd)<3 or cmd[0]not in TOOLS or
any(not isinstance(s,str)or not s or '\0'in s for s in cmd)or cmd.count('{output}')!=1):raise ValueError('Existing offline tool and one isolated output required')
inputs=job.get('inputs',[])
if not isinstance(inputs,list)or not inputs or any(not isinstance(s,str)or not s for s in inputs):raise ValueError('Declared job inputs required')
if type(job.get('timeout_seconds'))is not int or not 1<=job['timeout_seconds']<=3600:raise ValueError('Bounded job timeout required')
return plan
def run(plan_path,output,*,execute=False,only=None):
plan_path=Path(plan_path);plan=validate(json.loads(plan_path.read_text()))
selected=None
if only is not None:
known={j['id']:j for j in plan['jobs']}
if not isinstance(only,(list,tuple))or not only or any(not isinstance(n,str)or n not in known for n in only):
raise ValueError('Known canonical job selection required')
selected=set(only);pending=list(selected)
while pending:
for dependency in known[pending.pop()].get('depends_on',[]):
if dependency not in selected:selected.add(dependency);pending.append(dependency)
output=Path(output).absolute()
if not output.is_relative_to(ROOT/'runtime')or output.is_symlink()or output.resolve()!=output:raise ValueError('Owned runtime job directory required')
output.mkdir(parents=True,exist_ok=True)
with (output/'queue.lock').open('a')as lock:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
statuses={};results=[];directories={}
for job in plan['jobs']:
if selected is not None and job['id']not in selected:continue
name=job['id'];receipt=output/(name+'.json')
row=dict(id=name,installed=False,engine_loaded=False,gameplay_verified=False)
if job.get('blocked'):row.update(status='blocked',reason=job['blocked'])
elif job.get('deferred'):row.update(status='deferred',reason=job['deferred'])
elif any(statuses[d]not in('complete','reused')for d in job.get('depends_on',[])):row.update(status='blocked',reason='dependency-not-complete')
else:
def expand(value):
for dependency in job.get('depends_on',[]):value=value.replace('{'+dependency+'}',directories[dependency])
if ('{'in value or '}'in value)and value!='{output}':raise ValueError('Undeclared job-output reference')
return value
command=[expand(value)for value in job['command']];tool=ROOT/'ops'/command[0]
try:
effective=dict(job,command=command,inputs=[expand(value)for value in job['inputs']])
paths=input_paths(effective,tool)
before=pins(paths);fingerprint=dict(command=command,inputs=before)
prior=json.loads(receipt.read_text())if receipt.exists()else None
if prior and prior.get('status')=='complete'and prior.get('fingerprint')==fingerprint and pins([Path(p)for p in prior['outputs']])==prior['outputs']:
directory=prior.get('output_directory')
if not isinstance(directory,str)or not Path(directory).is_relative_to(output):raise ValueError('Receipt output ownership differs')
row.update(status='reused',receipt=str(receipt),output_directory=directory)
elif not execute:row.update(status='ready',command=command)
else:
# Retain failed/older directories. A new attempt never
# overwrites a converter's incomplete artifacts.
attempt=output/(name+'-'+str(time.time_ns()))
argv=[sys.executable,str(tool)]+[str(attempt)if s=='{output}'else s for s in command[1:]]
log=output/(attempt.name+'.log');start=time.monotonic()
with log.open('xb')as stream:
process=subprocess.run(argv,cwd=ROOT,stdout=stream,stderr=subprocess.STDOUT,timeout=job['timeout_seconds'],check=False)
if process.returncode:raise ValueError('Converter failed; inspect '+str(log))
if pins(paths)!=before:raise ValueError('Declared input changed during job')
files=list(attempt.rglob('*'))
if not files or any(p.is_symlink()for p in files):raise ValueError('Missing or linked job outputs')
result=dict(status='complete',fingerprint=fingerprint,output_directory=str(attempt),outputs=pins([p for p in files if p.is_file()]),log=str(log),elapsed_seconds=round(time.monotonic()-start,3))
atomic(receipt,result);row.update(status='complete',receipt=str(receipt),output_directory=str(attempt),elapsed_seconds=result['elapsed_seconds'])
except (ValueError,OSError,subprocess.TimeoutExpired)as error:
row.update(status='failed',reason=str(error))
statuses[name]=row['status'];results.append(row)
if row['status']in('complete','reused'):directories[name]=row['output_directory']
print(json.dumps(row),flush=True)
atomic(output/'status.json',dict(plan_sha256=digest(plan_path),jobs=results,installed=False,engine_loaded=False))
return results
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--plan',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
p.add_argument('--run',action='store_true',help='Execute ready offline jobs; default only checks readiness/receipts')
p.add_argument('--only',action='append',help='Run selected canonical jobs and their dependency closure; preserve one plan')
a=p.parse_args();run(a.plan,a.output,execute=a.run,only=a.only)