diff --git a/.claude/rules/ci.md b/.claude/rules/ci.md index a9684a0c4c..6f893af2f3 100644 --- a/.claude/rules/ci.md +++ b/.claude/rules/ci.md @@ -15,7 +15,7 @@ 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. -- **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. +- **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. The job also counts the instructions the tool executes generating each growth row at its two sizes, with callgrind (`--growth-instructions`): a count is the same on every run to within a thousandth, so it shows work that grows and writes nothing more where the row's wall time shows noise. A row over its "instructions" limit (else its "time" limit) is reported with the others, and a row that could not be counted fails. 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. diff --git a/.claude/rules/scripts.md b/.claude/rules/scripts.md index acb7b0189c..5c711b5e52 100644 --- a/.claude/rules/scripts.md +++ b/.claude/rules/scripts.md @@ -18,7 +18,7 @@ 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. 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/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`). `--growth-instructions HEAD_TOOL DIRECTORY` counts the instructions the tool executes generating each growth row at its two sizes (callgrind) against the row's limit. - `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. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ae66d58d15..81ed2764cb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -3592,6 +3592,33 @@ jobs: with: path: .generate-time/cached key: generate-time-tool-${{ runner.os }}-swift-6.2-${{ steps.commits.outputs.head }} + # The instructions the change's tool executes generating each growth + # row at its two sizes, counted by callgrind, against the row's limit + # (`--growth-instructions`): work that grows faster than the graph and + # writes nothing more moves no other measure but wall time, and one + # tool's count on one graph is the same on every run to within a + # thousandth (a row counted twice gave 291,455,905 and 291,258,972), + # where a row's wall time moves by a tenth and more. A row over its + # limit is reported with the other measures (`--report-measures`) and + # joins the pull request's timing comment; a row whose instructions + # could not be counted fails. Every row at both sizes was 330 billion + # instructions for the tool of 33773fa, which took 15 minutes four + # runs at a time on a four-core Linux machine. valgrind is installed + # here, since the image has none and no other step uses it. + - name: Install valgrind + if: ${{ !cancelled() && hashFiles('.generate-time/head/SafeDITool') != '' }} + uses: ./.github/actions/retry + with: + command: command -v valgrind >/dev/null || { apt-get update && apt-get install -y --no-install-recommends valgrind; } + - name: Count the Growth Rows' Instructions + if: ${{ !cancelled() && hashFiles('.generate-time/head/SafeDITool') != '' }} + run: | + mkdir -p "$RUNNER_TEMP/timing-comment" + status=0 + python3 -I Scripts/generate-time-check.py --growth-instructions --report-measures --summary "$RUNNER_TEMP/timing-comment/3-growth-instructions.md" \ + .generate-time/head/SafeDITool "$RUNNER_TEMP/growth-instructions" || status=$? + cat "$RUNNER_TEMP/timing-comment/3-growth-instructions.md" >> "$GITHUB_STEP_SUMMARY" || true + exit "$status" # 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 diff --git a/Scripts/generate-time-check.py b/Scripts/generate-time-check.py index 9e0846fde5..e244ca6cb0 100644 --- a/Scripts/generate-time-check.py +++ b/Scripts/generate-time-check.py @@ -6,6 +6,9 @@ [--report-only] [--base-name NAME] BASE_TOOL HEAD_TOOL DIRECTORY + generate-time-check.py --growth-instructions [--growth NAME,…] [--growth-limit RATIO] [--summary FILE] + [--report-measures] + HEAD_TOOL DIRECTORY generate-time-check.py --self-test DIRECTORY Compares how long two builds of `SafeDITool` take to `generate` synthetic dependency graphs, and exits 1 when @@ -24,7 +27,12 @@ and none fails: 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, which found no defect a reader of the figures would not. A shape or a row the head tool cannot generate, or does not finish, fails under each of the -three. With +three. `--growth-instructions` counts the instructions HEAD_TOOL executes generating each growth row at its two +numbers of layers (callgrind, so `valgrind` and a C compiler must be installed), and finds a row over its limit when +the larger graph took the row's "instructions" limit times the smaller's, else its "time" limit, else +`--growth-limit`: one tool's count on one graph is the same on every run to within a thousandth, so a row's count shows +work that grows and writes nothing more where its wall time shows noise. Such a row exits 1, or is reported under +`--report-measures`; a row whose instructions could not be counted always exits 1. With `--report-only` no finding fails, which is how CI compares the change's tool with the newest release's (`--base-name` names that base in the report's first line). CI posts the reports as one comment on the pull request. @@ -389,6 +397,7 @@ import sys import threading import time +from concurrent.futures import ThreadPoolExecutor NOISE_FLOOR_SECONDS = 0.1 MEMORY_NOISE_FLOOR_BYTES = 8 * 1024 * 1024 @@ -1476,7 +1485,9 @@ def shape_many_roots(roots, types): # within the default limits (1.84 times the code from three members to five), so the growth is the seam's places: # where a builder call closes depends on the set of members above it. # The roadmap's row 4 (seams: one stored graph per seam, a passed-up place a reference) removes these limits. - "TA-all-to-all-tangle": (lambda members: shape_all_to_all_tangle(members), 4, {"time": 27.0, "memory": 4.7, "size": 47.0, "code": 83.0}), + # Instructions: 27.25 times from four members to six where the wall time's limit is 27, and 28.18 with release + # 2.4.5's tool, so the row has a limit of its own for them, the maintainer's, just above the release's. + "TA-all-to-all-tangle": (lambda members: shape_all_to_all_tangle(members), 4, {"time": 27.0, "memory": 4.7, "size": 47.0, "code": 83.0, "instructions": 28.5}), # LS's screens are each built beneath every screen below them, so today's tree of its root grows with every path to # each screen (L8 took 15.0 s and 614 MB with 2.4.2); the root is laid out from one function per screen instead. "LS-layered-screens-opening-screen-above": (lambda layers: shape_screens_opening_screen_above(layers, width=4), 6, {}), @@ -1909,6 +1920,134 @@ def grow(head_tool, directory, growth_rows, runs, limit, time_limit=GROWTH_TIME_ return rows, failures +# MARK: Counting instructions + + +INSTRUCTIONS_NOISE_FLOOR = 10_000_000 +# A run under callgrind takes some fifty times as long as the run it counts. +INSTRUCTIONS_TIME_LIMIT_SECONDS = 3600 +# libdispatch waits in `sigsuspend`, which stops valgrind; a tool that loads this before libc sleeps there instead. Its +# process then never ends by itself, which is why `COUNTER` stops it once callgrind has written its totals. +SHIM = """#include +#include +int sigsuspend(const sigset_t *mask) { for (;;) sleep(100000); return -1; } +""" +# A stand-in for the tool that `generate` runs: `scan` goes to the tool as it is, since no row times it, and every +# other command runs under `command` (callgrind), which writes one file a run into `directory`. +COUNTER = """#!/usr/bin/env python3 +import os, subprocess, sys, tempfile, time +tool, command, directory, shim = {tool!r}, {command!r}, {directory!r}, {shim!r} +arguments = sys.argv[1:] +if arguments and arguments[0] == "scan": + os.execv(tool, [tool] + arguments) +os.makedirs(directory, exist_ok=True) +descriptor, counts = tempfile.mkstemp(prefix="counts.", suffix=".out", dir=directory) +os.close(descriptor) +environment = dict(os.environ, LD_PRELOAD=shim) if shim else dict(os.environ) +with open(counts + ".log", "wb") as log: + process = subprocess.Popen(command + ["--callgrind-out-file=" + counts, tool] + arguments, stdout=log, stderr=subprocess.STDOUT, env=environment) +def counted(): + with open(counts, "rb") as handle: + handle.seek(max(0, os.path.getsize(counts) - 65536)) + return any(line.startswith(b"totals:") for line in handle.read().splitlines()) +while process.poll() is None and not counted(): + time.sleep(0.5) +process.kill() +process.wait() +if not counted(): + with open(counts + ".log", errors="replace") as log: + sys.exit("no instruction count was written: " + log.read().strip()[-1500:]) +""" + + +def build_shim(directory): + """Compiles `SHIM` into `directory` and returns the library's path.""" + write(f"{directory}/sigsuspend-shim.c", SHIM) + library = f"{directory}/sigsuspend-shim.so" + for compiler in ("cc", "clang", "gcc"): + try: + if subprocess.run([compiler, "-shared", "-fPIC", "-o", library, f"{directory}/sigsuspend-shim.c"], capture_output=True).returncode == 0: + return library + except OSError: + continue + raise Failure("no C compiler (cc, clang or gcc) built the shim that lets valgrind run the tool") + + +def count_instructions(head_tool, directory, growth_rows, limit, command=("valgrind", "--tool=callgrind"), shim=None, jobs=None): + """Returns (the instruction table's rows, the failures): the instructions `head_tool` executes generating each of + `growth_rows` at its two numbers of layers, counted by callgrind, which gives one tool on one graph the same count + on every run to within a thousandth, where its wall time moves by a tenth and more. A row's limit is its + "instructions" limit, else its "time" limit, else `limit`. The runs are independent and counts do not depend on + what else the machine does, so `jobs` of them (default one a core) run at once.""" + def count(name, depth): + build, _, _, timed_module = row_parts(growth_rows[name]) + modules = build(depth) + place = f"{directory}/instructions-{name}/{depth}" + for module, _, source in modules: + write(f"{place}/sources/{module}/Types.swift", source) + counter = f"{place}/counter" + write(counter, COUNTER.format(tool=head_tool, command=list(command), directory=f"{place}/counts", shim=shim)) + os.chmod(counter, 0o755) + generate(counter, modules, f"{place}/sources", f"{place}/output", time_limit=INSTRUCTIONS_TIME_LIMIT_SECONDS, under_plugin=timed_module(depth) if timed_module else None) + total = 0 + for file in sorted(os.listdir(f"{place}/counts")): + if file.endswith(".out"): + with open(f"{place}/counts/{file}", "rb") as handle: + total += sum(int(line.split()[1]) for line in handle.read().splitlines() if line.startswith(b"totals:")) + return total + + def counted(name, depth): + try: + return count(name, depth) + except Failure as failure: + return failure + + pairs = [(name, depth) for name, row in growth_rows.items() for depth in row_parts(row)[1]] + with ThreadPoolExecutor(max_workers=jobs or os.cpu_count() or 1) as pool: + counts = dict(zip(pairs, pool.map(lambda pair: counted(*pair), pairs))) + rows = [] + failures = [] + for name, row in growth_rows.items(): + _, depths, row_limits, _ = row_parts(row) + smaller, larger = counts[(name, depths[0])], counts[(name, depths[1])] + refused = [(depth, count) for depth, count in zip(depths, (smaller, larger)) if isinstance(count, Failure)] + if refused: + rows.append(f"| {name} | {depths[0]} and {depths[1]} | not counted | | | **failed** |") + failures.append(f"{name}: the head tool's instructions were not counted at {refused[0][0]} layers: {refused[0][1]}") + continue + ratio = larger / smaller if smaller else float("inf") if larger else 1.0 + row_limit = row_limits.get("instructions", row_limits.get("time", limit)) + over = ratio >= row_limit and larger - smaller > INSTRUCTIONS_NOISE_FLOOR + if over: + failures.append(Measure(f"{name}: at {depths[1]} layers `generate` executed {ratio:.3f} times the instructions it executed at {depths[0]} layers ({larger} against {smaller}); the limit is {row_limit:g}, and the graph has {depths[1] / depths[0]:.2f} times the layers")) + rows.append(f"| {name} | {depths[0]} and {depths[1]} | {smaller} | {larger} | {ratio:.3f} (limit {row_limit:g}) | {'**over the limit**' if over else 'within the limit'} |") + print(f"{name}: at {depths[0]} and {depths[1]} layers, instructions {smaller}, {larger}, {ratio:.3f}", flush=True) + return rows, failures + + +def report_instructions(rows, failures, summary, reported=lambda failure: False): + """Prints the instruction table and its findings, appends them to `summary`, and returns the findings that fail: + those `reported` is false of. The others are listed apart, as `report` lists them.""" + listed = [failure for failure in failures if reported(failure)] + failing = [failure for failure in failures if not reported(failure)] + lines = [f"**`generate` growth by instructions, head tool: {len(failing)} failure(s){f', {len(listed)} row(s) over the limit reported' if listed else ''}.**", ""] + [f"- {failure}" for failure in failing] + if listed: + lines += ["", "Over the limit, reported and not failed:", ""] + [f"- {failure}" for failure in listed] + lines += ["", "
Every row", "", "The instructions the head tool executes generating each growth row at its two numbers of layers, counted by callgrind: the same on every run to within a thousandth, where a row's wall time moves by a tenth and more.", "", + "| Row | Layers | Instructions: fewer layers | More layers | Ratio | Verdict |", "|---|---|---|---|---|---|"] + rows + ["", "
"] + text = "\n".join(lines) + "\n" + print(text) + if summary: + with open(summary, "a") as handle: + handle.write(text) + 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 + + 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.""" @@ -1975,6 +2114,24 @@ def report(rows, size_rows, failures, runs, limit, memory_limit, size_limit, sum """ +# A stand-in for `valgrind --tool=callgrind`: runs the command after its own options, then writes a total. +STAND_IN_COUNTER = """#!/usr/bin/env python3 +import subprocess, sys, time +arguments = sys.argv[1:] +counts = [argument for argument in arguments if argument.startswith("--callgrind-out-file=")][0].split("=", 1)[1] +refuses = "--refuse" in arguments +command = [argument for argument in arguments if not argument.startswith("--callgrind-out-file=") and argument != "--refuse"] +if refuses or subprocess.run(command).returncode != 0: + sys.exit("stand-in counter: the tool failed") +under_plugin = "--swift-manifest" in command +types = sum(open(path).read().count("final class ") for path in open(command[1 if under_plugin else 2]).read().replace(",", " ").split()) +if {writes!r}: + open(counts, "w").write("events: Ir\\ntotals: " + str(1000000 * types ** {power!r}) + "\\n") +if {hangs!r}: + time.sleep(600) +""" + + def self_test(directory): failures = [] @@ -2127,9 +2284,45 @@ def expect_growth_under_plugin(name, head, expected_failures, expected_row, time 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}") + # Instructions, counted by a stand-in for callgrind that runs the tool, writes the number of types its input + # declares to a power as its total, and then, as the tool under the shim does, never ends: the count is read and + # the stand-in stopped. A count that grows with the types passes, with their cube fails at the default limit and + # passes a row's own, a row's "time" limit stands in for one, and a counter that writes no total fails the row. + def counter(name, power, hangs=True, writes=True): + path = f"{directory}/tools/{name}" + write(path, STAND_IN_COUNTER.format(power=power, hangs=hangs, writes=writes)) + os.chmod(path, 0o755) + return [path] + + def expect_instructions(name, command, expected_failures, expected_row, row_limits={}, under_plugin=False): + row = (shape_p, (4, 7), row_limits, lambda layers: "App") if under_plugin else (shape_p, 4, row_limits) + rows, found = count_instructions(fast, f"{directory}/{name}", {"P": row}, 2.0, command=command, jobs=2) + if len(found) != expected_failures or expected_row not in rows[0]: + failures.append(f"{name}: expected {expected_failures} failure(s) and a row with {expected_row!r}, got {found} and {rows}") + + linear, cubic = counter("counts-the-types", 1), counter("counts-their-cube", 3) + expect_instructions("instructions-with-the-types", linear, 0, "within the limit") + expect_instructions("instructions-with-their-cube", cubic, 1, "**over the limit**") + expect_instructions("instructions-within-the-rows-limit", cubic, 0, "(limit 9)", row_limits={"instructions": 9.0, "time": 2.0}) + expect_instructions("instructions-within-the-rows-time-limit", cubic, 0, "(limit 9)", row_limits={"time": 9.0}) + expect_instructions("instructions-over-the-rows-limit", cubic, 1, "**over the limit**", row_limits={"instructions": 3.0, "time": 9.0}) + expect_instructions("instructions-of-a-counter-that-ends", counter("counts-and-ends", 3, hangs=False), 1, "**over the limit**") + expect_instructions("instructions-not-counted", counter("counts-nothing", 1, hangs=False, writes=False), 1, "| not counted | | | **failed** |") + expect_instructions("instructions-of-a-tool-that-refuses", linear + ["--refuse"], 1, "| not counted | | | **failed** |") + expect_instructions("instructions-under-the-plugin", cubic, 1, "| P | 4 and 7 |", under_plugin=True) + # A row over its limit is a measure, which `--report-measures` lists apart and does not fail; a row that was not + # counted is no measure and fails either way. + for name, command, expected_measures in (("instruction-measure", cubic, 1), ("instruction-refusal", linear + ["--refuse"], 0)): + rows, found = count_instructions(fast, f"{directory}/{name}", {"P": (shape_p, 4, {})}, 2.0, command=command, jobs=2) + write(f"{directory}/{name}.md", "") + failing = report_instructions(rows, found, f"{directory}/{name}.md", reported=lambda failure: isinstance(failure, Measure)) + with open(f"{directory}/{name}.md") as handle: + text = handle.read() + if sum(isinstance(finding, Measure) for finding in found) != expected_measures or len(failing) != 1 - expected_measures or ("reported and not failed" in text) != bool(expected_measures): + failures.append(f"report {name}: of {found} it failed {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"}: + if not set(row_limits) <= {"time", "memory", "size", "code", "instructions"}: failures.append(f"growth row {row} limits {sorted(row_limits)}, which are not all measures") for module, dependencies, _ in build(fewer): if not all(dependency in [earlier for earlier, _, _ in build(fewer)] for dependency in dependencies): @@ -2217,6 +2410,7 @@ def main(arguments): report_growth_time = False report_measures = False report_only = False + growth_instructions = False base_name = "base" positional = [] self_testing = False @@ -2234,6 +2428,8 @@ def main(arguments): report_measures = True elif argument == "--report-only": report_only = True + elif argument == "--growth-instructions": + growth_instructions = 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": @@ -2264,7 +2460,7 @@ def main(arguments): positional.append(argument) unknown = [shape for shape in shapes if shape not in SHAPES] unknown_growth = [row for row in growth if row not in GROWTH_ROWS] - if len(positional) != (1 if self_testing else 3) or unknown or unknown_growth or runs < 1 or growth_runs < 1: + if len(positional) != (1 if self_testing else 2 if growth_instructions else 3) or unknown or unknown_growth or runs < 1 or growth_runs < 1: print(__doc__.split("\n\n")[0] + (f"\nunknown shape(s): {', '.join(unknown)}; the shapes are {', '.join(SHAPES)}" if unknown else "") + (f"\nunknown growth row(s): {', '.join(unknown_growth)}; the rows are {', '.join(GROWTH_ROWS)}" if unknown_growth else ""), file=sys.stderr) return 2 directory = os.path.abspath(positional[-1]) @@ -2273,6 +2469,14 @@ def main(arguments): return 2 if self_testing: return self_test(directory) + elif growth_instructions: + try: + shim = build_shim(directory) + except Failure as failure: + print(failure, file=sys.stderr) + return 2 + instruction_rows, failures = count_instructions(os.path.abspath(positional[0]), directory, {row: GROWTH_ROWS[row] for row in growth}, growth_limit, shim=shim) + return 1 if report_instructions(instruction_rows, failures, summary, reported=lambda failure: report_measures and isinstance(failure, Measure)) else 0 else: # A head tool that is the base tool, byte for byte or by its sources (`--same-sources`, which the caller passes # when no file the tool is built from differs between the two commits), has nothing to compare with the base: diff --git a/Scripts/perf-watch.py b/Scripts/perf-watch.py index 1e477e4120..e17f372ae3 100644 --- a/Scripts/perf-watch.py +++ b/Scripts/perf-watch.py @@ -6,7 +6,9 @@ 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. +ratio moved since and every other row whose ratio rose to RATIO (default 1.05) times the earlier one or more. A +growth row's instruction count (the report `--growth-instructions` writes, in the same artifact) is read as one more +measure of the row. 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. @@ -32,6 +34,7 @@ ("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"), + ("times the instructions it executed at", "growth: instructions"), ) GROWTH_MEASURES = ("growth: wall time", "growth: peak memory", "growth: `.safedi` size", "growth: generated code") @@ -53,13 +56,19 @@ def read_report(text): table = None reports = 0 reported = False + instructions = False for line in text.splitlines(): if line.startswith("**`generate`, head against "): reports += 1 reported = False - if reports != 1: + instructions = False + elif line.startswith("**`generate` growth by instructions"): + # The head tool's instruction counts, a report of their own after the comparisons: read wherever it is. + instructions = True + reported = False + if reports != 1 and not instructions: continue - if line.startswith("Reported and not failed:"): + if line.startswith(("Reported and not failed:", "Over the limit, reported and not failed:")): reported = True elif line.startswith("- "): sentence = line[2:] @@ -75,6 +84,8 @@ def read_report(text): table = "shapes" elif line.startswith("| Shape | Module |"): table = "sizes" + elif line.startswith("| Row | Layers | Instructions"): + table = "instructions" elif line.startswith("| Row | Layers |"): table = "growth" elif not line.startswith("|"): @@ -89,6 +100,8 @@ def read_report(text): 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 == "instructions" and len(cells) >= 5: + ratios[(cells[0], "growth: instructions")] = 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) @@ -145,7 +158,8 @@ def gh(*arguments, binary=False): def report_of_commit(repository, commit): - """The first Markdown file of the artifact of the newest run of `commit` that has one.""" + """The Markdown files, in name order, of the artifact of the newest run of `commit` that has one: the comparison + with the base first, and after it the head tool's instruction counts where the run counted them.""" 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"] @@ -154,7 +168,7 @@ def report_of_commit(repository, commit): 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']})" + return "\n".join(archive.read(name).decode(errors="replace") for name in names), 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?") @@ -190,6 +204,20 @@ def report_of_commit(repository, commit): 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 + +**`generate` growth by instructions, head tool: 0 failure(s), 1 row(s) over the limit reported.** + +Over the limit, reported and not failed: + +- K: at 6 layers `generate` executed 7.250 times the instructions it executed at 4 layers (7250000000 against 1000000000); the limit is 6.5, and the graph has 1.50 times the layers + +
Every row + +| Row | Layers | Instructions: fewer layers | More layers | Ratio | Verdict | +|---|---|---|---|---|---| +| K | 4 and 6 | 1000000000 | 7250000000 | 7.250 (limit 6.5) | **over the limit** | + +
""" @@ -197,15 +225,15 @@ 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} + ("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, ("K", "growth: instructions"): 7.25} 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)]: + 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), ("K", "growth: instructions", 7.25, 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 |", + for line in ("4 row(s) over a limit, of 11 measured.", "| K | growth: instructions | 7.25 | 6.5 | 7.25 in the earlier run, +0.00 | no, reported |", "| 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}")