From 0460564f392e1a49c188592185bafac9354463ca Mon Sep 17 00:00:00 2001 From: gedouluhui <208120966+gedouluhui@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:37:01 +0800 Subject: [PATCH 1/4] feat: assess missing glyphs with bounded font cmap evidence Bind renderer-selected font files and Unicode cmap IDs to D4 findings while keeping unavailable provenance explicitly unknown. --- CHANGELOG.md | 2 +- README.md | 28 +- README.zh-CN.md | 6 +- docs/B1_EXPORT_ASSEMBLY.md | 8 +- plotproof/capture.py | 59 ++++- plotproof/capture_events.py | 3 + plotproof/evidence.py | 40 ++- plotproof/export.py | 58 ++++- plotproof/font_evidence.py | 445 ++++++++++++++++++++++++++++++++ plotproof/rules.py | 36 ++- tests/test_complexity_budget.py | 4 +- tests/test_export.py | 10 +- tests/test_font_evidence.py | 282 ++++++++++++++++++++ tests/test_rules.py | 16 ++ 14 files changed, 947 insertions(+), 50 deletions(-) create mode 100644 plotproof/font_evidence.py create mode 100644 tests/test_font_evidence.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 270f106..868782a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,7 +15,7 @@ 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. ## 0.1.0a3 — 2026-11-29 diff --git a/README.md b/README.md index 9809346..1f2fd47 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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} } @@ -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. @@ -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. @@ -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` 只表示“在已评估类别中、覆盖率足够时没发现受支持的缺陷”,不代表图正确。 @@ -324,7 +326,7 @@ 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. diff --git a/README.zh-CN.md b/README.zh-CN.md index 45775c7..27b3357 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -61,14 +61,14 @@ 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。 diff --git a/docs/B1_EXPORT_ASSEMBLY.md b/docs/B1_EXPORT_ASSEMBLY.md index 3f451ee..da23f1d 100644 --- a/docs/B1_EXPORT_ASSEMBLY.md +++ b/docs/B1_EXPORT_ASSEMBLY.md @@ -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 @@ -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. diff --git a/plotproof/capture.py b/plotproof/capture.py index 8c7e818..1a3796d 100644 --- a/plotproof/capture.py +++ b/plotproof/capture.py @@ -10,11 +10,13 @@ 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() @@ -22,6 +24,8 @@ _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): @@ -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 = [] @@ -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 @@ -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) @@ -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: diff --git a/plotproof/capture_events.py b/plotproof/capture_events.py index 2832550..11d3066 100644 --- a/plotproof/capture_events.py +++ b/plotproof/capture_events.py @@ -4,6 +4,7 @@ from dataclasses import dataclass from .evidence import SaveWarning +from .font_evidence import FontUse from .geometry import Rect @@ -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: diff --git a/plotproof/evidence.py b/plotproof/evidence.py index 1c47304..b5bf392 100644 --- a/plotproof/evidence.py +++ b/plotproof/evidence.py @@ -89,14 +89,28 @@ class FontGlyph: family: str file_id: str | None glyph_id: int | None + cmap_status: str = 'known' + reason: str | None = None + renderer_glyph_id: int | None = None def __post_init__(self) -> None: - if self.glyph_id is not None: - integer_id(self.glyph_id, 'glyph_id') + if not isinstance(self.family, str) or not self.family: + raise ValueError('font family must be a nonempty string') + if self.file_id is not None and not isinstance(self.file_id, str): + raise TypeError('file_id must be a string or None') + if self.cmap_status not in ('known', 'unknown'): + raise ValueError('cmap_status must be known or unknown') + if self.reason is not None and (not isinstance(self.reason, str) or not self.reason): + raise ValueError('font reason must be a nonempty string or None') + for name in ('glyph_id', 'renderer_glyph_id'): + value = getattr(self, name) + if value is not None: + integer_id(value, name) @property def missing(self) -> bool: - return self.file_id is not None and (self.glyph_id is None or self.glyph_id == 0) + return (self.cmap_status == 'known' and self.file_id is not None + and (self.glyph_id is None or self.glyph_id == 0)) _WARNING = re.compile(r'^Glyph (\d+)\s+\([^\n]*\) missing from font\(s\) (.+)\.$') @@ -107,6 +121,7 @@ class GlyphEvidence: codepoint: int fonts: tuple[FontGlyph, ...] warnings: tuple[SaveWarning, ...] + reasons: tuple[str, ...] = () def __post_init__(self) -> None: integer_id(self.codepoint, 'codepoint') @@ -114,6 +129,25 @@ def __post_init__(self) -> None: raise ValueError('invalid Unicode code point') object.__setattr__(self, 'fonts', tuple(self.fonts)) object.__setattr__(self, 'warnings', tuple(self.warnings)) + object.__setattr__(self, 'reasons', tuple(dict.fromkeys(self.reasons))) + if not all(isinstance(reason, str) and reason for reason in self.reasons): + raise ValueError('glyph reasons must be nonempty strings') + + @property + def coverage(self) -> str: + """Cmap assessment independent of warning attribution and alignment.""" + if not self.fonts or any(font.cmap_status != 'known' for font in self.fonts): + return 'unknown' + if any(font.glyph_id is not None and font.glyph_id > 0 for font in self.fonts): + return 'covered' + if all(font.missing for font in self.fonts): + return 'missing' + return 'unknown' + + @property + def unknown_reasons(self) -> tuple[str, ...]: + return tuple(dict.fromkeys((*self.reasons, + *(font.reason for font in self.fonts if font.reason is not None)))) @property def codepoint_warnings(self) -> tuple[SaveWarning, ...]: diff --git a/plotproof/export.py b/plotproof/export.py index fa6ba01..ff04acc 100644 --- a/plotproof/export.py +++ b/plotproof/export.py @@ -7,8 +7,8 @@ What it does not do, and says so in the report: -* no font cmap evidence is collected, so D4 ``missing_glyph`` is reported as - not assessed - never as passed; +* D4 uses bounded local cmap evidence for renderer-selected fonts; unavailable + provenance is explicit UNKNOWN evidence, never a missing-glyph claim; * any capture issue that leaves material unmapped (images, collections, rasterized text, wrapped text, ...) makes the result ERROR rather than turning partial coverage into a pass; @@ -24,6 +24,7 @@ from .capture import CaptureError, _artists, capture_pdf from .core import CoreResult, check_core from .evidence import TextRecord +from .font_evidence import collect_font_evidence from .geometry import Rect, Transform from .occlusion import FilledRecord from .pdf_input import PdfReadError, read_pdf @@ -31,8 +32,9 @@ from .units import AccountingError, exclusion_reason -CHECKS_EVALUATED = ('D1_clipped_text', 'D2_occluded_text', 'D3_overlapping_text') -CHECKS_NOT_EVALUATED = ('D4_missing_glyph',) +CHECKS_EVALUATED = ('D1_clipped_text', 'D2_occluded_text', 'D3_overlapping_text', + 'D4_missing_glyph') +CHECKS_NOT_EVALUATED = () # Material this layer cannot map. D2 needs the complete painted inventory, so # these limit the assessed classes; they do not by themselves invalidate D1 or # D3, which use character boxes rather than occluder geometry. @@ -41,7 +43,10 @@ 'tex_capture_pending', 'rasterized_capture_pending', 'path_effect_capture_pending', 'unassociated_material_event', 'mathtext_capture_pending', 'multi_path_fill_unsupported', 'fill_without_geometry'}) -RULE_CLASSES = {'D1': 'D1_clipped_text', 'D2': 'D2_occluded_text', 'D3': 'D3_overlapping_text'} +FONT_PROVENANCE_ISSUES = frozenset({ + 'font_provenance_unavailable', 'font_stack_limit', 'font_use_limit'}) +RULE_CLASSES = {'D1': 'D1_clipped_text', 'D2': 'D2_occluded_text', + 'D3': 'D3_overlapping_text', 'D4': 'D4_missing_glyph'} _MAX_ROUND_TRIP = 200_000 @@ -70,6 +75,7 @@ class CheckReport: text_records: int filled_records: int complexity_budget: dict | None = None + font_evidence: dict | None = None def to_dict(self) -> dict: return asdict(self) @@ -220,14 +226,16 @@ def _collect(fig, captured, transform: Transform, page: Rect) -> _Collection: return result -def _state(core: CoreResult, findings: tuple[dict, ...]) -> str: +def _state(core: CoreResult, findings: tuple[dict, ...], *, + font_unknown: tuple[dict, ...] = (), font_complete: bool = True) -> str: """Recompute the state over the classes this run actually assessed.""" if core.errors: return 'ERROR' if any(item['confidence'] == 'high' for item in findings): return 'FAIL' coverage = core.coverage or {} - if (findings or core.unknown_objects or core.complexity_budget is not None + if (findings or core.unknown_objects or font_unknown or not font_complete + or core.complexity_budget is not None or coverage.get('ratio') is None or coverage.get('ratio', 0) < 0.90 or coverage.get('unsupported_units', 0) > 0): return 'UNKNOWN' @@ -273,13 +281,23 @@ def _check_figure(fig, *, bbox_inches=None, pad_inches=None, transparent=False, transform = Transform(captured.original_dpi, *captured.origin_display) collection = _collect(fig, captured, transform, page) paint_issue = any(issue in PAINT_LIMITS for issue in captured.capture_issues) + font_issues = tuple(issue for issue in captured.capture_issues + if issue in FONT_PROVENANCE_ISSUES) errors = [{'stage': 'capture', 'message': issue} - for issue in captured.capture_issues if issue not in PAINT_LIMITS] + for issue in captured.capture_issues + if issue not in PAINT_LIMITS and issue not in FONT_PROVENANCE_ISSUES] errors.extend(collection.errors) total = sum(1 for record in collection.records if record.is_unit) + fonts = collect_font_evidence(tuple(collection.records), captured.font_uses, + captured.warnings) + font_summary = dict(fonts.summary) + font_summary['issues'] = tuple(sorted(set(font_summary['issues']) | set(font_issues))) + if font_issues and font_summary['codepoints']: + font_summary['status'] = ('unavailable' if font_summary['covered'] + font_summary['missing'] == 0 + else 'partial') core: CoreResult = check_core( records=tuple(collection.records), chars=snapshot.characters, - fills=tuple(collection.fills), glyphs={}, transform=transform, page=page, + fills=tuple(collection.fills), glyphs=fonts.glyphs, transform=transform, page=page, source_units_total=total, errors=tuple(errors), max_d3_work=max_d3_work) d3_skipped = core.complexity_budget is not None assessed = tuple(name for name in CHECKS_EVALUATED @@ -287,10 +305,14 @@ def _check_figure(fig, *, bbox_inches=None, pad_inches=None, transparent=False, and not (d3_skipped and name == 'D3_overlapping_text')) findings = tuple(item for item in core.to_dict()['findings'] if RULE_CLASSES[item['rule_id']] in assessed) + # Dicts are not hashable; deduplicate by their stable serialized items. + font_unknown = tuple({tuple(sorted(item.items())): item + for item in (*core.unknown_objects, *fonts.unknown_objects)}.values()) return CheckReport( - state=_state(core, findings), + state=_state(core, findings, font_unknown=fonts.unknown_objects, + font_complete=font_summary['status'] in ('complete', 'empty')), findings=findings, - coverage=core.coverage, unknown_objects=core.unknown_objects, + coverage=core.coverage, unknown_objects=font_unknown, errors=core.errors, assessed=assessed, not_assessed=tuple(name for name in CHECKS_EVALUATED if name not in assessed) + CHECKS_NOT_EVALUATED, @@ -298,7 +320,8 @@ def _check_figure(fig, *, bbox_inches=None, pad_inches=None, transparent=False, page_size_pt=(page.x1, page.y1), input_sha256=captured.input_sha256, pdfium_version=snapshot.pdfium_version, source_units_total=total, text_records=len(collection.records), - filled_records=len(collection.fills), complexity_budget=core.complexity_budget) + filled_records=len(collection.fills), complexity_budget=core.complexity_budget, + font_evidence=font_summary) finally: if temporary is not None: temporary.unlink(missing_ok=True) @@ -322,6 +345,13 @@ def render_html(report: CheckReport) -> str: escape(str(item.get('message')))) for item in report.errors) coverage = report.coverage or {} + fonts = report.font_evidence or {} + font_issues = ''.join('
  • %s
  • ' % escape(str(issue)) + for issue in fonts.get('issues', ())) + font_summary = ('status %s · code points %d · covered %d · missing %d · unknown %d · font files %d' + % (fonts.get('status', 'n/a'), fonts.get('codepoints', 0), + fonts.get('covered', 0), fonts.get('missing', 0), + fonts.get('unknown', 0), fonts.get('font_files', 0))) return """ PlotProof report @@ -342,6 +372,9 @@ def render_html(report: CheckReport) -> str: %(rows)s
    RuleClassSourceConfidenceBox (pt)

    Unaligned / unsupported

    +

    D4 font cmap evidence

    +

    %(font_summary)s

    +

    Capture and accounting limits

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

    @@ -353,4 +386,5 @@ def render_html(report: CheckReport) -> str: 'ratio': 'n/a' if coverage.get('ratio') is None else '%.3f' % coverage['ratio'], 'digest': escape(report.input_sha256), 'pdfium': escape(report.pdfium_version), 'rows': ''.join(rows), 'unknown': unknown or '
  • none
  • ', + 'font_summary': escape(font_summary), 'font_issues': font_issues or '
  • none
  • ', 'errors': errors or '
  • none
  • '} diff --git a/plotproof/font_evidence.py b/plotproof/font_evidence.py new file mode 100644 index 0000000..95e819c --- /dev/null +++ b/plotproof/font_evidence.py @@ -0,0 +1,445 @@ +"""Bounded, local Unicode-cmap evidence for renderer-selected font files. + +Capture supplies file paths and FreeType glyph IDs; this module never resolves a +font by family name and never treats PDF text extraction as glyph evidence. +""" +from __future__ import annotations + +from dataclasses import asdict, dataclass, field +from hashlib import sha256 +from pathlib import Path +import struct +from typing import Mapping, Sequence + +from .evidence import FontGlyph, GlyphEvidence, SaveWarning, TextRecord, integer_id +from .units import AccountingError + +_MAX_FILES = 64 +_MAX_FILE_BYTES = 32 * 1024 * 1024 +_MAX_TOTAL_BYTES = 128 * 1024 * 1024 +_MAX_CMAP_ENTRIES = 1_000_000 +_MAX_CODEPOINTS = 200_000 +_CMAP_PREFERENCES = ((3, 10), (0, 6), (0, 4), (3, 1), + (0, 3), (0, 2), (0, 1), (0, 0)) +_SFNT_SIGNATURES = {b'\x00\x01\x00\x00', b'OTTO', b'true', b'typ1'} + + +@dataclass(frozen=True) +class FontUse: + source_object_id: int + codepoint: int + family: str + path: str + renderer_glyph_id: int + selected: bool = True + + def __post_init__(self) -> None: + integer_id(self.source_object_id, 'source_object_id') + integer_id(self.codepoint, 'codepoint') + if self.codepoint > 0x10FFFF or 0xD800 <= self.codepoint <= 0xDFFF: + raise ValueError('invalid Unicode code point') + if not isinstance(self.family, str) or not self.family: + raise ValueError('font family must be a nonempty string') + if not isinstance(self.path, str) or not Path(self.path).is_absolute(): + raise ValueError('font path must be an absolute local path') + integer_id(self.renderer_glyph_id, 'renderer_glyph_id') + if type(self.selected) is not bool: + raise TypeError('selected must be a boolean') + + +@dataclass(frozen=True) +class FontLimits: + max_files: int = _MAX_FILES + max_file_bytes: int = _MAX_FILE_BYTES + max_total_bytes: int = _MAX_TOTAL_BYTES + max_cmap_entries: int = _MAX_CMAP_ENTRIES + max_codepoints: int = _MAX_CODEPOINTS + + def __post_init__(self) -> None: + ceilings = {'max_files': _MAX_FILES, 'max_file_bytes': _MAX_FILE_BYTES, + 'max_total_bytes': _MAX_TOTAL_BYTES, + 'max_cmap_entries': _MAX_CMAP_ENTRIES, + 'max_codepoints': _MAX_CODEPOINTS} + for name, ceiling in ceilings.items(): + value = getattr(self, name) + if type(value) is not int or not 0 < value <= ceiling: + raise ValueError(f'{name} must be an integer in [1, {ceiling}]') + + +@dataclass(frozen=True) +class FontCollection: + glyphs: dict[int, tuple[GlyphEvidence, ...]] + issues: tuple[str, ...] + unknown_objects: tuple[dict, ...] + summary: dict + + def to_dict(self) -> dict: + return {'glyphs': {str(uid): [dict(g.__dict__) for g in evidence] + for uid, evidence in self.glyphs.items()}, + 'issues': self.issues, 'unknown_objects': self.unknown_objects, + 'summary': self.summary} + + +class _CmapLimit(ValueError): + pass + + +class _CmapMalformed(ValueError): + pass + + +@dataclass(frozen=True) +class _Cmap: + kind: str + length: int + entries: int + segments: tuple = () + groups: tuple = () + glyphs: bytes = b'' + + def get(self, codepoint: int) -> int | None: + if self.kind == 0: + return self.glyphs[codepoint] if codepoint < 256 else None + if self.kind == '6': + first, count = self.segments + index = codepoint - first + return struct.unpack_from('>H', self.glyphs, 2 * index)[0] if 0 <= index < count else None + if self.kind == '10': + first, count = self.segments + index = codepoint - first + return struct.unpack_from('>H', self.glyphs, 2 * index)[0] if 0 <= index < count else None + if self.kind in ('12', '13'): + for start, end, glyph in self.groups: + if codepoint < start: + break + if codepoint <= end: + return glyph if self.kind == '13' else glyph + codepoint - start + return None + # Format 4: (end, start, delta, range-offset field position, range offset). + for end, start, delta, position, offset in self.segments: + if codepoint > end: + continue + if codepoint < start: + return None + if offset == 0: + return (codepoint + delta) & 0xFFFF + address = position + offset + 2 * (codepoint - start) + glyph = struct.unpack_from('>H', self.glyphs, address)[0] + return (glyph + delta) & 0xFFFF if glyph else 0 + return None + + +def _u16(data: bytes, offset: int) -> int: + return struct.unpack_from('>H', data, offset)[0] + + +def _u32(data: bytes, offset: int) -> int: + return struct.unpack_from('>I', data, offset)[0] + + +def _parse_cmap(data: bytes, offset: int, length: int, fmt: int, + max_entries: int) -> _Cmap: + if length < 4 or offset < 0 or offset + length > len(data): + raise _CmapMalformed('subtable bounds') + table = memoryview(data)[offset:offset + length] + if fmt == 0: + if length != 262: + raise _CmapMalformed('format 0 length') + return _Cmap('0', length, 256, glyphs=bytes(table[6:262])) + if fmt == 6: + if length < 10: + raise _CmapMalformed('format 6 header') + first, count = _u16(data, offset + 6), _u16(data, offset + 8) + if length != 10 + 2 * count: + raise _CmapMalformed('format 6 length') + return _Cmap('6', length, count, segments=(first, count), glyphs=bytes(table[10:])) + if fmt == 10: + if length < 20: + raise _CmapMalformed('format 10 header') + first, count = _u32(data, offset + 8), _u32(data, offset + 12) + if length != 20 + 2 * count: + raise _CmapMalformed('format 10 length') + return _Cmap('10', length, count, segments=(first, count), glyphs=bytes(table[20:])) + if fmt == 4: + if length < 16 or length % 2: + raise _CmapMalformed('format 4 header') + count = _u16(data, offset + 6) + if count == 0 or count % 2 or length < 16 + 8 * (count // 2): + raise _CmapMalformed('format 4 segments') + count //= 2 + ends = offset + 14 + starts = ends + 2 * count + 2 + deltas = starts + 2 * count + ranges = deltas + 2 * count + glyph_array = ranges + 2 * count + segments = [] + entries = 0 + previous_end = -1 + for index in range(count): + end, start = _u16(data, ends + 2 * index), _u16(data, starts + 2 * index) + if start > end or end <= previous_end or end > 0xFFFF: + raise _CmapMalformed('format 4 ordering') + previous_end = end + entries += end - start + 1 + if entries > max_entries: + raise _CmapLimit('entry count') + position = ranges + 2 * index + delta, relative = _u16(data, deltas + 2 * index), _u16(data, position) + if relative: + address = position + relative + span = address + 2 * (end - start + 1) + if relative % 2 or address < glyph_array or span > offset + length: + raise _CmapMalformed('format 4 glyph array') + segments.append((end, start, delta, position, relative)) + if segments[-1][0] != 0xFFFF: + raise _CmapMalformed('format 4 sentinel') + return _Cmap('4', length, entries, segments=tuple(segments), glyphs=bytes(table)) + if fmt in (12, 13): + if length < 16: + raise _CmapMalformed('format 12/13 header') + declared, count = _u32(data, offset + 4), _u32(data, offset + 12) + if declared != length or length != 16 + 12 * count: + raise _CmapMalformed('format 12/13 length') + groups = [] + entries = 0 + previous_end = -1 + for index in range(count): + start, end, glyph = struct.unpack_from('>III', data, offset + 16 + 12 * index) + if start > end or end > 0x10FFFF or start <= previous_end: + raise _CmapMalformed('format 12/13 ordering') + previous_end = end + entries += end - start + 1 + if entries > max_entries: + raise _CmapLimit('entry count') + groups.append((start, end, glyph)) + return _Cmap(str(fmt), length, entries, groups=tuple(groups)) + raise _CmapMalformed('unsupported format') + + +def _font_cmap(data: bytes, max_entries: int) -> tuple[_Cmap, int]: + if len(data) < 12 or data[:4] not in _SFNT_SIGNATURES: + raise _CmapMalformed('SFNT header') + count = _u16(data, 4) + if count == 0 or count > 4096 or 12 + 16 * count > len(data): + raise _CmapMalformed('table directory') + cmap = None + maxp = None + for index in range(count): + entry = 12 + 16 * index + tag = data[entry:entry + 4] + offset, length = _u32(data, entry + 8), _u32(data, entry + 12) + if offset > len(data) or length > len(data) - offset: + raise _CmapMalformed('table bounds') + if tag == b'cmap': + if cmap is not None: + raise _CmapMalformed('duplicate cmap') + cmap = offset, length + elif tag == b'maxp': + maxp = offset, length + if cmap is None: + raise _CmapMalformed('cmap absent') + if maxp is None or maxp[1] < 6: + raise _CmapMalformed('maxp absent') + num_glyphs = _u16(data, maxp[0] + 4) + if num_glyphs == 0: + raise _CmapMalformed('empty font') + offset, length = cmap + if length < 4 or _u16(data, offset) != 0: + raise _CmapMalformed('cmap header') + count = _u16(data, offset + 2) + if count == 0 or count > 4096 or 4 + 8 * count > length: + raise _CmapMalformed('cmap records') + records = {} + for index in range(count): + platform, encoding, relative = struct.unpack_from('>HHI', data, offset + 4 + 8 * index) + if relative > length - 4: + raise _CmapMalformed('cmap subtable offset') + records.setdefault((platform, encoding), relative) + for key in _CMAP_PREFERENCES: + if key in records: + relative = records[key] + fmt = _u16(data, offset + relative) + if fmt in (12, 13): + size = _u32(data, offset + relative + 4) + elif fmt == 14: + size = _u32(data, offset + relative + 2) + else: + size = _u16(data, offset + relative + 2) + if size < 4 or size > length - relative: + raise _CmapMalformed('cmap subtable length') + cmap = _parse_cmap(data, offset + relative, size, fmt, max_entries) + if cmap.kind in ('12', '13'): + if any(glyph >= num_glyphs or (cmap.kind == '12' and glyph + end - start >= num_glyphs) + for start, end, glyph in cmap.groups): + raise _CmapMalformed('glyph ID out of range') + return cmap, num_glyphs + raise _CmapMalformed('Unicode cmap absent') + + +@dataclass +class _FileEvidence: + file_id: str | None = None + cmap: _Cmap | None = None + num_glyphs: int | None = None + reason: str | None = None + + +def _read_file(path: Path, limits: FontLimits, total_bytes: int) -> tuple[bytes | None, int, str | None]: + try: + stat = path.stat() + if not path.is_file(): + return None, total_bytes, 'font_unavailable' + if stat.st_size > limits.max_file_bytes: + return None, total_bytes, 'font_byte_limit' + if total_bytes + stat.st_size > limits.max_total_bytes: + return None, total_bytes, 'font_total_byte_limit' + with path.open('rb') as stream: + data = stream.read(limits.max_file_bytes + 1) + except (OSError, ValueError): + return None, total_bytes, 'font_unavailable' + if len(data) > limits.max_file_bytes: + return None, total_bytes, 'font_byte_limit' + if total_bytes + len(data) > limits.max_total_bytes: + return None, total_bytes, 'font_total_byte_limit' + return data, total_bytes + len(data), None + + +def _limits(value: FontLimits | Mapping[str, int] | None) -> FontLimits: + if value is None: + return FontLimits() + if isinstance(value, FontLimits): + return value + if isinstance(value, Mapping): + return FontLimits(**dict(value)) + raise ValueError('font limits must be FontLimits, a mapping, or None') + + +def collect_font_evidence(records: Sequence[TextRecord], uses: Sequence[FontUse], + warnings: Sequence[SaveWarning] = (), *, + limits: FontLimits | Mapping[str, int] | None = None) -> FontCollection: + """Map source code points to hash-bound cmap IDs for renderer-selected fonts.""" + limits = _limits(limits) + warnings = tuple(warnings) + by_id = {record.source_object_id: record for record in records} + if len(by_id) != len(records): + raise AccountingError('duplicate text source ID in font collection') + requested: dict[tuple[int, int], list[FontUse]] = {} + for record in records: + if not record.is_unit: + continue + for codepoint in sorted({ord(char) for char in record.text if not char.isspace()}): + requested[record.source_object_id, codepoint] = [] + all_requested = set(requested) + issues: set[str] = set() + unknown_objects: list[dict] = [] + if len(requested) > limits.max_codepoints: + issues.add('font_codepoint_limit') + keys = sorted(requested, key=lambda key: (key[0], key[1])) + for uid, _ in keys[limits.max_codepoints:]: + if not any(item['source_object_id'] == uid for item in unknown_objects): + unknown_objects.append({'source_object_id': uid, 'reason': 'font_codepoint_limit'}) + requested = {key: [] for key in keys[:limits.max_codepoints]} + seen_uses = set() + for use in uses: + key = use.source_object_id, use.codepoint + if use.source_object_id not in by_id: + raise AccountingError('font use references an unknown text ID') + if key not in all_requested: + if by_id[use.source_object_id].is_unit: + raise AccountingError('font use references an unknown text code point') + continue + if key not in requested: + continue + identity = (use.source_object_id, use.codepoint, use.family, use.path, + use.renderer_glyph_id, use.selected) + if identity not in seen_uses: + seen_uses.add(identity) + requested[key].append(use) + + files: dict[str, _FileEvidence] = {} + file_order: list[str] = [] + total_bytes = 0 + + def load(path: str) -> _FileEvidence: + nonlocal total_bytes + if path in files: + return files[path] + if len(file_order) >= limits.max_files: + evidence = _FileEvidence(reason='font_file_limit') + issues.add('font_file_limit') + files[path] = evidence + return evidence + file_order.append(path) + data, total_bytes, reason = _read_file(Path(path), limits, total_bytes) + if reason is not None: + issues.add(reason) + evidence = _FileEvidence(reason=reason) + else: + file_id = 'sha256:' + sha256(data).hexdigest() + try: + cmap, num_glyphs = _font_cmap(data, limits.max_cmap_entries) + evidence = _FileEvidence(file_id, cmap, num_glyphs) + except _CmapLimit: + reason = 'cmap_entry_limit' + issues.add(reason) + evidence = _FileEvidence(file_id=file_id, reason=reason) + except (_CmapMalformed, struct.error, OverflowError): + reason = 'malformed_cmap' + issues.add(reason) + evidence = _FileEvidence(file_id=file_id, reason=reason) + files[path] = evidence + return evidence + + glyphs: dict[int, list[GlyphEvidence]] = {} + counts = {'covered': 0, 'missing': 0, 'unknown': 0} + for (uid, codepoint), font_uses in sorted(requested.items()): + fonts = [] + reasons = [] + if not font_uses: + reasons.append('font_provenance_unavailable') + fonts.append(FontGlyph('unknown', None, None, 'unknown', + 'font_provenance_unavailable')) + for use in font_uses: + file = load(use.path) + if file.reason is not None: + fonts.append(FontGlyph(use.family, file.file_id, None, 'unknown', + file.reason, use.renderer_glyph_id)) + continue + glyph_id = file.cmap.get(codepoint) + if glyph_id is not None and glyph_id >= file.num_glyphs: + fonts.append(FontGlyph(use.family, file.file_id, glyph_id, 'unknown', + 'renderer_cmap_mismatch', use.renderer_glyph_id)) + issues.add('renderer_cmap_mismatch') + continue + if use.selected and (glyph_id or 0) != use.renderer_glyph_id: + fonts.append(FontGlyph(use.family, file.file_id, glyph_id, 'unknown', + 'renderer_cmap_mismatch', use.renderer_glyph_id)) + issues.add('renderer_cmap_mismatch') + else: + fonts.append(FontGlyph(use.family, file.file_id, glyph_id, 'known', + None, use.renderer_glyph_id if use.selected else None)) + glyph = GlyphEvidence(codepoint, tuple(fonts), warnings, tuple(reasons)) + glyphs.setdefault(uid, []).append(glyph) + counts[glyph.coverage] += 1 + total = sum(counts.values()) + if total == 0: + status = 'empty' + elif counts['unknown'] == 0 and not issues: + status = 'complete' + elif counts['covered'] + counts['missing'] == 0: + status = 'unavailable' + else: + status = 'partial' + file_rows = [] + for path in file_order: + file = files[path] + families = sorted({use.family for use in uses if use.path == path}) + file_rows.append({'file_id': file.file_id, 'families': tuple(families), + 'cmap_entries': None if file.cmap is None else file.cmap.entries, + 'status': 'known' if file.reason is None else 'unknown', + 'reason': file.reason}) + summary = {'status': status, 'codepoints': total, **counts, + 'font_files': len(file_order), 'files': tuple(file_rows), + 'issues': tuple(sorted(issues)), 'limits': asdict(limits)} + return FontCollection({uid: tuple(items) for uid, items in glyphs.items()}, + tuple(sorted(issues)), tuple(unknown_objects), summary) diff --git a/plotproof/rules.py b/plotproof/rules.py index 24ace0b..18612a8 100644 --- a/plotproof/rules.py +++ b/plotproof/rules.py @@ -190,28 +190,38 @@ def _d4(unit: Unit, aligned: bool, glyphs: Sequence[GlyphEvidence]) -> list[Find for glyph in sorted(glyphs, key=lambda g: g.codepoint): if chr(glyph.codepoint) not in unit.record.text: continue + coverage = glyph.coverage # §4 D4's explicit legal-fallback example qualifies the general # stack-disagreement medium case: confirmed supply + no warning is legal. supplied_without_warning = ( - all(font.file_id is not None for font in glyph.fonts) + all(font.file_id is not None and font.cmap_status == 'known' for font in glyph.fonts) and any(font.glyph_id is not None and font.glyph_id > 0 for font in glyph.fonts) and not glyph.codepoint_warnings) if supplied_without_warning: continue - has_missing = any(font.missing for font in glyph.fonts) - if not has_missing and not glyph.codepoint_warnings: - continue - # Without alignment only the explicitly proven-missing exception may emit. - if not aligned and not glyph.proven_missing: - continue - confidence = 'high' if aligned and glyph.proven_missing else 'medium' + if coverage == 'unknown': + # Unavailable provenance is an explicit D4 UNKNOWN, never a missing + # glyph claim and never a reason to hide an independent D2/D3 result. + confidence = 'medium' + else: + has_missing = any(font.missing for font in glyph.fonts) + if not has_missing and not glyph.codepoint_warnings: + continue + # Without alignment only the explicitly proven-missing exception may emit. + if not aligned and not glyph.proven_missing: + continue + confidence = 'high' if aligned and glyph.proven_missing else 'medium' output.append(_finding('D4', unit, confidence, unit.box_pdf, { - 'codepoint': glyph.codepoint, + 'codepoint': glyph.codepoint, 'coverage': coverage, + 'assessment': coverage, 'fonts': tuple({'family': font.family, 'file_id': font.file_id, - 'glyph_id': font.glyph_id, 'missing': font.missing} for font in glyph.fonts), + 'glyph_id': font.glyph_id, 'missing': font.missing, + 'cmap_status': font.cmap_status, 'reason': font.reason, + 'renderer_glyph_id': font.renderer_glyph_id} for font in glyph.fonts), 'resolved_families': tuple(font.family for font in glyph.fonts), 'warnings': tuple({'category': w.category, 'message': w.message} for w in glyph.codepoint_warnings), 'naming_warning': bool(glyph.naming_warnings), + 'reasons': glyph.unknown_reasons, 'source_bbox_pdf_points': unit.box_pdf.as_tuple(), 'unique_alignment': aligned, })) return output @@ -224,8 +234,14 @@ def apply_precedence(findings: Sequence[Finding]) -> tuple[Finding, ...]: kept: list[Finding] = [] for finding in ordered: members = {finding.source_object_id, finding.related_source_object_id} - {None} + # A D4 provenance UNKNOWN is not a defect candidate: it must neither + # suppress D2/D3 nor disappear behind them. + if finding.rule_id == 'D4' and finding.evidence.get('assessment') == 'unknown': + kept.append(finding) + continue suppressor = next((index for index, higher in enumerate(kept) if higher.confidence == finding.confidence and PRIORITY[higher.rule_id] < PRIORITY[finding.rule_id] + and not (higher.rule_id == 'D4' and higher.evidence.get('assessment') == 'unknown') and members.intersection({higher.source_object_id, higher.related_source_object_id} - {None})), None) if suppressor is None: kept.append(finding) diff --git a/tests/test_complexity_budget.py b/tests/test_complexity_budget.py index 83f09ec..086b203 100644 --- a/tests/test_complexity_budget.py +++ b/tests/test_complexity_budget.py @@ -145,14 +145,14 @@ def test_skipped_d3_does_not_hide_existing_fail_or_error(): assert errored.overall_state == 'ERROR' -def test_export_marks_d3_not_assessed_and_keeps_d4_not_assessed(): +def test_export_marks_d3_not_assessed_and_keeps_d4_assessed(): fig = figure() bars(fig) report = check_figure(fig, max_d3_work=1) assert report.state == 'UNKNOWN' assert 'D1_clipped_text' in report.assessed assert 'D3_overlapping_text' in report.not_assessed - assert 'D4_missing_glyph' in report.not_assessed + assert 'D4_missing_glyph' in report.assessed assert report.complexity_budget['skipped'] is True assert not any(f['rule_id'] == 'D3' for f in report.findings) assert report.to_dict()['complexity_budget']['estimated_work'] > 1 diff --git a/tests/test_export.py b/tests/test_export.py index fe5e1da..f579de2 100644 --- a/tests/test_export.py +++ b/tests/test_export.py @@ -42,7 +42,11 @@ def test_clean_figure_passes_in_assessed_classes(): assert report.coverage['ratio'] == 1.0 assert report.findings == () assert 'D1_clipped_text' in report.assessed - assert 'D4_missing_glyph' in report.not_assessed + assert 'D4_missing_glyph' in report.assessed + assert 'D4_missing_glyph' not in report.not_assessed + assert report.font_evidence['status'] == 'complete' + assert report.font_evidence['codepoints'] > 0 + assert report.font_evidence['unknown'] == 0 assert report.source_units_total == report.coverage['total_units'] @@ -72,7 +76,7 @@ def test_image_limits_occlusion_but_does_not_crash_or_pass_off_as_checked(): report = check_figure(fig) assert 'D2_occluded_text' in report.not_assessed assert report.state in ('PASS', 'UNKNOWN', 'FAIL') - assert report.assessed == ('D1_clipped_text', 'D3_overlapping_text') + assert report.assessed == ('D1_clipped_text', 'D3_overlapping_text', 'D4_missing_glyph') def test_report_is_json_serialisable_and_html_has_no_script(): @@ -84,6 +88,8 @@ def test_report_is_json_serialisable_and_html_has_no_script(): html = render_html(report) assert ' 0 + finally: + font.close() + result = collect((text_record(text='AB'),), + (use(1, 65, path, expected), use(1, 66, path, 0))) + assert [g.coverage for g in result.glyphs[1]] == ['covered', 'missing'] + assert result.glyphs[1][0].fonts[0].glyph_id == expected + assert result.glyphs[1][1].fonts[0].glyph_id is None + assert result.summary['font_files'] == 1 + + +def test_capture_records_actual_fallback_font_per_rendered_codepoint(tmp_path): + from matplotlib import font_manager + base = subset_font(tmp_path / 'base.ttf', 'A', 'PlotProof Base') + fallback = subset_font(tmp_path / 'fallback.ttf', 'B', 'PlotProof Fallback') + font_manager.fontManager.addfont(str(base)) + font_manager.fontManager.addfont(str(fallback)) + fig = Figure(figsize=(3, 1), dpi=100) + FigureCanvasAgg(fig) + fig.text(.1, .5, 'AB', fontproperties=FontProperties( + family=['PlotProof Base', 'PlotProof Fallback'], size=16)) + with mpl.rc_context({'pdf.fonttype': 42, 'pdf.use14corefonts': False}): + captured = capture_pdf(fig) + by_cp = {item.codepoint: item for item in captured.font_uses if item.selected} + assert by_cp[65].path == str(base.resolve()) + assert by_cp[66].path == str(fallback.resolve()) + records = (text_record(text='AB'),) + result = collect(records, captured.font_uses, captured.warnings) + assert [g.coverage for g in result.glyphs[1]] == ['covered', 'covered'] + assert len({next(f.file_id for f in g.fonts if f.renderer_glyph_id is not None) + for g in result.glyphs[1]}) == 2 + assert result.issues == () + + +def test_unknown_font_is_explicit_d4_unknown_never_missing(tmp_path): + absent = tmp_path / 'deleted.ttf' + warning = SaveWarning('UserWarning', + 'Glyph 131072 (test character) missing from font(s) Test Sans.') + result = collect((text_record(text='\U00020000'),), + (use(1, 0x20000, absent, 0),), (warning,)) + glyph = result.glyphs[1][0] + assert glyph.coverage == 'unknown' and not glyph.proven_missing + assert glyph.fonts[0].file_id is None + assert glyph.fonts[0].cmap_status == 'unknown' + assert glyph.fonts[0].reason == 'font_unavailable' + assert result.summary['status'] == 'unavailable' + record = text_record(text='\U00020000') + checked = check_core(records=(record,), chars=pdf_chars(record.text), fills=(), + glyphs=result.glyphs, transform=Transform(72, 0, 0), + page=Rect(0, 0, 1000, 1000), source_units_total=1) + assert checked.overall_state == 'UNKNOWN' + assert [(f.rule_id, f.confidence) for f in checked.findings] == [('D4', 'medium')] + assert checked.findings[0].evidence['assessment'] == 'unknown' + assert checked.findings[0].evidence['reasons'] == ('font_unavailable',) + + +def test_missing_capture_provenance_is_unknown_for_each_source_codepoint(tmp_path): + records = (text_record(1, 'AB'), text_record(2, 'C')) + result = collect(records, (use(2, 67, dejavu(), glyph_id(dejavu(), 67)),)) + assert [g.coverage for g in result.glyphs[1]] == ['unknown', 'unknown'] + assert result.glyphs[1][0].fonts[0].reason == 'font_provenance_unavailable' + assert result.glyphs[2][0].coverage == 'covered' + assert result.summary['status'] == 'partial' + assert result.unknown_objects == () + + +def test_multiple_fonts_and_repeated_codepoints_are_bound_to_source_ids(): + regular, italic = dejavu(), dejavu('italic') + records = (text_record(1, 'AA'), text_record(2, 'A')) + uses = (use(1, 65, regular, 36), use(1, 65, italic, 36), use(2, 65, regular, 36)) + result = collect(records, uses) + assert len(result.glyphs[1]) == len(result.glyphs[2]) == 1 + assert len(result.glyphs[1][0].fonts) == 2 + assert len(result.glyphs[2][0].fonts) == 1 + assert len({f.file_id for f in result.glyphs[1][0].fonts}) == 2 + assert result.summary['font_files'] == 2 + + +def test_format4_range_offset_cannot_point_back_into_segment_arrays(): + module = font_module() + data = struct.pack('>HHHHHHH', 4, 32, 0, 4, 4, 1, 0) + data += struct.pack('>HH', 65, 0xFFFF) + struct.pack('>H', 0) + data += struct.pack('>HH', 65, 0xFFFF) + data += struct.pack('>HH', 0, 1) + data += struct.pack('>HH', 2, 0) + with pytest.raises(module._CmapMalformed): + module._parse_cmap(data, 0, len(data), 4, 100) + + +def test_malformed_cmap_is_unknown_and_does_not_call_fonttools_parser(tmp_path, monkeypatch): + source = dejavu().read_bytes() + num_tables = struct.unpack_from('>H', source, 4)[0] + cmap_offset = None + for index in range(num_tables): + entry = 12 + 16 * index + if source[entry:entry + 4] == b'cmap': + cmap_offset = struct.unpack_from('>I', source, entry + 8)[0] + break + assert cmap_offset is not None + record_count = struct.unpack_from('>H', source, cmap_offset + 2)[0] + selected = None + for index in range(record_count): + platform, encoding, relative = struct.unpack_from('>HHI', source, cmap_offset + 4 + 8 * index) + if (platform, encoding) == (3, 10): + selected = cmap_offset + relative + break + assert selected is not None + malformed = bytearray(source) + struct.pack_into('>H', malformed, selected, 0xFFFF) + path = tmp_path / 'malformed.ttf' + path.write_bytes(malformed) + + import fontTools.ttLib + monkeypatch.setattr(fontTools.ttLib, 'TTFont', + lambda *a, **k: pytest.fail('malformed cmap reached fontTools')) + result = collect((text_record(text='A'),), (use(1, 65, path, 36),)) + glyph = result.glyphs[1][0] + assert glyph.coverage == 'unknown' and not glyph.proven_missing + assert glyph.fonts[0].cmap_status == 'unknown' + assert glyph.fonts[0].reason == 'malformed_cmap' + assert 'malformed_cmap' in result.issues + + +@pytest.mark.parametrize('limits,reason', [ + ({'max_files': 0}, 'invalid_font_limits'), + ({'max_file_bytes': 1}, 'font_byte_limit'), + ({'max_total_bytes': 1}, 'font_total_byte_limit'), + ({'max_cmap_entries': 1}, 'cmap_entry_limit'), + ({'max_codepoints': 1}, 'font_codepoint_limit'), +]) +def test_font_resource_limits_fail_unknown_not_missing(tmp_path, limits, reason): + path = dejavu() + uses = (use(1, 65, path, 36), use(1, 66, path, 37)) + if reason == 'invalid_font_limits': + with pytest.raises(ValueError, match='max_files'): + collect((text_record(text='AB'),), uses, **limits) + return + result = collect((text_record(text='AB'),), uses, **limits) + assert reason in result.issues + assert result.summary['status'] != 'complete' + assert all(not glyph.proven_missing for evidence in result.glyphs.values() for glyph in evidence) + if reason == 'font_codepoint_limit': + assert result.unknown_objects + else: + assert any(g.coverage == 'unknown' for evidence in result.glyphs.values() for g in evidence) + + +def test_font_file_count_limit_marks_unread_additional_font_unknown(): + first, second = dejavu(), dejavu('italic') + result = collect((text_record(text='A'),), + (use(1, 65, first, 36), use(1, 65, second, 36)), max_files=1) + assert 'font_file_limit' in result.issues + glyph = result.glyphs[1][0] + assert glyph.coverage == 'unknown' + assert {font.cmap_status for font in glyph.fonts} == {'known', 'unknown'} + + +def test_renderer_cmap_disagreement_is_unknown_not_missing(): + path = dejavu() + result = collect((text_record(text='A'),), (use(1, 65, path, 0),)) + glyph = result.glyphs[1][0] + assert glyph.coverage == 'unknown' + assert glyph.fonts[0].cmap_status == 'unknown' + assert glyph.fonts[0].reason == 'renderer_cmap_mismatch' + assert 'renderer_cmap_mismatch' in result.issues diff --git a/tests/test_rules.py b/tests/test_rules.py index 6af9a16..615ce54 100644 --- a/tests/test_rules.py +++ b/tests/test_rules.py @@ -177,6 +177,22 @@ def test_d4_missing_warning_stack_disagreement_and_wrong_family_are_medium(): glyphs={1: (legal_fallback,)}) == () +def test_d4_unknown_provenance_does_not_suppress_d2_or_d3_findings(): + e = module('evidence') + unknown = replace(glyph_evidence(codepoint=97), fonts=(e.FontGlyph( + 'Test Sans', None, None, cmap_status='unknown', reason='font_unavailable'),)) + assert {(f.rule_id, f.confidence) for f in single( + (occluder(),), {1: (unknown,)})} == {('D2', 'high'), ('D4', 'medium')} + unknown_non_bmp = replace(glyph_evidence(), fonts=(e.FontGlyph( + 'Test Sans', None, None, cmap_status='unknown', reason='font_unavailable'),)) + records = (text_record(9, 'a', Rect(10, 10, 20, 20), font_size_pt=10), + text_record(2, 'b', Rect(15, 10, 25, 20), font_size_pt=10), + text_record(3, '𠀀', Rect(50, 10, 60, 20), font_size_pt=10)) + chars = pdf_chars('a', x=10) + pdf_chars('b', x=15) + findings = detect(records, chars, glyphs={3: (unknown_non_bmp,)}) + assert {(f.rule_id, f.confidence) for f in findings} == {('D3', 'high'), ('D4', 'medium')} + + def test_precedence_is_confidence_scoped_and_records_suppression(): # Semi-transparent D2 must not erase a high D3 on the same unit. findings = pair(fills=(occluder(box=Rect(10, 10, 25, 20), facecolor_alpha=0.5),)) From 8379c3983ab2267cd900bd6fed0b4b608fd46145 Mon Sep 17 00:00:00 2001 From: gedouluhui <208120966+gedouluhui@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:42:06 +0800 Subject: [PATCH 2/4] release: prepare plotproof 0.1.0a4 --- CHANGELOG.md | 4 +++- README.md | 2 +- README.zh-CN.md | 2 +- pyproject.toml | 2 +- 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 868782a..635ff7b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 @@ -17,6 +17,8 @@ - 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. - 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 - 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 1f2fd47..35eb2bb 100644 --- a/README.md +++ b/README.md @@ -329,7 +329,7 @@ Expected: The missing figure module returns a structured stdout JSON error with 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. diff --git a/README.zh-CN.md b/README.zh-CN.md index 27b3357..0aae887 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -71,7 +71,7 @@ estimated_work = pairs + operand_work + intersection_work + union_sort_work 证据包括完整 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 估算工作量超过预算时整类跳过。输出回滚不具备崩溃原子性。 diff --git a/pyproject.toml b/pyproject.toml index 005e2a1..88ec029 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "plotproof" -version = "0.1.0a3" +version = "0.1.0a4" description = "Source-assisted export evidence for Matplotlib figures (B1 preview: clipped/overlapping text, no font evidence)" readme = "README.md" requires-python = ">=3.12,<3.13" From 7258f7ab93054845778d43a5f0eafd6c7c159762 Mon Sep 17 00:00:00 2001 From: gedouluhui <208120966+gedouluhui@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:46:04 +0800 Subject: [PATCH 3/4] docs: align governance support metadata --- CONTRIBUTING.md | 2 +- SECURITY.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9327f0c..84e4029 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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]" diff --git a/SECURITY.md b/SECURITY.md index bc20496..cd35bcf 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -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 From ce30dfc6f98fc02efbc6a85968adb62384251272 Mon Sep 17 00:00:00 2001 From: gedouluhui <208120966+gedouluhui@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:11:54 +0800 Subject: [PATCH 4/4] fix: align PlotProof package version probes Expose the release version consistently through source and installed-package checks. --- plotproof/__init__.py | 2 +- tests/test_package.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/plotproof/__init__.py b/plotproof/__init__.py index 8b9b0e5..46a12c2 100644 --- a/plotproof/__init__.py +++ b/plotproof/__init__.py @@ -5,7 +5,7 @@ """ from __future__ import annotations -__version__ = "0.1.0a3" +__version__ = "0.1.0a4" __all__ = ["CheckError", "CheckReport", "check_figure", "render_html"] diff --git a/tests/test_package.py b/tests/test_package.py index 1d51ef5..fa1ff01 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -31,7 +31,7 @@ def run_probe(extra: str = "") -> dict[str, object]: def test_package_exposes_the_preview_version_and_lazy_api() -> None: - assert plotproof.__version__ == "0.1.0a3" + assert plotproof.__version__ == "0.1.0a4" assert sorted(plotproof.__all__) == ["CheckError", "CheckReport", "check_figure", "render_html"] # The attribute exists without importing the heavy assembly at package import. @@ -40,7 +40,7 @@ def test_package_exposes_the_preview_version_and_lazy_api() -> None: def test_importing_the_package_loads_no_heavy_dependency() -> None: probe = run_probe() - assert probe["version"] == "0.1.0a3" + assert probe["version"] == "0.1.0a4" assert probe["heavy"] == []