Files
WoW-Hybrid-gateway/ops/spell_content_compare.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

223 lines
17 KiB
Python

#!/usr/bin/env python3
"""Compare pinned173-column Spell source versions without converting content.
Localized offsets are resolved through each file's own string block. Numeric
words, including floating-point values, remain exact unsigned32-bit patterns.
"""
import argparse
from collections import Counter
import hashlib
import json
import os
from pathlib import Path
import re
import struct
from turtle_data import DBC, spell_layout
from octo_client_data import canonical_sha256,observed_analysis_context
from item_package_preflight import bounded_digest
ROOT=Path(__file__).resolve().parents[1]
DEFAULT_DBD=Path.home()/'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions/Spell.dbd'
BUILD='BUILD 1.12.0.5595-1.12.3.6141'
# Tortoise src/shared/Common.h:210-220. ruRU is explicitly not in Vanilla.
LOCALES=('enUS','koKR','frFR','deDE','zhCN','zhTW','esES','esMX')
MAX_JSON=128*1024*1024
MAX_CODE_BYTES=1048576
MAX_EVENTS=2000000
REVIEWED_COLUMN_SHA256='eea86dababc363184c874ee787b4b404f033b8a4f37a018418be257aba61c413'
def sha(raw):return hashlib.sha256(raw).hexdigest()
def digest(value):
if not isinstance(value,str) or not re.fullmatch('[0-9a-f]{64}',value):raise ValueError('Require explicit lowercase SHA256 pin')
return value
def locale_slot(locale):
if locale=='enGB':locale='enUS'
if locale not in LOCALES:raise ValueError('Missing or unsupported original8-slot locale')
return locale,LOCALES.index(locale)
def reviewed_columns(raw,expected_sha256,expected_offsets):
"""Pure counterpart to the existing spell_layout disk-column resolver."""
if not isinstance(raw,bytes) or not raw or len(raw)>1048576 or sha(raw)!=digest(expected_sha256):raise ValueError('Pinned Spell DBD content differs')
source=raw.decode('utf-8');declarations=source.split('\n\n',1)[0].splitlines()
if not declarations or declarations[0]!='COLUMNS' or source.count(BUILD+'\n')!=1:raise ValueError('Missing or ambiguous reviewed Spell DBD build')
kinds={}
for line in declarations[1:]:
parts=line.split()
if len(parts)>=2:kinds[parts[1]]=parts[0].split('<',1)[0]
block=source.split(BUILD+'\n',1)[1].split('\n\n',1)[0]
columns=[];offsets={}
for line in block.splitlines():
match=re.fullmatch(r'(?:\$[^$]+\$)?(\w+)(?:<\d+>)?(?:\[(\d+)\])?',line)
if not match:raise ValueError('Unreviewed Spell DBD field syntax')
name,count=match.groups();kind=kinds.get(name)
if kind not in ('int','float','string','locstring') or name in offsets:raise ValueError('Unknown or repeated Spell DBD field')
offsets[name]=len(columns)
for array_index in range(int(count or 1)):
base=dict(field=name,array_index=array_index if count else None,declared_type=kind)
if kind=='locstring':
for slot,locale in enumerate(LOCALES):columns.append(dict(base,index=len(columns),kind='localized-text',locale=locale,locale_slot=slot))
columns.append(dict(base,index=len(columns),kind='localized-flags'))
else:columns.append(dict(base,index=len(columns),kind='string' if kind=='string' else 'numeric-bits'))
if len(columns)!=173 or offsets!=expected_offsets:raise ValueError('Reviewed Spell DBD layout changed')
localized={r['field'] for r in columns if r['kind']=='localized-text'}
if localized!={'Name_lang','NameSubtext_lang','Description_lang','AuraDescription_lang'}:raise ValueError('Reviewed Spell localized fields changed')
if canonical_sha256(columns)!=REVIEWED_COLUMN_SHA256:raise ValueError('Reviewed Spell column types or semantics changed')
return columns
def _observed_context(table,inventory,locale):
if not isinstance(inventory,dict) or type(inventory.get('schema_version'))is not int or inventory.get('schema_version')!=1 or inventory.get('kind')!='octo-observed-partial-dependency-inventory' or inventory.get('second_input_pass_verified') is not True:raise ValueError('Require validated observed source inventory')
validation=inventory.get('validation',{})
if validation.get('kind')!='octo-loaded-content-validation' or validation.get('trace_contracts_validated') is not True or validation.get('captured_content_rehashed') is not True:raise ValueError('Observed source validation is incomplete')
matching=[r for r in inventory.get('inventories',[])if r.get('table')=='Spell']
checked=[r for r in validation.get('tables',[])if r.get('table')=='Spell']
if len(matching)!=1 or len(checked)!=1:raise ValueError('Require one validated observed Spell table')
source=matching[0];checked=checked[0];identity=source.get('source_identity',{})
context=observed_analysis_context(inventory,validation,identity)
if not isinstance(context['source_installation'],str) or not context['source_installation'].startswith('/'):raise ValueError('Observed installation identity is missing')
digest(context['scan_sha256'])
if not isinstance(context['client_identity'],dict):raise ValueError('Observed client identity is missing')
digest(context['client_identity'].get('client_sha256'))
if locale_slot(context['client_identity'].get('locale'))[0]!=locale:raise ValueError('Observed locale differs from comparison locale')
for key,value in context.items():
if validation.get(key)!=value:raise ValueError('Observed validation context differs')
dataset='observed-content:'+canonical_sha256(context)
if inventory.get('analysis_dataset')!=dataset:raise ValueError('Observed analysis dataset differs')
expected=digest(table.digest())
if source.get('candidate_sha256')!=expected or identity.get('content_sha256')!=expected or (checked.get('sha256'),checked.get('rows'),checked.get('fields'),checked.get('bytes'))!=(expected,table.count,173,len(table.bytes)):raise ValueError('Observed capture hash/schema differs from inventory')
if checked.get('content_status')!='matched-observed-bytes' or source.get('schema',{}).get('status')!='reviewed-disk-shape' or source.get('schema',{}).get('fields')!=173:raise ValueError('Observed Spell schema is not reviewed')
for key,value in dict(dataset=dataset,provenance='selected-by-pinned-evidence',selection_scope='observed-file-content-only',**context).items():
if identity.get(key)!=value:raise ValueError('Observed table source identity differs')
for key in ('observation_sha256','loader_analysis_sha256'):
if digest(identity.get(key))!=digest(validation.get(key)):raise ValueError('Observed provenance pin differs')
records=source.get('records')
if not isinstance(records,list) or len(records)!=table.count:raise ValueError('Observed inventory record count differs')
seen=set()
for row in records:
key=row.get('identity')
if not isinstance(key,list) or len(key)!=2 or key[0]!='Spell' or type(key[1]) is not int or key[1] in seen or key[1] not in table.by_id:raise ValueError('Observed record identity differs')
seen.add(key[1]);raw=table.by_id[key[1]]
if row.get('raw_fields')!=list(raw) or row.get('raw_sha256')!=sha(struct.pack('<173I',*raw)):raise ValueError('Observed record bits differ from capture')
result=dict(context,dataset=dataset,content_sha256=expected,observation_sha256=validation['observation_sha256'],loader_analysis_sha256=validation['loader_analysis_sha256'])
if 'read_contract' in context:result['transmog_analysis_sha256']=identity['transmog_analysis_sha256']
return result
def compare_spell_content(observed,baseline,inventory,baseline_pin,dbd_source,*,dbd_sha256,locale,layout_offsets):
"""Pure comparison of already-decoded, pinned source tables; no I/O."""
locale,_=locale_slot(locale)
if observed.fields!=173 or baseline.fields!=173:raise ValueError('Both Spell source schemas must be reviewed173-column WDBC')
if not isinstance(baseline_pin,dict) or baseline_pin.get('role') not in ('installed-turtle-client','local-tortoise-server'):raise ValueError('Require explicit local baseline role')
if baseline.digest()!=digest(baseline_pin.get('sha256')):raise ValueError('Pinned baseline content differs')
if locale_slot(baseline_pin.get('locale'))[0]!=locale:raise ValueError('Baseline locale differs from comparison locale')
source=_observed_context(observed,inventory,locale);columns=reviewed_columns(dbd_source,dbd_sha256,layout_offsets)
strings={}
def text(table,value):
key=(id(table),value)
if key not in strings:strings[key]=table.string(value)
return strings[key]
string_columns=[r for r in columns if r['kind'] in ('localized-text','string')]
# Validate all source strings, including newly added/removed records.
for table in (observed,baseline):
for row in table.rows:
for column in string_columns:text(table,row[column['index']])
current=set(observed.by_id);previous=set(baseline.by_id);common=sorted(current&previous)
changed=[];relocations=[];raw_changed=[];raw_only=[];column_counts=Counter();relocation_counts=Counter();localized_changes=[];events=0
for ident in common:
before=baseline.by_id[ident];after=observed.by_id[ident];changes=[];moved=[]
if before!=after:raw_changed.append(ident)
for column in columns:
index=column['index'];a,b=before[index],after[index];kind=column['kind']
if kind in ('localized-text','string'):
old,new=text(baseline,a),text(observed,b)
if old!=new:
change=dict(column,before=old,after=new,before_offset=a,after_offset=b);changes.append(change)
if kind=='localized-text':localized_changes.append(dict(spell_id=ident,**change))
elif a!=b:moved.append(dict(column,before_offset=a,after_offset=b,text_sha256=sha(old.encode('utf-8'))))
elif a!=b:changes.append(dict(column,before_u32=a,after_u32=b,before_hex=f'{a:08x}',after_hex=f'{b:08x}'))
events+=len(changes)+len(moved)
if events>MAX_EVENTS:raise ValueError('Spell comparison event bound exceeded')
if changes:
changed.append(dict(id=ident,changes=changes))
column_counts.update(row['index']for row in changes)
elif before!=after:raw_only.append(ident)
if moved:
relocations.append(dict(id=ident,columns=moved));relocation_counts.update(row['index']for row in moved)
index={row['index']:row for row in columns}
counts=dict(baseline_records=baseline.count,observed_records=observed.count,common_records=len(common),added_records=len(current-previous),removed_records=len(previous-current),semantic_changed_records=len(changed),semantic_unchanged_records=len(common)-len(changed),raw_record_rows_changed=len(raw_changed),raw_only_changed_records=len(raw_only),string_offset_relocations=sum(relocation_counts.values()),localized_text_changes=len(localized_changes),localized_flag_changes=sum(column_counts[c['index']]for c in columns if c['kind']=='localized-flags'))
return dict(schema_version=1,kind='pinned-source-spell-semantic-comparison',comparison_locale=locale,locale_slots=list(LOCALES),source=source,
baseline=dict(baseline_pin,content_sha256=baseline.digest()),spell_dbd_sha256=dbd_sha256,spell_dbd_build=BUILD,counts=counts,
added_ids=sorted(current-previous),removed_ids=sorted(previous-current),changed_records=changed,
changed_columns=[dict(index[i],records=count)for i,count in sorted(column_counts.items())],
localized_text_changes=localized_changes,string_offset_relocations=relocations,raw_only_changed_ids=raw_only,
relocated_columns=[dict(index[i],records=count)for i,count in sorted(relocation_counts.items())],
numeric_comparison='exact-u32-including-float-raw-bits',localized_flag_interpretation='raw-u32-no-gameplay-meaning-inferred',
converted=False,engine_loaded=False,gameplay_verified=False,server_rules_equivalent=False,postload_semantics_verified=False,
limits=['The supplied observed inventory is checked for internal provenance and exact captured record bits; this does not independently reproduce its runtime observation.',
'Reviewed hook-profile contexts retain their distinct dataset identity; legacy, different read contracts and different loader profiles are not silently joined.',
'Raw-only string offset relocations are excluded from semantic changes only when the exact resolved text is equal.',
'Numeric changes retain every raw bit, including floating-point encodings; their gameplay impact is not inferred.',
'Source data differences do not establish server spell behavior, post-load hooks, destination conversion, engine loading or gameplay compatibility.'])
class BytesPath:
def __init__(self,name,raw):self.name=name;self.raw=raw
def read_bytes(self):return self.raw
def read_input(path,limit):
path=Path(path)
if path.is_symlink() or not path.is_file() or not 0<path.stat().st_size<=limit:raise ValueError('Require regular bounded pinned input')
with path.open('rb')as stream:raw=stream.read(limit+1)
if len(raw)>limit:raise ValueError('Input grew beyond bound')
if not raw:raise ValueError('Input became empty')
return path,raw,sha(raw)
def run(inventory_path,observed_path,baseline_path,dbd_path,output,*,baseline_sha256,baseline_role,baseline_locale,dbd_sha256,locale):
code_paths={name:Path(__file__).resolve().with_name(filename)for name,filename in [('comparison','spell_content_compare.py'),('dbc_decoder','turtle_data.py'),('source_context','octo_client_data.py'),('bounded_input_io','item_package_preflight.py')]}
code_pins={name:bounded_digest(path,MAX_CODE_BYTES)for name,path in code_paths.items()}
limits=dict(inventory=MAX_JSON,observed=67108864,baseline=67108864,dbd=1048576)
inputs={name:read_input(path,limits[name])for name,path in [('inventory',inventory_path),('observed',observed_path),('baseline',baseline_path),('dbd',dbd_path)]}
inventory=json.loads(inputs['inventory'][1]);observed=DBC(BytesPath('Spell.dbc',inputs['observed'][1]),173);baseline=DBC(BytesPath('Spell.dbc',inputs['baseline'][1]),173)
result=compare_spell_content(observed,baseline,inventory,dict(sha256=baseline_sha256,role=baseline_role,locale=baseline_locale),inputs['dbd'][1],dbd_sha256=dbd_sha256,locale=locale,layout_offsets=spell_layout())
result['input_file_sha256']={name:row[2]for name,row in sorted(inputs.items())}
result['tool_sha256']=code_pins['comparison'];result['implementation_file_sha256']=code_pins
result['reviewed_column_sha256']=REVIEWED_COLUMN_SHA256
if any(bounded_digest(path,limits[name])!=pinned for name,(path,_,pinned) in inputs.items()) or any(bounded_digest(path,MAX_CODE_BYTES)!=code_pins[name]for name,path in code_paths.items()):raise ValueError('Pinned input or implementation changed before publication')
result['second_input_pass_verified']=True
encoded=(json.dumps(result,sort_keys=True,ensure_ascii=False,separators=(',',':'),allow_nan=False)+'\n').encode()
if len(encoded)>MAX_JSON:raise ValueError('Spell comparison output bound exceeded')
output=Path(output).absolute()
if not output.is_relative_to(ROOT/'runtime') or output.exists() or output.is_symlink() or output.parent.resolve()!=output.parent:raise ValueError('Require new runtime comparison output')
staging=output.with_suffix(output.suffix+'.staging')
fd=os.open(staging,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600)
with os.fdopen(fd,'wb')as stream:stream.write(encoded)
if sha(staging.read_bytes())!=sha(encoded):raise ValueError('Staged comparison changed before publication')
os.link(staging,output)
return result
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--observed-inventory',type=Path,required=True);parser.add_argument('--observed-spell',type=Path,required=True)
parser.add_argument('--baseline-spell',type=Path,required=True);parser.add_argument('--baseline-sha256',required=True)
parser.add_argument('--baseline-role',choices=('installed-turtle-client','local-tortoise-server'),required=True);parser.add_argument('--baseline-locale',required=True)
parser.add_argument('--spell-dbd',type=Path,default=DEFAULT_DBD);parser.add_argument('--dbd-sha256',required=True);parser.add_argument('--locale',required=True)
parser.add_argument('--output',type=Path,required=True);args=parser.parse_args()
try:
result=run(args.observed_inventory,args.observed_spell,args.baseline_spell,args.spell_dbd,args.output,baseline_sha256=args.baseline_sha256,baseline_role=args.baseline_role,baseline_locale=args.baseline_locale,dbd_sha256=args.dbd_sha256,locale=args.locale)
print(json.dumps(dict(kind=result['kind'],counts=result['counts'],converted=False,engine_loaded=False,gameplay_verified=False),indent=2));return 0
except (ValueError,OSError,UnicodeError,KeyError,TypeError)as error:
print(json.dumps(dict(status='comparison-rejected',error_type=type(error).__name__,reason=str(error)),indent=2));return 1
if __name__=='__main__':raise SystemExit(main())