resolvers.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. import collections
  2. import operator
  3. from .providers import AbstractResolver
  4. from .structs import DirectedGraph, IteratorMapping, build_iter_view
  5. RequirementInformation = collections.namedtuple(
  6. "RequirementInformation", ["requirement", "parent"]
  7. )
  8. class ResolverException(Exception):
  9. """A base class for all exceptions raised by this module.
  10. Exceptions derived by this class should all be handled in this module. Any
  11. bubbling pass the resolver should be treated as a bug.
  12. """
  13. class RequirementsConflicted(ResolverException):
  14. def __init__(self, criterion):
  15. super(RequirementsConflicted, self).__init__(criterion)
  16. self.criterion = criterion
  17. def __str__(self):
  18. return "Requirements conflict: {}".format(
  19. ", ".join(repr(r) for r in self.criterion.iter_requirement()),
  20. )
  21. class InconsistentCandidate(ResolverException):
  22. def __init__(self, candidate, criterion):
  23. super(InconsistentCandidate, self).__init__(candidate, criterion)
  24. self.candidate = candidate
  25. self.criterion = criterion
  26. def __str__(self):
  27. return "Provided candidate {!r} does not satisfy {}".format(
  28. self.candidate,
  29. ", ".join(repr(r) for r in self.criterion.iter_requirement()),
  30. )
  31. class Criterion(object):
  32. """Representation of possible resolution results of a package.
  33. This holds three attributes:
  34. * `information` is a collection of `RequirementInformation` pairs.
  35. Each pair is a requirement contributing to this criterion, and the
  36. candidate that provides the requirement.
  37. * `incompatibilities` is a collection of all known not-to-work candidates
  38. to exclude from consideration.
  39. * `candidates` is a collection containing all possible candidates deducted
  40. from the union of contributing requirements and known incompatibilities.
  41. It should never be empty, except when the criterion is an attribute of a
  42. raised `RequirementsConflicted` (in which case it is always empty).
  43. .. note::
  44. This class is intended to be externally immutable. **Do not** mutate
  45. any of its attribute containers.
  46. """
  47. def __init__(self, candidates, information, incompatibilities):
  48. self.candidates = candidates
  49. self.information = information
  50. self.incompatibilities = incompatibilities
  51. def __repr__(self):
  52. requirements = ", ".join(
  53. "({!r}, via={!r})".format(req, parent)
  54. for req, parent in self.information
  55. )
  56. return "Criterion({})".format(requirements)
  57. def iter_requirement(self):
  58. return (i.requirement for i in self.information)
  59. def iter_parent(self):
  60. return (i.parent for i in self.information)
  61. class ResolutionError(ResolverException):
  62. pass
  63. class ResolutionImpossible(ResolutionError):
  64. def __init__(self, causes):
  65. super(ResolutionImpossible, self).__init__(causes)
  66. # causes is a list of RequirementInformation objects
  67. self.causes = causes
  68. class ResolutionTooDeep(ResolutionError):
  69. def __init__(self, round_count):
  70. super(ResolutionTooDeep, self).__init__(round_count)
  71. self.round_count = round_count
  72. # Resolution state in a round.
  73. State = collections.namedtuple("State", "mapping criteria")
  74. class Resolution(object):
  75. """Stateful resolution object.
  76. This is designed as a one-off object that holds information to kick start
  77. the resolution process, and holds the results afterwards.
  78. """
  79. def __init__(self, provider, reporter):
  80. self._p = provider
  81. self._r = reporter
  82. self._states = []
  83. @property
  84. def state(self):
  85. try:
  86. return self._states[-1]
  87. except IndexError:
  88. raise AttributeError("state")
  89. def _push_new_state(self):
  90. """Push a new state into history.
  91. This new state will be used to hold resolution results of the next
  92. coming round.
  93. """
  94. base = self._states[-1]
  95. state = State(
  96. mapping=base.mapping.copy(),
  97. criteria=base.criteria.copy(),
  98. )
  99. self._states.append(state)
  100. def _add_to_criteria(self, criteria, requirement, parent):
  101. self._r.adding_requirement(requirement=requirement, parent=parent)
  102. identifier = self._p.identify(requirement_or_candidate=requirement)
  103. criterion = criteria.get(identifier)
  104. if criterion:
  105. incompatibilities = list(criterion.incompatibilities)
  106. else:
  107. incompatibilities = []
  108. matches = self._p.find_matches(
  109. identifier=identifier,
  110. requirements=IteratorMapping(
  111. criteria,
  112. operator.methodcaller("iter_requirement"),
  113. {identifier: [requirement]},
  114. ),
  115. incompatibilities=IteratorMapping(
  116. criteria,
  117. operator.attrgetter("incompatibilities"),
  118. {identifier: incompatibilities},
  119. ),
  120. )
  121. if criterion:
  122. information = list(criterion.information)
  123. information.append(RequirementInformation(requirement, parent))
  124. else:
  125. information = [RequirementInformation(requirement, parent)]
  126. criterion = Criterion(
  127. candidates=build_iter_view(matches),
  128. information=information,
  129. incompatibilities=incompatibilities,
  130. )
  131. if not criterion.candidates:
  132. raise RequirementsConflicted(criterion)
  133. criteria[identifier] = criterion
  134. def _get_preference(self, name):
  135. return self._p.get_preference(
  136. identifier=name,
  137. resolutions=self.state.mapping,
  138. candidates=IteratorMapping(
  139. self.state.criteria,
  140. operator.attrgetter("candidates"),
  141. ),
  142. information=IteratorMapping(
  143. self.state.criteria,
  144. operator.attrgetter("information"),
  145. ),
  146. )
  147. def _is_current_pin_satisfying(self, name, criterion):
  148. try:
  149. current_pin = self.state.mapping[name]
  150. except KeyError:
  151. return False
  152. return all(
  153. self._p.is_satisfied_by(requirement=r, candidate=current_pin)
  154. for r in criterion.iter_requirement()
  155. )
  156. def _get_updated_criteria(self, candidate):
  157. criteria = self.state.criteria.copy()
  158. for requirement in self._p.get_dependencies(candidate=candidate):
  159. self._add_to_criteria(criteria, requirement, parent=candidate)
  160. return criteria
  161. def _attempt_to_pin_criterion(self, name):
  162. criterion = self.state.criteria[name]
  163. causes = []
  164. for candidate in criterion.candidates:
  165. try:
  166. criteria = self._get_updated_criteria(candidate)
  167. except RequirementsConflicted as e:
  168. causes.append(e.criterion)
  169. continue
  170. # Check the newly-pinned candidate actually works. This should
  171. # always pass under normal circumstances, but in the case of a
  172. # faulty provider, we will raise an error to notify the implementer
  173. # to fix find_matches() and/or is_satisfied_by().
  174. satisfied = all(
  175. self._p.is_satisfied_by(requirement=r, candidate=candidate)
  176. for r in criterion.iter_requirement()
  177. )
  178. if not satisfied:
  179. raise InconsistentCandidate(candidate, criterion)
  180. self._r.pinning(candidate=candidate)
  181. self.state.criteria.update(criteria)
  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.state.mapping.pop(name, None)
  185. self.state.mapping[name] = candidate
  186. return []
  187. # All candidates tried, nothing works. This criterion is a dead
  188. # end, signal for backtracking.
  189. return causes
  190. def _backtrack(self):
  191. """Perform backtracking.
  192. When we enter here, the stack is like this::
  193. [ state Z ]
  194. [ state Y ]
  195. [ state X ]
  196. .... earlier states are irrelevant.
  197. 1. No pins worked for Z, so it does not have a pin.
  198. 2. We want to reset state Y to unpinned, and pin another candidate.
  199. 3. State X holds what state Y was before the pin, but does not
  200. have the incompatibility information gathered in state Y.
  201. Each iteration of the loop will:
  202. 1. Discard Z.
  203. 2. Discard Y but remember its incompatibility information gathered
  204. previously, and the failure we're dealing with right now.
  205. 3. Push a new state Y' based on X, and apply the incompatibility
  206. information from Y to Y'.
  207. 4a. If this causes Y' to conflict, we need to backtrack again. Make Y'
  208. the new Z and go back to step 2.
  209. 4b. If the incompatibilities apply cleanly, end backtracking.
  210. """
  211. while len(self._states) >= 3:
  212. # Remove the state that triggered backtracking.
  213. del self._states[-1]
  214. # Retrieve the last candidate pin and known incompatibilities.
  215. broken_state = self._states.pop()
  216. name, candidate = broken_state.mapping.popitem()
  217. incompatibilities_from_broken = [
  218. (k, list(v.incompatibilities))
  219. for k, v in broken_state.criteria.items()
  220. ]
  221. # Also mark the newly known incompatibility.
  222. incompatibilities_from_broken.append((name, [candidate]))
  223. self._r.backtracking(candidate=candidate)
  224. # Create a new state from the last known-to-work one, and apply
  225. # the previously gathered incompatibility information.
  226. def _patch_criteria():
  227. for k, incompatibilities in incompatibilities_from_broken:
  228. if not incompatibilities:
  229. continue
  230. try:
  231. criterion = self.state.criteria[k]
  232. except KeyError:
  233. continue
  234. matches = self._p.find_matches(
  235. identifier=k,
  236. requirements=IteratorMapping(
  237. self.state.criteria,
  238. operator.methodcaller("iter_requirement"),
  239. ),
  240. incompatibilities=IteratorMapping(
  241. self.state.criteria,
  242. operator.attrgetter("incompatibilities"),
  243. {k: incompatibilities},
  244. ),
  245. )
  246. candidates = build_iter_view(matches)
  247. if not candidates:
  248. return False
  249. incompatibilities.extend(criterion.incompatibilities)
  250. self.state.criteria[k] = Criterion(
  251. candidates=candidates,
  252. information=list(criterion.information),
  253. incompatibilities=incompatibilities,
  254. )
  255. return True
  256. self._push_new_state()
  257. success = _patch_criteria()
  258. # It works! Let's work on this new state.
  259. if success:
  260. return True
  261. # State does not work after applying known incompatibilities.
  262. # Try the still previous state.
  263. # No way to backtrack anymore.
  264. return False
  265. def resolve(self, requirements, max_rounds):
  266. if self._states:
  267. raise RuntimeError("already resolved")
  268. self._r.starting()
  269. # Initialize the root state.
  270. self._states = [State(mapping=collections.OrderedDict(), criteria={})]
  271. for r in requirements:
  272. try:
  273. self._add_to_criteria(self.state.criteria, r, parent=None)
  274. except RequirementsConflicted as e:
  275. raise ResolutionImpossible(e.criterion.information)
  276. # The root state is saved as a sentinel so the first ever pin can have
  277. # something to backtrack to if it fails. The root state is basically
  278. # pinning the virtual "root" package in the graph.
  279. self._push_new_state()
  280. for round_index in range(max_rounds):
  281. self._r.starting_round(index=round_index)
  282. unsatisfied_names = [
  283. key
  284. for key, criterion in self.state.criteria.items()
  285. if not self._is_current_pin_satisfying(key, criterion)
  286. ]
  287. # All criteria are accounted for. Nothing more to pin, we are done!
  288. if not unsatisfied_names:
  289. self._r.ending(state=self.state)
  290. return self.state
  291. # Choose the most preferred unpinned criterion to try.
  292. name = min(unsatisfied_names, key=self._get_preference)
  293. failure_causes = self._attempt_to_pin_criterion(name)
  294. if failure_causes:
  295. # Backtrack if pinning fails. The backtrack process puts us in
  296. # an unpinned state, so we can work on it in the next round.
  297. success = self._backtrack()
  298. # Dead ends everywhere. Give up.
  299. if not success:
  300. causes = [i for c in failure_causes for i in c.information]
  301. raise ResolutionImpossible(causes)
  302. else:
  303. # Pinning was successful. Push a new state to do another pin.
  304. self._push_new_state()
  305. self._r.ending_round(index=round_index, state=self.state)
  306. raise ResolutionTooDeep(max_rounds)
  307. def _has_route_to_root(criteria, key, all_keys, connected):
  308. if key in connected:
  309. return True
  310. if key not in criteria:
  311. return False
  312. for p in criteria[key].iter_parent():
  313. try:
  314. pkey = all_keys[id(p)]
  315. except KeyError:
  316. continue
  317. if pkey in connected:
  318. connected.add(key)
  319. return True
  320. if _has_route_to_root(criteria, pkey, all_keys, connected):
  321. connected.add(key)
  322. return True
  323. return False
  324. Result = collections.namedtuple("Result", "mapping graph criteria")
  325. def _build_result(state):
  326. mapping = state.mapping
  327. all_keys = {id(v): k for k, v in mapping.items()}
  328. all_keys[id(None)] = None
  329. graph = DirectedGraph()
  330. graph.add(None) # Sentinel as root dependencies' parent.
  331. connected = {None}
  332. for key, criterion in state.criteria.items():
  333. if not _has_route_to_root(state.criteria, key, all_keys, connected):
  334. continue
  335. if key not in graph:
  336. graph.add(key)
  337. for p in criterion.iter_parent():
  338. try:
  339. pkey = all_keys[id(p)]
  340. except KeyError:
  341. continue
  342. if pkey not in graph:
  343. graph.add(pkey)
  344. graph.connect(pkey, key)
  345. return Result(
  346. mapping={k: v for k, v in mapping.items() if k in connected},
  347. graph=graph,
  348. criteria=state.criteria,
  349. )
  350. class Resolver(AbstractResolver):
  351. """The thing that performs the actual resolution work."""
  352. base_exception = ResolverException
  353. def resolve(self, requirements, max_rounds=100):
  354. """Take a collection of constraints, spit out the resolution result.
  355. The return value is a representation to the final resolution result. It
  356. is a tuple subclass with three public members:
  357. * `mapping`: A dict of resolved candidates. Each key is an identifier
  358. of a requirement (as returned by the provider's `identify` method),
  359. and the value is the resolved candidate.
  360. * `graph`: A `DirectedGraph` instance representing the dependency tree.
  361. The vertices are keys of `mapping`, and each edge represents *why*
  362. a particular package is included. A special vertex `None` is
  363. included to represent parents of user-supplied requirements.
  364. * `criteria`: A dict of "criteria" that hold detailed information on
  365. how edges in the graph are derived. Each key is an identifier of a
  366. requirement, and the value is a `Criterion` instance.
  367. The following exceptions may be raised if a resolution cannot be found:
  368. * `ResolutionImpossible`: A resolution cannot be found for the given
  369. combination of requirements. The `causes` attribute of the
  370. exception is a list of (requirement, parent), giving the
  371. requirements that could not be satisfied.
  372. * `ResolutionTooDeep`: The dependency tree is too deeply nested and
  373. the resolver gave up. This is usually caused by a circular
  374. dependency, but you can try to resolve this by increasing the
  375. `max_rounds` argument.
  376. """
  377. resolution = Resolution(self.provider, self.reporter)
  378. state = resolution.resolve(requirements, max_rounds=max_rounds)
  379. return _build_result(state)