diff --git a/.claude/rules/ci.md b/.claude/rules/ci.md index d729c3d8ec..a9684a0c4c 100644 --- a/.claude/rules/ci.md +++ b/.claude/rules/ci.md @@ -15,7 +15,8 @@ paths: - **Manage CI without asking.** macOS runners are few, and every push to a pull request queues a set of macOS jobs. An agent may always cancel a run in flight — one a newer push superseded, one whose result nobody will read, one holding runners a more urgent run waits for — and start it again later. Cancel, never delete: a cancelled run keeps its record and logs. When several agents work at once, the one coordinating them decides which runs hold the runners. - No job, and no step that builds, tests, fuzzes or measures, has a `timeout-minutes`: a limit sized from past runs fails work that is only slower than those runs, speed is checked where it is measured ("Check Generate Time on Linux", the growth rows), and GitHub's six hours end a step that hangs. Only a step that fetches, downloads, uploads, resolves or installs keeps a short one, against a stalled server. Never a per-test timeout either, which makes CI flaky: Swift Testing's `.timeLimit` also counts the time a test waits for a thread behind the rest of the suite, and tests that do a fraction of a second of work have waited more than ten minutes on a loaded runner. A test that never ends is stopped when its run is cancelled or at six hours, and the log then holds no verdict for it: save the step's log and `Scripts/unfinished-tests.py LOG` names every test that started and did not finish. The Linux test jobs run the test bundle directly, which writes each line as it happens, so a hung test is listed alone. A step that runs `swift test` off a terminal gets the tests' output in blocks and loses the last one when it is stopped, so its list also holds tests that passed; the script says when a log was cut. - No scheduled or unattended check without a path that turns its findings into fix pull requests. -- New Linux jobs use the container and setup of "Build Tests on Linux" and "Build and Test on Linux" in `ci.yml`, except "Build and Test on Latest Swift" (`swift:latest`), "Lint Swift" (`swift:6.3`, a release build of SwiftFormat), and "Build Release SafeDITool on Linux", which runs `publish.yml`'s Linux build command in `publish.yml`'s container, because publishing 2.3.0-alpha-1 crashed Swift 6.3.3 compiling that release build of code every CI job had passed. "Delete This Run's Scratch Ref" (`verify.yml`, `graph-fuzzer.yml`) has no container: it runs only GitHub's API and git. +- **Performance measures are reported, not failed.** A performance row over its limit fails no check: wall time, peak memory, `.safedi` size, and a growth row's time, memory, size and code. A wall time differs between runners and between runs of one, so a failure on it was answered by running the job again; a change that moved another measure was answered by a commit that moved a limit and a run of every check again. "Check Generate Time on Linux" (`--report-measures`) and "Check Function Compile Time on Linux" (`--report-only`) therefore report a row over its limit as a warning, and "Post Timing to the Pull Request" writes both reports, with the change's tool against the newest release's, into one comment on the pull request that every run rewrites. The limits stay, as what the report calls over, and a change still does not raise one without approval. `Scripts/perf-watch.py --commit SHA [--before-commit SHA]` lists from a run's report every row over its limit, its ratio and limit, and how it moved since an earlier run: run it on each landing on main and on a release branch's heads, and give each row over a limit or worse an owner, so a regression is listed debt with a fix planned and never unseen. A shape or a row the tool cannot generate, or does not finish, still fails, as do the checks of correctness. A new check of a performance measure joins that comment (an artifact named `timing-comment-…` holding a Markdown report) and fails only when it measured nothing. Only that job has `pull-requests: write`, and it runs none of the pull request's code. +- New Linux jobs use the container and setup of "Build Tests on Linux" and "Build and Test on Linux" in `ci.yml`, except "Build and Test on Latest Swift" (`swift:latest`), "Lint Swift" (`swift:6.3`, a release build of SwiftFormat), and "Build Release SafeDITool on Linux", which runs `publish.yml`'s Linux build command in `publish.yml`'s container, because publishing 2.3.0-alpha-1 crashed Swift 6.3.3 compiling that release build of code every CI job had passed. "Delete This Run's Scratch Ref" (`verify.yml`, `graph-fuzzer.yml`) and "Post Timing to the Pull Request" have no container: each runs only GitHub's API, the first git too. - `ci.yml` runs every check on a branch with no pull request: `gh workflow run ci.yml --ref `. A landing stack is checked this way, never through a pull request opened only to carry its CI. The run counts every file as changed, reads no stack position, and compares "Check Generate Time on Linux" and the fuzzer's base comparison with the branch's merge base with main. - `verify.yml` ("Verify on Linux") runs "Build Tests on Linux"'s build for one branch: `gh workflow run verify.yml --ref -f filter=` (empty runs the suite; `-f pins=true` also checks the fuzzer's pins). It restores main's content-stamped build (`.github/scripts/stamp-source-times.sh`) and passed-compile-check caches; keep its container and `RELEASE_SWIFT_TEST_ARGUMENTS` in step with "Build Tests on Linux" and `graph-fuzzer.yml`'s coverage build, which restores its key. `-f mode=fast` needs a filter and builds in debug without coverage, from "Warm the Fast Verify Build Cache"'s cache. `-f mode=function-compile-time` runs only "Check Function Compile Time on Linux"'s build and check ("Verify Function Compile Time on Linux"; keep the two jobs' container, command and check in step) and tests nothing: run it before a pull request that adds or grows a long function under `Sources/SafeDICore` joins a stack, because the limit is about Linux's Swift 6.2 and CI runs on a stack's top only. - **A restored build compiles every test target again when what the tests are compiled against changed.** A restored build did not always compile a test target again when a module it imports changed, and linked tests compiled for an enum of SafeDICore without its new case, which crashed them; such a target can as well pass a test that should fail. `.github/scripts/stamp-source-times.sh` therefore gives a file under `Tests` a time from its content and from `Sources`, the test support target and the manifest together, so a change to any of those compiles every test target again. A job that restores a build of the tests stamps first. To rule a restored build out of one result, label the pull request `clean-build` and re-run (every restore of a SwiftPM or xcodebuild build in `ci.yml` is skipped; the label is read as it is now), or pass `verify.yml` `-f clean=true`. diff --git a/.claude/rules/scripts.md b/.claude/rules/scripts.md index 6120610ff4..acb7b0189c 100644 --- a/.claude/rules/scripts.md +++ b/.claude/rules/scripts.md @@ -18,7 +18,8 @@ What each script is for. Read this before running or changing one, and before wr - `Scripts/multi-module-repro.sh [--conditions DEBUG,X] ROOT MODULE…` runs `generate` per module as Bazel and Tuist do and compiles the modules in order. - `Scripts/unexecuted-lines.py` is "Check Line Coverage on Linux": it needs both test jobs' reports, so it cannot check a local run. `.claude/rules/ci.md` says how to read a CI run's result locally. - Tools only agents run are skills under `.claude/skills/`: `verify-touched` runs the suites a branch touches, before any full Verify. Before a review, run `pre-review` on the final head and put its block in the hand-back: lint, the touched suites, every fuzzer corpus with its pins on CI when the change owes them, and the lists a reviewer would otherwise ask for (32 of the 49 findings of one day's review rounds were ones an existing command shows). -- `Scripts/generate-time-check.py BASE_TOOL HEAD_TOOL DIRECTORY` is "Check Generate Time on Linux": it times two builds of `SafeDITool` generating synthetic seam, inline and public mock graphs in alternating runs, and fails when the second takes twice as long on one. +- `Scripts/generate-time-check.py BASE_TOOL HEAD_TOOL DIRECTORY` is "Check Generate Time on Linux": it times two builds of `SafeDITool` generating synthetic seam, inline and public mock graphs in alternating runs. It fails when the head tool cannot generate a shape; under `--report-measures`, which CI passes, a measure over its limit (wall time, peak memory, `.safedi` size, a growth row) is reported and fails nothing ("Performance measures are reported" in `.claude/rules/ci.md`). +- `Scripts/perf-watch.py [--before EARLIER_REPORT] REPORT`, or `--commit SHA [--before-commit SHA]`, reads that check's report (a file, or the artifact of a commit's newest CI run) and lists every row over its limit with its ratio and limit, how it moved since the earlier run, and every other row that got worse. - `Scripts/check-claude-instruction-files.sh` fails when an instruction file could be truncated or would load at launch by mistake, when a rules file is missing from the table under "Where the rest lives", when an instruction file names a Swift symbol no other tracked file contains (`Scripts/check-instruction-symbols.py`), or when reading one tracked file would load more rules than a budget allows (`Scripts/check-instruction-load.py`, whose `--report FILE…` prints what a file loads); "Check Markdown links" runs it. ## CI from a branch diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e4658d3b9..36d081e338 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3379,7 +3379,9 @@ jobs: with: command: command -v python3 >/dev/null || { timeout 120 apt-get -o Acquire::http::Timeout=20 -o Acquire::Retries=0 update && timeout 120 apt-get -o Acquire::http::Timeout=20 -o Acquire::Retries=0 install -y --no-install-recommends python3; } || { sed -i -E 's#http://(archive|security)\.ubuntu\.com/ubuntu#http://azure.archive.ubuntu.com/ubuntu#' /etc/apt/sources.list.d/ubuntu.sources; false; } - name: Check the Script - run: python3 -I Scripts/generate-time-check.py --self-test "$RUNNER_TEMP/generate-time-self-test" + run: | + python3 -I Scripts/generate-time-check.py --self-test "$RUNNER_TEMP/generate-time-self-test" + python3 -I Scripts/perf-watch.py --self-test # Scripts/compile-time-check.py imports this job's script, and its timed # comparison is run by hand, so a change to either that breaks it fails # here. About 40 s. @@ -3434,6 +3436,11 @@ jobs: echo "head=$head" >> "$GITHUB_OUTPUT" echo "base=$base" >> "$GITHUB_OUTPUT" echo "head $head, base $base" + # The newest release the base holds, whose tool "Compare Generate + # Time with the Newest Release" times beside the change's. + release=$(git describe --tags --abbrev=0 "$base" 2>/dev/null || true) + echo "release=$release" >> "$GITHUB_OUTPUT" + echo "newest release ${release:-(none)}" # Whether any file the tool is built from differs between the two # commits: its sources, the manifest and the dependencies' pins. # Where none does, the head tool is the base tool, and "Compare @@ -3528,6 +3535,19 @@ jobs: # on the four shapes with a memory limit of their own add about a # minute (0.6, 0.6, 2.2 and 2.1 s a run on a four-core Linux # machine). + # + # A measure over its limit does not fail the step + # (`--report-measures`): wall time, peak memory, `.safedi` size, and a + # growth row's time, memory, size and code. A change that moved one was + # answered by a commit that moved a limit and a run of every check + # again, and a wall time by running the job again, neither of which + # found a defect a reader of the figures would not. "Post Timing to + # the Pull Request" posts the report, and Scripts/perf-watch.py lists + # from a run's report every row over its limit and how each moved since + # an earlier run, so a row over a limit is owned and fixed rather than + # met as a red build. The limits stay as they are: they are what the + # report calls over. A shape or a row the tool cannot generate, or does + # not finish, still fails. - name: Compare Generate Time env: SAME_SOURCES: ${{ steps.commits.outputs.same-sources }} @@ -3536,8 +3556,12 @@ jobs: if [ "$SAME_SOURCES" = true ]; then same_sources=(--same-sources) fi - python3 -I Scripts/generate-time-check.py --summary "$GITHUB_STEP_SUMMARY" "${same_sources[@]}" \ - .generate-time/base/SafeDITool .generate-time/head/SafeDITool "$RUNNER_TEMP/generate-time" + mkdir -p "$RUNNER_TEMP/timing-comment" + status=0 + python3 -I Scripts/generate-time-check.py --report-measures --summary "$RUNNER_TEMP/timing-comment/1-generate-time.md" "${same_sources[@]}" \ + .generate-time/base/SafeDITool .generate-time/head/SafeDITool "$RUNNER_TEMP/generate-time" || status=$? + cat "$RUNNER_TEMP/timing-comment/1-generate-time.md" >> "$GITHUB_STEP_SUMMARY" || true + exit "$status" # The lines the change's tool generates for wide graphs, against # Scripts/compile-time-baseline.txt: generated code that compiled 2.4 # times slower passed the step above, which times `generate` alone. @@ -3563,6 +3587,61 @@ jobs: with: path: .generate-time/cached key: generate-time-tool-${{ runner.os }}-swift-6.2-${{ steps.commits.outputs.head }} + # The newest release's tool, for the comparison below, saved once per + # release by the first push to main that finds none: a pull request's + # run can restore what main saved and nothing a pull request saves + # reaches another, so only main builds it. It is built in a worktree + # of its own, which leaves this checkout's build as it is. + - name: Restore the Newest Release's SafeDITool + id: release-tool + if: ${{ !cancelled() && steps.commits.outputs.release != '' && steps.commits.outputs.same-sources != 'true' }} + uses: actions/cache/restore@v6 + with: + path: .generate-time/release + key: generate-time-release-tool-${{ runner.os }}-swift-6.2-${{ steps.commits.outputs.release }} + - name: Build the Newest Release's SafeDITool + if: ${{ !cancelled() && steps.release-tool.outcome == 'success' && steps.release-tool.outputs.cache-hit != 'true' && github.event_name == 'push' && github.ref == 'refs/heads/main' }} + env: + RELEASE: ${{ steps.commits.outputs.release }} + run: | + git worktree add --detach "$RUNNER_TEMP/release" "$RELEASE" + swift build -c release --package-path "$RUNNER_TEMP/release" --product SafeDITool + mkdir -p .generate-time/release + cp "$RUNNER_TEMP/release/.build/release/SafeDITool" .generate-time/release/SafeDITool + - name: Save the Newest Release's SafeDITool + if: ${{ !cancelled() && steps.release-tool.outcome == 'success' && steps.release-tool.outputs.cache-hit != 'true' && hashFiles('.generate-time/release/SafeDITool') != '' }} + uses: actions/cache/save@v6 + with: + path: .generate-time/release + key: ${{ steps.release-tool.outputs.cache-primary-key }} + # The change's tool against the newest release's, on the shapes alone, + # three runs of each: every finding is reported and none fails + # (`--report-only`), since what a release took is no limit of this + # check's. "Compare Generate Time" took 9.7 and 15.1 minutes comparing + # two tools with five runs and the growth rows, which take about 5 of + # them (job 143071331612, which ran those alone) and which this step + # leaves out: 5 to 10 minutes for the shapes at five runs, so about 3 + # to 6 at three. + - name: Compare Generate Time with the Newest Release + if: ${{ !cancelled() && hashFiles('.generate-time/release/SafeDITool') != '' && hashFiles('.generate-time/head/SafeDITool') != '' }} + env: + RELEASE: ${{ steps.commits.outputs.release }} + run: | + mkdir -p "$RUNNER_TEMP/timing-comment" + python3 -I Scripts/generate-time-check.py --report-only --base-name "$RELEASE" --runs 3 --large-memory-runs 3 --growth none \ + --summary "$RUNNER_TEMP/timing-comment/2-generate-time-release.md" \ + .generate-time/release/SafeDITool .generate-time/head/SafeDITool "$RUNNER_TEMP/generate-time-release" + cat "$RUNNER_TEMP/timing-comment/2-generate-time-release.md" >> "$GITHUB_STEP_SUMMARY" || true + - name: Upload the Timing Reports + if: ${{ !cancelled() }} + uses: actions/upload-artifact@v7 + with: + name: timing-comment-generate-time + path: ${{ runner.temp }}/timing-comment/*.md + if-no-files-found: ignore + # Scripts/perf-watch.py compares a run's report with an earlier + # run's, which may be days older. + retention-days: 30 # Builds the SafeDITool of the pull request's base, which each fuzzer shard # below runs beside this commit's over the shard's graphs @@ -3796,9 +3875,95 @@ jobs: -Xswiftc -Xfrontend -Xswiftc -debug-time-function-bodies \ -Xswiftc -Xllvm -Xswiftc -sil-print-pass-time -Xswiftc -Xllvm -Xswiftc -sil-min-pass-time=20 \ > "$RUNNER_TEMP/function-compile-time.log" 2>&1 || { tail -n 200 "$RUNNER_TEMP/function-compile-time.log"; exit 1; } + # A function over its limit is reported and does not fail the step + # (`--report-only`), for the reason "Compare Generate Time" gives: the + # figures are the compiler's wall time on this runner. A log with no + # time in it still fails. - name: Check Each Function's Time if: ${{ steps.scope.outputs.timed == 'true' }} - run: python3 -I Scripts/function-compile-time-check.py --summary "$GITHUB_STEP_SUMMARY" "$RUNNER_TEMP/function-compile-time.log" + run: | + mkdir -p "$RUNNER_TEMP/timing-comment" + status=0 + python3 -I Scripts/function-compile-time-check.py --report-only --summary "$RUNNER_TEMP/timing-comment/3-function-compile-time.md" "$RUNNER_TEMP/function-compile-time.log" || status=$? + cat "$RUNNER_TEMP/timing-comment/3-function-compile-time.md" >> "$GITHUB_STEP_SUMMARY" || true + exit "$status" + - name: Upload the Timing Report + if: ${{ !cancelled() && steps.scope.outputs.timed == 'true' }} + uses: actions/upload-artifact@v7 + with: + name: timing-comment-function-compile-time + path: ${{ runner.temp }}/timing-comment/*.md + if-no-files-found: ignore + retention-days: 3 + + # Posts what "Check Generate Time on Linux" and "Check Function Compile + # Time on Linux" measured as one comment on the pull request, which every + # run rewrites: measures over a limit are read there and fail no job, so + # deciding on one needs no second run. It runs none of the pull request's + # code, which is why the two jobs that do hand it their reports as + # artifacts and it alone may write to the pull request. A pull request + # from a fork gets no comment, since its token cannot write; the reports + # are in the two jobs' summaries either way. It has no container: it runs + # only GitHub's API. A comment that cannot be posted is a warning, never a + # failure, since nothing was checked here. + timing-comment: + name: Post Timing to the Pull Request + needs: [generate-time, function-compile-time] + if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository && (needs.generate-time.result != 'skipped' || needs.function-compile-time.result != 'skipped') }} + runs-on: ubuntu-latest + permissions: + actions: read + pull-requests: write + steps: + # No artifact when both jobs skipped or measured nothing. + - name: Download the Reports + continue-on-error: true + timeout-minutes: 5 + uses: actions/download-artifact@v8 + with: + pattern: timing-comment-* + path: reports + merge-multiple: true + # Requests to GitHub only; the limit ends one that hangs. + - name: Post or Rewrite the Comment + timeout-minutes: 5 + env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + PULL_REQUEST: ${{ github.event.pull_request.number }} + HEAD: ${{ github.event.pull_request.head.sha }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + shopt -s nullglob + reports=(reports/*.md) + if [ "${#reports[@]}" -eq 0 ]; then + echo "Neither check measured anything in this run, so the comment, if there is one, stays as it is." + exit 0 + fi + marker='' + { + echo "$marker" + echo "### Timing of ${HEAD:0:9}" + echo + echo "Wall times measured in [this run]($RUN_URL). A wall time, peak memory, `.safedi` size or growth row over its limit is reported here and fails no check; a shape the tool cannot generate still fails \"Check Generate Time on Linux\". Every run rewrites this comment, and a check that did not run in it is not listed." + for report in "${reports[@]}"; do + echo + cat "$report" + done + } > body.md + # GitHub refuses a comment of more than 65,536 characters. + python3 -I -c 'import sys; text = open("body.md", encoding="utf-8", errors="replace").read(); open("body.md", "w", encoding="utf-8").write(text if len(text) <= 60000 else text[:60000] + "\n\n\n\nCut here: the rest is in the summary of the run.\n")' + if ! comment=$(gh api --paginate "repos/$REPOSITORY/issues/$PULL_REQUEST/comments?per_page=100" --jq '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith(""))) | .id' 2>&1); then + echo "::warning::Listing the pull request's comments failed, so the timing is in the jobs' summaries only: $(printf '%s' "$comment" | tr '\r\n' ' ')" + exit 0 + fi + comment=$(printf '%s\n' "$comment" | head -n 1) + if [ -n "$comment" ]; then + posted=$(gh api -X PATCH "repos/$REPOSITORY/issues/comments/$comment" -F body=@body.md --jq .html_url 2>&1) || { echo "::warning::Rewriting the timing comment failed: $(printf '%s' "$posted" | tr '\r\n' ' ')"; exit 0; } + else + posted=$(gh api -X POST "repos/$REPOSITORY/issues/$PULL_REQUEST/comments" -F body=@body.md --jq .html_url 2>&1) || { echo "::warning::Posting the timing comment failed: $(printf '%s' "$posted" | tr '\r\n' ' ')"; exit 0; } + fi + echo "$posted" # Fuzzes each of the graph fuzzer's corpora whole – the base corpus, seeds # 0..= size_limit and head_size - base_size > SIZE_NOISE_FLOOR_BYTES if size_over: - failures.append(f"{shape}: module {name}'s `.safedi` file is {size_ratio:.2f} times the base tool's ({head_size} bytes against {base_size}); the limit is {size_limit:g}") + failures.append(Measure(f"{shape}: module {name}'s `.safedi` file is {size_ratio:.2f} times the base tool's ({head_size} bytes against {base_size}); the limit is {size_limit:g}")) size_rows.append(f"| {shape} | {name} | {base_size} | {head_size} | {size_ratio:.2f} | {'**over the limit**' if size_over else f'within the accepted {accepted_size} bytes' if size_accepted else 'within the limit'} |") print(f"{shape}: module {name}'s `.safedi` file, base {base_size} bytes, head {head_size} bytes, ratio {size_ratio:.2f}", flush=True) for run in range(runs): @@ -1763,11 +1797,11 @@ def compare(base_tool, head_tool, directory, shapes, runs, limit, memory_limit, ratio = median["head"][0] / median["base"][0] over = ratio >= shape_limit and median["head"][0] - median["base"][0] > NOISE_FLOOR_SECONDS if over: - failures.append(f"{shape}: `generate` took {ratio:.2f} times as long as the base tool ({median['head'][0]:.3f} s against {median['base'][0]:.3f} s, median wall of {runs}); the limit is {shape_limit:g}") + failures.append(Timing(f"{shape}: `generate` took {ratio:.2f} times as long as the base tool ({median['head'][0]:.3f} s against {median['base'][0]:.3f} s, median wall of {runs}); the limit is {shape_limit:g}")) memory_ratio = median["head"][2] / median["base"][2] memory_over = not one_arena_only and memory_ratio >= shape_memory_limit and median["head"][2] - median["base"][2] > MEMORY_NOISE_FLOOR_BYTES if memory_over: - failures.append(f"{shape}: `generate` needed {memory_ratio:.2f} times the base tool's peak memory ({megabytes(median['head'][2])} against {megabytes(median['base'][2])}, median of {runs}); the limit is {shape_memory_limit:g}") + failures.append(Measure(f"{shape}: `generate` needed {memory_ratio:.2f} times the base tool's peak memory ({megabytes(median['head'][2])} against {megabytes(median['base'][2])}, median of {runs}); the limit is {shape_memory_limit:g}")) one_arena = "" if one_arena_runs: peaks = {"base": [], "head": []} @@ -1778,7 +1812,7 @@ def compare(base_tool, head_tool, directory, shapes, runs, limit, memory_limit, one_arena_ratio = head_peak / base_peak if one_arena_ratio >= one_arena_limit and head_peak - base_peak > MEMORY_NOISE_FLOOR_BYTES: memory_over = True - failures.append(f"{shape}: `generate` needed {one_arena_ratio:.2f} times the base tool's peak memory with one allocator arena ({megabytes(head_peak)} against {megabytes(base_peak)}, median of {one_arena_runs}); the limit is {one_arena_limit:g}") + failures.append(Measure(f"{shape}: `generate` needed {one_arena_ratio:.2f} times the base tool's peak memory with one allocator arena ({megabytes(head_peak)} against {megabytes(base_peak)}, median of {one_arena_runs}); the limit is {one_arena_limit:g}")) one_arena = f"; with one arena {megabytes(base_peak)} and {megabytes(head_peak)}, {one_arena_ratio:.2f}{', the figure compared' if one_arena_only else ''}" for label in ("base", "head"): print(f"{shape}: {label}'s peak memory of each run with one arena, lowest first, in MB: {' '.join(f'{peak / 1024 / 1024:.1f}' for peak in sorted(peaks[label]))}", flush=True) @@ -1852,15 +1886,25 @@ def grow(head_tool, directory, growth_rows, runs, limit, time_limit=GROWTH_TIME_ measure_limit = row_limits.get(measure, limit) if ratio >= measure_limit and larger - smaller > floor: over.append(measure) - failures.append(f"{name}: at {depths[1]} layers `generate` {phrase.format(ratio=ratio, fewer=depths[0])} ({printed(larger)} against {printed(smaller)}); the limit is {measure_limit:g}, and the graph has {depths[1] / depths[0]:.2f} times the layers") + failure = f"{name}: at {depths[1]} layers `generate` {phrase.format(ratio=ratio, fewer=depths[0])} ({printed(larger)} against {printed(smaller)}); the limit is {measure_limit:g}, and the graph has {depths[1] / depths[0]:.2f} times the layers" + failures.append(GrowthTiming(failure) if measure == "time" else Measure(failure)) cells.append(f"{printed(smaller)}, {printed(larger)}, {ratio:.2f}" + (f" (limit {measure_limit:g})" if measure in row_limits else "")) rows.append(f"| {name} | {depths[0]} and {depths[1]} | {' | '.join(cells)} | {'**' + ' and '.join(over) + ' over the limit**' if over else 'within the limits'} |") print(f"{name}: at {depths[0]} and {depths[1]} layers, " + "; ".join(f"{measure} {cell}" for (measure, _, _, _, _), cell in zip(measures, cells)), flush=True) return rows, failures -def report(rows, size_rows, failures, runs, limit, memory_limit, size_limit, summary, large_memory_limit=1.1, large_memory_runs=LARGE_MEMORY_RUNS, growth_rows=[], growth_runs=GROWTH_RUNS, growth_limit=2.0): - lines = [f"`generate` time and peak memory, head against base: median of {runs} alternating runs; a shape fails at {limit:g} times the base's wall time or {memory_limit:g} times its peak memory, and {', '.join(sorted(LARGE_MEMORY_SHAPES))} also at {min(memory_limit, large_memory_limit):g} times the base's median peak of {large_memory_runs} more runs with one allocator arena. {', '.join(sorted(ONE_ARENA_ONLY_SHAPES))} are compared on their runs with one arena alone, at {memory_limit:g} or at the shape's own memory limit.", "", +def report(rows, size_rows, failures, runs, limit, memory_limit, size_limit, summary, large_memory_limit=1.1, large_memory_runs=LARGE_MEMORY_RUNS, growth_rows=[], growth_runs=GROWTH_RUNS, growth_limit=2.0, reported=lambda failure: False, base="base"): + """Prints the tables and the findings, appends them to `summary`, and returns the findings that fail the check: + those `reported` is false of. The others are listed apart. `base` names the base tool in the headline.""" + listed = [failure for failure in failures if reported(failure)] + failing = [failure for failure in failures if not reported(failure)] + headline = f"**`generate`, head against {base}: {len(failing)} failure(s)" + (f", and {len(listed)} finding(s) reported and not failed" if listed else "") + ".**" + # The findings first and the tables folded, so that a comment made of this report reads in a few lines. + lines = [headline, ""] + [f"- {failure}" for failure in failing] + if listed: + lines += ["", "Reported and not failed:", ""] + [f"- {failure}" for failure in listed] + lines += ["", "
Every shape and row", "", f"`generate` time and peak memory, head against base: median of {runs} alternating runs; a shape fails at {limit:g} times the base's wall time or {memory_limit:g} times its peak memory, and {', '.join(sorted(LARGE_MEMORY_SHAPES))} also at {min(memory_limit, large_memory_limit):g} times the base's median peak of {large_memory_runs} more runs with one allocator arena. {', '.join(sorted(ONE_ARENA_ONLY_SHAPES))} are compared on their runs with one arena alone, at {memory_limit:g} or at the shape's own memory limit.", "", "| Shape | Runs | Base wall / CPU | Head wall / CPU | Head / base (wall) | Base peak | Head peak | Head / base (peak) | Generated code | Verdict |", "|---|---|---|---|---|---|---|---|---|---|"] + rows lines += ["", f"`.safedi` size, head against base: a module fails at {size_limit:g} times the base's bytes.", "", @@ -1868,15 +1912,18 @@ def report(rows, size_rows, failures, runs, limit, memory_limit, size_limit, sum if growth_rows: lines += ["", f"Growth, the head tool alone: each row at its layers and at {GROWTH_STEP} more, or at the two numbers it names; median of {growth_runs} alternating runs for time, and of {growth_runs} more with one allocator arena for peak memory. A measure fails at {growth_limit:g} times the smaller graph's, or at the limit beside it.", "", "| Row | Layers | Wall: fewer layers, more, ratio | Peak memory | `.safedi` bytes | Generated code | Verdict |", "|---|---|---|---|---|---|---|"] + growth_rows - lines += [""] + [f"- {failure}" for failure in failures] + lines += ["", "
"] text = "\n".join(lines) + "\n" print(text) if summary: with open(summary, "a") as handle: handle.write(text) - for failure in failures: - if os.environ.get("GITHUB_ACTIONS") == "true": + if os.environ.get("GITHUB_ACTIONS") == "true": + for failure in failing: print(f"::error::{failure.splitlines()[0]}") + for failure in listed: + print(f"::warning::{failure.splitlines()[0]}") + return failing # MARK: Self-test @@ -2038,6 +2085,25 @@ def expect_growth_under_plugin(name, head, expected_failures, expected_row, time expect_growth_under_plugin("growth-under-the-plugin-of-code-with-their-cube", tool("cubic-code-under-the-plugin", 0.0, grows={"code": 3}), 1, "**code over the limit**") expect_growth_under_plugin("growth-under-the-plugin-scan-refused", tool("scan-refuses", 0.0, refuses=True), 1, "**failed**") expect_growth_under_plugin("growth-under-the-plugin-never-ends", tool("never-ends-under-the-plugin", 30.0), 1, "**failed**", time_limit=1) + # A wall time over its limit is a `Timing`, against the base and in a growth row alike, and nothing else is: a + # report told to list those apart returns only the other findings, which still fail the check. + _, _, found = compare(fast, tool("slower-and-more-memory", 0.2, allocates=64 * 1024 * 1024), f"{directory}/reported-against-the-base", ["E16-seam"], 3, 2.0, 1.3, 2.0, large_memory_shapes=frozenset(), one_arena_only_shapes=frozenset()) + _, growth_found = grow(tool("cubic-time-and-code", 0.00001, grows={"time": 3, "code": 3}), f"{directory}/reported-growth", {"P": (shape_p, 4, {})}, 3, 2.0) + kinds = [[isinstance(finding, Timing) for finding in findings] for findings in (found, growth_found)] + refused = compare(fast, tool("refuses-and-is-no-measure", 0.01, refuses=True), f"{directory}/refused-is-no-measure", ["E16-seam"], 3, 2.0, 1.3, 2.0, large_memory_shapes=frozenset(), one_arena_only_shapes=frozenset())[2] + if not all(isinstance(finding, Measure) for finding in found + growth_found) or len(refused) != 1 or isinstance(refused[0], Measure): + failures.append(f"every finding over a limit is a measure and a shape the head tool refuses is none, but {found}, {growth_found} and {refused} gave {[type(finding).__name__ for finding in found + growth_found + refused]}") + if kinds != [[True, False], [True, False]] or isinstance(found[0], GrowthTiming) or not isinstance(growth_found[0], GrowthTiming): + failures.append(f"a slower head that needs more memory, and a row whose time and code grow, gave {found} and {growth_found}, whose wall times are {kinds}") + for name, reported, expected, lines in (("all-fail", lambda finding: False, 4, ["head against base: 4 failure(s).**"]), + ("times-reported", lambda finding: isinstance(finding, Timing), 2, ["head against base: 2 failure(s), and 2 finding(s) reported and not failed.**", "Reported and not failed:"]), + ("measures-reported", lambda finding: isinstance(finding, Measure), 0, ["head against base: 0 failure(s), and 4 finding(s) reported and not failed.**"]), + ("all-reported", lambda finding: True, 0, ["head against base: 0 failure(s), and 4 finding(s) reported and not failed.**"])): + failing = report([], [], found + growth_found, 3, 2.0, 1.3, 2.0, f"{directory}/summary-{name}.md", reported=reported) + with open(f"{directory}/summary-{name}.md") as handle: + text = handle.read() + if len(failing) != expected or any(reported(finding) for finding in failing) or not all(line in text for line in lines): + failures.append(f"report {name}: of two wall times and two other findings it returned {failing} and wrote {text!r}") for row, parts in GROWTH_ROWS.items(): build, (fewer, more), row_limits, timed_module = row_parts(parts) if not set(row_limits) <= {"time", "memory", "size", "code"}: @@ -2124,6 +2190,11 @@ def main(arguments): growth_limit = 2.0 summary = None same_sources = False + report_time = False + report_growth_time = False + report_measures = False + report_only = False + base_name = "base" positional = [] self_testing = False while arguments: @@ -2132,7 +2203,15 @@ def main(arguments): self_testing = True elif argument == "--same-sources": same_sources = True - elif argument in ("--runs", "--large-memory-runs", "--limit", "--memory-limit", "--large-memory-limit", "--size-limit", "--shapes", "--growth", "--growth-runs", "--growth-limit", "--summary") and arguments: + elif argument == "--report-time": + report_time = True + elif argument == "--report-growth-time": + report_growth_time = True + elif argument == "--report-measures": + report_measures = True + elif argument == "--report-only": + report_only = True + elif argument in ("--runs", "--large-memory-runs", "--limit", "--memory-limit", "--large-memory-limit", "--size-limit", "--shapes", "--growth", "--growth-runs", "--growth-limit", "--summary", "--base-name") and arguments: value = arguments.pop(0) if argument == "--runs": runs = int(value) @@ -2154,6 +2233,8 @@ def main(arguments): growth_runs = int(value) elif argument == "--growth-limit": growth_limit = float(value) + elif argument == "--base-name": + base_name = value else: summary = value else: @@ -2180,8 +2261,9 @@ def main(arguments): rows, size_rows, failures = compare(os.path.abspath(positional[0]), os.path.abspath(positional[1]), directory, shapes, runs, limit, memory_limit, size_limit, large_memory_limit, large_memory_runs=large_memory_runs) growth_rows, growth_failures = grow(os.path.abspath(positional[1]), directory, {row: GROWTH_ROWS[row] for row in growth}, growth_runs, growth_limit) failures += growth_failures - report(rows, size_rows, failures, runs, limit, memory_limit, size_limit, summary, large_memory_limit, large_memory_runs, growth_rows, growth_runs, growth_limit) - return 1 if failures else 0 + failing = report(rows, size_rows, failures, runs, limit, memory_limit, size_limit, summary, large_memory_limit, large_memory_runs, growth_rows, growth_runs, growth_limit, + reported=lambda failure: report_only or (report_measures and isinstance(failure, Measure)) or (report_growth_time if isinstance(failure, GrowthTiming) else report_time and isinstance(failure, Timing)), base=base_name) + return 1 if failing else 0 if __name__ == "__main__": diff --git a/Scripts/perf-watch.py b/Scripts/perf-watch.py new file mode 100644 index 0000000000..1e477e4120 --- /dev/null +++ b/Scripts/perf-watch.py @@ -0,0 +1,262 @@ +#!/usr/bin/env python3 +"""Usage: perf-watch.py [--before EARLIER_REPORT] [--worse RATIO] REPORT + perf-watch.py [--before-commit SHA] [--worse RATIO] [--repository OWNER/NAME] --commit SHA + perf-watch.py --self-test + +Reads the report "Check Generate Time on Linux" writes (Scripts/generate-time-check.py's summary, which CI uploads +as the artifact `timing-comment-generate-time` and posts in the pull request's timing comment) and prints, as +Markdown, every row over its limit with its ratio and its limit, and, given an earlier report, how each such row's +ratio moved since and every other row whose ratio rose to RATIO (default 1.05) times the earlier one or more. +A measure over its limit fails no check, so that a change is not answered by a commit that moves a limit and a run +of every check again; this is how such a row is seen, compared with the run before, and given to whoever fixes it. + +With `--commit`, the report is the artifact of the newest CI run of that commit that has one, fetched with `gh api` +(`--before-commit` names the earlier commit the same way). Exits 0 when no row is over a limit and none is worse, 1 +when one is, and 2 when a report cannot be read: a report with no row in it is an error, never a clean result.""" +import io +import json +import re +import subprocess +import sys +import zipfile + +ARTIFACT = "timing-comment-generate-time" + +# What a finding's sentence says, and the measure it is of. The first that matches names it. +FINDING_MEASURES = ( + ("took {} times as long as the base tool", "wall time"), + ("peak memory with one allocator arena", "peak memory with one arena"), + ("times the base tool's peak memory", "peak memory"), + ("`.safedi` file is", "`.safedi` size"), + ("times as long as at", "growth: wall time"), + ("times the peak memory it needed at", "growth: peak memory"), + ("wrote `.safedi` files", "growth: `.safedi` size"), + ("times the code it generated at", "growth: generated code"), +) +GROWTH_MEASURES = ("growth: wall time", "growth: peak memory", "growth: `.safedi` size", "growth: generated code") + + +def cells_of(line): + return [cell.strip() for cell in line.strip().strip("|").split("|")] + + +def number(text): + found = re.search(r"\d+(?:\.\d+)?", text) + return float(found.group(0)) if found else None + + +def read_report(text): + """Returns (the ratio of every (row, measure) in the tables, the findings as (row, measure, ratio, limit, fails, + sentence)). Only the first report of `text` is read: the comparison with the base, which the file starts with.""" + ratios = {} + findings = [] + table = None + reports = 0 + reported = False + for line in text.splitlines(): + if line.startswith("**`generate`, head against "): + reports += 1 + reported = False + if reports != 1: + continue + if line.startswith("Reported and not failed:"): + reported = True + elif line.startswith("- "): + sentence = line[2:] + row = sentence.split(": ", 1)[0] + measure = next((name for phrase, name in FINDING_MEASURES if all(part in sentence for part in phrase.split("{}"))), None) + ratio = re.search(r"(\d+(?:\.\d+)?) times", sentence) + limit = re.search(r"the limit is (\d+(?:\.\d+)?)", sentence) + module = re.search(r"module (\S+?)'s `\.safedi` file", sentence) + if module: + row = f"{row} / {module.group(1)}" + findings.append((row, measure, float(ratio.group(1)) if ratio and measure else None, float(limit.group(1)) if limit and measure else None, not reported, sentence)) + elif line.startswith("| Shape | Runs |"): + table = "shapes" + elif line.startswith("| Shape | Module |"): + table = "sizes" + elif line.startswith("| Row | Layers |"): + table = "growth" + elif not line.startswith("|"): + table = None + elif table and not line.startswith("|---"): + cells = cells_of(line) + if table == "shapes" and len(cells) >= 8: + ratios[(cells[0], "wall time")] = number(cells[4]) + ratios[(cells[0], "peak memory")] = number(cells[7]) + one_arena = re.search(r"with one arena .*?, (\d+(?:\.\d+)?)(?:,|$)", cells[7]) + if one_arena: + ratios[(cells[0], "peak memory with one arena")] = float(one_arena.group(1)) + elif table == "sizes" and len(cells) >= 5: + ratios[(f"{cells[0]} / {cells[1]}", "`.safedi` size")] = number(cells[4]) + elif table == "growth" and len(cells) >= 6: + for measure, cell in zip(GROWTH_MEASURES, cells[2:6]): + ratio = re.search(r", (\d+(?:\.\d+)?)(?: \(limit|$)", cell) + if ratio: + ratios[(cells[0], measure)] = float(ratio.group(1)) + return {key: value for key, value in ratios.items() if value is not None}, findings + + +def watch(text, before_text=None, worse=1.05, name="this run", before_name="the earlier run"): + """Returns (the Markdown, whether a row is over its limit or worse).""" + ratios, findings = read_report(text) + if not ratios: + raise ValueError(f"the report of {name} has no row in it") + before = read_report(before_text)[0] if before_text is not None else None + if before_text is not None and not before: + raise ValueError(f"the report of {before_name} has no row in it") + + def moved(key, ratio): + if before is None: + return "no earlier run given" + elif key not in before: + return f"not in {before_name}" + else: + return f"{before[key]:.2f} in {before_name}, {ratio - before[key]:+.2f}" + + lines = [f"## Performance rows of {name}", ""] + over = [finding for finding in findings if finding[1]] + other = [finding for finding in findings if not finding[1]] + lines += [f"{len(over)} row(s) over a limit, of {len(ratios)} measured.", ""] + if over: + lines += ["| Row | Measure | Ratio | Limit | Since the earlier run | Fails the check |", "|---|---|---|---|---|---|"] + for row, measure, ratio, limit, fails, _ in sorted(over): + lines.append(f"| {row} | {measure} | {ratio:.2f} | {limit:g} | {moved((row, measure), ratio)} | {'yes' if fails else 'no, reported'} |") + lines.append("") + if other: + lines += ["Findings that are no measure, which fail the check:", ""] + [f"- {finding[5]}" for finding in other] + [""] + worsened = [] + if before is not None: + listed = {(finding[0], finding[1]) for finding in over} + worsened = sorted((key, before[key], ratio) for key, ratio in ratios.items() if key in before and key not in listed and before[key] > 0 and ratio / before[key] >= worse and ratio - before[key] >= 0.05) + lines += [f"{len(worsened)} other row(s) whose ratio rose to {worse:g} times that of {before_name}, or more, and by 0.05 or more.", ""] + if worsened: + lines += ["| Row | Measure | Ratio | Earlier | Change |", "|---|---|---|---|---|"] + lines += [f"| {key[0]} | {key[1]} | {ratio:.2f} | {earlier:.2f} | {ratio - earlier:+.2f} |" for key, earlier, ratio in worsened] + lines.append("") + return "\n".join(lines), bool(over or other or worsened) + + +def gh(*arguments, binary=False): + result = subprocess.run(["gh", "api", *arguments], capture_output=True) + if result.returncode != 0: + raise ValueError(f"gh api {' '.join(arguments)} failed: {result.stderr.decode(errors='replace').strip()[:300]}") + return result.stdout if binary else result.stdout.decode() + + +def report_of_commit(repository, commit): + """The first Markdown file of the artifact of the newest run of `commit` that has one.""" + runs = json.loads(gh(f"repos/{repository}/actions/runs?head_sha={commit}&per_page=100"))["workflow_runs"] + for run in sorted(runs, key=lambda run: run["created_at"], reverse=True): + artifacts = json.loads(gh(f"repos/{repository}/actions/runs/{run['id']}/artifacts?per_page=100"))["artifacts"] + for artifact in artifacts: + if artifact["name"] == ARTIFACT and not artifact["expired"]: + archive = zipfile.ZipFile(io.BytesIO(gh(f"repos/{repository}/actions/artifacts/{artifact['id']}/zip", binary=True))) + names = sorted(name for name in archive.namelist() if name.endswith(".md")) + if names: + return archive.read(names[0]).decode(errors="replace"), f"{commit[:9]} (run {run['id']})" + raise ValueError(f"no run of {commit} has a `{ARTIFACT}` artifact: has \"Check Generate Time on Linux\" finished there, within the artifact's 30 days?") + + +SAMPLE = """**`generate`, head against base: 1 failure(s), and 3 finding(s) reported and not failed.** + +- E16-seam: the head tool did not generate it: refused + +Reported and not failed: + +- S12-mocks: `generate` needed 1.28 times the base tool's peak memory with one allocator arena (200.4 MB against 156.0 MB, median of 5); the limit is 1.1 +- M: module Root's `.safedi` file is 2.50 times the base tool's (25000 bytes against 10000); the limit is 2 +- K: at 6 layers `generate` took 6.62 times as long as at 4 layers (1.000 s against 0.151 s); the limit is 6.5, and the graph has 1.50 times the layers + +
Every shape and row + +| Shape | Runs | Base wall / CPU | Head wall / CPU | Head / base (wall) | Base peak | Head peak | Head / base (peak) | Generated code | Verdict | +|---|---|---|---|---|---|---|---|---|---| +| S12-mocks | 5, and 5 with one arena | 1.000 s / 1.000 s | 1.200 s / 1.200 s | 1.20 | 150.0 MB | 190.0 MB | 1.27; with one arena 156.0 MB and 200.4 MB, 1.28, the figure compared | identical | **memory over the limit** | +| S16 | 5 | 1.000 s / 1.000 s | 1.100 s / 1.100 s | 1.10 | 100.0 MB | 100.0 MB | 1.00 | identical | within the limits | + +| Shape | Module | Base bytes | Head bytes | Head / base | Verdict | +|---|---|---|---|---|---| +| M | Root | 10000 | 25000 | 2.50 | **over the limit** | + +| Row | Layers | Wall: fewer layers, more, ratio | Peak memory | `.safedi` bytes | Generated code | Verdict | +|---|---|---|---|---|---|---| +| K | 4 and 6 | 0.151 s, 1.000 s, 6.62 (limit 6.5) | 10.0 MB, 12.0 MB, 1.20 | 100 bytes, 150 bytes, 1.50 | 1000 bytes, 1500 bytes, 1.50 | **time over the limit** | + +
+ +**`generate`, head against 2.4.5: 0 failure(s), and 1 finding(s) reported and not failed.** + +Reported and not failed: + +- S16: `generate` took 9.00 times as long as the base tool (9.000 s against 1.000 s, median wall of 3); the limit is 2 +""" + + +def self_test(): + failures = [] + ratios, findings = read_report(SAMPLE) + expected = {("S12-mocks", "wall time"): 1.2, ("S12-mocks", "peak memory"): 1.27, ("S12-mocks", "peak memory with one arena"): 1.28, ("S16", "wall time"): 1.1, ("S16", "peak memory"): 1.0, + ("M / Root", "`.safedi` size"): 2.5, ("K", "growth: wall time"): 6.62, ("K", "growth: peak memory"): 1.2, ("K", "growth: `.safedi` size"): 1.5, ("K", "growth: generated code"): 1.5} + if ratios != expected: + failures.append(f"the sample's tables read as {ratios}") + read = [finding[:5] for finding in findings] + if read != [("E16-seam", None, None, None, True), ("S12-mocks", "peak memory with one arena", 1.28, 1.1, False), ("M / Root", "`.safedi` size", 2.5, 2.0, False), ("K", "growth: wall time", 6.62, 6.5, False)]: + failures.append(f"the sample's findings read as {read}: the second report's are not the base comparison's") + earlier = SAMPLE.replace("1.200 s / 1.200 s | 1.20 |", "1.000 s / 1.000 s | 1.00 |").replace("200.4 MB, 1.28, the", "170.0 MB, 1.09, the") + text, found = watch(SAMPLE, earlier) + for line in ("3 row(s) over a limit, of 10 measured.", "| S12-mocks | peak memory with one arena | 1.28 | 1.1 | 1.09 in the earlier run, +0.19 | no, reported |", "| K | growth: wall time | 6.62 | 6.5 | 6.62 in the earlier run, +0.00 | no, reported |", + "- E16-seam: the head tool did not generate it: refused", "1 other row(s) whose ratio rose", "| S12-mocks | wall time | 1.20 | 1.00 | +0.20 |"): + if line not in text: + failures.append(f"the sample against an earlier run lacks {line!r} in {text!r}") + clean = SAMPLE.split("**`generate`, head against 2.4.5")[0] + clean = "\n".join(line for line in clean.splitlines() if not line.startswith("- ")).replace("1 failure(s), and 3 finding(s) reported and not failed", "0 failure(s)") + if not found or watch(clean, clean)[1] or "no earlier run given" not in watch(SAMPLE)[0]: + failures.append("a report with rows over a limit must be found so, one with none compared with itself must not, and one alone says no earlier run was given") + try: + watch("nothing measured\n") + failures.append("a report with no row in it was read as clean") + except ValueError: + pass + for failure in failures: + print(f"- {failure}") + print("self-test " + ("failed" if failures else "passed")) + return 1 if failures else 0 + + +def main(arguments): + options = {"--before": None, "--before-commit": None, "--commit": None, "--worse": "1.05", "--repository": "dfed/SafeDI"} + positional = [] + while arguments: + argument = arguments.pop(0) + if argument == "--self-test": + return self_test() + elif argument in options and arguments: + options[argument] = arguments.pop(0) + else: + positional.append(argument) + if (len(positional) == 1) == bool(options["--commit"]) or any(argument.startswith("--") for argument in positional): + print(__doc__, file=sys.stderr) + return 2 + try: + if options["--commit"]: + text, name = report_of_commit(options["--repository"], options["--commit"]) + else: + with open(positional[0], errors="replace") as handle: + text, name = handle.read(), positional[0] + before_text, before_name = None, "the earlier run" + if options["--before-commit"]: + before_text, before_name = report_of_commit(options["--repository"], options["--before-commit"]) + elif options["--before"]: + with open(options["--before"], errors="replace") as handle: + before_text, before_name = handle.read(), options["--before"] + output, found = watch(text, before_text, float(options["--worse"]), name, before_name) + except (OSError, ValueError, KeyError, zipfile.BadZipFile) as error: + print(f"perf-watch.py: {error}", file=sys.stderr) + return 2 + print(output) + return 1 if found else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:]))