resolvers.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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 backtrack_causes")
  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. backtrack_causes=base.backtrack_causes[:],
  99. )
  100. self._states.append(state)
  101. def _add_to_criteria(self, criteria, requirement, parent):
  102. self._r.adding_requirement(requirement=requirement, parent=parent)
  103. identifier = self._p.identify(requirement_or_candidate=requirement)
  104. criterion = criteria.get(identifier)
  105. if criterion:
  106. incompatibilities = list(criterion.incompatibilities)
  107. else:
  108. incompatibilities = []
  109. matches = self._p.find_matches(
  110. identifier=identifier,
  111. requirements=IteratorMapping(
  112. criteria,
  113. operator.methodcaller("iter_requirement"),
  114. {identifier: [requirement]},
  115. ),
  116. incompatibilities=IteratorMapping(
  117. criteria,
  118. operator.attrgetter("incompatibilities"),
  119. {identifier: incompatibilities},
  120. ),
  121. )
  122. if criterion:
  123. information = list(criterion.information)
  124. information.append(RequirementInformation(requirement, parent))
  125. else:
  126. information = [RequirementInformation(requirement, parent)]
  127. criterion = Criterion(
  128. candidates=build_iter_view(matches),
  129. information=information,
  130. incompatibilities=incompatibilities,
  131. )
  132. if not criterion.candidates:
  133. raise RequirementsConflicted(criterion)
  134. criteria[identifier] = criterion
  135. def _get_preference(self, name):
  136. return self._p.get_preference(
  137. identifier=name,
  138. resolutions=self.state.mapping,
  139. candidates=IteratorMapping(
  140. self.state.criteria,
  141. operator.attrgetter("candidates"),
  142. ),
  143. information=IteratorMapping(
  144. self.state.criteria,
  145. operator.attrgetter("information"),
  146. ),
  147. backtrack_causes=self.state.backtrack_causes,
  148. )
  149. def _is_current_pin_satisfying(self, name, criterion):
  150. try:
  151. current_pin = self.state.mapping[name]
  152. except KeyError:
  153. return False
  154. return all(
  155. self._p.is_satisfied_by(requirement=r, candidate=current_pin)
  156. for r in criterion.iter_requirement()
  157. )
  158. def _get_updated_criteria(self, candidate):
  159. criteria = self.state.criteria.copy()
  160. for requirement in self._p.get_dependencies(candidate=candidate):
  161. self._add_to_criteria(criteria, requirement, parent=candidate)
  162. return criteria
  163. def _attempt_to_pin_criterion(self, name):
  164. criterion = self.state.criteria[name]
  165. causes = []
  166. for candidate in criterion.candidates:
  167. try:
  168. criteria = self._get_updated_criteria(candidate)
  169. except RequirementsConflicted as e:
  170. causes.append(e.criterion)
  171. continue
  172. # Check the newly-pinned candidate actually works. This should
  173. # always pass under normal circumstances, but in the case of a
  174. # faulty provider, we will raise an error to notify the implementer
  175. # to fix find_matches() and/or is_satisfied_by().
  176. satisfied = all(
  177. self._p.is_satisfied_by(requirement=r, candidate=candidate)
  178. for r in criterion.iter_requirement()
  179. )
  180. if not satisfied:
  181. raise InconsistentCandidate(candidate, criterion)
  182. self._r.pinning(candidate=candidate)
  183. self.state.criteria.update(criteria)
  184. # Put newly-pinned candidate at the end. This is essential because
  185. # backtracking looks at this mapping to get the last pin.
  186. self.state.mapping.pop(name, None)
  187. self.state.mapping[name] = candidate
  188. return []
  189. # All candidates tried, nothing works. This criterion is a dead
  190. # end, signal for backtracking.
  191. return causes
  192. def _backtrack(self):
  193. """Perform backtracking.
  194. When we enter here, the stack is like this::
  195. [ state Z ]
  196. [ state Y ]
  197. [ state X ]
  198. .... earlier states are irrelevant.
  199. 1. No pins worked for Z, so it does not have a pin.
  200. 2. We want to reset state Y to unpinned, and pin another candidate.
  201. 3. State X holds what state Y was before the pin, but does not
  202. have the incompatibility information gathered in state Y.
  203. Each iteration of the loop will:
  204. 1. Discard Z.
  205. 2. Discard Y but remember its incompatibility information gathered
  206. previously, and the failure we're dealing with right now.
  207. 3. Push a new state Y' based on X, and apply the incompatibility
  208. information from Y to Y'.
  209. 4a. If this causes Y' to conflict, we need to backtrack again. Make Y'
  210. the new Z and go back to step 2.
  211. 4b. If the incompatibilities apply cleanly, end backtracking.
  212. """
  213. while len(self._states) >= 3:
  214. # Remove the state that triggered backtracking.
  215. del self._states[-1]
  216. # Retrieve the last candidate pin and known incompatibilities.
  217. broken_state = self._states.pop()
  218. name, candidate = broken_state.mapping.popitem()
  219. incompatibilities_from_broken = [
  220. (k, list(v.incompatibilities))
  221. for k, v in broken_state.criteria.items()
  222. ]
  223. # Also mark the newly known incompatibility.
  224. incompatibilities_from_broken.append((name, [candidate]))
  225. self._r.backtracking(candidate=candidate)
  226. # Create a new state from the last known-to-work one, and apply
  227. # the previously gathered incompatibility information.
  228. def _patch_criteria():
  229. for k, incompatibilities in incompatibilities_from_broken:
  230. if not incompatibilities:
  231. continue
  232. try:
  233. criterion = self.state.criteria[k]
  234. except KeyError:
  235. continue
  236. matches = self._p.find_matches(
  237. identifier=k,
  238. requirements=IteratorMapping(
  239. self.state.criteria,
  240. operator.methodcaller("iter_requirement"),
  241. ),
  242. incompatibilities=IteratorMapping(
  243. self.state.criteria,
  244. operator.attrgetter("incompatibilities"),
  245. {k: incompatibilities},
  246. ),
  247. )
  248. candidates = build_iter_view(matches)
  249. if not candidates:
  250. return False
  251. incompatibilities.extend(criterion.incompatibilities)
  252. self.state.criteria[k] = Criterion(
  253. candidates=candidates,
  254. information=list(criterion.information),
  255. incompatibilities=incompatibilities,
  256. )
  257. return True
  258. self._push_new_state()
  259. success = _patch_criteria()
  260. # It works! Let's work on this new state.
  261. if success:
  262. return True
  263. # State does not work after applying known incompatibilities.
  264. # Try the still previous state.
  265. # No way to backtrack anymore.
  266. return False
  267. def resolve(self, requirements, max_rounds):
  268. if self._states:
  269. raise RuntimeError("already resolved")
  270. self._r.starting()
  271. # Initialize the root state.
  272. self._states = [
  273. State(
  274. mapping=collections.OrderedDict(),
  275. criteria={},
  276. backtrack_causes=[],
  277. )
  278. ]
  279. for r in requirements:
  280. try:
  281. self._add_to_criteria(self.state.criteria, r, parent=None)
  282. except RequirementsConflicted as e:
  283. raise ResolutionImpossible(e.criterion.information)
  284. # The root state is saved as a sentinel so the first ever pin can have
  285. # something to backtrack to if it fails. The root state is basically
  286. # pinning the virtual "root" package in the graph.
  287. self._push_new_state()
  288. for round_index in range(max_rounds):
  289. self._r.starting_round(index=round_index)
  290. unsatisfied_names = [
  291. key
  292. for key, criterion in self.state.criteria.items()
  293. if not self._is_current_pin_satisfying(key, criterion)
  294. ]
  295. # All criteria are accounted for. Nothing more to pin, we are done!
  296. if not unsatisfied_names:
  297. self._r.ending(state=self.state)
  298. return self.state
  299. # Choose the most preferred unpinned criterion to try.
  300. name = min(unsatisfied_names, key=self._get_preference)
  301. failure_causes = self._attempt_to_pin_criterion(name)
  302. if failure_causes:
  303. causes = [i for c in failure_causes for i in c.information]
  304. # Backtrack if pinning fails. The backtrack process puts us in
  305. # an unpinned state, so we can work on it in the next round.
  306. self._r.resolving_conflicts(causes=causes)
  307. success = self._backtrack()
  308. self.state.backtrack_causes[:] = causes
  309. # Dead ends everywhere. Give up.
  310. if not success:
  311. raise ResolutionImpossible(self.state.backtrack_causes)
  312. else:
  313. # Pinning was successful. Push a new state to do another pin.
  314. self._push_new_state()
  315. self._r.ending_round(index=round_index, state=self.state)
  316. raise ResolutionTooDeep(max_rounds)
  317. def _has_route_to_root(criteria, key, all_keys, connected):
  318. if key in connected:
  319. return True
  320. if key not in criteria:
  321. return False
  322. for p in criteria[key].iter_parent():
  323. try:
  324. pkey = all_keys[id(p)]
  325. except KeyError:
  326. continue
  327. if pkey in connected:
  328. connected.add(key)
  329. return True
  330. if _has_route_to_root(criteria, pkey, all_keys, connected):
  331. connected.add(key)
  332. return True
  333. return False
  334. Result = collections.namedtuple("Result", "mapping graph criteria")
  335. def _build_result(state):
  336. mapping = state.mapping
  337. all_keys = {id(v): k for k, v in mapping.items()}
  338. all_keys[id(None)] = None
  339. graph = DirectedGraph()
  340. graph.add(None) # Sentinel as root dependencies' parent.
  341. connected = {None}
  342. for key, criterion in state.criteria.items():
  343. if not _has_route_to_root(state.criteria, key, all_keys, connected):
  344. continue
  345. if key not in graph:
  346. graph.add(key)
  347. for p in criterion.iter_parent():
  348. try:
  349. pkey = all_keys[id(p)]
  350. except KeyError:
  351. continue
  352. if pkey not in graph:
  353. graph.add(pkey)
  354. graph.connect(pkey, key)
  355. return Result(
  356. mapping={k: v for k, v in mapping.items() if k in connected},
  357. graph=graph,
  358. criteria=state.criteria,
  359. )
  360. class Resolver(AbstractResolver):
  361. """The thing that performs the actual resolution work."""
  362. base_exception = ResolverException
  363. def resolve(self, requirements, max_rounds=100):
  364. """Take a collection of constraints, spit out the resolution result.
  365. The return value is a representation to the final resolution result. It
  366. is a tuple subclass with three public members:
  367. * `mapping`: A dict of resolved candidates. Each key is an identifier
  368. of a requirement (as returned by the provider's `identify` method),
  369. and the value is the resolved candidate.
  370. * `graph`: A `DirectedGraph` instance representing the dependency tree.
  371. The vertices are keys of `mapping`, and each edge represents *why*
  372. a particular package is included. A special vertex `None` is
  373. included to represent parents of user-supplied requirements.
  374. * `criteria`: A dict of "criteria" that hold detailed information on
  375. how edges in the graph are derived. Each key is an identifier of a
  376. requirement, and the value is a `Criterion` instance.
  377. The following exceptions may be raised if a resolution cannot be found:
  378. * `ResolutionImpossible`: A resolution cannot be found for the given
  379. combination of requirements. The `causes` attribute of the
  380. exception is a list of (requirement, parent), giving the
  381. requirements that could not be satisfied.
  382. * `ResolutionTooDeep`: The dependency tree is too deeply nested and
  383. the resolver gave up. This is usually caused by a circular
  384. dependency, but you can try to resolve this by increasing the
  385. `max_rounds` argument.
  386. """
  387. resolution = Resolution(self.provider, self.reporter)
  388. state = resolution.resolve(requirements, max_rounds=max_rounds)
  389. return _build_result(state)