Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Changelog


## Unreleased
## 0.1.0a4 — 2026-11-30

- Align public governance, bilingual quickstarts, issue templates, and documentation validation.
- Make CLI failures structured and fail closed, add explicit `--force` and rollback-safe paired
Expand All @@ -15,7 +15,9 @@
structure argparse/check `SystemExit` failures, validate both demo controls, and report only remaining recovery backups.
- Include fill sorting/scanning and the exact m/2m/2m union-sort passes in the D3 estimate.
- Reject ambiguous Windows output components, isolate user output at OS-fd level, preserve rollback recovery names, and use an exact rational union sweep that cannot underflow mixed-scale evidence to false zero.
- D4 `missing_glyph` remains not assessed: no font cmap evidence is collected.
- Collect bounded local Unicode-cmap evidence for renderer-selected fonts, bind font files by SHA-256, and assess D4 without turning unavailable provenance into a missing-glyph pass.

## Unreleased

## 0.1.0a3 — 2026-11-29

Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Contributions of focused fixes, reproducible counterexamples, and documentation

## Development setup

Supported version: **0.1.0a2**. Install and run the primary test command:
Supported version: **0.1.0a4**. Install and run the primary test command:

```sh
python -m pip install -e ".[dev]"
Expand Down
30 changes: 16 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ 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, no accuracy number, and
> no font evidence, so `D4_missing_glyph` is never assessed. Read
> 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.

## The problem
Expand Down Expand Up @@ -125,15 +126,15 @@ print(report.state, report.assessed)
| D1 | `clipped_text` — a positive-area character box has at least half its area outside the page, or its centre strictly outside | assessed |
| D2 | `occluded_text` — one artist with `α_eff ≥ 0.95`, painted after the text, covers at least 90% of it | assessed **only** when no image or collection was painted; otherwise reported as not assessed |
| D3 | `overlapping_text` — two text objects' painted character boxes overlap enough to impair reading | assessed unless its declared work budget is exceeded |
| D4 | `missing_glyph` — a character is absent from every resolved font and Matplotlib warned about it | **not assessed** (no font cmap evidence is collected yet) |
| D4 | `missing_glyph` — a character is absent from every resolved font and Matplotlib warned about it | assessed with bounded local cmap evidence; unavailable or malformed provenance is `UNKNOWN` |

Every report states the classes it assessed and why the others were skipped:

```json
{
"state": "PASS",
"assessed": ["D1_clipped_text", "D3_overlapping_text"],
"not_assessed": ["D2_occluded_text", "D4_missing_glyph"],
"assessed": ["D1_clipped_text", "D3_overlapping_text", "D4_missing_glyph"],
"not_assessed": ["D2_occluded_text"],
"capture_issues": ["collection_capture_pending", "unassociated_material_event"],
"coverage": {"aligned_units": 13, "total_units": 13, "ratio": 1.0}
}
Expand All @@ -159,8 +160,8 @@ estimated_work = pairs + operand_work + intersection_work + union_sort_work
Here `c_i` is the aligned character-box count (or one source box when unaligned). This is
a transparent operation budget, not an exact runtime prediction. If the estimate exceeds
the limit, the entire D3 pair loop is skipped: no individual pairs are silently dropped.
D1, D2 and the core's explicit D4 behavior remain intact; the assembly still reports
`D4_missing_glyph` as not assessed because it collects no font cmap evidence. D3 moves to
D1, D2 and D4 remain assessed; D4 reports explicit `UNKNOWN` evidence when font provenance
is unavailable. D3 moves to
`not_assessed`, a machine-readable `complexity_budget` record reports the components,
pair count, limit, formula and `skipped: true`, and the state becomes `UNKNOWN` unless an
existing `ERROR` or high-confidence `FAIL` correctly dominates. The boundary is inclusive.
Expand All @@ -184,8 +185,9 @@ text, unresolved alignment, coverage below 0.90, or a finding at medium confiden
- **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 font evidence yet.** D4 needs cmaps from the resolved font files plus the save's
missing-glyph warnings. That collector is the next slice.
- **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.
- **Rotated text is unsupported.** Matplotlib's default vertical y-label forces
`UNKNOWN`; use `rotation=0` to get an assessment. Mathtext, TeX, wrapped text,
rasterized text and path effects are also outside the supported set.
Expand Down Expand Up @@ -284,10 +286,10 @@ PlotProof 检查 Matplotlib 导出 PDF 时的**静默失败**:轴标签被页

当前是 **B1 工程预览**:确定性核心、受限 PDF 读取、CA1 保存期采集都已实现并通过完整测试;
端到端装配可以真正跑通一张图,**但不是认证过的检测器**——没有保留集结果、没有
准确率数字、没有字体 cmap 证据。
准确率数字;D4 使用有界的本地字体 cmap 证据,字体来源不可用时明确报告 `UNKNOWN`。

- 已评估:D1 文字被裁、D3 文字重叠(未超出复杂度预算时);D2 遮挡仅在“没有图像/集合被绘制”时评估。
- 未评估:D4 缺字(下一步做字体证据)。
- 已评估:D1 文字被裁、D3 文字重叠(未超出复杂度预算时)、D4 缺字(字体证据可用时);D2 遮挡仅在“没有图像/集合被绘制”时评估。
- D4 不会把缺失、畸形或超预算的字体证据伪装成“没有缺字”。
- 旋转文字(含默认竖排 y 轴标签)、数学公式、自动换行文字不支持,会强制 `UNKNOWN`。
- `PASS` 只表示“在已评估类别中、覆盖率足够时没发现受支持的缺陷”,不代表图正确。

Expand Down Expand Up @@ -324,10 +326,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 and end-to-end assembly. There is no holdout run, accuracy number, or font cmap evidence, and D4_missing_glyph is not assessed. 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 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.

### Support status
Version 0.1.0a3 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. It is not a certified detector and has no 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.
8 changes: 4 additions & 4 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,17 @@ estimated_work = pairs + operand_work + intersection_work + union_sort_work
```

`c_i` 为对齐后的字符框数(未对齐时为一个源框)。这是声明的操作预算,不是精确耗时预测。
估算值超过上限时跳过整个 D3 两两循环,绝不静默丢弃部分配对;D1、D2 和核心的显式 D4
行为保留。装配层仍因未采集字体 cmap 证据而将 `D4_missing_glyph` 标为未评估。D3 转为
估算值超过上限时跳过整个 D3 两两循环,绝不静默丢弃部分配对;D1、D2 和 D4
行为保留。D4 在字体来源不可用时给出显式 `UNKNOWN` 证据。D3 转为
`not_assessed`,机器可读的 `complexity_budget` 记录估算分量、配对数、上限、公式和
`skipped: true`;除非已有 `ERROR` 或高置信度 `FAIL` 正确优先,否则状态为 `UNKNOWN`。
估算值等于上限时仍执行 D3。矩形并集采用精确有理数坐标压缩线段树扫描,复杂度 O(m log m);有理坐标避免混合尺度下溢与中间溢出,真正无法表示为有限非零浮点数的面积会抛错,而不是返回虚假的有限零值。

### 证据与覆盖边界
证据包括完整 pytest 测试,覆盖确定性核心、受限 PDF 读取器、CA1 采集、结构化 CLI、安全发布、复杂度预算和端到端装配。没有保留集结果、准确率数字或字体 cmap 证据,D4_missing_glyph 未评估。PASS 仅表示在已评估类别中且覆盖足够时未发现受支持的缺陷。
证据包括完整 pytest 测试,覆盖确定性核心、受限 PDF 读取器、CA1 采集、结构化 CLI、安全发布、复杂度预算、本地字体 cmap 证据和端到端装配。没有保留集结果或准确率数字。D4 仅在渲染器选中的字体来源可用时评估,否则明确报告 `UNKNOWN`。PASS 仅表示在已评估类别中且覆盖足够时未发现受支持的缺陷。

### 支持状态
版本 0.1.0a3 是面向 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 上验证。它不是认证检测器,也没有准确率声明。维护为尽力而为,不提供 SLA。

### 限制
不支持旋转文字、数学公式、TeX、自动换行/栅格化文字、路径效果、任意/多页/旋转 PDF,也不做语义或美学判断。当图像或集合导致绘制清单不完整时,D2 会被跳过;D3 估算工作量超过预算时整类跳过。输出回滚不具备崩溃原子性。
2 changes: 1 addition & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## Supported versions

Only the current `world-class/v1` source line for **PlotProof 0.1.0a2** is considered for fixes. Older snapshots are unsupported. This is a best-effort project with no SLA, production support, or guarantee that every reported issue will receive a fix.
Only the current `world-class/v2` source line for **PlotProof 0.1.0a4** is considered for fixes. Older snapshots are unsupported. This is a best-effort project with no SLA, production support, or guarantee that every reported issue will receive a fix.

## Reporting a vulnerability

Expand Down
8 changes: 5 additions & 3 deletions docs/B1_EXPORT_ASSEMBLY.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ declared operation budget, not a runtime prediction. An estimate strictly greate
skips the entire D3 pair loop and records components, pair count, limit, formula and reason in
`complexity_budget`. Equality executes D3. D1/D2 results remain, D3 is removed from `assessed` and
added to `not_assessed`, and `_state` returns UNKNOWN unless ERROR or a high-confidence FAIL
correctly dominates. D4 remains not assessed because the assembly still collects no cmap evidence.
correctly dominates. D4 remains assessed with bounded local cmap evidence; unavailable
font provenance is explicit UNKNOWN evidence rather than a missing-glyph claim.

`geometry.union_area` uses exact rational coordinate compression plus a range-add/covered-length segment tree,
O(m log m). Rational coordinates prevent mixed-scale underflow and intermediate overflow; unrepresentable
Expand All @@ -104,8 +105,9 @@ randomized inputs and an operation-count regression protect the replacement.

## What the assembly does not do

- No font cmap collection, so D4 is never assessed. A report that says `PASS` therefore
never means "no missing glyph".
- Font cmap collection is bounded to renderer-selected local files and hash-bound in the
report. Missing, malformed or over-budget provenance makes D4 UNKNOWN; it never becomes
a missing-glyph PASS.
- No image/collection geometry, so D2 is skipped whenever one is painted.
- No claim of a §11 report: the fields are a subset, and no benchmark sample is touched.

Expand Down
2 changes: 1 addition & 1 deletion plotproof/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"""
from __future__ import annotations

__version__ = "0.1.0a3"
__version__ = "0.1.0a4"

__all__ = ["CheckError", "CheckReport", "check_figure", "render_html"]

Expand Down
59 changes: 58 additions & 1 deletion plotproof/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,22 @@
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
from .font_evidence import FontUse
from .geometry import Rect

_LOCK = threading.Lock()
_LOCAL = threading.local()
_MAX_BYTES = 16 * 1024 * 1024
_MAX_EVENTS = 100_000
_MAX_VERTICES = 1_000_000
_MAX_FONT_USES = 200_000
_MAX_FONT_STACK = 64


class CaptureError(ValueError):
Expand Down Expand Up @@ -89,6 +93,8 @@ def __init__(self, fig, output, max_events):
self.sources = []
self.stack = []
self.events = []
self.font_uses = []
self.font_use_keys = set()
self.issues = set()
self.vertex_count = 0
self.crop_calls = []
Expand Down Expand Up @@ -178,6 +184,55 @@ def add(self, kind, renderer, gc, *, color=None, artist=None, box=None,
None if source is None else source.artist_class,box,self.applied(gc,color,text=kind=='text'),
None if raw_alpha is None else float(raw_alpha),raw_color,text,size,angle,vertices,codes))

def record_fonts(self, renderer, prop, text, artist):
"""Bind each rendered code point to the renderer's full resolved stack."""
if artist is None or not text:
return
uid = self.register(artist)
try:
import matplotlib as mpl
from matplotlib import font_manager
font = renderer._get_font_ttf(prop)
paths = tuple(font_manager.fontManager._find_fonts_by_props(prop))
if not paths or len(paths) > _MAX_FONT_STACK:
self.issues.add('font_stack_limit')
return
families = {}
for path in paths:
resolved = str(Path(path).resolve())
entry = next((font for font in font_manager.fontManager.ttflist
if str(Path(font.fname).resolve()) == resolved), None)
if entry is not None:
families[resolved] = entry.name
selected = {}
if mpl.rcParams['pdf.fonttype'] in (3, 42):
selected = {char: fallback for char, fallback in font._get_fontmap(text).items()}
for char in dict.fromkeys(text):
if char.isspace():
continue
chosen = selected.get(char, font)
chosen_path = str(Path(chosen.fname).resolve())
uses = []
for path in paths:
resolved = str(Path(path).resolve())
is_selected = resolved == chosen_path
family = chosen.family_name if is_selected else families.get(resolved, 'unknown')
uses.append(FontUse(uid, ord(char), family, resolved,
chosen.get_char_index(ord(char)) if is_selected else 0,
is_selected))
if len(self.font_uses) + len(uses) > _MAX_FONT_USES:
self.issues.add('font_use_limit')
return
for use in uses:
key = (use.source_object_id, use.codepoint, use.family, use.path,
use.renderer_glyph_id, use.selected)
if key not in self.font_use_keys:
self.font_use_keys.add(key)
self.font_uses.append(use)
except Exception:
# Font provenance is a D4 limit, not permission to change or fail the save.
self.issues.add('font_provenance_unavailable')

def install(self):
from matplotlib.backends.backend_pdf import RendererPdf
original_text = self.Text.draw
Expand Down Expand Up @@ -216,6 +271,8 @@ def emit_text(renderer,gc,x,y,s,prop,angle,ismath=False,mtext=None):
if isinstance(artist,self.Text):
# Call the Text extent, not Annotation's union with its arrow.
box = self.Text.get_window_extent(artist,renderer).extents
if not ismath:
self.record_fonts(renderer, prop, s, artist)
self.add('text',renderer,gc,artist=artist,box=box,text=s,
size=float(prop.get_size_in_points()),angle=float(angle))
return original_emit_text(renderer,gc,x,y,s,prop,angle,ismath=ismath,mtext=mtext)
Expand Down Expand Up @@ -323,7 +380,7 @@ def _capture_locked(fig, bbox_inches, pad_inches, transparent, max_events, max_p
tuple(recorder.sources),tuple(recorder.events),
tuple(dict.fromkeys(SaveWarning(w.category.__name__,str(w.message)) for w in caught)),
tuple(sorted(recorder.issues)),
source_artists=tuple(recorder.objects))
source_artists=tuple(recorder.objects), font_uses=tuple(recorder.font_uses))
except CaptureError:
raise
except Exception:
Expand Down
3 changes: 3 additions & 0 deletions plotproof/capture_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from dataclasses import dataclass

from .evidence import SaveWarning
from .font_evidence import FontUse
from .geometry import Rect


Expand Down Expand Up @@ -65,6 +66,8 @@ class CapturedPdf:
# needs the object that produced each source ID; this adds no captured
# fact and is not serialized.
source_artists: tuple = ()
# Absolute paths remain internal capture provenance; reports expose hashes only.
font_uses: tuple[FontUse, ...] = ()

def to_source_display(self, box: Rect) -> Rect:
if self.origin_display is None:
Expand Down
Loading
Loading