diff --git a/benchmarks/interleave.py b/benchmarks/interleave.py index a28b95e5ac7bb..c3189d0885aae 100755 --- a/benchmarks/interleave.py +++ b/benchmarks/interleave.py @@ -5,9 +5,10 @@ """Run a baseline and a branch benchmark with interleaved iterations. -Both commands are `dfbench` invocations that accept `--lockstep-in` and -`--lockstep-out`. This script starts both processes, then for each query it -alternates single iterations between them, in ABBA order: +Both commands are `dfbench` invocations that accept `--lockstep-in`, +`--lockstep-out` and `--query`. For each query in `--queries`, this script +starts a fresh baseline and branch process with `--query `, and alternates +single iterations between them, in ABBA order: pair 0: A B pair 1: B A pair 2: A B ... @@ -33,12 +34,15 @@ If a query fails on one side, the script ends that query on both sides and moves on, like a sequential run does. -Each process writes its own results file (pass `-o` in each command), so +A fresh process pair per query keeps the results of one query independent of +the queries that ran before it (allocator state, caches, heap layout). Each +process writes its results to a temporary file. When all queries are done, the +script merges the files of each side into the `-o` file of that command, so `compare.py` reads the output as usual. Example: - ./interleave.py --iterations 3 --max-time 30 \\ + ./interleave.py --iterations 3 --max-time 30 --queries 1-5,7 \\ --baseline "../base/target/release/dfbench sort-pushdown ... -o base.json" \\ --branch "../target/release/dfbench sort-pushdown ... -o branch.json" """ @@ -46,6 +50,7 @@ import argparse import contextlib import errno +import json import math import os import shlex @@ -83,13 +88,13 @@ def median_ci_rel_half_width(samples): class Side: - def __init__(self, name, command, workdir): + def __init__(self, name, argv, workdir): self.name = name to_proc = os.path.join(workdir, f"{name}.in") from_proc = os.path.join(workdir, f"{name}.out") os.mkfifo(to_proc) os.mkfifo(from_proc) - argv = shlex.split(command) + [ + argv = argv + [ "--lockstep-in", to_proc, "--lockstep-out", @@ -238,39 +243,119 @@ def main(): help="stop when the ratio CI is within this fraction") parser.add_argument("--max-iterations", type=int, default=1000, help="maximum iterations per side (default: 1000)") + parser.add_argument("--queries", required=True, + help="query ids to run, each in a fresh process " + "pair, such as 0-42 or 1,3,5-7") args = parser.parse_args() if args.iterations < 1: parser.error("--iterations must be at least 1") + sides = { + "baseline": split_output(parser, "--baseline", args.baseline), + "branch": split_output(parser, "--branch", args.branch), + } + queries = parse_queries(parser, args.queries) + results = {name: [] for name in sides} with tempfile.TemporaryDirectory() as workdir: - a = Side("baseline", args.baseline, workdir) - b = Side("branch", args.branch, workdir) - try: - a.open() - b.open() - query = 0 - while True: - states = {side.name: side.start_query() for side in (a, b)} - if states[a.name] is None and states[b.name] is None: - break - if None in states.values(): - raise RuntimeError( - "the two commands ran a different number of queries" - ) - query += 1 - run_query(args, a, b, query, states) - except BaseException: - for side in (a, b): - side.proc.kill() - raise - finally: - for side in (a, b): - if side.writer: - with contextlib.suppress(BrokenPipeError): - side.writer.close() - codes = [a.proc.wait(), b.proc.wait()] + for query in queries: + query_dir = os.path.join(workdir, f"q{query}") + os.mkdir(query_dir) + paths = {} + argvs = {} + for name, (argv, _) in sides.items(): + paths[name] = os.path.join(query_dir, f"{name}.json") + argvs[name] = argv + ["--query", query, "-o", paths[name]] + run_pair(args, argvs, query, query_dir) + for name, path in paths.items(): + with open(path) as f: + results[name].append(json.load(f)) + for name, (_, output) in sides.items(): + write_merged(results[name], output) + + +def run_pair(args, argvs, query, workdir): + """Runs one query in a fresh baseline and branch process.""" + a = Side("baseline", argvs["baseline"], workdir) + b = Side("branch", argvs["branch"], workdir) + try: + a.open() + b.open() + states = {side.name: side.start_query() for side in (a, b)} + if None in states.values(): + raise RuntimeError(f"query {query}: a command ran no query") + run_query(args, a, b, query, states) + states = {side.name: side.start_query() for side in (a, b)} + if states != {a.name: None, b.name: None}: + raise RuntimeError(f"query {query}: a command ran more than one query") + except BaseException: + for side in (a, b): + side.proc.kill() + raise + finally: + for side in (a, b): + if side.writer: + with contextlib.suppress(BrokenPipeError): + side.writer.close() + codes = [a.proc.wait(), b.proc.wait()] if any(codes): - sys.exit(f"benchmark exit codes: baseline={codes[0]} branch={codes[1]}") + sys.exit( + f"query {query}: benchmark exit codes: " + f"baseline={codes[0]} branch={codes[1]}" + ) + + +def split_output(parser, flag, command): + """Splits `command` into its arguments without `-o`, and the `-o` path.""" + argv = shlex.split(command) + rest = [] + output = None + i = 0 + while i < len(argv): + arg = argv[i] + if arg in ("-o", "--output") and i + 1 < len(argv): + output = argv[i + 1] + i += 2 + continue + if arg.startswith("--output="): + output = arg.split("=", 1)[1] + elif arg in ("--query", "-q") or arg.startswith("--query="): + parser.error(f"{flag}: pass the queries with --queries, not --query") + else: + rest.append(arg) + i += 1 + if output is None: + parser.error(f"{flag}: the command needs -o ") + return rest, output + + +def parse_queries(parser, text): + """Parses `1-3,7` into `["1", "2", "3", "7"]`.""" + queries = [] + for part in text.split(","): + lo, sep, hi = part.strip().partition("-") + try: + if sep: + queries.extend(str(q) for q in range(int(lo), int(hi) + 1)) + else: + queries.append(str(int(lo))) + except ValueError: + parser.error(f"--queries: invalid query list {text!r}") + if not queries: + parser.error("--queries: no queries") + return queries + + +def write_merged(runs, output): + """Writes one `BenchmarkRun` JSON file with the queries of all `runs`. + + The context (versions, options, start time) comes from the first run. + """ + merged = { + "context": runs[0]["context"], + "queries": [q for run in runs for q in run["queries"]], + } + with open(output, "w") as f: + json.dump(merged, f, indent=2) if __name__ == "__main__":