142 lines
8.6 KiB
Python
142 lines
8.6 KiB
Python
import os
|
|
#!/usr/bin/env python3
|
|
"""Bounded ABI, isolated errors, concurrency, and pinned CLI equivalence."""
|
|
import concurrent.futures
|
|
import ctypes as C
|
|
import json
|
|
from pathlib import Path
|
|
import statistics
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from native_codec_driver import BOUND,MODES,ROOT,load,serialize,require_optional_file
|
|
EXPLICIT_CODEC_CLI = os.environ.get('GW_TEST_CODEC_CLI')
|
|
CODEC_CLI = Path(EXPLICIT_CODEC_CLI).resolve() if EXPLICIT_CODEC_CLI else ROOT / 'build/forever-schema/forever-create-codec'
|
|
CODEC_LIBRARY = Path(os.environ.get('GW_TEST_CODEC_PATH', ROOT / 'build/forever-schema/libforever_codec.so')).resolve()
|
|
if EXPLICIT_CODEC_CLI and not CODEC_CLI.is_file():
|
|
raise RuntimeError('Explicit GW_TEST_CODEC_CLI is not a file')
|
|
if os.environ.get('GW_TEST_CODEC_PATH') and not CODEC_LIBRARY.is_file():
|
|
raise RuntimeError('Explicit GW_TEST_CODEC_PATH is not a file')
|
|
|
|
|
|
require_optional_file(CODEC_LIBRARY)
|
|
require_optional_file(CODEC_CLI)
|
|
library=load();call=library.gw_codec_serialize
|
|
written=C.c_uint32(99);guard=C.create_string_buffer(b'unchanged')
|
|
def invoke(mode,data=None,size=0,flags=0,output=guard,capacity=9):
|
|
written.value=99
|
|
result=call(mode,data,size,flags,output,capacity,C.byref(written))
|
|
return result,written.value
|
|
for args in ((999,), (0,None,BOUND+1), (0,None,1), (15,None,0,2), (15,None,0,0,None,1), (15,None,0,0,guard,BOUND+1)):
|
|
assert invoke(*args)==(1,0)
|
|
assert guard.raw.startswith(b'unchanged')
|
|
assert call(15,None,0,0,None,0,None)==1
|
|
assert invoke(13,None,0)==(2,0) # Truncated attack-error body.
|
|
assert invoke(15,None,0,0,None,0)[0]==3
|
|
required=written.value
|
|
assert required>9 and invoke(15)==(3,required) and guard.raw.startswith(b'unchanged')
|
|
assert len(serialize(library,15,b''))==required
|
|
|
|
# Pinned original ActivePlayerData::WriteCreate emits these fields even when
|
|
# their changes-mask bits are clear. This independent full-self fixture caught
|
|
# zero spell-power/periodic-healing/weapon factors despite school factors of1.
|
|
# Locate SkillInfo by its unique source language row, then independently walk
|
|
# the original fixed fields and counted BitVectors to the school-stat window.
|
|
pack=struct.pack
|
|
self_fields={22:80,28:80,34:60,35:1,36:0x01000101,718:98,719:0x012C012C}
|
|
# Tortoise emits real 1.0 school multipliers; omitted source fields mean zero.
|
|
self_fields.update({1215+i:0x3f800000 for i in range(7)})
|
|
self_mask=[0]*(max(self_fields)//32+1)
|
|
for index in self_fields:self_mask[index//32]|=1<<(index%32)
|
|
self_body=pack('<IBB',1,0,3)+bytes.fromhex('039d11')+bytes([4,0x21])
|
|
self_body+=pack('<II4fI',0,100,1,2,3,0,0)+pack('<6f',2.5,7,4.5,4.72,2.5,3.14)
|
|
self_body+=bytes([len(self_mask)])+pack('<'+str(len(self_mask))+'I',*self_mask)
|
|
self_body+=b''.join(pack('<I',self_fields[i]) for i in sorted(self_fields))
|
|
self_header=pack('<QHIIIII',4509,70,0x46010046,0,12,0,0)
|
|
self_header+=b'Gatewaytest\0'+bytes([1,1,0])+pack('<I',0xA9)
|
|
self_packet=serialize(library,0,self_header+self_body)
|
|
language_row=pack('<7H',98,0,300,1,300,0,0)
|
|
assert self_packet.count(language_row)==1
|
|
skill_start=self_packet.index(language_row)
|
|
# SkillInfo: 300 seven-word rows. ActivePlayerData then writes 26 scalar words,
|
|
# 14 counted uint64 BitVectors, two empty data-element vectors and two RestInfo.
|
|
scalar_start=skill_start+300*14+26*4
|
|
for _ in range(14):
|
|
count=struct.unpack_from('<I',self_packet,scalar_start)[0]
|
|
assert count<=1024
|
|
scalar_start+=4+count*8
|
|
assert scalar_start<=len(self_packet)
|
|
assert self_packet[scalar_start:scalar_start+8]==bytes(8)
|
|
scalar_start+=8+2*5
|
|
assert len(self_packet)-scalar_start==1024,'Pinned full-self scalar/tail layout changed'
|
|
expected_scalars=pack('<iiff',0,0,1,1)*7+pack('<iff',0,1,1)
|
|
expected_scalars+=pack('<ff',1,1)*3+pack('<f',1)
|
|
assert self_packet[scalar_start:scalar_start+len(expected_scalars)]==expected_scalars, \
|
|
'Full-self neutral factors differ from native InitStatsForLevel defaults'
|
|
source_self=subprocess.run([str(CODEC_CLI)],
|
|
input=self_header+self_body,capture_output=True,check=True).stdout
|
|
assert source_self==self_packet,'C ABI and pinned source-writer full-self bytes differ'
|
|
print('Full-self original-writer school, healing, spell-power and weapon neutral factors verified offline.')
|
|
|
|
# Independent native WriteCreate layout: 300 interleaved seven-word skill rows.
|
|
# Keep original source slots and add only actual target child representations.
|
|
language_row=pack('<7H',98,0,300,1,300,0,0)
|
|
assert self_packet.count(language_row)==1
|
|
skill_start=self_packet.index(language_row)
|
|
profession_fields=dict(self_fields)
|
|
profession_fields.update({721:164,722:(300<<16)|270,723:0x0005ffff,
|
|
724:186,725:(300<<16)|300})
|
|
profession_mask=[0]*(max(profession_fields)//32+1)
|
|
for index in profession_fields:profession_mask[index//32]|=1<<(index%32)
|
|
profession_body=self_body[:self_body.index(bytes([len(self_mask)])+pack('<'+str(len(self_mask))+'I',*self_mask))]
|
|
profession_body+=bytes([len(profession_mask)])+pack('<'+str(len(profession_mask))+'I',*profession_mask)
|
|
profession_body+=b''.join(pack('<I',profession_fields[i])for i in sorted(profession_fields))
|
|
profession_packet=serialize(library,0,self_header+profession_body)
|
|
assert len(profession_packet)==len(self_packet)
|
|
smith=pack('<5HhH',164,4,270,1,300,-1,5)
|
|
mining=pack('<7H',186,4,300,1,300,0,0)
|
|
assert profession_packet[skill_start+14:skill_start+28]==smith
|
|
assert profession_packet[skill_start+28:skill_start+42]==mining
|
|
assert profession_packet[skill_start+129*14:skill_start+130*14]==pack('<5HhH',2938,4,270,1,300,-1,5)
|
|
assert profession_packet[skill_start+134*14:skill_start+135*14]==pack('<7H',2946,4,300,1,300,0,0)
|
|
assert profession_packet[skill_start+128*14:skill_start+129*14]==bytes(14), 'Unlearned First Aid child must stay absent'
|
|
print('Full-self profession slots, native child skill ranks and signed bonuses verified offline.')
|
|
|
|
# Explicit per-call options replace process-global getenv. Verify calls do not
|
|
# change each other's packet output or the host environment.
|
|
cases=[(13,bytes([i])) for i in range(4)]+[(14,struct.pack('<HQBI',70,4509,1,150)),(15,b'')]
|
|
expected={(mode,data):serialize(library,mode,data) for mode,data in cases}
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
|
|
results=list(pool.map(lambda case:serialize(library,*case),cases*12))
|
|
assert results==[expected[case] for case in cases*12]
|
|
for mode,data in cases:
|
|
saved=ROOT/'runtime/codec-before-native-library'
|
|
command=[str(CODEC_CLI if EXPLICIT_CODEC_CLI else saved if saved.exists() else CODEC_CLI)]
|
|
if MODES[mode]:command.append(MODES[mode])
|
|
baseline=subprocess.run(command,input=data,capture_output=True,check=True).stdout
|
|
assert expected[mode,data]==baseline
|
|
|
|
fixtures=['self_create','unit_values','query_serializer','spline_serializer','vendor_serializer','sell_serializer','buy_serializer','trainer_serializer','gossip_serializer','combat_serializer','spell_serializer','periodic_serializer','guild_serializer','npc_combat_serializer']
|
|
driver=ROOT/'tests/native_codec_driver.py'
|
|
for fixture in fixtures:
|
|
subprocess.run([sys.executable,str(ROOT/'tests'/f'{fixture}_fixture.py'),str(driver)],check=True)
|
|
|
|
# Same public, fixed payloads. This isolates process launch/codec execution from
|
|
# network RTT and game waits; it is NOT an end-to-end latency measurement.
|
|
benchmark=[]
|
|
for mode,data in cases:
|
|
direct=[];process=[]
|
|
source=C.create_string_buffer(data);output=C.create_string_buffer(BOUND);count=C.c_uint32()
|
|
for i in range(25):
|
|
start=time.perf_counter_ns()
|
|
assert call(mode,source,len(data),0,output,BOUND,C.byref(count))==0
|
|
direct.append((time.perf_counter_ns()-start)/1000)
|
|
start=time.perf_counter_ns()
|
|
subprocess.run([str(CODEC_CLI if EXPLICIT_CODEC_CLI else saved if saved.exists() else CODEC_CLI),MODES[mode]],input=data,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE,check=True)
|
|
process.append((time.perf_counter_ns()-start)/1000)
|
|
benchmark.append({'mode':MODES[mode],'payload_bytes':len(data),'samples':25,'direct_median_us':round(statistics.median(direct),2),'subprocess_median_us':round(statistics.median(process),2)})
|
|
evidence={'kind':'offline-serializer-only','engine_world_entry':False,'pre_change_binary_compared':saved.exists(),'fixture_groups':fixtures,'parallel_calls':len(results),'benchmark':benchmark,'limits':['Not network, movement responsiveness, or actual Forever engine latency.','Direct calls reuse caller-owned buffers; subprocess timings include process launch.']}
|
|
(ROOT/'runtime/native-serializer-tests.json').write_text(json.dumps(evidence,indent=2)+'\n')
|
|
print('Native C ABI bounds, error isolation,72 concurrent calls, baseline bytes and',len(fixtures),'fixture groups passed.')
|