209 lines
11 KiB
Python
209 lines
11 KiB
Python
#!/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()
|