diff --git a/src/taskgraph/optimize/base.py b/src/taskgraph/optimize/base.py index 9c578848b..f4a397112 100644 --- a/src/taskgraph/optimize/base.py +++ b/src/taskgraph/optimize/base.py @@ -12,9 +12,12 @@ """ import datetime +import functools import logging from abc import ABCMeta, abstractmethod from collections import defaultdict +from typing import Any as AnyType +from typing import NamedTuple, cast from slugid import nice as slugid @@ -22,7 +25,6 @@ from taskgraph.taskgraph import TaskGraph from taskgraph.util.parameterization import resolve_task_references, resolve_timestamps from taskgraph.util.python_path import import_sibling_modules -from taskgraph.util.taskcluster import find_task_id_batched, status_task_batched logger = logging.getLogger("optimization") registry = {} @@ -54,9 +56,6 @@ def optimize_task_graph( Perform task optimization, returning a taskgraph and a map from label to assigned taskId, including replacement tasks. """ - # avoid circular import - from taskgraph.optimize.strategies import IndexSearch # noqa: PLC0415 - label_to_taskid = {} if not existing_tasks: existing_tasks = {} @@ -66,43 +65,27 @@ def optimize_task_graph( if strategy_override: strategies.update(strategy_override) - optimizations = _get_optimizations(target_task_graph, strategies) + # Map task labels -> TaskStrategy. This is done once, upfront, to make + # things easier for `remove_tasks` and `replace_tasks`, and ensure that + # we don't do this work differently in different places. + task_strategies = resolve_task_strategies(target_task_graph, strategies) removed_tasks = remove_tasks( target_task_graph=target_task_graph, requested_tasks=requested_tasks, - optimizations=optimizations, + task_strategies=task_strategies, params=params, do_not_optimize=do_not_optimize, ) - # Gather each relevant task's index - indexes = set() - for label in target_task_graph.tasks: - if label in do_not_optimize: - continue - _, strategy, arg = optimizations(label) - if isinstance(strategy, IndexSearch) and arg is not None: - indexes.update(arg) - - index_to_taskid = {} - taskid_to_status = {} - if indexes: - # Find their respective status using TC index/queue batch APIs - indexes = list(indexes) - index_to_taskid = find_task_id_batched(indexes) - taskid_to_status = status_task_batched(list(index_to_taskid.values())) - replaced_tasks = replace_tasks( target_task_graph=target_task_graph, - optimizations=optimizations, + task_strategies=task_strategies, params=params, do_not_optimize=do_not_optimize, label_to_taskid=label_to_taskid, existing_tasks=existing_tasks, removed_tasks=removed_tasks, - index_to_taskid=index_to_taskid, - taskid_to_status=taskid_to_status, ) return ( @@ -117,19 +100,34 @@ def optimize_task_graph( ) -def _get_optimizations(target_task_graph, strategies): - def optimizations(label): - task = target_task_graph.tasks[label] +class TaskStrategy(NamedTuple): + name: str + strategy: "OptimizationStrategy" + arg: AnyType + + +def resolve_task_strategies(target_task_graph, strategies): + task_strategies = {} + for label, task in target_task_graph.tasks.items(): if task.optimization: - opt_by, arg = list(task.optimization.items())[0] - strategy = strategies[opt_by] + name, arg = next(iter(task.optimization.items())) + strategy = strategies[name] if hasattr(strategy, "description"): - opt_by += f" ({strategy.description})" - return (opt_by, strategy, arg) + name += f" ({strategy.description})" + task_strategies[label] = TaskStrategy(name, strategy, arg) else: - return ("never", strategies["never"], None) + task_strategies[label] = TaskStrategy("never", strategies["never"], None) + return task_strategies + - return optimizations +def _group_by_strategy(labels, task_strategies): + groups = {} + for label in labels: + _, strategy, arg = task_strategies[label] + _, group_labels, args = groups.setdefault(id(strategy), (strategy, [], {})) + group_labels.append(label) + args[label] = arg + return groups.values() def _log_optimization(verb, opt_counts, opt_reasons=None): @@ -149,21 +147,38 @@ def _log_optimization(verb, opt_counts, opt_reasons=None): def remove_tasks( - target_task_graph, requested_tasks, params, optimizations, do_not_optimize + target_task_graph, requested_tasks, params, task_strategies, do_not_optimize ): """ Implement the "Removing Tasks" phase, returning a set of task labels of all removed tasks. """ opt_counts = defaultdict(int) opt_reasons = {} - removed = set() _, dependents_of = target_task_graph.graph.links_and_reverse_links_dict() tasks = target_task_graph.tasks + + # Generate an ordered list of tasks that optimization strategies need to + # be called. Traverse the graph so dependents (child nodes) are guaranteed + # to be process first. + order = list(target_task_graph.graph.visit_preorder()) + # Only tasks that are both requested for removal _and_ not in + # `do_not_optimize` are candidates for explicit removal. + candidates = [l for l in order if l in requested_tasks and l not in do_not_optimize] + + # Find the tasks that would be removed by any strategy. + strategy_removes = set() + for strategy, labels, args in _group_by_strategy(candidates, task_strategies): + strategy_removes |= strategy.should_remove_tasks( + target_task_graph, labels, params, args + ) + + removed = set() prune_candidates = set() - # Traverse graph so dependents (child nodes) are guaranteed to be processed - # first. - for label in target_task_graph.graph.visit_preorder(): + # Now that we have all of the necessary information, find tasks that can + # definitely be removed, and those that are candidates for removal (subject + # to additional conditions that cannot be evaluated in this loop). + for label in order: # Dependents that can be pruned away (shouldn't cause this task to run). # Only dependents that either: # A) Explicitly reference this task in their 'if_dependencies' list, or @@ -236,22 +251,23 @@ def _remove(reason): _remove("dependents optimized") continue - # Call the optimization strategy. - task = tasks[label] - opt_by, opt, arg = optimizations(label) - if opt.should_remove_task(task, params, arg): + opt_by = task_strategies[label].name + # The task is not in `do_not_optimize`, not required for a descendent + # task that was kept, and explicitly requested for removal: remove it. + if label in strategy_removes: _remove(opt_by) continue # Some tasks should only run if their dependency was also run. Since we # haven't processed dependencies yet, we add them to a list of # candidate tasks for pruning. - if task.if_dependencies: + if tasks[label].if_dependencies: opt_reasons[label] = ("kept", opt_by) prune_candidates.add(label) else: _keep(opt_by) + # Add any `prune_candidates` that qualify to `removed`. if prune_candidates: reason = "if-dependencies pruning" for label in prune_candidates: @@ -279,22 +295,17 @@ def _remove(reason): def replace_tasks( target_task_graph, params, - optimizations, + task_strategies, do_not_optimize, label_to_taskid, removed_tasks, existing_tasks, - index_to_taskid, - taskid_to_status, ): """ Implement the "Replacing Tasks" phase, returning a set of task labels of all replaced tasks. The replacement taskIds are added to label_to_taskid as a side-effect. """ - # avoid circular import - from taskgraph.optimize.strategies import IndexSearch # noqa: PLC0415 - opt_counts = defaultdict(int) replaced = set() dependencies_of, dependents_of = ( @@ -304,16 +315,35 @@ def replace_tasks( # Many tasks share dependents (e.g. docker images or toolchains), so # resolve the deadline of each dependent only once. now = datetime.datetime.now(datetime.timezone.utc) - deadlines = {} - def get_deadline(label): - if label not in deadlines: - deadlines[label] = resolve_timestamps( - now, target_task_graph.tasks[label].task["deadline"] + @functools.cache + def get_deadline(label) -> str: + return cast( + str, + resolve_timestamps(now, target_task_graph.tasks[label].task["deadline"]), + ) + + order = list(target_task_graph.graph.visit_postorder()) + candidates = [ + l for l in order if l not in do_not_optimize and not existing_tasks.get(l) + ] + deadlines = { + label: ( + max(get_deadline(l) for l in dependents_of[label]) + if dependents_of[label] + else None + ) + for label in candidates + } + replacements = {} + for strategy, labels, args in _group_by_strategy(candidates, task_strategies): + replacements.update( + strategy.should_replace_tasks( + target_task_graph, labels, params, deadlines, args ) - return deadlines[label] + ) - for label in target_task_graph.graph.visit_postorder(): + for label in order: logger.debug(f"replace_tasks: {label}") # if we're not allowed to optimize, that's easy.. if label in do_not_optimize: @@ -338,19 +368,8 @@ def get_deadline(label): logger.debug(f"replace_tasks: {label} replaced from existing_tasks") continue - # call the optimization strategy - task = target_task_graph.tasks[label] - opt_by, opt, arg = optimizations(label) - - # compute latest deadline of dependents (if any) - deadline = None - if dependents_of[label]: - deadline = max(get_deadline(l) for l in dependents_of[label]) - - if isinstance(opt, IndexSearch): - arg = arg, index_to_taskid, taskid_to_status - - repl = opt.should_replace_task(task, params, deadline, arg) + opt_by = task_strategies[label].name + repl = replacements.get(label) if repl: if repl is True: logger.debug(f"replace_tasks: {label} removed by optimization strategy") @@ -478,6 +497,37 @@ def should_replace_task(self, task, params, deadline, arg): keep the task.""" return False + def should_remove_tasks(self, graph, labels, params, args): + """Determine which of the tasks in `labels` should be removed, returning + the set of labels to remove. This default implementation simply calls + `self.should_remove_task` for each task. Subclasses that only make the + removal decision based on task data should override that method. + Subclasses that need to evaluate all of their tasks at once to + determine what to remove should override _this_ method.""" + tasks = graph.tasks + return { + label + for label in labels + if self.should_remove_task(tasks[label], params, args[label]) + } + + def should_replace_tasks(self, graph, labels, params, deadlines, args): + """Determine which of the tasks in `labels` should be replaced with + an existing task. The default implementation simply calls + `self.should_replace_task` for each task. Subclasses that only make + the replacement decision based on task data should override that + method. Subclasses that need to evaluate all of their tasks at once + to determine what to replace should override _this_ method.""" + tasks = graph.tasks + replacements = {} + for label in labels: + repl = self.should_replace_task( + tasks[label], params, deadlines[label], args[label] + ) + if repl: + replacements[label] = repl + return replacements + @register_strategy("always") class Always(OptimizationStrategy): @@ -536,6 +586,17 @@ def should_replace_task(self, *args): results = self._generate_results("should_replace_task", *args) return self.reduce(results) + def _split_args(self, labels, args): + """Return the args for all strategies and all labels.""" + splits = { + label: list(self.split_args(args[label], self.substrategies)) + for label in labels + } + return [ + {label: split[i] for label, split in splits.items() if i < len(split)} + for i in range(len(self.substrategies)) + ] + class Any(CompositeStrategy): """Given one or more optimization strategies, remove or replace a task if any of them @@ -555,6 +616,33 @@ def reduce(cls, results): return rv return False + def should_remove_tasks(self, graph, labels, params, args): + removed = set() + remaining = labels + for sub, sub_args in zip(self.substrategies, self._split_args(labels, args)): + sub_labels = [l for l in remaining if l in sub_args] + if sub_labels: + removed |= sub.should_remove_tasks(graph, sub_labels, params, sub_args) + remaining = [l for l in remaining if l not in removed] + if not remaining: + break + return removed + + def should_replace_tasks(self, graph, labels, params, deadlines, args): + replacements = {} + remaining = labels + for sub, sub_args in zip(self.substrategies, self._split_args(labels, args)): + sub_labels = [l for l in remaining if l in sub_args] + if sub_labels: + result = sub.should_replace_tasks( + graph, sub_labels, params, deadlines, sub_args + ) + replacements.update((l, r) for l, r in result.items() if r) + remaining = [l for l in remaining if l not in replacements] + if not remaining: + break + return replacements + class All(CompositeStrategy): """Given one or more optimization strategies, remove or replace a task if all of them @@ -588,6 +676,39 @@ def reduce(cls, results): # If no result says no, return the first result. return first + def should_remove_tasks(self, graph, labels, params, args): + candidates = labels + for sub, sub_args in zip(self.substrategies, self._split_args(labels, args)): + sub_labels = [l for l in candidates if l in sub_args] + if sub_labels: + removed = sub.should_remove_tasks(graph, sub_labels, params, sub_args) + candidates = [ + l for l in candidates if l not in sub_args or l in removed + ] + if not candidates: + break + return set(candidates) + + def should_replace_tasks(self, graph, labels, params, deadlines, args): + candidates = labels + first = {} + for i, (sub, sub_args) in enumerate( + zip(self.substrategies, self._split_args(labels, args)) + ): + sub_labels = [l for l in candidates if l in sub_args] + if sub_labels: + result = sub.should_replace_tasks( + graph, sub_labels, params, deadlines, sub_args + ) + if i == 0: + first = result + candidates = [ + l for l in candidates if l not in sub_args or result.get(l) + ] + if not candidates: + break + return {l: first.get(l, True) for l in candidates} + class Alias(CompositeStrategy): """Provides an alias to an existing strategy. @@ -606,6 +727,14 @@ def description(self): def reduce(self, results): return next(results) + def should_remove_tasks(self, graph, labels, params, args): + return self.substrategies[0].should_remove_tasks(graph, labels, params, args) + + def should_replace_tasks(self, graph, labels, params, deadlines, args): + return self.substrategies[0].should_replace_tasks( + graph, labels, params, deadlines, args + ) + class Not(CompositeStrategy): """Given a strategy, returns the opposite.""" @@ -620,6 +749,16 @@ def description(self): def reduce(self, results): return not next(results) + def should_remove_tasks(self, graph, labels, params, args): + removed = self.substrategies[0].should_remove_tasks(graph, labels, params, args) + return {l for l in labels if l not in removed} + + def should_replace_tasks(self, graph, labels, params, deadlines, args): + result = self.substrategies[0].should_replace_tasks( + graph, labels, params, deadlines, args + ) + return {l: True for l in labels if not result.get(l)} + # Trigger registration in sibling modules. import_sibling_modules() diff --git a/src/taskgraph/optimize/strategies.py b/src/taskgraph/optimize/strategies.py index 459412c8a..35f64b4d1 100644 --- a/src/taskgraph/optimize/strategies.py +++ b/src/taskgraph/optimize/strategies.py @@ -6,7 +6,12 @@ from taskgraph.optimize.base import OptimizationStrategy, register_strategy from taskgraph.util.path import match as match_path -from taskgraph.util.taskcluster import find_task_id, status_task +from taskgraph.util.taskcluster import ( + find_task_id, + find_task_id_batched, + status_task, + status_task_batched, +) logger = logging.getLogger("optimization") @@ -34,28 +39,40 @@ class IndexSearch(OptimizationStrategy): def should_replace_task(self, task, params, deadline, arg): "Look for a task with one of the given index paths" - batched = False - # Appease static checker that doesn't understand that this is not needed - label_to_taskid = {} - taskid_to_status = {} - - if isinstance(arg, tuple) and len(arg) == 3: - # allow for a batched call optimization instead of two queries - # per index path - index_paths, label_to_taskid, taskid_to_status = arg - batched = True - else: - index_paths = arg - - for index_path in index_paths: + + def lookup(index_path): + # 404 is raised as `KeyError` + task_id = find_task_id(index_path) + return task_id, status_task(task_id) + + return self._find_replacement(task, arg, deadline, lookup) + + def should_replace_tasks(self, graph, labels, params, deadlines, args): + index_paths = sorted({path for label in labels for path in args[label] or ()}) + if not index_paths: + return {} + + # Find their respective status using TC index/queue batch APIs + index_to_taskid = find_task_id_batched(index_paths) + taskid_to_status = status_task_batched(list(index_to_taskid.values())) + + def lookup(index_path): + task_id = index_to_taskid[index_path] + return task_id, taskid_to_status[task_id] + + replacements = {} + for label in labels: + repl = self._find_replacement( + graph.tasks[label], args[label], deadlines[label], lookup + ) + if repl: + replacements[label] = repl + return replacements + + def _find_replacement(self, task, index_paths, deadline, lookup): + for index_path in index_paths or (): try: - if batched: - task_id = label_to_taskid[index_path] - status = taskid_to_status[task_id] - else: - # 404 is raised as `KeyError` also end up here - task_id = find_task_id(index_path) - status = status_task(task_id) + task_id, status = lookup(index_path) # status can be `None` if we're in `testing` mode # (e.g. test-action-callback) if not status or status.get("state") in ("exception", "failed"): # type: ignore diff --git a/test/test_optimize.py b/test/test_optimize.py index dbd6b069b..ff17c29b1 100644 --- a/test/test_optimize.py +++ b/test/test_optimize.py @@ -11,6 +11,7 @@ from taskgraph.graph import Graph from taskgraph.optimize import base as optimize_mod from taskgraph.optimize.base import ( + Alias, All, Any, Not, @@ -269,7 +270,7 @@ def test_remove_tasks(monkeypatch, graph, kwargs, exp_removed): got_removed = optimize_mod.remove_tasks( target_task_graph=graph, - optimizations=optimize_mod._get_optimizations(graph, strategies), + task_strategies=optimize_mod.resolve_task_strategies(graph, strategies), **kwargs, ) assert got_removed == exp_removed @@ -284,9 +285,7 @@ def test_remove_tasks(monkeypatch, graph, kwargs, exp_removed): t1={"replace": "e1"}, t3={"replace": "e3"}, ), - { - "index_to_taskid": {"t1": "e1"}, - }, + {}, # expectations {"t1"}, set(), @@ -301,7 +300,6 @@ def test_remove_tasks(monkeypatch, graph, kwargs, exp_removed): ), { "do_not_optimize": {"t2"}, - "index_to_taskid": {"t1": "e1"}, }, # expectations {"t1"}, @@ -324,9 +322,7 @@ def test_remove_tasks(monkeypatch, graph, kwargs, exp_removed): t2={"replace": "e2"}, t3={"replace": "e3"}, ), - { - "index_to_taskid": {"t1": "e1", "t2": "e2", "t3": "e3"}, - }, + {}, # expectations {"t1", "t2", "t3"}, set(), @@ -339,9 +335,7 @@ def test_remove_tasks(monkeypatch, graph, kwargs, exp_removed): t2={"replace": True}, t3={"replace": True}, ), - { - "index_to_taskid": {"t1": "e1"}, - }, + {}, # expectations {"t1"}, {"t2", "t3"}, @@ -387,14 +381,14 @@ def test_replace_tasks( kwargs.setdefault("params", {}) kwargs.setdefault("do_not_optimize", set()) kwargs.setdefault("label_to_taskid", {}) - kwargs.setdefault("index_to_taskid", {}) - kwargs.setdefault("taskid_to_status", {}) kwargs.setdefault("removed_tasks", set()) kwargs.setdefault("existing_tasks", {}) got_replaced = optimize_mod.replace_tasks( target_task_graph=graph, - optimizations=optimize_mod._get_optimizations(graph, default_strategies()), + task_strategies=optimize_mod.resolve_task_strategies( + graph, default_strategies() + ), **kwargs, ) assert got_replaced == exp_replaced @@ -489,6 +483,46 @@ def test_register_strategy(mocker): m.assert_called_with("one", "two", n=1) +class RecordingRemove(OptimizationStrategy): + def __init__(self, remove=()): + self.remove = set(remove) + self.calls = [] + + def should_remove_tasks(self, graph, labels, params, args): + self.calls.append(list(labels)) + return {l for l in labels if l in self.remove} + + +def make_leaves(n, strategy): + return make_graph( + *(make_task(f"t{i}", optimization={strategy: None}) for i in range(1, n + 1)) + ) + + +def run_remove_tasks(graph, strategies, requested_tasks=None, do_not_optimize=()): + return optimize_mod.remove_tasks( + target_task_graph=graph, + requested_tasks=graph if requested_tasks is None else requested_tasks, + params={}, + task_strategies=optimize_mod.resolve_task_strategies(graph, strategies), + do_not_optimize=set(do_not_optimize), + ) + + +def test_resolve_task_strategies(): + strategies = default_strategies() + strategies["any"] = Any("never", "always") + graph = make_graph( + make_task("t1", optimization={"remove": ["a"]}), + make_task("t2", optimization={"any": None}), + make_task("t3"), + ) + resolved = optimize_mod.resolve_task_strategies(graph, strategies) + assert resolved["t1"] == ("remove", strategies["remove"], ["a"]) + assert resolved["t2"] == ("any (never-or-always)", strategies["any"], None) + assert resolved["t3"] == ("never", strategies["never"], None) + + def test_all_replaces_with_first_substrategy_value(): graph = make_graph(make_task("t1", optimization={"all": "e1"})) strategies = default_strategies() @@ -501,15 +535,335 @@ def test_all_replaces_with_first_substrategy_value(): replaced = optimize_mod.replace_tasks( target_task_graph=graph, params={}, - optimizations=optimize_mod._get_optimizations(graph, strategies), + task_strategies=optimize_mod.resolve_task_strategies(graph, strategies), do_not_optimize=set(), label_to_taskid=label_to_taskid, removed_tasks=removed_tasks, existing_tasks={}, - index_to_taskid={}, - taskid_to_status={}, ) assert removed_tasks == set() assert replaced == {"t1"} assert label_to_taskid == {"t1": "e1"} + + +def test_remove_tasks_batches_candidates_per_strategy(): + graph = make_graph( + make_task("t1", optimization={"rec": "a1"}), + make_task("t2", optimization={"rec": "a2"}), + make_task("t3", optimization={"rec": "a3"}), + make_task("t4", optimization={"rec": "a4"}), + make_task("t5", optimization={"remove": None}), + ("t3", "t1", "dep"), + ) + strategies = default_strategies() + args_seen = [] + + class Rec(RecordingRemove): + def should_remove_tasks(self, graph, labels, params, args): + args_seen.append(dict(args)) + return super().should_remove_tasks(graph, labels, params, args) + + rec = Rec(remove={"t1", "t2", "t3"}) + strategies["rec"] = rec + + removed = run_remove_tasks( + graph, + strategies, + requested_tasks={"t1", "t2", "t3", "t5"}, + do_not_optimize={"t2"}, + ) + + assert rec.calls == [["t3", "t1"]] + assert args_seen == [{"t3": "a3", "t1": "a1"}] + assert removed == {"t1", "t3", "t4", "t5"} + + +def test_remove_tasks_groups_by_strategy_object(): + graph = make_graph( + make_task("t1", optimization={"first-name": None}), + make_task("t2", optimization={"second-name": None}), + ) + rec = RecordingRemove(remove={"t2"}) + strategies = default_strategies() + strategies["first-name"] = rec + strategies["second-name"] = rec + + assert run_remove_tasks(graph, strategies) == {"t2"} + assert len(rec.calls) == 1 + assert sorted(rec.calls[0]) == ["t1", "t2"] + + +def test_remove_tasks_strategy_decides_with_whole_batch(): + class KeepFirst(OptimizationStrategy): + def should_remove_tasks(self, graph, labels, params, args): + return set(sorted(labels)[1:]) + + graph = make_leaves(3, "keep-first") + strategies = default_strategies() + strategies["keep-first"] = KeepFirst() + assert run_remove_tasks(graph, strategies) == {"t2", "t3"} + + +@pytest.mark.parametrize( + "make_composite,first_removes,second_removes,exp_second_sees,exp_removed", + ( + pytest.param(Any, {"t1"}, {"t2"}, ["t2", "t3"], {"t1", "t2"}, id="any"), + pytest.param(All, {"t1", "t2"}, {"t2", "t3"}, ["t1", "t2"], {"t2"}, id="all"), + ), +) +def test_composite_remove_short_circuits( + make_composite, first_removes, second_removes, exp_second_sees, exp_removed +): + graph = make_leaves(3, "composite") + first = RecordingRemove(remove=first_removes) + second = RecordingRemove(remove=second_removes) + labels = ["t1", "t2", "t3"] + assert ( + make_composite(first, second).should_remove_tasks( + graph, labels, {}, dict.fromkeys(labels) + ) + == exp_removed + ) + assert first.calls == [labels] + assert second.calls == [exp_second_sees] + + +def test_composite_remove_skips_substrategies_once_decided(): + graph = make_leaves(2, "composite") + second = RecordingRemove() + labels = ["t1", "t2"] + assert Any(RecordingRemove(remove=labels), second).should_remove_tasks( + graph, labels, {}, dict.fromkeys(labels) + ) == {"t1", "t2"} + assert second.calls == [] + + +def test_not_and_alias_remove(): + graph = make_leaves(3, "composite") + labels = ["t1", "t2", "t3"] + args = dict.fromkeys(labels) + inner = RecordingRemove(remove={"t2"}) + assert Not(inner).should_remove_tasks(graph, labels, {}, args) == {"t1", "t3"} + assert Alias(inner).should_remove_tasks(graph, labels, {}, args) == {"t2"} + + +def test_composite_split_args_are_per_task(): + class Mark(OptimizationStrategy): + def should_remove_task(self, task, params, arg): + arg["seen"] = task.label + return False + + class RemoveIfMarked(OptimizationStrategy): + def should_remove_tasks(self, graph, labels, params, args): + return {l for l in labels if args[l].get("seen") == l and args[l]["rm"]} + + def split(arg, substrategies): + shared = {"rm": arg} + return [shared, shared] + + graph = make_leaves(2, "composite") + composite = Any(Mark(), RemoveIfMarked(), split_args=split) + assert composite.should_remove_tasks( + graph, ["t1", "t2"], {}, {"t1": True, "t2": False} + ) == {"t1"} + + +def test_custom_composite_uses_per_task_reduce(): + class Majority(optimize_mod.CompositeStrategy): + description = "majority" + + def reduce(self, results): + results = list(results) + return sum(bool(r) for r in results) > len(results) / 2 + + graph = make_leaves(1, "composite") + strategy = Majority("always", "always", "never") + assert strategy.should_remove_tasks(graph, ["t1"], {}, {"t1": None}) == {"t1"} + + +class RecordingReplace(OptimizationStrategy): + def __init__(self, replacements=None): + self.replacements = replacements or {} + self.calls = [] + + def should_replace_tasks(self, graph, labels, params, deadlines, args): + self.calls.append((list(labels), dict(deadlines))) + return {l: self.replacements[l] for l in labels if l in self.replacements} + + +def run_replace_tasks(graph, strategies, do_not_optimize=(), existing_tasks=None): + label_to_taskid = {} + replaced = optimize_mod.replace_tasks( + target_task_graph=graph, + params={}, + task_strategies=optimize_mod.resolve_task_strategies(graph, strategies), + do_not_optimize=set(do_not_optimize), + label_to_taskid=label_to_taskid, + removed_tasks=set(), + existing_tasks=existing_tasks or {}, + ) + return replaced, label_to_taskid + + +def test_replace_tasks_batches_candidates_per_strategy(): + graph = make_graph( + make_task("t1", optimization={"rec": None}), + make_task("t2", optimization={"rec": None}), + make_task("t3", optimization={"rec": None}), + make_task("t4", optimization={"rec": None}), + ("t2", "t1", "dep"), + ) + rec = RecordingReplace({"t1": "e1", "t2": "e2", "t3": "e3", "t4": "e4"}) + strategies = default_strategies() + strategies["rec"] = rec + + replaced, label_to_taskid = run_replace_tasks( + graph, strategies, do_not_optimize={"t3"}, existing_tasks={"t4": "x4"} + ) + + assert len(rec.calls) == 1 + labels, deadlines = rec.calls[0] + assert labels == ["t1", "t2"] + assert deadlines["t2"] is None + assert deadlines["t1"] is not None + assert replaced == {"t1", "t2", "t4"} + assert label_to_taskid == {"t1": "e1", "t2": "e2", "t4": "x4"} + + +def test_replace_tasks_ignores_replacements_of_tasks_with_kept_dependencies(): + graph = make_graph( + make_task("t1"), + make_task("t2", optimization={"rec": None}), + ("t2", "t1", "dep"), + ) + rec = RecordingReplace({"t2": "e2"}) + strategies = default_strategies() + strategies["rec"] = rec + + replaced, _ = run_replace_tasks(graph, strategies) + assert rec.calls[0][0] == ["t2"] + assert replaced == set() + + +@pytest.mark.parametrize( + "make_composite,first,second,exp_second_sees,exp_replaced", + ( + pytest.param( + Any, + {"t1": "e1"}, + {"t1": "x1", "t2": "e2"}, + ["t2", "t3"], + {"t1": "e1", "t2": "e2"}, + id="any", + ), + pytest.param( + All, + {"t1": "e1", "t2": "e2"}, + {"t2": "x2", "t3": "x3"}, + ["t1", "t2"], + {"t2": "e2"}, + id="all", + ), + ), +) +def test_composite_replace_short_circuits( + make_composite, first, second, exp_second_sees, exp_replaced +): + graph = make_leaves(3, "composite") + first = RecordingReplace(first) + second = RecordingReplace(second) + labels = ["t1", "t2", "t3"] + result = make_composite(first, second).should_replace_tasks( + graph, labels, {}, dict.fromkeys(labels), dict.fromkeys(labels) + ) + assert result == exp_replaced + assert [call[0] for call in second.calls] == [exp_second_sees] + + +def test_not_and_alias_replace(): + graph = make_leaves(2, "composite") + labels = ["t1", "t2"] + deadlines = dict.fromkeys(labels) + args = dict.fromkeys(labels) + inner = RecordingReplace({"t1": "e1"}) + assert Not(inner).should_replace_tasks(graph, labels, {}, deadlines, args) == { + "t2": True + } + assert Alias(inner).should_replace_tasks(graph, labels, {}, deadlines, args) == { + "t1": "e1" + } + + +def test_composite_replace_matches_per_task_results(): + graph = make_leaves(4, "composite") + labels = ["t1", "t2", "t3", "t4"] + values = {"t1": ("e1", False), "t2": (False, "e2"), "t3": ("e3", "x3")} + + class PerTask(OptimizationStrategy): + def __init__(self, index): + self.index = index + + def should_replace_task(self, task, params, deadline, arg): + return values.get(task.label, (False, False))[self.index] + + for composite in ( + Any(PerTask(0), PerTask(1)), + All(PerTask(0), PerTask(1)), + Not(PerTask(0)), + Alias(PerTask(1)), + ): + expected = {} + for label in labels: + repl = composite.should_replace_task(graph.tasks[label], {}, None, None) + if repl: + expected[label] = repl + assert ( + composite.should_replace_tasks( + graph, labels, {}, dict.fromkeys(labels), dict.fromkeys(labels) + ) + == expected + ) + + +def short_split(arg, substrategies): + return [arg] * (1 if arg == "short" else len(substrategies)) + + +@pytest.mark.parametrize( + "make_composite,exp_removed", + ( + pytest.param(Any, {"t1", "t2"}, id="any"), + pytest.param(All, {"t1"}, id="all"), + ), +) +def test_composite_remove_with_fewer_split_args(make_composite, exp_removed): + graph = make_leaves(2, "composite") + first = RecordingRemove(remove={"t1", "t2"}) + second = RecordingRemove(remove=set()) + composite = make_composite(first, second, split_args=short_split) + removed = composite.should_remove_tasks( + graph, ["t1", "t2"], {}, {"t1": "short", "t2": "full"} + ) + assert removed == exp_removed + assert all("t1" not in labels for labels in second.calls) + + +@pytest.mark.parametrize( + "make_composite,exp_replaced", + ( + pytest.param(Any, {"t1": "e1", "t2": "e2"}, id="any"), + pytest.param(All, {"t1": "e1"}, id="all"), + ), +) +def test_composite_replace_with_fewer_split_args(make_composite, exp_replaced): + graph = make_leaves(2, "composite") + labels = ["t1", "t2"] + first = RecordingReplace({"t1": "e1", "t2": "e2"}) + second = RecordingReplace() + composite = make_composite(first, second, split_args=short_split) + replaced = composite.should_replace_tasks( + graph, labels, {}, dict.fromkeys(labels), {"t1": "short", "t2": "full"} + ) + assert replaced == exp_replaced + assert all("t1" not in call[0] for call in second.calls) diff --git a/test/test_optimize_strategies.py b/test/test_optimize_strategies.py index d09c05e93..0a790c220 100644 --- a/test/test_optimize_strategies.py +++ b/test/test_optimize_strategies.py @@ -7,7 +7,7 @@ from time import mktime import pytest -from pytest_taskgraph import make_task +from pytest_taskgraph import make_graph, make_task from taskgraph.optimize.strategies import IndexSearch, SkipUnlessChanged from taskgraph.util import taskcluster as tc @@ -84,30 +84,34 @@ def mock_client(service): monkeypatch.setattr(tc, "get_taskcluster_client", mock_client) - label_to_taskid = {index_path: taskid} - taskid_to_status = { - taskid: { - "state": state, - "expires": expires, - } - } + mock_index.findTasksAtIndex.side_effect = lambda payload, paginationHandler: ( + paginationHandler({"tasks": [{"namespace": index_path, "taskId": taskid}]}) + ) + mock_queue.statuses.side_effect = lambda payload, paginationHandler: ( + paginationHandler( + { + "statuses": [ + {"taskId": taskid, "status": {"state": state, "expires": expires}} + ] + } + ) + ) + task = make_task("task-label") opt = IndexSearch() deadline = "2021-06-07T19:03:20.482Z" - assert ( - opt.should_replace_task( - make_task("task-label"), - params, - deadline, - ([index_path], label_to_taskid, taskid_to_status), - ) - == expected - ) + assert opt.should_replace_tasks( + make_graph(task), + ["task-label"], + params, + {"task-label": deadline}, + {"task-label": [index_path]}, + ) == ({"task-label": expected} if expected else {}) + mock_index.findTasksAtIndex.assert_called_once() + mock_queue.statuses.assert_called_once() + # test the non-batched variant as well - assert ( - opt.should_replace_task(make_task("task-label"), params, deadline, [index_path]) - == expected - ) + assert opt.should_replace_task(task, params, deadline, [index_path]) == expected if logs: log_records = [