resolvers.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import collections
  2. from .providers import AbstractResolver
  3. from .structs import DirectedGraph
  4. RequirementInformation = collections.namedtuple(
  5. "RequirementInformation", ["requirement", "parent"]
  6. )
  7. class ResolverException(Exception):
  8. """A base class for all exceptions raised by this module.
  9. Exceptions derived by this class should all be handled in this module. Any
  10. bubbling pass the resolver should be treated as a bug.
  11. """
  12. class RequirementsConflicted(ResolverException):
  13. def __init__(self, criterion):
  14. super(RequirementsConflicted, self).__init__(criterion)
  15. self.criterion = criterion
  16. def __str__(self):
  17. return "Requirements conflict: {}".format(
  18. ", ".join(repr(r) for r in self.criterion.iter_requirement()),
  19. )
  20. class InconsistentCandidate(ResolverException):
  21. def __init__(self, candidate, criterion):
  22. super(InconsistentCandidate, self).__init__(candidate, criterion)
  23. self.candidate = candidate
  24. self.criterion = criterion
  25. def __str__(self):
  26. return "Provided candidate {!r} does not satisfy {}".format(
  27. self.candidate,
  28. ", ".join(repr(r) for r in self.criterion.iter_requirement()),
  29. )
  30. class Criterion(object):
  31. """Representation of possible resolution results of a package.
  32. This holds three attributes:
  33. * `information` is a collection of `RequirementInformation` pairs.
  34. Each pair is a requirement contributing to this criterion, and the
  35. candidate that provides the requirement.
  36. * `incompatibilities` is a collection of all known not-to-work candidates
  37. to exclude from consideration.
  38. * `candidates` is a collection containing all possible candidates deducted
  39. from the union of contributing requirements and known incompatibilities.
  40. It should never be empty, except when the criterion is an attribute of a
  41. raised `RequirementsConflicted` (in which case it is always empty).
  42. .. note::
  43. This class is intended to be externally immutable. **Do not** mutate
  44. any of its attribute containers.
  45. """
  46. def __init__(self, candidates, information, incompatibilities):
  47. self.candidates = candidates
  48. self.information = information
  49. self.incompatibilities = incompatibilities
  50. def __repr__(self):
  51. requirements = ", ".join(
  52. "{!r} from {!r}".format(req, parent)
  53. for req, parent in self.information
  54. )
  55. return "<Criterion {}>".format(requirements)
  56. @classmethod
  57. def from_requirement(cls, provider, requirement, parent):
  58. """Build an instance from a requirement.
  59. """
  60. candidates = provider.find_matches(requirement)
  61. criterion = cls(
  62. candidates=candidates,
  63. information=[RequirementInformation(requirement, parent)],
  64. incompatibilities=[],
  65. )
  66. if not candidates:
  67. raise RequirementsConflicted(criterion)
  68. return criterion
  69. def iter_requirement(self):
  70. return (i.requirement for i in self.information)
  71. def iter_parent(self):
  72. return (i.parent for i in self.information)
  73. def merged_with(self, provider, requirement, parent):
  74. """Build a new instance from this and a new requirement.
  75. """
  76. infos = list(self.information)
  77. infos.append(RequirementInformation(requirement, parent))
  78. candidates = [
  79. c
  80. for c in self.candidates
  81. if provider.is_satisfied_by(requirement, c)
  82. ]
  83. criterion = type(self)(candidates, infos, list(self.incompatibilities))
  84. if not candidates:
  85. raise RequirementsConflicted(criterion)
  86. return criterion
  87. def excluded_of(self, candidate):
  88. """Build a new instance from this, but excluding specified candidate.
  89. Returns the new instance, or None if we still have no valid candidates.
  90. """
  91. incompats = list(self.incompatibilities)
  92. incompats.append(candidate)
  93. candidates = [c for c in self.candidates if c != candidate]
  94. if not candidates:
  95. return None
  96. criterion = type(self)(candidates, list(self.information), incompats)
  97. return criterion
  98. class ResolutionError(ResolverException):
  99. pass
  100. class ResolutionImpossible(ResolutionError):
  101. def __init__(self, causes):
  102. super(ResolutionImpossible, self).__init__(causes)
  103. # causes is a list of RequirementInformation objects
  104. self.causes = causes
  105. class ResolutionTooDeep(ResolutionError):
  106. def __init__(self, round_count):
  107. super(ResolutionTooDeep, self).__init__(round_count)
  108. self.round_count = round_count
  109. # Resolution state in a round.
  110. State = collections.namedtuple("State", "mapping criteria")
  111. class Resolution(object):
  112. """Stateful resolution object.
  113. This is designed as a one-off object that holds information to kick start
  114. the resolution process, and holds the results afterwards.
  115. """
  116. def __init__(self, provider, reporter):
  117. self._p = provider
  118. self._r = reporter
  119. self._states = []
  120. @property
  121. def state(self):
  122. try:
  123. return self._states[-1]
  124. except IndexError:
  125. raise AttributeError("state")
  126. def _push_new_state(self):
  127. """Push a new state into history.
  128. This new state will be used to hold resolution results of the next
  129. coming round.
  130. """
  131. try:
  132. base = self._states[-1]
  133. except IndexError:
  134. state = State(mapping=collections.OrderedDict(), criteria={})
  135. else:
  136. state = State(
  137. mapping=base.mapping.copy(), criteria=base.criteria.copy(),
  138. )
  139. self._states.append(state)
  140. def _merge_into_criterion(self, requirement, parent):
  141. self._r.adding_requirement(requirement)
  142. name = self._p.identify(requirement)
  143. try:
  144. crit = self.state.criteria[name]
  145. except KeyError:
  146. crit = Criterion.from_requirement(self._p, requirement, parent)
  147. else:
  148. crit = crit.merged_with(self._p, requirement, parent)
  149. return name, crit
  150. def _get_criterion_item_preference(self, item):
  151. name, criterion = item
  152. try:
  153. pinned = self.state.mapping[name]
  154. except KeyError:
  155. pinned = None
  156. return self._p.get_preference(
  157. pinned, criterion.candidates, criterion.information,
  158. )
  159. def _is_current_pin_satisfying(self, name, criterion):
  160. try:
  161. current_pin = self.state.mapping[name]
  162. except KeyError:
  163. return False
  164. return all(
  165. self._p.is_satisfied_by(r, current_pin)
  166. for r in criterion.iter_requirement()
  167. )
  168. def _get_criteria_to_update(self, candidate):
  169. criteria = {}
  170. for r in self._p.get_dependencies(candidate):
  171. name, crit = self._merge_into_criterion(r, parent=candidate)
  172. criteria[name] = crit
  173. return criteria
  174. def _attempt_to_pin_criterion(self, name, criterion):
  175. causes = []
  176. for candidate in reversed(criterion.candidates):
  177. try:
  178. criteria = self._get_criteria_to_update(candidate)
  179. except RequirementsConflicted as e:
  180. causes.append(e.criterion)
  181. continue
  182. # Put newly-pinned candidate at the end. This is essential because
  183. # backtracking looks at this mapping to get the last pin.
  184. self._r.pinning(candidate)
  185. self.state.mapping.pop(name, None)
  186. self.state.mapping[name] = candidate
  187. self.state.criteria.update(criteria)
  188. # Check the newly-pinned candidate actually works. This should
  189. # always pass under normal circumstances, but in the case of a
  190. # faulty provider, we will raise an error to notify the implementer
  191. # to fix find_matches() and/or is_satisfied_by().
  192. if not self._is_current_pin_satisfying(name, criterion):
  193. raise InconsistentCandidate(candidate, criterion)
  194. return []
  195. # All candidates tried, nothing works. This criterion is a dead
  196. # end, signal for backtracking.
  197. return causes
  198. def _backtrack(self):
  199. # We need at least 3 states here:
  200. # (a) One known not working, to drop.
  201. # (b) One to backtrack to.
  202. # (c) One to restore state (b) to its state prior to candidate-pinning,
  203. # so we can pin another one instead.
  204. while len(self._states) >= 3:
  205. del self._states[-1]
  206. # Retract the last candidate pin, and create a new (b).
  207. name, candidate = self._states.pop().mapping.popitem()
  208. self._r.backtracking(candidate)
  209. self._push_new_state()
  210. # Mark the retracted candidate as incompatible.
  211. criterion = self.state.criteria[name].excluded_of(candidate)
  212. if criterion is None:
  213. # This state still does not work. Try the still previous state.
  214. continue
  215. self.state.criteria[name] = criterion
  216. return True
  217. return False
  218. def resolve(self, requirements, max_rounds):
  219. if self._states:
  220. raise RuntimeError("already resolved")
  221. self._push_new_state()
  222. for r in requirements:
  223. try:
  224. name, crit = self._merge_into_criterion(r, parent=None)
  225. except RequirementsConflicted as e:
  226. raise ResolutionImpossible(e.criterion.information)
  227. self.state.criteria[name] = crit
  228. self._r.starting()
  229. for round_index in range(max_rounds):
  230. self._r.starting_round(round_index)
  231. self._push_new_state()
  232. curr = self.state
  233. unsatisfied_criterion_items = [
  234. item
  235. for item in self.state.criteria.items()
  236. if not self._is_current_pin_satisfying(*item)
  237. ]
  238. # All criteria are accounted for. Nothing more to pin, we are done!
  239. if not unsatisfied_criterion_items:
  240. del self._states[-1]
  241. self._r.ending(curr)
  242. return self.state
  243. # Choose the most preferred unpinned criterion to try.
  244. name, criterion = min(
  245. unsatisfied_criterion_items,
  246. key=self._get_criterion_item_preference,
  247. )
  248. failure_causes = self._attempt_to_pin_criterion(name, criterion)
  249. # Backtrack if pinning fails.
  250. if failure_causes:
  251. result = self._backtrack()
  252. if not result:
  253. causes = [
  254. i for crit in failure_causes for i in crit.information
  255. ]
  256. raise ResolutionImpossible(causes)
  257. self._r.ending_round(round_index, curr)
  258. raise ResolutionTooDeep(max_rounds)
  259. def _has_route_to_root(criteria, key, all_keys, connected):
  260. if key in connected:
  261. return True
  262. if key not in criteria:
  263. return False
  264. for p in criteria[key].iter_parent():
  265. try:
  266. pkey = all_keys[id(p)]
  267. except KeyError:
  268. continue
  269. if pkey in connected:
  270. connected.add(key)
  271. return True
  272. if _has_route_to_root(criteria, pkey, all_keys, connected):
  273. connected.add(key)
  274. return True
  275. return False
  276. Result = collections.namedtuple("Result", "mapping graph criteria")
  277. def _build_result(state):
  278. mapping = state.mapping
  279. all_keys = {id(v): k for k, v in mapping.items()}
  280. all_keys[id(None)] = None
  281. graph = DirectedGraph()
  282. graph.add(None) # Sentinel as root dependencies' parent.
  283. connected = {None}
  284. for key, criterion in state.criteria.items():
  285. if not _has_route_to_root(state.criteria, key, all_keys, connected):
  286. continue
  287. if key not in graph:
  288. graph.add(key)
  289. for p in criterion.iter_parent():
  290. try:
  291. pkey = all_keys[id(p)]
  292. except KeyError:
  293. continue
  294. if pkey not in graph:
  295. graph.add(pkey)
  296. graph.connect(pkey, key)
  297. return Result(
  298. mapping={k: v for k, v in mapping.items() if k in connected},
  299. graph=graph,
  300. criteria=state.criteria,
  301. )
  302. class Resolver(AbstractResolver):
  303. """The thing that performs the actual resolution work.
  304. """
  305. base_exception = ResolverException
  306. def resolve(self, requirements, max_rounds=100):
  307. """Take a collection of constraints, spit out the resolution result.
  308. The return value is a representation to the final resolution result. It
  309. is a tuple subclass with three public members:
  310. * `mapping`: A dict of resolved candidates. Each key is an identifier
  311. of a requirement (as returned by the provider's `identify` method),
  312. and the value is the resolved candidate.
  313. * `graph`: A `DirectedGraph` instance representing the dependency tree.
  314. The vertices are keys of `mapping`, and each edge represents *why*
  315. a particular package is included. A special vertex `None` is
  316. included to represent parents of user-supplied requirements.
  317. * `criteria`: A dict of "criteria" that hold detailed information on
  318. how edges in the graph are derived. Each key is an identifier of a
  319. requirement, and the value is a `Criterion` instance.
  320. The following exceptions may be raised if a resolution cannot be found:
  321. * `ResolutionImpossible`: A resolution cannot be found for the given
  322. combination of requirements. The `causes` attribute of the
  323. exception is a list of (requirement, parent), giving the
  324. requirements that could not be satisfied.
  325. * `ResolutionTooDeep`: The dependency tree is too deeply nested and
  326. the resolver gave up. This is usually caused by a circular
  327. dependency, but you can try to resolve this by increasing the
  328. `max_rounds` argument.
  329. """
  330. resolution = Resolution(self.provider, self.reporter)
  331. state = resolution.resolve(requirements, max_rounds=max_rounds)
  332. return _build_result(state)