Files
texrra-engine/scripts/check-native-format-articles.py

344 lines
16 KiB
Python

#!/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())