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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion benchmarks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ python3 scripts/compare.py --validate-only # validation only
python3 scripts/compare.py --rounds 8 # validation and timing
python3 scripts/compare.py --suite site --rounds 8 # every site program
python3 scripts/compare.py --suite json --rounds 8 # API JSON and record transformations
python3 scripts/compare.py --validate-only --save-baseline DIR # preserve this build as a baseline
python3 scripts/compare.py --baseline DIR --rounds 12
python3 scripts/compare.py --cases '^json_transform/' --cases '^glue_orders/' --rounds 8 # chosen core cases
```
Expand All @@ -21,7 +22,11 @@ Every build is an offline release build with thin LTO and one codegen unit. Each

The JSON suite in `scripts/json_fixtures.py` covers roughly 1 KB, 16 KB, 256 KB and 1 MB API responses, typed packets and arrays of records, filtering/projecting records into JSON requests, and medium/large nested output. Its independently computed expectations participate in validation without adding cases to the recorded golden corpora. Summaries include time, allocation count and volume, logical steps, peak and retained tracked bytes, and per-case process RSS.

`--baseline DIR` adds the `rust-portable` and `rust-simd` timing and allocation binaries of an earlier revision, preserved in `DIR` with a `revision` file holding its full commit hash, for before-and-after comparisons. A run writes its environment, raw samples, allocations and `summary.json` to `benchmarks/results/<timestamp>`, or to `--out`.
Every build writes `benchmarks/bin/build.json` beside its binaries. It records the commit the build started from and any uncommitted changes to tracked files, the `rustc -vV` of the compiler Cargo runs (the one `RUSTC` names, else the one `CARGO_BUILD_RUSTC` names, else `rustc`), the build settings in the environment (`RUSTFLAGS`, `CARGO_ENCODED_RUSTFLAGS`, `CARGO_BUILD_RUSTFLAGS`, `CARGO_TARGET_<triple>_RUSTFLAGS` and `CARGO_PROFILE_*`), and each binary's SHA-256. A compiler or flags set in Cargo configuration files outside the repository are not seen. `--skip-build` reuses the binaries only when the record is there and every binary still has its recorded hash.

`--save-baseline DIR` preserves a build for later comparisons. After validation, it copies the `rust-portable` and `rust-simd` timing and allocation binaries into `DIR`, which must not exist yet, with a `build.json` that describes them. A baseline's revision must describe it, so the option refuses a build with uncommitted changes to tracked files. To preserve an earlier revision, check it out in its own worktree and run `scripts/compare.py --validate-only --save-baseline DIR` there.

`--baseline DIR` adds a saved baseline's binaries to validation and timing, for before-and-after comparisons. Before anything is built, it checks each baseline binary against its recorded hash, and checks that the baseline was built by the current build's compiler, with identical `rustc -vV` output, distribution included, and with the same build settings. A directory without a record, a replaced binary, or any compiler or setting difference stops the run, since a different toolchain or flag can move timings and accounting as much as the change being measured. With `--skip-build`, the current build's own record is the one compared. A run writes its environment, including both build records, raw samples, allocations and `summary.json` to `benchmarks/results/<timestamp>`, or to `--out`.

With a baseline, validation, including a `--validate-only` run, also pairs each fixture's record from a baseline build with the current build of the same flavor and compares the logical steps and the tracked peak and retained bytes each charged. Every difference is saved to `accounting-changes.jsonl`, one line per fixture and flavor with its `before` and `after` counters, and the file is empty when nothing changed. The run prints, for each flavor, how many records differ and how many rose or fell in each counter, then the first ten changed fixtures with their old and new values, giving the values once when both flavors changed alike. A difference does not fail the run, because accounting changes can be intended; the saved list is what makes them reviewable.

Expand Down
178 changes: 153 additions & 25 deletions scripts/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@
"""Build, validate, and measure runtime or parser workloads in portable and SIMD builds.

Validation checks every build against the golden corpora and the fixture
expectations. --baseline adds preserved builds of an earlier revision to
validation and timing, for before-and-after comparisons, and validation reports
each fixture whose accounting differs from the baseline build of its flavor.
expectations. Each build is recorded beside its binaries: the revision, the
compiler and build settings, and every binary's hash. --save-baseline preserves
a validated build with its record, and --baseline adds such a build of an
earlier revision to validation and timing, for before-and-after comparisons,
after checking that the same compiler and build settings made both builds.
Validation then reports each fixture whose accounting differs from the baseline
build of its flavor.
Paired timing reports the largest per-case median changes in each direction
for each flavor.
--cases times only the suite's cases whose names match, and the summary records
Expand Down Expand Up @@ -40,9 +44,20 @@
GOLDEN_CORPORA="conformance,language,rejections,compatibility"
# The counters a validation record charges for its call: logical steps and tracked memory.
ACCOUNTING=["steps","tracked_peak_bytes","tracked_retained_bytes"]
# Each binary build() makes: its name in BINS, the example it builds and the features it enables.
BUILDS=[("rust-portable","compare",[]),("rust-simd","compare",["simd"]),("rust-portable-alloc","compare",["allocation-stats"]),("rust-simd-alloc","compare",["simd","allocation-stats"]),("golden-portable","golden",[]),("golden-simd","golden",["simd"])]
# Each flavor's preserved baseline build and the current build it is paired with; a baseline
# directory names its builds as the current ones are named.
BASELINE_PAIRS={flavor:(f"rust-before-{flavor}",f"rust-{flavor}") for flavor in ["portable","simd"]}
# The binaries a baseline preserves: each flavor's timing and allocation builds.
PRESERVED=[f"{current}{suffix}" for _,current in BASELINE_PAIRS.values() for suffix in ["","-alloc"]]
# The record beside a directory of binaries that says what built them, and its fields; see build_identity.
BUILD_RECORD="build.json"
RECORD_FIELDS={"revision":str,"uncommitted_changes":str,"rustc":str,"build_settings":dict,"binary_sha256":dict}
FULL_REVISION=re.compile("[0-9a-f]{40}")
# The environment variables through which Cargo takes compiler flags and profile settings from outside
# the repository.
BUILD_SETTINGS=re.compile(r"RUSTFLAGS|CARGO_ENCODED_RUSTFLAGS|CARGO_BUILD_RUSTFLAGS|CARGO_TARGET_\w+_RUSTFLAGS|CARGO_PROFILE_\w+")
# Like golden.py's counter drift, an accounting report prints only its first few fixtures.
SHOWN_CHANGES=10
SHOWN_TIMING_CHANGES=5
Expand All @@ -57,20 +72,114 @@ def run(cmd,**kwargs):
return subprocess.run([str(x) for x in cmd],check=True,text=True,**kwargs)


def build(out):
def sha256(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()


def build_identity() -> dict:
"""Describes the build that build() makes here: the checked-out revision and any uncommitted changes
to tracked files, the `rustc -vV` of the compiler Cargo runs, and the build settings in the environment."""
def output(cmd):
return run(cmd,cwd=ROOT,capture_output=True).stdout
# Cargo runs the compiler RUSTC names, then the one CARGO_BUILD_RUSTC (build.rustc) names, then rustc.
rustc = next((os.environ[name] for name in ["RUSTC","CARGO_BUILD_RUSTC"] if name in os.environ), "rustc")
return {
"revision": output(["git","rev-parse","HEAD"]).strip(),
"uncommitted_changes": output(["git","status","--porcelain","--untracked-files=no"]),
"rustc": output([rustc,"-vV"]),
"build_settings": {name: value for name, value in sorted(os.environ.items()) if BUILD_SETTINGS.fullmatch(name)},
}


def build(out: Path, identity: dict) -> dict:
"""Builds every binary into BINS and records the build beside them; returns the record."""
BINS.mkdir(parents=True,exist_ok=True)
# An interrupted build must not leave an earlier record beside the binaries it replaced.
(BINS/BUILD_RECORD).unlink(missing_ok=True)
with (out/"build.log").open("w") as log:
for name,features in [("rust-portable",[]),("rust-simd",["simd"]),("rust-portable-alloc",["allocation-stats"]),("rust-simd-alloc",["simd","allocation-stats"])]:
cmd=[CARGO,"build","--offline","--release","--locked","--example","compare","--no-default-features"]
for name,example,features in BUILDS:
cmd=[CARGO,"build","--offline","--release","--locked","--example",example,"--no-default-features"]
if features: cmd += ["--features",",".join(features)]
run(cmd,cwd=ROOT,stdout=log,stderr=log)
shutil.copy2(ROOT/"target/release/examples/compare",BINS/name)
for name,features in [("golden-portable",[]),("golden-simd",["simd"])]:
cmd=[CARGO,"build","--offline","--release","--locked","--example","golden","--no-default-features"]
if features: cmd += ["--features",",".join(features)]
run(cmd,cwd=ROOT,stdout=log,stderr=log)
shutil.copy2(ROOT/"target/release/examples/golden",BINS/name)
shutil.copy2(ROOT/"target/release/examples"/example,BINS/name)
record = {**identity, "binary_sha256": {name: sha256(BINS/name) for name, _, _ in BUILDS}}
write_record(BINS, record)
print("Built portable and SIMD timing, allocation-instrumented and golden binaries",flush=True)
return record


def write_record(directory: Path, record: dict) -> None:
(directory/BUILD_RECORD).write_text(json.dumps(record, indent=2, sort_keys=True) + "\n")


def load_build(directory: Path, names: list[str]) -> dict:
"""Reads the build record in a directory of binaries and checks the named binaries against it.

Raises ValueError when the record is missing or malformed, or when a binary is missing or differs
from its recorded hash."""
path = directory/BUILD_RECORD
try:
record = json.loads(path.read_text())
except FileNotFoundError:
raise ValueError(f"{directory} has no {BUILD_RECORD} recording what built its binaries") from None
except json.JSONDecodeError as error:
raise ValueError(f"{path} is not JSON: {error}") from None
if not (isinstance(record, dict) and record.keys() == RECORD_FIELDS.keys()
and all(isinstance(record[field], kind) for field, kind in RECORD_FIELDS.items())):
raise ValueError(f"{path} is not a build record with the fields {', '.join(RECORD_FIELDS)}")
if not FULL_REVISION.fullmatch(record["revision"]):
raise ValueError(f"{path} does not give a full commit hash")
check_binaries(record, {name: directory/name for name in names}, path)
return record


def check_binaries(record: dict, paths: dict[str, Path], recorded_in: Path) -> None:
"""Checks that each named binary has the hash its build record gives it."""
for name, path in paths.items():
if name not in record["binary_sha256"]:
raise ValueError(f"{recorded_in} records no {name}")
try:
actual = sha256(path)
except FileNotFoundError:
raise ValueError(f"{path} is missing") from None
if actual != record["binary_sha256"][name]:
raise ValueError(f"{path} is not the {name} that {recorded_in} records; it was replaced after that build")


def check_pairing(baseline: dict, current: dict) -> None:
"""Checks that a baseline was built from its committed revision by the current build's compiler and
with its build settings, so that a comparison measures only the change in source.

Raises ValueError listing every difference."""
problems = []
if baseline["uncommitted_changes"]:
problems.append("the baseline was built with uncommitted changes, so its revision does not describe it")
old, new = baseline["rustc"].splitlines(), current["rustc"].splitlines()
if old != new:
problems.append("the baseline was built by a different compiler; rustc -vV gave"
+ "".join(f"\n baseline: {line}" for line in old if line not in new)
+ "".join(f"\n current: {line}" for line in new if line not in old))
for name in sorted(baseline["build_settings"].keys() | current["build_settings"].keys()):
old, new = baseline["build_settings"].get(name), current["build_settings"].get(name)
if old != new:
problems.append(f"{name} was {'unset' if old is None else repr(old)} for the baseline "
f"and is {'unset' if new is None else repr(new)} for the current build")
if problems:
raise ValueError("\n".join(problems))


def save_baseline(directory: Path, record: dict) -> None:
"""Preserves the current build's timing and allocation binaries in a new directory for --baseline,
with a build record listing only them."""
directory.mkdir(parents=True)
for name in PRESERVED:
shutil.copy2(BINS/name, directory/name)
saved = {**record, "binary_sha256": {name: record["binary_sha256"][name] for name in PRESERVED}}
# The copies must be the binaries that were validated, and the record comes last, so that an
# interrupted or failed save leaves no usable baseline.
check_binaries(saved, {name: directory/name for name in PRESERVED}, BINS/BUILD_RECORD)
write_record(directory, saved)
print(f"Saved the build of {record['revision']} as a baseline in {directory}", flush=True)


def executable(variant,out):
Expand Down Expand Up @@ -344,7 +453,8 @@ def cpu_name():
def main():
parser=argparse.ArgumentParser();parser.add_argument("--out",type=Path,default=ROOT/"benchmarks/results"/time.strftime("%Y-%m-%d-%H%M%S"));parser.add_argument("--skip-build",action="store_true");parser.add_argument("--validate-only",action="store_true");parser.add_argument("--rounds",type=int,default=8);parser.add_argument("--target-ms",type=float,default=75);parser.add_argument("--suite",choices=list(SUITES),default="core",help="core micro-benchmarks, site programs, API JSON, glue text, or parser workloads")
parser.add_argument("--cases",type=case_pattern,action="append",default=[],metavar="PATTERN",help="time only the suite's cases whose names match this regular expression anywhere; repeat to add cases. Validation still covers every case")
parser.add_argument("--baseline",type=Path,help="Directory containing prior rust-portable/rust-simd timing and allocation binaries, plus a revision file. Reports per-case accounting differences and the largest median timing changes from those builds")
parser.add_argument("--baseline",type=Path,metavar="DIR",help="a build of an earlier revision preserved by --save-baseline. Its timing and allocation binaries join validation and timing, which report per-case accounting differences and the largest median timing changes from them. The baseline must have been built by the current build's compiler with its build settings")
parser.add_argument("--save-baseline",type=Path,metavar="DIR",help="after validation, preserve the current build's timing and allocation binaries and its build record in DIR, a new directory, for --baseline. The build must have no uncommitted changes to tracked files")
args=parser.parse_args()
cases=selection=None
if args.validate_only:
Expand All @@ -355,30 +465,48 @@ def main():
except ValueError as error:
parser.error(f"--cases: {error}")
if selection["partial"]: print(f"Timing {coverage(selection)} chosen by --cases, a partial run: {', '.join(case['name'] for case in cases)}",flush=True)
out=args.out.resolve();out.mkdir(parents=True,exist_ok=False)
baseline_revision=None
# Without a build, the binaries' own record describes them; otherwise the build will.
if args.skip_build:
try:
current=load_build(BINS,[name for name,_,_ in BUILDS])
except ValueError as error:
parser.error(f"--skip-build: {error}; build without --skip-build")
else:
current=build_identity()
baseline=None
if args.baseline:
baseline=args.baseline.resolve()
baseline_revision=(baseline/"revision").read_text().strip()
if len(baseline_revision)!=40 or any(c not in "0123456789abcdef" for c in baseline_revision):
parser.error("baseline revision must contain a full commit hash")
baseline_dir=args.baseline.resolve()
try:
baseline=load_build(baseline_dir,PRESERVED)
check_pairing(baseline,current)
except ValueError as error:
parser.error(f"--baseline: {error}")
if args.save_baseline:
if current["uncommitted_changes"]:
parser.error("--save-baseline: the build has uncommitted changes to tracked files, so its revision would not describe the baseline; commit them first:\n"+current["uncommitted_changes"])
if args.save_baseline.exists():
parser.error(f"--save-baseline: {args.save_baseline} already exists")
if baseline:
BINS.mkdir(parents=True,exist_ok=True)
for before,current in BASELINE_PAIRS.values():
for before,name in BASELINE_PAIRS.values():
for suffix in ["","-alloc"]:
shutil.copy2(baseline/f"{current}{suffix}",BINS/f"{before}{suffix}")
shutil.copy2(baseline_dir/f"{name}{suffix}",BINS/f"{before}{suffix}")
VARIANTS.append(before)
if args.target_ms<=0 or (not args.validate_only and (args.rounds<len(VARIANTS) or args.rounds%len(VARIANTS))):
parser.error("use a positive target time and a round count that is a positive multiple of the variant count")
if not args.skip_build: build(out)
metadata={"platform":platform.platform(),"machine":platform.machine(),"cpu":cpu_name(),"rustc":run(["rustc","-Vv"],capture_output=True).stdout,"source_revision":run(["git","rev-parse","HEAD"],cwd=ROOT,capture_output=True).stdout.strip(),"dirty":run(["git","status","--porcelain"],cwd=ROOT,capture_output=True).stdout,"binary_sha256":{name:hashlib.sha256((BINS/name).read_bytes()).hexdigest() for name in VARIANTS},"RUSTFLAGS":os.environ.get("RUSTFLAGS",""),"target_ms":args.target_ms,"command":sys.argv}
metadata["baseline_source_revision"]=baseline_revision
out=args.out.resolve();out.mkdir(parents=True,exist_ok=False)
if not args.skip_build: current=build(out,current)
baseline_revision=baseline["revision"] if baseline else None
metadata={"platform":platform.platform(),"machine":platform.machine(),"cpu":cpu_name(),"build":current,"source_revision":run(["git","rev-parse","HEAD"],cwd=ROOT,capture_output=True).stdout.strip(),"dirty":run(["git","status","--porcelain"],cwd=ROOT,capture_output=True).stdout,"binary_sha256":{name:sha256(BINS/name) for name in VARIANTS},"target_ms":args.target_ms,"command":sys.argv}
metadata["baseline_build"]=baseline
metadata["execution_path"]=str(out/"compare-runner")
if sys.platform.startswith("linux"):
metadata["personality"]=Path("/proc/self/personality").read_text().strip()
metadata["cpu_affinity"]=sorted(os.sched_getaffinity(0))
metadata["allocation_binary_sha256"]={name+"-alloc":hashlib.sha256((BINS/(name+"-alloc")).read_bytes()).hexdigest() for name in VARIANTS}
metadata["allocation_binary_sha256"]={name+"-alloc":sha256(BINS/(name+"-alloc")) for name in VARIANTS}
(out/"environment.json").write_text(json.dumps(metadata,indent=2)+"\n")
expected=validate(out,baseline_revision)
if args.save_baseline: save_baseline(args.save_baseline.resolve(),current)
if not args.validate_only: measure(out,args.rounds,args.target_ms,expected,cases,selection,baseline_revision=baseline_revision)


Expand Down
Loading
Loading