Files
texrra-engine/scripts/check-native-statistics.py
T

75 lines
6.4 KiB
Python

#!/usr/bin/env python3
"""Real statistics controls/channels, exact page costs and unchanged PDF oracle.
Native resource counts describe Rust-owned data; they are never compared to
invented TeX arena sizes. Reference parity is timing/control/channel behavior.
"""
import argparse,hashlib,importlib.util,json,os,re,subprocess
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
def module(name,file):
s=importlib.util.spec_from_file_location(name,ROOT/'scripts'/file);m=importlib.util.module_from_spec(s);s.loader.exec_module(m);return m
INK=module('statistics_ink','check-native-pages.py');WORDS=module('statistics_words','check-native-paragraphs.py')
def sha(data):return hashlib.sha256(data).hexdigest()
def run(args,cwd,env):
r=subprocess.run([str(v)for v in args],cwd=cwd,env=env,capture_output=True,timeout=60)
if r.returncode:raise RuntimeError((r.stdout+r.stderr).decode(errors='replace'))
return r.stdout,r.stderr
def page_records(text):
lines=text.splitlines();out=[];i=0
while i<len(lines):
starts=[p for p in [lines[i].find('%% goal height='),lines[i].find('% t=')]if p>=0]
if not starts:i+=1;continue
value=lines[i][min(starts):]
while len(lines[i])==79 and i+1<len(lines):i+=1;value+=lines[i]
marker=', max depth='if value.startswith('%%')else' c=';at=value.index(marker)+len(marker)
m=re.match(r'[-.\d*#]+',value[at:]);assert m;out.append(value[:at+m.end()]);i+=1
return out
def case(binary,out,kind,level,online):
name=f'{kind}-stats{level}-online{online}';d=out/name;n=d/'native';r=d/'reference';n.mkdir(parents=True,exist_ok=True);r.mkdir(parents=True,exist_ok=True)
original=ROOT/'examples/native-bootstrap/native-job.tex';before=sha(original.read_bytes())
prefix=(r'\catcode123=1\catcode125=2\pdfoutput=1\pdfpkresolution=600'
+f'\\tracingstats={level}\\tracingpages=1\\tracingonline={online}')
if kind=='copied':
source=prefix+(r'\pdfminorversion=7\pdfobjcompresslevel=3\pdfcompresslevel=0\pdfpagewidth=300bp\pdfpageheight=160bp'
r'\pdfhorigin=20pt\pdfvorigin=20pt\font\F=cmr10 at12pt\F\immediate\openout1=statistics.aux\count0=1'
r'\def\payload{Native statistics AV office}\setbox0=\vbox{\hbox{\payload}\kern2pt\hbox{Second actual line}\write1{PAGE=\number\count0}}'
r'\shipout\copy0\pdfcompresslevel=9\count0=2\shipout\box0\immediate\closeout1\end')
expected=2;aux='statistics.aux'
else:
source=prefix+'\\input '+str(original)+'\n';expected=4;aux='pages.aux'
file=d/'source.tex';file.write_text(source);source_sha=sha(file.read_bytes())
env=os.environ.copy();env['TFMFONTS']=str(ROOT/'crates/texrra-tex-core/assets');env['T1FONTS']=str(ROOT/'assets/fonts');env['TEXINPUTS']=str(ROOT/'examples/native-bootstrap')+':';env['TEXFONTMAPS']=str(Path(subprocess.check_output(['kpsewhich','pdftex.map'],text=True).strip()).parent)
ns,nt=run([binary,'native','--job','--initex','--etex','--resource-manifest',n/'resources.json',file,n/'job.pdf'],n,env);rt,re_=run(['pdftex','-ini','-etex','-interaction=nonstopmode','-halt-on-error',file],r,env)
(n/'stdout.log').write_bytes(ns);(n/'terminal.log').write_bytes(nt);(r/'terminal.log').write_bytes(rt+re_)
nl=(n/'job.log').read_text();rl=(r/'source.log').read_text();terminal=nt.decode();ref_terminal=rt.decode()
ship=nl.count('Route-D resources at shipout:');end=nl.count('resource usage at core execution end (success)')
assert ship==rl.count('Memory usage before:')==(expected if level>1 else 0)
assert terminal.count('Route-D resources at shipout:')==ref_terminal.count('Memory usage before:')==ship
assert end==rl.count("Here is how much of TeX's memory you used:")==int(level>0)
assert 'resource usage at core execution end'not in terminal
assert 'words of memory out of'not in nl and 'still untouched:'not in nl
records=[page_records(x)for x in [nl,rl,terminal,ref_terminal]];assert records[0]==records[1] and records[2]==records[3]
if online==0:assert not records[2]
else:assert records[0]==records[2]
if kind=='natural':assert records[0]
native,reference=n/'job.pdf',r/'source.pdf';words=[WORDS.words(v)for v in [native,reference]];assert len(words[0])==len(words[1])==expected
labels=[[w[0]for page in pages for w in page]for pages in words];assert labels[0]==labels[1]
flat=[[w for page in pages for w in page]for pages in words];errors={key:max(abs(a[1][key]-b[1][key])for a,b in zip(*flat))for key in ['xMin','xMax','yMin','yMax']}
ink=[INK.ink_report(INK.raster(native,n/f'page-{i}',i),INK.raster(reference,r/f'page-{i}',i))for i in range(1,expected+1)]
aux_equal=(n/aux).read_bytes()==(r/aux).read_bytes();unchanged=sha(file.read_bytes())==source_sha and sha(original.read_bytes())==before
passed=max(errors.values())<=.02 and all(i['passed']for i in ink)and aux_equal and unchanged
result=dict(id=name,kind=kind,passed=passed,pages=expected,level=level,tracingonline=online,shipout_reports=ship,end_reports=end,page_records=records[0],exact_page_diagnostics=True,max_word_box_errors_bp=errors,ink=ink,aux_equal=aux_equal,source_unchanged=unchanged,source_sha256=source_sha,native_pdf_sha256=sha(native.read_bytes()))
(d/'audit.json').write_text(json.dumps(result,indent=2)+'\n');return result
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--binary',type=Path,required=True);p.add_argument('--output-dir',type=Path,required=True);a=p.parse_args();out=a.output_dir.resolve();out.mkdir(parents=True,exist_ok=True);results=[]
for kind in ['copied','natural']:
for level in [0,1,2,3]:
for online in [0,1]:
r=case(a.binary.resolve(),out,kind,level,online);results.append(r);print(r['id'],'passed'if r['passed']else'FAILED',flush=True)
for kind in ['copied','natural']:assert len({r['native_pdf_sha256']for r in results if r['kind']==kind})==1,'statistics changed actual PDF bytes'
report=dict(passed=all(r['passed']for r in results),cases=len(results),pages=sum(r['pages']for r in results),byte_identical_across_trace_controls=True,binary_sha256=sha(a.binary.resolve().read_bytes()),reference_version=subprocess.check_output(['pdftex','--version'],text=True).splitlines()[0],scope='Real timing/channels and exact native break costs; native ownership counters intentionally are not counterfeit TeX arena words',results=results)
(out/'audit.json').write_text(json.dumps(report,indent=2)+'\n')
if not report['passed']:raise SystemExit(1)
if __name__=='__main__':main()