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

291 lines
21 KiB
Python

#!/usr/bin/env python3
"""Read bounded public item/spell definitions from the authorized local Tortoise DB.
No account/character queries or writes. Hex output avoids mysql batch escaping
changing literal newlines, backslashes or Unicode in names and descriptions.
"""
import argparse,hashlib,json,re,struct,subprocess
from pathlib import Path
from local_tortoise import db,ROOT
from classic_query_cache import read_classic_query_cache
SERVER=Path.home()/'Servers/tortoise-wow'
def server_git_revision():
"""Source checkout identity only; never claim the running binary matches."""
value=subprocess.check_output(['git','-C',str(SERVER),'rev-parse','HEAD'],text=True,stderr=subprocess.DEVNULL).strip()
if not re.fullmatch(r'[0-9a-f]{40}(?:[0-9a-f]{24})?',value):raise ValueError('Invalid local server source revision')
return value
def _encoded(value):return (json.dumps(value,ensure_ascii=False,sort_keys=True,indent=2,allow_nan=False)+'\n').encode('utf-8')
def _sha(value):return hashlib.sha256(value).hexdigest()
def read_item_cache_prefix(path):
"""Read bounded public item references from the installed classic WDB.
This is the cached prefix only, not a complete item-template converter or
evidence that cached records still match a live realm. The remaining bytes
are hashed and retained opaque. In particular no spell/visual/asset IDs are
invented from the item's name.
"""
path=Path(path)
raw,cached_rows=read_classic_query_cache(path,signature=b'BDIW',min_payload=92)
names=('display_id','quality','flags','buy_price','sell_price','inventory_type',
'allowable_class','allowable_race','item_level','required_level','required_skill',
'required_skill_rank','required_spell','required_honor_rank','required_city_rank',
'required_reputation_faction','required_reputation_rank','max_count','stackable','container_slots')
records=[]
for ident,body in cached_rows:
size=len(body)
cls,sub=struct.unpack_from('<II',body);cursor=8;labels=[]
for _ in range(4):
end=body.find(b'\0',cursor,min(cursor+257,len(body)))
if end<0:raise ValueError('Classic cached item name bound')
labels.append(body[cursor:end].decode('utf-8'));cursor=end+1
if not labels[0] or cursor+80>len(body):raise ValueError('Truncated cached item prefix')
values=dict(zip(names,struct.unpack_from('<20I',body,cursor)))
for key in ('allowable_class','allowable_race'):
if values[key]&0x80000000:values[key]-=0x100000000
records.append(dict(entry=ident,name=labels[0],**{'class':cls},subclass=sub,**values,
cached_payload_sha256=_sha(body),cached_payload_bytes=size))
if len(records)>100000:raise ValueError('Classic item-cache record count bound')
return dict(kind='installed-classic-item-cache-prefix',schema_version=1,build=5875,
sha256=_sha(raw),locale_bytes_hex=raw[8:12].hex(),records=records,
full_item_template_decoded=False,live_server_equality_verified=False)
def cached_name_corrections(templates,cache):
"""Explicit lossless UTF8/cp1252 mojibake repairs corroborated by cache.
Changed gameplay fields or genuinely different names are excluded. Returned
records are build inputs only; they do not edit the DB or install client data.
"""
if cache.get('kind')!='installed-classic-item-cache-prefix':raise ValueError('Reviewed cached reference input required')
by_id={r['entry']:r for r in templates}
if len(by_id)!=len(templates):raise ValueError('Duplicate source template identity')
out=[]
for r in cache['records']:
source=by_id.get(r['entry'])
if source is None or source['name']==r['name']:continue
try:repaired=source['name'].encode('cp1252').decode('utf-8')
except (UnicodeEncodeError,UnicodeDecodeError):continue
if repaired!=r['name']:continue
compared={k:v for k,v in r.items()if k not in ('name','cached_payload_sha256','cached_payload_bytes')}
if any(k not in source or source[k]!=v for k,v in compared.items()):continue
out.append(dict(entry=r['entry'],original_name=source['name'],display_name=repaired,
policy='lossless-cp1252-to-utf8-roundtrip-matching-cached-item-prefix',
source_cache_sha256=cache['sha256'],cached_payload_sha256=r['cached_payload_sha256']))
return sorted(out,key=lambda r:r['entry'])
def _json_rows(raw):
if not isinstance(raw,str) or len(raw)>134217728:raise ValueError('Public JSON query size bound')
def unique(pairs):
row={}
for key,value in pairs:
if key in row:raise ValueError('Duplicate public JSON field')
row[key]=value
return row
rows=[]
for line in raw.splitlines():
if not re.fullmatch(r'(?:[0-9a-fA-F]{2})+',line):raise ValueError('Invalid public JSON hex encoding')
row=json.loads(bytes.fromhex(line).decode('utf-8'),object_pairs_hook=unique)
if not isinstance(row,dict):raise ValueError('Expected public row object')
rows.append(row)
return rows
def _template_table(table):
if table not in('item_template','spell_template'):raise ValueError('Only public local item/spell template tables are allowed')
return table
def _bulk_schema(query,table='item_template'):
table=_template_table(table)
raw=query('SHOW COLUMNS FROM tw_world.'+table+';')
if not isinstance(raw,str) or len(raw)>1048576:raise ValueError('Item schema size bound')
columns=[]
for line in raw.splitlines():
parts=line.split('\t')
# The existing mysql helper strips final empty batch columns. DDL
# below preserves the complete definition, including literal defaults.
if not 3<=len(parts)<=6:raise ValueError('Unexpected item column metadata')
parts+=['']*(6-len(parts));name,kind,nullable,key,default,extra=parts
if not re.fullmatch(r'[A-Za-z_][A-Za-z_0-9]*',name) or not kind or nullable not in ('YES','NO') or key not in ('','PRI','UNI','MUL'):raise ValueError('Unexpected item schema metadata')
columns.append(dict(name=name,sql_type=kind,nullable=nullable,key=key,default_batch_text=default,extra=extra))
names=[row['name'] for row in columns]
if not 1<=len(names)<=512 or len(set(names))!=len(names) or 'entry' not in names:raise ValueError('Invalid item schema columns')
ddl=query('SHOW CREATE TABLE tw_world.'+table+';')
if not isinstance(ddl,str) or not ddl.startswith(table+'\tCREATE TABLE') or len(ddl)>1048576:raise ValueError('Missing complete public template DDL')
return dict(columns=columns,column_names=names,show_create_table_batch_text=ddl)
def _public_provenance(query,table='item_template'):
table=_template_table(table)
version=query('SELECT VERSION();')
if not isinstance(version,str) or not re.fullmatch(r'[A-Za-z0-9._+~ -]{1,128}',version):raise ValueError('Invalid public database engine version')
present=query("SHOW TABLES FROM tw_world LIKE 'migrations';")
if present not in ('','migrations'):raise ValueError('Unexpected public migration-table discovery')
migrations=None
if present:
migrations=_json_rows(query("SELECT HEX(JSON_OBJECT('Id',Id,'Name',Name,'Hash',Hash,'AppliedAt',AppliedAt)) FROM tw_world.migrations ORDER BY Id LIMIT 100001;"))
if len(migrations)>100000:raise ValueError('Public migration inventory bound')
previous=0
for row in migrations:
if set(row)!=set(('Id','Name','Hash','AppliedAt')) or type(row['Id']) is not int or not previous<row['Id']<=0xffffffff or any(not isinstance(row[key],str) or len(row[key])>bound for key,bound in (('Name',255),('Hash',128),('AppliedAt',32))):raise ValueError('Invalid public migration version metadata')
previous=row['Id']
return dict(database='tw_world',table=table,engine_version=version,world_migrations=migrations,
migration_version_status='available' if migrations is not None else 'table-absent/unknown')
def _all_ids(query,chunk_size,table='item_template'):
table=_template_table(table)
result=[];last=None
while True:
where='' if last is None else ' WHERE entry>'+str(last)
raw=query('SELECT entry FROM tw_world.'+table+where+' ORDER BY entry LIMIT '+str(chunk_size)+';')
if not isinstance(raw,str) or len(raw)>chunk_size*11:raise ValueError('Item ID query bound')
values=[]
for text in raw.splitlines():
# Bulk inventory preserves stored sentinel0 too. It is classified
# separately below and never admitted by identities()/conversion.
if not re.fullmatch(r'(?:0|[1-9][0-9]{0,9})',text) or int(text)>0xffffffff:raise ValueError('Invalid public item ID')
value=int(text)
previous=values[-1] if values else (-1 if last is None else last)
if value<=previous:raise ValueError('Duplicate or unordered public item ID')
values.append(value)
if len(values)>chunk_size or len(result)+len(values)>1000000:raise ValueError('Bulk item inventory bound')
result+=values
if len(values)<chunk_size:return result
last=values[-1]
def snapshot_all(output,chunk_size=512,*,query=None,revision=None,table='item_template'):
"""Stage deterministic public chunks and publish only after verification.
Separate queries are NOT a transactional point-in-time snapshot (the pinned
source table is MyISAM). A second content/ID/schema/provenance pass detects
observed drift, but cannot rule out every concurrent change between reads.
Injection is for offline tests; the default retains the local-only DB tool.
"""
if type(chunk_size) is not int or not 1<=chunk_size<=4096:raise ValueError('Chunk size must be1..4096')
table=_template_table(table);role='item'if table=='item_template'else'spell'
output=Path(output);resolved=output.resolve();staging=output.with_name(output.name+'.staging')
if not resolved.is_relative_to(ROOT/'runtime') or output.exists() or output.is_symlink() or staging.exists() or staging.is_symlink() or not output.parent.is_dir():raise ValueError('Require new runtime directory; preserve existing output/staging')
query=db if query is None else query;revision=server_git_revision if revision is None else revision
source_revision=revision()
if not isinstance(source_revision,str) or not re.fullmatch(r'[0-9a-f]{40}(?:[0-9a-f]{24})?',source_revision):raise ValueError('Require pinned server source revision')
schema=_bulk_schema(query,table);provenance=_public_provenance(query,table);ids=_all_ids(query,chunk_size,table)
if not ids or (len(ids)+chunk_size-1)//chunk_size>4096:raise ValueError('Empty or excessive bulk chunk inventory')
columns=schema['column_names'];fields=','.join("'"+name+"',`"+name+'`' for name in columns)
def read(ids):
rows=_json_rows(query('SELECT HEX(JSON_OBJECT('+fields+')) FROM tw_world.'+table+' WHERE entry IN ('+','.join(map(str,ids))+') ORDER BY entry;'))
if len(rows)!=len(ids) or any(set(row)!=set(columns) or type(row.get('entry')) is not int for row in rows) or [row['entry'] for row in rows]!=ids:raise ValueError('Missing, duplicate, unordered or schema-drifted item rows')
return rows
staging.mkdir(mode=0o700);chunks=[];content=hashlib.sha256();total=0
for offset in range(0,len(ids),chunk_size):
selected=ids[offset:offset+chunk_size];rows=read(selected);raw=_encoded(rows);total+=len(raw)
if total>2147483648:raise ValueError('Bulk export exceeds2GiB staged bound')
path=staging/(role+'s-'+str(len(chunks)).zfill(6)+'.json');path.write_bytes(raw);path.chmod(0o600)
sha=_sha(raw)
if _sha(path.read_bytes())!=sha:raise ValueError('Staged item chunk hash mismatch')
for row in rows:content.update((json.dumps(row,ensure_ascii=False,sort_keys=True,separators=(',',':'),allow_nan=False)+'\n').encode())
chunks.append(dict(path=path.name,count=len(rows),first_id=selected[0],last_id=selected[-1],bytes=len(raw),sha256=sha))
# Verify the exact complete rows, not merely COUNT/MAX or chosen examples.
for index,chunk in enumerate(chunks):
selected=ids[index*chunk_size:(index+1)*chunk_size]
if _sha(_encoded(read(selected)))!=chunk['sha256']:raise ValueError('Item content changed during bulk export')
if _all_ids(query,chunk_size,table)!=ids or _bulk_schema(query,table)!=schema or _public_provenance(query,table)!=provenance or revision()!=source_revision:raise ValueError('Source inventory/schema/version/revision changed during bulk export')
manifest=dict(schema_version=1,kind='public-local-tortoise-'+role+'-inventory',source='authorized local Tortoise tw_world.'+table,
server_source_path=str(SERVER),server_source_git_revision=source_revision,server_worktree_clean_verified=False,running_server_binary_revision_verified=False,
schema=schema,schema_sha256=_sha(_encoded(schema)),database_provenance=provenance,
item_count=len(ids),chunk_size=chunk_size,first_id=ids[0],last_id=ids[-1],total_chunk_bytes=total,
source_identity_classification=dict(positive_uint32_rows=sum(i>0 for i in ids),all_stored_rows_preserved=True,
blocked=[dict(entry=0,status='blocked-non-wire-identity',reason='Stored source sentinel0 cannot identify a usable '+role+'; preserved without conversion or gameplay claims.')] if ids[0]==0 else []),
ids_sha256=_sha((''.join(str(i)+'\n' for i in ids)).encode()),content_sha256=content.hexdigest(),chunks=chunks,
consistency=dict(transactional_snapshot=False,second_content_pass_verified=True,second_inventory_schema_provenance_revision_pass_verified=True),
limits=['Separate bounded read-only queries; not a transactional or guaranteed point-in-time snapshot. Concurrent changes between reads remain possible.',
'Server source Git HEAD is pinned; uncommitted source changes and the running binary revision are not verified.',
'Complete public local item definitions only; no live Octo equivalence, client conversion, asset, engine-loading or gameplay claim.',
'Failure leaves staging artifacts without a final manifest; inspect and preserve them before retrying under a new output name.'])
if role=='spell':
manifest['spell_count']=manifest.pop('item_count')
manifest['limits'][2]=manifest['limits'][2].replace('item definitions','spell definitions')
if output.exists() or output.is_symlink():raise ValueError('Output appeared during staging; preserve both directories')
complete=staging/'manifest.json'
try:
complete.write_bytes(_encoded(manifest));complete.chmod(0o600)
if output.exists() or output.is_symlink():raise ValueError('Output appeared before publication; preserve staging')
staging.rename(output)
except Exception:
# Retain completed metadata without presenting it as a published export.
if complete.is_file():complete.rename(staging/'manifest.unpublished.json')
raise
return manifest
def identities(text):
parts=text.split(',')
if not 1<=len(parts)<=4096 or any(not re.fullmatch(r'[1-9][0-9]{0,9}',p) or int(p)>0xffffffff for p in parts):
raise ValueError('Require1..4096 positive uint32 item IDs')
values=list(map(int,parts))
if len(set(values))!=len(values):raise ValueError('Duplicate item IDs')
return sorted(values)
def snapshot(ids,output):
if not isinstance(ids,list) or any(type(i) is not int for i in ids):raise ValueError('Require bounded integer item identities')
ids=identities(','.join(map(str,ids)))
if not output.resolve().is_relative_to(ROOT/'runtime') or output.exists() or output.with_suffix('.manifest.json').exists():
raise ValueError('Require a new runtime output; existing evidence is preserved')
columns=[line.split('\t',1)[0] for line in db('SHOW COLUMNS FROM tw_world.item_template;').splitlines()]
if not columns or len(columns)>512 or any(not re.fullmatch(r'[A-Za-z_][A-Za-z_0-9]*',c) for c in columns):
raise ValueError('Unexpected local item schema')
fields=','.join("'"+c+"',`"+c+'`' for c in columns)
raw=db('SELECT HEX(JSON_OBJECT('+fields+')) FROM tw_world.item_template WHERE entry IN ('+','.join(map(str,ids))+') ORDER BY entry;')
if len(raw)>134217728:raise ValueError('Item snapshot size bound')
rows=[json.loads(bytes.fromhex(line).decode('utf-8')) for line in raw.splitlines()]
if [r['entry'] for r in rows]!=ids:raise ValueError('Some requested item IDs are absent; no incomplete snapshot published')
encoded=json.dumps(rows,ensure_ascii=False,indent=2)+'\n'
output.parent.mkdir(parents=True,exist_ok=True);output.write_text(encoded)
manifest={'source':'authorized local Tortoise tw_world.item_template','requested_ids':ids,
'columns':columns,'sha256':hashlib.sha256(encoded.encode()).hexdigest(),
'schema_columns_sha256':hashlib.sha256('\n'.join(columns).encode()).hexdigest(),
'limits':['Current local item definitions only; not independently verified against the live Octo realm.',
'Client appearances/spell effects require separate client tables; no database or character changes.']}
output.with_suffix('.manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
return rows
def compare_templates(previous,current):
"""Semantic public-template diff; numeric JSON formatting is not a change."""
def indexed(rows):
if not isinstance(rows,list) or not 1<=len(rows)<=4096:raise ValueError('Template comparison record bound')
result={}
for row in rows:
if not isinstance(row,dict) or type(row.get('entry')) is not int or not 0<row['entry']<=0xffffffff or row['entry'] in result:raise ValueError('Invalid/duplicate template comparison identity')
result[row['entry']]=row
return result
before,after=indexed(previous),indexed(current);changed=[]
for entry in sorted(before.keys()&after.keys()):
a,b=before[entry],after[entry];fields={}
for key in sorted(a.keys()|b.keys()):
if key in a and key in b and a[key]==b[key]:continue
value={'before_present':key in a,'after_present':key in b}
if key in a:value['before']=a[key]
if key in b:value['after']=b[key]
fields[key]=value
if fields:changed.append({'entry':entry,'fields':fields})
return dict(added_ids=sorted(after.keys()-before.keys()),removed_ids=sorted(before.keys()-after.keys()),changed=changed,
unchanged_ids=sorted((before.keys()&after.keys())-{r['entry'] for r in changed}),
limits=['Public local server template comparison only; no claim of converted client data, effects, appearances or live Octo equivalence.','Integer/float JSON representations with equal numeric values compare equal; field absence differs from explicit null.'])
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__);selection=p.add_mutually_exclusive_group(required=True);selection.add_argument('--ids');selection.add_argument('--all',action='store_true');p.add_argument('--chunk-size',type=int,default=512);p.add_argument('--table',choices=('item_template','spell_template'),default='item_template');p.add_argument('--output',type=Path,required=True);p.add_argument('--compare',type=Path,help='Earlier public template snapshot; write semantic diff alongside the new snapshot');a=p.parse_args()
if a.all:
if a.compare:p.error('--compare remains a bounded --ids snapshot operation')
report=snapshot_all(a.output,a.chunk_size,table=a.table)
print('Read',report.get('item_count',report.get('spell_count')),'public',a.table,'definitions in',len(report['chunks']),'verified chunks; multi-query snapshot, no DB/client changes:',a.output)
raise SystemExit(0)
if a.chunk_size!=512:p.error('--chunk-size is only used with --all')
old=json.loads(a.compare.read_text()) if a.compare else None;diff=a.output.with_suffix('.diff.json')
if old is not None:
compare_templates(old,old)
if diff.exists():raise ValueError('Preserve existing template comparison evidence')
if a.table!='item_template':p.error('Spell snapshots require --all; no alternative narrow extraction path')
values=identities(a.ids);rows=snapshot(values,a.output)
if old is not None:
report=compare_templates(old,rows);report['before_sha256']=hashlib.sha256(a.compare.read_bytes()).hexdigest();report['after_sha256']=hashlib.sha256(a.output.read_bytes()).hexdigest();diff.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
print('Semantic item changes:',len(report['changed']),'; added:',len(report['added_ids']),'; removed:',len(report['removed_ids']))
print('Read',len(rows),'complete local item templates without changing DB/client state:',a.output)