Files
WoW-Hybrid-gateway/tests/item_sparse_compact_payload_test.py
praxisandClaude Fable 5.2 7f2139d8d0 Offline test fixtures
883 files, from working commit b1a079a.

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

128 lines
8.2 KiB
Python

#!/usr/bin/env python3
"""Small C++ registry parity by default; large qualification/timing are opt-in."""
import argparse
import hashlib
import json
import struct
import subprocess
import sys
import time
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'ops'))
import item_sparse_compat as emitter
READER=r'''
#include "registry.hpp"
#include <iostream>
#include <iterator>
#include <algorithm>
namespace g=gateway::item_sparse_compat;
static void put(uint32_t value){for(unsigned i=0;i<4;++i)std::cout.put(char(value>>(i*8)));}
template<class R> static uint32_t status(R const& row){if constexpr(requires{row.status;})return row.status;else return 1;}
int main(){
put(uint32_t(g::PushID));put(uint32_t(std::size(g::Pushes)));
for(auto const& p:g::Pushes){put(uint32_t(p.id));put(p.first);put(p.count);}
put(uint32_t(std::size(g::Records)));
for(auto const& r:g::Records){
auto boundary=(&r==&g::Records[0]||&r==&g::Records[std::size(g::Records)-1]);
std::span<const uint8_t> found;
if(boundary){
// Model the runtime query boundary; prevent O1 from exhaustively folding
// a187k-entry constant search while compiling this reader harness.
volatile uint32_t table=r.table,ident=r.id;found=g::find(table,ident);
}
// Avoid the quadratic lookup for every high-count row: lookup API is checked
// for first/last entries, while all record data are independently read back.
if(boundary&&
(found.size()!=r.data.size()||!std::equal(found.begin(),found.end(),r.data.begin())))return 2;
put(r.table);put(r.id);put(status(r));put(uint32_t(r.data.size()));
std::cout.write(reinterpret_cast<char const*>(r.data.data()),r.data.size());
}
volatile uint32_t missing_table=0xffffffffu,missing_id=0x7fffffffu;
if(!g::find(missing_table,missing_id).empty())return 3;
}
'''
def row(ident,raw):
return dict(id=ident,table_hash='0x12345678',wire_hex=raw.hex(),sha256=hashlib.sha256(raw).hexdigest())
def removed():
baseline=dict(ID=100,ItemEffectID=2,ItemID=3)
return dict(id=100,table_hash='0x00cb674f',table_name='ItemXItemEffect',source_item=3,record_status='removed',record=None,wire_hex='',sha256=hashlib.sha256(b'').hexdigest(),baseline_record=baseline,policy='source-authoritative-per-item-passive-link-replacement',baseline_record_sha256=hashlib.sha256(struct.pack('<iI',2,3)).hexdigest())
def expected(rows,push,pages):
out=bytearray(struct.pack('<II',push,len(pages)))
for p in pages:out+=struct.pack('<III',p['push_id'],p['first'],p['count'])
out+=struct.pack('<I',len(rows))
for r in rows:
raw=bytes.fromhex(r['wire_hex']);out+=struct.pack('<IIII',int(r['table_hash'],16),r['id'],2 if r.get('record_status')=='removed'else 1,len(raw))+raw
return bytes(out)
def compile_read(output,label,rows,compact,compiler,timeout_seconds=600):
output=output/label;output.mkdir()
start=time.monotonic();push,header,pages=emitter._package_data(rows,compact_payloads=compact);emit_seconds=time.monotonic()-start
(output/'registry.hpp').write_text(header);(output/'reader.cpp').write_text(READER)
executable=output/'reader';metrics=output/'compile.metrics.json';log=output/'compile.private.log'
command=[compiler,'-std=c++20','-O1','-fPIC','-fvisibility=hidden','-ffunction-sections','-fdata-sections',str(output/'reader.cpp'),'-o',str(executable)]
start=time.monotonic()
with log.open('wb')as stream:
measure='''import json,os,resource,signal,subprocess,sys,time
from pathlib import Path
t=time.monotonic();tmp=Path(sys.argv[1]).parent/'compiler-tmp';tmp.mkdir()
env=dict(os.environ,TMPDIR=str(tmp),TMP=str(tmp),TEMP=str(tmp))
child=subprocess.Popen(sys.argv[3:],start_new_session=True,env=env)
try:code=child.wait(timeout=float(sys.argv[2]))
except subprocess.TimeoutExpired:
os.killpg(child.pid,signal.SIGKILL);child.wait();raise
if code:raise SystemExit(code)
Path(sys.argv[1]).write_text(json.dumps(dict(wall_seconds=time.monotonic()-t,max_rss_kib=resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss)))'''
subprocess.run([sys.executable,'-c',measure,str(metrics),str(timeout_seconds),*command],check=True,stdout=stream,stderr=subprocess.STDOUT)
compile_seconds=time.monotonic()-start
actual=subprocess.run([str(executable)],check=True,capture_output=True).stdout
assert actual==expected(rows,push,pages),label+' actual C++ registry readback differs'
result=dict(rows=len(rows),compact=compact,header_bytes=len(header.encode()),executable_bytes=executable.stat().st_size,emit_seconds=round(emit_seconds,6),compile_seconds=round(compile_seconds,6),compiler_metrics=json.loads(metrics.read_text()),readback_sha256=hashlib.sha256(actual).hexdigest(),push_id=push,pages=pages)
(output/'result.private.json').write_text(json.dumps(result,indent=2)+'\n')
return result
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output-directory',type=Path,default=ROOT/'runtime/continuation-20261113/codex/Combined-C52/Build-performance/small-parity-runs'/str(time.time_ns()))
parser.add_argument('--compiler',default='clang++')
parser.add_argument('--qualify-large',action='store_true',help='Explicitly compile/read back the high-row fixture at the default constexpr budget')
parser.add_argument('--benchmark',action='store_true',help='Explicitly time one legacy/compact pair with bounded small row count')
parser.add_argument('--benchmark-rows',type=int,default=4096)
parser.add_argument('--high-rows',type=int,default=187676)
args=parser.parse_args();out=args.output_directory.resolve()
if not out.is_relative_to(ROOT/'runtime')and not out.is_relative_to(ROOT/'build'):parser.error('Keep test output on the project Games runtime/build filesystem')
if not 1024<=args.benchmark_rows<=5000 or not 65536<=args.high_rows<=emitter.MAX_PACKAGE_ROWS:parser.error('Bounded meaningful row counts required')
out.mkdir(parents=True,exist_ok=False)
versions=subprocess.check_output([args.compiler,'--version'],text=True).splitlines();results={}
# Cross literal boundaries, embedded NUL, all high bytes and digits adjacent
# to byte escapes. A real validated relation-removal fixture keeps empty spans.
edge=bytes(range(256))+b'\0\xff0123456789abcdefABCDEF\x80\0'
small=[row(1,edge[:149]),removed(),row(2,edge[149:])]
for label,rows in [('edges-removed',small),('no-removals',small[::2])]:
old=compile_read(out,label+'-legacy',rows,False,args.compiler);new=compile_read(out,label+'-compact',rows,True,args.compiler)
assert (old['push_id'],old['pages'],old['readback_sha256'])==(new['push_id'],new['pages'],new['readback_sha256']);results[label]={'legacy':old,'compact':new}
default_push,default_header=emitter.package_payloads(rows)
assert default_push==old['push_id'] and default_header==(out/(label+'-legacy')/'registry.hpp').read_text()
assert emitter.package_payloads(rows,compact_payloads=True)[1]==emitter._package_data(rows,compact_payloads=True)[1]
# Many individually valid small rows exercise the unchanged default constexpr
# step limit only when explicitly requested. No step override is permitted.
if args.qualify_large:
high=[row(i+1,bytes([i&255]))for i in range(args.high_rows)]
results['high-row-count']=compile_read(out,'high-row-count-compact',high,True,args.compiler)
del high
# Timing is independently opt-in; it never activates the large qualification.
if args.benchmark:
raw=bytes(range(256))*2;bench=[row(i+1,raw)for i in range(args.benchmark_rows)]
old=compile_read(out,'benchmark-legacy',bench,False,args.compiler);new=compile_read(out,'benchmark-compact',bench,True,args.compiler)
assert (old['push_id'],old['pages'],old['readback_sha256'])==(new['push_id'],new['pages'],new['readback_sha256']);results['benchmark']={'legacy':old,'compact':new,'compile_speedup':old['compile_seconds']/new['compile_seconds']}
report=dict(state='PASS',compiler=versions,results=results,large_qualification_executed=args.qualify_large,benchmark_executed=args.benchmark,default_constexpr_budget=True,actual_cpp_reader=True,source_rows_filtered=0,native_runtime_acceptance='not performed')
(out/'report.private.json').write_text(json.dumps(report,indent=2)+'\n')
print('PASS compact registry: small parity/default compatibility; large qualification', 'executed'if args.qualify_large else'skipped','; benchmark','executed'if args.benchmark else'skipped')
if __name__=='__main__':main()