Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/optimize/base.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4 """
5 The objective of optimization is to remove as many tasks from the graph as
6 possible, as efficiently as possible, thereby delivering useful results as
7 quickly as possible. For example, ideally if only a test script is modified in
8 a push, then the resulting graph contains only the corresponding test suite
9 task.
10
11 See ``taskcluster/docs/optimization.rst`` for more information.
12 """
13
14 import datetime
15 import logging
16 from abc import ABCMeta, abstractmethod
17 from collections import defaultdict
18 from typing import Dict, Set
19
20 from slugid import nice as slugid
21
22 from taskgraph.graph import Graph
23 from taskgraph.taskgraph import TaskGraph
24 from taskgraph.util.parameterization import resolve_task_references, resolve_timestamps
25 from taskgraph.util.python_path import import_sibling_modules
26 from taskgraph.util.taskcluster import find_task_id_batched, status_task_batched
27
28 logger = logging.getLogger("optimization")
29 registry = {}
30
31
32 def register_strategy(name, args=(), kwargs=None):
33 kwargs = kwargs or {}
34
35 def wrap(cls):
36 if name not in registry:
37 registry[name] = cls(*args, **kwargs)
38 if not hasattr(registry[name], "description"):
39 registry[name].description = name
40 return cls
41
42 return wrap
43
44
45 def optimize_task_graph(
46 target_task_graph,
47 requested_tasks,
48 params,
49 do_not_optimize,
50 decision_task_id,
51 existing_tasks=None,
52 strategy_override=None,
53 ):
54 """
55 Perform task optimization, returning a taskgraph and a map from label to
56 assigned taskId, including replacement tasks.
57 """
58 # avoid circular import
59 from taskgraph.optimize.strategies import IndexSearch
60
61 label_to_taskid = {}
62 if not existing_tasks:
63 existing_tasks = {}
64
65 # instantiate the strategies for this optimization process
66 strategies = registry.copy()
67 if strategy_override:
68 strategies.update(strategy_override)
69
70 optimizations = _get_optimizations(target_task_graph, strategies)
71
72 removed_tasks = remove_tasks(
73 target_task_graph=target_task_graph,
74 requested_tasks=requested_tasks,
75 optimizations=optimizations,
76 params=params,
77 do_not_optimize=do_not_optimize,
78 )
79
80 # Gather each relevant task's index
81 indexes = set()
82 for label in target_task_graph.graph.visit_postorder():
83 if label in do_not_optimize:
84 continue
85 _, strategy, arg = optimizations(label)
86 if isinstance(strategy, IndexSearch) and arg is not None:
87 indexes.update(arg)
88
89 index_to_taskid = {}
90 taskid_to_status = {}
91 if indexes:
92 # Find their respective status using TC index/queue batch APIs
93 indexes = list(indexes)
94 index_to_taskid = find_task_id_batched(indexes)
95 taskid_to_status = status_task_batched(list(index_to_taskid.values()))
96
97 replaced_tasks = replace_tasks(
98 target_task_graph=target_task_graph,
99 optimizations=optimizations,
100 params=params,
101 do_not_optimize=do_not_optimize,
102 label_to_taskid=label_to_taskid,
103 existing_tasks=existing_tasks,
104 removed_tasks=removed_tasks,
105 index_to_taskid=index_to_taskid,
106 taskid_to_status=taskid_to_status,
107 )
108
109 return (
110 get_subgraph(
111 target_task_graph,
112 removed_tasks,
113 replaced_tasks,
114 label_to_taskid,
115 decision_task_id,
116 ),
117 label_to_taskid,
118 )
119
120
121 def _get_optimizations(target_task_graph, strategies):
122 def optimizations(label):
123 task = target_task_graph.tasks[label]
124 if task.optimization:
125 opt_by, arg = list(task.optimization.items())[0]
126 strategy = strategies[opt_by]
127 if hasattr(strategy, "description"):
128 opt_by += f" ({strategy.description})"
129 return (opt_by, strategy, arg)
130 else:
131 return ("never", strategies["never"], None)
132
133 return optimizations
134
135
136 def _log_optimization(verb, opt_counts, opt_reasons=None):
137 if opt_reasons:
138 message = "optimize: {label} {action} because of {reason}"
139 for label, (action, reason) in opt_reasons.items():
140 logger.debug(message.format(label=label, action=action, reason=reason))
141
142 if opt_counts:
143 logger.info(
144 f"{verb.title()} "
145 + ", ".join(f"{c} tasks by {b}" for b, c in sorted(opt_counts.items()))
146 + " during optimization."
147 )
148 else:
149 logger.info(f"No tasks {verb} during optimization")
150
151
152 def remove_tasks(
153 target_task_graph, requested_tasks, params, optimizations, do_not_optimize
154 ):
155 """
156 Implement the "Removing Tasks" phase, returning a set of task labels of all removed tasks.
157 """
158 opt_counts = defaultdict(int)
159 opt_reasons = {}
160 removed = set()
161 dependents_of = target_task_graph.graph.reverse_links_dict()
162 tasks = target_task_graph.tasks
163 prune_candidates = set()
164
165 # Traverse graph so dependents (child nodes) are guaranteed to be processed
166 # first.
167 for label in target_task_graph.graph.visit_preorder():
168 # Dependents that can be pruned away (shouldn't cause this task to run).
169 # Only dependents that either:
170 # A) Explicitly reference this task in their 'if_dependencies' list, or
171 # B) Don't have an 'if_dependencies' attribute (i.e are in 'prune_candidates'
172 # because they should be removed but have prune_deps themselves)
173 # should be considered.
174 prune_deps = {
175 l
176 for l in dependents_of[label]
177 if l in prune_candidates
178 if not tasks[l].if_dependencies or label in tasks[l].if_dependencies
179 }
180
181 def _keep(reason):
182 """Mark a task as being kept in the graph. Also recursively removes
183 any dependents from `prune_candidates`, assuming they should be
184 kept because of this task.
185 """
186 opt_reasons[label] = ("kept", reason)
187
188 # Removes dependents that were in 'prune_candidates' from a task
189 # that ended up being kept (and therefore the dependents should
190 # also be kept).
191 queue = list(prune_deps)
192 while queue:
193 l = queue.pop()
194
195 # If l is a prune_dep of multiple tasks it could be queued up
196 # multiple times. Guard against it being already removed.
197 if l not in prune_candidates:
198 continue
199
200 # If a task doesn't set 'if_dependencies' itself (rather it was
201 # added to 'prune_candidates' due to one of its depenendents),
202 # then we shouldn't remove it.
203 if not tasks[l].if_dependencies:
204 continue
205
206 prune_candidates.remove(l)
207 queue.extend([r for r in dependents_of[l] if r in prune_candidates])
208
209 def _remove(reason):
210 """Potentially mark a task as being removed from the graph. If the
211 task has dependents that can be pruned, add this task to
212 `prune_candidates` rather than removing it.
213 """
214 if prune_deps:
215 # If there are prune_deps, unsure if we can remove this task yet.
216 prune_candidates.add(label)
217 else:
218 opt_reasons[label] = ("removed", reason)
219 opt_counts[reason] += 1
220 removed.add(label)
221
222 # if we're not allowed to optimize, that's easy..
223 if label in do_not_optimize:
224 _keep("do not optimize")
225 continue
226
227 # If there are remaining tasks depending on this one, do not remove.
228 if any(
229 l for l in dependents_of[label] if l not in removed and l not in prune_deps
230 ):
231 _keep("dependent tasks")
232 continue
233
234 # Some tasks in the task graph only exist because they were required
235 # by a task that has just been optimized away. They can now be removed.
236 if label not in requested_tasks:
237 _remove("dependents optimized")
238 continue
239
240 # Call the optimization strategy.
241 task = tasks[label]
242 opt_by, opt, arg = optimizations(label)
243 if opt.should_remove_task(task, params, arg):
244 _remove(opt_by)
245 continue
246
247 # Some tasks should only run if their dependency was also run. Since we
248 # haven't processed dependencies yet, we add them to a list of
249 # candidate tasks for pruning.
250 if task.if_dependencies:
251 opt_reasons[label] = ("kept", opt_by)
252 prune_candidates.add(label)
253 else:
254 _keep(opt_by)
255
256 if prune_candidates:
257 reason = "if-dependencies pruning"
258 for label in prune_candidates:
259 # There's an edge case where a triangle graph can cause a
260 # dependency to stay in 'prune_candidates' when the dependent
261 # remains. Do a final check to ensure we don't create any bad
262 # edges.
263 dependents = any(
264 d
265 for d in dependents_of[label]
266 if d not in prune_candidates
267 if d not in removed
268 )
269 if dependents:
270 opt_reasons[label] = ("kept", "dependent tasks")
271 continue
272 removed.add(label)
273 opt_counts[reason] += 1
274 opt_reasons[label] = ("removed", reason)
275
276 _log_optimization("removed", opt_counts, opt_reasons)
277 return removed
278
279
280 def replace_tasks(
281 target_task_graph,
282 params,
283 optimizations,
284 do_not_optimize,
285 label_to_taskid,
286 removed_tasks,
287 existing_tasks,
288 index_to_taskid,
289 taskid_to_status,
290 ):
291 """
292 Implement the "Replacing Tasks" phase, returning a set of task labels of
293 all replaced tasks. The replacement taskIds are added to label_to_taskid as
294 a side-effect.
295 """
296 # avoid circular import
297 from taskgraph.optimize.strategies import IndexSearch
298
299 opt_counts = defaultdict(int)
300 replaced = set()
301 dependents_of = target_task_graph.graph.reverse_links_dict()
302 dependencies_of = target_task_graph.graph.links_dict()
303
304 for label in target_task_graph.graph.visit_postorder():
305 logger.debug(f"replace_tasks: {label}")
306 # if we're not allowed to optimize, that's easy..
307 if label in do_not_optimize:
308 logger.debug(f"replace_tasks: {label} is in do_not_optimize")
309 continue
310
311 # if this task depends on un-replaced, un-removed tasks, do not replace
312 if any(
313 l not in replaced and l not in removed_tasks for l in dependencies_of[label]
314 ):
315 logger.debug(
316 f"replace_tasks: {label} depends on an unreplaced or unremoved task"
317 )
318 continue
319
320 # if the task already exists, that's an easy replacement
321 repl = existing_tasks.get(label)
322 if repl:
323 label_to_taskid[label] = repl
324 replaced.add(label)
325 opt_counts["existing_tasks"] += 1
326 logger.debug(f"replace_tasks: {label} replaced from existing_tasks")
327 continue
328
329 # call the optimization strategy
330 task = target_task_graph.tasks[label]
331 opt_by, opt, arg = optimizations(label)
332
333 # compute latest deadline of dependents (if any)
334 dependents = [target_task_graph.tasks[l] for l in dependents_of[label]]
335 deadline = None
336 if dependents:
337 now = datetime.datetime.now(datetime.timezone.utc)
338 deadline = max(
339 resolve_timestamps(now, task.task["deadline"])
340 for task in dependents # type: ignore
341 )
342
343 if isinstance(opt, IndexSearch):
344 arg = arg, index_to_taskid, taskid_to_status
345
346 repl = opt.should_replace_task(task, params, deadline, arg)
347 if repl:
348 if repl is True:
349 logger.debug(f"replace_tasks: {label} removed by optimization strategy")
350 # True means remove this task; get_subgraph will catch any
351 # problems with removed tasks being depended on
352 removed_tasks.add(label)
353 else:
354 logger.debug(
355 f"replace_tasks: {label} replaced with {repl} by optimization strategy"
356 )
357 label_to_taskid[label] = repl
358 replaced.add(label)
359 opt_counts[opt_by] += 1
360 continue
361 else:
362 logger.debug(f"replace_tasks: {label} kept by optimization strategy")
363
364 _log_optimization("replaced", opt_counts)
365 return replaced
366
367
368 def get_subgraph(
369 target_task_graph: TaskGraph,
370 removed_tasks: Set[str],
371 replaced_tasks: Set[str],
372 label_to_taskid: Dict[str, str],
373 decision_task_id: str,
374 ):
375 """
376 Return the subgraph of target_task_graph consisting only of
377 non-optimized tasks and edges between them.
378
379 To avoid losing track of taskIds for tasks optimized away, this method
380 simultaneously substitutes real taskIds for task labels in the graph, and
381 populates each task definition's `dependencies` key with the appropriate
382 taskIds. Task references are resolved in the process.
383 """
384
385 # check for any dependency edges from included to removed tasks
386 bad_edges = [
387 (l, r, n)
388 for l, r, n in target_task_graph.graph.edges
389 if l not in removed_tasks and r in removed_tasks
390 ]
391 if bad_edges:
392 probs = ", ".join(
393 f"{l} depends on {r} as {n} but it has been removed"
394 for l, r, n in bad_edges
395 )
396 raise Exception("Optimization error: " + probs)
397
398 # fill in label_to_taskid for anything not removed or replaced
399 assert replaced_tasks <= set(label_to_taskid)
400 for label in sorted(
401 target_task_graph.graph.nodes - removed_tasks - set(label_to_taskid)
402 ):
403 task_id = slugid()
404 assert isinstance(task_id, str)
405 label_to_taskid[label] = task_id
406
407 # resolve labels to taskIds and populate task['dependencies']
408 tasks_by_taskid = {}
409 named_links_dict = target_task_graph.graph.named_links_dict()
410 omit = removed_tasks | replaced_tasks
411 for label, task in target_task_graph.tasks.items():
412 if label in omit:
413 continue
414 task.task_id = label_to_taskid[label]
415 named_task_dependencies = {
416 name: label_to_taskid[label]
417 for name, label in named_links_dict.get(label, {}).items()
418 }
419
420 # Add remaining soft dependencies
421 if task.soft_dependencies:
422 named_task_dependencies.update(
423 {
424 label: label_to_taskid[label]
425 for label in task.soft_dependencies
426 if label in label_to_taskid and label not in omit
427 }
428 )
429
430 assert task.task_id
431 task.task = resolve_task_references(
432 task.label,
433 task.task,
434 task_id=task.task_id,
435 decision_task_id=decision_task_id,
436 dependencies=named_task_dependencies,
437 )
438 deps = task.task.setdefault("dependencies", [])
439 deps.extend(sorted(named_task_dependencies.values()))
440 tasks_by_taskid[task.task_id] = task
441
442 # resolve edges to taskIds
443 edges_by_taskid = (
444 (label_to_taskid.get(left), label_to_taskid.get(right), name)
445 for (left, right, name) in target_task_graph.graph.edges
446 )
447 # ..and drop edges that are no longer entirely in the task graph
448 # (note that this omits edges to replaced tasks, but they are still in task.dependnecies)
449 edges_by_taskid = {
450 (left, right, name)
451 for (left, right, name) in edges_by_taskid
452 if left in tasks_by_taskid and right in tasks_by_taskid
453 }
454
455 return TaskGraph(tasks_by_taskid, Graph(set(tasks_by_taskid), edges_by_taskid)) # type: ignore
456
457
458 @register_strategy("never")
459 class OptimizationStrategy:
460 def should_remove_task(self, task, params, arg):
461 """Determine whether to optimize this task by removing it. Returns
462 True to remove."""
463 return False
464
465 def should_replace_task(self, task, params, deadline, arg):
466 """Determine whether to optimize this task by replacing it. Returns a
467 taskId to replace this task, True to replace with nothing, or False to
468 keep the task."""
469 return False
470
471
472 @register_strategy("always")
473 class Always(OptimizationStrategy):
474 def should_remove_task(self, task, params, arg):
475 return True
476
477
478 class CompositeStrategy(OptimizationStrategy, metaclass=ABCMeta):
479 def __init__(self, *substrategies, **kwargs):
480 self.substrategies = []
481 missing = set()
482 for sub in substrategies:
483 if isinstance(sub, str):
484 if sub not in registry.keys():
485 missing.add(sub)
486 continue
487 sub = registry[sub]
488
489 self.substrategies.append(sub)
490
491 if missing:
492 raise TypeError(
493 "substrategies aren't registered: {}".format(
494 ", ".join(sorted(missing))
495 )
496 )
497
498 self.split_args = kwargs.pop("split_args", None)
499 if not self.split_args:
500 self.split_args = lambda arg, substrategies: [arg] * len(substrategies)
501 if kwargs:
502 raise TypeError("unexpected keyword args")
503
504 @property
505 @abstractmethod
506 def description(self):
507 """A textual description of the combined substrategies."""
508
509 @abstractmethod
510 def reduce(self, results):
511 """Given all substrategy results as a generator, return the overall
512 result."""
513
514 def _generate_results(self, fname, *args):
515 *passthru, arg = args
516 for sub, arg in zip(
517 self.substrategies, self.split_args(arg, self.substrategies)
518 ):
519 yield getattr(sub, fname)(*passthru, arg)
520
521 def should_remove_task(self, *args):
522 results = self._generate_results("should_remove_task", *args)
523 return self.reduce(results)
524
525 def should_replace_task(self, *args):
526 results = self._generate_results("should_replace_task", *args)
527 return self.reduce(results)
528
529
530 class Any(CompositeStrategy):
531 """Given one or more optimization strategies, remove or replace a task if any of them
532 says to.
533
534 Replacement will use the value returned by the first strategy that says to replace.
535 """
536
537 @property
538 def description(self):
539 return "-or-".join([s.description for s in self.substrategies])
540
541 @classmethod
542 def reduce(cls, results):
543 for rv in results:
544 if rv:
545 return rv
546 return False
547
548
549 class All(CompositeStrategy):
550 """Given one or more optimization strategies, remove or replace a task if all of them
551 says to.
552
553 Replacement will use the value returned by the first strategy passed in.
554 Note the values used for replacement need not be the same, as long as they
555 all say to replace.
556 """
557
558 @property
559 def description(self):
560 return "-and-".join([s.description for s in self.substrategies])
561
562 @classmethod
563 def reduce(cls, results):
564 for rv in results:
565 if not rv:
566 return rv
567 return True
568
569
570 class Alias(CompositeStrategy):
571 """Provides an alias to an existing strategy.
572
573 This can be useful to swap strategies in and out without needing to modify
574 the task transforms.
575 """
576
577 def __init__(self, strategy):
578 super().__init__(strategy)
579
580 @property
581 def description(self):
582 return self.substrategies[0].description
583
584 def reduce(self, results):
585 return next(results)
586
587
588 class Not(CompositeStrategy):
589 """Given a strategy, returns the opposite."""
590
591 def __init__(self, strategy):
592 super().__init__(strategy)
593
594 @property
595 def description(self):
596 return "not-" + self.substrategies[0].description
597
598 def reduce(self, results):
599 return not next(results)
600
601
602 # Trigger registration in sibling modules.
603 import_sibling_modules()