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 +[](https://github.com/gedouluhui/plotproof/actions/workflows/ci.yml) +[](https://github.com/gedouluhui/plotproof/releases) +[](https://github.com/gedouluhui/plotproof/blob/main/pyproject.toml) +[](LICENSE) +[](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('
%(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)}
| Rule | Class | Source | Confidence | Box (pt) |
|---|
%(font_summary)s
-{escape(font_summary)}
+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 '