diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..2d9c210 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,39 @@ +# Bug report + +## Summary + +Describe the observable problem and the contract you expected to hold. Do not include secrets or private data. + +## Environment + +- Python or Node version: +- Package version or commit: +- Operating system and version: +- Relevant dependency versions: +- Installation source (editable checkout, wheel, source archive, or other): + +## Exact command + +```text +Provide the exact command and arguments that reproduce the issue. +``` + +## Minimal sanitized input + +Provide the smallest synthetic or fully sanitized input. Remove credentials, private paths, proprietary data, model weights, prompts, database rows, footage, and other sensitive content. + +## Expected result + +State the expected status, output, and exit code, and cite the relevant contract if applicable. + +## Actual result + +State the observed status, output, and exit code. Include bounded logs or report excerpts with sensitive values removed. + +## Installed package reproduction + +State whether the issue reproduces from an installed package outside the source checkout. If not, explain what differs and include the clean-install command you tried. + +## Evidence and coverage boundaries + +List the tests or checks you ran, any optional integrations that were unavailable, and what the evidence does not establish. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..e2248c6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,17 @@ +# Feature request + +## Problem + +Describe the concrete workflow or failure mode. Explain why existing behavior is insufficient without claiming unmeasured users, benchmarks, or compatibility. + +## Proposed behavior + +Describe the smallest useful behavior, its inputs and outputs, expected exit/status semantics, and how it fits the existing contract. + +## Alternatives + +List alternatives considered, including existing tools or a smaller documentation-only change. + +## Additional context + +Include Python/Node and OS versions, package version or commit, a minimal sanitized example, and any evidence or coverage boundaries. Do not include credentials or private data. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index afe51de..bf84594 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,8 +14,8 @@ jobs: os: [ubuntu-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - - uses: actions/checkout@v4 - - uses: actions/setup-python@v5 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 with: python-version: "3.12" - name: Install @@ -28,7 +28,7 @@ jobs: run: python benchmark/validate_manifest.py - name: Demo reports run: python -m plotproof demo --output ci-demo - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 if: always() with: name: demo-${{ matrix.os }} diff --git a/.pytest-tmp2/test_a2_limits_allow_both_orie0/input.pdf b/.pytest-tmp2/test_a2_limits_allow_both_orie0/input.pdf new file mode 100644 index 0000000..e60d55e Binary files /dev/null and b/.pytest-tmp2/test_a2_limits_allow_both_orie0/input.pdf differ diff --git a/.pytest-tmp2/test_character_pixel_and_respo0/input.pdf b/.pytest-tmp2/test_character_pixel_and_respo0/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_character_pixel_and_respo0/input.pdf differ diff --git a/.pytest-tmp2/test_encrypt_marker_in_plain_p0/input.pdf b/.pytest-tmp2/test_encrypt_marker_in_plain_p0/input.pdf new file mode 100644 index 0000000..a22b497 Binary files /dev/null and b/.pytest-tmp2/test_encrypt_marker_in_plain_p0/input.pdf differ diff --git a/.pytest-tmp2/test_hash_mismatch_and_size_li0/input.pdf b/.pytest-tmp2/test_hash_mismatch_and_size_li0/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_hash_mismatch_and_size_li0/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_hash_path_and_non0/input.pdf b/.pytest-tmp2/test_invalid_hash_path_and_non0/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_invalid_hash_path_and_non0/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_hash_path_and_non0/not-pdf.png b/.pytest-tmp2/test_invalid_hash_path_and_non0/not-pdf.png new file mode 100644 index 0000000..edff9fe --- /dev/null +++ b/.pytest-tmp2/test_invalid_hash_path_and_non0/not-pdf.png @@ -0,0 +1,32 @@ +%PDF-1.4 +1 0 obj +<< /Type /Catalog /Pages 2 0 R >> +endobj +2 0 obj +<< /Type /Pages /Count 1 /Kids [3 0 R] >> +endobj +3 0 obj +<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Rotate 0 /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >> +endobj +4 0 obj +<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> +endobj +5 0 obj +<< /Length 35 >> +stream +BT /F1 12 Tf 10 60 Td (Hello) Tj ET +endstream +endobj +xref +0 6 +0000000000 65535 f +0000000009 00000 n +0000000058 00000 n +0000000115 00000 n +0000000251 00000 n +0000000321 00000 n +trailer +<< /Size 6 /Root 1 0 R >> +startxref +406 +%%EOF diff --git a/.pytest-tmp2/test_invalid_pdf_shapes_are_er0/input.pdf b/.pytest-tmp2/test_invalid_pdf_shapes_are_er0/input.pdf new file mode 100644 index 0000000..f22873d Binary files /dev/null and b/.pytest-tmp2/test_invalid_pdf_shapes_are_er0/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_pdf_shapes_are_er1/input.pdf b/.pytest-tmp2/test_invalid_pdf_shapes_are_er1/input.pdf new file mode 100644 index 0000000..e799811 Binary files /dev/null and b/.pytest-tmp2/test_invalid_pdf_shapes_are_er1/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_pdf_shapes_are_er2/input.pdf b/.pytest-tmp2/test_invalid_pdf_shapes_are_er2/input.pdf new file mode 100644 index 0000000..5abd09d Binary files /dev/null and b/.pytest-tmp2/test_invalid_pdf_shapes_are_er2/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_pdf_shapes_are_er3/input.pdf b/.pytest-tmp2/test_invalid_pdf_shapes_are_er3/input.pdf new file mode 100644 index 0000000..fb66c47 Binary files /dev/null and b/.pytest-tmp2/test_invalid_pdf_shapes_are_er3/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_pdf_shapes_are_er4/input.pdf b/.pytest-tmp2/test_invalid_pdf_shapes_are_er4/input.pdf new file mode 100644 index 0000000..184fbf7 Binary files /dev/null and b/.pytest-tmp2/test_invalid_pdf_shapes_are_er4/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_pdf_shapes_are_er5/input.pdf b/.pytest-tmp2/test_invalid_pdf_shapes_are_er5/input.pdf new file mode 100644 index 0000000..86f56cb Binary files /dev/null and b/.pytest-tmp2/test_invalid_pdf_shapes_are_er5/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_pdf_shapes_are_er6/input.pdf b/.pytest-tmp2/test_invalid_pdf_shapes_are_er6/input.pdf new file mode 100644 index 0000000..c8fdb4b Binary files /dev/null and b/.pytest-tmp2/test_invalid_pdf_shapes_are_er6/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_pdf_shapes_are_er7/input.pdf b/.pytest-tmp2/test_invalid_pdf_shapes_are_er7/input.pdf new file mode 100644 index 0000000..0168600 Binary files /dev/null and b/.pytest-tmp2/test_invalid_pdf_shapes_are_er7/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_pdf_shapes_are_er8/input.pdf b/.pytest-tmp2/test_invalid_pdf_shapes_are_er8/input.pdf new file mode 100644 index 0000000..8805681 Binary files /dev/null and b/.pytest-tmp2/test_invalid_pdf_shapes_are_er8/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_render_scale_fail0/input.pdf b/.pytest-tmp2/test_invalid_render_scale_fail0/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_invalid_render_scale_fail0/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_render_scale_fail1/input.pdf b/.pytest-tmp2/test_invalid_render_scale_fail1/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_invalid_render_scale_fail1/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_render_scale_fail2/input.pdf b/.pytest-tmp2/test_invalid_render_scale_fail2/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_invalid_render_scale_fail2/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_render_scale_fail3/input.pdf b/.pytest-tmp2/test_invalid_render_scale_fail3/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_invalid_render_scale_fail3/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_render_scale_fail4/input.pdf b/.pytest-tmp2/test_invalid_render_scale_fail4/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_invalid_render_scale_fail4/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_render_scale_fail5/input.pdf b/.pytest-tmp2/test_invalid_render_scale_fail5/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_invalid_render_scale_fail5/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_render_scale_fail6/input.pdf b/.pytest-tmp2/test_invalid_render_scale_fail6/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_invalid_render_scale_fail6/input.pdf differ diff --git a/.pytest-tmp2/test_invalid_render_scale_fail7/input.pdf b/.pytest-tmp2/test_invalid_render_scale_fail7/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_invalid_render_scale_fail7/input.pdf differ diff --git a/.pytest-tmp2/test_reader_parent_never_loads0/input.pdf b/.pytest-tmp2/test_reader_parent_never_loads0/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_reader_parent_never_loads0/input.pdf differ diff --git a/.pytest-tmp2/test_real_pdf_bytes_become_unr0/input.pdf b/.pytest-tmp2/test_real_pdf_bytes_become_unr0/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_real_pdf_bytes_become_unr0/input.pdf differ diff --git a/.pytest-tmp2/test_render_dimensions_and_pix0/input.pdf b/.pytest-tmp2/test_render_dimensions_and_pix0/input.pdf new file mode 100644 index 0000000..edff9fe Binary files /dev/null and b/.pytest-tmp2/test_render_dimensions_and_pix0/input.pdf differ diff --git a/CHANGELOG.md b/CHANGELOG.md index 2739c0f..270f106 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,31 @@ # Changelog + +## Unreleased + +- Align public governance, bilingual quickstarts, issue templates, and documentation validation. +- Make CLI failures structured and fail closed, add explicit `--force` and rollback-safe paired + report publication, and apply the same overwrite policy to demo evidence. +- Add the optional positive `max_d3_work` budget (default 1,000,000 declared operations) to the + library and CLI. Over-budget runs skip all D3 pairs, mark D3 not assessed, emit a transparent + `complexity_budget` record, and remain UNKNOWN unless ERROR/high-confidence FAIL dominates. +- Replace rectangle-union strip rescans with an exact O(m log m) coordinate-compressed segment-tree + sweep, scale extreme axes independently, reject unrepresentable union areas, and pin all external CI Actions to full commit SHAs. +- Prevent alias-error overwrites and backup-name collisions, publish paired error evidence, suppress user stdout/stderr, + 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. + +## 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. +- Replace rectangle-union rescans with an exact rational coordinate-compressed segment-tree sweep; reject unrepresentable areas and account for fill and union sorting in the D3 work budget. +- Validate clean and clipped demo controls before publication and preserve named recovery evidence on failed rollback. +- Reject positive exact union areas that underflow binary64, count full aligned witness/background scans in D3 work, and refuse destination identity changes after preflight. +- Remove partial backup copies after copy failures. +- Verify 432 tests with two Windows privilege skips, the 228-sample manifest and real demo outputs. D4 remains unassessed and no holdout accuracy is claimed. + ## 0.1.0a2 — 2026-11-19 Fixes what a fresh install would have hit. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..dd974b9 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,27 @@ +# Code of Conduct + +## Our pledge + +We pledge to make participation in this project a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. + +## Our standards + +Examples of behavior that contributes to a positive environment include showing empathy, respecting differing viewpoints, giving and gracefully accepting constructive feedback, and focusing on reproducible evidence rather than personal attacks. + +Unacceptable behavior includes sexualized language or imagery, trolling or insulting comments, public or private harassment, publishing private information without permission, and other conduct that could reasonably be considered inappropriate in a professional setting. + +## Enforcement responsibilities + +Project maintainers are responsible for clarifying and enforcing these standards. They may remove, edit, or reject comments, commits, code, issues, and other contributions that violate this Code of Conduct, and will communicate reasons when appropriate. + +## Scope + +This Code of Conduct applies in project spaces and when an individual officially represents the project in public spaces. + +## Enforcement + +Report security vulnerabilities privately through GitHub Security Advisories as described in [SECURITY.md](SECURITY.md). For conduct concerns, request private contact in a minimal issue without naming individuals or including sensitive details; if no private channel is published, do not post evidence publicly. Maintainers will review reports promptly and handle them with discretion. Retaliation against a reporter is not tolerated. + +## Attribution + +Adapted from the [Contributor Covenant, version 2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..9327f0c --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,35 @@ +# Contributing + +Contributions of focused fixes, reproducible counterexamples, and documentation improvements are welcome. Read the README support status and limitations before proposing work. + +## Before you start + +- Use synthetic, self-generated, or fully sanitized inputs. Never post credentials, private datasets, model weights, prompts, databases, videos, or personal filesystem paths. +- Search existing issues and pull requests before opening a duplicate. +- For a behavior change, add a failing regression test first and show the named assertion fail before the fix. +- Keep claims bounded by executable evidence. Do not invent benchmarks, users, adoption, release URLs, or compatibility results. + +## Development setup + +Supported version: **0.1.0a2**. Install and run the primary test command: + +```sh +python -m pip install -e ".[dev]" +python -m pytest +python scripts/check_docs.py +``` + +The install and test commands above are the documented source-checkout workflow. If an optional integration dependency is unavailable, report the exact skip or failure instead of treating it as a pass. + +## Pull requests + +- Keep the change scoped and explain the problem, contract, and evidence. +- Preserve existing CLI/API/report semantics unless the pull request explicitly revises the contract and updates tests and documentation. +- Add positive and negative controls for security, correctness, or output-publication changes. +- Do not add runtime network access, telemetry, hidden dependencies, or unsupported compatibility claims without an explicit design discussion. +- Run the relevant tests plus `python scripts/check_docs.py`, and state any environment you could not verify. +- Contributions are provided under the repository's MIT license; third-party dependencies retain their own licenses. + +## Reporting issues + +Use the bug or feature template. Include Python/Node and OS versions, package version or commit, the exact command, minimal sanitized input, expected and actual results, and whether the issue reproduces from an installed package. For vulnerabilities, follow [SECURITY.md](SECURITY.md) instead of opening a public issue. diff --git a/README.md b/README.md index 2cf4633..9809346 100644 --- a/README.md +++ b/README.md @@ -5,8 +5,8 @@ figure intends to draw at save time, compares that record with the exported PDF, 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 -> (356 tests). An experimental assembly runs the whole path end to end on one figure. +> 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 > [What this does not do](#what-this-does-not-do) before trusting any output. @@ -77,16 +77,44 @@ def figure(): ``` ```bash -.venv/Scripts/python -m plotproof check make_figure.py --json report.json --html report.html -# exit 0 for PASS/UNKNOWN, 1 for FAIL, 2 when the figure is outside the contract +.venv/Scripts/python -m plotproof check make_figure.py --json report.json --html report.html --max-d3-work 1000000 +# add --force only when intentionally replacing existing reports +# exit 0 for PASS/UNKNOWN, 1 for FAIL, 2 for ERROR reports or input/check/budget/output failures ``` +Existing JSON/HTML files are refused unless `--force` is supplied. Destinations are +preflighted before the figure module runs: symlinks, non-files/non-directory parents, ambiguous Windows trailing-dot/space/reserved components, input-module aliases +(including hardlinks), JSON/HTML aliases, and collisions with `.plotproof-backup` are rejected. Report text is staged before +publication. Existing targets are backed up, then replaced in order; an ordinary publication failure rolls back both files. If rollback also fails, +only the recovery backups that still exist are retained and reported for manual recovery. This is **not crash atomicity**: a +process or power loss can leave a mixed pair. The demo uses the same policy and also +requires `--force` to replace old evidence. + +### Structured CLI errors + +Input, factory, check, budget and output failures return exit 2 and print one JSON object +to stdout, without a traceback or private exception/path details: + +```json +{ + "status": "ERROR", + "error": {"code": "INPUT_NOT_FOUND", "message": "The input module does not exist."} +} +``` + +When `--json` or `--html` names a safe destination, the error object (and a minimal escaped ERROR page) is published as a pair when possible. A failed +error-publication attempt never hides the original error. Preflight/argument failures are stdout-only, so an alias refusal cannot overwrite the file it refused. User import/factory/check stdout and stderr are discarded at both Python and OS file-descriptor level, including child-process inheritance, to keep diagnostics parseable. `KeyboardInterrupt` is not +converted. Other stable codes include `FACTORY_NOT_FOUND`, `FACTORY_FAILED`, +`IMPORT_FAILED`, `CHECK_FAILED`, `INVALID_ARGUMENTS`, `INVALID_BUDGET`, `OUTPUT_EXISTS`, `OUTPUT_ALIAS`, +`INPUT_ALIAS`, `OUTPUT_SYMLINK`, `OUTPUT_BACKUP_EXISTS`, `OUTPUT_PUBLISH_FAILED` and +`OUTPUT_ROLLBACK_FAILED`. + The library form is the same call: ```python import plotproof -report = plotproof.check_figure(fig) # captures, reads, checks +report = plotproof.check_figure(fig, max_d3_work=1_000_000) # optional positive integer print(report.state, report.assessed) ``` @@ -96,7 +124,7 @@ 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 | +| 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) | Every report states the classes it assessed and why the others were skipped: @@ -111,6 +139,37 @@ Every report states the classes it assessed and why the others were skipped: } ``` +### D3 complexity budget + +`check_figure(..., max_d3_work=N)` and `check --max-d3-work N` accept a positive integer; +the finite default is 1,000,000 declared operations. After alignment, PlotProof estimates +all supported-unit pair work in O(n + fills): + +```text +pairs = n*(n-1)/2 +operand_work = (n-1)*sum(c_i) +intersection_work = (sum(c_i)^2 - sum(c_i^2))/2 +union_sort_work = (n-1)*sum(sort_work(c_i) + 2*sort_work(2*c_i)) +cut_union_work = pairs*(sort_work(max(c_i)^2) + 2*sort_work(2*max(c_i)^2)) +fill_work = pairs*(fill_count + sort_work(fill_count)) +estimated_work = pairs + operand_work + intersection_work + union_sort_work + + cut_union_work + fill_work + 32*pairs +``` + +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 +`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. + +Rectangle unions use an exact rational coordinate-compressed segment-tree sweep, O(m log m), rather +than rescanning every box for every x strip. Rational coordinates avoid intermediate overflow, +mixed-scale underflow and `inf * 0`; a true union area that cannot be represented as a finite, +nonzero float raises `ValueError` instead of emitting `NaN`/`Infinity` or false zero evidence. + **`PASS` means "no supported defect was found with sufficient coverage in the assessed classes".** It is not a statement that the figure is correct, and it is not a benchmark result. @@ -204,7 +263,7 @@ Verified facts worth knowing before extending this: ```bash .venv/Scripts/python -m pip install -e ".[dev]" -.venv/Scripts/python -m pytest # 356 tests +python -m pytest # run the full suite; see task report for verified totals .venv/Scripts/python benchmark/validate_manifest.py ``` @@ -223,18 +282,52 @@ PlotProof 检查 Matplotlib 导出 PDF 时的**静默失败**:轴标签被页 文字互相遮挡、中文缺字变成空白或方框。它靠两条证据:保存时在 Matplotlib 内部记录的 绘制意图,以及用受限 PDFium 子进程读出的字符框。 -当前是 **B1 工程预览**:确定性核心、受限 PDF 读取、CA1 保存期采集都已实现并通过 356 项 -测试;端到端装配可以真正跑通一张图,**但不是认证过的检测器**——没有保留集结果、没有 +当前是 **B1 工程预览**:确定性核心、受限 PDF 读取、CA1 保存期采集都已实现并通过完整测试; +端到端装配可以真正跑通一张图,**但不是认证过的检测器**——没有保留集结果、没有 准确率数字、没有字体 cmap 证据。 -- 已评估:D1 文字被裁、D3 文字重叠;D2 遮挡仅在“没有图像/集合被绘制”时评估。 +- 已评估:D1 文字被裁、D3 文字重叠(未超出复杂度预算时);D2 遮挡仅在“没有图像/集合被绘制”时评估。 - 未评估:D4 缺字(下一步做字体证据)。 - 旋转文字(含默认竖排 y 轴标签)、数学公式、自动换行文字不支持,会强制 `UNKNOWN`。 - `PASS` 只表示“在已评估类别中、覆盖率足够时没发现受支持的缺陷”,不代表图正确。 ```bash python -m plotproof demo --output plotproof-demo # 干净图 PASS / 故意裁切图 FAIL -python -m plotproof check make_figure.py --html report.html +python -m plotproof demo --output plotproof-demo --force # 明确替换旧证据 +python -m plotproof check make_figure.py --html report.html --max-d3-work 1000000 +``` + +退出码:`0` 表示 PASS/UNKNOWN,`1` 表示 FAIL,`2` 表示 ERROR 报告或输入、工厂、检查、预算、输出错误。 +错误以 stdout 中的结构化 JSON 返回;旧报告需显式 `--force` 才替换,相关回滚与 D3 预算语义 +见上方“安全输出”“结构化 CLI 错误”和“D3 复杂度预算”。 + +## Quickstart and support + +### Problem +Detect silent Matplotlib PDF export defects by combining save-time draw intent with bounded PDF character-box evidence. + +### Install +```sh +python -m pip install -e ".[dev]" ``` -退出码:`0` 表示 PASS/UNKNOWN,`1` 表示 FAIL,`2` 表示超出契约。 +### Success +```sh +python -m plotproof demo --output plotproof-demo +``` +Expected: The generated clean figure passes and the deliberately clipped figure fails; the demo command exits 0 after verifying both controls. + +### Deliberate failure +```sh +python -m plotproof check does-not-exist.py --json missing-report.json --html missing-report.html +``` +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. + +### 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. + +### 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 new file mode 100644 index 0000000..45775c7 --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,77 @@ +# PlotProof 中文快速开始 + +[English](README.md) + +## 快速开始与支持状态 + +### 问题 +通过结合保存时绘制意图和受限 PDF 字符框证据,检测 Matplotlib PDF 导出的静默缺陷。 + +### 安装 +```sh +python -m pip install -e ".[dev]" +``` + +### 成功命令 +```sh +python -m plotproof demo --output plotproof-demo +``` +预期:干净图通过,故意裁切图失败;演示验证两个对照后退出码 0。 + +### 故意失败命令 +```sh +python -m plotproof check does-not-exist.py --json missing-report.json --html missing-report.html +``` +预期:缺失的 figure 模块返回结构化错误,退出码为 2,stdout 输出 JSON,且不声称成功。 + +### 安全输出与结构化错误 + +`check` 与 `demo` 默认拒绝覆盖已有报告;确认需要替换时显式添加 `--force`。所有目标会在 +执行 figure 模块前预检:拒绝符号链接、非普通文件/父目录、Windows 尾点/空格/保留组件、输入模块别名(含硬链接)、JSON/HTML +互相别名,以及与 `<目标>.plotproof-backup` 冲突的目标。报告文本先完整暂存,再按顺序发布;已有文件先备份。 +普通发布失败会回滚两个文件;回滚也失败时只保留并报告仍实际存在的恢复备份。此机制**不是崩溃原子性**: +进程或断电仍可能留下不配套的报告。 + +输入、工厂、检查、预算和输出失败均返回退出码 2,stdout 只输出如下结构化对象,不包含 traceback、 +原始异常内容或私有绝对路径: + +```json +{"status":"ERROR","error":{"code":"INPUT_NOT_FOUND","message":"The input module does not exist."}} +``` + +`--json` 或 `--html` 目的地安全时会尽量以配对方式写入错误 JSON 与最小转义 ERROR 页面;错误写入失败不会遮蔽原始错误。预检/参数失败只写 stdout,避免覆盖被拒绝的别名。用户 figure 模块的 stdout/stderr 会在 Python 与操作系统 fd 层丢弃,子进程继承的输出也会被隔离。`KeyboardInterrupt` +不会被转换。稳定错误码还包括 `FACTORY_NOT_FOUND`、`FACTORY_FAILED`、`IMPORT_FAILED`、 +`CHECK_FAILED`、`INVALID_ARGUMENTS`、`INVALID_BUDGET`、`OUTPUT_EXISTS`、`OUTPUT_ALIAS`、`INPUT_ALIAS`、 +`OUTPUT_SYMLINK`、`OUTPUT_BACKUP_EXISTS`、`OUTPUT_PUBLISH_FAILED` 和 `OUTPUT_ROLLBACK_FAILED`。 + +### D3 复杂度预算 + +`check_figure(..., max_d3_work=N)` 与 `check --max-d3-work N` 接受正整数,默认上限为 +1,000,000 个声明操作。对齐后以 O(n + fills) 估算全部受支持单元的两两工作: + +```text +pairs = n*(n-1)/2 +operand_work = (n-1)*sum(c_i) +intersection_work = (sum(c_i)^2-sum(c_i^2))/2 +union_sort_work = (n-1)*sum(sort_work(c_i) + 2*sort_work(2*c_i)) +cut_union_work = pairs*(sort_work(max(c_i)^2) + 2*sort_work(2*max(c_i)^2)) +fill_work = pairs*(fill_count + sort_work(fill_count)) +estimated_work = pairs + operand_work + intersection_work + union_sort_work + + cut_union_work + fill_work + 32*pairs +``` + +`c_i` 为对齐后的字符框数(未对齐时为一个源框)。这是声明的操作预算,不是精确耗时预测。 +估算值超过上限时跳过整个 D3 两两循环,绝不静默丢弃部分配对;D1、D2 和核心的显式 D4 +行为保留。装配层仍因未采集字体 cmap 证据而将 `D4_missing_glyph` 标为未评估。D3 转为 +`not_assessed`,机器可读的 `complexity_budget` 记录估算分量、配对数、上限、公式和 +`skipped: true`;除非已有 `ERROR` 或高置信度 `FAIL` 正确优先,否则状态为 `UNKNOWN`。 +估算值等于上限时仍执行 D3。矩形并集采用精确有理数坐标压缩线段树扫描,复杂度 O(m log m);有理坐标避免混合尺度下溢与中间溢出,真正无法表示为有限非零浮点数的面积会抛错,而不是返回虚假的有限零值。 + +### 证据与覆盖边界 +证据包括完整 pytest 测试,覆盖确定性核心、受限 PDF 读取器、CA1 采集、结构化 CLI、安全发布、复杂度预算和端到端装配。没有保留集结果、准确率数字或字体 cmap 证据,D4_missing_glyph 未评估。PASS 仅表示在已评估类别中且覆盖足够时未发现受支持的缺陷。 + +### 支持状态 +版本 0.1.0a3 是面向 Python 3.12 和 Matplotlib 3.10.8 的 B1 工程预览。PDF worker 路径仅在 Windows 上验证。它不是认证检测器,也没有准确率声明。维护为尽力而为,不提供 SLA。 + +### 限制 +不支持旋转文字、数学公式、TeX、自动换行/栅格化文字、路径效果、任意/多页/旋转 PDF,也不做语义或美学判断。当图像或集合导致绘制清单不完整时,D2 会被跳过;D3 估算工作量超过预算时整类跳过。输出回滚不具备崩溃原子性。 diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..bc20496 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,15 @@ +# Security + +## 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. + +## Reporting a vulnerability + +Do not include credentials, private data, proprietary inputs, personal paths, or unreduced production artifacts in public issues. Report vulnerabilities privately through [GitHub Security Advisories](https://github.com/gedouluhui/plotproof/security/advisories/new). Include the affected version or commit, operating system, runtime/dependency versions, a minimal sanitized reproduction, and the security impact you observed. + +## Security boundaries + +The checker executes a local figure module and an owned PDFium worker against bounded local files. It is not a hostile-code sandbox or a general PDF security checker. + +Hashes and fingerprints identify bytes or normalized inputs; they are not signatures or proof of trust. Review generated reports before sharing because metadata, names, prompts, queries, or previews may still be sensitive. diff --git a/docs/B1_EXPORT_ASSEMBLY.md b/docs/B1_EXPORT_ASSEMBLY.md index 94e5c58..3f451ee 100644 --- a/docs/B1_EXPORT_ASSEMBLY.md +++ b/docs/B1_EXPORT_ASSEMBLY.md @@ -52,6 +52,56 @@ fail-closed decisions; it does not add a rule. assessed classes only. Hard limits (invalid geometry, ambiguous crop origin, non-rectangular clip, wrapped text) are still `ERROR`. +## Fail-closed CLI and paired publication + +The CLI places loading, factory execution, checking, serialization and publication behind a +structured error boundary. Exit 2 emits `{"status":"ERROR","error":{"code":"...","message":"..."}}` +on stdout without tracebacks, arbitrary exception text or private absolute paths. User +`SystemExit` is structured during import/factory/check execution; `KeyboardInterrupt` is not caught. +User import/factory/check stdout and stderr are discarded at Python and OS-fd level, including inherited child handles. Safe `--json`/`--html` destinations receive +the error JSON and a minimal escaped ERROR page as a pair when possible; preflight/argument +failures remain stdout-only so they cannot overwrite a refused alias. + +Before loading/checking, all output destinations are preflighted. Symlinks, non-files, aliases +of the input module (resolved paths and `samefile`, including hardlinks), and JSON/HTML aliases +are refused, including ambiguous Windows trailing-dot/space/reserved components. Existing files require explicit `--force`. Backup names are reserved during preflight, +so an output cannot collide with another output's recovery path. All report text is staged first; +existing targets are copied to `.plotproof-backup`, then atomically replaced per file in +order. Ordinary publication failure rolls back all published targets. Successful rollback removes +backups; rollback failure retains and reports only backups that still exist and raises `OUTPUT_ROLLBACK_FAILED`. +This is recoverable ordinary-failure behavior, **not crash atomicity**. Demo preflights and stages +both controls together, requires clean PASS plus clipped FAIL before publication, and uses the same force/backup/rollback mechanism. + +## D3 complexity budget and union geometry + +`check_figure` and pure `check_core` accept optional positive integer `max_d3_work`, default +1,000,000; the CLI exposes `--max-d3-work`. Validation happens before capture/accounting. +After alignment, `estimate_d3_work` computes in O(n + fills): + +```text +pairs = n*(n-1)/2 +operand_work = (n-1)*sum(c_i) +intersection_work = (sum(c_i)^2-sum(c_i^2))/2 +union_sort_work = (n-1)*sum(sort_work(c_i) + 2*sort_work(2*c_i)) +cut_union_work = pairs*(sort_work(max(c_i)^2) + 2*sort_work(2*max(c_i)^2)) +fill_work = pairs*(fill_count + sort_work(fill_count)) +estimated_work = pairs + operand_work + intersection_work + union_sort_work + + cut_union_work + fill_work + 32*pairs +``` + +`c_i` is the aligned character-box count, or one for an unaligned source box. The estimate is a +declared operation budget, not a runtime prediction. An estimate strictly greater than the limit +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. + +`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 +or underflow-to-zero nonzero area raises instead of returning false finite evidence. +Independent integer/fractional cell oracles, duplicates, touching boxes, extreme finite coordinates, +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 @@ -72,5 +122,11 @@ core: - a figure without an Agg canvas raises `CheckError` instead of guessing; - the demo CLI writes both reports and returns 0. -The full suite is 358 tests. None of this is a holdout result, and the holdout remains -unopened. +Task 4 adds `tests/test_cli_errors.py`, `tests/test_output_alias.py`, +`tests/test_complexity_budget.py`, and independent geometry sweep regressions. These exercise the +real CLI/publication/core paths; fault injection is limited to ordinary filesystem failures. +The final 0.1.0a3 gate ran **432 tests with two Windows privilege skips**. The benchmark +manifest passed with 228 samples (114 holdout), and the real demo returned clean `PASS` and +clipped `FAIL` before publishing both reports. The suite includes strict CLI/publication, +Windows alias, low-level output, complexity-budget and exact-geometry regressions. These are +regression and fixture checks, not a holdout detector result; the holdout remains unopened. diff --git a/plotproof/__init__.py b/plotproof/__init__.py index 67fe8cb..8b9b0e5 100644 --- a/plotproof/__init__.py +++ b/plotproof/__init__.py @@ -5,7 +5,7 @@ """ from __future__ import annotations -__version__ = "0.1.0a2" +__version__ = "0.1.0a3" __all__ = ["CheckError", "CheckReport", "check_figure", "render_html"] diff --git a/plotproof/cli.py b/plotproof/cli.py index 964dab5..d3c74e1 100644 --- a/plotproof/cli.py +++ b/plotproof/cli.py @@ -2,42 +2,288 @@ 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 -from pathlib import Path +import os +from pathlib import Path, PureWindowsPath +import shutil +import stat import sys +import tempfile from .export import CheckError, CheckReport, check_figure, render_html +from .rules import DEFAULT_MAX_D3_WORK, validate_max_d3_work -def _write(path: Path, text: str) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(text, encoding='utf-8', newline='\n') +class StructuredParser(argparse.ArgumentParser): + def error(self, message): + raise ValueError('invalid command line') -def _save(report: CheckReport, json_path: str | None, html_path: str | None) -> None: - payload = json.dumps(report.to_dict(), indent=2, sort_keys=True) + '\n' - if json_path: - _write(Path(json_path), payload) - else: +@contextmanager +def _quiet_user_output(): + sys.stdout.flush() + sys.stderr.flush() + saved_stdout = os.dup(1) + saved_stderr = os.dup(2) + try: + with open(os.devnull, 'w', encoding='utf-8') as sink: + os.dup2(sink.fileno(), 1) + os.dup2(sink.fileno(), 2) + try: + with redirect_stdout(sink), redirect_stderr(sink): + yield + finally: + sys.stdout.flush() + sys.stderr.flush() + os.dup2(saved_stdout, 1) + os.dup2(saved_stderr, 2) + finally: + os.close(saved_stdout) + os.close(saved_stderr) + + +class OutputError(ValueError): + """A safe publication contract failed; details never contain user paths.""" + + def __init__(self, code: str, message: str, recovery_backups: tuple[str, ...] = ()): + self.code = code + self.message = message + self.recovery_backups = recovery_backups + super().__init__(message) + + +def _error_payload(code: str, message: str, recovery_backups=()) -> dict: + error = {'code': code, 'message': message} + if recovery_backups: + error['recovery_backups'] = list(recovery_backups) + return {'status': 'ERROR', 'error': error} + + +def _same_file(left: Path, right: Path) -> bool: + try: + return os.path.samefile(left, right) + except OSError: + return False + + +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 = [] + source = Path(input_path).resolve() if input_path is not None else None + for raw in (json_path, html_path): + if not raw: + destinations.append(None) + continue + path = Path(raw) + if os.name == 'nt': + for part in path.parts: + if part == path.anchor: + continue + if part.endswith(('.', ' ')) or ':' in part or PureWindowsPath(part).is_reserved(): + raise OutputError('OUTPUT_AMBIGUOUS', 'Output paths contain ambiguous or reserved Windows components.') + resolved = path.resolve() + if source is not None and (resolved == source or _same_file(resolved, source)): + raise OutputError('INPUT_ALIAS', 'An output destination aliases the input module.') + if path.is_symlink(): + raise OutputError('OUTPUT_SYMLINK', 'Output destinations must not be symbolic links.') + 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: + continue + if path.parent.exists() and not path.parent.is_dir(): + raise OutputError('OUTPUT_PARENT', 'Output parent must be a directory.') + backup = path.with_name(path.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): + 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.') + return destinations[0], destinations[1] + + +def _remove_quietly(path: Path) -> None: + try: + path.unlink(missing_ok=True) + except BaseException: + # Recovery/cleanup must not turn committed reports into a failed run. + pass + + +def _output_identity(path: Path): + try: + info = path.lstat() + except FileNotFoundError: + return None + if not stat.S_ISREG(info.st_mode): + raise OutputError('OUTPUT_CONFLICT', 'Output destination changed to a non-regular file.') + return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns + + +def _expected_identities(items): + return {path: _output_identity(path) for path, _ in items} + + +def _publish_texts(items: list[tuple[Path, str]], expected=None) -> None: + """Publish in order with named backups and best-effort ordinary-failure rollback. + + This is not crash atomicity: a process/power loss between replacements can + leave a mixed pair. Backups are named ``.plotproof-backup``. + """ + staged: list[tuple[Path, Path]] = [] + backups: dict[Path, Path] = {} + published: list[Path] = [] + try: + 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) + temporary = Path(name) + staged.append((path, temporary)) + try: + handle = os.fdopen(fd, 'w', encoding='utf-8', newline='\n') + fd = None + with handle: + handle.write(text) + finally: + if fd is not None: + os.close(fd) + 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.') + if path.exists(): + backup = path.with_name(path.name + '.plotproof-backup') + if backup.exists() or backup.is_symlink(): + raise OutputError('OUTPUT_BACKUP_EXISTS', 'A named recovery backup already exists.') + try: + shutil.copy2(path, backup) + except BaseException: + _remove_quietly(backup) + raise + backups[path] = backup + for path, temporary in staged: + os.replace(temporary, path) + published.append(path) + except Exception as error: + for path in list(backups): + if path not in published: + _remove_quietly(backups.pop(path)) + rollback_failed = [] + for path in reversed(published): + try: + if path in backups: + os.replace(backups[path], path) + backups.pop(path, None) + else: + path.unlink(missing_ok=True) + except Exception: + rollback_failed.append(path) + if rollback_failed: + remaining = tuple(backup.name for backup in backups.values() if backup.exists()) + remaining += tuple(path.name for path in rollback_failed + if path not in backups and path.exists()) + raise OutputError('OUTPUT_ROLLBACK_FAILED', + 'Publication and rollback failed; recover from the named backups or partial outputs.', + remaining) from None + for backup in backups.values(): + _remove_quietly(backup) + if isinstance(error, OutputError): + raise + raise OutputError('OUTPUT_PUBLISH_FAILED', 'Report publication failed; previous outputs were restored.') from None + finally: + for _, temporary in staged: + _remove_quietly(temporary) + for backup in backups.values(): + _remove_quietly(backup) + + +def _save(report: CheckReport, json_path: str | None, html_path: str | None, *, + force: bool = False, input_path: str | Path | None = None, expected=None) -> None: + json_target, html_target = _preflight(json_path, html_path, force=force, input_path=input_path) + if expected is None: + expected = _expected_identities([(path, '') for path in (json_target, html_target) if path is not None]) + try: + payload = json.dumps(report.to_dict(), indent=2, sort_keys=True, allow_nan=False) + '\n' + 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.append((html_target, html)) + _publish_texts(items, expected) + if json_target is None: sys.stdout.write(payload) - if html_path: - _write(Path(html_path), render_html(report)) def _load_figure(module_path: str, factory: str): path = Path(module_path).resolve() if not path.is_file(): - raise SystemExit('no such file: %s' % path) + raise FileNotFoundError spec = spec_from_file_location('plotproof_user_figure', path) if spec is None or spec.loader is None: - raise SystemExit('cannot import %s' % path) + raise ImportError module = module_from_spec(spec) - spec.loader.exec_module(module) - build = getattr(module, factory, None) + try: + with _quiet_user_output(): + spec.loader.exec_module(module) + except SystemExit: + raise + except Exception: + raise ImportError from None + try: + with _quiet_user_output(): + build = getattr(module, factory, None) + except SystemExit: + raise + except Exception: + raise ImportError from None if not callable(build): - raise SystemExit('%s has no callable %s()' % (path.name, factory)) - return build() + raise LookupError + try: + with _quiet_user_output(): + return build() + except SystemExit: + raise RuntimeError from None + except Exception: + raise RuntimeError from None + + +def _error_html(payload): + error = payload['error'] + return ('PlotProof error' + '

ERROR

' + escape(error['code']) + ' ' + + escape(error['message']) + '

\n') + + +def _emit_error(code: str, message: str, json_path: str | None, html_path: str | None = None, *, + force: bool = False, input_path: str | Path | None = None, + recovery_backups=(), expected=None) -> None: + payload = _error_payload(code, message, recovery_backups) + text = json.dumps(payload, indent=2, sort_keys=True, allow_nan=False) + '\n' + if json_path or html_path: + try: + json_target, html_target = _preflight(json_path, html_path, force=force, input_path=input_path) + items = [] + if json_target is not None: + items.append((json_target, text)) + if html_target is not None: + items.append((html_target, _error_html(payload))) + _publish_texts(items, _expected_identities(items) if expected is None else expected) + except OutputError as publication_error: + if publication_error.recovery_backups: + payload = _error_payload(code, message, publication_error.recovery_backups) + text = json.dumps(payload, indent=2, sort_keys=True, allow_nan=False) + '\n' + except Exception: + pass + try: + sys.stdout.write(text) + except OSError: + pass def _demo_figure(deliberate: bool): @@ -56,36 +302,147 @@ def _demo_figure(deliberate: bool): return fig +def _check_command(args) -> int: + try: + args.max_d3_work = int(args.max_d3_work) + validate_max_d3_work(args.max_d3_work) + json_target, html_target = _preflight(args.json_path, args.html_path, + force=args.force, input_path=args.module) + expected = _expected_identities([(path, '') for path in (json_target, html_target) + if path is not None]) + except OutputError as error: + _emit_error(error.code, error.message, None) + return 2 + except ValueError: + _emit_error('INVALID_BUDGET', '--max-d3-work must be a positive integer.', None) + return 2 + except OSError: + _emit_error('OUTPUT_FAILED', 'Output destinations could not be preflighted.', None) + return 2 + + def emit(code, message, recovery=()): + _emit_error(code, message, args.json_path, args.html_path, + force=args.force, input_path=args.module, + recovery_backups=recovery, expected=expected) + + try: + fig = _load_figure(args.module, args.factory) + except FileNotFoundError: + emit('INPUT_NOT_FOUND', 'The input module does not exist.') + return 2 + except OSError: + emit('INPUT_LOAD_FAILED', 'The input module could not be read.') + return 2 + except LookupError: + emit('FACTORY_NOT_FOUND', 'The input module has no callable with the requested factory name.') + return 2 + except ImportError: + emit('IMPORT_FAILED', 'The input module could not be imported.') + return 2 + except SystemExit: + emit('IMPORT_FAILED', 'The input module exited during import.') + return 2 + except RuntimeError: + emit('FACTORY_FAILED', 'The figure factory failed.') + return 2 + try: + with _quiet_user_output(): + report = check_figure(fig, max_d3_work=args.max_d3_work) + except SystemExit: + emit('CHECK_FAILED', 'Figure checking failed.') + return 2 + except Exception: + emit('CHECK_FAILED', 'Figure checking failed.') + return 2 + try: + _save(report, args.json_path, args.html_path, force=args.force, + input_path=args.module, expected=expected) + except OutputError as error: + if error.code == 'OUTPUT_SERIALIZATION_FAILED': + emit(error.code, error.message, error.recovery_backups) + else: + _emit_error(error.code, error.message, None, + recovery_backups=error.recovery_backups) + return 2 + except Exception: + _emit_error('OUTPUT_FAILED', 'Report publication failed.', None) + return 2 + if report.state == 'FAIL': + return 1 + return 2 if report.state == 'ERROR' else 0 + + +def _demo_command(args) -> int: + output = Path(args.output).resolve() + destinations = [] + try: + for name in ('clean', 'clipped'): + pair = _preflight(str(output / (name + '.json')), + str(output / (name + '.html')), force=args.force) + destinations.extend(path for path in pair if path is not None) + for index, path in enumerate(destinations): + if any(path == other or _same_file(path, other) for other in destinations[index + 1:]): + raise OutputError('OUTPUT_ALIAS', 'Demo report destinations must be different files.') + except OutputError as error: + _emit_error(error.code, error.message, None) + return 2 + except OSError: + _emit_error('OUTPUT_FAILED', 'Demo destinations could not be preflighted.', None) + return 2 + expected = _expected_identities([(path, '') for path in destinations]) + try: + reports = [(name, check_figure(_demo_figure(deliberate))) + for name, deliberate in (('clean', False), ('clipped', True))] + except SystemExit: + _emit_error('CHECK_FAILED', 'Demo figure checking failed.', None) + return 2 + except Exception: + _emit_error('CHECK_FAILED', 'Demo figure checking failed.', None) + return 2 + if reports[0][1].state != 'PASS' or reports[1][1].state != 'FAIL': + _emit_error('CHECK_FAILED', 'Demo clean/clipped controls did not produce their required states.', None) + return 2 + try: + # Stage both controls before publishing either, so serialization cannot + # leave half of the demo evidence behind. + staged = [] + for name, report in reports: + staged.append((output / (name + '.json'), + json.dumps(report.to_dict(), indent=2, sort_keys=True, allow_nan=False) + '\n')) + staged.append((output / (name + '.html'), render_html(report))) + _publish_texts(staged, expected) + except OutputError as error: + _emit_error(error.code, error.message, None, + recovery_backups=error.recovery_backups) + return 2 + except Exception: + _emit_error('OUTPUT_FAILED', 'Demo report publication failed.', None) + return 2 + for name, report in reports: + print('%s: %s' % (name, report.state)) + return 0 + + def main(argv=None) -> int: - parser = argparse.ArgumentParser(prog='plotproof', + parser = StructuredParser(prog='plotproof', description='Source-assisted export evidence for Matplotlib figures.') sub = parser.add_subparsers(dest='command', required=True) demo = sub.add_parser('demo', help='run a clean and a deliberately clipped sample') demo.add_argument('--output', default='plotproof-demo', help='directory for reports') + demo.add_argument('--force', action='store_true', help='replace existing demo reports explicitly') check = sub.add_parser('check', help='check a figure built by a Python file') check.add_argument('module', help='path to a .py file exposing figure()') check.add_argument('--factory', default='figure', help='callable returning a Figure (default: figure)') check.add_argument('--json', dest='json_path', default=None) check.add_argument('--html', dest='html_path', default=None) - args = parser.parse_args(argv) - - if args.command == 'demo': - output = Path(args.output) - status = 0 - for name, deliberate in (('clean', False), ('clipped', True)): - report = check_figure(_demo_figure(deliberate)) - _save(report, str(output / (name + '.json')), str(output / (name + '.html'))) - print('%s: %s' % (name, report.state)) - if deliberate and report.state != 'FAIL': - print('the deliberate sample did not produce a finding', file=sys.stderr) - status = 1 - return status - + check.add_argument('--force', action='store_true', help='replace existing reports explicitly') + check.add_argument('--max-d3-work', default=DEFAULT_MAX_D3_WORK, + help='positive declared D3 operation budget (default: %(default)s)') try: - fig = _load_figure(args.module, args.factory) - except CheckError as error: - print('check failed: %s' % error.reason, file=sys.stderr) + args = parser.parse_args(argv) + except ValueError: + _emit_error('INVALID_ARGUMENTS', 'The command line is invalid.', None) return 2 - report = check_figure(fig) - _save(report, args.json_path, args.html_path) - return 1 if report.state == 'FAIL' else 0 + except SystemExit as exc: + return int(exc.code or 0) + return _demo_command(args) if args.command == 'demo' else _check_command(args) diff --git a/plotproof/core.py b/plotproof/core.py index 79f4e76..1876c65 100644 --- a/plotproof/core.py +++ b/plotproof/core.py @@ -12,7 +12,7 @@ from .evidence import GlyphEvidence, PdfChar, TextRecord from .geometry import Rect, Transform from .occlusion import FilledRecord -from .rules import Finding, detect_rules +from .rules import DEFAULT_MAX_D3_WORK, Finding, detect_rules, validate_max_d3_work from .units import AccountingError, enumerate_units @@ -24,6 +24,7 @@ class CoreResult: unknown_objects: tuple[dict, ...] errors: tuple[dict, ...] zero_unit_samples: int + complexity_budget: dict | None = None def to_dict(self) -> dict: result = asdict(self) @@ -59,25 +60,29 @@ def _check_references(records: Sequence[TextRecord], fills: Sequence[FilledRecor def check_core(*, records: Sequence[TextRecord], chars: Sequence[PdfChar], fills: Sequence[FilledRecord], glyphs: Mapping[int, Sequence[GlyphEvidence]], transform: Transform, page: Rect, source_units_total: int, - errors: Sequence[dict] = ()) -> CoreResult: + errors: Sequence[dict] = (), max_d3_work: int = DEFAULT_MAX_D3_WORK) -> CoreResult: """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 = [] try: _check_references(records, fills, glyphs) units = enumerate_units(records, transform, page, source_units_total) alignment = align_units(units, chars, glyphs) coverage = alignment.coverage - findings = detect_rules(alignment, page, fills, glyphs) + findings = detect_rules(alignment, page, fills, glyphs, + max_d3_work=max_d3_work, budget_record=budget_record) except AccountingError as error: return CoreResult('ERROR', None, (), (), (*errors, {'stage': 'accounting', 'message': str(error)}), 0) + budget = budget_record[0] unknown = tuple({'source_object_id': uid, 'reason': reason} for uid, reason in alignment.unknown.items()) if errors: state = 'ERROR' elif any(f.confidence == 'high' for f in findings): state = 'FAIL' - elif (findings or coverage['ratio'] is None or coverage['ratio'] < 0.90 + elif (budget is not None or findings or coverage['ratio'] is None or coverage['ratio'] < 0.90 or coverage['unsupported_units'] > 0): state = 'UNKNOWN' else: state = 'PASS' - return CoreResult(state, coverage, findings, unknown, errors, int(source_units_total == 0)) + return CoreResult(state, coverage, findings, unknown, errors, int(source_units_total == 0), budget) diff --git a/plotproof/export.py b/plotproof/export.py index 60a9bae..fa6ba01 100644 --- a/plotproof/export.py +++ b/plotproof/export.py @@ -27,6 +27,7 @@ from .geometry import Rect, Transform from .occlusion import FilledRecord from .pdf_input import PdfReadError, read_pdf +from .rules import DEFAULT_MAX_D3_WORK, validate_max_d3_work from .units import AccountingError, exclusion_reason @@ -68,6 +69,7 @@ class CheckReport: source_units_total: int text_records: int filled_records: int + complexity_budget: dict | None = None def to_dict(self) -> dict: return asdict(self) @@ -225,7 +227,7 @@ def _state(core: CoreResult, findings: tuple[dict, ...]) -> str: if any(item['confidence'] == 'high' for item in findings): return 'FAIL' coverage = core.coverage or {} - if (findings or core.unknown_objects + if (findings or core.unknown_objects 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' @@ -233,11 +235,13 @@ def _state(core: CoreResult, findings: tuple[dict, ...]) -> str: def check_figure(fig, *, bbox_inches=None, pad_inches=None, transparent=False, - keep_pdf: str | Path | None = None) -> CheckReport: + keep_pdf: str | Path | None = None, + max_d3_work: int = DEFAULT_MAX_D3_WORK) -> CheckReport: """Capture, read and check one live Matplotlib Figure.""" + validate_max_d3_work(max_d3_work) try: return _check_figure(fig, bbox_inches=bbox_inches, pad_inches=pad_inches, - transparent=transparent, keep_pdf=keep_pdf) + transparent=transparent, keep_pdf=keep_pdf, max_d3_work=max_d3_work) except CheckError: raise except (CaptureError, PdfReadError, AccountingError) as error: @@ -246,7 +250,8 @@ def check_figure(fig, *, bbox_inches=None, pad_inches=None, transparent=False, def _check_figure(fig, *, bbox_inches=None, pad_inches=None, transparent=False, - keep_pdf: str | Path | None = None) -> CheckReport: + keep_pdf: str | Path | None = None, + max_d3_work: int = DEFAULT_MAX_D3_WORK) -> CheckReport: captured = capture_pdf(fig, bbox_inches=bbox_inches, pad_inches=pad_inches, transparent=transparent) if captured.origin_display is None: @@ -275,9 +280,11 @@ def _check_figure(fig, *, bbox_inches=None, pad_inches=None, transparent=False, core: CoreResult = check_core( records=tuple(collection.records), chars=snapshot.characters, fills=tuple(collection.fills), glyphs={}, transform=transform, page=page, - source_units_total=total, errors=tuple(errors)) + 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 - if not (paint_issue and name == 'D2_occluded_text')) + if not (paint_issue and name == 'D2_occluded_text') + 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) return CheckReport( @@ -291,7 +298,7 @@ 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)) + filled_records=len(collection.fills), complexity_budget=core.complexity_budget) finally: if temporary is not None: temporary.unlink(missing_ok=True) diff --git a/plotproof/geometry.py b/plotproof/geometry.py index 0fb5457..12dcacc 100644 --- a/plotproof/geometry.py +++ b/plotproof/geometry.py @@ -2,7 +2,8 @@ from __future__ import annotations from dataclasses import dataclass -from math import fsum, isfinite +from fractions import Fraction +from math import isfinite from typing import Iterable, Literal @@ -52,7 +53,7 @@ def as_tuple(self) -> tuple[float, float, float, float]: def bounding_rect(boxes: Iterable[Rect]) -> Rect | None: - boxes = tuple(b for b in boxes if b.area > 0) + boxes = tuple(b for b in boxes if b.x1 > b.x0 and b.y1 > b.y0) if not boxes: return None return Rect(min(b.x0 for b in boxes), min(b.y0 for b in boxes), @@ -66,25 +67,53 @@ def intersections(left: Iterable[Rect], right: Iterable[Rect]) -> tuple[Rect, .. def union_area(boxes: Iterable[Rect]) -> float: - """Exact axis-aligned sweep, not a raster estimate or sum of box areas.""" - boxes = tuple(sorted(set(b for b in boxes if b.area > 0))) - xs = sorted({x for b in boxes for x in (b.x0, b.x1)}) + """Exact rational coordinate-compressed segment-tree sweep in O(m log m).""" + boxes = tuple(sorted(set(b for b in boxes if b.x1 > b.x0 and b.y1 > b.y0))) + if not boxes: + return 0.0 + coordinates = {value: Fraction(value) for box in boxes for value in box.as_tuple()} + ys = sorted({coordinates[value] for box in boxes for value in (box.y0, box.y1)}) + index = {y: i for i, y in enumerate(ys)} + size = 4 * max(1, len(ys) - 1) + cover = [0] * size + length = [Fraction(0)] * size + + def add(node: int, low: int, high: int, start: int, end: int, delta: int) -> None: + if start <= low and high <= end: + cover[node] += delta + else: + middle = (low + high) // 2 + if start < middle: + add(node * 2, low, middle, start, end, delta) + if middle < end: + add(node * 2 + 1, middle, high, start, end, delta) + if cover[node]: + length[node] = ys[high] - ys[low] + elif high - low == 1: + length[node] = Fraction(0) + else: + length[node] = length[node * 2] + length[node * 2 + 1] + + events = sorted((coordinates[x], index[coordinates[box.y0]], index[coordinates[box.y1]], delta) + for box in boxes for x, delta in ((box.x0, 1), (box.x1, -1))) strips = [] - for x0, x1 in zip(xs, xs[1:]): - intervals = sorted((b.y0, b.y1) for b in boxes if b.x0 < x1 and b.x1 > x0) - if not intervals: - continue - start, end = intervals[0] - lengths = [] - for low, high in intervals[1:]: - if low > end: - lengths.append(end - start) - start, end = low, high - else: - end = max(end, high) - lengths.append(end - start) - strips.append((x1 - x0) * fsum(lengths)) - return fsum(strips) + index_event = 0 + while index_event + 1 < len(events): + x0 = events[index_event][0] + while index_event < len(events) and events[index_event][0] == x0: + _, start, end, delta = events[index_event] + add(1, 0, len(ys) - 1, start, end, delta) + index_event += 1 + if index_event < len(events): + strips.append((events[index_event][0] - x0) * length[1]) + total = sum(strips, Fraction(0)) + try: + result = float(total) + except OverflowError: + raise ValueError('rectangle union area is not representable as a finite float') from None + if not isfinite(result) or (total and result == 0.0): + raise ValueError('rectangle union area is not representable as a finite float') + return result def iou(left: Rect, right: Rect) -> float: diff --git a/plotproof/pdf_input.py b/plotproof/pdf_input.py index 95fc3af..fea64d4 100644 --- a/plotproof/pdf_input.py +++ b/plotproof/pdf_input.py @@ -342,8 +342,10 @@ def _decode_snapshot(reply, digest: str, limits: PdfLimits, scale: float | None) crop, media, 0, tuple(characters), render) except PdfReadError: raise - except (ValueError, TypeError, KeyError, OverflowError, RecursionError, struct.error): - raise PdfReadError('worker_protocol') from None + except (ValueError, TypeError, KeyError, OverflowError, RecursionError, struct.error) as error: + # Keep the machine-readable reason first; the detail makes a failed + # platform build diagnosable without guessing which check rejected it. + raise PdfReadError('worker_protocol: ' + str(error)[:120]) from None def read_pdf(path, expected_sha256: str, *, limits: PdfLimits = PdfLimits(), diff --git a/plotproof/rules.py b/plotproof/rules.py index ec76587..24ace0b 100644 --- a/plotproof/rules.py +++ b/plotproof/rules.py @@ -14,6 +14,63 @@ CLASSES = {'D1': 'clipped_text', 'D2': 'occluded_text', 'D3': 'overlapping_text', 'D4': 'missing_glyph'} PRIORITY = {'D1': 0, 'D4': 1, 'D2': 2, 'D3': 3} +DEFAULT_MAX_D3_WORK = 1_000_000 +D3_FIXED_OVERHEAD = 32 +D3_FORMULA = ('pairs + operand scans + union sorting (m and two 2m sorts) + ' + 'pairwise intersections and aligned witness scans + per-pair fill sorting/scanning ' + 'and own-background intersection scans + 32*pairs') + + +def _sort_work(count): + return count * (1 + (count.bit_length() - 1 if count > 1 else 0)) + + +def _union_sort_work(count): + return _sort_work(count) + 2 * _sort_work(2 * count) + + +def validate_max_d3_work(value: int) -> int: + if type(value) is not int or value <= 0: + raise ValueError('max_d3_work must be a positive integer') + return value + + +def estimate_d3_work(alignment: AlignmentResult, fills: Sequence[FilledRecord] = ()) -> dict: + """Conservative declared operation estimate in O(n + fills), not a runtime prediction.""" + supported = tuple(u for u in alignment.units.units if not u.unsupported_reason) + n = len(supported) + counts = [len(alignment.assignments[uid].boxes) if uid in alignment.assignments else 1 + for uid in (u.record.source_object_id for u in supported)] + total = sum(counts) + squares = sum(count * count for count in counts) + pairs = n * (n - 1) // 2 + operand_work = (n - 1) * total if n else 0 + intersection_work = (total * total - squares) // 2 + aligned_counts = [count for uid, count in zip( + (u.record.source_object_id for u in supported), counts) if uid in alignment.assignments] + aligned_total = sum(aligned_counts) + aligned_squares = sum(count * count for count in aligned_counts) + witness_work = (aligned_total * aligned_total - aligned_squares) // 2 + intersection_work += witness_work + union_sort_work = (n - 1) * sum(_union_sort_work(count) for count in counts) if n else 0 + largest_intersection = max(counts, default=0) ** 2 + cut_union_work = pairs * _union_sort_work(largest_intersection) + fill_count = len(fills) + fill_work = pairs * (fill_count + _sort_work(fill_count)) + supported_ids = {u.record.source_object_id for u in supported} + own_fill_count = sum(fill.owner_unit_id in supported_ids for fill in fills) + background_intersection_work = pairs * own_fill_count * largest_intersection + fixed_overhead = D3_FIXED_OVERHEAD * pairs + estimated = (pairs + operand_work + intersection_work + union_sort_work + + cut_union_work + fill_work + background_intersection_work + fixed_overhead) + return {'supported_units': n, 'operand_boxes': total, 'pair_count': pairs, + 'operand_work': operand_work, 'intersection_work': intersection_work, + 'witness_work': witness_work, 'union_sort_work': union_sort_work, + 'cut_union_work': cut_union_work, 'fill_count': fill_count, 'fill_work': fill_work, + 'background_intersection_work': background_intersection_work, + 'fixed_overhead': fixed_overhead, 'estimated_work': estimated, + 'formula': D3_FORMULA} + @dataclass(frozen=True) @@ -182,7 +239,10 @@ def apply_precedence(findings: Sequence[Finding]) -> tuple[Finding, ...]: def detect_rules(alignment: AlignmentResult, page: Rect, - fills: Sequence[FilledRecord], glyphs: Mapping[int, Sequence[GlyphEvidence]]) -> tuple[Finding, ...]: + fills: Sequence[FilledRecord], glyphs: Mapping[int, Sequence[GlyphEvidence]], + *, max_d3_work: int = DEFAULT_MAX_D3_WORK, + budget_record: list[dict | None] | None = None) -> tuple[Finding, ...]: + limit = validate_max_d3_work(max_d3_work) supported = sorted((u for u in alignment.units.units if not u.unsupported_reason), key=lambda u: u.record.source_object_id) findings = [] @@ -194,7 +254,14 @@ def detect_rules(alignment: AlignmentResult, page: Rect, if candidate: findings.append(candidate) findings.extend(_d4(unit, span is not None, glyphs.get(uid, ()))) - for left, right in combinations(supported, 2): - if candidate := _d3(left, right, alignment, fills): - findings.append(candidate) + estimate = estimate_d3_work(alignment, fills) + skipped = estimate['estimated_work'] > limit + if budget_record is not None: + budget_record.append(None if not skipped else { + **estimate, 'limit': limit, 'skipped': True, + 'reason': 'estimated D3 pair work exceeds the declared budget'}) + if not skipped: + for left, right in combinations(supported, 2): + if candidate := _d3(left, right, alignment, fills): + findings.append(candidate) return apply_precedence(findings) diff --git a/pyproject.toml b/pyproject.toml index 265873e..b9d89e8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "plotproof" -version = "0.1.0a2" +version = "0.1.0a3" 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" diff --git a/scripts/check_docs.py b/scripts/check_docs.py new file mode 100644 index 0000000..bcd7345 --- /dev/null +++ b/scripts/check_docs.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Validate required public docs, local Markdown links, and obvious placeholders.""" +from __future__ import annotations + +import re +import sys +import urllib.parse +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +REQUIRED_FILES = [ + "README.md", + "README.zh-CN.md", + "SECURITY.md", + "CONTRIBUTING.md", + "CODE_OF_CONDUCT.md", + "CHANGELOG.md", + ".github/ISSUE_TEMPLATE/bug_report.md", + ".github/ISSUE_TEMPLATE/feature_request.md", +] +REQUIRED_HEADINGS = { + "README.md": [ + "## Quickstart and support", "### Problem", "### Install", "### Success", + "### Deliberate failure", "### Evidence and coverage boundaries", + "### Support status", "### Limitations", + ], + "README.zh-CN.md": [ + "## 快速开始与支持状态", "### 问题", "### 安装", "### 成功命令", + "### 故意失败命令", "### 证据与覆盖边界", "### 支持状态", "### 限制", + ], + "SECURITY.md": ["# Security", "## Supported versions", "## Reporting a vulnerability", "## Security boundaries"], + "CONTRIBUTING.md": ["# Contributing", "## Before you start", "## Development setup", "## Pull requests", "## Reporting issues"], + "CODE_OF_CONDUCT.md": ["# Code of Conduct", "## Our pledge", "## Our standards", "## Enforcement responsibilities", "## Scope", "## Enforcement", "## Attribution"], + "CHANGELOG.md": ["# Changelog", "## Unreleased"], + ".github/ISSUE_TEMPLATE/bug_report.md": ["# Bug report", "## Environment", "## Exact command", "## Minimal sanitized input", "## Expected result", "## Actual result", "## Installed package reproduction"], + ".github/ISSUE_TEMPLATE/feature_request.md": ["# Feature request", "## Problem", "## Proposed behavior", "## Alternatives", "## Additional context"], +} +PLACEHOLDER = re.compile( + r"\b(?:TODO|TBD|FIXME|XXX)\b|your[-_ ]?(?:username|repo|repository)|]+>|[^)\s]+)(?:\s+[\"'][^)]*[\"'])?\s*\)") +REFERENCE_DEF = re.compile(r"^\s{0,3}\[[^\]]+\]:\s*(<[^>]+>|\S+)", re.MULTILINE) +HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$", re.MULTILINE) + + +def without_fences(text: str) -> str: + text = re.sub(r"(?ms)^```.*?^```[ \t]*$", "", text) + return re.sub(r"(?ms)^~~~.*?^~~~[ \t]*$", "", text) + + +def headings(text: str) -> set[str]: + return {f"{len(m.group(1)) * '#'} {m.group(2).strip()}" for m in HEADING.finditer(text)} + + +def local_target(raw: str) -> str | None: + target = raw.strip() + if target.startswith("<") and ">" in target: + target = target[1:target.index(">")] + else: + target = target.split()[0] if target else "" + target = urllib.parse.unquote(target) + if not target or target.startswith("#") or re.match(r"^[A-Za-z][A-Za-z0-9+.-]*:", target): + return None + target = target.split("#", 1)[0].split("?", 1)[0] + return target or None + + +def main() -> int: + errors: list[str] = [] + checked_links = 0 + for relative in REQUIRED_FILES: + path = ROOT / relative + if not path.is_file(): + errors.append(f"{relative}: missing required file") + continue + text = path.read_text(encoding="utf-8") + present = headings(text) + for required in REQUIRED_HEADINGS.get(relative, []): + if required not in present: + errors.append(f"{relative}: missing heading {required!r}") + prose = without_fences(text) + match = PLACEHOLDER.search(prose) + if match: + errors.append(f"{relative}: obvious placeholder {match.group(0)!r}") + targets = [m.group(1) for m in INLINE_LINK.finditer(prose)] + targets.extend(m.group(1) for m in REFERENCE_DEF.finditer(prose)) + for raw in targets: + target = local_target(raw) + if target is None: + continue + checked_links += 1 + candidate = (path.parent / target).resolve() + if not candidate.exists(): + errors.append(f"{relative}: broken local link {target!r}") + if errors: + for error in errors: + print(f"docs: {error}", file=sys.stderr) + print(f"docs: FAILED ({len(errors)} errors)", file=sys.stderr) + return 1 + print(f"docs: OK ({len(REQUIRED_FILES)} files, {checked_links} local links)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_cli_errors.py b/tests/test_cli_errors.py new file mode 100644 index 0000000..ff8951a --- /dev/null +++ b/tests/test_cli_errors.py @@ -0,0 +1,264 @@ +"""The CLI boundary must fail closed without leaking user diagnostics.""" +import json +import os +from pathlib import Path +import subprocess +import sys + +import pytest +from unittest.mock import patch + +from plotproof import cli +from plotproof.export import CheckError + + +def invoke(monkeypatch, capsys, module, *options): + assert cli.main(['check', str(module), *options]) == 2 + captured = capsys.readouterr() + assert captured.err == '' + assert 'Traceback' not in captured.out + return json.loads(captured.out) + + +def assert_error(payload, code, private='PRIVATE_USER_DETAIL'): + assert payload['status'] == 'ERROR' + assert payload['error']['code'] == code + assert isinstance(payload['error']['message'], str) and payload['error']['message'] + assert private not in json.dumps(payload) + assert 'Traceback' not in json.dumps(payload) + + +def test_missing_module_has_stable_input_error_and_safe_json_report(tmp_path, capsys): + destination = tmp_path / 'missing.json' + payload = invoke(None, capsys, tmp_path / 'absent.py', '--json', str(destination)) + assert_error(payload, 'INPUT_NOT_FOUND') + assert json.loads(destination.read_text(encoding='utf-8')) == payload + + +def test_missing_factory_has_stable_factory_error(tmp_path, capsys): + module = tmp_path / 'figure.py' + module.write_text('value = 1\n', encoding='utf-8') + assert_error(invoke(None, capsys, module, '--factory', 'absent'), 'FACTORY_NOT_FOUND') + + +@pytest.mark.parametrize('phase', ['import', 'factory']) +@pytest.mark.parametrize('exception', ['RuntimeError("PRIVATE_USER_DETAIL")', 'SystemExit("PRIVATE_USER_DETAIL")']) +def test_user_exception_and_system_exit_are_structured(tmp_path, capsys, phase, exception): + module = tmp_path / 'figure.py' + module.write_text( + 'def figure():\n raise %s\n' % exception if phase == 'factory' else + 'raise %s\n' % exception, encoding='utf-8') + code = 'FACTORY_FAILED' if phase == 'factory' else 'IMPORT_FAILED' + assert_error(invoke(None, capsys, module), code) + + +def test_module_attribute_lookup_exception_is_structured(tmp_path, capsys): + module = tmp_path / 'figure.py' + module.write_text('def __getattr__(name):\n raise ValueError("PRIVATE_USER_DETAIL")\n', encoding='utf-8') + assert_error(invoke(None, capsys, module), 'IMPORT_FAILED') + + +def test_check_failure_has_stable_error(tmp_path, capsys, monkeypatch): + module = tmp_path / 'figure.py' + module.write_text('def figure():\n return object()\n', encoding='utf-8') + monkeypatch.setattr(cli, 'check_figure', lambda *a, **k: (_ for _ in ()).throw( + CheckError('PRIVATE_USER_DETAIL'))) + assert_error(invoke(None, capsys, module), 'CHECK_FAILED') + + +def test_load_os_error_is_structured(tmp_path, capsys, monkeypatch): + module = tmp_path / 'figure.py' + module.write_text('def figure(): pass\n', encoding='utf-8') + monkeypatch.setattr(cli, '_load_figure', lambda *a: (_ for _ in ()).throw(PermissionError('PRIVATE_USER_DETAIL'))) + assert_error(invoke(None, capsys, module), 'INPUT_LOAD_FAILED') + + +def test_preflight_os_error_is_structured(tmp_path, capsys, monkeypatch): + module = tmp_path / 'figure.py' + module.write_text('def figure(): pass\n', encoding='utf-8') + monkeypatch.setattr(cli, '_preflight', lambda *a, **k: (_ for _ in ()).throw(PermissionError('PRIVATE_USER_DETAIL'))) + assert_error(invoke(None, capsys, module, '--json', str(tmp_path / 'report.json')), 'OUTPUT_FAILED') + + +def test_output_failure_has_stable_error(tmp_path, capsys, monkeypatch): + module = tmp_path / 'figure.py' + module.write_text('def figure():\n return object()\n', encoding='utf-8') + monkeypatch.setattr(cli, 'check_figure', lambda *a, **k: __import__('types').SimpleNamespace(state='PASS')) + monkeypatch.setattr(cli, '_save', lambda *a, **k: (_ for _ in ()).throw(OSError('PRIVATE_USER_DETAIL'))) + assert_error(invoke(None, capsys, module, '--json', str(tmp_path / 'report.json')), 'OUTPUT_FAILED') + + +def test_serialization_error_is_published_to_safe_json(tmp_path, capsys, monkeypatch): + module = tmp_path / 'figure.py' + module.write_text('def figure(): pass\n', encoding='utf-8') + destination = tmp_path / 'report.json' + monkeypatch.setattr(cli, 'check_figure', lambda *a, **k: __import__('types').SimpleNamespace(state='PASS')) + monkeypatch.setattr(cli, '_save', lambda *a, **k: (_ for _ in ()).throw( + cli.OutputError('OUTPUT_SERIALIZATION_FAILED', 'Report serialization failed; no output was published.'))) + assert cli.main(['check', str(module), '--json', str(destination)]) == 2 + payload = json.loads(destination.read_text(encoding='utf-8')) + assert payload['status'] == 'ERROR' + assert payload['error']['code'] == 'OUTPUT_SERIALIZATION_FAILED' + assert json.loads(capsys.readouterr().out) == payload + + +@pytest.mark.parametrize('value', ['0', '-1', '1.5', 'true']) +def test_invalid_budget_is_rejected_before_figure_loading(tmp_path, capsys, value): + module = tmp_path / 'figure.py' + module.write_text('raise RuntimeError("must not execute")\n', encoding='utf-8') + assert_error(invoke(None, capsys, module, '--max-d3-work', value), 'INVALID_BUDGET') + + +def test_output_failure_does_not_hide_original_error(tmp_path, capsys, monkeypatch): + module = tmp_path / 'figure.py' + module.write_text('raise RuntimeError("PRIVATE_USER_DETAIL")\n', encoding='utf-8') + monkeypatch.setattr(cli.os, 'fdopen', lambda *a, **k: (_ for _ in ()).throw(OSError('PRIVATE_USER_DETAIL'))) + assert_error(invoke(None, capsys, module, '--json', str(tmp_path / 'report.json')), 'IMPORT_FAILED') + + +def test_demo_preflight_os_error_is_structured(capsys, monkeypatch): + monkeypatch.setattr(cli, '_preflight', lambda *a, **k: (_ for _ in ()).throw(PermissionError('PRIVATE_USER_DETAIL'))) + assert cli.main(['demo']) == 2 + captured = capsys.readouterr() + assert captured.err == '' + assert_error(json.loads(captured.out), 'OUTPUT_FAILED') + + +def test_error_report_exits_two_and_preserves_structured_evidence(tmp_path, capsys, monkeypatch): + module = tmp_path / 'figure.py' + module.write_text('def figure(): pass\n', encoding='utf-8') + error_report = __import__('types').SimpleNamespace( + state='ERROR', to_dict=lambda: {'status': 'ERROR', 'error': {'code': 'CAPTURE', 'message': 'limited'}}) + monkeypatch.setattr(cli, 'check_figure', lambda *a, **k: error_report) + assert cli.main(['check', str(module)]) == 2 + assert json.loads(capsys.readouterr().out)['status'] == 'ERROR' + + +def test_alias_refusal_does_not_overwrite_the_aliased_file(tmp_path, capsys): + module = tmp_path / 'figure.py' + module.write_text('def figure(): pass\n', encoding='utf-8') + destination = tmp_path / 'report.json' + destination.write_text('original evidence', encoding='utf-8') + assert cli.main(['check', str(module), '--json', str(destination), + '--html', str(destination), '--force']) == 2 + assert destination.read_text(encoding='utf-8') == 'original evidence' + assert json.loads(capsys.readouterr().out)['error']['code'] == 'OUTPUT_ALIAS' + + +def test_broken_stdout_does_not_prevent_safe_error_file(tmp_path): + destination = tmp_path / 'error.json' + + class BrokenStdout: + def write(self, text): + raise BrokenPipeError('injected stdout failure') + + with patch.object(cli.sys, 'stdout', BrokenStdout()): + assert cli.main(['check', str(tmp_path / 'missing.py'), '--json', str(destination)]) == 2 + assert json.loads(destination.read_text(encoding='utf-8'))['error']['code'] == 'INPUT_NOT_FOUND' + + +def test_user_print_cannot_corrupt_or_leak_structured_error(tmp_path, capsys): + module = tmp_path / 'figure.py' + module.write_text('print("PRIVATE_USER_DETAIL")\nraise RuntimeError("PRIVATE_USER_DETAIL")\n', + encoding='utf-8') + payload = invoke(None, capsys, module) + assert_error(payload, 'IMPORT_FAILED') + + +def test_low_level_stdout_write_cannot_corrupt_structured_error(tmp_path, capsys): + module = tmp_path / 'figure.py' + module.write_text('import os\nos.write(1, b"PRIVATE_USER_DETAIL")\nraise RuntimeError("PRIVATE_USER_DETAIL")\n', + encoding='utf-8') + payload = invoke(None, capsys, module) + assert_error(payload, 'IMPORT_FAILED') + + +def test_subprocess_low_level_stdout_write_cannot_corrupt_error(tmp_path): + module = tmp_path / 'figure.py' + module.write_text('import os\nos.write(1, b"PRIVATE_USER_DETAIL")\nraise RuntimeError("PRIVATE_USER_DETAIL")\n', + encoding='utf-8') + result = subprocess.run([sys.executable, '-m', 'plotproof', 'check', str(module)], + capture_output=True, text=True, encoding='utf-8', errors='replace') + assert result.returncode == 2 + payload = json.loads(result.stdout) + assert_error(payload, 'IMPORT_FAILED') + assert result.stderr == '' + + +def test_error_publication_rollback_names_reach_stdout(tmp_path, capsys, monkeypatch): + json_path = tmp_path / 'report.json' + html_path = tmp_path / 'report.html' + json_path.write_text('old json', encoding='utf-8') + html_path.write_text('old html', encoding='utf-8') + replace = os.replace + + def fail_rollback(source, destination): + if Path(destination) == html_path and not str(source).endswith('.plotproof-backup'): + raise OSError('injected publication failure') + if Path(destination) == json_path and str(source).endswith('.plotproof-backup'): + raise OSError('injected rollback failure') + return replace(source, destination) + + monkeypatch.setattr(cli.os, 'replace', fail_rollback) + cli._emit_error('INPUT_NOT_FOUND', 'missing', str(json_path), str(html_path), force=True) + payload = json.loads(capsys.readouterr().out) + assert 'report.json.plotproof-backup' in payload['error']['recovery_backups'] + + +def test_argparse_failure_is_structured(capsys): + assert cli.main(['check']) == 2 + payload = json.loads(capsys.readouterr().out) + assert payload['status'] == 'ERROR' + assert payload['error']['code'] == 'INVALID_ARGUMENTS' + + +def test_system_exit_during_check_is_structured(tmp_path, capsys, monkeypatch): + module = tmp_path / 'figure.py' + module.write_text('def figure(): pass\n', encoding='utf-8') + monkeypatch.setattr(cli, 'check_figure', lambda *a, **k: (_ for _ in ()).throw(SystemExit(7))) + assert_error(invoke(None, capsys, module), 'CHECK_FAILED') + + +def test_forced_precheck_error_updates_both_paired_outputs(tmp_path, capsys): + json_path = tmp_path / 'report.json' + html_path = tmp_path / 'report.html' + json_path.write_text('{"state":"PASS"}', encoding='utf-8') + html_path.write_text('

PASS

', encoding='utf-8') + assert cli.main(['check', str(tmp_path / 'missing.py'), '--json', str(json_path), + '--html', str(html_path), '--force']) == 2 + assert json.loads(json_path.read_text(encoding='utf-8'))['status'] == 'ERROR' + assert 'ERROR' in html_path.read_text(encoding='utf-8') + assert 'PASS' not in html_path.read_text(encoding='utf-8') + json.loads(capsys.readouterr().out) + + +def test_html_only_publication_failure_emits_only_error(tmp_path, capsys, monkeypatch): + module = tmp_path / 'figure.py' + module.write_text('def figure(): pass\n', encoding='utf-8') + monkeypatch.setattr(cli, 'check_figure', lambda *a, **k: __import__('types').SimpleNamespace( + state='PASS', to_dict=lambda: {'state': 'PASS'})) + monkeypatch.setattr(cli, 'render_html', lambda report: '

PASS

') + monkeypatch.setattr(cli, '_publish_texts', lambda *a, **k: (_ for _ in ()).throw(OSError('injected'))) + assert cli.main(['check', str(module), '--html', str(tmp_path / 'report.html')]) == 2 + payload = json.loads(capsys.readouterr().out) + assert payload['status'] == 'ERROR' + assert payload['error']['code'] == 'OUTPUT_FAILED' + + +def test_demo_controls_must_be_clean_pass_and_clipped_fail(tmp_path, capsys, monkeypatch): + monkeypatch.setattr(cli, '_demo_figure', lambda deliberate: 'clipped' if deliberate else 'clean') + monkeypatch.setattr(cli, 'render_html', lambda report: '

' + report.state + '

') + states = {'clean': 'ERROR', 'clipped': 'FAIL'} + monkeypatch.setattr(cli, 'check_figure', lambda fig, **kwargs: __import__('types').SimpleNamespace( + state=states[fig], to_dict=lambda: {'state': states[fig]})) + output = tmp_path / 'demo' + assert cli.main(['demo', '--output', str(output)]) == 2 + assert json.loads(capsys.readouterr().out)['error']['code'] == 'CHECK_FAILED' + assert not output.exists() + + +def test_keyboard_interrupt_is_not_converted(tmp_path): + module = tmp_path / 'figure.py' + module.write_text('def figure():\n raise KeyboardInterrupt()\n', encoding='utf-8') + with pytest.raises(KeyboardInterrupt): + cli.main(['check', str(module)]) diff --git a/tests/test_complexity_budget.py b/tests/test_complexity_budget.py new file mode 100644 index 0000000..83f09ec --- /dev/null +++ b/tests/test_complexity_budget.py @@ -0,0 +1,171 @@ +"""D3's declared operation budget skips the whole pair loop, never a subset.""" +import json +from dataclasses import replace + +import pytest + +from _core_fixtures import module, text_record, pdf_chars, Rect, Transform +from plotproof import rules +from test_export import bars, figure +from plotproof.export import check_figure + + +def facts(count): + records = tuple(text_record(i + 1, chr(97 + i), Rect(10 + i * 20, 10, 20 + i * 20, 20)) + for i in range(count)) + chars = tuple(module('evidence').PdfChar(r.text, r.bbox_display) for r in records) + return records, chars + + +def core(count, budget, fills=()): + records, chars = facts(count) + return module('core').check_core( + records=records, chars=chars, fills=fills, glyphs={}, + transform=Transform(72, 0, 0), page=Rect(0, 0, 1000, 1000), + source_units_total=count, max_d3_work=budget) + + +def test_small_budget_skips_all_d3_pairs_and_makes_core_unknown(monkeypatch): + def forbidden(*args): + pytest.fail('D3 pair evaluation must be skipped entirely') + monkeypatch.setattr(rules, '_d3', forbidden) + result = core(6, 1) + assert result.overall_state == 'UNKNOWN' + assert result.coverage['ratio'] == 1 + assert result.findings == () + budget = result.to_dict()['complexity_budget'] + assert budget['skipped'] is True + assert budget['supported_units'] == 6 + assert budget['pair_count'] == 15 + assert budget['limit'] == 1 + assert budget['estimated_work'] > budget['limit'] + assert budget['formula'] + json.dumps(result.to_dict(), allow_nan=False) + + +def test_estimate_has_transparent_closed_form_components(): + records, chars = facts(4) + units = module('units').enumerate_units(records, Transform(72, 0, 0), Rect(0, 0, 1000, 1000), 4) + alignment = module('alignment').align_units(units, chars, {}) + estimate = rules.estimate_d3_work(alignment) + assert estimate['supported_units'] == 4 + assert estimate['operand_boxes'] == 4 + assert estimate['pair_count'] == 6 + assert estimate['operand_work'] == 12 + assert estimate['intersection_work'] == 12 + assert estimate['witness_work'] == 6 + assert estimate['union_sort_work'] == 108 + assert estimate['cut_union_work'] == 54 + assert estimate['fill_work'] == 0 + assert estimate['background_intersection_work'] == 0 + assert estimate['fixed_overhead'] == 192 + assert estimate['estimated_work'] == 384 + + +def test_fill_scans_are_included_in_d3_budget(monkeypatch): + fills = tuple(module('occlusion').FilledRecord( + source_object_id=10_000 + i, box_pdf=Rect(0, 0, 1, 1), artist_class='Patch', + path_kind='axis_aligned_rectangle', path_is_concave=False, fancybox=None, + facecolor_alpha=1.0, artist_alpha=1.0, paint_order=i, filled_area=1.0, + owner_unit_id=None, image_opacity=None) for i in range(2_000)) + records, chars = facts(2) + alignment = module('alignment').align_units( + module('units').enumerate_units(records, Transform(72, 0, 0), Rect(0, 0, 1000, 1000), 2), chars, {}) + estimate = rules.estimate_d3_work(alignment, fills) + assert estimate['fill_count'] == 2_000 + assert estimate['estimated_work'] > 36 + + def forbidden(*args): + pytest.fail('fill-heavy D3 must be skipped when its declared budget is exceeded') + + monkeypatch.setattr(rules, '_d3', forbidden) + result = core(2, 36, fills) + assert result.overall_state == 'UNKNOWN' + assert result.complexity_budget['skipped'] is True + + +def test_union_sort_work_alone_cannot_exceed_declared_budget(monkeypatch): + records = (text_record(1, 'aaaaaaaaaa', Rect(10, 10, 110, 20)), + text_record(2, 'bbbbbbbbbb', Rect(210, 10, 310, 20))) + chars = pdf_chars('aaaaaaaaaa', x=10) + pdf_chars('bbbbbbbbbb', x=210) + alignment = module('alignment').align_units( + module('units').enumerate_units(records, Transform(72, 0, 0), Rect(0, 0, 1000, 1000), 2), chars, {}) + sort_only = 2 * rules._union_sort_work(10) + rules._union_sort_work(100) + + def forbidden(*args): + pytest.fail('D3 executed even though union sorting alone exceeded its budget') + + monkeypatch.setattr(rules, '_d3', forbidden) + result = module('core').check_core( + records=records, chars=chars, fills=(), glyphs={}, + transform=Transform(72, 0, 0), page=Rect(0, 0, 1000, 1000), + source_units_total=2, max_d3_work=sort_only - 1) + assert result.overall_state == 'UNKNOWN' + assert result.complexity_budget['skipped'] is True + assert result.complexity_budget['estimated_work'] > sort_only - 1 + + +def test_full_aligned_witness_scan_is_included_in_budget(): + records = (text_record(1, 'a' * 100, Rect(10, 10, 110, 20)), + text_record(2, 'b' * 100, Rect(10, 10, 110, 20))) + chars = pdf_chars('a' * 100, x=10, width=1) + pdf_chars('b' * 100, x=10, width=1) + alignment = module('alignment').align_units( + module('units').enumerate_units(records, Transform(72, 0, 0), Rect(0, 0, 1000, 1000), 2), chars, {}) + estimate = rules.estimate_d3_work(alignment) + assert estimate['witness_work'] == 10_000 + assert estimate['intersection_work'] == 20_000 + + +def test_budget_boundary_is_inclusive_and_normal_budget_preserves_findings(): + records, chars = facts(2) + records = (records[0], replace(records[1], bbox_display=Rect(15, 10, 25, 20))) + chars = (chars[0], replace(chars[1], box=records[1].bbox_display)) + options = dict(records=records, chars=chars, fills=(), glyphs={}, + transform=Transform(72, 0, 0), page=Rect(0, 0, 1000, 1000), source_units_total=2) + estimate = rules.estimate_d3_work(module('alignment').align_units( + module('units').enumerate_units(records, options['transform'], options['page'], 2), chars, {})) + at_boundary = module('core').check_core(**options, max_d3_work=estimate['estimated_work']) + assert at_boundary.overall_state == 'FAIL' + assert [(f.rule_id, f.confidence) for f in at_boundary.findings] == [('D3', 'high')] + assert at_boundary.complexity_budget is None + assert core(6, 1_000_000).complexity_budget is None + + +def test_skipped_d3_does_not_hide_existing_fail_or_error(): + records, chars = facts(3) + records = (*records, text_record(9, 'x', Rect(-5, 10, 5, 20))) + chars = (*chars, module('evidence').PdfChar('x', records[-1].bbox_display)) + options = dict(records=records, chars=chars, fills=(), glyphs={}, + transform=Transform(72, 0, 0), page=Rect(0, 0, 1000, 1000), + source_units_total=4, max_d3_work=1) + failed = module('core').check_core(**options) + assert failed.overall_state == 'FAIL' + assert any(f.rule_id == 'D1' for f in failed.findings) + errored = module('core').check_core(**options, errors=({'stage': 'capture', 'message': 'limited'},)) + assert errored.overall_state == 'ERROR' + + +def test_export_marks_d3_not_assessed_and_keeps_d4_not_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 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 + + +@pytest.mark.parametrize('budget', [0, -1, True, 1.5, '10']) +def test_invalid_library_budget_fails_before_capture(monkeypatch, budget): + monkeypatch.setattr('plotproof.export._check_figure', + lambda *a, **k: pytest.fail('capture must not run')) + with pytest.raises(ValueError, match='max_d3_work'): + check_figure(object(), max_d3_work=budget) + + +def test_invalid_core_budget_fails_before_accounting(): + with pytest.raises(ValueError, match='max_d3_work'): + core(0, 0) diff --git a/tests/test_core_mutations.py b/tests/test_core_mutations.py index 0e47402..2815ab4 100644 --- a/tests/test_core_mutations.py +++ b/tests/test_core_mutations.py @@ -19,7 +19,7 @@ (" if box.area == 0:\n return None\n", ''), ('(outside > 0 and outside >= 0.5 * box.area)', '(outside >= 0.5 * box.area)'), ), 'test_geometry.py::test_boundary_positive_area_and_unrounded_thresholds'), - ('sum_not_union', 'geometry', (('return fsum(strips)', 'return fsum(b.area for b in boxes)'),), + ('sum_not_union', 'geometry', (('total = sum(strips, Fraction(0))', 'total = sum((box.area for box in boxes), Fraction(0))'),), 'test_geometry.py::test_union_is_not_sum_or_bounding_box_and_ignores_degenerates'), ('no_wrapper_reconciliation', 'units', ( ('if record.is_unit is not (reason is None) or record.exclusion_reason != reason:', 'if False:'),), diff --git a/tests/test_geometry.py b/tests/test_geometry.py index 73a33ef..79fd4d5 100644 --- a/tests/test_geometry.py +++ b/tests/test_geometry.py @@ -68,6 +68,54 @@ def test_union_against_independent_unit_cell_oracle(): assert g.union_area([g.Rect(*c) for c in coords]) == len(cells) +def test_union_fractional_randomized_against_coordinate_cell_oracle(): + g = geometry() + rng = random.Random(90210) + for _ in range(100): + boxes = [] + for _ in range(rng.randrange(15)): + x0, x1 = sorted((rng.uniform(-10, 10), rng.uniform(-10, 10))) + y0, y1 = sorted((rng.uniform(-10, 10), rng.uniform(-10, 10))) + boxes.append(g.Rect(x0, y0, x1, y1)) + xs = sorted({x for b in boxes for x in (b.x0, b.x1)}) + ys = sorted({y for b in boxes for y in (b.y0, b.y1)}) + expected = math.fsum((x1 - x0) * (y1 - y0) + for x0, x1 in zip(xs, xs[1:]) for y0, y1 in zip(ys, ys[1:]) + if any(b.x0 <= x0 and x1 <= b.x1 and b.y0 <= y0 and y1 <= b.y1 for b in boxes)) + assert g.union_area(boxes + boxes[:3]) == pytest.approx(expected, rel=1e-14, abs=1e-14) + + +def test_union_touching_duplicates_and_extreme_finite_coordinates(): + g = geometry() + assert g.union_area([g.Rect(0, 0, 1, 1), g.Rect(1, 0, 2, 1), + g.Rect(0, 1, 1, 2), g.Rect(1, 1, 2, 2)]) == 4 + huge = [g.Rect(-1e150, -1e150, 1e150, 1e150), + g.Rect(0, 0, 5e149, 5e149), g.Rect(-1e150, -1e150, 1e150, 1e150)] + assert g.union_area(huge) == pytest.approx(4e300, rel=1e-15) + tiny = g.Rect(0, 0, 1e-150, 1e-150) + assert g.union_area([tiny, tiny]) == pytest.approx(1e-300, rel=1e-15, abs=0) + + +def test_union_rejects_positive_exact_area_that_underflows_float(): + g = geometry() + with pytest.raises(ValueError, match='not representable'): + g.union_area([g.Rect(0, 0, 1e-200, 1e-200)]) + + +def test_union_sweep_does_not_rescan_every_box_per_strip(monkeypatch): + g = geometry() + sorts = {'count': 0} + original_sorted = sorted + def counted_sorted(*args, **kwargs): + sorts['count'] += 1 + return original_sorted(*args, **kwargs) + import builtins + monkeypatch.setattr(builtins, 'sorted', counted_sorted) + boxes = [g.Rect(i, 0, i + 2, 1) for i in range(200)] + assert g.union_area(boxes) == 201 + assert sorts['count'] <= 4 + + @pytest.mark.parametrize('box,want', [ ((0, 0, 1, 1), None), ((-1, 0, 1, 2), 'high'), ((-0.99, 0, 1.01, 2), 'medium'), ((-2, 0, -1, 1), 'high'), @@ -90,6 +138,33 @@ def test_extreme_finite_boxes_do_not_overflow_iou_or_invent_clipping(): assert g.boundary_evidence(g.Rect(0, 0, 5e-324, 1), g.Rect(0, 0, 10, 10)) is None +def test_union_handles_separated_coordinates_without_inf_times_zero(): + g = geometry() + boxes = [g.Rect(-1e308, 0, -9e307, 1), g.Rect(9e307, 0, 1e308, 1)] + assert g.union_area(boxes) == pytest.approx(2e307) + + +def test_union_handles_aggregate_length_overflow_without_nonfinite_result(): + g = geometry() + boxes = [g.Rect(0, -1.7e308, 1e-308, -1e307), + g.Rect(0, 1e307, 1e-308, 1.7e308)] + assert g.union_area(boxes) == pytest.approx(3.2) + + +def test_union_preserves_tiny_boxes_beside_huge_axis_coordinates(): + g = geometry() + boxes = [g.Rect(0, 0, 1e-100, 1e100), + g.Rect(1e308, 0, 1.0000000000000002e308, 1e-308)] + assert g.union_area(boxes) == pytest.approx(1.0) + + +def test_union_rejects_unrepresentable_total_area_instead_of_returning_infinity(): + g = geometry() + boxes = [g.Rect(-1e154, -1e154, 0, 0), g.Rect(0, 0, 1e154, 1e154)] + with pytest.raises(ValueError): + g.union_area(boxes) + + def test_transform_plain_tight_and_page_pullback(): g = geometry() plain = g.Transform(100, 0, 0) diff --git a/tests/test_output_alias.py b/tests/test_output_alias.py new file mode 100644 index 0000000..22992b2 --- /dev/null +++ b/tests/test_output_alias.py @@ -0,0 +1,337 @@ +"""Output destinations are preflighted and published as one recoverable pair.""" +import json +import os +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from plotproof import cli + + +def report(state='PASS'): + return SimpleNamespace(state=state, to_dict=lambda: {'state': state}) + + +def test_json_html_aliases_are_refused_even_with_force(tmp_path): + destination = tmp_path / 'report.json' + with pytest.raises(cli.OutputError) as caught: + cli._save(report(), str(destination), str(destination), force=True) + assert caught.value.code == 'OUTPUT_ALIAS' + + +@pytest.mark.parametrize('alias', ['direct', 'symlink', 'hardlink']) +def test_output_cannot_alias_input_module(tmp_path, alias): + module = tmp_path / 'figure.py' + module.write_text('def figure(): pass\n', encoding='utf-8') + destination = module + if alias != 'direct': + destination = tmp_path / ('alias.py' if alias == 'symlink' else 'hard.py') + try: + if alias == 'symlink': + destination.symlink_to(module) + else: + os.link(module, destination) + except OSError as error: + pytest.skip('link creation unsupported: %s' % error) + with pytest.raises(cli.OutputError) as caught: + cli._save(report(), str(destination), None, force=True, input_path=module) + assert caught.value.code == 'INPUT_ALIAS' + assert module.read_text(encoding='utf-8') == 'def figure(): pass\n' + + +def test_symlink_destination_is_refused_even_when_dangling(tmp_path): + target = tmp_path / 'old.json' + destination = tmp_path / 'report.json' + try: + destination.symlink_to(target) + except OSError as error: + pytest.skip('symlink creation unsupported: %s' % error) + with pytest.raises(cli.OutputError) as caught: + cli._save(report(), str(destination), None, force=True) + assert caught.value.code == 'OUTPUT_SYMLINK' + assert not target.exists() + + +def test_existing_outputs_need_force_and_forced_replacement_succeeds(tmp_path, monkeypatch): + monkeypatch.setattr(cli, 'render_html', lambda report: '

new

\n') + json_path, html_path = tmp_path / 'report.json', tmp_path / 'report.html' + json_path.write_text('old json', encoding='utf-8') + html_path.write_text('old html', encoding='utf-8') + with pytest.raises(cli.OutputError) as caught: + cli._save(report(), str(json_path), str(html_path)) + assert caught.value.code == 'OUTPUT_EXISTS' + assert json_path.read_text(encoding='utf-8') == 'old json' + assert html_path.read_text(encoding='utf-8') == 'old html' + cli._save(report(), str(json_path), str(html_path), force=True) + assert json.loads(json_path.read_text(encoding='utf-8')) == {'state': 'PASS'} + assert html_path.read_text(encoding='utf-8') == '

new

\n' + + +@pytest.mark.parametrize('existing', [False, True]) +def test_second_publication_failure_rolls_back_both_outputs(tmp_path, monkeypatch, existing): + monkeypatch.setattr(cli, 'render_html', lambda report: '

new

\n') + json_path, html_path = tmp_path / 'report.json', tmp_path / 'report.html' + if existing: + json_path.write_text('old json', encoding='utf-8') + html_path.write_text('old html', encoding='utf-8') + replace = os.replace + def fail_second(source, destination): + if Path(destination) == html_path: + raise OSError('injected second publication failure') + return replace(source, destination) + monkeypatch.setattr(cli.os, 'replace', fail_second) + with pytest.raises(cli.OutputError) as caught: + cli._save(report(), str(json_path), str(html_path), force=True) + assert caught.value.code == 'OUTPUT_PUBLISH_FAILED' + if existing: + assert json_path.read_text(encoding='utf-8') == 'old json' + assert html_path.read_text(encoding='utf-8') == 'old html' + assert not json_path.with_name(json_path.name + '.plotproof-backup').exists() + assert not html_path.with_name(html_path.name + '.plotproof-backup').exists() + else: + assert not json_path.exists() and not html_path.exists() + + +def test_backup_cleanup_failure_does_not_turn_successful_publication_into_failure(tmp_path, monkeypatch): + monkeypatch.setattr(cli, 'render_html', lambda report: '

new

\n') + destination = tmp_path / 'report.json' + destination.write_text('old json', encoding='utf-8') + original_unlink = Path.unlink + def fail_backup_cleanup(path, *args, **kwargs): + if path.name.endswith('.plotproof-backup'): + raise OSError('injected cleanup failure') + return original_unlink(path, *args, **kwargs) + monkeypatch.setattr(Path, 'unlink', fail_backup_cleanup) + cli._save(report(), str(destination), None, force=True) + assert json.loads(destination.read_text(encoding='utf-8')) == {'state': 'PASS'} + assert (tmp_path / 'report.json.plotproof-backup').read_text(encoding='utf-8') == 'old json' + + +def test_render_time_destination_creation_is_not_overwritten(tmp_path, monkeypatch): + destination = tmp_path / 'report.json' + + def create_destination(report): + destination.write_text('concurrent', encoding='utf-8') + return '

new

\n' + + monkeypatch.setattr(cli, 'render_html', create_destination) + with pytest.raises(cli.OutputError) as caught: + cli._save(report(), str(destination), str(tmp_path / 'report.html')) + assert caught.value.code == 'OUTPUT_CONFLICT' + assert destination.read_text(encoding='utf-8') == 'concurrent' + assert not (tmp_path / 'report.html').exists() + + +def test_partial_backup_copy_is_removed_on_failure(tmp_path, monkeypatch): + destination = tmp_path / 'report.json' + destination.write_text('old', encoding='utf-8') + backup = destination.with_name(destination.name + '.plotproof-backup') + + def partial_copy(source, target): + Path(target).write_text('partial', encoding='utf-8') + raise OSError('injected copy failure') + + monkeypatch.setattr(cli.shutil, 'copy2', partial_copy) + with pytest.raises(cli.OutputError): + cli._save(report(), str(destination), None, force=True) + assert destination.read_text(encoding='utf-8') == 'old' + assert not backup.exists() + + +def test_factory_replacement_after_preflight_is_not_overwritten_with_force(tmp_path, monkeypatch): + from test_export import figure + + destination = tmp_path / 'report.json' + destination.write_text('old', encoding='utf-8') + module = tmp_path / 'figure.py' + module.write_text('def figure():\n return None\n', encoding='utf-8') + + def replace_during_factory(*args): + destination.write_text('user replacement', encoding='utf-8') + return figure() + + monkeypatch.setattr(cli, '_load_figure', replace_during_factory) + monkeypatch.setattr(cli, 'check_figure', lambda *args, **kwargs: report()) + result = cli.main(['check', str(module), '--json', str(destination), '--force']) + assert result == 2 + assert destination.read_text(encoding='utf-8') == 'user replacement' + + +def test_import_failure_error_output_preserves_post_preflight_replacement(tmp_path, monkeypatch): + destination = tmp_path / 'report.json' + destination.write_text('old', encoding='utf-8') + module = tmp_path / 'figure.py' + module.write_text('raise ImportError("user import")\n', encoding='utf-8') + + def replace_then_fail(*args): + destination.write_text('user replacement', encoding='utf-8') + raise ImportError('user import') + + monkeypatch.setattr(cli, '_load_figure', replace_then_fail) + result = cli.main(['check', str(module), '--json', str(destination), '--force']) + assert result == 2 + assert destination.read_text(encoding='utf-8') == 'user replacement' + + +def test_relative_demo_output_can_be_force_refreshed(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + assert cli.main(['demo', '--output', 'demo']) == 0 + assert cli.main(['demo', '--output', 'demo', '--force']) == 0 + + +def test_rollback_attempts_second_restore_after_first_restore_fails(tmp_path, monkeypatch): + first, second, third = (tmp_path / name for name in ('first.json', 'second.json', 'third.json')) + for path in (first, second, third): + path.write_text('old ' + path.name, encoding='utf-8') + replace = os.replace + def fail_first_restore(source, destination): + if Path(destination) == second and str(source).endswith('.plotproof-backup'): + raise OSError('injected first restore failure') + if Path(destination) == third and str(source).endswith('.tmp'): + raise OSError('injected third publication failure') + return replace(source, destination) + monkeypatch.setattr(cli.os, 'replace', fail_first_restore) + with pytest.raises(cli.OutputError) as caught: + cli._publish_texts([(path, 'new') for path in (first, second, third)]) + assert caught.value.code == 'OUTPUT_ROLLBACK_FAILED' + assert first.read_text(encoding='utf-8') == 'old first.json' + assert third.read_text(encoding='utf-8') == 'old third.json' + assert caught.value.recovery_backups == ('second.json.plotproof-backup',) + + +def test_rollback_failure_retains_named_recovery_backups(tmp_path, monkeypatch): + monkeypatch.setattr(cli, 'render_html', lambda report: '

new

\n') + json_path, html_path = tmp_path / 'report.json', tmp_path / 'report.html' + json_path.write_text('old json', encoding='utf-8') + html_path.write_text('old html', encoding='utf-8') + replace = os.replace + def fail_rollback(source, destination): + if Path(destination) == json_path and str(source).endswith('.plotproof-backup'): + raise OSError('injected rollback failure') + if Path(destination) == html_path and not str(source).endswith('.plotproof-backup'): + raise OSError('injected publication failure') + return replace(source, destination) + monkeypatch.setattr(cli.os, 'replace', fail_rollback) + with pytest.raises(cli.OutputError) as caught: + cli._save(report(), str(json_path), str(html_path), force=True) + assert caught.value.code == 'OUTPUT_ROLLBACK_FAILED' + assert set(caught.value.recovery_backups) == {'report.json.plotproof-backup'} + assert (tmp_path / 'report.json.plotproof-backup').read_text(encoding='utf-8') == 'old json' + assert not (tmp_path / 'report.html.plotproof-backup').exists() + + +@pytest.mark.skipif(os.name != 'nt', reason='Windows trailing-dot alias control') +def test_windows_trailing_dot_output_aliases_are_rejected(tmp_path, monkeypatch): + monkeypatch.setattr(cli, 'render_html', lambda report: '

new

\n') + json_path = tmp_path / 'report.json' + json_path.write_text('old json', encoding='utf-8') + with pytest.raises(cli.OutputError) as caught: + cli._save(report(), str(json_path), str(json_path) + '.plotproof-backup.', force=True) + assert caught.value.code == 'OUTPUT_AMBIGUOUS' + assert json_path.read_text(encoding='utf-8') == 'old json' + + +def test_backup_name_collision_is_refused_before_publication(tmp_path, monkeypatch): + monkeypatch.setattr(cli, 'render_html', lambda report: '

new

\n') + json_path = tmp_path / 'report.json' + html_path = tmp_path / 'report.json.plotproof-backup' + json_path.write_text('old json', encoding='utf-8') + with pytest.raises(cli.OutputError) as caught: + cli._save(report(), str(json_path), str(html_path), force=True) + assert caught.value.code == 'OUTPUT_BACKUP_EXISTS' + assert json_path.read_text(encoding='utf-8') == 'old json' + assert not html_path.exists() + + +def test_fdopen_failure_closes_descriptor_and_leaves_no_temporary(tmp_path, monkeypatch): + monkeypatch.setattr(cli, 'render_html', lambda report: '

new

\n') + destination = tmp_path / 'report.json' + + def fail_fdopen(*args, **kwargs): + raise OSError('injected fdopen failure') + + monkeypatch.setattr(cli.os, 'fdopen', fail_fdopen) + with pytest.raises(cli.OutputError): + cli._save(report(), str(destination), None) + assert not destination.exists() + assert not list(tmp_path.glob('*.tmp')) + + +def test_regular_file_parent_is_rejected_before_factory(tmp_path, capsys): + parent = tmp_path / 'not-a-directory' + parent.write_text('keep', encoding='utf-8') + module = tmp_path / 'figure.py' + module.write_text('def figure():\n raise RuntimeError("must not run")\n', encoding='utf-8') + assert cli.main(['check', str(module), '--json', str(parent / 'report.json')]) == 2 + assert json.loads(capsys.readouterr().out)['status'] == 'ERROR' + assert parent.read_text(encoding='utf-8') == 'keep' + + +def test_serialization_failure_publishes_nothing(tmp_path, monkeypatch): + destination = tmp_path / 'report.json' + broken = SimpleNamespace(to_dict=lambda: (_ for _ in ()).throw(ValueError('private'))) + monkeypatch.setattr(cli, 'render_html', lambda report: '

new

\n') + with pytest.raises(cli.OutputError) as caught: + cli._save(broken, str(destination), str(tmp_path / 'report.html')) + assert caught.value.code == 'OUTPUT_SERIALIZATION_FAILED' + assert not destination.exists() + + +def test_cli_refuses_existing_report_before_running_factory(tmp_path, monkeypatch, capsys): + module = tmp_path / 'figure.py' + module.write_text('def figure():\n raise RuntimeError("must not run")\n', encoding='utf-8') + destination = tmp_path / 'report.json' + destination.write_text('old evidence', encoding='utf-8') + assert cli.main(['check', str(module), '--json', str(destination)]) == 2 + payload = json.loads(capsys.readouterr().out) + assert payload['error']['code'] == 'OUTPUT_EXISTS' + assert destination.read_text(encoding='utf-8') == 'old evidence' + + +def test_cli_forced_output_failure_does_not_replace_restored_evidence(tmp_path, monkeypatch, capsys): + module = tmp_path / 'figure.py' + module.write_text('def figure(): pass\n', encoding='utf-8') + json_path, html_path = tmp_path / 'report.json', tmp_path / 'report.html' + json_path.write_text('old json', encoding='utf-8') + html_path.write_text('old html', encoding='utf-8') + monkeypatch.setattr(cli, 'check_figure', lambda *a, **k: report()) + monkeypatch.setattr(cli, 'render_html', lambda report: '

new

\n') + replace = os.replace + def fail_html(source, destination): + if Path(destination) == html_path and not str(source).endswith('.plotproof-backup'): + raise OSError('injected') + return replace(source, destination) + monkeypatch.setattr(cli.os, 'replace', fail_html) + assert cli.main(['check', str(module), '--json', str(json_path), + '--html', str(html_path), '--force']) == 2 + assert json.loads(capsys.readouterr().out)['error']['code'] == 'OUTPUT_PUBLISH_FAILED' + assert json_path.read_text(encoding='utf-8') == 'old json' + assert html_path.read_text(encoding='utf-8') == 'old html' + + +def test_demo_preflight_rejects_cross_report_hardlink_aliases(tmp_path): + output = tmp_path / 'demo' + output.mkdir() + first = output / 'clean.json' + first.write_text('old evidence', encoding='utf-8') + try: + os.link(first, output / 'clipped.html') + except OSError as error: + pytest.skip('hardlink creation unsupported: %s' % error) + assert cli.main(['demo', '--output', str(output), '--force']) == 2 + assert first.read_text(encoding='utf-8') == 'old evidence' + + +def test_demo_refuses_old_evidence_without_force_and_replaces_with_force(tmp_path, monkeypatch): + output = tmp_path / 'demo' + output.mkdir() + old = output / 'clean.json' + old.write_text('old evidence', encoding='utf-8') + monkeypatch.setattr(cli, 'render_html', lambda report: '

new

\n') + monkeypatch.setattr(cli, 'check_figure', lambda fig, **kwargs: report('FAIL' if 'clipped' in str(fig) else 'PASS')) + assert cli.main(['demo', '--output', str(output)]) == 2 + assert old.read_text(encoding='utf-8') == 'old evidence' + monkeypatch.setattr(cli, '_demo_figure', lambda deliberate: 'clipped' if deliberate else 'clean') + assert cli.main(['demo', '--output', str(output), '--force']) == 0 + assert json.loads(old.read_text(encoding='utf-8')) == {'state': 'PASS'} diff --git a/tests/test_package.py b/tests/test_package.py index 6b798c2..1d51ef5 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.0a2" + assert plotproof.__version__ == "0.1.0a3" 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.0a2" + assert probe["version"] == "0.1.0a3" assert probe["heavy"] == []