diff --git a/scripts/use_cases/run_use_case_on_systems.py b/scripts/use_cases/run_use_case_on_systems.py index 682d284d..aa6dfb87 100644 --- a/scripts/use_cases/run_use_case_on_systems.py +++ b/scripts/use_cases/run_use_case_on_systems.py @@ -11,6 +11,7 @@ import statistics import subprocess import sys +import threading import time import urllib.error import urllib.parse @@ -525,7 +526,7 @@ def describe_backend_plan(plan, promql): return f"{'; '.join(names) or 'exact'} ({views} materialized views)" -def control_plane(binary, spec, queries, arm, workdir, name, calls=None): +def control_plane(binary, spec, queries, arm, workdir, name, calls=None, timeout=None): max_error = in_process.max_error_of(arm) path = os.path.join(workdir, f"{name}-workload.json") with open(path, "w") as f: @@ -539,26 +540,35 @@ def control_plane(binary, spec, queries, arm, workdir, name, calls=None): cmd.append("--ignore-accuracy-guarantees") log = os.path.join(workdir, f"{name}-control-plane.log") started = time.monotonic() + timed_out = [] with open(log, "w") as stderr: proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=stderr) + timer = None + if timeout is not None: + timer = threading.Timer(timeout, lambda: (timed_out.append(True), proc.kill())) + timer.start() _, status, usage = os.wait4(proc.pid, 0) + if timer is not None: + timer.cancel() with open(log) as f: lines = f.read().strip().splitlines() os.remove(log) - failed = os.waitstatus_to_exitcode(status) != 0 + failed = bool(timed_out) or os.waitstatus_to_exitcode(status) != 0 if calls is not None: - calls.append({"name": name, "queries": len(queries), "planned": not failed, + calls.append({"name": name, "queries": len(queries), "planned": not failed, "timed out": bool(timed_out), "seconds": time.monotonic() - started, "peak resident bytes": usage.ru_maxrss * (1 if sys.platform == "darwin" else 1024), "plan bytes": None if failed else os.path.getsize(out)}) + if timed_out: + return None, f"planning did not finish in {timeout:g} s" if failed: return None, (lines or ["control plane failed"])[-1] with open(out) as f: return out, json.load(f) -def plan_groups(binary, spec, arm, workdir, calls=None): - planned, plan = control_plane(binary, spec, spec["queries"], arm, workdir, arm, calls=calls) +def plan_groups(binary, spec, arm, workdir, calls=None, timeout=None): + planned, plan = control_plane(binary, spec, spec["queries"], arm, workdir, arm, calls=calls, timeout=timeout) if planned: return [(planned, plan, list(spec["queries"]))], {} groups, unsupported = [], {} @@ -568,7 +578,17 @@ def plan_groups(binary, spec, arm, workdir, calls=None): groups.append((path, result, [q])) else: unsupported[q["id"]] = result - if groups: + if 1 < len(groups) < len(spec["queries"]): + supported = [q for _, _, members in groups for q in members] + planned, plan = control_plane(binary, spec, supported, arm, workdir, f"{arm}-supported", calls=calls, + timeout=timeout) + if planned: + print(f"{arm}: {len(supported)} of {len(spec['queries'])} queries plan; they plan together, one " + "instance", file=sys.stderr) + return [(planned, plan, supported)], unsupported + print(f"{arm}: the {len(supported)} queries that plan alone do not plan together ({plan})", + file=sys.stderr) + if len(groups) > 1: print(f"{arm}: the queries do not plan together; {len(groups)} plan alone, one instance each", file=sys.stderr) return groups, unsupported @@ -958,7 +978,8 @@ def largest(key): def planner_summary(calls): if not calls: return {} - return {"planner calls": len(calls), "planner seconds": sum(c["seconds"] for c in calls), + return {"planner calls": len(calls), "planner timeouts": sum(1 for c in calls if c.get("timed out")), + "planner seconds": sum(c["seconds"] for c in calls), "planner peak resident bytes": max(c["peak resident bytes"] for c in calls), "largest plan bytes": max((c["plan bytes"] or 0) for c in calls)} @@ -966,7 +987,7 @@ def planner_summary(calls): def run_planned(args, system, spec_path, spec, arm, workdir, exact_path): calls = [] groups, unsupported = plan_groups(os.path.join(args.backend_dir, "control_plane"), spec, arm, workdir, - calls=calls) + calls=calls, timeout=args.joint_plan_timeout) planner = planner_summary(calls) ran, installed = [], [] for planned, plan, members in groups: @@ -1191,6 +1212,9 @@ def main(argv=None): help=f"default ${data_root.ENV}, else datasets/ in the repository") parser.add_argument("--keep-data", action="store_true", help=f"keep {VICTORIAMETRICS}'s data directory and {BACKEND}'s view directories") + parser.add_argument("--joint-plan-timeout", type=float, default=1800, metavar="SECONDS", + help=f"how long {BACKEND}'s control_plane may take to plan several queries together; past " + "it the queries plan alone, one instance each [1800]") parser.add_argument("--trials", type=int, default=1, help="runs of both systems; each starts both systems afresh and writes the data again, " "and runs after the first are named -trialN, as run_use_case.py names them") diff --git a/scripts/use_cases/test_run_use_case_on_systems.py b/scripts/use_cases/test_run_use_case_on_systems.py index c4e89025..c9c1e57b 100644 --- a/scripts/use_cases/test_run_use_case_on_systems.py +++ b/scripts/use_cases/test_run_use_case_on_systems.py @@ -228,13 +228,17 @@ def test_sketches_and_materialized_views_below_the_query_root(self): self.assertEqual(describe_backend_plan(plan, "c"), "exact (0 materialized views)") -def planner(unplannable, conflicts): - def control_plane(binary, spec, queries, arm, workdir, name, calls=None): +def planner(unplannable, conflicts, too_slow=None, asked=None): + def control_plane(binary, spec, queries, arm, workdir, name, calls=None, timeout=None): ids = {q["id"] for q in queries} + if asked is not None: + asked.append((sorted(ids), timeout)) if ids & unplannable: return None, "unsupported" if any(pair <= ids for pair in conflicts): return None, "not together" + if too_slow is not None and len(ids) >= too_slow: + return None, f"planning did not finish in {timeout:g} s" return f"{name}-plan.json", {"ids": sorted(ids)} return control_plane @@ -244,20 +248,38 @@ def spec_of(*ids): class PlanGroupsTest(unittest.TestCase): - def groups(self, spec, unplannable=(), conflicts=()): + def groups(self, spec, unplannable=(), conflicts=(), too_slow=None, asked=None): with mock.patch.object(run_use_case_on_systems, "control_plane", - planner(set(unplannable), [set(c) for c in conflicts])): - groups, unsupported = plan_groups("cp", spec, "noraw", "/tmp") + planner(set(unplannable), [set(c) for c in conflicts], too_slow, asked)): + groups, unsupported = plan_groups("cp", spec, "noraw", "/tmp", timeout=60) return [[q["id"] for q in members] for _, _, members in groups], unsupported def test_one_group_when_everything_plans_together(self): self.assertEqual(self.groups(spec_of("a", "b", "c")), ([["a", "b", "c"]], {})) - def test_unplannable_queries_are_recorded_and_the_rest_plan_alone(self): - groups, unsupported = self.groups(spec_of("a", "b", "c"), unplannable={"b"}) + def test_unplannable_queries_are_recorded_and_the_rest_plan_together(self): + asked = [] + groups, unsupported = self.groups(spec_of("a", "b", "c"), unplannable={"b"}, asked=asked) + self.assertEqual(groups, [["a", "c"]]) + self.assertEqual(unsupported, {"b": "unsupported"}) + self.assertEqual(asked, [(["a", "b", "c"], 60), (["a"], None), (["b"], None), (["c"], None), + (["a", "c"], 60)]) + + def test_the_supported_queries_plan_alone_when_they_do_not_plan_together(self): + groups, unsupported = self.groups(spec_of("a", "b", "c"), unplannable={"b"}, conflicts=[("a", "c")]) self.assertEqual(groups, [["a"], ["c"]]) self.assertEqual(unsupported, {"b": "unsupported"}) + def test_the_supported_queries_plan_alone_when_planning_them_together_takes_too_long(self): + groups, unsupported = self.groups(spec_of("a", "b", "c", "d"), unplannable={"b"}, too_slow=2) + self.assertEqual(groups, [["a"], ["c"], ["d"]]) + self.assertEqual(unsupported, {"b": "unsupported"}) + + def test_the_same_queries_are_not_planned_together_twice(self): + asked = [] + self.groups(spec_of("a", "b"), too_slow=2, asked=asked) + self.assertEqual(asked, [(["a", "b"], 60), (["a"], None), (["b"], None)]) + def test_queries_that_do_not_plan_together_plan_alone(self): groups, unsupported = self.groups(spec_of("a", "b", "c"), conflicts=[("a", "c")]) self.assertEqual(groups, [["a"], ["b"], ["c"]]) @@ -426,13 +448,14 @@ def cell_of_(path, engine, workload_, variant): with tempfile.TemporaryDirectory() as root, mock.patch("sys.stderr"), \ mock.patch.object(run_use_case_on_systems, "plan_groups", - lambda binary, spec_, arm, workdir, calls=None: ( + lambda binary, spec_, arm, workdir, calls=None, timeout=None: ( [("plan.json", {}, list(spec_["queries"]))], {})), \ mock.patch.object(run_use_case_on_systems, "start_backend", start), \ mock.patch.object(run_use_case_on_systems, "benchmark_external", lambda *a, **k: None), \ mock.patch.object(run_use_case_on_systems, "cell_of", cell_of_): asked, summary, _, unsupported = run_use_case_on_systems.run_planned( - argparse.Namespace(backend_dir=root, speed=None, keep_data=True), "asapquery-backend", "spec.json", + argparse.Namespace(backend_dir=root, speed=None, keep_data=True, joint_plan_timeout=1800), + "asapquery-backend", "spec.json", spec, "noraw", root, None) self.assertEqual(started, ["noraw", "noraw-query-q1", "noraw-query-q2", "noraw-query-q3"]) self.assertEqual([(q["id"], q["evaluations"], q.get("failed"), q["failed_evaluations"]) @@ -728,12 +751,12 @@ def start(args, workdir, name, spec_, plan, raw_store=False): with tempfile.TemporaryDirectory() as root, \ mock.patch.object(run_use_case_on_systems, "plan_groups", - lambda binary, spec_, arm, workdir, calls=None: ( + lambda binary, spec_, arm, workdir, calls=None, timeout=None: ( [("plan.json", {}, list(spec_["queries"]))], {})), \ mock.patch.object(run_use_case_on_systems, "start_backend", start), \ mock.patch.object(run_use_case_on_systems, "benchmark_external", lambda *a, **k: None), \ mock.patch.object(run_use_case_on_systems, "cell_of", harness_cell): - args = argparse.Namespace(backend_dir=root, speed=None, keep_data=True) + args = argparse.Namespace(backend_dir=root, speed=None, keep_data=True, joint_plan_timeout=1800) asked, summary, _, unsupported = run_use_case_on_systems.run_planned( args, "asapquery-backend", "spec.json", spec, "noraw", root, None) self.assertEqual(started, ["noraw-every-10000ms", "noraw-every-60000ms"]) @@ -744,7 +767,7 @@ def start(args, workdir, name, spec_, plan, raw_store=False): class ReferenceBackendTest(unittest.TestCase): def systems(self, root, planned, unplannable): - def plan_groups_(binary, spec, arm, workdir, calls=None): + def plan_groups_(binary, spec, arm, workdir, calls=None, timeout=None): members = [q for q in spec["queries"] if q["id"] in planned] return ([("plan.json", {}, members)] if members else []), {i: "refused" for i in unplannable} @@ -776,7 +799,8 @@ def scored_(args, spec_path, document, exact_path, out): def args(self, root): return argparse.Namespace(reference="asapquery-backend", candidate="victoriametrics", backend_dir=root, planeval="planeval", data_root="d", speed=None, keep_data=True, arm=None, - trials=1, approxbench="approxbench", max_core_busy=0.1, own_cgroup=False) + trials=1, approxbench="approxbench", max_core_busy=0.1, own_cgroup=False, + joint_plan_timeout=1800) def test_a_spec_runs_with_the_backend_as_reference_and_is_scored_against_its_answers(self): spec = {"name": "x", "start_ms": 0, "duration_ms": 1000, "metrics": [], "queries": [text_query("q1")]}