diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf84594..62b55cf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3,10 +3,24 @@ name: ci on: push: branches: [main] + tags: ["v*"] pull_request: workflow_dispatch: jobs: + + quality: + name: Lint and type check + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.2.2 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: '3.12' + - run: python -m pip install --upgrade pip nox + - run: nox -s lint typecheck + test: strategy: fail-fast: false @@ -22,6 +36,8 @@ jobs: run: | python -m pip install --upgrade pip python -m pip install -e ".[dev]" + - name: Fetch pinned benchmark font + run: python spikes/fetch_b0_font.py - name: Test run: python -m pytest -q - name: Validate frozen benchmark manifest diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml new file mode 100644 index 0000000..e720421 --- /dev/null +++ b/.github/workflows/scorecard.yml @@ -0,0 +1,42 @@ +name: Scorecard supply-chain security +on: + branch_protection_rule: + schedule: + - cron: '30 1 * * 1' + push: + branches: ["main"] + workflow_dispatch: + +permissions: read-all + +jobs: + analysis: + name: Scorecard analysis + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + security-events: write + id-token: write + contents: read + actions: read + steps: + - name: Checkout code + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.2.2 + with: + persist-credentials: false + - name: Run analysis + uses: ossf/scorecard-action@62b2cac7ed8198b15735ed49ab1e5cf35480ba46 # v2.4.0 + with: + results_file: results.sarif + results_format: sarif + publish_results: true + - name: Upload artifact + uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 + with: + name: SARIF file + path: results.sarif + retention-days: 5 + - name: Upload to code-scanning + uses: github/codeql-action/upload-sarif@f09c1c0a94de965c15400f5634aa42fac8fb8f88 # v3.27.5 + with: + sarif_file: results.sarif diff --git a/.gitignore b/.gitignore index 6a1717b..708ed6e 100644 --- a/.gitignore +++ b/.gitignore @@ -19,8 +19,15 @@ venv/ # Generated holdout samples and labels (sealed; only seal.json is committed) benchmark/holdout/* !benchmark/holdout/seal.json +!benchmark/holdout/BURNED # OS / editor .DS_Store Thumbs.db .pytest-tmp/ + +# Local verification virtualenvs +.venv*/ + +# Internal planning notes +.superpowers/ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..87f8df7 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,36 @@ +minimum_pre_commit_version: "3.7.0" +default_language_version: + python: python3 +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 + hooks: + - id: check-yaml + args: [--allow-multiple-documents] + - id: check-toml + - id: check-json + - id: check-added-large-files + args: [--maxkb=2048] + - id: check-merge-conflict + - id: check-case-conflict + - id: end-of-file-fixer + - id: trailing-whitespace + args: [--markdown-linebreak-ext=md] + - id: mixed-line-ending + args: [--fix=lf] + # Local hooks so the hook and the CI job run the exact same binary version. + # Install once: python -m pip install ruff mypy (or from the shared wheelhouse) + - repo: local + hooks: + - id: ruff + name: ruff + entry: ruff check --fix --exit-non-zero-on-fix + language: system + types_or: [python, pyi] + require_serial: true + - id: mypy + name: mypy + entry: mypy --config-file=pyproject.toml + language: system + pass_filenames: false + types_or: [python, pyi] diff --git a/CHANGELOG.md b/CHANGELOG.md index 635ff7b..af07e0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,16 @@ ## Unreleased +- Add a deterministic frozen-manifest holdout generator with pre-execution sample ID, PDF, + source, label, code and runtime hashes; the seal excludes labels and records the lack of an + independent custodian or human PDF-review session. +- Add a one-shot Windows-only holdout runner that refuses changed code/input/runtime evidence, + retains full raw reports, and publishes pooled/per-class precision, recall, false-PASS, + UNKNOWN and ERROR rates with 95% Wilson intervals. No detector threshold tuning is exposed. +- Correct package metadata to describe bounded local font-cmap evidence and run CI on `v*` tags. +- Record that v3 TDD exercised `H01.clean.s1` before sealing, burning the current manifest under + B0 §6.6; add a fail-closed `BURNED` guard and make no holdout accuracy claim. + ## 0.1.0a3 — 2026-11-29 - Add structured CLI errors, explicit force semantics, paired rollback-safe reports, OS-fd output isolation and strict Windows output-component checks. diff --git a/README.md b/README.md index 35eb2bb..006e20d 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,23 @@ # PlotProof +[![CI](https://github.com/gedouluhui/plotproof/actions/workflows/ci.yml/badge.svg)](https://github.com/gedouluhui/plotproof/actions/workflows/ci.yml) +[![Release](https://img.shields.io/github/v/tag/gedouluhui/plotproof?label=release&sort=semver)](https://github.com/gedouluhui/plotproof/releases) +[![Python](https://img.shields.io/badge/python-3.12%2B-blue)](https://github.com/gedouluhui/plotproof/blob/main/pyproject.toml) +[![License](https://img.shields.io/github/license/gedouluhui/plotproof)](LICENSE) +[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/gedouluhui/plotproof/badge)](https://securityscorecards.dev/viewer/?uri=github.com/gedouluhui/plotproof) + **Source-assisted export evidence for Matplotlib figures.** PlotProof records what a figure intends to draw at save time, compares that record with the exported PDF, and reports what went wrong — or `UNKNOWN` when the evidence is not strong enough. -> **Status: B1 engineering preview (2026-11-19).** The deterministic checker core, the -> bounded PDF reader and the CA1 save-time capture layer are implemented and tested. -> An experimental assembly runs the whole path end to end on one figure. -> It is **not** a certified detector: there is no holdout run and no accuracy number. -> D4 now uses bounded local font-cmap evidence; unavailable provenance is reported as -> `UNKNOWN`, never as a missing-glyph pass. Read -> [What this does not do](#what-this-does-not-do) before trusting any output. +> **Status: B1 engineering preview with v3 holdout tooling.** The deterministic checker core, +> bounded PDF reader, CA1 capture layer and reproducible sealed-holdout runner are implemented +> and tested. There is **no valid holdout result or accuracy number**: the v3 TDD worker contract +> exercised `H01.clean.s1` before sealing, which burns this manifest for confirmatory use under +> B0 §6.6. The runner refuses burned holdouts; a new preregistered seed/template set is required. +> D4 uses bounded local font-cmap evidence; unavailable provenance is reported as `UNKNOWN`, +> never as a missing-glyph pass. Read [What this does not do](#what-this-does-not-do) before +> trusting any output. ## The problem @@ -182,9 +189,10 @@ text, unresolved alignment, coverage below 0.90, or a finding at medium confiden ## What this does not do -- **No holdout, no accuracy claim.** The benchmark manifest is frozen at B0; its - holdout has never been generated or inspected. Nothing here is a precision/recall - measurement. +- **No valid holdout, no accuracy claim.** The v3 TDD worker test ran the frozen + `H01.clean.s1` input before sealing. B0 §6.6 therefore burns this manifest for confirmatory + use; no precision/recall result from it would be valid. `benchmark/holdout/BURNED` records + the cause, and the runner fails closed on that marker. - **Font evidence is bounded and local.** D4 reads Unicode cmaps only from the renderer-selected font files, binds them by SHA-256, and treats missing, malformed or over-budget provenance as `UNKNOWN`. It does not certify font licensing, embedding, or every backend/version combination. @@ -258,7 +266,7 @@ Verified facts worth knowing before extending this: | B1 | deterministic core for D1–D4, bounded PDF reader, CA1 capture | core/reader/capture implemented and tested | | B1.5 | end-to-end assembly, D1/D3 assessment, class-scoped reports | this preview | | B2 | font evidence (D4), complete paint inventory (D2 for collections/images), dev-split calibration | not started | -| B3 | one sealed holdout run, preregistered report | not started | +| B3 | one sealed holdout run, preregistered report | runner implemented; current manifest burned by pre-seal TDD exposure | | B4 | release, documentation, examples | not started | ## Development @@ -267,9 +275,31 @@ Verified facts worth knowing before extending this: .venv/Scripts/python -m pip install -e ".[dev]" python -m pytest # run the full suite; see task report for verified totals .venv/Scripts/python benchmark/validate_manifest.py + +# Windows + the pinned runtime/font only; generate once, review once, then execute once: +.venv/Scripts/python benchmark/generate_holdout.py --generate-only --output-dir benchmark/holdout +# Owner opens every PDF and corrects labels in the logged review session; no detector runs. +.venv/Scripts/python benchmark/generate_holdout.py --seal-reviewed --reviewed-by OWNER --output-dir benchmark/holdout +.venv/Scripts/python benchmark/run_holdout.py --holdout-dir benchmark/holdout ``` -CI runs the suite on Ubuntu 3.12 and Windows 3.12 with Matplotlib 3.10.8. +The generator seals all 114 holdout sample IDs and PDF/source hashes before benchmark execution. +Generation writes `generation.json`, unreviewed `labels.json` and `label_review_log.json`, but no +seal. Sealing is a separate explicit step requiring `--reviewed-by`; it rejects changed code, +runtime, labels or malformed review metadata and binds the review-log hash. The runner verifies +the frozen manifest, labels, code bytes, pinned Windows runtime and every input hash, logs the +unseal, refuses burned holdouts, and refuses a second run once predictions exist. It writes +`predictions.jsonl`, full `raw_outcomes.jsonl`, `results.json` and `summary.md`; the summary +reports pooled and per-class precision/recall, false-PASS, UNKNOWN/ERROR rates, macro alignment +coverage and 95% Wilson intervals. Generated holdout files are git-ignored. The procedural seal +is not access control: no independent custodian or human PDF label-review session is claimed by +the tooling itself, and synthetic-template results do not establish real-world accuracy. + +The current runner implements the detector metrics and Wilson intervals, but **not** the B0 +baseline-B delta gate or template-cluster bootstrap. Its aggregate `all_pass` therefore fails +closed. See [B3 holdout methodology](docs/B3_HOLDOUT.md) for evidence boundaries and commands. + +CI runs the suite on Ubuntu 3.12 and Windows 3.12 with Matplotlib 3.10.8, and on `v*` tags. ## License @@ -326,10 +356,10 @@ python -m plotproof check does-not-exist.py --json missing-report.json --html mi Expected: The missing figure module returns a structured stdout JSON error with exit 2 and no success is claimed. Existing outputs require explicit `--force`; safe error JSON is published when possible. `--max-d3-work` bounds all D3 pair evaluation. ### Evidence and coverage boundaries -Evidence includes the full pytest suite for the deterministic core, bounded PDF reader, CA1 capture, structured CLI, safe publication, complexity budget, local font-cmap evidence and end-to-end assembly. There is no holdout run or accuracy number. D4 is assessed only when renderer-selected font provenance is available; otherwise it is explicitly UNKNOWN. PASS means only that no supported defect was found with sufficient coverage in assessed classes. +Evidence includes the full pytest suite for the deterministic core, bounded PDF reader, CA1 capture, structured CLI, safe publication, complexity budget, local font-cmap evidence, end-to-end assembly and sealed-holdout validation/metrics. There is no valid holdout run or accuracy number: pre-seal TDD exposure burned the current manifest under B0 §6.6. D4 is assessed only when renderer-selected font provenance is available; otherwise it is explicitly UNKNOWN. PASS means only that no supported defect was found with sufficient coverage in assessed classes. ### Support status -Version 0.1.0a4 is a B1 engineering preview for Python 3.12 and Matplotlib 3.10.8. The PDF worker path is verified on Windows only. It is not a certified detector and has no accuracy claim. Maintenance is best-effort with no SLA. +Version 0.1.0a4 is a B1 engineering preview for Python 3.12 and Matplotlib 3.10.8. The PDF worker path is verified on Windows only. The v3 sealed-holdout runner is implemented, but the current manifest is burned and has no valid accuracy claim. Maintenance is best-effort with no SLA. ### Limitations Rotated text, mathtext, TeX, wrapped/rasterized text, path effects, arbitrary/multi-page/rotated PDFs, and semantic or aesthetic judgment are outside scope. D2 is skipped when images or collections prevent a complete paint inventory. D3 is skipped as a whole when its declared work budget is exceeded. Output rollback is not crash atomicity. diff --git a/README.zh-CN.md b/README.zh-CN.md index 0aae887..f4bf30d 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -68,10 +68,10 @@ estimated_work = pairs + operand_work + intersection_work + union_sort_work 估算值等于上限时仍执行 D3。矩形并集采用精确有理数坐标压缩线段树扫描,复杂度 O(m log m);有理坐标避免混合尺度下溢与中间溢出,真正无法表示为有限非零浮点数的面积会抛错,而不是返回虚假的有限零值。 ### 证据与覆盖边界 -证据包括完整 pytest 测试,覆盖确定性核心、受限 PDF 读取器、CA1 采集、结构化 CLI、安全发布、复杂度预算、本地字体 cmap 证据和端到端装配。没有保留集结果或准确率数字。D4 仅在渲染器选中的字体来源可用时评估,否则明确报告 `UNKNOWN`。PASS 仅表示在已评估类别中且覆盖足够时未发现受支持的缺陷。 +证据包括完整 pytest 测试,覆盖确定性核心、受限 PDF 读取器、CA1 采集、结构化 CLI、安全发布、复杂度预算、本地字体 cmap 证据、端到端装配,以及保留集封存验证和指标计算。没有有效的保留集结果或准确率数字:v3 TDD worker 测试在封存前运行了 `H01.clean.s1`,依据 B0 §6.6 烧毁了当前清单。运行器会拒绝已烧毁的保留集;需要新的预注册种子/模板集。D4 仅在渲染器选中的字体来源可用时评估,否则明确报告 `UNKNOWN`。PASS 仅表示在已评估类别中且覆盖足够时未发现受支持的缺陷。 ### 支持状态 -版本 0.1.0a4 是面向 Python 3.12 和 Matplotlib 3.10.8 的 B1 工程预览。PDF worker 路径仅在 Windows 上验证。它不是认证检测器,也没有准确率声明。维护为尽力而为,不提供 SLA。 +版本 0.1.0a4 是面向 Python 3.12 和 Matplotlib 3.10.8 的 B1 工程预览。PDF worker 路径仅在 Windows 上验证。v3 保留集运行器已实现,但当前清单已烧毁,没有有效准确率声明。维护为尽力而为,不提供 SLA。 ### 限制 不支持旋转文字、数学公式、TeX、自动换行/栅格化文字、路径效果、任意/多页/旋转 PDF,也不做语义或美学判断。当图像或集合导致绘制清单不完整时,D2 会被跳过;D3 估算工作量超过预算时整类跳过。输出回滚不具备崩溃原子性。 diff --git a/benchmark/generate_holdout.py b/benchmark/generate_holdout.py new file mode 100644 index 0000000..d2b3ac4 --- /dev/null +++ b/benchmark/generate_holdout.py @@ -0,0 +1,630 @@ +#!/usr/bin/env python3 +"""Generate, review and then seal the deterministic frozen-manifest holdout. + +Generation uses the real CA1 PDF capture path but never invokes check_figure or +any defect rule. It writes unreviewed labels and generation.json, never a seal. +A separate --seal-reviewed step requires an explicit human reviewer and binds +the review-log hash; the seal contains sample identities and hashes only. +""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import sys +from dataclasses import asdict, dataclass +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from benchmark.holdout import ( + FONT_PATH, + MANIFEST_KEY, + ROOT, + HoldoutError, + canonical_json, + code_fingerprint, + emit_error, + expand_samples, + holdout_sample_ids, + load_manifest, + pinned_environment, + sha256_file, + validate_environment, + validate_review_log, + validate_seal, + write_json, +) + + +@dataclass +class BuiltSample: + figure: Any + target: Any + related: Any + save_kwargs: dict[str, Any] + injection: dict[str, Any] + + +def _template(manifest: dict[str, Any], sample: dict[str, Any]) -> dict[str, Any]: + if sample.get("variant") == "counterexample": + return {} + return next(item for item in manifest["templates"] if item["id"] == sample["template_id"]) + + +def _counter(manifest: dict[str, Any], sample: dict[str, Any]) -> dict[str, Any]: + if sample.get("variant") != "counterexample": + return {} + return next(item for item in manifest["counterexamples"] + if item["id"] == sample["counterexample_id"]) + + +def _font_properties(cjk: bool = False): + from matplotlib.font_manager import FontProperties + + return FontProperties(fname=str(FONT_PATH)) if cjk else FontProperties(family="DejaVu Sans") + + +def _labels(ax, *, xlabel: str = "X value", ylabel: str = "Y value", + right: bool = False) -> None: + ax.set_xlabel(xlabel, rotation=0, labelpad=4.0) + ax.set_ylabel(ylabel, rotation=0, labelpad=4.0, + ha="left" if right else "right") + + +def _line(ax, seed: int, *, multi: int = 1, log: bool = False, + dates: bool = False, dense: bool = False, twin: bool = False, + scientific: bool = False) -> None: + import numpy as np + from matplotlib.ticker import FuncFormatter, ScalarFormatter + + if dates: + x = [datetime(2024, 1, 1) + timedelta(days=index) for index in range(8)] + y = np.array([2, 4, 3, 6, 5, 8, 7, 9], dtype=float) + seed / 10 + ax.plot(x, y, marker="o") + ax.tick_params(axis="x", rotation=0) + else: + x = np.linspace(0, 10, 40 if dense else 30) + for series in range(multi): + y = np.sin(x * (0.5 + series * 0.2) + series) + seed / 10 + series + ax.plot(x, y, label=f"Series {series + 1}") + if log: + ax.set_yscale("log") + ax.yaxis.set_major_formatter(FuncFormatter("{:g}".format)) + if scientific: + ax.set_ylim(0, 5000) + ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=False)) + ax.ticklabel_format(axis="y", style="sci", scilimits=(3, 3), useMathText=False) + if dense: + ax.set_xticks(list(range(40))) + ax.set_xlim(-0.5, 39.5) + ax.xaxis.set_minor_locator(__import__("matplotlib").ticker.MultipleLocator(0.25)) + ax.xaxis.set_major_formatter(FuncFormatter("{:d}".format)) + ax.tick_params(axis="x", rotation=0) + if twin: + twin_ax = ax.twinx() + twin_ax.plot(x, np.cos(x) + 2, color="tab:orange", label="Right series") + twin_ax.set_ylabel("Right value", rotation=0, labelpad=4.0, ha="left") + if multi > 1 or twin: + ax.legend(loc="upper left", frameon=True) + + +def _chart(fig: Any, template: dict[str, Any], seed: int) -> Any: + import numpy as np + from matplotlib.ticker import FuncFormatter + + tid = template["id"] + family = template["family"] + if tid == "H11": + axes = fig.subplots(1, 2) + for index, ax in enumerate(axes): + x = np.linspace(0, 4, 20) + ax.plot(x, np.sin(x + index), label=f"Panel {index + 1}") + ax.set_xlabel("Shared X", rotation=0, labelpad=4.0) + ax.legend(loc="upper right") + fig.supylabel("Shared Y", rotation=0, ha="left") + return axes[0] + ax = fig.subplots() + x = np.arange(6) + line_like = (family.startswith("line") or family in {"log_scale", "datetime_axis"} + or tid in {"H05", "H07", "H08", "H09", "H10"}) + if line_like: + _line(ax, seed, multi=3 if tid == "D02" else 1, + log=family == "log_scale" or tid == "D11", + dates=family == "datetime_axis" or tid == "D12", dense=tid == "H07", + twin=tid == "H05", scientific=tid == "H09") + if tid == "H10": + ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.18), frameon=True) + _labels(ax, right=tid == "H05") + if tid == "H05": + ax.set_ylabel("Left value", rotation=0, labelpad=4.0, ha="right") + elif family in {"bar_vertical", "bar_grouped", "bar_stacked"} or tid == "H12": + values = (np.array([-9000, -5000, 0, 5000, 9000, 2000], dtype=float) + seed / 10 + if tid == "H12" else np.array([3, 6, 4, 8, 5, 7]) + seed / 10) + if tid == "D04": + ax.bar(x - 0.2, values, width=0.4, label="Group A") + ax.bar(x + 0.2, values - 1, width=0.4, label="Group B") + ax.legend() + elif tid == "H02": + bottom = np.zeros(6) + for index in range(3): + heights = values / (index + 2) + ax.bar(x, heights, bottom=bottom, label=f"Stack {index + 1}") + bottom += heights + ax.legend() + else: + bars = ax.bar(x, values) + ax.bar_label(bars, padding=2) + _labels(ax) + elif family == "bar_horizontal": + values = np.array([8, 6, 10, 7, 9, 5]) + seed / 10 + bars = ax.barh(np.arange(6), values) + ax.set_yticks(np.arange(6), ["Long category A", "Long category B", "Category C", + "Category D", "Category E", "Category F"], rotation=0) + ax.bar_label(bars, padding=2) + _labels(ax, xlabel="Value", ylabel="Category") + elif family == "scatter": + ax.scatter(x, values := np.array([3, 6, 4, 8, 5, 7]) + seed / 10, + label="Points") + for index in range(3): + ax.annotate(f"P{index}", (x[index], values[index]), xytext=(5, 5), + textcoords="offset points") + ax.grid(True) + ax.legend() + _labels(ax) + elif family == "histogram": + ax.hist(np.sin(np.linspace(0, 20, 200)) * 3 + seed, bins=12) + _labels(ax, ylabel="Count") + elif family in {"box", "boxplot", "violin"} or family.startswith("violin"): + data = [np.sin(np.linspace(0, 5, 40)) * (index + 1) + seed for index in range(4)] + if family.startswith("box"): + ax.boxplot(data, tick_labels=["A", "B", "C", "D"]) + else: + ax.violinplot(data, showmedians=True) + ax.set_xticks([1, 2, 3, 4], ["A", "B", "C", "D"]) + _labels(ax) + elif family in {"heatmap", "contour"}: + grid = np.sin(np.linspace(0, 3, 30))[:, None] + np.cos(np.linspace(0, 3, 30))[None, :] + if family == "heatmap": + image = ax.imshow(grid, origin="lower", aspect="auto") + else: + image = ax.contourf(grid, levels=12) + colorbar = fig.colorbar(image, ax=ax, orientation="horizontal", pad=0.2) + colorbar.ax.set_xlabel("Color value", rotation=0, labelpad=4.0) + _labels(ax) + elif family == "pie": + ax.pie([4, 6, 3, 5], labels=["A", "B", "C", "D"], autopct="%1.0f%%") + elif family == "errorbar": + ax.errorbar(x, np.array([3, 6, 4, 8, 5, 7]) + seed / 10, + yerr=np.linspace(0.2, 0.6, 6), capsize=4, label="Mean") + ax.legend() + _labels(ax) + elif family in {"area", "area_stacked"}: + x_area = np.linspace(0, 8, 30) + first = 1 + np.sin(x_area) + second = 1 + np.cos(x_area) + ax.stackplot(x_area, first, second, labels=["Area A", "Area B"]) + ax.legend() + _labels(ax) + else: + raise HoldoutError("TEMPLATE_UNSUPPORTED", f"no generator for template {tid}") + if tid == "H12": + ax.set_ylim(-10000, 10000) + ax.set_yticks([-10000, -5000, 0, 5000, 10000]) + ax.yaxis.set_major_formatter(FuncFormatter("{:,}".format)) + ax.tick_params(axis="y", rotation=0) + return ax + + +def _counter_figure(fig: Any, counter: dict[str, Any]) -> tuple[Any, Any, dict[str, Any]]: + import numpy as np + from matplotlib.patches import Rectangle + + cid = counter["id"] + ax = fig.subplots() + target = None + related = None + injection: dict[str, Any] = {"kind": "legal_counterexample", "counterexample_id": cid} + if cid in {"L02", "L08"}: + ax.plot(np.linspace(0, 1, 50), np.sin(np.linspace(0, 8, 50)), label="Data") + ax.legend(loc="center", frameon=cid == "L02") + target = ax.text(0.02, 0.02, "Corner note", transform=ax.transAxes) + elif cid == "L07": + ax.imshow(np.arange(16).reshape(4, 4), origin="lower") + target = ax.text(1.5, 1.5, "White label", color="white", ha="center") + elif cid == "L09": + image = ax.imshow(np.arange(16).reshape(4, 4), origin="lower") + colorbar = fig.colorbar(image, ax=ax, orientation="horizontal", pad=0.25) + colorbar.ax.set_xlabel("Value", rotation=0, labelpad=4.0) + target = colorbar.ax.xaxis.label + elif cid == "L11": + target = fig.text(1.02, 0.5, "Tight page keeps this annotation", + ha="left", va="center", clip_on=False) + return target, None, injection + else: + _labels(ax) + if cid == "L01": + target = ax.text(0.5, 0.5, "White background", ha="center", + bbox={"facecolor": "white", "edgecolor": "none", "pad": 3}) + elif cid == "L03": + target = ax.text(0.30, 0.50, "I I", ha="left") + related = ax.text(0.325, 0.50, "I I", ha="left") + elif cid == "L04": + target = ax.text(0.5, 0.5, "Rotated legal text", rotation=45, ha="center") + elif cid == "L05": + target = fig.text(0.995, 0.5, "Near edge", ha="right", va="center", clip_on=False) + elif cid == "L06": + target = ax.text(0.5, 0.5, "Semi-transparent cover", ha="center", va="center") + fig.canvas.draw() + box = target.get_window_extent(fig.canvas.get_renderer()).expanded(1.1, 1.3) + related = Rectangle((box.x0 / fig.bbox.width, box.y0 / fig.bbox.height), + box.width / fig.bbox.width, box.height / fig.bbox.height, + transform=fig.transFigure, facecolor="black", + alpha=0.5, edgecolor="none", zorder=100) + fig.add_artist(related) + elif cid == "L10": + target = ax.text(-0.08, 0.5, "Outside axes, inside page", + transform=ax.transAxes, clip_on=False, ha="left") + elif cid == "L12": + target = ax.text(0.5, 0.5, "Line one\nLine two\nLine three", + ha="center", va="center", linespacing=1.4) + else: + raise HoldoutError("COUNTEREXAMPLE_UNSUPPORTED", f"no generator for {cid}") + return target, related, injection + + +def build_sample(sample: dict[str, Any], manifest: dict[str, Any]) -> BuiltSample: + """Build one live figure solely from a frozen sample record.""" + import matplotlib as mpl + from matplotlib.backends.backend_agg import FigureCanvasAgg + from matplotlib.figure import Figure + from matplotlib.font_manager import fontManager + from matplotlib.patches import Rectangle + + if not FONT_PATH.is_file(): + raise HoldoutError("FONT_UNAVAILABLE", f"required CJK fixture font is missing: {FONT_PATH}") + fontManager.addfont(str(FONT_PATH)) + template = _template(manifest, sample) + counter = _counter(manifest, sample) + save_kwargs = {"bbox_inches": None, "pad_inches": 0.1, "transparent": False} + if counter.get("save_override"): + save_kwargs = {"bbox_inches": counter["save_override"]["bbox_inches"], + "pad_inches": 0.1, "transparent": False} + with mpl.rc_context({ + "backend": "Agg", + "figure.dpi": 100, + "figure.figsize": [10.0, 6.0], + "font.size": 10.0, + "font.family": "DejaVu Sans", + "axes.unicode_minus": False, + "pdf.fonttype": 42, + "savefig.transparent": False, + "savefig.pad_inches": 0.1, + }): + fig = Figure(figsize=(10, 6), dpi=100, layout="constrained") + FigureCanvasAgg(fig) + if counter: + target, related, injection = _counter_figure(fig, counter) + else: + ax = _chart(fig, template, int(sample["seed"])) + tid = template["id"] + variant = sample["variant"] + title = f"{tid} benchmark title" + if variant == "clip": + title = f"{tid} clipped target title" + elif variant == "occlude": + title = f"{tid} occluded target title" + elif variant == "overlap": + title = f"{tid} overlapping target" + elif variant == "missing_glyph": + title = f"{tid} Trend \U00020000 chart" + cjk = tid in {"H08", "H12"} + target = (fig.suptitle(title, fontproperties=_font_properties(cjk), fontsize=14) + if tid == "H11" else + ax.set_title(title, fontproperties=_font_properties(cjk), fontsize=14, + pad=8)) + if cjk: + if tid == "H08": + ax.set_xlabel("时间 Time", fontproperties=_font_properties(True), + rotation=0, labelpad=4.0) + else: + ax.set_ylabel("数值 Units", fontproperties=_font_properties(True), + rotation=0, labelpad=4.0, ha="right") + related = None + injection = {"kind": variant, "defect_class": sample.get("defect_class"), + "target_role": sample.get("target_role")} + if variant == "clip": + if tid == "H11": + target.set_ha("right") + target.set_x(1.08) + else: + target.set_ha("right") + target.set_position((1.25, 1.0)) + target.set_clip_on(False) + elif variant in {"occlude", "overlap"}: + fig.canvas.draw() + box = target.get_window_extent(fig.canvas.get_renderer()) + if variant == "occlude": + related = Rectangle( + ((box.x0 - 1) / fig.bbox.width, (box.y0 - 1) / fig.bbox.height), + (box.width + 2) / fig.bbox.width, (box.height + 2) / fig.bbox.height, + transform=fig.transFigure, facecolor="black", edgecolor="none", zorder=100) + fig.add_artist(related) + else: + related = fig.text(box.x0 / fig.bbox.width, box.y0 / fig.bbox.height, + f"{tid} target overlap", ha="left", va="bottom", + fontsize=14, transform=fig.transFigure, zorder=100) + return BuiltSample(fig, target, related, save_kwargs, injection) + + +def close_built(built: BuiltSample) -> None: + built.figure.clear() + + +def _jsonable(value: Any) -> Any: + if hasattr(value, "__dataclass_fields__"): + return {key: _jsonable(item) for key, item in asdict(value).items()} + if isinstance(value, dict): + return {key: _jsonable(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_jsonable(item) for item in value] + if isinstance(value, Path): + return value.as_posix() + return value + + +def _coverage(box: Any, target: Any) -> float: + x0, y0 = max(box.x0, target.x0), max(box.y0, target.y0) + x1, y1 = min(box.x1, target.x1), min(box.y1, target.y1) + intersection = max(0.0, x1 - x0) * max(0.0, y1 - y0) + return intersection / target.area if target.area > 0 else 0.0 + + +def _validate_injection(built: BuiltSample, captured: Any) -> None: + """Reject unreachable source-geometry mutations before writing the seal.""" + sources = captured.sources + artists = captured.source_artists + target_id = next((source.source_object_id for artist, source in zip(artists, sources, strict=False) + if artist is built.target), None) + if target_id is None: + raise HoldoutError("INJECTION_UNREACHABLE", "target artist is absent from capture inventory") + related_id = None + if built.related is not None: + related_id = next((source.source_object_id for artist, source in zip(artists, sources, strict=False) + if artist is built.related), None) + built.injection.update({"target_source_object_id": target_id, + "related_source_object_id": related_id, + "operand_status": "source_geometry_validated"}) + events = {event.source_object_id: event for event in captured.events + if event.source_object_id is not None} + target_event = events.get(target_id) + if target_event is None or target_event.bbox_pdf is None: + raise HoldoutError("INJECTION_UNREACHABLE", "target has no captured PDF geometry") + built.injection["target_bbox_pdf_points"] = list(target_event.bbox_pdf.as_tuple()) + kind = built.injection.get("kind") + if kind == "clip": + box = target_event.bbox_pdf + outside = max(0.0, -box.x0) + max(0.0, box.x1 - 720.0) + if outside <= 0: + raise HoldoutError("INJECTION_UNREACHABLE", "clip target does not cross the page boundary") + elif kind == "occlude": + related_event = events.get(related_id) + if related_event is None or related_event.bbox_pdf is None: + raise HoldoutError("INJECTION_UNREACHABLE", "occluder has no captured PDF geometry") + coverage = _coverage(related_event.bbox_pdf, target_event.bbox_pdf) + built.injection["source_bbox_coverage"] = coverage + if related_event.sequence <= target_event.sequence or coverage < 0.90: + raise HoldoutError("INJECTION_UNREACHABLE", + "occluder must be later and cover at least 90% of the target") + elif kind == "overlap": + related_event = events.get(related_id) + if related_event is None or related_event.bbox_pdf is None: + raise HoldoutError("INJECTION_UNREACHABLE", "overlap partner has no captured PDF geometry") + a, b = target_event.bbox_pdf, related_event.bbox_pdf + intersection = max(0.0, min(a.x1, b.x1) - max(a.x0, b.x0)) * max( + 0.0, min(a.y1, b.y1) - max(a.y0, b.y0)) + ratio = intersection / min(a.area, b.area) if min(a.area, b.area) > 0 else 0.0 + built.injection["source_bbox_overlap_ratio"] = ratio + if ratio < 0.50: + raise HoldoutError("INJECTION_UNREACHABLE", + "overlap partner covers less than 50% of the smaller source bbox") + elif kind == "missing_glyph": + occurrences = sum((source.text or "").count("\U00020000") for source in sources) + warning = any("131072" in item.message for item in captured.warnings) + if occurrences != 1 or not warning: + raise HoldoutError("INJECTION_UNREACHABLE", + "U+20000 must occur once and emit a save-scoped warning") + + +def generate_one(sample: dict[str, Any], manifest: dict[str, Any], + output_dir: Path) -> dict[str, Any]: + """Capture one deterministic input and return its seal entry and label.""" + from plotproof.capture import CaptureError, capture_pdf + + built = build_sample(sample, manifest) + try: + try: + captured = capture_pdf(built.figure, **built.save_kwargs) + except CaptureError as error: + raise HoldoutError("CAPTURE_FAILED", f"sample {sample['id']}: {error}") from None + _validate_injection(built, captured) + sample_id = str(sample["id"]) + samples_dir = output_dir / "samples" + samples_dir.mkdir(parents=True, exist_ok=True) + pdf_path = samples_dir / f"{sample_id}.pdf" + source_path = samples_dir / f"{sample_id}.source.json" + pdf_path.write_bytes(captured.pdf_bytes) + source_document = { + "schema_version": 1, + "sample_id": sample_id, + "capture_revision": captured.capture_revision, + "input_sha256": captured.input_sha256, + "original_dpi": captured.original_dpi, + "bbox_inches": captured.bbox_inches, + "pad_inches": captured.pad_inches, + "transparent": captured.transparent, + "origin_display": captured.origin_display, + "save_tight_bbox_inches": captured.save_tight_bbox_inches, + "sources": _jsonable(captured.sources), + "events": _jsonable(captured.events), + "warnings": _jsonable(captured.warnings), + "capture_issues": list(captured.capture_issues), + "injection": built.injection, + "label_review_status": "machine_generated_unreviewed", + } + source_path.write_bytes(canonical_json(source_document)) + target_id = built.injection["target_source_object_id"] + target_event = next(event for event in captured.events + if event.source_object_id == target_id) + label = { + "sample_id": sample_id, + "expected_state": sample["expected_state"], + "defect_class": sample.get("defect_class"), + "source_object_id": target_id if sample["expected_state"] == "FAIL" else None, + "related_source_object_id": (built.injection["related_source_object_id"] + if sample["expected_state"] == "FAIL" else None), + "source_bbox_pdf_points": (list(target_event.bbox_pdf.as_tuple()) + if sample["expected_state"] == "FAIL" else None), + } + return { + "id": sample_id, + "pdf": f"samples/{sample_id}.pdf", + "sha256": sha256_file(pdf_path), + "size": pdf_path.stat().st_size, + "source": f"samples/{sample_id}.source.json", + "source_sha256": sha256_file(source_path), + "label": label, + } + finally: + close_built(built) + + +def generate_all(output_dir: Path) -> dict[str, Any]: + """Generate all inputs and unreviewed labels, but never create a seal.""" + validate_environment(pinned_environment()) + manifest = load_manifest() + records = [item for item in expand_samples(manifest) if item.get("split") == "holdout"] + records.sort(key=lambda item: item["id"]) + if [item["id"] for item in records] != holdout_sample_ids(manifest): + raise HoldoutError("HOLDOUT_PLAN_INVALID", "generator plan differs from frozen holdout IDs") + # Fail before writing anything: a half-generated fixture set must never exist. + for sample in records: + close_built(build_sample(sample, manifest)) + if output_dir.exists() and any(output_dir.iterdir()): + raise HoldoutError("OUTPUT_NOT_EMPTY", + "holdout output directory already exists and is not empty") + output_dir.mkdir(parents=True, exist_ok=True) + seal_samples = [] + labels = [] + for index, sample in enumerate(records, 1): + generated = generate_one(sample, manifest, output_dir) + seal_samples.append({key: value for key, value in generated.items() if key != "label"}) + labels.append(generated["label"]) + print(f"generated {index}/{len(records)} {sample['id']}", flush=True) + labels_path = output_dir / "labels.json" + write_json(labels_path, labels) + review_log = output_dir / "label_review_log.json" + write_json(review_log, []) + code = code_fingerprint() + revision = subprocess.run(["git", "rev-parse", "HEAD"], cwd=ROOT, check=True, + capture_output=True, text=True).stdout.strip() + generation = { + "schema_version": 1, + "generated_at_utc": datetime.now().astimezone().isoformat(), + "revision": revision, + "manifest_sha256": code[MANIFEST_KEY], + "labels_sha256": sha256_file(labels_path), + "label_review_log_sha256": sha256_file(review_log), + "label_review_status": "machine_generated_unreviewed", + "protocol_limitations": [ + "No independent custodian or human PDF label-review session is claimed.", + "Synthetic templates measure cross-template generalization, not real-world accuracy.", + ], + "generator_sha256": code["benchmark/generate_holdout.py"], + "evaluator_sha256": code["benchmark/run_holdout.py"], + "code_sha256": code, + "environment": pinned_environment(), + "samples": seal_samples, + } + write_json(output_dir / "generation.json", generation) + return generation + + +def seal_existing(holdout_dir: Path, review_log_path: Path, reviewed_by: str) -> dict[str, Any]: + """Seal generated evidence only after an explicit human-review attestation.""" + reviewer = reviewed_by.strip() + if not reviewer: + raise HoldoutError("LABEL_REVIEW_REQUIRED", "a non-empty human reviewer is required") + generation_path = holdout_dir / "generation.json" + if not generation_path.is_file(): + raise HoldoutError("GENERATION_MISSING", "generation.json is missing; run --generate-only first") + if (holdout_dir / "seal.json").exists(): + raise HoldoutError("SEAL_EXISTS", "holdout seal already exists; use a new output directory") + generation = json.loads(generation_path.read_text(encoding="utf-8")) + if generation.get("label_review_status") != "machine_generated_unreviewed": + raise HoldoutError("GENERATION_INVALID", "generation.json is not an unreviewed generation record") + if not review_log_path.is_file(): + raise HoldoutError("LABEL_REVIEW_MISSING", "label review log is missing") + review_log = json.loads(review_log_path.read_text(encoding="utf-8")) + manifest = load_manifest() + validate_review_log(review_log, set(holdout_sample_ids(manifest))) + code = code_fingerprint() + environment = pinned_environment() + if generation.get("code_sha256") != code: + raise HoldoutError("CODE_CHANGED", "detector/evaluator source bytes changed after generation") + if generation.get("environment") != environment: + raise HoldoutError("ENVIRONMENT_NOT_PINNED", "runtime changed after generation") + labels_path = holdout_dir / "labels.json" + if generation.get("labels_sha256") != sha256_file(labels_path): + raise HoldoutError("LABELS_CHANGED", "labels changed after generation") + canonical_review = holdout_dir / "label_review_log.json" + if review_log_path.resolve() != canonical_review.resolve(): + canonical_review.write_bytes(canonical_json(review_log)) + seal = dict(generation) + seal.update({ + "sealed_at_utc": datetime.now(UTC).isoformat(), + "label_review_status": "human_reviewed", + "reviewed_by": reviewer, + "label_review_log_sha256": sha256_file(canonical_review), + }) + validate_seal(seal, holdout_dir, manifest, code, environment) + write_json(holdout_dir / "seal.json", seal) + return seal + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", type=Path, + default=Path(__file__).resolve().parent / "holdout") + mode = parser.add_mutually_exclusive_group(required=True) + mode.add_argument("--generate-only", action="store_true", + help="generate PDFs, source evidence and unreviewed labels; do not seal") + mode.add_argument("--seal-reviewed", action="store_true", + help="seal existing generation after the logged human PDF review") + parser.add_argument("--reviewed-by", help="non-empty human label reviewer identity") + args = parser.parse_args() + try: + if args.seal_reviewed: + if not args.reviewed_by: + raise HoldoutError("LABEL_REVIEW_REQUIRED", "--seal-reviewed requires --reviewed-by") + seal = seal_existing(args.output_dir, args.output_dir / "label_review_log.json", + args.reviewed_by) + print(f"HOLDOUT SEALED: {len(seal['samples'])} samples") + else: + if (args.output_dir / "seal.json").exists(): + raise HoldoutError("SEAL_EXISTS", + "holdout seal already exists; use a new output directory") + generation = generate_all(args.output_dir) + print(f"HOLDOUT GENERATED (UNREVIEWED): {len(generation['samples'])} samples") + return 0 + except (HoldoutError, OSError, ValueError) as error: + if isinstance(error, HoldoutError): + return emit_error(error) + return emit_error(HoldoutError("GENERATION_FAILED", str(error))) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/benchmark/holdout.py b/benchmark/holdout.py new file mode 100644 index 0000000..d9b13af --- /dev/null +++ b/benchmark/holdout.py @@ -0,0 +1,553 @@ +"""Shared validation, sealing and metrics for the PlotProof holdout. + +This module is deliberately stdlib-only at import time. The pinned scientific +stack is imported only when recording or validating an execution environment. +""" + +from __future__ import annotations + +import json +import math +import sys +from datetime import UTC, datetime +from hashlib import sha256 +from pathlib import Path +from typing import Any + +ROOT = Path(__file__).resolve().parents[1] +CLASSES = ("clipped_text", "occluded_text", "overlapping_text", "missing_glyph") + +# The sealed pipeline reads the v3 preregistration. benchmark/manifest.json is the +# superseded v2 freeze: it is retained byte-for-byte as the record of the burned +# holdout and is never used to generate, seal or execute a fixture again. +MANIFEST_PATH = ROOT / "benchmark" / "manifest-v3.json" + +# A seal can only be confirmatory when a human reviewed every PDF label. The +# machine tier exists so the pipeline can be smoke-tested without pretending a +# review happened; anything sealed that way is non-confirmatory by construction. +SEAL_STATUS_HUMAN = "human_reviewed" +SEAL_STATUS_MACHINE = "machine_sealed_unreviewed" +SEAL_STATUSES = (SEAL_STATUS_HUMAN, SEAL_STATUS_MACHINE) +CONFIRMATORY_SEAL_STATUSES = (SEAL_STATUS_HUMAN,) + +BURN_MARKER = "BURNED" +BURN_STATUS_PRE_SEAL = "BURNED_FOR_CONFIRMATORY_USE" +BURN_STATUS_CONSUMED = "BURNED_BY_SINGLE_PIPELINE_RUN" + +FONT_PATH = ROOT / ".fonts" / "NotoSansCJKsc-Regular.otf" +FONT_SHA256 = "2c76254f6fc379fddfce0a7e84fb5385bb135d3e399294f6eeb6680d0365b74b" +EXPECTED_ENVIRONMENT = { + "python": "3.12.3", + "matplotlib": "3.10.8", + "pypdfium2": "5.8.0", + "pdfium": "149.0.7825.0", + "numpy": "2.4.6", + "fonttools": "4.61.1", + "pillow": "12.2.0", + "cjk_font_sha256": FONT_SHA256, +} +CODE_FILES = ( + "benchmark/manifest-v3.json", + "benchmark/holdout.py", + "benchmark/generate_holdout.py", + "benchmark/run_holdout.py", +) +MANIFEST_KEY = MANIFEST_PATH.relative_to(ROOT).as_posix() +VARIANT_CLASSES = { + "clip": "clipped_text", + "occlude": "occluded_text", + "overlap": "overlapping_text", + "missing_glyph": "missing_glyph", +} + + +class HoldoutError(ValueError): + """A sealed-holdout precondition failed.""" + + def __init__(self, code: str, message: str): + self.code = code + self.message = message + super().__init__(message) + + +def emit_error(error: HoldoutError) -> int: + print(json.dumps({"status": "ERROR", "error": { + "code": error.code, "message": error.message, + }}, indent=2)) + return 2 + + +def require_windows(platform_name: str | None = None) -> None: + if (platform_name or sys.platform) != "win32": + raise HoldoutError("PLATFORM_NOT_PINNED", + "The sealed holdout must run on Windows (win32).") + + +def sha256_file(path: Path) -> str: + digest = sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def canonical_json(value: Any) -> bytes: + return (json.dumps(value, ensure_ascii=False, sort_keys=True, + separators=(",", ":"), allow_nan=False) + "\n").encode("utf-8") + + +def write_json(path: Path, value: Any) -> None: + path.write_bytes(canonical_json(value)) + + +def pinned_environment() -> dict[str, str]: + """Record the complete runtime identity used by generation and execution.""" + import platform + + import fontTools + import matplotlib + import numpy + import PIL + import pypdfium2 + + return { + "python": platform.python_version(), + "matplotlib": matplotlib.__version__, + "pypdfium2": str(pypdfium2.PYPDFIUM_INFO), + "pdfium": str(pypdfium2.PDFIUM_INFO), + "numpy": numpy.__version__, + "fonttools": fontTools.__version__, + "pillow": PIL.__version__, + "cjk_font_sha256": sha256_file(FONT_PATH) if FONT_PATH.is_file() else "missing", + } + + +def validate_environment(environment: dict[str, str], *, + platform_name: str | None = None) -> None: + require_windows(platform_name) + if environment != EXPECTED_ENVIRONMENT: + differences = { + key: {"expected": EXPECTED_ENVIRONMENT.get(key), "actual": environment.get(key)} + for key in sorted(set(EXPECTED_ENVIRONMENT) | set(environment)) + if environment.get(key) != EXPECTED_ENVIRONMENT.get(key) + } + raise HoldoutError("ENVIRONMENT_NOT_PINNED", + "holdout environment is not the frozen Windows runtime: " + + json.dumps(differences, sort_keys=True)) + + +def code_fingerprint() -> dict[str, str]: + """Hash detector, generator, evaluator and manifest source bytes.""" + paths = [ROOT / relative for relative in CODE_FILES] + paths.extend(sorted((ROOT / "plotproof").glob("*.py"))) + return {path.relative_to(ROOT).as_posix(): sha256_file(path) for path in paths} + + +def expand_samples(manifest: dict[str, Any]) -> list[dict[str, Any]]: + """Return sample records, expanding a preregistration declaration if needed. + + A v2-style manifest lists every sample explicitly. A v3-style preregistration + declares templates, variants and seeds and materializes the same records here, + so the declared fixture list stays the single source of truth. + """ + if isinstance(manifest.get("samples"), list): + return list(manifest["samples"]) + seeds = manifest["seeds"] + records: list[dict[str, Any]] = [] + for template in manifest["templates"]: + for variant in manifest["variants"]: + for seed in seeds["clean"] if variant == "clean" else seeds["defect"]: + records.append({ + "id": f"{template['id']}.{variant}.s{seed}", + "template_id": template["id"], + "family": template["family"], + "split": template["split"], + "variant": variant, + "seed": seed, + "target_role": template["target_role"], + "defect_class": None if variant == "clean" else VARIANT_CLASSES[variant], + "expected_state": "PASS" if variant == "clean" else "FAIL", + }) + for counter in manifest["counterexamples"]: + records.append({ + "id": f"{counter['id']}.counterexample", + "counterexample_id": counter["id"], + "family": counter["family"], + "split": counter["split"], + "variant": "counterexample", + "seed": None, + "target_role": None, + "defect_class": None, + "expected_state": counter["expected_state"], + }) + return records + + +def holdout_sample_ids(manifest: dict[str, Any]) -> list[str]: + sample_ids = sorted(str(item["id"]) for item in expand_samples(manifest) + if item.get("split") == "holdout") + if len(sample_ids) != 114 or len(set(sample_ids)) != 114: + raise HoldoutError("HOLDOUT_PLAN_INVALID", + "frozen manifest must contain exactly 114 unique holdout samples") + return sample_ids + + +def wilson_interval(successes: int, total: int) -> tuple[float, float] | None: + if total == 0: + return None + if not 0 <= successes <= total: + raise ValueError("successes must be between zero and total") + z = 1.96 + proportion = successes / total + denominator = 1 + z * z / total + center = (proportion + z * z / (2 * total)) / denominator + margin = z * math.sqrt(proportion * (1 - proportion) / total + + z * z / (4 * total * total)) / denominator + return max(0.0, center - margin), min(1.0, center + margin) + + +def _proportion(numerator: int, denominator: int) -> dict[str, Any]: + interval = wilson_interval(numerator, denominator) + return { + "numerator": numerator, + "denominator": denominator, + "estimate": None if denominator == 0 else numerator / denominator, + "wilson_95": None if interval is None else list(interval), + } + + +def _iou(a: Any, b: Any) -> float: + if not isinstance(a, (list, tuple)) or not isinstance(b, (list, tuple)): + return 0.0 + if len(a) != 4 or len(b) != 4: + return 0.0 + x0, y0 = max(float(a[0]), float(b[0])), max(float(a[1]), float(b[1])) + x1, y1 = min(float(a[2]), float(b[2])), min(float(a[3]), float(b[3])) + intersection = max(0.0, x1 - x0) * max(0.0, y1 - y0) + area_a = max(0.0, float(a[2]) - float(a[0])) * max(0.0, float(a[3]) - float(a[1])) + area_b = max(0.0, float(b[2]) - float(b[0])) * max(0.0, float(b[3]) - float(b[1])) + union = area_a + area_b - intersection + return intersection / union if union > 0 else 0.0 + + +def _finding_key(finding: dict[str, Any]) -> tuple[Any, ...]: + related = finding.get("related_source_object_id") + source = finding.get("source_object_id") + if finding.get("defect_class") == "overlapping_text" and source is not None and related is not None: + source, related = sorted((source, related)) + box = finding.get("box_pdf_points") + rounded = tuple(round(float(value), 1) for value in box) if isinstance(box, (list, tuple)) else None + return (finding.get("sample_id"), finding.get("defect_class"), source, related, + finding.get("rule_id"), rounded) + + +def summarize_outcomes(labels: list[dict[str, Any]], + outcomes: list[dict[str, Any]]) -> dict[str, Any]: + """Compute preregistered pooled and per-class metrics from raw outcomes.""" + references = [item for item in labels if item.get("expected_state") == "FAIL"] + by_sample: dict[str, list[dict[str, Any]]] = {} + for reference in references: + by_sample.setdefault(str(reference["sample_id"]), []).append(reference) + matched_references: set[tuple[Any, ...]] = set() + predicted_counts = {name: 0 for name in CLASSES} + true_positive_counts = {name: 0 for name in CLASSES} + false_positive_counts = {name: 0 for name in CLASSES} + seen_findings: set[tuple[Any, ...]] = set() + false_pass_counts = {name: 0 for name in CLASSES} + reference_counts = {name: 0 for name in CLASSES} + decidable_reference_counts = {name: 0 for name in CLASSES} + decidable_tp_counts = {name: 0 for name in CLASSES} + for reference in references: + name = reference.get("defect_class") + if name in reference_counts: + reference_counts[name] += 1 + + outcome_by_id = {str(item["sample_id"]): item for item in outcomes} + if len(outcome_by_id) != len(outcomes) or set(outcome_by_id) != {str(x["sample_id"]) for x in labels}: + raise HoldoutError("OUTCOMES_INVALID", + "raw outcomes must contain each sealed sample exactly once") + + for label in labels: + sample_id = str(label["sample_id"]) + outcome = outcome_by_id[sample_id] + state = outcome.get("state") + if state not in {"PASS", "FAIL", "UNKNOWN", "ERROR"}: + raise HoldoutError("OUTCOMES_INVALID", f"sample {sample_id}: invalid state {state!r}") + name = label.get("defect_class") + if label.get("expected_state") == "FAIL": + if state == "PASS" and name in false_pass_counts: + false_pass_counts[name] += 1 + if state in {"PASS", "FAIL"} and name in decidable_reference_counts: + decidable_reference_counts[name] += 1 + for finding in outcome.get("findings", []): + if finding.get("confidence") != "high": + continue + key = _finding_key({**finding, "sample_id": sample_id}) + if key in seen_findings: + continue + seen_findings.add(key) + predicted = finding.get("defect_class") + if predicted not in predicted_counts: + continue + predicted_counts[predicted] += 1 + candidates = [reference for reference in by_sample.get(sample_id, []) + if reference.get("defect_class") == predicted + and (str(reference["sample_id"]), predicted, + reference.get("source_object_id"), + reference.get("related_source_object_id")) not in matched_references] + source = finding.get("source_object_id") + related = finding.get("related_source_object_id") + match = None + for reference in candidates: + ref_source = reference.get("source_object_id") + ref_related = reference.get("related_source_object_id") + if predicted == "overlapping_text": + if source is not None and related is not None and ref_source is not None and ref_related is not None: + if sorted((source, related)) == sorted((ref_source, ref_related)): + match = reference + break + elif related is None and ref_related is None: + if source is not None and source == ref_source: + match = reference + break + if source is None and _iou(finding.get("box_pdf_points"), + reference.get("source_bbox_pdf_points")) >= 0.50: + match = reference + break + if match is None: + false_positive_counts[predicted] += 1 + else: + true_positive_counts[predicted] += 1 + matched_references.add((str(match["sample_id"]), predicted, + match.get("source_object_id"), + match.get("related_source_object_id"))) + if state in {"PASS", "FAIL"}: + decidable_tp_counts[predicted] += 1 + + def class_row(name: str) -> dict[str, Any]: + tp = true_positive_counts[name] + return { + "precision": _proportion(tp, predicted_counts[name]), + "recall": _proportion(tp, reference_counts[name]), + "conditional_recall": _proportion(decidable_tp_counts[name], + decidable_reference_counts[name]), + "false_pass_rate": _proportion(false_pass_counts[name], reference_counts[name]), + "true_positives": tp, + "false_positives": false_positive_counts[name], + "references": reference_counts[name], + "false_passes": false_pass_counts[name], + } + + states = [item.get("state") for item in outcomes] + total = len(outcomes) + expected_defects = len(references) + expected_clean = [item for item in labels if item.get("expected_state") != "FAIL"] + clean_fail = sum(outcome_by_id[str(item["sample_id"])].get("state") == "FAIL" + for item in expected_clean) + clean_pass = sum(outcome_by_id[str(item["sample_id"])].get("state") == "PASS" + for item in expected_clean) + coverage_values = [] + zero_unit_samples = 0 + for item in outcomes: + report = item.get("report") or {} + total_units = report.get("source_units_total") + ratio = (report.get("coverage") or {}).get("ratio") + if total_units == 0: + zero_unit_samples += 1 + if isinstance(total_units, int) and total_units > 0 and isinstance(ratio, (int, float)): + coverage_values.append(float(ratio)) + alignment_coverage = { + "numerator": sum(coverage_values), + "denominator": len(coverage_values), + "estimate": (sum(coverage_values) / len(coverage_values) + if coverage_values else None), + "wilson_95": None, + "aggregation": "macro_mean_per_sample", + } + total_tp = sum(true_positive_counts.values()) + return { + "pooled": { + "precision": _proportion(total_tp, sum(predicted_counts.values())), + "recall": _proportion(total_tp, expected_defects), + "conditional_recall": _proportion(sum(decidable_tp_counts.values()), + sum(decidable_reference_counts.values())), + "false_pass_rate": _proportion(sum(false_pass_counts.values()), expected_defects), + "unknown_rate": _proportion(states.count("UNKNOWN"), total), + "error_rate": _proportion(states.count("ERROR"), total), + "clean_or_legal_pass_rate": _proportion(clean_pass, len(expected_clean)), + "clean_or_legal_pass_count": clean_pass, + "clean_or_legal_fail_count": clean_fail, + "alignment_coverage": alignment_coverage, + "zero_unit_samples": zero_unit_samples, + "state_counts": {state: states.count(state) + for state in ("PASS", "FAIL", "UNKNOWN", "ERROR")}, + }, + "per_class": {name: class_row(name) for name in CLASSES}, + } + + +def _safe_artifact(root: Path, relative: Any) -> Path: + if not isinstance(relative, str) or not relative: + raise HoldoutError("SEAL_INVALID", "artifact path must be a non-empty string") + path = Path(relative) + if path.is_absolute() or ".." in path.parts: + raise HoldoutError("SEAL_INVALID", f"unsafe artifact path: {relative!r}") + target = (root / path).resolve() + try: + target.relative_to(root.resolve()) + except ValueError: + raise HoldoutError("SEAL_INVALID", f"artifact escapes holdout directory: {relative!r}") from None + return target + + +def load_manifest(path: Path | None = None) -> dict[str, Any]: + """Read the frozen v3 preregistration (or an explicit path).""" + target = Path(path) if path is not None else MANIFEST_PATH + return json.loads(target.read_text(encoding="utf-8")) + + +def read_burn_marker(holdout_dir: Path) -> dict[str, str] | None: + """Return the parsed BURNED record, or None when no marker exists.""" + path = holdout_dir / BURN_MARKER + if not path.is_file(): + return None + record: dict[str, str] = {} + for line in path.read_text(encoding="utf-8").splitlines(): + if "=" in line: + key, value = line.split("=", 1) + record[key.strip()] = value.strip() + return record + + +def write_burn_marker(holdout_dir: Path, *, status: str, cause: str, + consequence: str) -> dict[str, str]: + """Write the one-shot marker that makes every later run refuse this holdout.""" + record = { + "status": status, + "rule": "B0_PREREGISTRATION_SECTION_6.6", + "manifest": MANIFEST_PATH.relative_to(ROOT).as_posix(), + "manifest_sha256": sha256_file(MANIFEST_PATH), + "cause": " ".join(cause.split()), + "detected_at_utc": datetime.now(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"), + "consequence": " ".join(consequence.split()), + "threshold_tuning_after_detection": "none", + } + lines = [f"{key}={value}" for key, value in record.items()] + (holdout_dir / BURN_MARKER).write_text("\n".join(lines) + "\n", encoding="utf-8") + return record + + +def confirmatory_verdict(seal: dict[str, Any], gate_results: dict[str, Any], + burn: dict[str, str] | None) -> dict[str, Any]: + """Decide, fail-closed, whether a run may be described as a confirmatory result.""" + reasons: list[str] = [] + status = seal.get("label_review_status") + if status not in CONFIRMATORY_SEAL_STATUSES: + reasons.append( + f"seal label_review_status is {status!r}; no human PDF label review was recorded, " + "so labels are machine-generated and unverified") + if not seal.get("reviewed_by"): + reasons.append("no named human reviewer is bound in the seal") + unimplemented = gate_results.get("not_implemented") or [] + if unimplemented: + reasons.append("preregistered gates are not implemented: " + ", ".join(unimplemented)) + if gate_results.get("all_pass") is not True: + reasons.append("the aggregate gate verdict is not a pass") + if burn is not None: + reasons.append(f"the holdout is marked {burn.get('status', 'BURNED')}") + confirmatory = not reasons + return { + "confirmatory": confirmatory, + "result_label": "CONFIRMATORY" if confirmatory else "NONCONFIRMATORY", + "nonconfirmatory_reasons": reasons, + } + + +def validate_review_log(review_log: Any, expected_ids: set[str]) -> None: + """Validate correction metadata without accepting any label text.""" + if not isinstance(review_log, list): + raise HoldoutError("LABEL_REVIEW_INVALID", "label review log must contain an array") + required = {"sample_id", "old_label_sha256", "new_label_sha256", "reason_code", "at_utc"} + for entry in review_log: + if not isinstance(entry, dict) or set(entry) != required: + raise HoldoutError("LABEL_REVIEW_INVALID", + "label review log entries must contain correction metadata only") + if entry["sample_id"] not in expected_ids: + raise HoldoutError("LABEL_REVIEW_INVALID", "review log references an unknown sample") + for key in ("old_label_sha256", "new_label_sha256"): + value = entry[key] + if (not isinstance(value, str) or len(value) != 64 + or any(char not in "0123456789abcdef" for char in value)): + raise HoldoutError("LABEL_REVIEW_INVALID", f"review log {key} must be a SHA-256") + if not isinstance(entry["reason_code"], str) or not entry["reason_code"].strip(): + raise HoldoutError("LABEL_REVIEW_INVALID", "review log reason_code must be non-empty") + try: + timestamp = datetime.fromisoformat(entry["at_utc"].replace("Z", "+00:00")) + except (TypeError, ValueError): + raise HoldoutError("LABEL_REVIEW_INVALID", "review log at_utc must be an ISO timestamp") from None + if timestamp.tzinfo is None: + raise HoldoutError("LABEL_REVIEW_INVALID", "review log at_utc must include a timezone") + + +def validate_seal(seal: dict[str, Any], holdout_dir: Path, manifest: dict[str, Any], + code_hashes: dict[str, str], environment: dict[str, str], *, + platform_name: str | None = None) -> list[dict[str, Any]]: + """Verify every sealed identity before any detector code is invoked.""" + validate_environment(environment, platform_name=platform_name) + if type(seal.get("schema_version")) is not int or seal.get("schema_version") != 1: + raise HoldoutError("SEAL_INVALID", "seal schema_version must be 1") + if seal.get("label_review_status") != "human_reviewed": + raise HoldoutError("LABEL_REVIEW_REQUIRED", + "sealed holdout requires a logged human PDF label-review session") + manifest_keys = sorted(key for key in code_hashes + if key.startswith("benchmark/manifest") and key.endswith(".json")) + if len(manifest_keys) != 1: + raise HoldoutError("SEAL_INVALID", + "code fingerprint must bind exactly one frozen manifest") + if seal.get("manifest_sha256") != code_hashes[manifest_keys[0]]: + raise HoldoutError("CODE_CHANGED", "seal manifest hash disagrees with code fingerprint") + if seal.get("code_sha256") != code_hashes: + raise HoldoutError("CODE_CHANGED", "sealed detector/evaluator source bytes have changed") + if seal.get("environment") != environment: + raise HoldoutError("ENVIRONMENT_NOT_PINNED", "seal environment differs from this runtime") + + labels_path = holdout_dir / "labels.json" + if not labels_path.is_file(): + raise HoldoutError("LABELS_MISSING", "sealed labels.json is missing") + if seal.get("labels_sha256") != sha256_file(labels_path): + raise HoldoutError("LABELS_CHANGED", "sealed labels sha256 does not match labels.json") + review_log_path = holdout_dir / "label_review_log.json" + if not review_log_path.is_file(): + raise HoldoutError("LABEL_REVIEW_MISSING", "sealed label review log is missing") + if seal.get("label_review_log_sha256") != sha256_file(review_log_path): + raise HoldoutError("LABEL_REVIEW_CHANGED", + "sealed label review log sha256 does not match label_review_log.json") + review_log = json.loads(review_log_path.read_text(encoding="utf-8")) + labels = json.loads(labels_path.read_text(encoding="utf-8")) + if not isinstance(labels, list): + raise HoldoutError("LABELS_INVALID", "labels.json must contain an array") + label_ids = [str(item.get("sample_id")) for item in labels] + expected_ids = holdout_sample_ids(manifest) + validate_review_log(review_log, set(expected_ids)) + if len(label_ids) != len(set(label_ids)) or sorted(label_ids) != expected_ids: + raise HoldoutError("LABELS_INVALID", "labels sample IDs do not exactly match the seal plan") + + samples = seal.get("samples") + if not isinstance(samples, list): + raise HoldoutError("SEAL_INVALID", "seal samples must be an array") + sealed_ids = [str(item.get("id")) for item in samples] + if len(sealed_ids) != len(set(sealed_ids)) or sorted(sealed_ids) != expected_ids: + raise HoldoutError("SEAL_INVALID", "seal sample IDs do not exactly match the frozen holdout") + allowed_keys = {"id", "pdf", "sha256", "size", "source", "source_sha256"} + for item in samples: + if set(item) != allowed_keys: + raise HoldoutError("SEAL_INVALID", "seal sample records may not contain labels or extra keys") + pdf = _safe_artifact(holdout_dir, item["pdf"]) + source = _safe_artifact(holdout_dir, item["source"]) + if not pdf.is_file() or pdf.stat().st_size != item["size"]: + raise HoldoutError("SAMPLE_CHANGED", f"sample {item['id']}: PDF size mismatch") + if sha256_file(pdf) != item["sha256"]: + raise HoldoutError("SAMPLE_CHANGED", f"sample {item['id']}: PDF sha256 mismatch") + if not source.is_file() or sha256_file(source) != item["source_sha256"]: + raise HoldoutError("SAMPLE_CHANGED", f"sample {item['id']}: source sha256 mismatch") + return labels diff --git a/benchmark/holdout/BURNED b/benchmark/holdout/BURNED new file mode 100644 index 0000000..cd65da5 --- /dev/null +++ b/benchmark/holdout/BURNED @@ -0,0 +1,8 @@ +status=BURNED_FOR_CONFIRMATORY_USE +rule=B0_PREREGISTRATION_SECTION_6.6 +sample_id=H01.clean.s1 +cause=The TDD worker contract invoked the unchanged detector on the deterministic frozen H01.clean.s1 input before benchmark/holdout/seal.json existed. +detected_at_utc=2026-11-30 +consequence=No confirmatory sealed-holdout metrics may be claimed from this manifest. A new preregistered seed/template set and full rerun are required. +threshold_tuning_after_detection=none +partial_generation=stopped_and_removed diff --git a/benchmark/manifest-v3.json b/benchmark/manifest-v3.json new file mode 100644 index 0000000..c99f652 --- /dev/null +++ b/benchmark/manifest-v3.json @@ -0,0 +1,950 @@ +{ + "schema_version": 2, + "frozen_at": "2026-12-01", + "product": "PlotProof", + "split_policy": "template_family", + "registration": { + "status": "preregistered_before_generation", + "registered_on": "2026-12-01", + "seeds": { + "clean": [ + 3 + ], + "defect": [ + 4, + 5 + ] + }, + "supersedes": { + "manifest": "benchmark/manifest.json", + "manifest_sha256_at_supersession": "f837fe95f76792e19244a6d75d85d7a1bed7ea311105637e59c5750d8db04f3e", + "burned_fixture": "H01.clean.s1", + "burn_marker": "benchmark/holdout/BURNED", + "reason": "The v2 TDD worker contract invoked the unchanged detector on H01.clean.s1 before a seal existed (B0 section 6.6). The whole v2 holdout is therefore unusable for confirmatory claims." + }, + "holdout_template_ids": [ + "H13", + "H14", + "H15", + "H16", + "H17", + "H18", + "H19", + "H20", + "H21", + "H22", + "H23", + "H24" + ], + "holdout_counterexample_ids": [ + "L13", + "L14", + "L15", + "L16", + "L17", + "L18" + ], + "holdout_sample_count": 114, + "declaration": "This fixture list was committed before any fixture in it was generated or executed. No detector output for any sample below existed when it was written." + }, + "label_binding": { + "layout": "constrained", + "axis_label_rotation": 0, + "axis_labelpad_pt": 4.0, + "left_ylabel_ha": "right", + "right_ylabel_ha": "left", + "supylabel_ha": "left", + "colorbar_orientation": "horizontal", + "colorbar_label_rotation": 0, + "colorbar_label_role": "xlabel", + "clean_sample_check": "no page clipping and no D3 candidate with smaller-union coverage >= 0.15" + }, + "save_binding": { + "matplotlib_version": "3.10.8", + "backend": "Agg", + "pdf_fonttype": 42, + "figure_dpi": 100, + "figure_size_inches": [ + 10.0, + 6.0 + ], + "base_font_size_pt": 10.0, + "layout": "constrained", + "axes_unicode_minus": false, + "transparent": false, + "font_family_ascii": "DejaVu Sans", + "font_family_cjk": "Noto Sans CJK SC", + "cjk_font_scope": "per-text fontproperties", + "bbox_inches": null, + "pad_inches": null, + "pad_inches_effective": 0.1 + }, + "variants": [ + "clean", + "clip", + "occlude", + "overlap", + "missing_glyph" + ], + "defect_variants": [ + "clip", + "occlude", + "overlap", + "missing_glyph" + ], + "seeds": { + "clean": [ + 3 + ], + "defect": [ + 4, + 5 + ] + }, + "injection_binding": { + "clip": "at least one aligned target character box has positive area A and A_out >= 0.5*A, or is a positive-area box whose center is strictly outside the page", + "occlude": "one contributing artist with alpha_eff >= 0.95, later recorded paint order, supported occluder geometry, R_a inside the page, and its own coverage of the target character union >= 0.90", + "overlap": "both members aligned, r >= 0.50 on their character-box unions, one character-box pair overlapping >= 0.5 pt in both axes, and neither own opaque background patch intersecting the overlap", + "missing_glyph": "exactly one character absent from every resolved font: U+20000" + }, + "templates": [ + { + "id": "D01", + "family": "line_basic", + "split": "dev", + "chart": "line", + "language": "en", + "similarity_group": "line", + "features": [ + "title", + "xlabel", + "ylabel", + "xticks", + "yticks", + "legend_inside", + "single_series" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "series": 1, + "points": 30, + "freq": 0.5, + "phase": 0.0, + "legend": false + } + }, + { + "id": "D02", + "family": "line_multi", + "split": "dev", + "chart": "line", + "language": "en", + "similarity_group": "line", + "features": [ + "title", + "xlabel", + "ylabel", + "legend_inside", + "three_series", + "y_unit" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "series": 3, + "points": 30, + "freq": 0.5, + "phase": 0.0, + "legend": true + } + }, + { + "id": "D03", + "family": "bar_vertical", + "split": "dev", + "chart": "bar", + "language": "en", + "similarity_group": "bar", + "features": [ + "title", + "xlabel", + "ylabel", + "xticks", + "value_labels" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "mode": "single", + "values": [ + 3, + 6, + 4, + 8, + 5, + 7 + ], + "value_labels": true + } + }, + { + "id": "D04", + "family": "bar_grouped", + "split": "dev", + "chart": "bar", + "language": "en", + "similarity_group": "bar", + "features": [ + "title", + "xlabel", + "ylabel", + "legend_inside", + "two_groups", + "xticks" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "mode": "grouped", + "values": [ + 3, + 6, + 4, + 8, + 5, + 7 + ], + "value_labels": false + } + }, + { + "id": "D05", + "family": "scatter", + "split": "dev", + "chart": "scatter", + "language": "en", + "similarity_group": "scatter", + "features": [ + "title", + "xlabel", + "ylabel", + "annotations", + "grid" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "points": 6, + "annotations": 3, + "grid": true, + "legend": true + } + }, + { + "id": "D06", + "family": "histogram", + "split": "dev", + "chart": "histogram", + "language": "en", + "similarity_group": "distribution", + "features": [ + "title", + "xlabel", + "ylabel", + "xticks" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "bins": 12, + "samples": 200 + } + }, + { + "id": "D07", + "family": "boxplot", + "split": "dev", + "chart": "box", + "language": "en", + "similarity_group": "distribution", + "features": [ + "title", + "xlabel", + "ylabel", + "xticks", + "four_groups" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "groups": 4 + } + }, + { + "id": "D08", + "family": "heatmap", + "split": "dev", + "chart": "heatmap", + "language": "en", + "similarity_group": "matrix", + "features": [ + "title", + "colorbar", + "colorbar_label", + "xticks", + "yticks", + "colorbar_horizontal" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "grid": 30, + "colorbar_label": "Color value" + } + }, + { + "id": "D09", + "family": "pie", + "split": "dev", + "chart": "pie", + "language": "en", + "similarity_group": "part_to_whole", + "features": [ + "title", + "slice_labels", + "percent_labels" + ], + "target_role": "title", + "params": { + "values": [ + 4, + 6, + 3, + 5 + ], + "labels": [ + "A", + "B", + "C", + "D" + ] + } + }, + { + "id": "D10", + "family": "errorbar", + "split": "dev", + "chart": "errorbar", + "language": "en", + "similarity_group": "line", + "features": [ + "title", + "xlabel", + "ylabel", + "legend_inside", + "five_points" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "points": 6, + "legend": true + } + }, + { + "id": "D11", + "family": "log_scale", + "split": "dev", + "chart": "line", + "language": "en", + "similarity_group": "line", + "features": [ + "title", + "xlabel", + "ylabel", + "log_y", + "log_ticks_plain_text" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "series": 1, + "points": 30, + "freq": 0.5, + "phase": 0.0, + "legend": false, + "log_y": true + }, + "note": "Log tick labels are plain text via the callable FuncFormatter('{:g}'.format) and contain no '$'; the bare string '{:g}' is not callable. Default mathdefault log labels are out of scope (section 3.2) and would push the clean sample below the 0.90 coverage gate.", + "tick_formatter": "FuncFormatter('{:g}'.format)" + }, + { + "id": "D12", + "family": "datetime_axis", + "split": "dev", + "chart": "line", + "language": "en", + "similarity_group": "time", + "features": [ + "title", + "xlabel", + "ylabel", + "date_ticks_horizontal" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "series": 1, + "dates": true, + "points": 8, + "legend": false + }, + "note": "Date tick labels are horizontal (date_ticks_horizontal); rotated ticks are out of scope (section 3.2) and would push the clean sample below the 0.90 coverage gate." + }, + { + "id": "H13", + "family": "line_annotated", + "split": "holdout", + "chart": "line", + "language": "en", + "similarity_group": "line", + "features": [ + "title", + "xlabel", + "ylabel", + "xticks", + "markers", + "single_series" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "series": 1, + "points": 24, + "freq": 0.7, + "phase": 0.3, + "legend": false, + "markers": true + } + }, + { + "id": "H14", + "family": "violin_five", + "split": "holdout", + "chart": "violin", + "language": "en", + "similarity_group": "distribution", + "features": [ + "title", + "xlabel", + "ylabel", + "xticks", + "five_groups" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "groups": 5 + } + }, + { + "id": "H15", + "family": "bar_stacked_three", + "split": "holdout", + "chart": "bar", + "language": "en", + "similarity_group": "bar", + "features": [ + "title", + "xlabel", + "ylabel", + "legend_inside", + "three_stacks", + "xticks" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "mode": "stacked", + "values": [ + 3, + 6, + 4, + 8, + 5, + 7 + ], + "stacks": 3 + } + }, + { + "id": "H16", + "family": "bar_horizontal_six", + "split": "holdout", + "chart": "barh", + "language": "en", + "similarity_group": "bar", + "features": [ + "title", + "xlabel", + "long_category_labels", + "six_bars" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "categories": [ + "Long category A", + "Long category B", + "Category C", + "Category D", + "Category E", + "Category F" + ], + "values": [ + 8, + 6, + 10, + 7, + 9, + 5 + ] + } + }, + { + "id": "H17", + "family": "contour_colorbar", + "split": "holdout", + "chart": "contour", + "language": "en", + "similarity_group": "matrix", + "features": [ + "title", + "colorbar", + "colorbar_label", + "xticks", + "yticks", + "colorbar_horizontal" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "grid": 28, + "levels": 10, + "colorbar_label": "Level" + } + }, + { + "id": "H18", + "family": "twin_axes_dual", + "split": "holdout", + "chart": "line", + "language": "en", + "similarity_group": "line", + "features": [ + "title", + "xlabel", + "two_ylabels", + "legend_inside", + "dual_y" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "series": 1, + "points": 30, + "freq": 0.5, + "phase": 0.0, + "legend": true, + "twin": true + } + }, + { + "id": "H19", + "family": "area_stacked_two", + "split": "holdout", + "chart": "area", + "language": "en", + "similarity_group": "area", + "features": [ + "title", + "xlabel", + "ylabel", + "legend_inside", + "two_series", + "stacked" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "series": 2, + "points": 30 + } + }, + { + "id": "H20", + "family": "dense_ticks_thirty", + "split": "holdout", + "chart": "line", + "language": "en", + "similarity_group": "line", + "features": [ + "title", + "xlabel", + "ylabel", + "thirty_xticks", + "minor_ticks" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "series": 1, + "dense": 30, + "freq": 0.5, + "phase": 0.0, + "legend": false + }, + "note": "Thirty major x ticks at rotation 0 with four minor subdivisions per interval; the dense-tick family exercises label crowding without leaving the supported set.", + "tick_binding": { + "x_major_ticks": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29 + ], + "x_limits": [ + -0.5, + 29.5 + ], + "x_minor_subdivisions": 4, + "x_label_rotation": 0, + "x_label_format": "{:d}" + } + }, + { + "id": "H21", + "family": "scientific_notation", + "split": "holdout", + "chart": "line", + "language": "en", + "similarity_group": "line", + "features": [ + "title", + "xlabel", + "ylabel", + "scientific_offset", + "xticks" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "series": 1, + "points": 30, + "freq": 0.5, + "phase": 0.0, + "legend": false, + "sci": true, + "ylim": [ + 0, + 5000 + ] + }, + "note": "Offset text is plain 1e3 notation (axes.formatter.use_mathtext=False); mathtext offsets are out of scope (section 3.2).", + "tick_formatter": "ScalarFormatter(useMathText=False)" + }, + { + "id": "H22", + "family": "legend_below_axes", + "split": "holdout", + "chart": "line", + "language": "en", + "similarity_group": "line", + "features": [ + "title", + "xlabel", + "ylabel", + "legend_below_axes", + "bbox_to_anchor" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "series": 2, + "points": 30, + "freq": 0.5, + "phase": 0.0, + "legend": true, + "legend_position": "below" + } + }, + { + "id": "H23", + "family": "subplots_suptitle", + "split": "holdout", + "chart": "subplots_1x2", + "language": "en", + "similarity_group": "layout", + "features": [ + "suptitle", + "shared_xlabel", + "shared_ylabel", + "two_axes", + "legends" + ], + "target_role": "suptitle", + "labels_horizontal": true, + "params": { + "panels": 2 + } + }, + { + "id": "H24", + "family": "units_negative_cjk", + "split": "holdout", + "chart": "bar", + "language": "zh_en", + "similarity_group": "bar", + "features": [ + "title_cjk", + "title", + "ylabel_cjk_unit", + "negative_values", + "ascii_minus", + "thousands_separator" + ], + "target_role": "title", + "labels_horizontal": true, + "params": { + "mode": "single", + "values": [ + -9000, + -5000, + 0, + 5000, + 9000, + 2000 + ], + "cjk_title": true, + "cjk_ylabel": true, + "thousands": true, + "ylim": [ + -10000, + 10000 + ], + "ylabel": "数值 Units" + }, + "tick_formatter": "FuncFormatter('{:,}'.format)", + "tick_binding": { + "y_limits": [ + -10000, + 10000 + ], + "y_major_ticks": [ + -10000, + -5000, + 0, + 5000, + 10000 + ], + "y_label_rotation": 0, + "y_label_format": "{:,d}" + } + } + ], + "counterexamples": [ + { + "id": "L01", + "family": "legal_text_on_white_bbox", + "split": "dev", + "kind": "white_label", + "params": { + "text": "White background" + }, + "expected_state": "PASS", + "note": "Legal construction that must not be reported as a supported defect." + }, + { + "id": "L02", + "family": "framed_legend_over_data", + "split": "dev", + "kind": "framed_legend", + "params": { + "frameon": true + }, + "expected_state": "PASS", + "note": "Legal construction that must not be reported as a supported defect." + }, + { + "id": "L03", + "family": "narrow_gap_between_texts", + "split": "dev", + "kind": "narrow_gap", + "params": { + "text": "I I", + "offset": 0.025 + }, + "expected_state": "PASS", + "note": "Legal construction that must not be reported as a supported defect." + }, + { + "id": "L04", + "family": "rotated_text_out_of_scope", + "split": "dev", + "kind": "rotated_text", + "params": { + "rotation": 45 + }, + "expected_state": "UNKNOWN", + "note": "Legal construction that must not be reported as a supported defect." + }, + { + "id": "L05", + "family": "near_edge_inside_page", + "split": "dev", + "kind": "near_edge", + "params": { + "x": 0.995 + }, + "expected_state": "PASS", + "note": "Legal construction that must not be reported as a supported defect." + }, + { + "id": "L06", + "family": "translucent_cover_medium_alpha", + "split": "dev", + "kind": "translucent_cover", + "params": { + "alpha": 0.5 + }, + "expected_state": "UNKNOWN", + "note": "Legal construction that must not be reported as a supported defect.", + "alpha_binding": { + "facecolor_alpha": 0.5, + "artist_alpha": 1.0 + } + }, + { + "id": "L13", + "family": "white_label_on_heatmap", + "split": "holdout", + "kind": "white_label", + "params": { + "text": "White label", + "on_heatmap": true + }, + "expected_state": "PASS", + "note": "Legal construction that must not be reported as a supported defect." + }, + { + "id": "L14", + "family": "frameless_legend_over_data", + "split": "holdout", + "kind": "framed_legend", + "params": { + "frameon": false + }, + "expected_state": "PASS", + "note": "Legal construction that must not be reported as a supported defect." + }, + { + "id": "L15", + "family": "colorbar_label_close_no_overlap", + "split": "holdout", + "kind": "colorbar_label", + "params": { + "label": "Value" + }, + "expected_state": "PASS", + "note": "Legal construction that must not be reported as a supported defect." + }, + { + "id": "L16", + "family": "axis_label_outside_axes_inside_page", + "split": "holdout", + "kind": "outside_axes_label", + "params": { + "x": -0.08 + }, + "expected_state": "PASS", + "note": "Legal construction that must not be reported as a supported defect." + }, + { + "id": "L17", + "family": "tight_bbox_includes_annotation", + "split": "holdout", + "kind": "tight_bbox", + "params": { + "text": "Tight page keeps this annotation" + }, + "expected_state": "PASS", + "note": "Legal construction that must not be reported as a supported defect.", + "save_override": { + "bbox_inches": "tight" + } + }, + { + "id": "L18", + "family": "multiline_text_line_spacing", + "split": "holdout", + "kind": "multiline", + "params": { + "lines": 3 + }, + "expected_state": "PASS", + "note": "Legal construction that must not be reported as a supported defect." + } + ], + "counts": { + "templates_total": 24, + "templates_dev": 12, + "templates_holdout": 12, + "samples_per_template": 9, + "clean_samples_total": 24, + "defect_samples_total": 192, + "counterexamples_total": 12, + "samples_total": 228, + "holdout_samples": 114, + "dev_samples": 114, + "defect_instances_total": 192, + "defect_instances_holdout": 96, + "per_defect_class_total": { + "clipped_text": 48, + "missing_glyph": 48, + "occluded_text": 48, + "overlapping_text": 48 + }, + "per_defect_class_holdout": { + "clipped_text": 24, + "missing_glyph": 24, + "occluded_text": 24, + "overlapping_text": 24 + } + } +} diff --git a/benchmark/run_holdout.py b/benchmark/run_holdout.py new file mode 100644 index 0000000..0493cbe --- /dev/null +++ b/benchmark/run_holdout.py @@ -0,0 +1,366 @@ +#!/usr/bin/env python3 +"""Verify, unseal and execute the frozen PlotProof holdout exactly once. + +The runner has no threshold, rule or sample-selection options. It verifies the +manifest, labels, code bytes, environment and every input hash before logging +the unseal. Full per-sample reports are retained in raw_outcomes.jsonl. +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import time +from datetime import UTC, datetime +from pathlib import Path +from typing import Any + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from benchmark.generate_holdout import build_sample, close_built +from benchmark.holdout import ( + ROOT, + HoldoutError, + canonical_json, + code_fingerprint, + emit_error, + expand_samples, + load_manifest, + pinned_environment, + require_windows, + sha256_file, + summarize_outcomes, + validate_seal, + write_json, +) + + +def evaluate_sample(sample: dict[str, Any], expected_sha256: str) -> dict[str, Any]: + """Worker entry point: run the unchanged detector and bind its raw report.""" + start = time.perf_counter() + # The detector receives only rendering coordinates, never split/answer fields. + build_record = {key: sample[key] for key in + ("id", "template_id", "counterexample_id", "variant", "seed", "target_role") + if key in sample} + built = build_sample(build_record, _load_manifest()) + try: + from plotproof import CheckError, check_figure + + try: + report = check_figure(built.figure, **built.save_kwargs).to_dict() + except CheckError as error: + return { + "sample_id": sample["id"], + "state": "ERROR", + "input_sha256": None, + "findings": [], + "report": None, + "error": {"code": "CHECK_FAILED", "message": str(error)}, + "elapsed_ms": round((time.perf_counter() - start) * 1000, 3), + } + if report.get("input_sha256") != expected_sha256: + return { + "sample_id": sample["id"], + "state": "ERROR", + "input_sha256": report.get("input_sha256"), + "findings": [], + "report": report, + "error": {"code": "SEALED_INPUT_MISMATCH", + "message": "detector input hash differs from the sealed PDF"}, + "elapsed_ms": round((time.perf_counter() - start) * 1000, 3), + } + return { + "sample_id": sample["id"], + "state": report["state"], + "input_sha256": report["input_sha256"], + "findings": report["findings"], + "report": report, + "error": None, + "elapsed_ms": round((time.perf_counter() - start) * 1000, 3), + } + except Exception as error: + return { + "sample_id": sample["id"], + "state": "ERROR", + "input_sha256": None, + "findings": [], + "report": None, + "error": {"code": "WORKER_INTERNAL", "message": f"{type(error).__name__}: {error}"}, + "elapsed_ms": round((time.perf_counter() - start) * 1000, 3), + } + finally: + close_built(built) + + +def _load_manifest() -> dict[str, Any]: + return load_manifest() + + +def _worker(sample_id: str, expected_sha256: str) -> int: + sample = next((item for item in expand_samples(_load_manifest()) + if item["id"] == sample_id), None) + if sample is None or sample.get("split") != "holdout": + return emit_error(HoldoutError("SAMPLE_INVALID", "worker sample is not in the frozen holdout")) + outcome = evaluate_sample(sample, expected_sha256) + sys.stdout.write(canonical_json(outcome).decode("utf-8")) + return 0 + + +def _run_worker(sample_id: str, expected_sha256: str, timeout: float) -> dict[str, Any]: + start = time.perf_counter() + try: + completed = subprocess.run( + [sys.executable, str(Path(__file__).resolve()), "_worker", sample_id, expected_sha256], + cwd=ROOT, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + env=dict(os.environ, PYTHONIOENCODING="utf-8", MPLBACKEND="Agg"), + timeout=timeout, + ) + except subprocess.TimeoutExpired: + return { + "sample_id": sample_id, + "state": "ERROR", + "input_sha256": None, + "findings": [], + "report": None, + "error": {"code": "WORKER_TIMEOUT", "message": f"worker exceeded {timeout:g} seconds"}, + "elapsed_ms": round((time.perf_counter() - start) * 1000, 3), + } + if completed.returncode != 0: + return { + "sample_id": sample_id, + "state": "ERROR", + "input_sha256": None, + "findings": [], + "report": None, + "error": {"code": "WORKER_EXIT", "message": completed.stderr.strip() + or f"worker exited {completed.returncode}"}, + "elapsed_ms": round((time.perf_counter() - start) * 1000, 3), + } + try: + outcome = json.loads(completed.stdout) + except json.JSONDecodeError: + outcome = None + if (not isinstance(outcome, dict) or outcome.get("sample_id") != sample_id + or outcome.get("state") not in {"PASS", "FAIL", "UNKNOWN", "ERROR"} + or (outcome.get("state") != "ERROR" and outcome.get("input_sha256") != expected_sha256) + or not isinstance(outcome.get("findings"), list)): + return { + "sample_id": sample_id, + "state": "ERROR", + "input_sha256": None, + "findings": [], + "report": None, + "error": {"code": "WORKER_PROTOCOL", "message": "worker returned invalid JSON evidence"}, + "elapsed_ms": round((time.perf_counter() - start) * 1000, 3), + } + outcome["worker_elapsed_ms"] = round((time.perf_counter() - start) * 1000, 3) + return outcome + + +def ensure_first_run(holdout_dir: Path) -> None: + if (holdout_dir / "predictions.jsonl").exists(): + raise HoldoutError("ALREADY_RUN", + "holdout predictions.jsonl already exists; a rerun requires a new seal") + + +def _append_jsonl(path: Path, value: dict[str, Any]) -> None: + with path.open("ab") as handle: + handle.write(canonical_json(value)) + handle.flush() + os.fsync(handle.fileno()) + + +def _record_unseal(holdout_dir: Path, seal: dict[str, Any], seal_hash: str) -> None: + path = holdout_dir / "unseal.json" + document = json.loads(path.read_text(encoding="utf-8")) if path.exists() else { + "schema_version": 1, "attempts": [], + } + document["attempts"].append({ + "at_utc": datetime.now(UTC).isoformat(), + "seal_sha256": seal_hash, + "environment": pinned_environment(), + "code_sha256": code_fingerprint(), + "threshold_tuning_performed": False, + }) + write_json(path, document) + + +def _metric_text(metric: dict[str, Any]) -> str: + if metric["estimate"] is None: + return "undefined (n=0)" + interval = metric["wilson_95"] + return (f"{metric['estimate']:.4f} ({metric['numerator']}/{metric['denominator']}; " + f"Wilson 95% {interval[0]:.4f}–{interval[1]:.4f})") + + +def _mean_text(metric: dict[str, Any]) -> str: + if metric["estimate"] is None: + return "undefined (n=0)" + return f"{metric['estimate']:.4f} (mean over {metric['denominator']} samples)" + + +def render_markdown(summary: dict[str, Any], seal: dict[str, Any]) -> str: + pooled = summary["pooled"] + lines = [ + "# PlotProof sealed holdout result", + "", + f"- Label review status: `{seal.get('label_review_status', 'unknown')}`", + f"- Frozen revision: `{seal.get('revision', 'unknown')}`", + "- Threshold tuning after unsealing: **none**", + "- Intervals: two-sided 95% Wilson score intervals; descriptive only.", + "", + "## Pooled metrics", + "", + "| Metric | Estimate (count; Wilson 95%) |", + "|---|---:|", + ] + for key, title in ( + ("precision", "High-confidence precision"), + ("recall", "End-to-end recall"), + ("conditional_recall", "Conditional-on-decidable recall"), + ("false_pass_rate", "False-PASS rate (expected FAIL observed PASS)"), + ("unknown_rate", "UNKNOWN rate"), + ("error_rate", "ERROR rate"), + ("clean_or_legal_pass_rate", "Clean/legal PASS rate"), + ): + lines.append(f"| {title} | {_metric_text(pooled[key])} |") + lines.extend([ + "", + f"Clean/legal high-confidence FAIL count: **{pooled['clean_or_legal_fail_count']}**", + f"Clean/legal PASS count: **{pooled['clean_or_legal_pass_count']}/{pooled['clean_or_legal_pass_rate']['denominator']}**", + f"Macro alignment coverage: **{_mean_text(pooled['alignment_coverage'])}**; zero-unit samples: {pooled['zero_unit_samples']}", + "", + "State counts: " + ", ".join(f"{key}={value}" for key, value in pooled["state_counts"].items()), + "", + "## Per-class metrics", + "", + "Class-level intervals are wide and descriptive; the pooled gate is binding.", + "", + "| Class | Precision | Recall | Conditional recall | False-PASS rate | TP / FP / references |", + "|---|---:|---:|---:|---:|---:|", + ]) + for name, row in summary["per_class"].items(): + lines.append( + f"| `{name}` | {_metric_text(row['precision'])} | {_metric_text(row['recall'])} | " + f"{_metric_text(row['conditional_recall'])} | {_metric_text(row['false_pass_rate'])} | " + f"{row['true_positives']} / {row['false_positives']} / {row['references']} |") + lines.extend(["", "## Protocol limitations", ""]) + for limitation in seal.get("protocol_limitations", []): + lines.append(f"- {limitation}") + lines.extend([ + "- No independent custodian or human PDF label-review session is claimed.", + "- The seal is a procedural hash commitment, not access control or independent annotation.", + "- Synthetic templates and shared fonts do not establish real-world accuracy.", + "- The B0 baseline-B delta gate and template-cluster bootstrap are not implemented; all_pass fails closed.", + "- Full reports: `raw_outcomes.jsonl`; minimal predictions: `predictions.jsonl`.", + "", + ]) + return "\n".join(lines) + + +def _gate_results(summary: dict[str, Any]) -> dict[str, Any]: + pooled = summary["pooled"] + gates = { + "precision_ge_0_95": (pooled["precision"]["estimate"] is not None + and pooled["precision"]["estimate"] >= 0.95), + "recall_ge_0_80": (pooled["recall"]["estimate"] is not None + and pooled["recall"]["estimate"] >= 0.80), + "unknown_rate_le_0_20": pooled["unknown_rate"]["estimate"] <= 0.20, + "error_rate_le_0_05": pooled["error_rate"]["estimate"] <= 0.05, + "clean_or_legal_fail_count_zero": pooled["clean_or_legal_fail_count"] == 0, + "clean_or_legal_pass_rate_ge_16_18": (pooled["clean_or_legal_pass_count"] >= 16 + and pooled["clean_or_legal_pass_rate"]["denominator"] == 18), + "alignment_coverage_ge_0_90": (pooled["alignment_coverage"]["estimate"] is not None + and pooled["alignment_coverage"]["estimate"] >= 0.90), + "false_pass_rate_zero": pooled["false_pass_rate"]["estimate"] == 0.0, + } + return { + "implemented_subset_only": True, + "not_implemented": ["baseline_B_delta_gate", "template_cluster_bootstrap"], + "gates": gates, + "all_pass": False, + } + + +def execute(holdout_dir: Path, *, timeout: float = 180.0) -> dict[str, Any]: + require_windows() + if (holdout_dir / "BURNED").exists(): + raise HoldoutError("HOLDOUT_BURNED", + "holdout is burned for confirmatory use; see BURNED and B0 section 6.6") + if not (holdout_dir / "seal.json").is_file(): + raise HoldoutError("SEAL_MISSING", "holdout seal.json is missing") + seal = json.loads((holdout_dir / "seal.json").read_text(encoding="utf-8")) + manifest = _load_manifest() + environment = pinned_environment() + code = code_fingerprint() + labels = validate_seal(seal, holdout_dir, manifest, code, environment) + ensure_first_run(holdout_dir) + seal_hash = sha256_file(holdout_dir / "seal.json") + _record_unseal(holdout_dir, seal, seal_hash) + outcomes = [] + sealed_by_id = {item["id"]: item for item in seal["samples"]} + for index, sample_id in enumerate(sorted(sealed_by_id), 1): + outcome = _run_worker(sample_id, sealed_by_id[sample_id]["sha256"], timeout) + outcomes.append(outcome) + prediction = {key: outcome.get(key) for key in + ("sample_id", "state", "input_sha256", "findings", "error", "elapsed_ms")} + _append_jsonl(holdout_dir / "predictions.jsonl", prediction) + _append_jsonl(holdout_dir / "raw_outcomes.jsonl", outcome) + print(f"evaluated {index}/{len(sealed_by_id)} {sample_id}: {outcome['state']}", + file=sys.stderr, flush=True) + summary = summarize_outcomes(labels, outcomes) + results = { + "schema_version": 1, + "completed_at_utc": datetime.now(UTC).isoformat(), + "seal_sha256": seal_hash, + "revision": seal["revision"], + "environment": environment, + "code_sha256": code, + "label_review_status": seal["label_review_status"], + "protocol_limitations": seal["protocol_limitations"], + "threshold_tuning_performed": False, + "metrics": summary, + "gate_results": _gate_results(summary), + "raw_outcomes": "raw_outcomes.jsonl", + "predictions": "predictions.jsonl", + } + write_json(holdout_dir / "results.json", results) + (holdout_dir / "summary.md").write_text(render_markdown(summary, seal), encoding="utf-8") + return results + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--holdout-dir", type=Path, + default=Path(__file__).resolve().parent / "holdout") + parser.add_argument("--worker-timeout", type=float, default=180.0, + help="per-sample subprocess timeout in seconds (not a detector threshold)") + args = parser.parse_args() + try: + if args.worker_timeout <= 0: + raise HoldoutError("INVALID_TIMEOUT", "worker timeout must be positive") + results = execute(args.holdout_dir, timeout=args.worker_timeout) + print(json.dumps({"status": "OK", "results": "results.json", + "all_gates_pass": results["gate_results"]["all_pass"]}, indent=2)) + return 0 + except (HoldoutError, OSError, ValueError, json.JSONDecodeError) as error: + if isinstance(error, HoldoutError): + return emit_error(error) + return emit_error(HoldoutError("RUN_FAILED", str(error))) + + +if __name__ == "__main__": + if len(sys.argv) >= 2 and sys.argv[1] == "_worker": + if len(sys.argv) != 4: + return_code = emit_error(HoldoutError("WORKER_ARGUMENTS", "usage: run_holdout.py _worker ID SHA256")) + else: + return_code = _worker(sys.argv[2], sys.argv[3]) + raise SystemExit(return_code) + raise SystemExit(main()) diff --git a/benchmark/validate_manifest.py b/benchmark/validate_manifest.py index 858d39a..f4b8e12 100644 --- a/benchmark/validate_manifest.py +++ b/benchmark/validate_manifest.py @@ -38,7 +38,7 @@ def strict_equal(value: object, expected: object) -> bool: return ( isinstance(value, list) and len(value) == len(expected) - and all(strict_equal(v, e) for v, e in zip(value, expected)) + and all(strict_equal(v, e) for v, e in zip(value, expected, strict=False)) ) if isinstance(expected, dict): return ( diff --git a/noxfile.py b/noxfile.py new file mode 100644 index 0000000..8a8e823 --- /dev/null +++ b/noxfile.py @@ -0,0 +1,67 @@ +"""Nox sessions: multi-interpreter tests plus lint/typecheck/build gates. + +Local use: + python -m pip install nox + nox -l + nox -s tests-3.13 # one interpreter + nox # every interpreter installed on this machine + +CI runs ``nox -s lint typecheck`` in the ``quality`` job and the native +``test`` matrix for full interpreter coverage. Keep both paths in sync. +""" + +from __future__ import annotations + +from pathlib import Path + +import nox + +nox.options.sessions = ["lint", "typecheck", "tests"] +nox.options.reuse_existing_virtualenvs = False + +PYTHONS = ["3.10", "3.11", "3.12", "3.13"] +RUFF = "ruff==0.17.6" +MYPY = "mypy==2.4.1" + + +def _sources() -> list[str]: + """Lint the shipped packages plus the tests, whichever layout is used.""" + roots = [d for d in ("src", "tests") if Path(d).is_dir()] + for parent in (Path("src"), Path(".")): + if not parent.is_dir(): + continue + for child in sorted(parent.iterdir()): + if child.is_dir() and (child / "__init__.py").is_file(): + name = child.as_posix() + if name not in roots: + roots.append(name) + return roots or ["."] + + +@nox.session(python=PYTHONS) +def tests(session: nox.Session) -> None: + """Run the test suite on one interpreter.""" + session.install("-e", ".") + session.run("python", "-m", "pytest", "tests", "-q", *session.posargs) + + +@nox.session +def lint(session: nox.Session) -> None: + """Ruff lint gate, identical to the pre-commit hook.""" + session.install(RUFF) + session.run("ruff", "check", ".") + + +@nox.session +def typecheck(session: nox.Session) -> None: + """Mypy gate over the shipped package.""" + session.install(MYPY) + session.install("-e", ".") + session.run("mypy", "--config-file=pyproject.toml") + + +@nox.session +def build(session: nox.Session) -> None: + """Build sdist and wheel.""" + session.install("build") + session.run("python", "-m", "build") diff --git a/plotproof/_pdf_worker.py b/plotproof/_pdf_worker.py index d7e5ddf..f9a7d7f 100644 --- a/plotproof/_pdf_worker.py +++ b/plotproof/_pdf_worker.py @@ -2,11 +2,11 @@ from __future__ import annotations import base64 +import json +import sys from hashlib import sha256 from io import BytesIO -import json from pathlib import Path -import sys # -I excludes both cwd and PYTHONPATH. Add only this installed package's root. sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) diff --git a/plotproof/alignment.py b/plotproof/alignment.py index 9fd8d4f..32df667 100644 --- a/plotproof/alignment.py +++ b/plotproof/alignment.py @@ -1,12 +1,12 @@ """Frozen §7.1 canonicalization, candidate search and deterministic assignment.""" from __future__ import annotations +import unicodedata +from collections.abc import Mapping, Sequence from dataclasses import dataclass from math import hypot from statistics import median from types import MappingProxyType -from typing import Mapping, Sequence -import unicodedata from .evidence import GlyphEvidence, PdfChar from .geometry import Rect, iou @@ -84,7 +84,7 @@ def coverage(self) -> dict: def _source_searches(unit: Unit, glyphs: Sequence[GlyphEvidence]) -> list[tuple[Canonical, tuple[int, ...]]]: text = unit.record.text - searches = [(canonicalize(text, source=True), ())] + searches: list[tuple[Canonical, tuple[int, ...]]] = [(canonicalize(text, source=True), ())] removed = tuple(sorted({g.codepoint for g in glyphs if g.proven_missing and chr(g.codepoint) in text})) if removed: kept_indices = [i for i, c in enumerate(text) if ord(c) not in removed] @@ -136,11 +136,12 @@ def align_units(units: UnitSet, chars: Sequence[PdfChar], pdf = canonicalize(''.join(c.text for c in chars), source=False) indices: list[list[int]] = [[] for _ in pdf.text] for original, canonical in enumerate(pdf.original_to_canonical): - indices[canonical].append(original) + if canonical is not None: + indices[canonical].append(original) unknown: dict[int, str] = {} valid_by_unit: dict[int, list[Span]] = {} all_by_unit: dict[int, list[Span]] = {} - pairs = [] + pairs: list[tuple[int, Span]] = [] for unit in units.units: uid = unit.record.source_object_id if unit.unsupported_reason: @@ -168,7 +169,7 @@ def align_units(units: UnitSet, chars: Sequence[PdfChar], indistinguishable = any( (other.start, other.end) != (assigned.start, assigned.end) and other.canonical_text == assigned.canonical_text - and all(abs(a - b) <= 1.0 for a, b in zip(other.box.as_tuple(), assigned.box.as_tuple())) + and all(abs(a - b) <= 1.0 for a, b in zip(other.box.as_tuple(), assigned.box.as_tuple(), strict=False)) for other in all_by_unit[uid]) best = valid_by_unit[uid][:2] tied = (len(best) == 2 and hypot(best[0].box.center[0] - best[1].box.center[0], diff --git a/plotproof/capture.py b/plotproof/capture.py index 1a3796d..4cb4204 100644 --- a/plotproof/capture.py +++ b/plotproof/capture.py @@ -6,13 +6,13 @@ """ from __future__ import annotations +import threading +import warnings from dataclasses import replace from hashlib import sha256 from io import BytesIO from math import isfinite from pathlib import Path -import threading -import warnings from .capture_events import AppliedAlpha, CapturedPdf, DrawEvent, SourceArtist from .evidence import SaveWarning @@ -84,8 +84,8 @@ def _artists(fig): class _Recorder: def __init__(self, fig, output, max_events): - from matplotlib.text import Text from matplotlib.patches import Patch + from matplotlib.text import Text self.fig, self.output, self.max_events = fig, output, max_events self.Text, self.Patch = Text, Patch self.ids = {} @@ -97,7 +97,7 @@ def __init__(self, fig, output, max_events): self.font_use_keys = set() self.issues = set() self.vertex_count = 0 - self.crop_calls = [] + self.crop_calls: list[tuple[float, float, float, float]] = [] self.hooks = _Hooks() def register(self, artist, owner=None): @@ -296,7 +296,8 @@ def tight(renderer=None,*args,**kwargs): raise CaptureError('unsupported_tex') box = original_tight(renderer,*args,**kwargs) if self.fig.canvas.is_saving(): - self.crop_calls.append(tuple(map(float,box.bounds))) + x0, y0, width, height = box.bounds + self.crop_calls.append((float(x0), float(y0), float(width), float(height))) return box self.hooks.set(self.Text,'draw',text_draw) @@ -358,7 +359,12 @@ def _capture_locked(fig, bbox_inches, pad_inches, transparent, max_events, max_p with warnings.catch_warnings(record=True): warnings.simplefilter('always') fig.canvas.draw() - pre = tuple(map(float,fig.get_tightbbox(fig.canvas.get_renderer()).bounds)) if bbox_inches=='tight' else None + if bbox_inches == 'tight': + x0, y0, x1, y1 = fig.get_tightbbox(fig.canvas.get_renderer()).bounds + pre: tuple[float, float, float, float] | None = ( + float(x0), float(y0), float(x1), float(y1)) + else: + pre = None recorder.inventory() # Layout may have created additional source artists. with warnings.catch_warnings(record=True) as caught: warnings.simplefilter('always') @@ -366,7 +372,7 @@ def _capture_locked(fig, bbox_inches, pad_inches, transparent, max_events, max_p fig.savefig(output,format='pdf',bbox_inches=bbox_inches,pad_inches=float(pad),transparent=transparent, metadata={'CreationDate':None,'ModDate':None,'Creator':'PlotProof CA1 capture'}) saved = None - origin = (0.0,0.0) + origin: tuple[float, float] | None = (0.0, 0.0) if bbox_inches=='tight': if len(recorder.crop_calls)!=1: recorder.issues.add('ambiguous_crop_origin');origin=None diff --git a/plotproof/cli.py b/plotproof/cli.py index d3c74e1..6205ed0 100644 --- a/plotproof/cli.py +++ b/plotproof/cli.py @@ -2,18 +2,18 @@ from __future__ import annotations import argparse -from contextlib import contextmanager, redirect_stderr, redirect_stdout -from html import escape -from importlib.util import module_from_spec, spec_from_file_location import json import os -from pathlib import Path, PureWindowsPath import shutil import stat import sys import tempfile +from contextlib import contextmanager, redirect_stderr, redirect_stdout +from html import escape +from importlib.util import module_from_spec, spec_from_file_location +from pathlib import Path, PureWindowsPath -from .export import CheckError, CheckReport, check_figure, render_html +from .export import CheckReport, check_figure, render_html from .rules import DEFAULT_MAX_D3_WORK, validate_max_d3_work @@ -56,7 +56,7 @@ def __init__(self, code: str, message: str, recovery_backups: tuple[str, ...] = def _error_payload(code: str, message: str, recovery_backups=()) -> dict: - error = {'code': code, 'message': message} + error: dict[str, object] = {'code': code, 'message': message} if recovery_backups: error['recovery_backups'] = list(recovery_backups) return {'status': 'ERROR', 'error': error} @@ -71,7 +71,7 @@ def _same_file(left: Path, right: Path) -> bool: def _preflight(json_path: str | None, html_path: str | None, *, force: bool = False, input_path: str | Path | None = None) -> tuple[Path | None, Path | None]: - destinations = [] + destinations: list[Path | None] = [] source = Path(input_path).resolve() if input_path is not None else None for raw in (json_path, html_path): if not raw: @@ -92,16 +92,17 @@ def _preflight(json_path: str | None, html_path: str | None, *, if resolved.exists() and not resolved.is_file(): raise OutputError('OUTPUT_NOT_FILE', 'Output destinations must be regular files.') destinations.append(resolved) - for path in destinations: - if path is None: + for target in destinations: + if target is None: continue - if path.parent.exists() and not path.parent.is_dir(): + if target.parent.exists() and not target.parent.is_dir(): raise OutputError('OUTPUT_PARENT', 'Output parent must be a directory.') - backup = path.with_name(path.name + '.plotproof-backup') + backup = target.with_name(target.name + '.plotproof-backup') if backup in destinations or backup == source or backup.exists() or backup.is_symlink(): raise OutputError('OUTPUT_BACKUP_EXISTS', 'A named recovery backup already exists or collides with an output.') - if all(path is not None for path in destinations): - if destinations[0] == destinations[1] or _same_file(*destinations): + first, second = destinations + if first is not None and second is not None: + if first == second or _same_file(first, second): raise OutputError('OUTPUT_ALIAS', 'JSON and HTML destinations must be different files.') if not force and any(path is not None and path.exists() for path in destinations): raise OutputError('OUTPUT_EXISTS', 'Output already exists; use --force to replace it explicitly.') @@ -143,16 +144,17 @@ def _publish_texts(items: list[tuple[Path, str]], expected=None) -> None: for path, text in items: path.parent.mkdir(parents=True, exist_ok=True) fd, name = tempfile.mkstemp(prefix='.' + path.name + '.', suffix='.tmp', dir=path.parent) + pending: int | None = fd temporary = Path(name) staged.append((path, temporary)) try: handle = os.fdopen(fd, 'w', encoding='utf-8', newline='\n') - fd = None + pending = None with handle: handle.write(text) finally: - if fd is not None: - os.close(fd) + if pending is not None: + os.close(pending) for path, _ in staged: if expected is not None and _output_identity(path) != expected.get(path): raise OutputError('OUTPUT_CONFLICT', 'Output destination changed after preflight.') @@ -212,8 +214,10 @@ def _save(report: CheckReport, json_path: str | None, html_path: str | None, *, html = render_html(report) if html_target is not None else None except Exception: raise OutputError('OUTPUT_SERIALIZATION_FAILED', 'Report serialization failed; no output was published.') from None - items = [] if json_target is None else [(json_target, payload)] - if html_target is not None: + items: list[tuple[Path, str]] = [] + if json_target is not None: + items.append((json_target, payload)) + if html_target is not None and html is not None: items.append((html_target, html)) _publish_texts(items, expected) if json_target is None: @@ -374,7 +378,7 @@ def emit(code, message, recovery=()): def _demo_command(args) -> int: output = Path(args.output).resolve() - destinations = [] + destinations: list[Path] = [] try: for name in ('clean', 'clipped'): pair = _preflight(str(output / (name + '.json')), @@ -419,7 +423,7 @@ def _demo_command(args) -> int: _emit_error('OUTPUT_FAILED', 'Demo report publication failed.', None) return 2 for name, report in reports: - print('%s: %s' % (name, report.state)) + print(f'{name}: {report.state}') return 0 diff --git a/plotproof/core.py b/plotproof/core.py index 1876c65..7d297d3 100644 --- a/plotproof/core.py +++ b/plotproof/core.py @@ -5,8 +5,8 @@ """ from __future__ import annotations +from collections.abc import Mapping, Sequence from dataclasses import asdict, dataclass -from typing import Mapping, Sequence from .alignment import align_units from .evidence import GlyphEvidence, PdfChar, TextRecord @@ -64,7 +64,7 @@ def check_core(*, records: Sequence[TextRecord], chars: Sequence[PdfChar], """Evaluate validated in-memory facts; ERROR dominates all other states.""" validate_max_d3_work(max_d3_work) errors = tuple(dict(error) for error in errors) - budget_record = [] + budget_record: list[dict | None] = [] try: _check_references(records, fills, glyphs) units = enumerate_units(records, transform, page, source_units_total) diff --git a/plotproof/evidence.py b/plotproof/evidence.py index b5bf392..9580800 100644 --- a/plotproof/evidence.py +++ b/plotproof/evidence.py @@ -2,8 +2,8 @@ from __future__ import annotations import ast -from dataclasses import dataclass import re +from dataclasses import dataclass from .geometry import Rect, finite_number @@ -57,13 +57,14 @@ def __post_init__(self) -> None: for name in ('paint_order', 'background_patch_id'): if getattr(self, name) is not None: integer_id(getattr(self, name), name) - if (self.tick_location is None) != (self.view_limits is None): + tick_location, view_limits = self.tick_location, self.view_limits + if (tick_location is None) != (view_limits is None): raise ValueError('tick location and view limits must both be present or absent') - if self.tick_location is not None: - object.__setattr__(self, 'tick_location', finite_number(self.tick_location, 'tick_location')) - if len(self.view_limits) != 2: + if tick_location is not None and view_limits is not None: + object.__setattr__(self, 'tick_location', finite_number(tick_location, 'tick_location')) + if len(view_limits) != 2: raise ValueError('view_limits must have two endpoints') - object.__setattr__(self, 'view_limits', tuple(finite_number(x, 'view_limit') for x in self.view_limits)) + object.__setattr__(self, 'view_limits', tuple(finite_number(x, 'view_limit') for x in view_limits)) @dataclass(frozen=True) @@ -159,7 +160,10 @@ def naming_warnings(self) -> tuple[SaveWarning, ...]: result = [] families = {font.family for font in self.fonts} for warning in self.codepoint_warnings: - text = _WARNING.fullmatch(warning.message).group(2) + match = _WARNING.fullmatch(warning.message) + if match is None: # codepoint_warnings already proved the shape + continue + text = match.group(2) if text.startswith('['): try: names = ast.literal_eval(text) diff --git a/plotproof/export.py b/plotproof/export.py index ff04acc..d9c7814 100644 --- a/plotproof/export.py +++ b/plotproof/export.py @@ -17,11 +17,12 @@ """ from __future__ import annotations +import tempfile from dataclasses import asdict, dataclass, field, replace from pathlib import Path -import tempfile from .capture import CaptureError, _artists, capture_pdf +from .capture_events import DrawEvent from .core import CoreResult, check_core from .evidence import TextRecord from .font_evidence import collect_font_evidence @@ -31,7 +32,6 @@ from .rules import DEFAULT_MAX_D3_WORK, validate_max_d3_work from .units import AccountingError, exclusion_reason - CHECKS_EVALUATED = ('D1_clipped_text', 'D2_occluded_text', 'D3_overlapping_text', 'D4_missing_glyph') CHECKS_NOT_EVALUATED = () @@ -145,8 +145,8 @@ def _collect(fig, captured, transform: Transform, page: Rect) -> _Collection: result.errors.append({'stage': 'inventory', 'message': 'source_count_mismatch'}) return result - text_events = {} - fill_events = {} + text_events: dict[int, DrawEvent] = {} + fill_events: dict[int, list[DrawEvent]] = {} for event in captured.events: if event.source_object_id is None: continue @@ -156,7 +156,7 @@ def _collect(fig, captured, transform: Transform, page: Rect) -> _Collection: fill_events.setdefault(event.source_object_id, []).append(event) renderer = fig.canvas.get_renderer() - for artist, source in zip(artists, sources): + for artist, source in zip(artists, sources, strict=False): if type(artist).__name__ != source.artist_class: result.errors.append({'stage': 'inventory', 'message': 'source_inventory_mismatch'}) return result @@ -327,64 +327,61 @@ def _check_figure(fig, *, bbox_inches=None, pad_inches=None, transparent=False, temporary.unlink(missing_ok=True) +_REPORT_STYLE = """""" + + def render_html(report: CheckReport) -> str: """Offline, script-free report for a browser or a CI artifact.""" from html import escape rows = [] for finding in report.findings: - rows.append('%s%s%s%s%s' % ( + rows.append('{}{}{}{}{}'.format( escape(finding['rule_id']), escape(finding['defect_class']), escape(str(finding['source_object_id'])), escape(finding['confidence']), - escape(', '.join('%.1f' % value for value in finding['box_pdf_points'])))) + escape(', '.join(f'{value:.1f}' for value in finding['box_pdf_points'])))) if not rows: rows.append('No finding in the assessed classes.') - unknown = ''.join('
  • %s: %s
  • ' % (escape(str(item.get('source_object_id'))), + unknown = ''.join('
  • {}: {}
  • '.format(escape(str(item.get('source_object_id'))), escape(str(item.get('reason')))) for item in report.unknown_objects) - errors = ''.join('
  • %s: %s
  • ' % (escape(str(item.get('stage'))), + errors = ''.join('
  • {}: {}
  • '.format(escape(str(item.get('stage'))), escape(str(item.get('message')))) for item in report.errors) coverage = report.coverage or {} fonts = report.font_evidence or {} - font_issues = ''.join('
  • %s
  • ' % escape(str(issue)) + font_issues = ''.join(f'
  • {escape(str(issue))}
  • ' for issue in fonts.get('issues', ())) - font_summary = ('status %s · code points %d · covered %d · missing %d · unknown %d · font files %d' - % (fonts.get('status', 'n/a'), fonts.get('codepoints', 0), - fonts.get('covered', 0), fonts.get('missing', 0), - fonts.get('unknown', 0), fonts.get('font_files', 0))) - return """ + font_summary = (f"status {fonts.get('status', 'n/a')} · code points {fonts.get('codepoints', 0)}" + f" · covered {fonts.get('covered', 0)} · missing {fonts.get('missing', 0)}" + f" · unknown {fonts.get('unknown', 0)} · font files {fonts.get('font_files', 0)}") + ratio = 'n/a' if coverage.get('ratio') is None else f"{coverage['ratio']:.3f}" + page_w, page_h = report.page_size_pt + return f""" PlotProof report - +{_REPORT_STYLE} +

    PlotProof report

    -

    %(state)s assessed: %(assessed)s — not assessed: %(missing)s

    -

    page %(page_w).1f × %(page_h).1f pt · units %(units)d · aligned coverage %(ratio)s · -input %(digest)s · PDFium %(pdfium)s

    +

    {escape(report.state)} assessed: {escape(', '.join(report.assessed))} — not assessed: {escape(', '.join(report.not_assessed))}

    +

    page {page_w:.1f} × {page_h:.1f} pt · units {report.source_units_total} · aligned coverage {ratio} · +input {escape(report.input_sha256)} · PDFium {escape(report.pdfium_version)}

    Findings

    -%(rows)s
    RuleClassSourceConfidenceBox (pt)
    -

    Unaligned / unsupported

    +{''.join(rows)} +

    Unaligned / unsupported

    D4 font cmap evidence

    -

    %(font_summary)s

    - -

    Capture and accounting limits

    +

    {escape(font_summary)}

    + +

    Capture and accounting limits

    PASS means no supported defect was found with sufficient coverage in the assessed classes. It does not mean the figure is correct, and it is not a benchmark result.

    -""" % {'state': escape(report.state), 'assessed': escape(', '.join(report.assessed)), - 'missing': escape(', '.join(report.not_assessed)), - 'page_w': report.page_size_pt[0], 'page_h': report.page_size_pt[1], - 'units': report.source_units_total, - 'ratio': 'n/a' if coverage.get('ratio') is None else '%.3f' % coverage['ratio'], - 'digest': escape(report.input_sha256), 'pdfium': escape(report.pdfium_version), - 'rows': ''.join(rows), 'unknown': unknown or '
  • none
  • ', - 'font_summary': escape(font_summary), 'font_issues': font_issues or '
  • none
  • ', - 'errors': errors or '
  • none
  • '} +""" diff --git a/plotproof/font_evidence.py b/plotproof/font_evidence.py index 95e819c..5391e4e 100644 --- a/plotproof/font_evidence.py +++ b/plotproof/font_evidence.py @@ -5,11 +5,11 @@ """ from __future__ import annotations -from dataclasses import asdict, dataclass, field +import struct +from collections.abc import Mapping, Sequence +from dataclasses import asdict, dataclass from hashlib import sha256 from pathlib import Path -import struct -from typing import Mapping, Sequence from .evidence import FontGlyph, GlyphEvidence, SaveWarning, TextRecord, integer_id from .units import AccountingError @@ -222,7 +222,7 @@ def _font_cmap(data: bytes, max_entries: int) -> tuple[_Cmap, int]: count = _u16(data, 4) if count == 0 or count > 4096 or 12 + 16 * count > len(data): raise _CmapMalformed('table directory') - cmap = None + cmap_table: tuple[int, int] | None = None maxp = None for index in range(count): entry = 12 + 16 * index @@ -231,25 +231,25 @@ def _font_cmap(data: bytes, max_entries: int) -> tuple[_Cmap, int]: if offset > len(data) or length > len(data) - offset: raise _CmapMalformed('table bounds') if tag == b'cmap': - if cmap is not None: + if cmap_table is not None: raise _CmapMalformed('duplicate cmap') - cmap = offset, length + cmap_table = offset, length elif tag == b'maxp': maxp = offset, length - if cmap is None: + if cmap_table is None: raise _CmapMalformed('cmap absent') if maxp is None or maxp[1] < 6: raise _CmapMalformed('maxp absent') num_glyphs = _u16(data, maxp[0] + 4) if num_glyphs == 0: raise _CmapMalformed('empty font') - offset, length = cmap + offset, length = cmap_table if length < 4 or _u16(data, offset) != 0: raise _CmapMalformed('cmap header') count = _u16(data, offset + 2) if count == 0 or count > 4096 or 4 + 8 * count > length: raise _CmapMalformed('cmap records') - records = {} + records: dict[tuple[int, int], int] = {} for index in range(count): platform, encoding, relative = struct.unpack_from('>HHI', data, offset + 4 + 8 * index) if relative > length - 4: @@ -371,9 +371,10 @@ def load(path: str) -> _FileEvidence: return evidence file_order.append(path) data, total_bytes, reason = _read_file(Path(path), limits, total_bytes) - if reason is not None: - issues.add(reason) - evidence = _FileEvidence(reason=reason) + if reason is not None or data is None: + issue = reason or 'font_unavailable' + issues.add(issue) + evidence = _FileEvidence(reason=issue) else: file_id = 'sha256:' + sha256(data).hexdigest() try: @@ -405,8 +406,14 @@ def load(path: str) -> _FileEvidence: fonts.append(FontGlyph(use.family, file.file_id, None, 'unknown', file.reason, use.renderer_glyph_id)) continue - glyph_id = file.cmap.get(codepoint) - if glyph_id is not None and glyph_id >= file.num_glyphs: + cmap, num_glyphs = file.cmap, file.num_glyphs + if cmap is None or num_glyphs is None: + fonts.append(FontGlyph(use.family, file.file_id, None, 'unknown', + 'font_evidence_incomplete', use.renderer_glyph_id)) + issues.add('font_evidence_incomplete') + continue + glyph_id = cmap.get(codepoint) + if glyph_id is not None and glyph_id >= num_glyphs: fonts.append(FontGlyph(use.family, file.file_id, glyph_id, 'unknown', 'renderer_cmap_mismatch', use.renderer_glyph_id)) issues.add('renderer_cmap_mismatch') diff --git a/plotproof/geometry.py b/plotproof/geometry.py index 12dcacc..a454bfc 100644 --- a/plotproof/geometry.py +++ b/plotproof/geometry.py @@ -1,10 +1,11 @@ """Unrounded binary64 rectangle geometry in bottom-left PDF coordinates.""" from __future__ import annotations +from collections.abc import Iterable from dataclasses import dataclass from fractions import Fraction from math import isfinite -from typing import Iterable, Literal +from typing import Literal def finite_number(value: float, name: str) -> float: diff --git a/plotproof/occlusion.py b/plotproof/occlusion.py index 6021064..72841f8 100644 --- a/plotproof/occlusion.py +++ b/plotproof/occlusion.py @@ -1,8 +1,8 @@ """Captured filled geometry in PDF points and conservative D2 contributions.""" from __future__ import annotations +from collections.abc import Sequence from dataclasses import dataclass -from typing import Sequence from .evidence import alpha, integer_id from .geometry import Rect, finite_number, intersections, union_area diff --git a/plotproof/pdf_input.py b/plotproof/pdf_input.py index fea64d4..f828320 100644 --- a/plotproof/pdf_input.py +++ b/plotproof/pdf_input.py @@ -2,18 +2,18 @@ from __future__ import annotations import base64 -from dataclasses import asdict, dataclass -from hashlib import sha256 import json -from math import ceil import os -from pathlib import Path import re import struct import subprocess import sys import time import zlib +from dataclasses import asdict, dataclass +from hashlib import sha256 +from math import ceil +from pathlib import Path from .evidence import PdfChar from .geometry import Rect, finite_number @@ -145,32 +145,34 @@ def _run_worker(data: bytes, limits: PdfLimits, scale: float | None) -> dict: except OSError: raise PdfReadError('worker_crash') from None output = bytearray() - pipes = (process.stdin, process.stdout, process.stderr) - counts = {process.stdout: 0, process.stderr: 0} - position = 0 view = memoryview(data) try: - for pipe in pipes: + stdin, stdout, stderr = process.stdin, process.stdout, process.stderr + if stdin is None or stdout is None or stderr is None: # Popen with PIPE always yields pipes + raise PdfReadError('worker_crash') + counts = {stdout: 0, stderr: 0} + position = 0 + for pipe in (stdin, stdout, stderr): os.set_blocking(pipe.fileno(), False) while True: if time.monotonic() >= deadline: raise PdfReadError('timeout') exited = process.poll() is not None progressed = False - if not process.stdin.closed: + if not stdin.closed: if exited or position == len(data): - process.stdin.close() + stdin.close() else: try: - sent = os.write(process.stdin.fileno(), view[position:position+65536]) + sent = os.write(stdin.fileno(), view[position:position+65536]) position += sent progressed |= sent > 0 except BlockingIOError: pass except BrokenPipeError: - process.stdin.close() + stdin.close() read_progress = False - for pipe in (process.stdout, process.stderr): + for pipe in (stdout, stderr): if pipe.closed: continue # Fair bounded draining keeps the deadline and other pipe live. @@ -186,10 +188,10 @@ def _run_worker(data: bytes, limits: PdfLimits, scale: float | None) -> dict: break read_progress = True counts[pipe] += len(chunk) - cap = limits.max_output_bytes if pipe is process.stdout else 65536 + cap = limits.max_output_bytes if pipe is stdout else 65536 if counts[pipe] > cap: raise PdfReadError('output_limit') - if pipe is process.stdout: + if pipe is stdout: output.extend(chunk) if exited and not read_progress: break @@ -201,8 +203,9 @@ def _run_worker(data: bytes, limits: PdfLimits, scale: float | None) -> dict: if process.poll() is None: process.kill() process.wait() - for pipe in pipes: - pipe.close() + for owned in (process.stdin, process.stdout, process.stderr): + if owned is not None: + owned.close() view.release() if process.returncode != 0: raise PdfReadError('worker_crash') diff --git a/plotproof/py.typed b/plotproof/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/plotproof/rules.py b/plotproof/rules.py index 18612a8..d236744 100644 --- a/plotproof/rules.py +++ b/plotproof/rules.py @@ -1,9 +1,9 @@ """D1–D4 pure evidence rules. Inputs must already have capture provenance verified.""" from __future__ import annotations +from collections.abc import Mapping, Sequence from dataclasses import dataclass, replace from itertools import combinations -from typing import Mapping, Sequence from .alignment import AlignmentResult from .evidence import GlyphEvidence @@ -47,7 +47,7 @@ def estimate_d3_work(alignment: AlignmentResult, fills: Sequence[FilledRecord] = operand_work = (n - 1) * total if n else 0 intersection_work = (total * total - squares) // 2 aligned_counts = [count for uid, count in zip( - (u.record.source_object_id for u in supported), counts) if uid in alignment.assignments] + (u.record.source_object_id for u in supported), counts, strict=False) if uid in alignment.assignments] aligned_total = sum(aligned_counts) aligned_squares = sum(count * count for count in aligned_counts) witness_work = (aligned_total * aligned_total - aligned_squares) // 2 @@ -99,7 +99,7 @@ def _finding(rule: str, unit: Unit, confidence: str, box: Rect, evidence: dict, def _d1(unit: Unit, boxes: Sequence[Rect], page: Rect) -> Finding | None: - selected = {'high': [], 'medium': []} + selected: dict[str, list[Rect]] = {'high': [], 'medium': []} for box in boxes: band = boundary_evidence(box, page) if band: @@ -129,7 +129,10 @@ def _d2(unit: Unit, boxes: Sequence[Rect], fills: Sequence[FilledRecord], page: # Unknown-opacity intersections are possible, not confirmed coverage. confirmed = tuple(Rect(*b) for artist in artists if artist['effective_alpha'] is not None for b in artist['intersection_boxes']) - return _finding('D2', unit, 'high' if high else 'medium', bounding_rect(cuts), { + bound = bounding_rect(cuts) + if bound is None: + return None + return _finding('D2', unit, 'high' if high else 'medium', bound, { 'character_boxes': tuple(b.as_tuple() for b in boxes), 'occluders': artists, 'joint_coverage': joint, 'confirmed_joint_coverage': union_area(confirmed) / area, 'coverage_has_unknown_opacity': any(a['effective_alpha'] is None for a in artists), @@ -142,8 +145,12 @@ def _d3(left: Unit, right: Unit, alignment: AlignmentResult, left_span = alignment.assignments.get(left.record.source_object_id) right_span = alignment.assignments.get(right.record.source_object_id) aligned = left_span is not None and right_span is not None - a = left_span.boxes if aligned else (left.box_pdf,) - b = right_span.boxes if aligned else (right.box_pdf,) + if left_span is not None and right_span is not None: + a = left_span.boxes + b = right_span.boxes + else: + a = (left.box_pdf,) + b = (right.box_pdf,) smaller = min(union_area(a), union_area(b)) if smaller == 0: return None @@ -162,18 +169,21 @@ def _d3(left: Unit, right: Unit, alignment: AlignmentResult, if witness: break own_backgrounds = [] + demoted = False for patch in sorted(fills, key=lambda fill: fill.source_object_id): if patch.owner_unit_id not in (left.record.source_object_id, right.record.source_object_id): continue effective = patch.facecolor_alpha * patch.artist_alpha intersects = bool(intersections(cuts, (patch.box_pdf,))) + demoted = demoted or (effective >= 0.95 and intersects) own_backgrounds.append({'owner_unit_id': patch.owner_unit_id, 'source_object_id': patch.source_object_id, 'rectangle': patch.box_pdf.as_tuple(), 'effective_alpha': effective, 'facecolor_alpha': patch.facecolor_alpha, 'artist_alpha': patch.artist_alpha, 'intersects_overlap': intersects}) - demoted = any(p['effective_alpha'] >= 0.95 and p['intersects_overlap'] for p in own_backgrounds) high = aligned and ratio >= 0.50 and witness is not None and not demoted bound = bounding_rect(cuts) + if bound is None: + return None return _finding('D3', left, 'high' if high else 'medium', bound, { 'operand_set': 'char_unions' if aligned else 'source_bboxes', 'left_boxes': tuple(box.as_tuple() for box in a), diff --git a/plotproof/units.py b/plotproof/units.py index 24e3e07..2adb2a5 100644 --- a/plotproof/units.py +++ b/plotproof/units.py @@ -1,8 +1,8 @@ """Recompute the frozen ordered source-unit predicate without trusting wrapper totals.""" from __future__ import annotations +from collections.abc import Iterable from dataclasses import dataclass -from typing import Iterable from .evidence import TextRecord from .geometry import Rect, Transform @@ -40,7 +40,10 @@ def exclusion_reason(record: TextRecord, transform: Transform, page: Rect) -> st if record.clip_box_display is not None and record.bbox_display.intersection(record.clip_box_display) is None: return 'fully_clipped' if record.tick_location is not None: - low, high = sorted(record.view_limits) + limits = record.view_limits + if limits is None: + raise AccountingError('tick location present without view limits') + low, high = sorted(limits) if not low <= record.tick_location <= high: return 'tick_outside_view' return None diff --git a/pyproject.toml b/pyproject.toml index 88ec029..ed9f21e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta" [project] name = "plotproof" version = "0.1.0a4" -description = "Source-assisted export evidence for Matplotlib figures (B1 preview: clipped/overlapping text, no font evidence)" +description = "Source-assisted export evidence for Matplotlib figures with bounded local font-cmap evidence" readme = "README.md" requires-python = ">=3.12,<3.13" license = { text = "MIT" } @@ -49,3 +49,33 @@ packages = ["plotproof"] [tool.pytest.ini_options] testpaths = ["tests"] addopts = "-ra" + +[tool.ruff] +line-length = 100 +target-version = "py312" +src = ["src"] +exclude = [".venv", ".venv-verify", ".venv-*", "build", "dist"] + +[tool.ruff.lint] +select = ["E4", "E7", "E9", "F", "I", "B", "UP"] +# E701/E702 are pure layout preferences about one-line `if x: return y` statements. +# They are not enforced by large projects either, and rewriting them would bury the +# real review signal under cosmetic churn. +ignore = ["E701", "E702"] + +[tool.ruff.lint.isort] +known-first-party = ["plotproof"] + +[tool.mypy] +python_version = "3.12" +files = ["plotproof"] +warn_unused_configs = true +warn_redundant_casts = true +warn_unused_ignores = true +no_implicit_optional = true +check_untyped_defs = true +ignore_missing_imports = true +show_error_codes = true + +[tool.setuptools.package-data] +"*" = ["py.typed"] diff --git a/spikes/b0_d1_boundary_probe.py b/spikes/b0_d1_boundary_probe.py index 28db5a5..29d9f40 100644 --- a/spikes/b0_d1_boundary_probe.py +++ b/spikes/b0_d1_boundary_probe.py @@ -25,7 +25,7 @@ import json import platform import tempfile -from datetime import datetime, timezone +from datetime import UTC, datetime from importlib.metadata import version as dist_version from pathlib import Path @@ -456,7 +456,7 @@ def main() -> int: record = { "schema_version": 1, "probe": "b0_d1_boundary_predicate", - "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "generated_at": datetime.now(UTC).isoformat(timespec="seconds"), "script": project_path(Path(__file__).resolve()), "script_sha256": script_hash, "figure_spec": FIGURE_SPEC, diff --git a/spikes/b0_missing_glyph_alignment_probe.py b/spikes/b0_missing_glyph_alignment_probe.py index e1defc1..8d73852 100644 --- a/spikes/b0_missing_glyph_alignment_probe.py +++ b/spikes/b0_missing_glyph_alignment_probe.py @@ -32,7 +32,7 @@ import tempfile import unicodedata import warnings -from datetime import datetime, timezone +from datetime import UTC, datetime from importlib.metadata import version as dist_version from pathlib import Path @@ -605,7 +605,7 @@ def main() -> int: record = { "schema_version": 1, "probe": "b0_missing_glyph_alignment", - "generated_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "generated_at": datetime.now(UTC).isoformat(timespec="seconds"), "script": project_path(Path(__file__).resolve()), "script_sha256": script_hash, "figure_spec": FIGURE_SPEC, diff --git a/spikes/b0_pdfium_spike.py b/spikes/b0_pdfium_spike.py index 22e4fe5..15d944f 100644 --- a/spikes/b0_pdfium_spike.py +++ b/spikes/b0_pdfium_spike.py @@ -23,8 +23,9 @@ import sys import tempfile import warnings -from datetime import datetime, timezone -from importlib.metadata import distribution, version as dist_version +from datetime import UTC, datetime +from importlib.metadata import distribution +from importlib.metadata import version as dist_version from pathlib import Path import matplotlib @@ -306,7 +307,7 @@ def main() -> int: script_hash = sha256_file(Path(__file__).resolve()) record: dict[str, object] = { "spike_version": 2, - "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "timestamp_utc": datetime.now(UTC).isoformat(), "python": sys.version, "platform": platform.platform(), "backend": matplotlib.get_backend(), diff --git a/spikes/b0_validator_bypass_repro.py b/spikes/b0_validator_bypass_repro.py index ff7306d..b8d0068 100644 --- a/spikes/b0_validator_bypass_repro.py +++ b/spikes/b0_validator_bypass_repro.py @@ -39,7 +39,7 @@ import subprocess import sys import tempfile -from datetime import datetime, timezone +from datetime import UTC, datetime from pathlib import Path ROOT = Path(__file__).resolve().parents[1] @@ -155,7 +155,7 @@ def main() -> int: record: dict[str, object] = { "spike_version": 1, - "timestamp_utc": datetime.now(timezone.utc).isoformat(), + "timestamp_utc": datetime.now(UTC).isoformat(), "git_head": git_head(), "old_validator_sha256": sha256_bytes(old_validator), "old_manifest_sha256": sha256_bytes(old_manifest_bytes), diff --git a/spikes/b1_capture_semantics_probe.py b/spikes/b1_capture_semantics_probe.py index f3d3192..4f9e44d 100644 --- a/spikes/b1_capture_semantics_probe.py +++ b/spikes/b1_capture_semantics_probe.py @@ -8,24 +8,23 @@ """ from __future__ import annotations -from datetime import datetime, timezone -from hashlib import sha256 -from io import BytesIO -from pathlib import Path import json import platform import re +from datetime import UTC, datetime +from hashlib import sha256 +from io import BytesIO +from pathlib import Path from threading import Lock import matplotlib as mpl +import numpy as np +import PIL +import pypdfium2 as pdfium from matplotlib import ft2font from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure from matplotlib.patches import Rectangle -import numpy as np -import PIL -import pypdfium2 as pdfium - _PROBE_LOCK = Lock() _PAGE_TOLERANCE_PT = 1e-4 # PDFium reports float-sized page dimensions. @@ -182,8 +181,8 @@ def _bbox_case(*, constrained: bool) -> dict: pdf = _inspect_pdf(data) pre_prediction = [(dimension + 2 * 0.1) * 72 for dimension in pre[2:]] save_prediction = [(dimension + 2 * 0.1) * 72 for dimension in saved[2:]] - pre_error = [a - b for a, b in zip(pdf["page_size_pt"], pre_prediction)] - save_error = [a - b for a, b in zip(pdf["page_size_pt"], save_prediction)] + pre_error = [a - b for a, b in zip(pdf["page_size_pt"], pre_prediction, strict=False)] + save_error = [a - b for a, b in zip(pdf["page_size_pt"], save_prediction, strict=False)] pre_matches = all(abs(error) <= _PAGE_TOLERANCE_PT for error in pre_error) save_matches = all(abs(error) <= _PAGE_TOLERANCE_PT for error in save_error) classification = "inconclusive" @@ -210,8 +209,8 @@ def _bbox_case(*, constrained: bool) -> dict: "pdf": pdf, "interpretation": { "classification": classification, - "save_minus_pre_bounds_inches": [a - b for a, b in zip(saved, pre)], - "bounds_agree_within_1e_9_inches": all(abs(a - b) <= 1e-9 for a, b in zip(saved, pre)), + "save_minus_pre_bounds_inches": [a - b for a, b in zip(saved, pre, strict=False)], + "bounds_agree_within_1e_9_inches": all(abs(a - b) <= 1e-9 for a, b in zip(saved, pre, strict=False)), "pre_prediction_error_pt": pre_error, "save_prediction_error_pt": save_error, "pre_prediction_matches_pdf": pre_matches, @@ -252,7 +251,7 @@ def run_probe() -> dict: return { "schema_version": 1, "classification": "capture_contract_counterexamples", - "generated_at": datetime.now(timezone.utc).isoformat(), + "generated_at": datetime.now(UTC).isoformat(), "script_sha256": sha256(Path(__file__).resolve().read_bytes()).hexdigest(), "versions": { "python": platform.python_version(), @@ -343,7 +342,7 @@ def _assert_premises_and_controls(report: dict) -> None: pdf = case["pdf"] assert pdf["page_count"] == 1 and pdf["rotation_degrees"] == 0 assert len(pdf["page_size_pt"]) == 2 and len(saved["bounds_inches"]) == 4 - for actual, extent in zip(pdf["page_size_pt"], saved["bounds_inches"][2:]): + for actual, extent in zip(pdf["page_size_pt"], saved["bounds_inches"][2:], strict=False): assert abs(actual - (extent + 0.2) * 72) <= 1e-4 diff --git a/tests/_core_fixtures.py b/tests/_core_fixtures.py index e9c14e5..1b45634 100644 --- a/tests/_core_fixtures.py +++ b/tests/_core_fixtures.py @@ -1,8 +1,8 @@ """Synthetic, hand-positioned facts; never benchmark or holdout fixtures.""" -from importlib import import_module, util from dataclasses import replace +from importlib import import_module, util -from plotproof.geometry import Rect, Transform +from plotproof.geometry import Rect, Transform # noqa: F401 (re-exported for sibling tests) def module(name): @@ -37,5 +37,5 @@ def glyph_evidence(codepoint=0x20000, glyph_ids=(None,), families=('Test Sans',) f'Glyph {codepoint} (test character) missing from font(s) Test Sans.'),) return e.GlyphEvidence(codepoint, tuple( e.FontGlyph(family, family + '.ttf', glyph_id) - for family, glyph_id in zip(families, glyph_ids) + for family, glyph_id in zip(families, glyph_ids, strict=False) ), tuple(warnings)) diff --git a/tests/test_alignment.py b/tests/test_alignment.py index 70abc8e..ce3a91d 100644 --- a/tests/test_alignment.py +++ b/tests/test_alignment.py @@ -2,8 +2,7 @@ from itertools import permutations import pytest - -from _core_fixtures import module, text_record, pdf_chars, glyph_evidence, Rect, Transform +from _core_fixtures import Rect, Transform, glyph_evidence, module, pdf_chars, text_record def align(records, chars, glyphs=None, dpi=72): diff --git a/tests/test_capture.py b/tests/test_capture.py index 58be1f6..8d862eb 100644 --- a/tests/test_capture.py +++ b/tests/test_capture.py @@ -1,15 +1,13 @@ -from dataclasses import asdict from hashlib import sha256 from importlib import import_module, util from io import BytesIO -import json import matplotlib as mpl +import pytest from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.backends.backend_pdf import RendererPdf from matplotlib.figure import Figure from matplotlib.patches import Rectangle -import pytest from plotproof.pdf_input import read_pdf @@ -143,7 +141,7 @@ def test_save_warning_scope_and_non_bmp_capture(): fig=figure();fig.text(.2,.4,'Missing𠀀') with warnings.catch_warnings(record=True) as outside: warnings.simplefilter('always') - warnings.warn('outside save') + warnings.warn('outside save', stacklevel=2) c=api().capture_pdf(fig) assert any(str(w.message)=='outside save' for w in outside) assert any('131072' in w.message for w in c.warnings) diff --git a/tests/test_capture_isolation.py b/tests/test_capture_isolation.py index 7368f2d..45c14dc 100644 --- a/tests/test_capture_isolation.py +++ b/tests/test_capture_isolation.py @@ -2,15 +2,12 @@ from concurrent.futures import ThreadPoolExecutor from io import BytesIO +import matplotlib as mpl +import pytest from matplotlib.artist import Artist -from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.backends.backend_pdf import RendererPdf -from matplotlib.figure import Figure from matplotlib.table import Table from matplotlib.text import Text -import matplotlib as mpl -import pytest - from test_capture import api, figure @@ -50,7 +47,7 @@ def test_table_cell_text_is_in_inventory_and_has_emitted_identity(): def test_annotated_text_box_excludes_arrow_union(): fig=figure();ax=fig.subplots() - ann=ax.annotate('label',xy=(.8,.8),xytext=(.2,.2),arrowprops={'arrowstyle':'->'}) + ax.annotate('label',xy=(.8,.8),xytext=(.2,.2),arrowprops={'arrowstyle':'->'}) c=api().capture_pdf(fig) e=next(e for e in c.events if e.text=='label') # The far arrow would make a ~130pt wide box; the actual text is much narrower. @@ -189,8 +186,8 @@ def deny(*args,**kwargs): @pytest.mark.parametrize('feature,issue', [ ('effects','path_effect_capture_pending'),('clip','nonrectangular_clip_capture_pending')]) def test_dynamic_coverage_features_cannot_be_silently_accepted(feature,issue): - from matplotlib.patheffects import Normal from matplotlib.patches import Circle + from matplotlib.patheffects import Normal fig=figure();text=fig.text(.2,.4,'dynamic feature') def change(event): if fig.canvas.is_saving(): diff --git a/tests/test_capture_pixels.py b/tests/test_capture_pixels.py index 582bc6a..cd8bac3 100644 --- a/tests/test_capture_pixels.py +++ b/tests/test_capture_pixels.py @@ -1,13 +1,12 @@ """Cross-check captured alpha and crop against a separate real PDFium process.""" -from hashlib import sha256 from io import BytesIO -from PIL import Image -from matplotlib.patches import Rectangle import pytest +from matplotlib.patches import Rectangle +from PIL import Image +from test_capture import api, figure from plotproof.pdf_input import read_pdf -from test_capture import api, figure @pytest.mark.parametrize('alpha,gray', [(None,102),(.6,102),(1,0)]) diff --git a/tests/test_capture_semantics.py b/tests/test_capture_semantics.py index f26a0c3..4f30304 100644 --- a/tests/test_capture_semantics.py +++ b/tests/test_capture_semantics.py @@ -5,20 +5,19 @@ """ from __future__ import annotations +import importlib.util +import json +import re from copy import deepcopy from datetime import datetime from functools import lru_cache from hashlib import sha256 -import importlib.util -import json from pathlib import Path -import re import matplotlib as mpl +import pytest from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure -import pytest - ROOT = Path(__file__).resolve().parents[1] SCRIPT = ROOT / "spikes" / "b1_capture_semantics_probe.py" @@ -138,15 +137,15 @@ def test_bbox_predictions_use_recorded_save_call_not_a_post_save_measurement(cas assert case["pre_draw_predicted_page_size_pt"] == pytest.approx(expected_pre) assert case["save_predicted_page_size_pt"] == pytest.approx(expected_save) assert actual == pytest.approx(expected_save, abs=1e-4) - pre_matches = all(abs(a - p) <= 1e-4 for a, p in zip(actual, expected_pre)) + pre_matches = all(abs(a - p) <= 1e-4 for a, p in zip(actual, expected_pre, strict=False)) assert case["interpretation"]["pre_prediction_matches_pdf"] is pre_matches assert case["interpretation"]["save_prediction_matches_pdf"] is True assert case["interpretation"]["classification"] == ("control_agrees" if pre_matches else "counterexample") assert case["interpretation"]["pre_prediction_error_pt"] == pytest.approx( - [a - p for a, p in zip(actual, expected_pre)] + [a - p for a, p in zip(actual, expected_pre, strict=False)] ) assert case["interpretation"]["save_minus_pre_bounds_inches"] == pytest.approx( - [a - b for a, b in zip(saved, pre)] + [a - b for a, b in zip(saved, pre, strict=False)] ) diff --git a/tests/test_cli_errors.py b/tests/test_cli_errors.py index ff8951a..9160c48 100644 --- a/tests/test_cli_errors.py +++ b/tests/test_cli_errors.py @@ -1,12 +1,12 @@ """The CLI boundary must fail closed without leaking user diagnostics.""" import json import os -from pathlib import Path import subprocess import sys +from pathlib import Path +from unittest.mock import patch import pytest -from unittest.mock import patch from plotproof import cli from plotproof.export import CheckError @@ -46,8 +46,8 @@ def test_missing_factory_has_stable_factory_error(tmp_path, capsys): def test_user_exception_and_system_exit_are_structured(tmp_path, capsys, phase, exception): module = tmp_path / 'figure.py' module.write_text( - 'def figure():\n raise %s\n' % exception if phase == 'factory' else - 'raise %s\n' % exception, encoding='utf-8') + f'def figure():\n raise {exception}\n' if phase == 'factory' else + f'raise {exception}\n', encoding='utf-8') code = 'FACTORY_FAILED' if phase == 'factory' else 'IMPORT_FAILED' assert_error(invoke(None, capsys, module), code) diff --git a/tests/test_complexity_budget.py b/tests/test_complexity_budget.py index 086b203..b7e6f46 100644 --- a/tests/test_complexity_budget.py +++ b/tests/test_complexity_budget.py @@ -3,10 +3,10 @@ from dataclasses import replace import pytest +from _core_fixtures import Rect, Transform, module, pdf_chars, text_record +from test_export import bars, figure -from _core_fixtures import module, text_record, pdf_chars, Rect, Transform from plotproof import rules -from test_export import bars, figure from plotproof.export import check_figure @@ -88,7 +88,7 @@ def test_union_sort_work_alone_cannot_exceed_declared_budget(monkeypatch): records = (text_record(1, 'aaaaaaaaaa', Rect(10, 10, 110, 20)), text_record(2, 'bbbbbbbbbb', Rect(210, 10, 310, 20))) chars = pdf_chars('aaaaaaaaaa', x=10) + pdf_chars('bbbbbbbbbb', x=210) - alignment = module('alignment').align_units( + module('alignment').align_units( module('units').enumerate_units(records, Transform(72, 0, 0), Rect(0, 0, 1000, 1000), 2), chars, {}) sort_only = 2 * rules._union_sort_work(10) + rules._union_sort_work(100) diff --git a/tests/test_core.py b/tests/test_core.py index 28455bf..0641e3f 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1,9 +1,8 @@ -from dataclasses import replace import json +from dataclasses import replace import pytest - -from _core_fixtures import module, text_record, pdf_chars, glyph_evidence, Rect, Transform +from _core_fixtures import Rect, Transform, glyph_evidence, module, pdf_chars, text_record from test_rules import occluder diff --git a/tests/test_core_mutations.py b/tests/test_core_mutations.py index 2815ab4..5b98b60 100644 --- a/tests/test_core_mutations.py +++ b/tests/test_core_mutations.py @@ -2,11 +2,11 @@ from __future__ import annotations import os -from pathlib import Path import shutil import subprocess import sys import xml.etree.ElementTree as ET +from pathlib import Path import pytest @@ -43,8 +43,8 @@ ('no_background_demotion', 'rules', (('and not demoted', 'and True'),), 'test_rules.py::test_d3_own_opaque_background_demotes_not_suppresses'), ('source_box_for_ink', 'rules', ( - ('a = left_span.boxes if aligned else (left.box_pdf,)', 'a = (left.box_pdf,)'), - ('b = right_span.boxes if aligned else (right.box_pdf,)', 'b = (right.box_pdf,)'),), + ('a = left_span.boxes', 'a = (left.box_pdf,)'), + ('b = right_span.boxes', 'b = (right.box_pdf,)'),), 'test_rules.py::test_d3_uses_unions_not_outer_bboxes'), ('cross_confidence_suppression', 'rules', ( ('higher.confidence == finding.confidence and PRIORITY', 'PRIORITY'),), diff --git a/tests/test_core_pdf_integration.py b/tests/test_core_pdf_integration.py index 81577b3..c52d68a 100644 --- a/tests/test_core_pdf_integration.py +++ b/tests/test_core_pdf_integration.py @@ -7,22 +7,22 @@ """ from __future__ import annotations +import warnings from dataclasses import dataclass from hashlib import sha256 from pathlib import Path from statistics import median -import warnings -from fontTools.ttLib import TTFont import matplotlib as mpl +import pypdfium2 as pdfium +import pypdfium2.raw as pdfium_raw +import pytest +from fontTools.ttLib import TTFont from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.colors import to_rgba from matplotlib.figure import Figure from matplotlib.font_manager import FontProperties, findfont from matplotlib.patches import Rectangle -import pypdfium2 as pdfium -import pypdfium2.raw as pdfium_raw -import pytest from plotproof.alignment import AlignmentResult, align_units from plotproof.core import CoreResult, check_core @@ -31,7 +31,6 @@ from plotproof.occlusion import FilledRecord from plotproof.units import enumerate_units - TRANSFORM = Transform(100, 0, 0) @@ -163,7 +162,7 @@ def draw(renderer): assert fig.dpi == 100 records = [] - for uid, (artist, box) in enumerate(zip(texts, text_boxes), start=1): + for uid, (artist, box) in enumerate(zip(texts, text_boxes, strict=False), start=1): color_alpha = to_rgba(artist.get_color())[3] artist_alpha = artist.get_alpha() artist_alpha = 1.0 if artist_alpha is None else artist_alpha diff --git a/tests/test_export.py b/tests/test_export.py index f579de2..5e6d08d 100644 --- a/tests/test_export.py +++ b/tests/test_export.py @@ -1,11 +1,10 @@ """Assembly-level checks: a real save, the real reader and the frozen core.""" import json -from pathlib import Path import matplotlib as mpl +import pytest from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure -import pytest from plotproof.cli import main from plotproof.export import CheckError, check_figure, render_html diff --git a/tests/test_font_evidence.py b/tests/test_font_evidence.py index 8bad56f..5d9aebe 100644 --- a/tests/test_font_evidence.py +++ b/tests/test_font_evidence.py @@ -1,21 +1,20 @@ """Local cmap evidence from the fonts selected by the real PDF text renderer.""" from __future__ import annotations -from dataclasses import replace +import struct from hashlib import sha256 from importlib import import_module, util from pathlib import Path -import struct +import matplotlib as mpl +import pytest +from _core_fixtures import Rect, Transform, pdf_chars, text_record from fontTools import subset from fontTools.ttLib import TTFont -import matplotlib as mpl from matplotlib.backends.backend_agg import FigureCanvasAgg from matplotlib.figure import Figure from matplotlib.font_manager import FontProperties, findfont -import pytest -from _core_fixtures import module, text_record, pdf_chars, Rect, Transform from plotproof.capture import capture_pdf from plotproof.core import check_core from plotproof.evidence import SaveWarning diff --git a/tests/test_geometry.py b/tests/test_geometry.py index 79fd4d5..59905d6 100644 --- a/tests/test_geometry.py +++ b/tests/test_geometry.py @@ -1,7 +1,7 @@ """Independent numeric oracles: no expected value uses production geometry.""" -from importlib import import_module, util import math import random +from importlib import import_module, util import pytest @@ -80,7 +80,7 @@ def test_union_fractional_randomized_against_coordinate_cell_oracle(): xs = sorted({x for b in boxes for x in (b.x0, b.x1)}) ys = sorted({y for b in boxes for y in (b.y0, b.y1)}) expected = math.fsum((x1 - x0) * (y1 - y0) - for x0, x1 in zip(xs, xs[1:]) for y0, y1 in zip(ys, ys[1:]) + for x0, x1 in zip(xs, xs[1:], strict=False) for y0, y1 in zip(ys, ys[1:], strict=False) if any(b.x0 <= x0 and x1 <= b.x1 and b.y0 <= y0 and y1 <= b.y1 for b in boxes)) assert g.union_area(boxes + boxes[:3]) == pytest.approx(expected, rel=1e-14, abs=1e-14) diff --git a/tests/test_holdout_runner.py b/tests/test_holdout_runner.py new file mode 100644 index 0000000..e319dcb --- /dev/null +++ b/tests/test_holdout_runner.py @@ -0,0 +1,442 @@ +"""Contract tests for the deterministic sealed-holdout command line tools.""" + +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +import pytest +from benchmark import generate_holdout as generator +from benchmark import holdout +from benchmark import run_holdout as runner + +ROOT = Path(__file__).resolve().parents[1] + + +def run_tool(name: str, *args: str) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, str(ROOT / "benchmark" / name), *args], + cwd=ROOT, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + env=dict(os.environ, PYTHONIOENCODING="utf-8"), + timeout=30, + ) + + +@pytest.mark.parametrize("name", ["generate_holdout.py", "run_holdout.py"]) +def test_holdout_tool_exposes_help(name: str) -> None: + result = run_tool(name, "--help") + assert result.returncode == 0, result.stderr + assert "holdout" in result.stdout.lower() + + +def test_runner_checks_platform_before_reading_a_seal(tmp_path: Path) -> None: + result = run_tool("run_holdout.py", "--holdout-dir", str(tmp_path)) + assert result.returncode == 2 + if os.name == "nt": + assert '"status": "ERROR"' in result.stdout + assert "seal.json" in result.stdout + else: + assert "Windows" in result.stdout + + +def test_generator_rejects_an_existing_seal_without_force(tmp_path: Path) -> None: + (tmp_path / "seal.json").write_text("{}\n", encoding="utf-8") + result = run_tool("generate_holdout.py", "--generate-only", "--output-dir", str(tmp_path)) + assert result.returncode == 2 + assert "already exists" in result.stdout + + +def test_generator_help_exposes_two_phase_review_sealing() -> None: + result = run_tool("generate_holdout.py", "--help") + assert "--generate-only" in result.stdout + assert "--seal-reviewed" in result.stdout + assert "--reviewed-by" in result.stdout + + +def test_seal_requires_an_explicit_nonempty_reviewer(tmp_path: Path) -> None: + + holdout.write_json(tmp_path / "review.json", []) + generation = { + "schema_version": 1, + "generated_at_utc": "2026-11-30T00:00:00+00:00", + "revision": "test-revision", + "manifest_sha256": holdout.sha256_file(ROOT / "benchmark" / "manifest.json"), + "labels_sha256": "0" * 64, + "label_review_log_sha256": holdout.sha256_file(tmp_path / "review.json"), + "label_review_status": "machine_generated_unreviewed", + "code_sha256": {}, + "environment": dict(holdout.EXPECTED_ENVIRONMENT), + "samples": [], + "protocol_limitations": [], + } + holdout.write_json(tmp_path / "generation.json", generation) + holdout.write_json(tmp_path / "review.json", []) + with pytest.raises(holdout.HoldoutError, match="reviewer"): + generator.seal_existing(tmp_path, tmp_path / "review.json", " ") + + +def test_holdout_plan_is_exactly_the_frozen_114_samples() -> None: + import json + + manifest = json.loads((ROOT / "benchmark" / "manifest.json").read_text(encoding="utf-8")) + sample_ids = holdout.holdout_sample_ids(manifest) + assert len(sample_ids) == 114 + assert len(set(sample_ids)) == 114 + assert sample_ids == sorted(sample_ids) + assert sample_ids[0] == "H01.clean.s1" + assert sample_ids[-1] == "L12.counterexample" + + +def test_wilson_interval_matches_known_binomial_bounds() -> None: + low, high = holdout.wilson_interval(1, 2) + assert low == pytest.approx(0.09452865480086614) + assert high == pytest.approx(0.9054713451991339) + assert holdout.wilson_interval(0, 0) is None + + +def test_summary_publishes_class_metrics_false_pass_and_rates() -> None: + labels = [ + {"sample_id": "a", "expected_state": "PASS", "defect_class": None}, + {"sample_id": "b", "expected_state": "FAIL", "defect_class": "clipped_text", + "source_object_id": 1, "related_source_object_id": None}, + {"sample_id": "c", "expected_state": "FAIL", "defect_class": "occluded_text", + "source_object_id": 1, "related_source_object_id": None}, + {"sample_id": "d", "expected_state": "FAIL", "defect_class": "overlapping_text", + "source_object_id": 1, "related_source_object_id": None}, + ] + outcomes = [ + {"sample_id": "a", "state": "PASS", "findings": []}, + {"sample_id": "b", "state": "FAIL", "findings": [ + {"defect_class": "clipped_text", "source_object_id": 1, + "related_source_object_id": None, "confidence": "high", "rule_id": "D1", + "box_pdf_points": [0, 0, 1, 1]}, + ]}, + {"sample_id": "c", "state": "UNKNOWN", "findings": []}, + {"sample_id": "d", "state": "PASS", "findings": [ + {"defect_class": "clipped_text", "source_object_id": 2, + "related_source_object_id": None, "confidence": "high", "rule_id": "D1", + "box_pdf_points": [0, 0, 1, 1]}, + ]}, + ] + summary = holdout.summarize_outcomes(labels, outcomes) + pooled = summary["pooled"] + assert pooled["precision"]["estimate"] == pytest.approx(0.5) + assert pooled["recall"]["estimate"] == pytest.approx(1 / 3) + assert pooled["false_pass_rate"]["estimate"] == pytest.approx(1 / 3) + assert pooled["unknown_rate"]["estimate"] == pytest.approx(0.25) + assert pooled["error_rate"]["estimate"] == 0.0 + assert summary["per_class"]["clipped_text"]["precision"]["numerator"] == 1 + assert summary["per_class"]["clipped_text"]["precision"]["denominator"] == 2 + assert summary["per_class"]["occluded_text"]["recall"]["estimate"] == 0.0 + assert summary["per_class"]["overlapping_text"]["precision"]["estimate"] is None + + +def test_summary_reports_coverage_and_clean_pass_gate_inputs() -> None: + labels = [{"sample_id": "a", "expected_state": "PASS", "defect_class": None}] + outcomes = [{"sample_id": "a", "state": "PASS", "findings": [], + "report": {"coverage": {"ratio": 0.95}, "source_units_total": 20}}] + summary = holdout.summarize_outcomes(labels, outcomes) + assert summary["pooled"]["alignment_coverage"]["estimate"] == pytest.approx(0.95) + assert summary["pooled"]["alignment_coverage"]["denominator"] == 1 + assert summary["pooled"]["zero_unit_samples"] == 0 + assert summary["pooled"]["clean_or_legal_pass_count"] == 1 + + +def test_pinned_environment_rejects_wrong_platform_and_versions() -> None: + environment = dict(holdout.EXPECTED_ENVIRONMENT) + holdout.validate_environment(environment, platform_name="win32") + with pytest.raises(holdout.HoldoutError, match="Windows"): + holdout.validate_environment(environment, platform_name="linux") + changed = dict(environment, matplotlib="3.10.7") + with pytest.raises(holdout.HoldoutError, match="matplotlib"): + holdout.validate_environment(changed, platform_name="win32") + + +def test_seal_validation_detects_pdf_tampering_and_label_changes(tmp_path: Path) -> None: + import json + + manifest = holdout.load_manifest() + sample_ids = holdout.holdout_sample_ids(manifest) + sample_id = sample_ids[0] + (tmp_path / "samples").mkdir() + samples = [] + labels = [] + for item_id in sample_ids: + pdf = tmp_path / "samples" / f"{item_id}.pdf" + source = tmp_path / "samples" / f"{item_id}.source.json" + pdf.write_bytes(b"%PDF-test") + source.write_text("{}\n", encoding="utf-8") + samples.append({ + "id": item_id, + "pdf": f"samples/{item_id}.pdf", + "sha256": holdout.sha256_file(pdf), + "size": pdf.stat().st_size, + "source": f"samples/{item_id}.source.json", + "source_sha256": holdout.sha256_file(source), + }) + labels.append({"sample_id": item_id, "expected_state": "PASS", "defect_class": None}) + labels_path = tmp_path / "labels.json" + labels_path.write_text(json.dumps(labels), encoding="utf-8") + review_log_path = tmp_path / "label_review_log.json" + review_log_path.write_text("[]\n", encoding="utf-8") + manifest_hash = holdout.sha256_file(holdout.MANIFEST_PATH) + code = {holdout.MANIFEST_KEY: manifest_hash} + seal = { + "schema_version": 1, + "manifest_sha256": manifest_hash, + "labels_sha256": holdout.sha256_file(labels_path), + "label_review_log_sha256": holdout.sha256_file(review_log_path), + "label_review_status": "human_reviewed", + "code_sha256": code, + "environment": dict(holdout.EXPECTED_ENVIRONMENT), + "samples": samples, + } + holdout.validate_seal(seal, tmp_path, manifest, code, + dict(holdout.EXPECTED_ENVIRONMENT), platform_name="win32") + assert "expected_state" not in json.dumps(seal) + generation = { + "schema_version": 1, + "generated_at_utc": "2026-11-30T00:00:00+00:00", + "revision": "test-revision", + "manifest_sha256": manifest_hash, + "labels_sha256": holdout.sha256_file(labels_path), + "label_review_log_sha256": holdout.sha256_file(review_log_path), + "label_review_status": "machine_generated_unreviewed", + "code_sha256": holdout.code_fingerprint(), + "environment": dict(holdout.EXPECTED_ENVIRONMENT), + "samples": samples, + "protocol_limitations": [], + } + write_json = holdout.write_json + write_json(tmp_path / "generation.json", generation) + review_log_path.write_text(json.dumps([{ + "sample_id": sample_id, "old_label_sha256": "a" * 64, "new_label_sha256": "b" * 64, + "reason_code": "reviewed", "at_utc": "2026-11-30T00:00:00Z", + }]), encoding="utf-8") + reviewed_seal = generator.seal_existing(tmp_path, review_log_path, "test-reviewer") + assert reviewed_seal["label_review_status"] == "human_reviewed" + assert reviewed_seal["reviewed_by"] == "test-reviewer" + assert (tmp_path / "seal.json").is_file() + unreviewed = dict(seal, label_review_status="machine_generated_unreviewed") + with pytest.raises(holdout.HoldoutError, match="human"): + holdout.validate_seal(unreviewed, tmp_path, manifest, code, + dict(holdout.EXPECTED_ENVIRONMENT), platform_name="win32") + (tmp_path / "samples" / f"{sample_id}.pdf").write_bytes(b"%PDF-evil") + with pytest.raises(holdout.HoldoutError, match="sha256"): + holdout.validate_seal(seal, tmp_path, manifest, code, + dict(holdout.EXPECTED_ENVIRONMENT), platform_name="win32") + (tmp_path / "samples" / f"{sample_id}.pdf").write_bytes(b"%PDF-test") + review_log_path.write_text('[{"sample_id": "tampered"}]\n', encoding="utf-8") + with pytest.raises(holdout.HoldoutError, match="label review"): + holdout.validate_seal(seal, tmp_path, manifest, code, + dict(holdout.EXPECTED_ENVIRONMENT), platform_name="win32") + review_log_path.write_text("[]\n", encoding="utf-8") + labels_path.write_text("[]\n", encoding="utf-8") + with pytest.raises(holdout.HoldoutError, match="labels"): + holdout.validate_seal(seal, tmp_path, manifest, code, + dict(holdout.EXPECTED_ENVIRONMENT), platform_name="win32") + + +def _frozen_manifest() -> dict: + import json + + return json.loads((ROOT / "benchmark" / "manifest.json").read_text(encoding="utf-8")) + + +def _sample(manifest: dict, sample_id: str) -> dict: + return next(item for item in manifest["samples"] if item["id"] == sample_id) + + +def test_generator_builds_each_variant_from_its_frozen_record() -> None: + manifest = _frozen_manifest() + for sample_id in ("D01.clean.s1", "D01.clip.s1", "D01.occlude.s1", + "D01.overlap.s1", "D01.missing_glyph.s1"): + built = generator.build_sample(_sample(manifest, sample_id), manifest) + assert built.figure.get_size_inches().tolist() == [10.0, 6.0] + assert built.target.get_text() + assert built.target.get_rotation() == 0 + if ".missing_glyph." in sample_id: + assert built.target.get_text().count("\U00020000") == 1 + generator.close_built(built) + + +@pytest.mark.skipif(os.environ.get("PLOTPROOF_HOLDOUT_SMOKE") != "1", + reason="opening a holdout fixture is a separate logged smoke procedure") +def test_generator_pins_tight_bbox_counterexample() -> None: + built = generator.build_sample(_sample(_frozen_manifest(), "L11.counterexample"), + _frozen_manifest()) + assert built.save_kwargs == {"bbox_inches": "tight", "pad_inches": 0.1, + "transparent": False} + generator.close_built(built) + + +def test_every_frozen_dev_figure_can_be_built() -> None: + manifest = _frozen_manifest() + sample_ids = sorted(item["id"] for item in manifest["samples"] if item["split"] == "dev") + assert len(sample_ids) == 114 + for sample_id in sample_ids: + built = generator.build_sample(_sample(manifest, sample_id), manifest) + assert built.figure.axes + generator.close_built(built) + + +@pytest.mark.skipif(os.environ.get("PLOTPROOF_HOLDOUT_SMOKE") != "1", + reason="opening holdout fixtures is a separate logged smoke procedure") +def test_every_frozen_holdout_figure_can_be_built() -> None: + manifest = _frozen_manifest() + for sample_id in holdout.holdout_sample_ids(manifest): + built = generator.build_sample(_sample(manifest, sample_id), manifest) + assert built.figure.axes + generator.close_built(built) + + +@pytest.mark.parametrize("variant", ["clip", "occlude", "overlap", "missing_glyph"]) +def test_each_defect_injection_is_reachable_before_sealing(tmp_path: Path, variant: str) -> None: + manifest = _frozen_manifest() + generated = generator.generate_one(_sample(manifest, f"D01.{variant}.s1"), + manifest, tmp_path) + assert generated["label"]["defect_class"] is not None + assert generated["label"]["source_object_id"] is not None + + +def test_generation_writes_hashable_pdf_and_source_without_detector_report(tmp_path: Path) -> None: + sample = _sample(_frozen_manifest(), "D01.clean.s1") + first = generator.generate_one(sample, _frozen_manifest(), tmp_path) + second = generator.generate_one(sample, _frozen_manifest(), tmp_path) + assert first["sha256"] == second["sha256"] + assert first["source_sha256"] == second["source_sha256"] + assert first["label"]["expected_state"] == "PASS" + source = __import__("json").loads( + (tmp_path / first["source"]).read_text(encoding="utf-8")) + assert source["sample_id"] == sample["id"] + assert source["capture_revision"] == "CA1" + assert not (tmp_path / "report.json").exists() + + +def test_worker_returns_a_hash_bound_raw_outcome(tmp_path: Path) -> None: + manifest = _frozen_manifest() + sample = _sample(manifest, "D01.clean.s1") + generated = generator.generate_one(sample, manifest, tmp_path) + outcome = runner.evaluate_sample(sample, generated["sha256"]) + assert outcome["sample_id"] == sample["id"] + assert outcome["input_sha256"] == generated["sha256"] + assert outcome["state"] in {"PASS", "FAIL", "UNKNOWN", "ERROR"} + assert "report" in outcome + assert outcome["elapsed_ms"] >= 0 + + +def test_worker_turns_a_sealed_hash_mismatch_into_error() -> None: + sample = _sample(_frozen_manifest(), "D01.clean.s1") + outcome = runner.evaluate_sample(sample, "0" * 64) + assert outcome["state"] == "ERROR" + assert outcome["error"]["code"] == "SEALED_INPUT_MISMATCH" + + +def test_worker_builds_from_a_label_free_sample_record(monkeypatch: pytest.MonkeyPatch) -> None: + sample = _sample(_frozen_manifest(), "D01.clean.s1") + seen = {} + built = generator.BuiltSample(object(), object(), None, {}, {}) + + def capture_build(candidate, manifest): + seen.update(candidate) + return built + + monkeypatch.setattr(generator, "build_sample", capture_build) + monkeypatch.setattr(runner, "build_sample", capture_build) + monkeypatch.setattr(runner, "_load_manifest", lambda: {"samples": [sample]}) + monkeypatch.setattr(runner, "close_built", lambda value: None) + monkeypatch.setattr("plotproof.check_figure", lambda *args, **kwargs: (_ for _ in ()).throw( + runner.CheckError("stop-after-build"))) + outcome = runner.evaluate_sample(sample, "0" * 64) + assert outcome["state"] == "ERROR" + assert "expected_state" not in seen + assert "defect_class" not in seen + assert "split" not in seen + assert seen["id"] == sample["id"] + + +def test_review_log_rejects_label_text_and_malformed_entries(tmp_path: Path) -> None: + review = [{ + "sample_id": "H01.clean.s1", "old_label_sha256": "a" * 64, + "new_label_sha256": "b" * 64, "reason_code": "corrected", + "at_utc": "2026-11-30T00:00:00Z", "label_text": "secret answer", + }] + holdout.write_json(tmp_path / "label_review_log.json", review) + with pytest.raises(holdout.HoldoutError, match="review log"): + holdout.validate_review_log(review, {"H01.clean.s1"}) + + +def test_runner_rejects_worker_protocol_with_wrong_hash_or_state(monkeypatch: pytest.MonkeyPatch) -> None: + import json + + def fake_run(*args, **kwargs): + return subprocess.CompletedProcess(args[0], 0, json.dumps({ + "sample_id": "D01.clean.s1", "state": "PASS", + "input_sha256": "0" * 64, "findings": [], + }), "") + + monkeypatch.setattr(runner.subprocess, "run", fake_run) + outcome = runner._run_worker("D01.clean.s1", "1" * 64, 10) + assert outcome["state"] == "ERROR" + assert outcome["error"]["code"] == "WORKER_PROTOCOL" + + +def test_runner_refuses_to_reuse_a_predictions_file(tmp_path: Path) -> None: + (tmp_path / "predictions.jsonl").write_text("", encoding="utf-8") + with pytest.raises(holdout.HoldoutError, match="predictions"): + runner.ensure_first_run(tmp_path) + + +@pytest.mark.skipif(os.name != "nt", reason="sealed execution is Windows-only") +def test_runner_refuses_a_burned_holdout_before_unsealing(tmp_path: Path) -> None: + (tmp_path / "BURNED").write_text("pre-seal detector exposure\n", encoding="utf-8") + with pytest.raises(holdout.HoldoutError, match="burned"): + runner.execute(tmp_path) + + +def test_package_description_acknowledges_font_evidence() -> None: + text = (ROOT / "pyproject.toml").read_text(encoding="utf-8") + description = next(line for line in text.splitlines() if line.startswith("description =")) + assert "no font evidence" not in description.lower() + assert "font" in description.lower() + + +def test_ci_runs_on_version_tags() -> None: + text = (ROOT / ".github" / "workflows" / "ci.yml").read_text(encoding="utf-8") + trigger = text.split("jobs:", 1)[0] + assert "tags:" in trigger + assert "v*" in trigger + + +def test_gate_verdict_fails_closed_while_preregistered_gates_are_unimplemented() -> None: + labels = [{"sample_id": "a", "expected_state": "FAIL", "defect_class": "clipped_text", + "source_object_id": 1, "related_source_object_id": None}] + outcomes = [{"sample_id": "a", "state": "FAIL", "findings": [{ + "defect_class": "clipped_text", "source_object_id": 1, + "related_source_object_id": None, "confidence": "high", "rule_id": "D1", + "box_pdf_points": [0, 0, 1, 1], + }], "report": {"coverage": {"ratio": 1.0}, "source_units_total": 1}}] + verdict = runner._gate_results(holdout.summarize_outcomes(labels, outcomes)) + assert verdict["all_pass"] is False + assert "baseline_B_delta_gate" in verdict["not_implemented"] + assert "template_cluster_bootstrap" in verdict["not_implemented"] + + +def test_markdown_report_publishes_intervals_and_limitations() -> None: + labels = [{"sample_id": "a", "expected_state": "PASS", "defect_class": None}] + outcomes = [{"sample_id": "a", "state": "PASS", "findings": []}] + summary = holdout.summarize_outcomes(labels, outcomes) + text = runner.render_markdown(summary, {"label_review_status": "machine_generated_unreviewed"}) + assert "clipped_text" in text + assert "Wilson 95%" in text + assert "False-PASS" in text + assert "UNKNOWN rate" in text + assert "ERROR rate" in text + assert "machine_generated_unreviewed" in text + assert "No independent custodian" in text diff --git a/tests/test_manifest_mutations.py b/tests/test_manifest_mutations.py index a90a491..c658c8d 100644 --- a/tests/test_manifest_mutations.py +++ b/tests/test_manifest_mutations.py @@ -29,8 +29,8 @@ import os import subprocess import sys +from collections.abc import Callable from pathlib import Path -from typing import Callable import pytest diff --git a/tests/test_output_alias.py b/tests/test_output_alias.py index 22992b2..0f21ef2 100644 --- a/tests/test_output_alias.py +++ b/tests/test_output_alias.py @@ -33,7 +33,7 @@ def test_output_cannot_alias_input_module(tmp_path, alias): else: os.link(module, destination) except OSError as error: - pytest.skip('link creation unsupported: %s' % error) + pytest.skip(f'link creation unsupported: {error}') with pytest.raises(cli.OutputError) as caught: cli._save(report(), str(destination), None, force=True, input_path=module) assert caught.value.code == 'INPUT_ALIAS' @@ -46,7 +46,7 @@ def test_symlink_destination_is_refused_even_when_dangling(tmp_path): try: destination.symlink_to(target) except OSError as error: - pytest.skip('symlink creation unsupported: %s' % error) + pytest.skip(f'symlink creation unsupported: {error}') with pytest.raises(cli.OutputError) as caught: cli._save(report(), str(destination), None, force=True) assert caught.value.code == 'OUTPUT_SYMLINK' @@ -318,7 +318,7 @@ def test_demo_preflight_rejects_cross_report_hardlink_aliases(tmp_path): try: os.link(first, output / 'clipped.html') except OSError as error: - pytest.skip('hardlink creation unsupported: %s' % error) + pytest.skip(f'hardlink creation unsupported: {error}') assert cli.main(['demo', '--output', str(output), '--force']) == 2 assert first.read_text(encoding='utf-8') == 'old evidence' diff --git a/tests/test_pdf_input.py b/tests/test_pdf_input.py index ec4f07a..06ef138 100644 --- a/tests/test_pdf_input.py +++ b/tests/test_pdf_input.py @@ -1,15 +1,14 @@ -from hashlib import sha256 -from importlib import import_module, util -from io import BytesIO import json import math -from pathlib import Path import subprocess import sys +from hashlib import sha256 +from importlib import import_module, util +from io import BytesIO import pytest - from _pdf_fixtures import pdf_bytes + from plotproof.geometry import Rect @@ -143,7 +142,7 @@ def test_invalid_hash_path_and_non_pdf_extension_are_explicit(tmp_path): def test_reader_parent_never_loads_native_stack_even_when_rendering(tmp_path): - a = api() + api() path = tmp_path / 'input.pdf'; path.write_bytes(pdf_bytes()) code = """ import sys, json diff --git a/tests/test_pdf_process.py b/tests/test_pdf_process.py index 182f0dc..425b13f 100644 --- a/tests/test_pdf_process.py +++ b/tests/test_pdf_process.py @@ -1,11 +1,9 @@ -from copy import deepcopy -from hashlib import sha256 -import json import subprocess import sys +from copy import deepcopy +from hashlib import sha256 import pytest - from _pdf_fixtures import pdf_bytes from test_pdf_input import api, read_bytes diff --git a/tests/test_pdf_transport_edges.py b/tests/test_pdf_transport_edges.py index e480c66..401625b 100644 --- a/tests/test_pdf_transport_edges.py +++ b/tests/test_pdf_transport_edges.py @@ -1,18 +1,15 @@ """Adversarial process/PNG controls beyond ordinary PDF parser outcomes.""" -from concurrent.futures import ThreadPoolExecutor -from copy import deepcopy -from hashlib import sha256 import base64 -from pathlib import Path import struct import subprocess -import sys import threading import time import zlib +from concurrent.futures import ThreadPoolExecutor +from copy import deepcopy +from hashlib import sha256 import pytest - from _pdf_fixtures import pdf_bytes from test_pdf_input import api, read_bytes from test_pdf_process import worker_script diff --git a/tests/test_rules.py b/tests/test_rules.py index 615ce54..a879bd5 100644 --- a/tests/test_rules.py +++ b/tests/test_rules.py @@ -1,8 +1,7 @@ from dataclasses import replace import pytest - -from _core_fixtures import module, text_record, pdf_chars, glyph_evidence, Rect, Transform +from _core_fixtures import Rect, Transform, glyph_evidence, module, pdf_chars, text_record from test_alignment import align @@ -14,7 +13,8 @@ def occluder(object_id=8, box=None, **changes): return replace(record, **changes) -def detect(records, chars, fills=(), glyphs=None, page=Rect(0, 0, 100, 100)): +def detect(records, chars, fills=(), glyphs=None, page=None): + page = Rect(0, 0, 100, 100) if page is None else page result = align(records, chars, glyphs) return module('rules').detect_rules(result, page, fills, glyphs or {}) diff --git a/tests/test_units.py b/tests/test_units.py index 091187f..a9e8188 100644 --- a/tests/test_units.py +++ b/tests/test_units.py @@ -1,9 +1,8 @@ -from dataclasses import replace import math +from dataclasses import replace import pytest - -from _core_fixtures import module, text_record, glyph_evidence, Rect, Transform +from _core_fixtures import Rect, Transform, glyph_evidence, module, text_record @pytest.mark.parametrize('changes,reason', [