Advance native LaTeX execution and preview

This commit is contained in:
gloamxun committed 2026-11-18 22:17:21 +08:00
1 parent 91f9d76b16
commit 2741546ca8
414 files changed
+99872 -933

No files matched your search

+107
View File
@@ -0,0 +1,107 @@
"""Read-only differential audit; missing native features are findings, not passes."""
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
import argparse,hashlib,json,re,subprocess
ROOT=Path(__file__).resolve().parents[1]
BASE=r'''\catcode123=1 \catcode125=2 \catcode35=6
\font\rm=cmr10 \rm \hsize=100pt \baselineskip=12pt
\hbadness=10000 \vbadness=10000
'''
MATH=(ROOT/'examples/native-bootstrap/math-fonts.tex').read_text()
CASES=[
('control-numexpr','control',r'\count0=\numexpr(7+5)*3/2\relax\message{AUDIT=\the\count0;}',0),
('control-latin-ligatures','control',r'\setbox0=\hbox{office AV}\message{AUDIT=\the\wd0;}',0),
('control-hfuzz','control',r'\hfuzz=.1pt\message{AUDIT=\the\hfuzz;}',0),
('showbox-first-job','diagnostics',r'\showboxbreadth=20\showboxdepth=5\setbox0=\hbox{office AV}\showbox0',1),
('errorcontextlines','diagnostics',r'\errorcontextlines=5\message{AUDIT=\the\errorcontextlines;}',0),
('nested-error-context','diagnostics',r'\def\A#1{\B{#1}\relax}\def\B#1{\C{#1}\relax}\def\C#1{\errmessage{AUDIT_NESTED_ERROR}}\A{X}',1),
('show','diagnostics',r'\show\relax',1),
('showthe','diagnostics',r'\count0=17\showthe\count0',1),
('showlists','diagnostics',r'\setbox0=\vbox{\hbox{A}\showlists}',1),
('math-compound-showbox','diagnostics',r'\setbox0=\hbox{$x^2$}\showboxbreadth=100\showboxdepth=10\showbox0',1),
('math-glue-showbox','diagnostics',r'\setbox0=\hbox{$x+x$}\showboxbreadth=100\showboxdepth=10\showbox0',1),
('punctuation-ligature','text',r"\setbox0=\hbox{--- -- ``Hi''}\message{AUDIT=\the\wd0;}",0),
('sfcode','text',r'\sfcode`\.=3000\setbox0=\hbox{A. B}\message{AUDIT=\the\wd0;}',0),
('everypar','hooks',r'\everypar={\message{AUDIT=EVERYPAR;}}\noindent A\par',0),
('everymath','hooks',r'\everymath={\message{AUDIT=EVERYMATH;}}\setbox0=\hbox{$x$}',0),
('everydisplay','hooks',r'\everydisplay={\message{AUDIT=EVERYDISPLAY;}}\noindent A$$x$$\par',0),
('dimexpr','expressions',r'\dimen0=\dimexpr(1pt+2pt)*3/2\relax\message{AUDIT=\the\dimen0;}',0),
('glueexpr','expressions',r'\skip0=\glueexpr1pt plus2fil+3pt plus1fill\relax\message{AUDIT=\the\skip0;}',0),
('muexpr','expressions',r'\muskip0=\muexpr3mu plus1fil*2\relax\message{AUDIT=\the\muskip0;}',0),
('unhcopy','lists',r'\setbox0=\hbox{AB}\setbox1=\hbox{C\unhcopy0 D}\message{AUDIT=\the\wd1;}',0),
('lastbox','lists',r'\setbox0=\vbox{\hbox{A}\setbox1=\lastbox\message{AUDIT=\the\wd1;}}',0),
('hfill','lists',r'\setbox0=\hbox to30pt{A\hfill B}\message{AUDIT=\the\wd0;}',0),
('vrule','lists',r'\setbox0=\hbox{\vrule width1pt height2pt depth1pt}\message{AUDIT=\the\wd0;}',0),
('overfullrule','page',r'\overfullrule=5pt\setbox0=\hbox to1pt{AB}\message{AUDIT=\the\wd0;}',0),
('maxdepth','page',r'\maxdepth=4pt\message{AUDIT=\the\maxdepth;}',0),
('splitmaxdepth','page',r'\splitmaxdepth=4pt\message{AUDIT=\the\splitmaxdepth;}',0),
('topskip','page',r'\topskip=10pt\message{AUDIT=\the\topskip;}',0),
('splittopskip','page',r'\splittopskip=10pt\message{AUDIT=\the\splittopskip;}',0),
('vsize','page',r'\vsize=100pt\message{AUDIT=\the\vsize;}',0),
('font-at','font',r'\font\t=cmr10 at12pt\t\setbox0=\hbox{AV}\message{AUDIT=\the\wd0;}',0),
('font-scaled','font',r'\font\t=cmr10 scaled1200\t\setbox0=\hbox{AV}\message{AUDIT=\the\wd0;}',0),
('font-cmr7-text','font',r'\font\t=cmr7\t\setbox0=\hbox{AV}\message{AUDIT=\the\wd0;}',0),
('font-bold','font',r'\font\t=cmbx10\t\setbox0=\hbox{AV}\message{AUDIT=\the\wd0;}',0),
('fontdimen','font',r'\fontdimen2\rm=4pt\message{AUDIT=\the\fontdimen2\rm;}',0),
('futurelet','expansion',r'\def\A{\ifx\peek\relax\message{AUDIT=YES;}\fi}\futurelet\peek\A\relax',0),
('afterassignment','expansion',r'\afterassignment\relax\count0=2\message{AUDIT=\the\count0;}',0),
('aftergroup','expansion',r'\def\A{\message{AUDIT=AFTERGROUP;}}{\aftergroup\A}',0),
('outer','expansion',r'\outer\def\A{\relax}\A',0),
('radical','math',r'\setbox0=\hbox{$\radical"270370 x$}\message{AUDIT=\the\wd0;}',0),
('mathchoice','math',r'\setbox0=\hbox{$\mathchoice{a}{b}{c}{d}$}\message{AUDIT=\the\wd0;}',0),
]
def run(case, binary, output_dir):
name,group,body,expected=case;out=output_dir/name;out.mkdir(parents=True,exist_ok=True)
source=out/'probe.tex';source.write_text(BASE+(MATH if group=='math' or group=='hooks' or name.startswith('math-')else'')+body+'\n\\end\n')
native=subprocess.run([str(binary),'native','--initex','--etex',str(source),str(out/'native.pdf')],cwd=out,capture_output=True,text=True,timeout=30)
args=['pdftex','-ini','-etex','-interaction=nonstopmode']
if name=='nested-error-context':args.append('-halt-on-error')
reference=subprocess.run(args+['probe.tex'],cwd=out,capture_output=True,text=True,timeout=30)
for label,result in [('native',native),('reference',reference)]:
(out/f'{label}-stdout.txt').write_text(result.stdout);(out/f'{label}-stderr.txt').write_text(result.stderr)
native_text=native.stdout+'\n'+native.stderr;reference_text=(out/'probe.log').read_text()
errors=re.findall(r'(?m)^! (.*)',reference_text)
assert reference.returncode==expected,(name,reference.returncode,reference.stdout[-1500:])
if expected==0:assert not errors,(name,errors)
elif name in ['show','showthe']:assert not errors and re.search(r'(?m)^> ',reference_text),(name,errors)
elif name!='nested-error-context':assert errors==['OK.'],(name,errors)
marks=lambda t:re.findall(r'AUDIT=([^;]*);',t)
controls_ok=None
if group=='control':
controls_ok=native.returncode==reference.returncode and marks(native_text)==marks(reference_text)
assert controls_ok,(name,native_text,reference_text)
first=next((line for line in native.stderr.splitlines()if line.startswith('error:')),'')
box_equal=None
if name=='showbox-first-job':
n=(out/'native.log').read_text();b=lambda t:re.findall(r'(?ms)^> \\box\d+=.*?(?=\n! OK\.)',t)
box_equal=b(n)==b(reference_text)and len(b(n))==1
return dict(id=name,group=group,source=str(source),source_sha256=hashlib.sha256(source.read_bytes()).hexdigest(),native_exit=native.returncode,reference_exit=reference.returncode,native_error=first,native_values=marks(native_text),reference_values=marks(reference_text),control_equal=controls_ok,box_body_equal=box_equal,native_has_context_frames=bool(re.search(r'(?m)^\\[ABC] ',native_text)),reference_has_context_frames=bool(re.search(r'(?m)^\\[ABC] ',reference_text)))
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--binary',type=Path,default=ROOT/'target/release/texrra')
parser.add_argument('--output-dir',type=Path,required=True)
args=parser.parse_args()
binary=args.binary.resolve();output_dir=args.output_dir.resolve()
output_dir.mkdir(parents=True,exist_ok=True)
with ThreadPoolExecutor(max_workers=4)as pool:
results=list(pool.map(lambda item:run(item,binary,output_dir),CASES))
findings=dict(
undefined_entry_probes=sum('undefined native control sequence'in r['native_error']for r in results),
unsupported_semantic_probes=sum(bool(r['native_error'])and'undefined native control sequence'not in r['native_error']and r['id']!='nested-error-context'for r in results),
missing_context_probes=sum(r['reference_has_context_frames']and not r['native_has_context_frames']for r in results),
first_show_body_mismatches=sum(r['box_body_equal']is False for r in results))
report=dict(audit_completed=True,production_code_changed=False,goal_implemented=False,
binary=str(binary),binary_sha256=hashlib.sha256(binary.read_bytes()).hexdigest(),
reference_version=subprocess.check_output(['pdftex','--version'],text=True).splitlines()[0],
cases=len(results),controls=sum(r['group']=='control'for r in results),findings=findings,
results=results,scope='Representative probes, not a complete primitive count or conformance score. Unsupported cases remain failures of native capability, never successful compatibility tests.')
(output_dir/'audit.json').write_text(json.dumps(report,indent=2)+'\n')
for r in results:print(r['id'],r['native_exit'],r['reference_exit'],r['native_error'])
print('Audit completed:',len(results),'probes; implementation remains pending.')
if __name__=='__main__':
main()
+73
View File
@@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Report fonts actually used by extracted PDF text spans and embedded resources.
This is an audit, not a visual fidelity gate. Equal font names do not prove
equal metrics, glyph outlines, encoding, shaping or paragraph layout.
Uses stdlib and Poppler. XML font sizes are rounded to integer bp at zoom 1;
they are diagnostic labels, not precise TeX-size measurements.
"""
import argparse
from collections import Counter
import json
from pathlib import Path
import re
import subprocess
import xml.etree.ElementTree as ET
def font_name(name):
return re.sub(r"^[A-Z]{6}\+", "", name)
def inspect(path):
resource_list = subprocess.check_output(["pdffonts", str(path)], text=True)
resources = {font_name(re.split(r"\s{2,}", row)[0])
for row in resource_list.splitlines()[2:] if row.strip()}
xml = subprocess.check_output(["pdftohtml", "-xml", "-hidden", "-fontfullname",
"-i", "-stdout", "-zoom", "1", str(path)])
document = ET.fromstring(xml)
usage = Counter()
fonts = {}
for page in document.findall("page"):
fonts.update({spec["id"]: (font_name(spec["family"]), int(spec["size"]))
for spec in (node.attrib for node in page.findall("fontspec"))})
for span in page.findall("text"):
usage[fonts[span.attrib["font"]]] += len("".join(span.itertext()))
return {
"path": str(path.resolve()),
"pages": len(document.findall("page")),
"resource_font_names": sorted(resources),
"used_font_names": sorted({name for name, size in usage}),
"span_characters_by_font_and_rounded_size_bp": [
{"font": name, "rounded_size_bp": size, "characters": count}
for (name, size), count in sorted(usage.items())
],
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--reference", type=Path, required=True)
parser.add_argument("--candidate", type=Path, required=True)
parser.add_argument("--json", type=Path, required=True)
args = parser.parse_args()
reference = inspect(args.reference)
candidate = inspect(args.candidate)
expected = set(reference["used_font_names"])
actual = set(candidate["used_font_names"])
report = {
"audit_completed": True,
"font_identity_sets_equal": expected == actual,
"reference_only_used_fonts": sorted(expected - actual),
"candidate_only_used_fonts": sorted(actual - expected),
"reference": reference,
"candidate": candidate,
"scope": "PDF text-span font identity/size audit; not rendering or full-format acceptance",
}
args.json.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({key: value for key, value in report.items()
if key not in ("reference", "candidate")}, indent=2))
if __name__ == "__main__":
main()
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env python3
"""Generate SVG paths from the exact Type1 programs embedded in math PDFs.
Requires fontTools only when regenerating. Runtime previews use the bundled
paths, so they need neither installed fonts nor an external conversion tool.
"""
import json
from pathlib import Path
from fontTools.pens.svgPathPen import SVGPathPen
from fontTools.t1Lib import T1Font
ROOT = Path(__file__).resolve().parent.parent
NAMES = ["cmr10", "cmr7", "cmr5", "cmmi10", "cmmi7", "cmmi5",
"cmsy10", "cmsy7", "cmsy5", "cmex10"]
result = []
for name in NAMES:
font = T1Font(str(ROOT / "assets/fonts" / (name + ".pfb")))
glyphs = font.getGlyphSet()
encoding = font["Encoding"]
paths = []
for slot in range(256):
glyph = encoding[slot]
if glyph == ".notdef" or glyph not in glyphs:
paths.append("")
continue
pen = SVGPathPen(glyphs)
glyphs[glyph].draw(pen)
paths.append(pen.getCommands())
result.append(paths)
output = ROOT / "crates/texrra-tex-core/assets/math-outlines.json"
output.write_text(json.dumps(result, separators=(",", ":")) + "\n")
print(output)
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env python3
"""Freeze independently decoded real pdfTeX Type3 masks for PK font tests.
Test generator only: pypdf parses real PDF glyph streams; the product PK
decoder is never called. Binary fixtures are the original installed PK files.
"""
from pathlib import Path
import argparse, hashlib, json, re, shutil, subprocess
from pypdf import PdfReader
import pypdf
ROOT=Path(__file__).resolve().parents[1]
def sha(data):return hashlib.sha256(data).hexdigest()
def main():
p=argparse.ArgumentParser(description=__doc__);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)
fixtures=ROOT/'crates/texrra-tex-core/tests/fixtures/pk';fixtures.mkdir(exist_ok=True)
texmf=Path(subprocess.check_output(['kpsewhich','--var-value=TEXMFDIST'],text=True).strip())
results={}
for name in ['cmr10','cmmi10','cmex10']:
d=out/name;d.mkdir(exist_ok=True)
source=(r'\catcode123=1\catcode125=2\pdfoutput=1\pdfcompresslevel=0\pdfobjcompresslevel=0\pdfmapfile{}\pdfpkresolution=600'
+f'\\font\\F={name}\\F'+r'\pdfpagewidth=1000pt\pdfpageheight=100pt\shipout\hbox{'
+''.join(f'\\char{i}\\kern0pt 'for i in range(128))+r'}\end')
(d/'source.tex').write_text(source)
r=subprocess.run(['pdftex','-ini','-etex','-interaction=nonstopmode','-halt-on-error','source.tex'],cwd=d,capture_output=True)
(d/'cli.log').write_bytes(r.stdout+r.stderr);r.check_returncode()
pdf=d/'source.pdf';reader=PdfReader(pdf,strict=True);font=next(iter(reader.pages[0]['/Resources']['/Font'].values())).get_object()
assert font['/Subtype']=='/Type3'
glyphs={}
for key,ref in font['/CharProcs'].items():
slot=int(str(key)[2:]);data=ref.get_data();header=re.match(rb'(-?[\d.]+) 0 (-?\d+) (-?\d+) (-?\d+) (-?\d+) d1\n',data);assert header
image=re.search(rb'/W (\d+)\s*/H (\d+)\s*/IM true\s*/BPC 1\s*/D \[1 0\]\s*ID ',data)
bitmap=b'';w=h=0
if image:
w,h=map(int,image.groups());length=((w+7)//8)*h;bitmap=data[image.end():image.end()+length]
assert data[image.end()+length:].startswith(b'\nEI\nQ\n')
glyphs[str(slot)]=dict(width_hundredths=round(float(header[1])*100),bbox=[int(v)for v in header.groups()[1:]],image_width=w,image_height=h,bitmap_sha256=sha(bitmap),bitmap_bytes=len(bitmap))
pk=texmf/f'fonts/pk/ljfour/public/cm/dpi600/{name}.pk';shutil.copyfile(pk,fixtures/f'{name}.600pk')
results[name]=dict(pk_sha256=sha(pk.read_bytes()),pk_source=str(pk),tfm_sha256=sha((ROOT/f'crates/texrra-tex-core/assets/{name}.tfm').read_bytes()),source_sha256=sha(source.encode()),pdf_sha256=sha(pdf.read_bytes()),font_matrix_scale=round(float(font['/FontMatrix'][0])*100000),font_bbox=[int(v)for v in font['/FontBBox']],glyphs=glyphs)
print(name,len(glyphs),'independent glyph masks',flush=True)
report=dict(reference_version=subprocess.check_output(['pdftex','--version'],text=True).splitlines()[0],pypdf_version=pypdf.__version__,method='Real pdfTeX PK Type3 charprocs independently decompressed by pypdf; product decoder never invoked',fonts=results)
(fixtures/'oracle.json').write_text(json.dumps(report,indent=2)+'\n')
if __name__=='__main__':main()
+62
View File
@@ -0,0 +1,62 @@
#!/usr/bin/env python3
"""Freeze independent fontTools Type1 path hashes for all actual bundled PFBs.
fontTools is needed only to regenerate this test oracle, never by the kernel.
Paths are unhinted, absolute M/L/C/Z commands in the standard 1000-unit space.
"""
import hashlib,json,math
from pathlib import Path
from fontTools.t1Lib import T1Font
from fontTools.pens.recordingPen import DecomposingRecordingPen
from fontTools.pens.transformPen import TransformPen
from fontTools.misc.psCharStrings import T1CharString
ROOT=Path(__file__).resolve().parents[1]
def number(v):return format(v,'.6f').rstrip('0').rstrip('.')
def canonical(commands):
out=[]
for op,args in commands:
if op=='endPath':continue
if op=='closePath':out.append('Z');continue
if op not in ['moveTo','lineTo','curveTo']:raise ValueError(op)
out.append({'moveTo':'M','lineTo':'L','curveTo':'C'}[op]+ ' '.join(number(v) for point in args for v in point))
return ''.join(out)
# A valid, independently serialized program exercises seac, subroutines, div,
# lenIV=0, nonstandard FontMatrix, and glyphs absent from the builtin encoding.
fixture=ROOT/'crates/texrra-tex-core/tests/fixtures/type1-fixture.pfb'
f=T1Font(str(ROOT/'assets/fonts/cmr10.pfb'));f.parse()
f.font['FontName']='NativeType1Fixture'
f.font.pop('UniqueID',None)
f.font['FontMatrix']=[.002,0,.0005,.001,.01,-.02]
f.font['FontBBox']=[-100,-100,1000,1000]
private={'lenIV':0,**f.font['Private']};private.pop('UniqueID',None)
private['Subrs']=[T1CharString(program=[100,0,'rlineto',0,100,'rlineto',-100,0,'rlineto','closepath','return'])]
f.font['Private']=private
programs={
'.notdef':[0,600,'hsbw','endchar'],
'A':[0,600,'hsbw',50,0,'rmoveto',200,600,'rlineto',200,-600,'rlineto','closepath','endchar'],
'acute':[0,300,'hsbw',100,650,'rmoveto',100,100,'rlineto',50,0,'rlineto',-100,-100,'rlineto','closepath','endchar'],
'Aacute':[0,600,'hsbw',0,0,0,65,194,'seac'],
'divided':[0,600,'hsbw',100,3,'div',0,'rmoveto',200,0,'rlineto',10,20,30,40,50,60,'rrcurveto','closepath','endchar'],
'subr':[0,600,'hsbw',100,100,'rmoveto',0,'callsubr','endchar'],
}
programs['uni00410301']=programs['A'];programs['u1F600']=programs['A']
f.font['CharStrings']={n:T1CharString(program=v,subrs=private['Subrs']) for n,v in programs.items()}
f.saveAs(str(fixture),'PFB')
faces=[]
paths=sorted((ROOT/'assets/fonts').glob('*.pfb'))+[fixture]
for path in paths:
f=T1Font(str(path));glyphs=f.getGlyphSet();matrix=[n*1000 for n in f['FontMatrix']]
records={}
for name,glyph in sorted(glyphs.items()):
pen=DecomposingRecordingPen(glyphs);glyph.draw(TransformPen(pen,matrix));d=canonical(pen.value)
records[name]=hashlib.sha256(d.encode()).hexdigest()
bbox=f['FontBBox']
corners=[(matrix[0]*x+matrix[2]*y+matrix[4],matrix[1]*x+matrix[3]*y+matrix[5]) for x in [bbox[0],bbox[2]] for y in [bbox[1],bbox[3]]]
normalized_bbox=[math.floor(min(p[0] for p in corners)),math.floor(min(p[1] for p in corners)),math.ceil(max(p[0] for p in corners)),math.ceil(max(p[1] for p in corners))]
stem=f['Private'].get('StdVW',[0])[0]
faces.append(dict(file=path.name,path=str(path.relative_to(ROOT)),sha256=hashlib.sha256(path.read_bytes()).hexdigest(),
italic_angle=f['FontInfo'].get('ItalicAngle',0),fixed_pitch=bool(f['FontInfo'].get('isFixedPitch',False)),
stem_v=round(stem*abs(matrix[0])),normalized_bbox=normalized_bbox,glyphs=records))
out=ROOT/'crates/texrra-tex-core/tests/fixtures/type1-outlines.json'
out.write_text(json.dumps(dict(source='fontTools 4.68.0 T1OutlineExtractor + DecomposingRecordingPen; independent of Rust decoder',faces=faces),indent=2)+'\n')
print(len(faces),'actual PFB files;',sum(len(f['glyphs']) for f in faces),'complete glyph programs;',out)
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Absolute-page math gate for the arXiv fixture (stdlib + Poppler).
This selects the fixture's wide fraction rule from vector output and also
compares the formula ink bounds at 144dpi. No rendering offsets are fitted.
"""
import argparse
import json
import re
import subprocess
import tempfile
from pathlib import Path
def run(*args):
return subprocess.check_output([str(a) for a in args])
def native_rule(pdf):
data = Path(pdf).read_bytes()
paper = re.search(rb"/MediaBox\s*\[0 0 ([\d.]+) ([\d.]+)\]", data)
height = float(paper[2])
candidates = []
for stream in re.findall(rb"stream\r?\n(.*?)endstream", data, re.S):
if b"BT /M" not in stream:
continue
origin = re.search(rb"1 0 0 1 ([-\d.]+) ([-\d.]+) cm", stream)
dx, dy = map(float, origin.groups()) if origin else (0, 0)
for rect in re.finditer(rb"([-\d.]+) ([-\d.]+) ([-\d.]+) ([-\d.]+) re f", stream):
x, y, width, thickness = map(float, rect.groups())
if 150 < width < 200 and x + dx > 250 and 0 < thickness < 1:
candidates.append(dict(x=x + dx, y=height - y - dy - thickness / 2,
width=width, thickness=thickness))
assert len(candidates) == 1, candidates
return candidates[0]
def reference_rule(pdf, directory):
svg = directory / "reference.svg"
run("pdftocairo", "-f", 2, "-l", 2, "-svg", pdf, svg)
candidates = []
for path in re.findall(r"<path\b[^>]*>", svg.read_text()):
line = re.search(r'd="M ([-\d.]+) ([-\d.]+) L ([-\d.]+) ([-\d.]+)\s*"', path)
matrix = re.search(r'transform="matrix\(([^)]+)\)"', path)
stroke = re.search(r'stroke-width="([-\d.]+)"', path)
if not (line and matrix and stroke):
continue
x1, y1, x2, y2 = map(float, line.groups())
a, b, c, d, e, f = map(float, matrix[1].split(","))
left, right = sorted((a*x1 + c*y1 + e, a*x2 + c*y2 + e))
width = right - left
if 150 < width < 200 and left > 250 and float(stroke[1]) < 1:
candidates.append(dict(x=left, y=b*(x1+x2)/2+d*(y1+y2)/2+f,
width=width, thickness=float(stroke[1])))
assert len(candidates) == 1, candidates
return candidates[0]
def ink_bounds(pdf, output, crop):
run("pdftoppm", "-f", 2, "-l", 2, "-singlefile", "-r", 144, "-gray", pdf, output)
data = output.with_suffix(".pgm").read_bytes()
header = re.match(rb"P5\s+(\d+)\s+(\d+)\s+255\s", data)
assert header
width, height = map(int, header.groups())
pixels = data[header.end():]
assert len(pixels) == width * height
left, top, right, bottom = crop
points = [(x, y) for y in range(top, bottom) for x in range(left, right)
if pixels[y * width + x] < 200]
assert points
xs, ys = zip(*points)
return [min(xs), min(ys), max(xs), max(ys)]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--reference", type=Path, required=True)
parser.add_argument("--candidate", type=Path, required=True)
parser.add_argument("--json", type=Path, required=True)
args = parser.parse_args()
with tempfile.TemporaryDirectory(prefix="texrra-absolute-math-") as temporary:
directory = Path(temporary)
reference = reference_rule(args.reference, directory)
native = native_rule(args.candidate)
errors = {key: native[key] - reference[key] for key in reference}
crop = (240, int((reference["y"] - 17) * 2), 1100, int((reference["y"] + 18) * 2))
reference_ink = ink_bounds(args.reference, directory / "reference", crop)
native_ink = ink_bounds(args.candidate, directory / "native", crop)
pages = [int(re.search(rb"Pages:\s*(\d+)", run("pdfinfo", pdf))[1])
for pdf in (args.reference, args.candidate)]
passed = (pages == [3, 3] and all(abs(value) <= 1 for value in errors.values())
and all(abs(a-b) <= 2 for a, b in zip(reference_ink, native_ink)))
result = dict(passed=passed, pages=pages, reference_rule_bp=reference,
native_rule_bp=native, error_bp=errors,
reference_ink_bbox_144dpi=reference_ink,
native_ink_bbox_144dpi=native_ink,
tolerances=dict(vector_bp=1, ink_bbox_pixels=2))
args.json.write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps(result, indent=2))
assert passed, "absolute-page math acceptance failed"
if __name__ == "__main__":
main()
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""Compare actual native accent ink with fresh INITEX output at 144dpi.
Wide CMEX accents/vector lack equivalent Unicode metadata in the reference;
this gate compares actual outlines/positions. Use accent-text.tex with the
unchanged paragraph PDF gate for matching Unicode text and word boxes.
"""
import argparse
import hashlib
import json
import os
import re
import subprocess
from pathlib import Path
def run(args, directory, env=None):
r = subprocess.run([str(a) for a in args], cwd=directory, env=env,
capture_output=True, text=True)
if r.returncode:
raise RuntimeError(r.stdout+'\n'+r.stderr)
return r.stdout+r.stderr
def raster(pdf, base):
run(['pdftoppm', '-singlefile', '-gray', '-r', '144', pdf, base], pdf.parent)
data = base.with_suffix('.pgm').read_bytes()
m = re.match(rb'P5\s+(\d+)\s+(\d+)\s+255\s', data)
assert m
width, height = map(int, m.groups())
pixels = data[m.end():]
assert len(pixels) == width*height
return width, height, {i for i, p in enumerate(pixels) if p < 200}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--binary', type=Path, required=True)
parser.add_argument('--output-dir', type=Path, required=True)
parser.add_argument('--json', type=Path, required=True)
parser.add_argument('--fixture', type=Path, help='native math fixture; defaults to accents.tex')
parser.add_argument('--expected-font', action='append', dest='expected_fonts',
help='required embedded font name; repeat for a different font fixture')
args = parser.parse_args()
root = Path(__file__).resolve().parent.parent
fixture = args.fixture.resolve() if args.fixture else root/'examples/native-bootstrap/accents.tex'
stem = fixture.stem
source = fixture.read_text()
out = args.output_dir.resolve()
out.mkdir(parents=True, exist_ok=True)
(out/'reference.tex').write_text('\\pdfoutput=1 \\pdfpagewidth=612bp '
'\\pdfpageheight=792bp \\vsize=648bp \\topskip=10bp\n'+source)
(out/'native-cli.txt').write_text(run([args.binary.resolve(), 'native',
'--initex', '--etex', fixture, out/(stem+'.pdf')], out))
(out/'reference-cli.txt').write_text(run(['pdftex', '-ini', '-etex',
'-interaction=nonstopmode', '-halt-on-error', 'reference.tex'], out,
{**os.environ, 'TEXINPUTS':str(fixture.parent)+os.pathsep+os.environ.get('TEXINPUTS','')}))
native = raster(out/(stem+'.pdf'), out/'native')
reference = raster(out/'reference.pdf', out/'reference')
assert native[:2] == reference[:2]
width, height, ni = native
ri = reference[2]
assert ni and ri
def unmatched(a, b):
return sum(not any(i+dy*width+dx in b for dy in [-1,0,1]
for dx in [-1,0,1]) for i in a)
def bbox(a):
return [min(i%width for i in a), min(i//width for i in a),
max(i%width for i in a), max(i//width for i in a)]
un, ur = unmatched(ni, ri), unmatched(ri, ni)
different = len(ni ^ ri)
nb, rb = bbox(ni), bbox(ri)
pdfs = [out/(stem+'.pdf'), out/'reference.pdf']
pages = [int(re.search(r'Pages:\s*(\d+)',run(['pdfinfo', p], out))[1]) for p in pdfs]
fonts = [run(['pdffonts', p], out) for p in pdfs]
texts = [run(['pdftotext', '-layout', p, '-'], out) for p in pdfs]
for name, text in zip(['native', 'reference'], texts):
(out/(name+'.txt')).write_text(text)
passed = (pages == [1,1] and un == ur == 0
and all(abs(a-b) <= 1 for a,b in zip(nb,rb))
and different <= len(ri)*.01
and all(all(name in f for name in (args.expected_fonts or ['CMR10','CMMI10','CMEX10'])) for f in fonts)
and '\ufffd' not in texts[0])
result = dict(passed=passed,source_sha256=hashlib.sha256(source.encode()).hexdigest(),
pages=pages,raster_size=[width,height],native_ink=len(ni),reference_ink=len(ri),
different_pixels=different,unmatched_native=un,unmatched_reference=ur,
native_bbox=nb,reference_bbox=rb,text_equal=texts[0]==texts[1],
native_fonts=fonts[0],reference_fonts=fonts[1],
tolerances=dict(dpi=144,ink_threshold=200,coverage_radius_pixels=1,bbox_pixels=1,max_xor_ratio=.01),
scope='Absolute whole-page native math ink; no fitted offsets. Reference extension-font Unicode metadata can differ; matching-Unicode word boxes are gated separately.')
args.json.parent.mkdir(parents=True,exist_ok=True)
args.json.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n')
print(json.dumps({k:v for k,v in result.items() if k not in ['native_fonts','reference_fonts']},indent=2))
if not passed:
raise SystemExit(1)
if __name__ == '__main__':
main()
+141
View File
@@ -0,0 +1,141 @@
#!/usr/bin/env python3
"""Exact supported input-context/show differential; preserve raw oracle artifacts.
External INITEX is used only by this acceptance program. Native jobs use their
own token executor. Fatal probes halt; show probes continue with status one.
"""
import argparse
import hashlib
import json
import re
import subprocess
from pathlib import Path
HEADER = r'\catcode123=1\catcode125=2\catcode35=6\catcode94=7\catcode0=12\catcode127=12\errorcontextlines=100 '
def cases():
nested = r'\def\A{\B\relax}\def\B{\C\relax}\def\C{\bad\relax}\A\end'
for limit in [-2, -1, 0, 1, 2, 100]:
yield f'limit-{limit}', HEADER + f'\\errorcontextlines={limit}\n' + nested + '\n', {}, 'fatal'
bodies = {
'tail': r'\def\A{\B}\def\B{\bad}\A\end',
'argument': r'\def\A#1{#1\relax}\A{\bad x}\end',
'alias': r'\def\A#1x{#1\relax}\let\alias\A\alias\bad x\end',
'active': r'\catcode33=13\def!{\bad\relax}!\end',
'edef': r'\def\A{\bad x}\edef\B{\A z}\end',
'message': r'\def\A{\bad x}\message{\A z}\end',
'expanded': r'\def\A{\bad x}\expanded{\A z}\end',
'inserted': r'\unexpanded{\bad}\end',
'backed-up': r'\expandafter\bad\relax\end',
'write': r'\immediate\write16{\bad}\end',
'hyphenation': r'\def\A{\bad x}\hyphenation{\A z}\end',
'parameter-char': r'\catcode33=6\def\A!1{!1\relax}\A{\bad x}\end',
'byte-body': r'\def\A{\^^62ad ^^00 ^^7f ^^c8}\A\end',
}
for name, body in bodies.items():
yield name, HEADER + '\n' + body + '\n', {}, 'fatal'
yield 'nested-source', HEADER + '\n\\input child \\end\n', {'child': '\\def\\A{\\bad x}\n\\A\\endinput\n'}, 'fatal'
for before, after in [(0, 100), (100, 0), (100, 100)]:
yield f'crop-{before}-{after}', HEADER + '\n' + '\\relax ' * before + '\\bad ' + '\\relax ' * after + '\\end\n', {}, 'fatal'
for name, body in {
'show-raw': r'\show\relax',
'show-undefined': r'\show\unknown',
'show-macro': r'\long\def\A#1x{hello #1}\show\A',
'show-parameters': r'\catcode33=6\def\A#1!2{#1!2}\show\A',
'showthe-count': r'\count0=17\showthe\count0\relax',
'showthe-glue': r'\skip0=1pt plus2fil minus3pt\showthe\skip0\relax',
'showthe-toks': r'\toks0={\relax ## x}\showthe\toks0\relax',
}.items():
yield name, HEADER + '\n' + body + r'\message{G1_AFTER_SHOW}\end' + '\n', {}, 'show'
for online in [-1, 0, 1]:
for message in [False, True]:
body = (f'\\tracingonline={online}' + r'\setbox0=\hbox{}\showboxbreadth=20\showboxdepth=20'
+ (r'\message{BEFORE_SHOW}' if message else '') + '\n'
+ r'\showbox0\relax\message{G1_AFTER_SHOW}\end')
yield f'showbox-{online}-{int(message)}', HEADER + '\n' + body + '\n', {}, 'showbox'
yield 'errmessage', HEADER + '\n' + r'\def\A#1{\B{#1}\relax}\def\B#1{\C{#1}\relax}\def\C#1{\errmessage{AUDIT_NESTED_ERROR}}\A{X}' + '\n\\end\n', {}, 'errmessage'
mark = r'\setbox1=\vbox{\mark{\noexpand\bad x}\hbox{}}\setbox0=\vsplit1 to0pt\relax '
for limit in [-2, -1, 0, 1, 2, 100]:
yield f'split-mark-limit-{limit}', HEADER + '\n' + f'\\errorcontextlines={limit}' + mark + r'\splitfirstmark\end' + '\n', {}, 'fatal'
for name, action in {
'alias': r'\let\K=\splitbotmark\def\A{\K\relax}\A',
'message': r'\message{\splitfirstmark}',
'edef': r'\edef\A{\splitbotmark}',
}.items():
yield 'split-mark-' + name, HEADER + '\n' + mark + action + '\\end\n', {}, 'fatal'
yield 'split-marks-extended', HEADER + '\n' + r'\setbox1=\vbox{\marks32767{\noexpand\bad x}\hbox{}}\setbox0=\vsplit1 to0pt\relax\splitbotmarks32767\end' + '\n', {}, 'fatal'
long_mark = r'\setbox1=\vbox{\mark{' + r'\noexpand\relax ' * 100 + r'\noexpand\bad ' + r'\noexpand\relax ' * 100 + r'}\hbox{}}\setbox0=\vsplit1 to0pt\relax\splitfirstmark\end'
yield 'split-mark-crop', HEADER + '\n' + long_mark + '\n', {}, 'fatal'
for limit in [-2, -1, 0, 1, 2, 100]:
for name, action in {
'direct': r'\bad x',
'macro': r'\A\relax',
'message': r'\message{\bad x}',
'write': r'\immediate\write16{\bad x}',
}.items():
source = (HEADER + f'\\errorcontextlines={limit}'
+ r'\vsize=20pt\topskip=10pt\maxdepth=2pt\def\A{\bad x}'
+ f'\\output{{{action}}}\n' + r'\hbox{}\penalty-10000\end' + '\n')
yield f'output-{name}-limit-{limit}', source, {}, 'fatal-job'
def run(binary, out, item):
name, source, files, kind = item
d = out / name
d.mkdir(parents=True, exist_ok=True)
(d / 'probe.tex').write_text(source)
before = hashlib.sha256((d / 'probe.tex').read_bytes()).hexdigest()
for file, text in files.items():
(d / file).write_text(text)
pdf = d / 'native.pdf'
pdf.write_bytes(b'KEEP_EXISTING_PDF')
n = subprocess.run([str(binary), 'native', '--initex', '--etex']
+ (['--job'] if kind == 'fatal-job' else [])
+ ['probe.tex', 'native.pdf'], cwd=d, capture_output=True, text=True, timeout=30)
args = ['pdftex', '-ini', '-etex', '-interaction=nonstopmode']
if kind not in ['show', 'showbox']:
args += ['-halt-on-error']
r = subprocess.run(args + ['probe.tex'], cwd=d, capture_output=True, text=True, timeout=30)
for label, p in [('native', n), ('reference', r)]:
(d / (label + '-stdout.txt')).write_text(p.stdout)
(d / (label + '-stderr.txt')).write_text(p.stderr)
transcript = (d / 'native.log').read_text()
if kind in ['show', 'showbox']:
prefix = '> ' if kind == 'show' else '! OK'
exact = r.stdout[r.stdout.index(prefix):r.stdout.rindex('G1_AFTER_SHOW')]
reference_log = (d / 'probe.log').read_text()
exact_log = reference_log[reference_log.index(prefix):reference_log.rindex('G1_AFTER_SHOW')]
equal = exact in n.stderr and exact_log in transcript and 'error:' not in n.stderr
else:
header = '! AUDIT_NESTED_ERROR.\n' if kind == 'errmessage' else '! Undefined control sequence.\n'
exact = r.stdout.split(header, 1)[1].split('No pages of output.', 1)[0]
native_header = re.search(r'(?m)^! [^\n]*\n', n.stderr)
error = re.search(r'(?m)^error: ', n.stderr)
actual = n.stderr[native_header.end():error.start()] if native_header and error else None
equal = actual == exact and exact in transcript
result = dict(id=name, kind=kind, exit_codes=[n.returncode, r.returncode], exact_body_context_equal=equal,
pdf_protected=pdf.read_bytes() == b'KEEP_EXISTING_PDF', source_sha256=before,
source_unchanged=before == hashlib.sha256((d / 'probe.tex').read_bytes()).hexdigest())
result['passed'] = result['exit_codes'] == [1, 1] and equal and result['pdf_protected'] and result['source_unchanged']
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 = [run(a.binary.resolve(), out, item) for item in cases()]
report = dict(passed=all(r['passed'] for r in results), cases=len(results), results=results,
scope='Exact supported body/context bytes and real status/channels; general interactive recovery, showlists and compound math diagnostics are outside G1.')
(out / 'audit.json').write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps(report, indent=2))
if not report['passed']:
raise SystemExit(1)
if __name__ == '__main__':
main()
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env python3
"""Independent actual PDF device/mag/true oracle; unchanged physical tolerances.
Every synthetic input is identical for native and reference execution. External
TeX is used only here, never by the product. Retain all source/PDF/aux evidence.
"""
import argparse
import hashlib
import importlib.util
import json
import os
import re
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def module(name, file):
spec = importlib.util.spec_from_file_location(name, ROOT/'scripts'/file)
result = importlib.util.module_from_spec(spec)
spec.loader.exec_module(result)
return result
INK = module('native_page_ink', 'check-native-pages.py')
WORDS = module('native_page_words', 'check-native-paragraphs.py')
def cases():
fixture = ROOT/'examples/native-bootstrap/device.tex'
yield 'original-device-fixture', fixture.read_text(), fixture.parent, 3, ['cmr10', 'cmmi7']
fonts = (ROOT/'examples/native-bootstrap/math-fonts.tex').read_text()
for mag in [500, 1000, 1095, 1200, 2000, 4096]:
for unit in ['pt', 'truept']:
source = (fonts + f'\\mag={mag}\\pdfpagewidth=180{unit}\\pdfpageheight=140{unit}'
+ f'\\pdfhorigin=10{unit}\\pdfvorigin=12{unit}'
+ r'\hoffset=2pt\voffset=3pt\count0=1\immediate\openout1=device.aux'
+ r'\setbox0=\vbox{\hbox{Native AV office $x_i^j+y$}\kern2pt\hrule height1pt depth2pt'
+ r'\write1{SHIP=\number\count0;MAG=\number\mag}}\shipout\copy0'
+ r'{\pdfpagewidth=0pt\pdfpageheight=0pt\hoffset=-1pt\voffset=2pt'
+ r'\count0=2\shipout\box0}'
+ r'\pdfpagewidth=999pt\pdfpageheight=888pt\pdfhorigin=123pt'
+ '\\immediate\\closeout1\\end\n')
yield f'mag-{mag}-{unit}', source, fixture.parent, 2, ['cmr10', 'cmmi7']
for mag in [1, 32768]:
# Keep the actual TeX font size below its 2048pt limit at mag=1.
font_size = 2 if mag == 1 else 10
source = (r'\catcode123=1\catcode125=2' + f'\\mag={mag}'
+ f'\\font\\physical=cmr10 at{font_size}truept\\physical'
+ r'\pdfpagewidth=12truept\pdfpageheight=12truept'
+ r'\pdfhorigin=1truept\pdfvorigin=1truept\count0=1'
+ r'\immediate\openout1=device.aux\shipout\hbox{A'
+ r'\vrule width1truept height2truept depth.5truept'
+ r'\write1{SHIP=\number\count0;MAG=\number\mag}}'
+ '\\immediate\\closeout1\\end\n')
yield f'mag-boundary-{mag}', source, fixture.parent, 1, ['cmr10']
def mediaboxes(path):
# Poppler resolves both classic and compressed object/xref layouts.
text = INK.run(['pdftotext', '-bbox', path, '-'], path.parent)
return [[0.0, 0.0, float(w), float(h)] for w, h in re.findall(
r'<page\s+width="([-.\d]+)"\s+height="([-.\d]+)"', text)]
def audit(binary, out, item):
name, source, inputs, count, expected_fonts = item
d = out/name
n, r = d/'native', d/'reference'
n.mkdir(parents=True, exist_ok=True)
r.mkdir(parents=True, exist_ok=True)
file = d/'source.tex'
file.write_text(source)
# Preserve the fixture's project input bytes alongside the copied main
# source; native project lookup uses its actual source directory.
(d/'math-fonts.tex').write_bytes((ROOT/'examples/native-bootstrap/math-fonts.tex').read_bytes())
before = hashlib.sha256(file.read_bytes()).hexdigest()
run = INK.run
(n/'cli.log').write_text(run([binary, 'native', '--job', '--initex', '--etex',
'--resource-manifest', n/'resources.json', file, n/'job.pdf'], n))
(r/'reference.tex').write_text('\\pdfoutput=1\\pdfcompresslevel=0\\pdfobjcompresslevel=0\n'
+ f'\\input "{file.as_posix()}"\n')
(r/'cli.log').write_text(run(['pdftex', '-ini', '-etex', '-interaction=nonstopmode',
'-halt-on-error', 'reference.tex'], r,
{**os.environ, 'TEXINPUTS': str(inputs)+os.pathsep+os.environ.get('TEXINPUTS', '')}))
pdfs = [n/'job.pdf', r/'reference.pdf']
media = [mediaboxes(p) for p in pdfs]
page_counts = [len(m) for m in media]
paper_equal = (page_counts == [count, count] and all(a == b
for am, bm in zip(*media) for a, b in zip(am, bm)))
words = [WORDS.words(p) for p in pdfs]
text_equal = ([[w[0] for w in p] for p in words[0]] == [[w[0] for w in p] for p in words[1]])
flat = [[w for p in pages for w in p] for pages in words]
errors = {k: max(abs(a[1][k]-b[1][k]) for a, b in zip(*flat))
for k in ['xMin', 'xMax', 'yMin', 'yMax']} if text_equal and all(flat) else None
ink = []
if paper_equal:
for page in range(1, count+1):
v = INK.ink_report(INK.raster(pdfs[0], n/f'page-{page}', page),
INK.raster(pdfs[1], r/f'page-{page}', page))
v['page'] = page
ink.append(v)
aux = [p.read_bytes() for p in [n/'device.aux', r/'device.aux']]
trace = json.loads((n/'resources.json').read_text())
resources = all(any(v['path'].endswith(font+suffix) for v in trace['reads'])
for font in expected_fonts for suffix in ['.tfm', '.pfb'])
source_unchanged = hashlib.sha256(file.read_bytes()).hexdigest() == before
passed = (paper_equal and text_equal and errors is not None and max(errors.values()) <= .02
and len(ink) == count and all(v['passed'] for v in ink) and aux[0] == aux[1]
and bool(aux[0]) and resources and source_unchanged)
result = dict(id=name, passed=passed, page_counts=page_counts, media_boxes=media, paper_equal=paper_equal,
text_equal=text_equal, word_counts=[len(v) for v in flat], max_word_box_errors_bp=errors,
ink=ink, aux_equal=aux[0] == aux[1], aux_hex=aux[0].hex(),
expected_fonts=expected_fonts, actual_resources_verified=resources, source_sha256=before, source_unchanged=source_unchanged)
(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)
args = p.parse_args()
out = args.output_dir.resolve()
out.mkdir(parents=True, exist_ok=True)
results = []
for item in cases():
result = audit(args.binary.resolve(), out, item)
results.append(result)
print(result['id'], 'passed' if result['passed'] else 'FAILED', result['max_word_box_errors_bp'], flush=True)
report = dict(passed=all(r['passed'] for r in results), cases=len(results),
pages=sum(r['page_counts'][0] for r in results), results=results,
binary_sha256=hashlib.sha256(args.binary.resolve().read_bytes()).hexdigest(),
reference_version=INK.run(['pdftex', '--version'], out).splitlines()[0],
tolerances=dict(word_box_bp=.02, media_box_bp=0, dpi=144,
ink_threshold=200, coverage_radius_pixels=1, bbox_pixels=1, max_xor_ratio=.01),
scope='Actual native per-shipout paper/origin/offset/mag/true and late I/O; full PDF configuration and format startup remain incomplete.')
(out/'audit.json').write_text(json.dumps(report, indent=2)+'\n')
if not report['passed']:
raise SystemExit(1)
if __name__ == '__main__':
main()
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Verify real showbox status/channels, exact bodies and continued PDF output.
Both jobs must return TeX's intentional show diagnostic status 1. Unexpected
errors remain failures. The runtime native engine never invokes TeX.
"""
import argparse
import json
import os
import re
import subprocess
import xml.etree.ElementTree as ET
from pathlib import Path
def words(pdf):
data=subprocess.check_output(['pdftotext','-bbox',str(pdf),'-'])
pdf.with_suffix('.bbox.html').write_bytes(data)
return [[(w.text,{k:float(v)for k,v in w.attrib.items()})for w in p.iter()if w.tag.endswith('}word')]
for p in ET.fromstring(data).iter()if p.tag.endswith('}page')]
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--binary',type=Path,required=True)
p.add_argument('--output-dir',type=Path,required=True)
p.add_argument('--json',type=Path,required=True)
a=p.parse_args();root=Path(__file__).resolve().parent.parent
fixture=root/'examples/native-bootstrap/diagnostics.tex';out=a.output_dir.resolve();out.mkdir(parents=True,exist_ok=True)
(out/'reference.tex').write_text('\\pdfoutput=1 \\pdfpagewidth=612bp \\pdfpageheight=792bp '
'\\vsize=648bp \\topskip=10bp\n'+fixture.read_text())
env={**os.environ,'TEXINPUTS':str(fixture.parent)+os.pathsep+os.environ.get('TEXINPUTS','')}
native=subprocess.run([str(a.binary.resolve()),'native','--initex','--etex',str(fixture),'diagnostics.pdf'],cwd=out,capture_output=True,text=True)
reference=subprocess.run(['pdftex','-ini','-etex','-interaction=nonstopmode','reference.tex'],cwd=out,env=env,capture_output=True,text=True)
for name,r in [('native',native),('reference',reference)]:
(out/(name+'-stdout.txt')).write_text(r.stdout);(out/(name+'-stderr.txt')).write_text(r.stderr)
logs=[(out/n).read_text()for n in ['diagnostics.log','reference.log']]
bodies=[re.findall(r'(?ms)^> \\box\d+=.*?(?=\n! OK\.)',s)for s in logs]
only_show_errors=all([l for l in s.splitlines()if l.startswith('! ')]==['! OK.']*5 for s in logs)
pdfs=[out/'diagnostics.pdf',out/'reference.pdf'];pages=[words(f)for f in pdfs]
text_equal=[[w[0]for w in page]for page in pages[0]]==[[w[0]for w in page]for page in pages[1]]
n=[w for page in pages[0]for w in page];r=[w for page in pages[1]for w in page]
errors={k:max(abs(x[1][k]-y[1][k])for x,y in zip(n,r))for k in ['xMin','xMax','yMin','yMax']}if text_equal and n else None
channels=('see the transcript file'in native.stderr and 'see the transcript file'not in logs[0]
and 'BEFORE_SHOWS'in native.stderr and 'AFTER_SHOWS'in native.stderr)
passed=([native.returncode,reference.returncode]==[1,1]and only_show_errors and'error:'not in native.stderr
and bodies[0]==bodies[1]and len(bodies[0])==5 and channels and all('AFTER_SHOWS'in s for s in logs)
and text_equal and[len(p)for p in pages]==[1,1]and errors is not None and max(errors.values())<=.02)
result=dict(passed=passed,exit_codes=[native.returncode,reference.returncode],show_counts=list(map(len,bodies)),
diagnostic_bodies_equal=bodies[0]==bodies[1],channels_verified=channels,only_show_errors=only_show_errors,
pages=list(map(len,pages)),word_counts=[len(n),len(r)],text_equal=text_equal,max_word_box_errors_bp=errors,
scope='Intentional nonstop show diagnostics, exact supported box bodies and unchanged 0.02bp PDF gate; source-context/error recovery is not certified.')
a.json.parent.mkdir(parents=True,exist_ok=True);a.json.write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
if not passed:raise SystemExit(1)
if __name__=='__main__':
main()
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Compare all 128 real CMR10 OT1 slots with pdfTeX at actual page positions.
The native/runtime engine never calls TeX. This external fixture oracle checks
per-cell ink at 144dpi; metadata labels cannot hide a substituted font or slot.
"""
import argparse,json,re,subprocess
from pathlib import Path
def run(args,cwd):
r=subprocess.run([str(a) for a in args],cwd=cwd,capture_output=True,text=True)
if r.returncode:raise RuntimeError(r.stdout+'\n'+r.stderr)
return r.stdout+r.stderr
def raster(pdf,base):
run(['pdftoppm','-singlefile','-gray','-r',144,pdf,base],pdf.parent)
data=base.with_suffix('.pgm').read_bytes();m=re.match(rb'P5\s+(\d+)\s+(\d+)\s+255\s',data)
assert m;w,h=map(int,m.groups());pixels=data[m.end():];assert len(pixels)==w*h
return w,h,pixels
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--binary',type=Path,required=True);p.add_argument('--output-dir',type=Path,required=True);p.add_argument('--json',type=Path,required=True);a=p.parse_args()
root=Path(__file__).resolve().parent.parent;out=a.output_dir.resolve();out.mkdir(parents=True,exist_ok=True)
source=(root/'examples/native-bootstrap/font-slots.tex').read_text();(out/'reference.tex').write_text('\\pdfoutput=1 \\pdfpagewidth=612bp \\pdfpageheight=792bp \\vsize=648bp \\topskip=10bp\n'+source)
(out/'native-cli.txt').write_text(run([a.binary.resolve(),'native','--initex','--etex',root/'examples/native-bootstrap/font-slots.tex',out/'slots.pdf'],out))
(out/'reference-cli.txt').write_text(run(['pdftex','-ini','-etex','-interaction=nonstopmode','-halt-on-error','reference.tex'],out))
native=raster(out/'slots.pdf',out/'native');reference=raster(out/'reference.pdf',out/'reference');assert native[:2]==reference[:2]
w,h,_=native;cells=[]
for slot in range(128):
row,col=divmod(slot,16);left=144+int(col*20*144/72.27);right=144+int((col+1)*20*144/72.27)
top=144+int(row*18*144/72.27);bottom=144+int((row+1)*18*144/72.27)
indices=[y*w+x for y in range(top,bottom) for x in range(left,right)]
ni={i for i in indices if native[2][i]<200};ri={i for i in indices if reference[2][i]<200};diff=len(ni^ri)
# Absolute subpixel text positioning can change edge coverage in
# Poppler. Require every ink pixel to have a counterpart within one
# pixel, matching bounding boxes, and a strict whole-grid XOR bound.
def unmatched(a,b):
return sum(not any(i+dy*w+dx in b for dy in [-1,0,1] for dx in [-1,0,1]) for i in a)
def bbox(a):
return [min(i%w for i in a),min(i//w for i in a),max(i%w for i in a),max(i//w for i in a)] if a else None
nb,rb=bbox(ni),bbox(ri)
bounds_ok=(nb is None and rb is None) or (nb is not None and rb is not None and all(abs(a-b)<=1 for a,b in zip(nb,rb)))
un,ur=unmatched(ni,ri),unmatched(ri,ni)
cells.append(dict(slot=slot,native_ink=len(ni),reference_ink=len(ri),different_pixels=diff,unmatched_native=un,unmatched_reference=ur,native_bbox=nb,reference_bbox=rb,passed=bounds_ok and un==0 and ur==0))
pages=[int(re.search(r'Pages:\s*(\d+)',run(['pdfinfo',out/name],out))[1]) for name in ['slots.pdf','reference.pdf']]
ink=sum(c['reference_ink'] for c in cells);different=sum(c['different_pixels'] for c in cells)
result=dict(passed=all(c['passed'] for c in cells) and pages==[1,1] and different<=ink*.01,pages=pages,slots=128,dpi=144,cells=cells,total_different_pixels=different,reference_ink_pixels=ink,tolerances=dict(coverage_radius_pixels=1,bbox_pixels=1,max_xor_fraction=.01),scope='CMR10 raw OT1 slot grid; real TFM/Type1 resources, no Unicode-font substitution')
a.json.resolve().write_text(json.dumps(result,indent=2)+'\n');print(json.dumps({k:result[k] for k in ['passed','pages','slots','dpi','total_different_pixels']}));assert result['passed'],[c for c in cells if not c['passed']]
if __name__=='__main__':main()
+343
View File
@@ -0,0 +1,343 @@
#!/usr/bin/env python3
"""Run the frozen article corpus from an actual native pdflatex.ini dump.
Records format/job resource traces and checks PDF-side gates independently.
Native 1sp geometry and raw font slots require their own evidence.
"""
import argparse
import datetime
import hashlib
import json
import os
from pathlib import Path
import re
import runpy
import shutil
import signal
import subprocess
import time
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[1]
FIXTURES = ROOT / "examples/native-format-stage"
MANIFEST = ROOT / "tests/fixtures/native-format-stage-reference.json"
def sha(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def verify_sources(manifest):
actual = {str(path.relative_to(FIXTURES)): sha(path) for path in FIXTURES.rglob("*.tex")}
if actual != manifest["corpus_sha256"]:
raise RuntimeError("article source differs from the frozen corpus")
def verify_resources(manifest, roots):
for item in manifest["resources"]:
namespace = item["namespace"]
base = FIXTURES if namespace == "PROJECT" else roots.get(namespace)
path = Path(item["path"]) if namespace == "EXTERNAL" else base / item["path"]
if not path.is_file() or path.stat().st_size != item["bytes"] or sha(path) != item["sha256"]:
raise RuntimeError(f"frozen resource changed: {namespace}:{item['path']}")
def verify_reference_artifacts(reference, manifest):
binary = Path(shutil.which("pdftex")).resolve(strict=True)
if sha(binary) != manifest["reference"]["binary_sha256"]:
raise RuntimeError("pdfTeX binary differs from the frozen reference")
audit = json.loads((reference.parent / "reference-audit.json").read_text())
versions = audit["verification_artifacts_sha256"]
paths = [reference / "format/reference.fmt"]
for name in manifest["required_cases"]:
case_dir = reference / name
paths.append(case_dir / "main.pdf")
paths.extend(sorted(case_dir.glob("*.aux")))
actual = {path.relative_to(reference).as_posix(): sha(path) for path in paths}
if actual != versions:
raise RuntimeError("reference format, PDF or aux artifacts changed")
def run_native(binary, options, source, output, directory, label, timeout, env=None):
aux_before = {path.name: sha(path) for path in sorted(directory.glob("*.aux"))}
started_utc = datetime.datetime.now(datetime.timezone.utc).isoformat()
memory = directory / f"{label}-peak-rss-kib.txt"
command = ["time", "-f", "%M", "-o", memory, binary, "native", "--etex", *options,
"--resource-manifest", directory / f"{label}-resources.json",
source, output]
start = time.monotonic()
with subprocess.Popen(command, cwd=directory, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
start_new_session=True, env=env) as process:
try:
stdout, stderr = process.communicate(timeout=timeout)
code = process.returncode
except subprocess.TimeoutExpired:
try:
os.killpg(process.pid, signal.SIGKILL)
except ProcessLookupError:
pass
stdout, stderr = process.communicate()
stderr += b"\nnative audit timed out\n"
code = 124
seconds = time.monotonic() - start
(directory / f"{label}-stdout.log").write_bytes(stdout)
(directory / f"{label}-stderr.log").write_bytes(stderr)
sample = memory.read_text().splitlines()[-1:] if memory.is_file() else []
peak_rss = int(sample[0]) if sample and sample[0].isdigit() else None
return {"exit_code": code, "seconds": seconds, "peak_rss_kib": peak_rss,
"started_utc": started_utc, "aux_before_sha256": aux_before}
def required_reads(trace_path, expected):
if not trace_path.is_file():
return {"passed": False, "missing_manifest": str(trace_path)}
trace = json.loads(trace_path.read_text())
reads = {}
for version in trace["reads"]:
reads.setdefault(Path(version["path"]), set()).add(version["sha256"])
mismatches = [
str(path) for path, digest in expected.items()
if reads.get(path.resolve()) != {digest}
]
return {"passed": not mismatches, "missing_or_changed_reads": mismatches}
def fonts(pdf):
report = subprocess.check_output(["pdffonts", pdf], text=True)
pdf.with_suffix(".fonts.txt").write_text(report)
return sorted({re.sub(r"^[A-Z]{6}\+", "", line.split()[0])
for line in report.splitlines()[2:] if line.strip() and line.split()[-5] == "yes"})
def pages(pdf):
report = subprocess.check_output(["pdfinfo", pdf], text=True)
return int(re.search(r"^Pages:\s*(\d+)", report, re.M)[1])
def compare_words(native, reference, tolerance):
try:
actual, expected = native, reference
if not actual or len(actual) != len(expected):
return {"passed": False, "reason": "missing or unequal pages"}
coordinates = []
for left, right in zip(actual, expected):
if [word for word, _ in left] != [word for word, _ in right]:
return {"passed": False, "reason": "word order or extraction differs"}
for (_, a), (_, b) in zip(left, right):
coordinates.extend(abs(a[key] - b[key]) for key in ("xMin", "yMin", "xMax", "yMax"))
if not coordinates:
return {"passed": False, "reason": "no comparable words"}
maximum = max(coordinates)
return {"passed": maximum <= tolerance, "max_word_box_error_bp": maximum}
except (KeyError, ValueError) as error:
return {"passed": False, "reason": str(error)}
def compare_pdfs(native, reference, manifest):
ink = runpy.run_path(str(ROOT / "scripts/check-native-pages.py"))
word_geometry = runpy.run_path(str(ROOT / "scripts/check-native-paragraphs.py"))
native_pages, reference_pages = pages(native), pages(reference)
native_fonts, reference_fonts = fonts(native), fonts(reference)
raster = []
if native_pages == reference_pages:
for page in range(1, native_pages + 1):
left = ink["raster"](native, native.parent / f"native-{page}", page)
right = ink["raster"](reference, native.parent / f"reference-{page}", page)
raster.append(ink["ink_report"](left, right) if left[:2] == right[:2] and left[2] and right[2]
else {"passed": False, "reason": "raster size or ink differs"})
try:
geometry = compare_words(word_geometry["words"](native), word_geometry["words"](reference),
manifest["geometry_gate"]["pdf_word_box_bp"])
except ET.ParseError as error:
geometry = {"passed": False, "reason": f"word extraction XML cannot be compared: {error}"}
return {
"pages": [native_pages, reference_pages],
"embedded_fonts": [native_fonts, reference_fonts],
"fonts_passed": bool(reference_fonts) and native_fonts == reference_fonts,
"word_geometry": geometry,
"raster": raster,
"raster_passed": bool(raster) and all(page["passed"] for page in raster),
}
def compare_raw_layout(layout, dvi, tolerance):
native = json.loads(layout.read_text())
if native["units"] != "tex-sp":
return {"passed": False, "reason": "layout is not measured in TeX sp"}
actual = native["pages"]
expected = runpy.run_path(str(ROOT / "scripts/native-math-dvi-oracle.py"))["read_dvi"](dvi)
if not actual or len(actual) != len(expected):
return {"passed": False, "reason": "native/DVI page counts differ"}
maximum = 0
glyphs = 0
rules = 0
# DVI records positions from TeX's fixed one-inch physical origin.
inch = 4_736_287
for left, right in zip(actual, expected):
if left["magnification"] != 1000:
return {"passed": False, "reason": "corpus requires unit magnification"}
if left.get("paint_order") != right["paint_order"]:
return {"passed": False, "reason": "glyph/rule paint order differs"}
for kind, identity, coordinates in (
("glyphs", ("font", "size", "slot"), ("x", "y")),
("rules", (), ("x", "y", "width", "height")),
):
if len(left[kind]) != len(right[kind]):
return {"passed": False, "reason": f"{kind} count differs"}
for a, b in zip(left[kind], right[kind]):
if any(a[key] != b[key] for key in identity):
return {"passed": False, "reason": "font, size or raw slot differs"}
maximum = max(maximum, *(abs(a[key] - b[key] - (inch if key in ("x", "y") else 0))
for key in coordinates))
if kind == "glyphs":
glyphs += len(left[kind])
else:
rules += len(left[kind])
return {"passed": glyphs > 0 and maximum <= tolerance, "max_error_sp": maximum,
"glyphs": glyphs, "rules": rules}
def reference_dvi(reference, source, directory, timeout):
directory.mkdir()
for aux in reference.glob("*.aux"):
shutil.copyfile(aux, directory / aux.name)
format_file = reference.parent / "format/reference.fmt"
result = subprocess.run(
["pdftex", f"-fmt={format_file}", "-jobname=main", "-interaction=nonstopmode",
"-halt-on-error", rf'\pdfoutput=0 \input "{source}"'],
cwd=directory, capture_output=True, timeout=timeout,
env={**os.environ, "TEXINPUTS": str(source.parent) + os.pathsep},
)
(directory / "stdout.log").write_bytes(result.stdout)
(directory / "stderr.log").write_bytes(result.stderr)
if result.returncode or not (directory / "main.dvi").is_file():
raise RuntimeError(f"reference DVI job failed: {directory}")
return directory / "main.dvi"
def run_articles(binary, format_image, options, directory, reference, manifest, timeout):
results = []
format_version = sha(format_image)
for name in manifest["required_cases"]:
project = FIXTURES / name
environment = {**os.environ, "TEXINPUTS": str(project) + os.pathsep}
case = directory / name
case.mkdir()
result = {"case": name, "passes": []}
results.append(result)
aux = []
pdf = case / "main.pdf"
expected_reads = {format_image: format_version}
expected_reads.update({
FIXTURES / path: digest
for path, digest in manifest["corpus_sha256"].items()
if Path(path).parts[0] == name
})
for number in range(1, 4):
layout = case / f"pass-{number}-layout.json"
status = run_native(binary, options + ["--load-format", format_image, "--layout-manifest", layout],
project / "main.tex", pdf, case, f"pass-{number}", timeout,
env=environment)
result["passes"].append(status)
if status["exit_code"] or not pdf.is_file():
break
status["required_reads"] = required_reads(case / f"pass-{number}-resources.json", expected_reads)
if not status["required_reads"]["passed"]:
break
aux.append({path.name: sha(path) for path in case.glob("*.aux")})
if len(aux) != 3:
continue
reference_case = reference / name
reference_aux = {path.name: sha(path) for path in reference_case.glob("*.aux")}
result["aux_converged"] = bool(aux[-1]) and aux[-2] == aux[-1]
result["aux_matches_reference"] = aux[-1] == reference_aux
log = (case / "main.log").read_text(errors="replace")
result["references_resolved"] = not re.search(r"undefined references|LaTeX Warning: Reference .* undefined", log)
reference_pdf = case / "reference.pdf"
shutil.copyfile(reference_case / "main.pdf", reference_pdf)
result.update(compare_pdfs(pdf, reference_pdf, manifest))
try:
dvi = reference_dvi(reference_case, project / "main.tex", case / "dvi-reference", timeout)
result["raw_layout"] = compare_raw_layout(layout, dvi, manifest["geometry_gate"]["native_list_sp"])
except (RuntimeError, subprocess.SubprocessError, OSError, ValueError) as error:
result["raw_layout"] = {"passed": False, "reason": str(error)}
return results
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", required=True, type=Path)
parser.add_argument("--output-dir", required=True, type=Path)
parser.add_argument("--reference-dir", required=True, type=Path,
help="verification directory produced by the frozen reference collector")
parser.add_argument("--reference-manifest", type=Path,
help="manifest emitted by the reference collector (default: reference-dir/../manifest.json)")
parser.add_argument("--step-limit", type=int, default=600_000_000)
parser.add_argument("--timeout", type=int, default=1800)
args = parser.parse_args()
if args.step_limit <= 0 or args.timeout <= 0:
parser.error("step limit and timeout must be positive")
manifest = json.loads(MANIFEST.read_text())
verify_sources(manifest)
reference = args.reference_dir.resolve(strict=True)
reference_manifest = args.reference_manifest or reference.parent / "manifest.json"
if json.loads(reference_manifest.read_text()) != manifest:
raise RuntimeError("reference artifacts do not match the frozen manifest")
if manifest["raster_gate"] != {
"dpi": 144, "coverage_radius_pixels": 1, "bbox_pixels": 1, "max_xor_ratio": .01,
}:
raise RuntimeError("reference raster settings differ from the existing raster oracle")
verify_reference_artifacts(reference, manifest)
namespaces = sorted({item["namespace"] for item in manifest["resources"] if item["namespace"].startswith("TEXMF")})
roots = {
namespace: Path(subprocess.check_output(
["kpsewhich", f"--var-value={namespace}"], text=True,
).strip()).resolve(strict=True)
for namespace in namespaces
}
verify_resources(manifest, roots)
namespace, relative = manifest["reference"]["entry_namespace"]
entry = roots[namespace] / relative
binary = args.binary.resolve(strict=True)
output = args.output_dir.resolve()
output.mkdir(parents=True)
format_dir = output / "format"
format_dir.mkdir()
image = format_dir / "latex.tfx"
options = ["--step-limit", str(args.step_limit), "--input-policy", "tex"]
for root in roots.values():
options.extend(["--texmf-root", root])
report = {"schema": 1, "binary_sha256": sha(binary), "format_boot_passed": False, "cases": []}
report["format"] = run_native(binary, options + ["--initex", "--dump-format"],
entry, image, format_dir, "dump", args.timeout,
env={**os.environ, "TEXINPUTS": os.pathsep})
entry_version = next(
item["sha256"] for item in manifest["resources"]
if (item["namespace"], item["path"]) == (namespace, relative)
)
report["format"]["required_reads"] = required_reads(format_dir / "dump-resources.json", {entry: entry_version})
report["format_boot_passed"] = (
report["format"]["exit_code"] == 0 and image.is_file()
and report["format"]["required_reads"]["passed"]
)
if report["format_boot_passed"]:
report["format"]["image_sha256"] = sha(image)
report["cases"] = run_articles(binary, image, options, output, reference, manifest, args.timeout)
verify_sources(manifest)
verify_resources(manifest, roots)
verify_reference_artifacts(reference, manifest)
report["pdf_gates_passed"] = len(report["cases"]) == len(manifest["required_cases"]) and all(
case.get("aux_converged") and case["aux_matches_reference"] and case["references_resolved"]
and case["fonts_passed"] and case["word_geometry"]["passed"] and case["raster_passed"]
for case in report["cases"]
)
report["raw_layout_gates_passed"] = len(report["cases"]) == len(manifest["required_cases"]) and all(
case.get("raw_layout", {}).get("passed", False) for case in report["cases"]
)
(output / "native-article-audit.json").write_text(json.dumps(report, indent=2) + "\n")
return 0 if report["pdf_gates_passed"] and report["raw_layout_gates_passed"] else 1
if __name__ == "__main__":
raise SystemExit(main())
+121
View File
@@ -0,0 +1,121 @@
#!/usr/bin/env python3
"""Audit actual native --job shipouts against the same unmodified TeX input.
Every physical PDF page is checked at the existing 0.02bp/144dpi tolerances.
Auxiliary output, fonts and actual resource reads are retained as evidence.
"""
import argparse
import hashlib
import importlib.util
import json
import os
import re
import subprocess
from pathlib import Path
def run(args, cwd, env=None):
r = subprocess.run([str(a) for a in args], cwd=cwd, env=env, capture_output=True, text=True, timeout=90)
if r.returncode:
raise RuntimeError(r.stdout + '\n' + r.stderr)
return r.stdout + r.stderr
def raster(pdf, base, page):
run(['pdftoppm', '-f', page, '-l', page, '-singlefile', '-gray', '-r', '144', pdf, base], pdf.parent)
data = base.with_suffix('.pgm').read_bytes()
m = re.match(rb'P5\s+(\d+)\s+(\d+)\s+255\s', data)
assert m
width, height = map(int, m.groups())
pixels = data[m.end():]
assert len(pixels) == width * height
return width, height, {i for i, value in enumerate(pixels) if value < 200}
def ink_report(a, b):
assert a[:2] == b[:2]
width, height, ni = a
ri = b[2]
assert ni and ri, 'each declared fixture page must contain actual ink'
def unmatched(x, y):
return sum(not any(0 <= i % width + dx < width and 0 <= i // width + dy < height
and i + dy * width + dx in y
for dy in [-1, 0, 1] for dx in [-1, 0, 1]) for i in x)
def bbox(x):
return [min(i % width for i in x), min(i // width for i in x),
max(i % width for i in x), max(i // width for i in x)]
un, ur = unmatched(ni, ri), unmatched(ri, ni)
nb, rb = bbox(ni), bbox(ri)
xor = len(ni ^ ri)
return dict(passed=un == ur == 0 and all(abs(x-y) <= 1 for x, y in zip(nb, rb)) and xor <= len(ri)*.01,
raster_size=[width, height], native_ink=len(ni), reference_ink=len(ri),
different_pixels=xor, unmatched_native=un, unmatched_reference=ur,
native_bbox=nb, reference_bbox=rb)
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--binary', type=Path, required=True)
p.add_argument('--fixture', type=Path, required=True)
p.add_argument('--output-dir', type=Path, required=True)
p.add_argument('--expected-pages', type=int, required=True)
p.add_argument('--json', type=Path, required=True)
args = p.parse_args()
root = Path(__file__).resolve().parents[1]
fixture, binary, out = args.fixture.resolve(), args.binary.resolve(), args.output_dir.resolve()
out.mkdir(parents=True, exist_ok=True)
native, reference = out/'native', out/'reference'
native.mkdir(exist_ok=True)
reference.mkdir(exist_ok=True)
source = fixture.read_bytes()
(native/'cli.log').write_text(run([binary, 'native', '--job', '--initex', '--etex',
'--resource-manifest', native/'resources.json', fixture, native/'job.pdf'], native))
(reference/'reference.tex').write_text('\\pdfoutput=1\n'
+ f'\\input "{fixture.as_posix()}"\n')
(reference/'cli.log').write_text(run(['pdftex', '-ini', '-etex', '-interaction=nonstopmode',
'-halt-on-error', 'reference.tex'], reference,
{**os.environ, 'TEXINPUTS': str(fixture.parent)+os.pathsep+os.environ.get('TEXINPUTS', '')}))
pdfs = [native/'job.pdf', reference/'reference.pdf']
counts = [int(re.search(r'Pages:\s*(\d+)', run(['pdfinfo', pdf], out))[1]) for pdf in pdfs]
spec = importlib.util.spec_from_file_location('paragraph_word_gate', root/'scripts/check-native-paragraphs.py')
gate = importlib.util.module_from_spec(spec)
spec.loader.exec_module(gate)
word_pages = [gate.words(pdf) for pdf in pdfs]
text_equal = [[w[0] for w in page] for page in word_pages[0]] == [[w[0] for w in page] for page in word_pages[1]]
words = [[w for page in pages for w in page] for pages in word_pages]
errors = ({key: max(abs(a[1][key]-b[1][key]) for a, b in zip(*words))
for key in ['xMin', 'xMax', 'yMin', 'yMax']} if text_equal and all(words) else None)
ink = []
if counts == [args.expected_pages]*2:
for page in range(1, args.expected_pages+1):
row = ink_report(raster(pdfs[0], native/f'page-{page}', page),
raster(pdfs[1], reference/f'page-{page}', page))
row['page'] = page
ink.append(row)
fonts = [run(['pdffonts', pdf], out) for pdf in pdfs]
expected_fonts = ['CMR10', 'CMMI10', 'CMMI7']
aux = [(directory/'pages.aux').read_bytes() for directory in [native, reference]]
trace = json.loads((native/'resources.json').read_text())
actual_reads = trace['reads']
required = [fixture.name, 'math-fonts.tex', 'cmr10.tfm', 'cmmi7.tfm', 'cmr10.pfb', 'cmmi7.pfb']
resources = all(any(r['path'].endswith(name) for r in actual_reads) for name in required)
passed = (counts == [args.expected_pages]*2 and text_equal and errors is not None
and max(errors.values()) <= .02 and len(ink) == args.expected_pages
and all(row['passed'] for row in ink) and all(all(name in f for name in expected_fonts) for f in fonts)
and bool(aux[0]) and aux[0] == aux[1] and resources and fixture.read_bytes() == source)
report = dict(passed=passed, source_sha256=hashlib.sha256(source).hexdigest(), source_unchanged=fixture.read_bytes() == source,
pages=counts, word_counts=list(map(len, words)), page_word_counts=[[len(page) for page in pages] for pages in word_pages],
text_equal=text_equal, max_word_box_errors_bp=errors, ink=ink, expected_fonts=expected_fonts,
native_fonts=fonts[0], reference_fonts=fonts[1], aux_equal=aux[0] == aux[1], aux_hex=aux[0].hex(),
actual_resources_verified=resources, native_reads=len(actual_reads),
tolerances=dict(word_box_bp=.02, dpi=144, ink_threshold=200, coverage_radius_pixels=1, bbox_pixels=1, max_xor_ratio=.01),
scope='Actual online native --job pages/output/shipout, captured paper/origin/magnification and real deferred auxiliary I/O; not complete pdfTeX configuration or format conformance')
args.json.parent.mkdir(parents=True, exist_ok=True)
args.json.write_text(json.dumps(report, indent=2)+'\n')
print(json.dumps({k:v for k,v in report.items() if k not in ['native_fonts', 'reference_fonts']}, indent=2))
if not passed:
raise SystemExit(1)
if __name__ == '__main__':
main()
+97
View File
@@ -0,0 +1,97 @@
#!/usr/bin/env python3
"""Actual paragraph diagnostics/channels and unchanged multi-page native PDF."""
import argparse
import json
import os
from pathlib import Path
import re
import subprocess
import importlib.util
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location("paragraph_trace_oracle", ROOT / "scripts/check-native-statistics.py")
ORACLE = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ORACLE)
def blocks(text):
return [text[m.start():].split("\n\n", 1)[0] for m in re.finditer(r"(?m)^@firstpass\n", text)]
def case(binary, out, level, online):
name = f"paragraphs{level}-online{online}"
d = out / name
native, reference = d / "native", d / "reference"
native.mkdir(parents=True, exist_ok=True)
reference.mkdir(parents=True, exist_ok=True)
original = ROOT / "examples/native-bootstrap/native-job.tex"
original_sha = ORACLE.sha(original.read_bytes())
source = d / "source.tex"
source.write_text(r"\catcode123=1\catcode125=2\pdfoutput=1\pdfpkresolution=600"
+ f"\\tracingparagraphs={level}\\tracingonline={online}\\input {original}\n")
source_sha = ORACLE.sha(source.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 = ORACLE.run([binary, "native", "--job", "--initex", "--etex", "--resource-manifest",
native / "resources.json", source, native / "job.pdf"], native, env)
rt, re_ = ORACLE.run(["pdftex", "-ini", "-etex", "-interaction=nonstopmode", "-halt-on-error", source], reference, env)
(native / "stdout.log").write_bytes(ns)
(native / "terminal.log").write_bytes(nt)
(reference / "terminal.log").write_bytes(rt + re_)
nl, rl = (native / "job.log").read_text(), (reference / "source.log").read_text()
traces = [blocks(s) for s in [nl, rl, nt.decode(), rt.decode()]]
assert traces[0] == traces[1], f"{name}: actual log paragraph decisions/short lists differ"
assert traces[2] == traces[3], f"{name}: actual terminal paragraph diagnostics differ"
if level > 0:
assert traces[0]
assert (traces[2] == traces[0]) if online else not traces[2]
else:
assert not any(traces)
pdf, ref_pdf = native / "job.pdf", reference / "source.pdf"
words = [ORACLE.WORDS.words(p) for p in [pdf, ref_pdf]]
assert len(words[0]) == len(words[1]) == 4
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 = {k: max(abs(a[1][k] - b[1][k]) for a, b in zip(*flat)) for k in ["xMin", "xMax", "yMin", "yMax"]}
ink = [ORACLE.INK.ink_report(ORACLE.INK.raster(pdf, native / f"page-{i}", i),
ORACLE.INK.raster(ref_pdf, reference / f"page-{i}", i)) for i in range(1, 5)]
aux_equal = (native / "pages.aux").read_bytes() == (reference / "pages.aux").read_bytes()
unchanged = ORACLE.sha(source.read_bytes()) == source_sha and ORACLE.sha(original.read_bytes()) == original_sha
passed = max(errors.values()) <= .02 and all(i["passed"] for i in ink) and aux_equal and unchanged
result = dict(id=name, passed=passed, pages=4, level=level, tracingonline=online,
paragraph_reports=len(traces[0]), decision_lines=sum(len(re.findall(r"(?m)^@", s)) for s in traces[0]),
exact_paragraph_diagnostics=True, max_word_box_errors_bp=errors, ink=ink,
aux_equal=aux_equal, source_unchanged=unchanged, source_sha256=source_sha,
native_pdf_sha256=ORACLE.sha(pdf.read_bytes()))
(d / "audit.json").write_text(json.dumps(result, indent=2) + "\n")
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
args = parser.parse_args()
out = args.output_dir.resolve()
out.mkdir(parents=True, exist_ok=True)
results = []
for level in [-1, 0, 1, 2]:
for online in [0, 1]:
r = case(args.binary.resolve(), out, level, online)
results.append(r)
print(r["id"], "passed" if r["passed"] else "FAILED", flush=True)
assert len({r["native_pdf_sha256"] for r in results}) == 1, "paragraph tracing changed 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=ORACLE.sha(args.binary.resolve().read_bytes()),
reference_version=subprocess.check_output(["pdftex", "--version"], text=True).splitlines()[0], results=results)
(out / "audit.json").write_text(json.dumps(report, indent=2) + "\n")
if not report["passed"]:
raise SystemExit(1)
if __name__ == "__main__":
main()
+151
View File
@@ -0,0 +1,151 @@
#!/usr/bin/env python3
"""Compare an owned-token paragraph PDF with real pdfTeX INITEX output.
Requires pdftex, pdftotext, pdfinfo and pdffonts. This is an external oracle,
never a runtime engine fallback. The fixture uses only implemented primitives.
"""
import argparse
import hashlib
import os
import json
import re
import subprocess
import xml.etree.ElementTree as ET
from pathlib import Path
def run(command, directory, env=None):
result = subprocess.run([str(x) for x in command], cwd=directory,
capture_output=True, text=True, env=env)
if result.returncode:
raise RuntimeError(f"{command[0]} exited {result.returncode}:\n"
f"{result.stdout}\n{result.stderr}")
return result.stdout + result.stderr
def parse_bbox(data):
"""Decode Poppler's bbox protocol, retaining every extracted code point.
Poppler writes PDF control characters literally inside word text, even
though they are forbidden by XML 1.0. Parse the unchanged word strings
separately, and validate the surrounding structure with the XML parser.
No character filtering, recovery, normalization, or placeholder alphabet
is used. XML entities are decoded exactly once; word order is unchanged.
"""
values = []
def word_text(match):
text = match[2]
parts = []
position = 0
named = {"amp": "&", "lt": "<", "gt": ">", "quot": '"', "apos": "'"}
for entity in re.finditer(r"&([^;]*);", text):
prefix = text[position:entity.start()]
if "&" in prefix:
raise ET.ParseError("unescaped ampersand in bbox word")
parts.append(prefix)
name = entity[1]
if name in named:
value = named[name]
elif re.fullmatch(r"#(?:[0-9]+|x[0-9A-Fa-f]+)", name):
number = int(name[2:], 16) if name.startswith("#x") else int(name[1:])
if number > 0x10FFFF or 0xD800 <= number <= 0xDFFF:
raise ET.ParseError("non-scalar character reference in bbox word")
value = chr(number)
else:
raise ET.ParseError("unknown entity in bbox word")
parts.append(value)
position = entity.end()
tail = text[position:]
if "&" in tail:
raise ET.ParseError("unescaped ampersand in bbox word")
parts.append(tail)
values.append("".join(parts))
return match[1] + match[3]
skeleton = re.sub(r"(<word(?:\s[^<>]*)?>)([^<]*)(</word>)", word_text,
data.decode("utf-8"), flags=re.DOTALL)
root = ET.fromstring(skeleton)
nodes = [node for node in root.iter() if node.tag.endswith("}word")]
if len(nodes) != len(values) or any(len(node) or node.text for node in nodes):
raise ET.ParseError("unexpected bbox word structure")
for node, text in zip(nodes, values):
node.text = text
return [[(node.text, {key: float(value) for key, value in node.attrib.items()})
for node in page.iter() if node.tag.endswith("}word")]
for page in root.iter() if page.tag.endswith("}page")]
def words(pdf):
data = subprocess.check_output(["pdftotext", "-bbox", str(pdf), "-"])
pdf.with_suffix(".bbox.html").write_bytes(data)
return parse_bbox(data)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", type=Path, required=True)
parser.add_argument("--fixture", type=Path, help="native paragraph/box source; default paragraphs.tex")
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--json", type=Path, required=True)
parser.add_argument("--expected-pages", type=int, default=1,
help="required page count for both native and reference outputs")
parser.add_argument("--expected-font", action="append", dest="expected_fonts",
help="required embedded font name; repeat for a different font fixture")
args = parser.parse_args()
binary = args.binary.resolve()
directory = args.output_dir.resolve()
directory.mkdir(parents=True, exist_ok=True)
repo = Path(__file__).resolve().parent.parent
fixture = args.fixture.resolve() if args.fixture else repo / "examples/native-bootstrap/paragraphs.tex"
stem = fixture.stem
source = fixture.read_text()
(directory / f"{stem}.tex").write_text(source)
(directory / "reference.tex").write_text(
# Declare the same host canvas explicitly in the reference. The native
# kernel does not claim page-parameter/output-routine execution yet.
"\\pdfoutput=1 \\pdfpagewidth=612bp \\pdfpageheight=792bp "
"\\vsize=648bp \\topskip=10bp\n" + source)
(directory / "native-cli.txt").write_text(run(
[binary, "native", "--initex", "--etex", fixture, f"{stem}.pdf"],
directory))
(directory / "reference-cli.txt").write_text(run(
["pdftex", "-ini", "-etex", "-interaction=nonstopmode", "-halt-on-error",
"reference.tex"], directory, env={**os.environ,"TEXINPUTS":str(fixture.parent)+os.pathsep+os.environ.get("TEXINPUTS","")}))
pdfs = [directory / f"{stem}.pdf", directory / "reference.pdf"]
native_pages, reference_pages = map(words, pdfs)
text_equal = ([[w[0] for w in page] for page in native_pages]
== [[w[0] for w in page] for page in reference_pages])
native = [word for page in native_pages for word in page]
reference = [word for page in reference_pages for word in page]
errors = ({key: max(abs(a[1][key] - b[1][key])
for a, b in zip(native, reference))
for key in ("xMin", "xMax", "yMin", "yMax")}
if text_equal and native else None)
pages = []
fonts = []
for pdf in pdfs:
info = subprocess.check_output(["pdfinfo", str(pdf)], text=True)
pages.append(int(next(line.split(":")[1] for line in info.splitlines()
if line.startswith("Pages:"))))
fonts.append(subprocess.check_output(["pdffonts", str(pdf)], text=True))
passed = (text_equal and bool(native) and pages == [args.expected_pages, args.expected_pages]
and max(errors.values()) <= 0.02
and all(all(name in f for name in (args.expected_fonts or ["CMR10"])) for f in fonts))
result = dict(passed=passed, source_sha256=hashlib.sha256(source.encode()).hexdigest(),
pages=pages, word_counts=[len(native), len(reference)],
page_word_counts=[[len(page) for page in pages_]
for pages_ in (native_pages, reference_pages)],
text_equal=text_equal, max_word_box_errors_bp=errors,
native_fonts=fonts[0], reference_fonts=fonts[1],
expected_fonts=args.expected_fonts or ["CMR10"],
scope=f"Native {stem} fixture at its actual fonts/sizes; host canvas, not full native page execution")
args.json.resolve().write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps({key: result[key] for key in
("passed", "pages", "word_counts", "max_word_box_errors_bp")}, indent=2))
return 0 if passed else 1
if __name__ == "__main__":
raise SystemExit(main())
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env python3
"""Actual version/precision/compression/ObjStm/xref and unchanged PDF ink oracle.
Requires the independent test reader pypdf (recorded in the audit). It is not a
product dependency. Poppler also parses/rasterizes every physical page.
"""
import argparse
import hashlib
import importlib.util
import json
import os
import re
from pathlib import Path
from pypdf import PdfReader
import pypdf
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('pdf_ink','check-native-pages.py')
WORDS=module('pdf_words','check-native-paragraphs.py')
def configurations():
for digits in range(5):
for minor,obj in [(4,0),(4,3),(5,1),(7,2),(7,3)]:
yield 1,minor,obj,digits,0 if digits%2==0 else 9
for level in [1,9]:yield 1,7,3,3,level
yield 2,0,3,4,9
def objects(reader):
from pypdf.generic import IndirectObject
ids={(obj,gen)for gen,items in reader.xref.items()for obj in items if obj!=0}
ids|={(obj,0)for obj in reader.xref_objStm}
return [(obj,IndirectObject(obj,gen,reader).get_object())for obj,gen in sorted(ids)]
def structure(pdf,major,minor,obj,digits,level):
r=PdfReader(pdf,strict=True);all_objects=objects(r);packed=len(r.xref_objStm)
effective=obj if major>1 or minor>=5 else 0
assert r.pdf_header==f'%PDF-{major}.{minor}'
assert bool(packed)==bool(effective),(pdf,packed,effective)
parsed=[]
for oid,value in all_objects:
if hasattr(value,'get_data'):
data=value.get_data();assert isinstance(data,bytes)
parsed.append(dict(id=oid,type=str(value.get('/Type','stream')),flate=str(value.get('/Filter',''))=='/FlateDecode',decoded_sha256=hashlib.sha256(data).hexdigest(),bytes=len(data)))
page_streams=[p['/Contents'].get_object()for p in r.pages]
assert [str(v.get('/Filter',''))=='/FlateDecode'for v in page_streams]==[level>0,level==0]
assert any(v['type']=='/ObjStm'for v in parsed)==bool(effective)
# Resolve every page, font dictionary, program and ToUnicode through xref.
fonts={}
for page in r.pages:
for name,ref in page['/Resources']['/Font'].items():
f=ref.get_object();program=f['/FontDescriptor']['/FontFile'].get_object();program.get_data()
assert (str(program.get('/Filter',''))=='/FlateDecode')==(level==0)
fonts[str(name)]=str(f['/BaseFont'])
info=r.trailer.raw_get('/Info')
assert (info.idnum in r.xref_objStm)==(effective>=3)
return dict(header=r.pdf_header,packed_objects=packed,streams=parsed,font_names=fonts,
pages=len(r.pages),media=[[float(x)for x in p.mediabox]for p in r.pages],
contents=[v.get_data().decode('ascii')for v in page_streams])
def audit(binary,out,config):
major,minor,obj,digits,level=config;name=f'{major}-{minor}-obj{obj}-digits{digits}-zip{level}';d=out/name;n=d/'native';r=d/'reference'
n.mkdir(parents=True,exist_ok=True);r.mkdir(parents=True,exist_ok=True)
fonts=(ROOT/'examples/native-bootstrap/math-fonts.tex').read_text()
source=(fonts+f'\\pdfoutput=1\\pdfmajorversion={major}\\pdfminorversion={minor}\\pdfobjcompresslevel={obj}\\pdfdecimaldigits={digits}\\pdfcompresslevel={level}'
+r'\mag=1200\pdfpagewidth=260truebp\pdfpageheight=180truebp\pdfhorigin=13.12345pt\pdfvorigin=16.34567pt'
+r'\immediate\openout1=config.aux\count0=1\setbox0=\vbox{\hbox{Native AV office $x_i^j+y$}'
+r'\kern.37pt\hrule width103.21pt height.4pt\hbox{AB\kern.17pt C\raise.3pt\hbox{D}\vrule width.35pt height2.5pt}'
+r'\write1{PAGE=\number\count0;ZIP=\number\pdfcompresslevel}}\shipout\copy0'
+f'\\pdfcompresslevel={9 if level==0 else 0}\\pdfobjcompresslevel={0 if obj else 3}\\pdfdecimaldigits={4 if digits==0 else 0}'
+r'\count0=2\shipout\box0\immediate\closeout1\end'+'\n')
file=d/'source.tex';file.write_text(source);sha=hashlib.sha256(file.read_bytes()).hexdigest()
(n/'cli.log').write_text(INK.run([binary,'native','--job','--initex','--etex','--resource-manifest',n/'resources.json',file,n/'job.pdf'],n))
(r/'cli.log').write_text(INK.run(['pdftex','-ini','-etex','-interaction=nonstopmode','-halt-on-error',file],r))
pdfs=[n/'job.pdf',r/'source.pdf'];parsed=structure(pdfs[0],major,minor,obj,digits,level);ref=PdfReader(pdfs[1],strict=True)
media=[[float(x)for x in p.mediabox]for p in ref.pages];assert parsed['media']==media
word_pages=[WORDS.words(p)for p in pdfs];text_equal=[[w[0]for w in p]for p in word_pages[0]]==[[w[0]for w in p]for p in word_pages[1]]
flat=[[w for p in pages for w in p]for pages in word_pages]
errors={k:max(abs(a[1][k]-b[1][k])for a,b in zip(*flat))for k in ['xMin','xMax','yMin','yMax']}if text_equal and all(flat)else None
ink=[INK.ink_report(INK.raster(pdfs[0],n/f'page-{i}',i),INK.raster(pdfs[1],r/f'page-{i}',i))for i in [1,2]]
aux=[p.read_bytes()for p in [n/'config.aux',r/'config.aux']]
source_unchanged=hashlib.sha256(file.read_bytes()).hexdigest()==sha
passed=text_equal and errors is not None and max(errors.values())<=.02 and all(p['passed']for p in ink)and aux[0]==aux[1]and source_unchanged
result=dict(id=name,passed=passed,max_word_box_errors_bp=errors,ink=ink,aux_equal=aux[0]==aux[1],source_sha256=sha,source_unchanged=source_unchanged,structure=parsed)
(d/'audit.json').write_text(json.dumps(result,indent=2)+'\n');return result
def object_stream_stress(binary,out):
d=out/'object-stream-boundary';n=d/'native';r=d/'reference';n.mkdir(parents=True,exist_ok=True);r.mkdir(parents=True,exist_ok=True)
source=(r'\catcode123=1\catcode125=2\font\R=cmr10\R\pdfoutput=1\pdfminorversion=7\pdfobjcompresslevel=3\pdfcompresslevel=9'
+r'\pdfpagewidth=20pt\pdfpageheight=20pt\pdfhorigin=1pt\pdfvorigin=1pt\immediate\openout1=stress.aux\count0=0'
+r'\setbox0=\hbox{A\write1{N=\number\count0}}'
+r'\shipout\copy0\advance\count0 by1 '*105
+r'\immediate\closeout1\end')
file=d/'source.tex';file.write_text(source);sha=hashlib.sha256(file.read_bytes()).hexdigest()
(n/'cli.log').write_text(INK.run([binary,'native','--job','--initex','--etex',file,n/'job.pdf'],n))
(r/'cli.log').write_text(INK.run(['pdftex','-ini','-etex','-interaction=nonstopmode','-halt-on-error',file],r))
reader=PdfReader(n/'job.pdf',strict=True);all_objects=objects(reader)
streams=[o for _,o in all_objects if hasattr(o,'get')and o.get('/Type')=='/ObjStm']
assert len(reader.pages)==105 and len(streams)>=2
assert max(int(v['/N'])for v in streams)==100
for page in reader.pages:assert page.extract_text().strip()=='A';page.get_contents().get_data()
assert [p.extract_text().strip()for p in PdfReader(r/'source.pdf',strict=True).pages]==['A']*105
aux=(n/'stress.aux').read_bytes();assert aux==(r/'stress.aux').read_bytes()==''.join(f'N={i}\n'for i in range(105)).encode()
assert hashlib.sha256(file.read_bytes()).hexdigest()==sha
result=dict(passed=True,pages=105,object_streams=len(streams),packed_objects=len(reader.xref_objStm),aux_equal=True,source_sha256=sha,scope='Independent full xref/ObjStm rollover/font/page/text/late-write resolution; raster gates are the separate 56 configuration pages.')
(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 c in configurations():
r=audit(a.binary.resolve(),out,c);results.append(r);print(r['id'],'passed'if r['passed']else'FAILED',r['max_word_box_errors_bp'],flush=True)
stress=object_stream_stress(a.binary.resolve(),out)
report=dict(passed=all(r['passed']for r in results)and stress['passed'],cases=len(results),pages=2*len(results),object_stream_stress=stress,pypdf_version=pypdf.__version__,binary_sha256=hashlib.sha256(a.binary.resolve().read_bytes()).hexdigest(),results=results)
(out/'audit.json').write_text(json.dumps(report,indent=2)+'\n')
if not report['passed']:raise SystemExit(1)
if __name__=='__main__':main()
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""Independent real PK Type3 device, bitmap, text and raster oracle.
Both engines read the same source, TFM, map and PK bytes. No mktexpk or font
substitution is used by the native product. Requires test-only pypdf/Poppler.
"""
import argparse,hashlib,importlib.util,json,os,re,subprocess
from pathlib import Path
from pypdf import PdfReader
import pypdf
ROOT=Path(__file__).resolve().parents[1]
def module(name,file):
spec=importlib.util.spec_from_file_location(name,ROOT/'scripts'/file);m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m
INK=module('pk_ink','check-native-pages.py')
def sha(data):return hashlib.sha256(data).hexdigest()
def run(args,cwd,env):
r=subprocess.run([str(a)for a in args],cwd=cwd,env=env,capture_output=True,timeout=40)
if r.returncode:raise RuntimeError(f'{args[0]} failed: '+(r.stdout+r.stderr).decode(errors='replace'))
return (r.stdout+r.stderr).decode(errors='replace')
def raw_words(pdf):
# PK slot labels can contain control bytes in Poppler's otherwise XML-like
# output. Preserve those exact UTF-8 labels; do not sanitize or remap them.
data=subprocess.check_output(['pdftotext','-bbox',str(pdf),'-'])
pdf.with_suffix('.bbox.xml').write_bytes(data)
pages=[]
for page in re.findall(rb'<page\s[^>]*>(.*?)</page>',data,re.S):
words=[]
for attrs,label in re.findall(rb'<word\s([^>]*)>(.*?)</word>',page,re.S):
coords={k.decode():float(v)for k,v in re.findall(rb'(xMin|xMax|yMin|yMax)="([^"]+)"',attrs)};assert len(coords)==4
words.append((label.decode('utf-8'),coords))
assert len(words)==page.count(b'<word ')
pages.append(words)
assert pages
return pages
def type3_fonts(file):
reader=PdfReader(file,strict=True);result=[];seen=set()
for page in reader.pages:
for ref in page['/Resources']['/Font'].values():
if ref.idnum in seen:continue
seen.add(ref.idnum);font=ref.get_object()
if font['/Subtype']!='/Type3':continue
glyphs={}
for key,value in font['/CharProcs'].items():
data=value.get_data();header=re.match(rb'(-?[\d.]+) 0 (-?\d+) (-?\d+) (-?\d+) (-?\d+) d1\n',data);assert header
image=re.search(rb'/W (\d+)\s*/H (\d+)\s*/IM true\s*/BPC 1\s*/D \[1 0\]\s*ID ',data);bitmap=b'';w=h=0
if image:
w,h=map(int,image.groups());length=((w+7)//8)*h;bitmap=data[image.end():image.end()+length];assert data[image.end()+length:].startswith(b'\nEI\nQ\n')
glyphs[str(key)]=dict(width=float(header[1]),bbox=[int(v)for v in header.groups()[1:]],w=w,h=h,bitmap_sha256=sha(bitmap))
result.append(dict(matrix=[float(v)for v in font['/FontMatrix']],bbox=[int(v)for v in font['/FontBBox']],glyphs=glyphs,widths=[float(v)for v in font['/Widths']]))
return sorted(result,key=lambda f:json.dumps(f,sort_keys=True))
def case(binary,out,name,resolution,size,digits,font='cmr10',mixed=False):
d=out/name;n=d/'native';r=d/'reference';n.mkdir(parents=True,exist_ok=True);r.mkdir(parents=True,exist_ok=True)
maps=d/'maps';maps.mkdir(exist_ok=True);map_data='% Actual bitmap fonts: no outline entry in this configured map.\n'
if mixed:
installed=Path(subprocess.check_output(['kpsewhich','pdftex.map'],text=True).strip())
map_data+='\n'.join(l for l in installed.read_text().splitlines()if l.split()and l.split()[0]=='cmmi10')+'\n'
(maps/'pdftex.map').write_text(map_data)
env=os.environ.copy();env['TEXFONTMAPS']=str(maps);env['PKFONTS']=str(ROOT/'crates/texrra-tex-core/tests/fixtures/pk');env['TFMFONTS']=str(ROOT/'crates/texrra-tex-core/assets');env['T1FONTS']=str(ROOT/'assets/fonts')
extra_font=r'\font\G=cmmi10 at20pt'if mixed else ''
body=r'AV office -- ffi'+(r'{\G XYZ} AV'if mixed else '')
source=(r'\catcode123=1\catcode125=2\pdfoutput=1\pdfminorversion=7\pdfobjcompresslevel=3\pdfcompresslevel=0'
+f'\\pdfdecimaldigits={digits}\\pdfpkresolution={resolution}\\font\\F={font} at{size}pt\\F'
+extra_font
+r'\mag=1200\pdfpagewidth=900truebp\pdfpageheight=260truebp\pdfhorigin=13.12345pt\pdfvorigin=16.34567pt'
+r'\immediate\openout1=bitmap.aux\count0=1\setbox0=\hbox{'+body+r'\kern.17pt A\raise.3pt\hbox{B}\write1{PAGE=\number\count0;DPI=\number\pdfpkresolution}}'
+r'\shipout\copy0\pdfpkresolution=1200\pdfcompresslevel=9\count0=2\shipout\box0\immediate\closeout1\end'+'\n')
file=d/'source.tex';file.write_text(source);before=sha(file.read_bytes())
(n/'cli.log').write_text(run([binary,'native','--job','--initex','--etex','--resource-manifest',n/'resources.json',file,n/'job.pdf'],n,env))
(r/'cli.log').write_text(run(['pdftex','-ini','-etex','-no-mktex=pk','-interaction=nonstopmode','-halt-on-error',file],r,env))
native,reference=n/'job.pdf',r/'source.pdf';nf=type3_fonts(native);rf=type3_fonts(reference);assert nf==rf and nf
pages=[raw_words(p)for p in [native,reference]];text_equal=[[w[0]for w in p]for p in pages[0]]==[[w[0]for w in p]for p in pages[1]]
flat=[[w for p in v for w in p]for v in pages];errors={k:max(abs(a[1][k]-b[1][k])for a,b in zip(*flat))for k in ['xMin','xMax','yMin','yMax']}if text_equal and all(flat)else None
ink=[INK.ink_report(INK.raster(native,n/f'page-{i}',i),INK.raster(reference,r/f'page-{i}',i))for i in [1,2]]
media=[[list(map(float,p.mediabox))for p in PdfReader(f,strict=True).pages]for f in [native,reference]]
aux=(n/'bitmap.aux').read_bytes();aux_equal=aux==(r/'bitmap.aux').read_bytes()
resources=json.loads((n/'resources.json').read_text());pk=[v for v in resources['reads']if v['path'].endswith('.600pk')];assert pk
for v in pk:assert sha(Path(v['path']).read_bytes())==v['sha256']
assert any(v['path'].endswith('.pfb')for v in resources['reads'])==mixed
unchanged=sha(file.read_bytes())==before
passed=nf==rf and text_equal and errors is not None and max(errors.values())<=.02 and all(i['passed']for i in ink)and media[0]==media[1]and aux_equal and unchanged
controls=sum(any(ord(c)<32 and c not in '\t\n\r'for c in label)for page in pages[0]for label,_ in page)
result=dict(id=name,passed=passed,font=font,resolution=resolution,size_pt=size,decimaldigits=digits,type3_equal=nf==rf,type3=nf,mixed_type1=mixed,max_word_box_errors_bp=errors,raw_word_labels_preserved=True,xml10_control_labels=controls,ink=ink,media_equal=media[0]==media[1],aux_equal=aux_equal,source_sha256=before,source_unchanged=unchanged,pk_resources=pk)
(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 digits in range(5):
for res,size in [(0,'83.333333'),(72,'83.333333'),(300,'20'),(600,'10'),(1200,'5'),(8000,'.75'),(-1,'83.333333'),(9000,'.75')]:
c=case(a.binary.resolve(),out,f'digits{digits}-dpi{res}',res,size,digits);results.append(c);print(c['id'],'passed'if c['passed']else'FAILED',c['max_word_box_errors_bp'],flush=True)
for font in ['cmmi10','cmex10']:
c=case(a.binary.resolve(),out,font,600,'10',3,font);results.append(c);print(font,'passed'if c['passed']else'FAILED',flush=True)
c=case(a.binary.resolve(),out,'pk-type1-cursor-switch',300,'20',3,mixed=True);results.append(c);print(c['id'],'passed'if c['passed']else'FAILED',flush=True)
report=dict(passed=all(r['passed']for r in results),cases=len(results),pages=2*len(results),binary_sha256=sha(a.binary.resolve().read_bytes()),reference_version=subprocess.check_output(['pdftex','--version'],text=True).splitlines()[0],pypdf_version=pypdf.__version__,results=results)
(out/'audit.json').write_text(json.dumps(report,indent=2)+'\n')
if not report['passed']:raise SystemExit(1)
if __name__=='__main__':main()
+74
View File
@@ -0,0 +1,74 @@
#!/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()
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env python3
"""Freeze actual pdfLaTeX format/article inputs from recorder output.
This is reference infrastructure, never a runtime compiler fallback. Two full
reference runs verify that the discovered source/resource closure stayed fixed.
Generated fmt/aux/PDF files are artifacts, not native-format implementations.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import stat
import subprocess
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[1]
FIXTURES = ROOT / "examples/native-format-stage"
CASES = ["a0-minimal", "a1-fonts-10", "a1-fonts-11", "a1-fonts-12", "a2-math", "a3-pages", "a4-project"]
ROOT_VARIABLES = ["TEXMFDIST", "TEXMFLOCAL", "TEXMFSYSCONFIG", "TEXMFSYSVAR", "TEXMFCONFIG", "TEXMFVAR", "TEXMFHOME"]
def sha(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def command(args, cwd, env=None):
result = subprocess.run([str(x) for x in args], cwd=cwd, env=env,
capture_output=True, text=True, timeout=120)
return result
def roots():
result = {}
for variable in ROOT_VARIABLES:
value = subprocess.check_output(["kpsewhich", f"--var-value={variable}"], text=True).strip()
if value and Path(value).is_dir():
result[variable] = Path(value).resolve()
return result
def classify(path, job, root_paths):
if path.is_relative_to(FIXTURES):
return "PROJECT", path.relative_to(FIXTURES).as_posix()
if path.is_relative_to(job):
return "GENERATED", path.relative_to(job).as_posix()
for name, root in sorted(root_paths.items(), key=lambda x: len(str(x[1])), reverse=True):
if path.is_relative_to(root):
return name, path.relative_to(root).as_posix()
return "EXTERNAL", path.as_posix()
def recorder(path, job, root_paths):
resources = {}
reads = []
specials = []
for line in path.read_text().splitlines():
if not line.startswith("INPUT "):
continue
name = line[6:]
actual = (job / name).resolve()
mode = actual.stat().st_mode
namespace, relative = classify(actual, job.parent, root_paths)
if namespace == "GENERATED":
reads.append({"namespace": namespace, "path": relative})
elif stat.S_ISREG(mode):
key = namespace + ":" + relative
item = dict(namespace=namespace, path=relative, bytes=actual.stat().st_size, sha256=sha(actual))
resources[key] = (actual, item)
reads.append({"namespace": namespace, "path": relative})
else:
# A real device input (such as /dev/null) is recorded as a device,
# never fabricated as an empty regular source or omitted silently.
specials.append(dict(path=str(actual), mode=stat.S_IFMT(mode)))
return resources, reads, specials
def run_reference(output, entry, root_paths):
output.mkdir(parents=True, exist_ok=True)
format_dir = output / "format"
format_dir.mkdir(exist_ok=True)
env = {**os.environ, "TEXINPUTS": ":"}
result = command(["pdftex", "-ini", "-etex", "-interaction=nonstopmode", "-halt-on-error",
"-recorder", "-jobname=reference", entry], format_dir, env)
(format_dir / "stdout.txt").write_text(result.stdout)
(format_dir / "stderr.txt").write_text(result.stderr)
if result.returncode or not (format_dir / "reference.fmt").is_file():
raise RuntimeError(f"real format creation failed; see {format_dir}")
resources, format_reads, specials = recorder(format_dir / "reference.fls", format_dir, root_paths)
def compile_case(name):
project = FIXTURES / name
source = project / "main.tex"
directory = output / name
directory.mkdir(exist_ok=True)
env = {**os.environ, "TEXINPUTS": str(project) + os.pathsep}
auxiliary = []
for number in range(1, 4):
result = command(["pdftex", "-fmt=" + str(format_dir / "reference.fmt"),
"-interaction=nonstopmode", "-halt-on-error", "-recorder", source], directory, env)
(directory / f"pass-{number}-stdout.txt").write_text(result.stdout)
(directory / f"pass-{number}-stderr.txt").write_text(result.stderr)
if result.returncode:
raise RuntimeError(f"real article {name} pass {number} failed; see {directory}")
auxiliary.append({p.name: sha(p) for p in directory.glob("*.aux")})
if auxiliary[1] != auxiliary[2]:
raise RuntimeError(f"aux files did not converge for {name}")
if "undefined references" in result.stdout or re.search(r"LaTeX Warning: Reference .* undefined", result.stdout):
raise RuntimeError(f"unresolved reference in {name}")
pdf = directory / "main.pdf"
info = subprocess.check_output(["pdfinfo", str(pdf)], text=True)
pages = int(re.search(r"^Pages:\s*(\d+)", info, re.M)[1])
if (name == "a0-minimal" and pages != 1) or (name == "a3-pages" and pages < 2):
raise RuntimeError(f"unexpected page count in {name}: {pages}")
bbox = subprocess.check_output(["pdftotext", "-bbox", str(pdf), "-"])
(directory / "main.bbox.html").write_bytes(bbox)
bbox_error = None
try:
words = sum(1 for node in ET.fromstring(bbox).iter() if node.tag.endswith("}word"))
except ET.ParseError as error:
# Legacy reference math-font extraction can contain XML 1.0
# control codes. Keep those exact bytes and flag the issue. This
# counts reference word tags only; it certifies no Unicode match.
bbox_error = str(error)
words = len(re.findall(rb"<word\s", bbox))
fonts = subprocess.check_output(["pdffonts", str(pdf)], text=True)
(directory / "fonts.txt").write_text(fonts)
if words == 0 or "CMR" not in fonts:
raise RuntimeError(f"missing real text/font output for {name}")
case_resources, reads, devices = recorder(directory / "main.fls", directory, root_paths)
summary = dict(case=name, pages=pages, words=words, aux_converged=True,
aux_sha256=auxiliary[-1], source_sha256=sha(source), input_trace=reads,
special_inputs=devices, font_report=fonts,
bbox_xml_valid=bbox_error is None, bbox_parse_error=bbox_error)
return case_resources, summary
summaries = []
with ThreadPoolExecutor(max_workers=4) as pool:
for case_resources, summary in pool.map(compile_case, CASES):
for key, value in case_resources.items():
if key in resources and resources[key][1] != value[1]:
raise RuntimeError(f"resource changed while collecting reference: {key}")
resources[key] = value
summaries.append(summary)
return resources, dict(format_created=True, native_format_boot_passed=False, format_input_trace=format_reads,
format_special_inputs=specials, cases=summaries)
def verify_resources(resources):
for key, (path, version) in resources.items():
if not path.is_file() or sha(path) != version["sha256"]:
raise RuntimeError(f"reference input changed: {key}")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--verify", type=Path, help="require an existing frozen source/resource manifest")
args = parser.parse_args()
output = args.output_dir.resolve()
entry = Path(subprocess.check_output(["kpsewhich", "pdflatex.ini"], text=True).strip()).resolve()
root_paths = roots()
binary = Path(shutil.which("pdftex")).resolve()
reference = dict(version=subprocess.check_output(["pdftex", "--version"], text=True).splitlines()[0],
binary_sha256=sha(binary), entry_namespace=list(classify(entry, output, root_paths)))
project_versions = {p.relative_to(FIXTURES).as_posix(): sha(p) for p in sorted(FIXTURES.rglob("*.tex"))}
resources, discovery = run_reference(output / "discovery", entry, root_paths)
verify_resources(resources)
checked, verification = run_reference(output / "verification", entry, root_paths)
verify_resources(resources)
if {k: v[1] for k, v in resources.items()} != {k: v[1] for k, v in checked.items()}:
raise RuntimeError("resource closure changed between discovery and verification")
if project_versions != {p.relative_to(FIXTURES).as_posix(): sha(p) for p in sorted(FIXTURES.rglob("*.tex"))}:
raise RuntimeError("corpus sources were changed by reference compilation")
manifest = dict(schema=1, profile="pdfTeX/pdfLaTeX", reference=reference,
corpus_sha256=project_versions, resources=[v[1] for _, v in sorted(resources.items())],
required_cases=CASES,
raster_gate=dict(dpi=144, coverage_radius_pixels=1, bbox_pixels=1, max_xor_ratio=.01),
geometry_gate=dict(native_list_sp=1, pdf_word_box_bp=.02),
scope="Reference inputs only; generated fmt/aux/PDF are artifacts, not native implementation evidence.")
if args.verify and json.loads(args.verify.read_text()) != manifest:
raise RuntimeError("frozen reference inputs/profile differ; inspect the versions before updating the manifest")
args.manifest.parent.mkdir(parents=True, exist_ok=True)
args.manifest.write_text(json.dumps(manifest, indent=2) + "\n")
report = dict(reference_audit_completed=True, source_unchanged=True, native_format_boot_passed=False,
frozen_resources=len(resources), discovery=discovery, verification=verification)
artifact_root = output / "verification"
artifacts = [artifact_root / "format/reference.fmt"]
for name in CASES:
case_dir = artifact_root / name
artifacts.append(case_dir / "main.pdf")
artifacts.extend(sorted(case_dir.glob("*.aux")))
report["verification_artifacts_sha256"] = {
path.relative_to(artifact_root).as_posix(): sha(path) for path in artifacts
}
(output / "reference-audit.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps({"reference_audit_completed": True, "frozen_resources": len(resources),
"cases": [{k: case[k] for k in ["case", "pages", "words", "aux_converged"]}
for case in verification["cases"]],
"native_format_boot_passed": False}, indent=2))
if __name__ == "__main__":
main()
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""Regenerate isolated CM math-box probes with pdfTeX (no PDF integration).
Run from any directory. Requires pdftex; Cargo tests consume the checked-in JSON.
TeX dimensions are integer scaled points, not PDF big points (72/72.27).
"""
import json
from pathlib import Path
import subprocess
import tempfile
ROOT = Path(__file__).resolve().parent.parent
STYLES = [
("Display", r"\displaystyle"),
("Text", r"\textstyle"),
("Script", r"\scriptstyle"),
("ScriptScript", r"\scriptscriptstyle"),
]
CASES = [
"x", r"\alpha", r"\Omega", "x+y=z", "-x--y", "(x,y)",
"x/y", "x.y", "x!y?z", "x;y", "x<y>z", "x+(-y)",
r"\epsilon+\varepsilon", r"\phi+\varphi", r"\theta+\vartheta",
r"\pi+\varpi", r"\rho+\varrho", r"\sigma+\varsigma",
r"\Gamma+\Delta+\Theta+\Lambda+\Xi+\Pi+\Sigma+\Upsilon+\Phi+\Psi+\Omega",
"x_i", "x^2", "x_i^2", "f_j^N", "x_{i_j}^{N^2}",
r"\displaystyle x_i^2", r"\textstyle x_i^2",
r"\scriptstyle x+y=z", r"\scriptscriptstyle x+y=z",
r"x+{\scriptstyle y+z}+w",
r"\sum\limits_{i=1}^N", r"\sum\nolimits_{i=1}^N",
r"\sum_{i=1}^N\limits", r"\int\limits_0^1",
r"\int\displaylimits_0^1",
r"a\,b\:c\;d\!e", r"a\mskip3mu b", r"a\mkern-1.5mu b",
r"\varGamma", r"\varOmega^2", r"\tfrac{a}{b}", r"\dfrac{a}{b}",
r"\frac{a}{x^2}", r"\frac{a}{x_i^2}",
r"\frac{a}{b}", r"\frac{x_i^2}{y_j}",
r"\frac{a}{\frac{b}{c}}", r"{x_i\atop y_j}",
r"\sum", r"\sum_{i=1}^N", r"\prod_{j=1}^N", r"\int_0^1",
r"\sin(x)", r"\mathinner{x}\mathinner{y}",
# The fraction body of the arXiv fixture; the rule width is its widest child.
r"\frac{\alpha_i(t)a^{w_t}_{ij}\beta_j(t+1)b^{v_{t+1}}_j(y_{t+1})}"
r"{\sum_{i=1}^N\sum_{j=1}^N\alpha_i(t)a^{w_t}_{ij}"
r"\beta_j(t+1)b^{v_{t+1}}_j(y_{t+1})}",
]
CLASSES = ["mathord", "mathop", "mathbin", "mathrel", "mathopen",
"mathclose", "mathpunct", "mathinner"]
# Every class pair also tests TeX's context-dependent binary normalization.
CASES += [rf"\{left}{{x}}\{right}{{y}}" for left in CLASSES for right in CLASSES]
ARXIV = (ROOT / "fixtures/arxiv-template/template.tex").read_text()
CASES.append(ARXIV.split(r"\begin{equation}", 1)[1].split(r"\end{equation}", 1)[0].strip())
def main():
lines = [r"\def\frac#1#2{{#1\over#2}}",
r"\def\dfrac#1#2{{\displaystyle\frac{#1}{#2}}}",
r"\def\tfrac#1#2{{\textstyle\frac{#1}{#2}}}",
r'\mathchardef\varGamma="0100 \mathchardef\varOmega="010A',
r"\def\:{\mskip4mu}",
r"\newwrite\probes",
r"\immediate\openout\probes=metrics.csv"]
records = []
for style, command in STYLES:
for source in CASES:
expression = command + " " + source
index = len(records)
lines += [r"\setbox0=\hbox{$" + expression + "$}",
rf"\immediate\write\probes{{{index},\number\wd0,\number\ht0,\number\dp0}}"]
records.append({"style": style, "source": source})
lines += [r"\immediate\closeout\probes", r"\bye"]
with tempfile.TemporaryDirectory(prefix="texrra-math-oracle-") as directory:
path = Path(directory)
(path / "probes.tex").write_text("\n".join(lines) + "\n")
result = subprocess.run(["pdftex", "-interaction=nonstopmode", "-halt-on-error", "probes.tex"],
cwd=path, capture_output=True, text=True)
if result.returncode:
raise RuntimeError(result.stdout)
for line in (path / "metrics.csv").read_text().splitlines():
index, width, height, depth = map(int, line.split(","))
records[index].update(width=width, height=height, depth=depth)
output = ROOT / "crates/texrra-tex-core/tests/fixtures/math-tex-oracle.json"
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text("[\n" + ",\n".join(" " + json.dumps(record) for record in records) + "\n]\n")
print(f"{len(records)} pdfTeX probes: {output}")
if __name__ == "__main__":
main()
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""Read TeX DVI glyph/rule positions in sp, using the reference's actual TFM.
External test oracle only. No native engine code or geometry is imported.
"""
import argparse
import json
import struct
import subprocess
from pathlib import Path
def read_dvi(path):
data = Path(path).read_bytes()
at = 0
fonts = {}
pages = []
stack = []
pos = [0] * 6 # h,v,w,x,y,z; current font is not pushed.
current = None
def number(n, signed=False):
nonlocal at
value = int.from_bytes(data[at:at+n], 'big', signed=signed)
at += n
return value
def font_definition(n):
key = number(n)
number(4) # checksum
scale, design = number(4), number(4)
area, length = number(1), number(1)
nonlocal at
name = data[at:at+area+length].decode('ascii')
at += area+length
tfm_path = subprocess.check_output(['kpsewhich', name+'.tfm'], text=True).strip()
tfm = Path(tfm_path).read_bytes()
_, lh, bc, ec, nw = struct.unpack('>5H', tfm[:10])
char_base = 24 + lh*4
width_base = char_base + (ec-bc+1)*4
widths = struct.unpack(f'>{nw}i', tfm[width_base:width_base+nw*4])
# TeX's TFM scaling for the supported real 10/7/5pt masters; all
# bundled advance fix_words are nonnegative and scale < 2^23.
advances = {c: (widths[tfm[char_base+(c-bc)*4]]*scale)//(1 << 20)
for c in range(bc, ec+1)}
fonts[key] = (name, scale, design, advances)
while at < len(data):
op = number(1)
if op <= 131 or 133 <= op <= 136:
slot = op if op < 128 else number(op-127 if op <= 131 else op-132)
name, scale, _, widths = fonts[current]
pages[-1]['paint_order'].append(['glyph', len(pages[-1]['glyphs'])])
pages[-1]['glyphs'].append(dict(font=name, size=scale, slot=slot,
x=pos[0], y=pos[1], advance=widths[slot]))
if op <= 131:
pos[0] += widths[slot]
elif op in (132, 137):
height, width = number(4, True), number(4, True)
if height > 0 and width > 0:
pages[-1]['paint_order'].append(['rule', len(pages[-1]['rules'])])
pages[-1]['rules'].append(dict(x=pos[0], y=pos[1]-height,
width=width, height=height))
if op == 132:
pos[0] += width
elif op == 138:
pass
elif op == 139:
at += 44
pos = [0]*6
stack = []
pages.append(dict(glyphs=[], rules=[], paint_order=[]))
elif op == 140:
assert not stack
elif op == 141:
stack.append(pos.copy())
elif op == 142:
pos = stack.pop()
elif 143 <= op <= 146:
pos[0] += number(op-142, True)
elif 147 <= op <= 156:
base, register = (147, 2) if op <= 151 else (152, 3)
if op != base:
pos[register] = number(op-base, True)
pos[0] += pos[register]
elif 157 <= op <= 160:
pos[1] += number(op-156, True)
elif 161 <= op <= 170:
base, register = (161, 4) if op <= 165 else (166, 5)
if op != base:
pos[register] = number(op-base, True)
pos[1] += pos[register]
elif 171 <= op <= 234:
current = op-171
elif 235 <= op <= 238:
current = number(op-234)
elif 239 <= op <= 242:
length = number(op-238)
at += length
elif 243 <= op <= 246:
font_definition(op-242)
elif op == 247:
assert number(1) == 2
assert [number(4) for _ in range(3)] == [25400000, 473628672, 1000]
length = number(1)
at += length
elif op == 248:
break
else:
raise ValueError(f'unsupported DVI opcode {op}')
return pages
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('dvi', type=Path)
print(json.dumps(read_dvi(parser.parse_args().dvi)))
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env python3
"""Audit strict native startup of an unmodified, entry-source-pinned format.
This records the first blocking diagnostic. A completed audit is not a
successful format boot; format_boot_passed remains false on native failure.
Transitive format dependencies and a portable fmt loader are not yet pinned.
"""
import argparse
import hashlib
import json
import re
from pathlib import Path
import subprocess
import tempfile
def main():
root = Path(__file__).resolve().parents[1]
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--binary", type=Path, default=root / "target/release/texrra")
parser.add_argument("--texmf", type=Path, required=True)
parser.add_argument("--manifest", type=Path, default=root / "tests/fixtures/native-format-entry.json")
parser.add_argument("--json", type=Path, required=True)
args = parser.parse_args()
manifest = json.loads(args.manifest.read_text())
entry = (args.texmf / manifest["entry"]).resolve()
before = hashlib.sha256(entry.read_bytes()).hexdigest()
if before != manifest["sha256"]:
raise SystemExit(f"format entry hash mismatch: {entry}; expected {manifest['sha256']}, got {before}")
with tempfile.TemporaryDirectory(prefix="texrra-native-format-") as temporary:
pdf = Path(temporary) / "format.pdf"
result = subprocess.run([str(args.binary.resolve()), "native", "--job", "--initex", "--etex", str(entry), str(pdf)],
capture_output=True, text=True, timeout=60, cwd=temporary)
after = hashlib.sha256(entry.read_bytes()).hexdigest()
assert before == after, "native format probe modified its source"
assert result.returncode == 0 or not pdf.exists(), "failed native execution wrote a PDF"
location = re.search(r"error: (.*):(\d+):(\d+): (.*)", result.stderr)
report = {
"audit_completed": True,
# A zero exit only proves execution reached the end. This slice
# has no native dump writer/loader, so it cannot certify a format.
"format_boot_passed": False,
"native_execution_completed": result.returncode == 0,
"profile": "native e-TeX job (partial; format-image completion is not certified)",
"entry": manifest["entry"],
"version": manifest["version"],
"sha256": before,
"source_unchanged": True,
"native_exit_code": result.returncode,
"first_blocker": {"source": location[1], "line": int(location[2]),
"column": int(location[3]), "message": location[4]} if location else None,
"diagnostic": result.stderr.strip(),
"stdout": result.stdout.strip(),
"job_files": {path.name: path.read_text() for path in Path(temporary).iterdir()
if path.is_file() and path.suffix in (".aux", ".log")},
"scope": "entry source only; transitive dependencies and fmt serialization are not certified",
}
args.json.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""Run original publisher samples in independent reference and native jobs."""
import argparse
import hashlib
import json
import os
import re
import shutil
import stat
import subprocess
import zipfile
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path, PurePosixPath
ROOT = Path(__file__).resolve().parent.parent
CASES = [
("arxiv", "preprint", None, "template.tex"),
("springer-nature", "journal", "springer-journal", "sn-article-template/sn-article.tex"),
("elsevier-cas-sc", "journal-single-column", "elsevier-cas", "els-cas-templates/cas-sc-sample.tex"),
("elsevier-cas-dc", "journal-two-columns", "elsevier-cas", "els-cas-templates/cas-dc-sample.tex"),
("ieee-transactions", "journal-two-columns", "ieee", "IEEEtran/bare_jrnl.tex"),
("aps-revtex-reprint", "journal-two-columns", "revtex", "revtex/sample/aps/apssamp.tex"),
("springer-lncs", "conference", "springer-lncs", "samplepaper.tex"),
("ieee-conference", "conference", "ieee", "IEEEtran/bare_conf.tex"),
("acl", "conference", "acl", "acl-style-files-master/acl_latex.tex"),
("cvpr-2026", "conference", "cvpr-2026", "author-kit-CVPR2026-v1-latex-/main.tex"),
]
EPS_FIGURES = {
"springer-nature": ["fig.eps"],
"aps-revtex-reprint": ["fig_1.eps", "fig_2.eps", "vid_1a.eps", "vid_1b.eps"],
"springer-lncs": ["fig1.eps"],
}
def sha(path):
with path.open("rb") as stream:
return hashlib.file_digest(stream, "sha256").hexdigest()
def inputs(directory):
return {p.relative_to(directory).as_posix(): sha(p)
for p in sorted(directory.rglob("*")) if p.is_file()}
def unpack(path, directory):
with zipfile.ZipFile(path) as archive:
for info in archive.infolist():
name = PurePosixPath(info.filename)
if name.is_absolute() or ".." in name.parts or "\\" in info.filename:
raise ValueError(f"unsafe path in {path}: {info.filename}")
if stat.S_ISLNK(info.external_attr >> 16):
raise ValueError(f"unexpected symlink in {path}: {info.filename}")
archive.extractall(directory)
def run(command, cwd, env, label, evidence):
with (evidence / f"{label}.stdout.log").open("wb") as output, \
(evidence / f"{label}.stderr.log").open("wb") as errors:
try:
status = subprocess.run(command, cwd=cwd, env=env, stdout=output, stderr=errors,
timeout=90).returncode
except subprocess.TimeoutExpired:
status = 124
return {"command": list(map(str, command)), "exit_code": status, "label": label}
def diagnostics(evidence, label):
lines = []
for stream in ("stderr", "stdout"):
log = (evidence / f"{label}.{stream}.log").read_text(errors="replace")
lines.extend(line for line in log.splitlines()
if line.startswith(("error:", "!", "pdftex:", "I couldn't", "I found no")))
return lines[:15]
def prepare_figures(name, template, entry, evidence, args):
if not args.ghostscript or name not in EPS_FIGURES:
return []
directory = template / Path(entry).parent
output = evidence / "converted-eps"
output.mkdir()
env = {**os.environ, "SOURCE_DATE_EPOCH": "1783900800"}
results = []
for file_name in EPS_FIGURES[name]:
source = directory / file_name
stem = source.stem
pdf = output / f"{stem}-eps-converted-to.pdf"
assert source.is_file() and not (directory / pdf.name).exists()
source_sha256 = sha(source)
result = run(["epstopdf", f"--gscmd={args.ghostscript}", f"--outfile={pdf}", source],
output, env, stem, output)
assert result["exit_code"] == 0 and pdf.is_file(), result
with pdf.open("rb") as stream:
assert stream.read(5) == b"%PDF-", pdf
assert sha(source) == source_sha256
results.append({"source": file_name, "source_sha256": source_sha256, "pdf_path": str(pdf),
"pdf_sha256": sha(pdf), **result})
return results
def compile_sample(template, entry, evidence, args, engine, figures):
work = evidence / "work"
evidence.mkdir()
shutil.copytree(template, work)
frozen = inputs(work)
assert frozen == inputs(template) and entry in frozen
cwd = work / Path(entry).parent
for figure in figures:
pdf = Path(figure["pdf_path"])
assert sha(pdf) == figure["pdf_sha256"]
shutil.copyfile(pdf, cwd / pdf.name)
prefix = "texrra-oracle"
jobname = prefix if engine == "reference" else Path(entry).stem
output = cwd / f"{prefix}.pdf"
assert not output.exists()
aux = cwd / f"{jobname}.aux"
env = {**os.environ, "TEXINPUTS": os.pathsep, "TEXRRA_STATE_DIR": str(evidence / "state"),
"BSTINPUTS": f"{cwd}/bst//:", "BIBINPUTS": f"{cwd}:", "SOURCE_DATE_EPOCH": "1783900800"}
if args.texmf_overlay:
env["TEXMFHOME"] = str(args.texmf_overlay)
if args.font_map:
env["TEXFONTMAPS"] = str(args.font_map.parent) + os.pathsep
if engine == "reference":
latex = ["pdftex", f"-fmt={args.reference_format}", "-interaction=nonstopmode",
"-halt-on-error", "-no-shell-escape", "-recorder", f"-jobname={prefix}", Path(entry).name]
else:
latex = [args.binary, "native", "--job", "--etex", "--step-limit", "600000000",
"--input-policy", "tex", "--load-format", args.native_format]
if args.texmf_overlay:
latex.extend(["--texmf-root", args.texmf_overlay])
latex.extend(["--texmf-root", "/usr/share/texlive/texmf-dist", "--texmf-root", "/var/lib/texmf",
Path(entry).name, output.name])
commands = []
aux_checksums = []
for idx in range(1, args.max_passes + 1):
label = f"latex-{idx}"
command = latex
if engine == "native":
command = [*latex[:-2], "--resource-manifest", evidence / f"{label}.resources.json",
"--layout-manifest", evidence / f"{label}.layout.json", *latex[-2:]]
step = run(command, cwd, env, label, evidence)
recorder = cwd / f"{prefix}.fls"
if engine == "reference" and recorder.is_file():
shutil.copyfile(recorder, evidence / f"{label}.fls")
commands.append(step)
if step["exit_code"]:
break
if aux.is_file():
shutil.copyfile(aux, evidence / f"{label}.aux")
aux_checksums.append(sha(aux) if aux.is_file() else None)
if idx == 1 and aux.is_file() and b"\\bibdata{" in aux.read_bytes():
step = run(["bibtex", jobname], cwd, env, "bibtex", evidence)
commands.append(step)
if step["exit_code"]:
break
if idx >= 3 and aux_checksums[-1] is not None and aux_checksums[-1] == aux_checksums[-2]:
break
changed = [name for name, digest in frozen.items()
if not (work / name).is_file() or sha(work / name) != digest]
last = commands[-1]
built = last["exit_code"] == 0 and output.is_file()
logfile = cwd / f"{prefix}.log"
log = logfile.read_text(errors="replace") if logfile.is_file() else ""
pdf = {}
if built:
pdf = {"sha256": sha(output), "bytes": output.stat().st_size}
for cmd in ("pdfinfo", "pdffonts"):
run([cmd, output.name], cwd, env, cmd, evidence)
run(["pdftotext", "-bbox-layout", output.name, evidence / "word-boxes.html"],
cwd, env, "pdf-word-boxes", evidence)
info = (evidence / "pdfinfo.stdout.log").read_text(errors="replace")
pages = re.search(r"^Pages:\s+(\d+)", info, re.M)
pdf["pages"] = int(pages.group(1)) if pages else None
return {"commands": commands, "diagnostics": diagnostics(evidence, last["label"]),
"aux_file": aux.name,
"packaged_files_changed_in_work_directory": {
name: {"before": frozen[name], "after": sha(work / name) if (work / name).is_file() else None}
for name in changed
},
"entry_sha256": frozen[entry],
"aux_sha256_per_pass": aux_checksums, "aux_converged": len(aux_checksums) >= 2
and aux_checksums[-1] is not None and aux_checksums[-1] == aux_checksums[-2],
"undefined_reference_warnings": [
line for line in log.splitlines()
if re.search(r"\bundefined (references|citations)\b|\b(?:Reference|Citation)\b.*\bundefined\b",
line, re.I)
],
"pdf_built": built, "pdf": pdf}
def main():
parser = argparse.ArgumentParser(description=__doc__)
for key in ("archives", "output", "binary", "native-format", "reference-format"):
parser.add_argument(f"--{key}", type=lambda p: Path(p).resolve(), required=True)
parser.add_argument("--texmf-overlay", type=lambda p: Path(p).resolve())
parser.add_argument("--font-map", type=lambda p: Path(p).resolve())
parser.add_argument("--ghostscript", type=lambda p: Path(p).resolve(strict=True),
help="Ghostscript executable for explicit conversion of the original EPS figures")
parser.add_argument("--max-passes", type=int, choices=range(4, 13), default=4)
parser.add_argument("--case", action="append", choices=[item[0] for item in CASES],
help="run selected cases; omit to run the complete matrix")
args = parser.parse_args()
if args.font_map and args.font_map.name != "pdftex.map":
parser.error("--font-map must name a pdftex.map file")
config = json.loads((ROOT / "scripts/publisher-template-matrix.json").read_text())
sources = args.output / "inputs"
sources.mkdir(parents=True)
for archive, (digest, url) in config.items():
path = args.archives / f"{archive}.zip"
if sha(path) != digest:
raise ValueError(f"archive bytes differ from the pinned SHA-256: {path}")
unpack(path, sources / archive)
if args.texmf_overlay and not args.texmf_overlay.is_dir():
raise ValueError(f"missing overlay: {args.texmf_overlay}")
additions = inputs(args.texmf_overlay) if args.texmf_overlay else {}
font_map_sha256 = sha(args.font_map) if args.font_map else None
def case(item):
name, category, archive, entry = item
template = sources / archive if archive else ROOT / "fixtures/arxiv-template"
evidence = args.output / name
evidence.mkdir()
frozen = inputs(template)
row = {"name": name, "category": category, "archive": archive, "entry": entry,
"inputs": frozen}
figures = prepare_figures(name, template, entry, evidence, args)
row["converted_eps"] = figures
for engine in ("reference", "native"):
row[engine] = compile_sample(template, entry, evidence / engine, args, engine, figures)
assert inputs(template) == frozen
assert all(entry not in row[engine]["packaged_files_changed_in_work_directory"]
for engine in ("reference", "native"))
(evidence / "report.json").write_text(json.dumps(row, indent=2) + "\n")
print(name, row["reference"]["pdf_built"], row["native"]["pdf_built"], flush=True)
return row
selected = [item for item in CASES if not args.case or item[0] in args.case]
with ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(case, selected))
report = {"schema": 1, "scope": "compile and collect evidence; PDF creation alone is not fidelity",
"archives": config, "native_binary_sha256": sha(args.binary),
"native_format_sha256": sha(args.native_format),
"reference_format_sha256": sha(args.reference_format), "texmf_overlay": additions,
"font_map_sha256": font_map_sha256,
"templates": results}
assert not args.texmf_overlay or inputs(args.texmf_overlay) == additions
assert not args.font_map or sha(args.font_map) == font_map_sha256
(args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n")
if __name__ == "__main__":
main()
+30
View File
@@ -0,0 +1,30 @@
{
"springer-journal": [
"812e76dcaa9c28dc1bff1fb6065d51729b67d4ea140552a05088317414a3ecae",
"https://cms-resources.apps.public.k8s.springernature.io/springer-cms/rest/v1/content/18782940/data/v12"
],
"springer-lncs": [
"42afb32ed4fadc9e209134ec65dab1bd2a7ead42f9a3f8abb184f250c4a197b9",
"https://cms-resources.apps.public.k8s.springernature.io/springer-cms/rest/v1/content/27851904/data/LaTeX2e%20Proceedings%20Template%20ZIP"
],
"elsevier-cas": [
"36d97da01c6bbd134f315bff6c3de553735e2550444a6ddd4f869ddc67a20757",
"https://mirrors.ctan.org/macros/latex/contrib/els-cas-templates.zip"
],
"ieee": [
"e0cd4f5afbd42c8076092280e72b3e0a5111efe501d35de9f715cfb8da313cb4",
"https://mirrors.ctan.org/macros/latex/contrib/IEEEtran.zip"
],
"revtex": [
"5a5ebc9831ae219b2bcf2f8b408dc07a55a9e244af1317f1f25ca187daa40d82",
"https://mirrors.ctan.org/macros/latex/contrib/revtex.zip"
],
"acl": [
"bead1eec1aa2c4de8596ddcdd5ac22917f38b2c8441b853ff13015c0b0b8b92e",
"https://codeload.github.com/acl-org/acl-style-files/zip/refs/heads/master"
],
"cvpr-2026": [
"ef672bf4ad1c6801237b957d57b0087d4412e7dee01ad3b512abe82960c6466c",
"https://codeload.github.com/cvpr-org/author-kit/zip/refs/tags/CVPR2026-v1%28latex%29"
]
}
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Exact bbox decoding tests; no lossy XML recovery or text normalization."""
from pathlib import Path
import runpy
import unittest
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[1]
parse = runpy.run_path(str(ROOT / "scripts/check-native-paragraphs.py"))["parse_bbox"]
compare = runpy.run_path(str(ROOT / "scripts/check-native-format-articles.py"))["compare_words"]
def bbox(text):
return ('<html xmlns="http://www.w3.org/1999/xhtml"><body><doc><page width="1" height="1">'
'<word xMin="0" yMin="1" xMax="2" yMax="3">' + text +
'</word></page></doc></body></html>').encode("utf-8")
class ExactBbox(unittest.TestCase):
def test_control_noncharacter_astral_and_collision_like_strings_are_retained(self):
text = ''.join(map(chr, range(32))) + '\u007f\u0080\ue000\ue001\ufffe\U0001f600%CONTROL0012%'
self.assertEqual(parse(bbox(text))[0][0][0], text)
def test_entities_are_decoded_once_and_numeric_controls_are_retained(self):
self.assertEqual(parse(bbox('&amp;#18;&lt;&gt;&quot;&apos;&#18;&#x13;&#xE000;&#x1F600;'))[0][0][0],
'&#18;<>"\'\x12\x13\ue000\U0001f600')
def test_valid_xml_retains_the_previous_coordinates_and_text(self):
data = bbox('A &amp; B &#x1F600;')
expected = [(node.text, {key: float(value) for key, value in node.attrib.items()})
for node in ET.fromstring(data).iter() if node.tag.endswith('}word')]
self.assertEqual(parse(data), [expected])
def test_malformed_structure_and_entities_still_fail(self):
for text in ['&unknown;', '&amp', '<nested/>', 'a & b', '&#x110000;', '&#xD800;']:
with self.subTest(text=text), self.assertRaises(ET.ParseError):
parse(bbox(text))
with self.assertRaises(ET.ParseError):
parse(bbox('okay').replace(b'<body>', b'<body>\x12'))
def test_characters_and_order_remain_mandatory(self):
for actual, expected in [('(', '\x12'), ('\x12', '\x13'), ('\x12\x13', '\x13\x12'),
('A', 'A\x00'), ('\ue000', '\ue001')]:
self.assertFalse(compare(parse(bbox(actual)), parse(bbox(expected)), .02)['passed'])
def test_a2_delimiter_character_and_word_order_difference_still_fails(self):
# The original failure had two separately positioned delimiter words.
def pair(left, right):
return bbox(left).replace(b'</word>', ('</word><word xMin="4" yMin="1" xMax="6" yMax="3">' +
right + '</word>').encode('utf-8'), 1)
actual = parse(pair('(', ')'))
expected = parse(pair('\x13', '\x12'))
self.assertFalse(compare(actual, expected, .02)['passed'])
self.assertEqual([text for text, _ in actual[0] if text in ['(', ')', '\x12', '\x13']], ['(', ')'])
self.assertEqual([text for text, _ in expected[0] if text in ['(', ')', '\x12', '\x13']], ['\x13', '\x12'])
if __name__ == '__main__':
unittest.main()