Voice et bot modif

This commit is contained in:
pi 2026-06-16 17:09:34 +00:00
parent 189d56026b
commit 7333a22bcd
10774 changed files with 634644 additions and 933308 deletions

View file

@ -1,13 +0,0 @@
Copyright (c) 2018, Tzu-ping Chung <uranusjr@gmail.com>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View file

@ -1,23 +1,22 @@
__all__ = [
"__version__",
"AbstractProvider",
"AbstractResolver",
"BaseReporter",
"InconsistentCandidate",
"Resolver",
"RequirementsConflicted",
"ResolutionError",
"ResolutionImpossible",
"ResolutionTooDeep",
"Resolver",
"__version__",
]
__version__ = "1.2.1"
__version__ = "1.0.1"
from .providers import AbstractProvider
from .providers import AbstractProvider, AbstractResolver
from .reporters import BaseReporter
from .resolvers import (
AbstractResolver,
InconsistentCandidate,
RequirementsConflicted,
ResolutionError,

View file

@ -0,0 +1,6 @@
__all__ = ["Mapping", "Sequence"]
try:
from collections.abc import Mapping, Sequence
except ImportError:
from collections import Mapping, Sequence

View file

@ -1,58 +1,30 @@
from __future__ import annotations
from typing import (
TYPE_CHECKING,
Generic,
Iterable,
Iterator,
Mapping,
Sequence,
)
from .structs import CT, KT, RT, Matches, RequirementInformation
if TYPE_CHECKING:
from typing import Any, Protocol
class Preference(Protocol):
def __lt__(self, __other: Any) -> bool: ...
class AbstractProvider(Generic[RT, CT, KT]):
class AbstractProvider(object):
"""Delegate class to provide the required interface for the resolver."""
def identify(self, requirement_or_candidate: RT | CT) -> KT:
"""Given a requirement or candidate, return an identifier for it.
def identify(self, requirement_or_candidate):
"""Given a requirement, return an identifier for it.
This is used to identify, e.g. whether two requirements
should have their specifier parts merged or a candidate matches a
requirement via ``find_matches()``.
This is used to identify a requirement, e.g. whether two requirements
should have their specifier parts merged.
"""
raise NotImplementedError
def get_preference(
self,
identifier: KT,
resolutions: Mapping[KT, CT],
candidates: Mapping[KT, Iterator[CT]],
information: Mapping[KT, Iterator[RequirementInformation[RT, CT]]],
backtrack_causes: Sequence[RequirementInformation[RT, CT]],
) -> Preference:
identifier,
resolutions,
candidates,
information,
backtrack_causes,
):
"""Produce a sort key for given requirement based on preference.
As this is a sort key it will be called O(n) times per backtrack
step, where n is the number of `identifier`s, if you have a check
which is expensive in some sense. E.g. It needs to make O(n) checks
per call or takes significant wall clock time, consider using
`narrow_requirement_selection` to filter the `identifier`s, which
is applied before this sort key is called.
The preference is defined as "I think this requirement should be
resolved first". The lower the return value is, the more preferred
this group of arguments is.
:param identifier: An identifier as returned by ``identify()``. This
identifies the requirement being considered.
identifies the dependency matches which should be returned.
:param resolutions: Mapping of candidates currently pinned by the
resolver. Each key is an identifier, and the value is a candidate.
The candidate may conflict with requirements from ``information``.
@ -60,9 +32,8 @@ class AbstractProvider(Generic[RT, CT, KT]):
Each value is an iterator of candidates.
:param information: Mapping of requirement information of each package.
Each value is an iterator of *requirement information*.
:param backtrack_causes: Sequence of *requirement information* that are
the requirements that caused the resolver to most recently
backtrack.
:param backtrack_causes: Sequence of requirement information that were
the requirements that caused the resolver to most recently backtrack.
A *requirement information* instance is a named tuple with two members:
@ -89,21 +60,15 @@ class AbstractProvider(Generic[RT, CT, KT]):
"""
raise NotImplementedError
def find_matches(
self,
identifier: KT,
requirements: Mapping[KT, Iterator[RT]],
incompatibilities: Mapping[KT, Iterator[CT]],
) -> Matches[CT]:
def find_matches(self, identifier, requirements, incompatibilities):
"""Find all possible candidates that satisfy the given constraints.
:param identifier: An identifier as returned by ``identify()``. All
candidates returned by this method should produce the same
identifier.
:param identifier: An identifier as returned by ``identify()``. This
identifies the dependency matches of which should be returned.
:param requirements: A mapping of requirements that all returned
candidates must satisfy. Each key is an identifier, and the value
an iterator of requirements for that dependency.
:param incompatibilities: A mapping of known incompatibile candidates of
:param incompatibilities: A mapping of known incompatibilities of
each dependency. Each key is an identifier, and the value an
iterator of incompatibilities known to the resolver. All
incompatibilities *must* be excluded from the return value.
@ -124,7 +89,7 @@ class AbstractProvider(Generic[RT, CT, KT]):
"""
raise NotImplementedError
def is_satisfied_by(self, requirement: RT, candidate: CT) -> bool:
def is_satisfied_by(self, requirement, candidate):
"""Whether the given requirement can be satisfied by a candidate.
The candidate is guaranteed to have been generated from the
@ -135,7 +100,7 @@ class AbstractProvider(Generic[RT, CT, KT]):
"""
raise NotImplementedError
def get_dependencies(self, candidate: CT) -> Iterable[RT]:
def get_dependencies(self, candidate):
"""Get dependencies of a candidate.
This should return a collection of requirements that `candidate`
@ -143,54 +108,26 @@ class AbstractProvider(Generic[RT, CT, KT]):
"""
raise NotImplementedError
def narrow_requirement_selection(
self,
identifiers: Iterable[KT],
resolutions: Mapping[KT, CT],
candidates: Mapping[KT, Iterator[CT]],
information: Mapping[KT, Iterator[RequirementInformation[RT, CT]]],
backtrack_causes: Sequence[RequirementInformation[RT, CT]],
) -> Iterable[KT]:
class AbstractResolver(object):
"""The thing that performs the actual resolution work."""
base_exception = Exception
def __init__(self, provider, reporter):
self.provider = provider
self.reporter = reporter
def resolve(self, requirements, **kwargs):
"""Take a collection of constraints, spit out the resolution result.
This returns a representation of the final resolution state, with one
guarenteed attribute ``mapping`` that contains resolved candidates as
values. The keys are their respective identifiers.
:param requirements: A collection of constraints.
:param kwargs: Additional keyword arguments that subclasses may accept.
:raises: ``self.base_exception`` or its subclass.
"""
An optional method to narrow the selection of requirements being
considered during resolution. This method is called O(1) time per
backtrack step.
:param identifiers: An iterable of `identifiers` as returned by
``identify()``. These identify all requirements currently being
considered.
:param resolutions: A mapping of candidates currently pinned by the
resolver. Each key is an identifier, and the value is a candidate
that may conflict with requirements from ``information``.
:param candidates: A mapping of each dependency's possible candidates.
Each value is an iterator of candidates.
:param information: A mapping of requirement information for each package.
Each value is an iterator of *requirement information*.
:param backtrack_causes: A sequence of *requirement information* that are
the requirements causing the resolver to most recently
backtrack.
A *requirement information* instance is a named tuple with two members:
* ``requirement`` specifies a requirement contributing to the current
list of candidates.
* ``parent`` specifies the candidate that provides (is depended on for)
the requirement, or ``None`` to indicate a root requirement.
Must return a non-empty subset of `identifiers`, with the default
implementation being to return `identifiers` unchanged. Those `identifiers`
will then be passed to the sort key `get_preference` to pick the most
prefered requirement to attempt to pin, unless `narrow_requirement_selection`
returns only 1 requirement, in which case that will be used without
calling the sort key `get_preference`.
This method is designed to be used by the provider to optimize the
dependency resolution, e.g. if a check cost is O(m) and it can be done
against all identifiers at once then filtering the requirement selection
here will cost O(m) but making it part of the sort key in `get_preference`
will cost O(m*n), where n is the number of `identifiers`.
Returns:
Iterable[KT]: A non-empty subset of `identifiers`.
"""
return identifiers
raise NotImplementedError

View file

@ -1,36 +1,26 @@
from __future__ import annotations
class BaseReporter(object):
"""Delegate class to provider progress reporting for the resolver."""
from typing import TYPE_CHECKING, Collection, Generic
from .structs import CT, KT, RT, RequirementInformation, State
if TYPE_CHECKING:
from .resolvers import Criterion
class BaseReporter(Generic[RT, CT, KT]):
"""Delegate class to provide progress reporting for the resolver."""
def starting(self) -> None:
def starting(self):
"""Called before the resolution actually starts."""
def starting_round(self, index: int) -> None:
def starting_round(self, index):
"""Called before each round of resolution starts.
The index is zero-based.
"""
def ending_round(self, index: int, state: State[RT, CT, KT]) -> None:
def ending_round(self, index, state):
"""Called before each round of resolution ends.
This is NOT called if the resolution ends at this round. Use `ending`
if you want to report finalization. The index is zero-based.
"""
def ending(self, state: State[RT, CT, KT]) -> None:
def ending(self, state):
"""Called before the resolution ends successfully."""
def adding_requirement(self, requirement: RT, parent: CT | None) -> None:
def adding_requirement(self, requirement, parent):
"""Called when adding a new requirement into the resolve criteria.
:param requirement: The additional requirement to be applied to filter
@ -40,16 +30,14 @@ class BaseReporter(Generic[RT, CT, KT]):
requirements passed in from ``Resolver.resolve()``.
"""
def resolving_conflicts(
self, causes: Collection[RequirementInformation[RT, CT]]
) -> None:
def resolving_conflicts(self, causes):
"""Called when starting to attempt requirement conflict resolution.
:param causes: The information on the collision that caused the backtracking.
"""
def rejecting_candidate(self, criterion: Criterion[RT, CT], candidate: CT) -> None:
def rejecting_candidate(self, criterion, candidate):
"""Called when rejecting a candidate during backtracking."""
def pinning(self, candidate: CT) -> None:
def pinning(self, candidate):
"""Called when adding a candidate to the potential solution."""

View file

@ -1,99 +1,127 @@
from __future__ import annotations
import collections
import itertools
import operator
from typing import TYPE_CHECKING, Generic
from ..structs import (
CT,
KT,
RT,
DirectedGraph,
IterableView,
IteratorMapping,
RequirementInformation,
State,
build_iter_view,
)
from .abstract import AbstractResolver, Result
from .criterion import Criterion
from .exceptions import (
InconsistentCandidate,
RequirementsConflicted,
ResolutionImpossible,
ResolutionTooDeep,
ResolverException,
from .providers import AbstractResolver
from .structs import DirectedGraph, IteratorMapping, build_iter_view
RequirementInformation = collections.namedtuple(
"RequirementInformation", ["requirement", "parent"]
)
if TYPE_CHECKING:
from collections.abc import Collection, Iterable, Mapping
from ..providers import AbstractProvider, Preference
from ..reporters import BaseReporter
class ResolverException(Exception):
"""A base class for all exceptions raised by this module.
_OPTIMISTIC_BACKJUMPING_RATIO: float = 0.1
Exceptions derived by this class should all be handled in this module. Any
bubbling pass the resolver should be treated as a bug.
"""
def _build_result(state: State[RT, CT, KT]) -> Result[RT, CT, KT]:
mapping = state.mapping
all_keys: dict[int, KT | None] = {id(v): k for k, v in mapping.items()}
all_keys[id(None)] = None
class RequirementsConflicted(ResolverException):
def __init__(self, criterion):
super(RequirementsConflicted, self).__init__(criterion)
self.criterion = criterion
graph: DirectedGraph[KT | None] = DirectedGraph()
graph.add(None) # Sentinel as root dependencies' parent.
connected: set[KT | None] = {None}
for key, criterion in state.criteria.items():
if not _has_route_to_root(state.criteria, key, all_keys, connected):
continue
if key not in graph:
graph.add(key)
for p in criterion.iter_parent():
try:
pkey = all_keys[id(p)]
except KeyError:
continue
if pkey not in graph:
graph.add(pkey)
graph.connect(pkey, key)
return Result(
mapping={k: v for k, v in mapping.items() if k in connected},
graph=graph,
criteria=state.criteria,
)
def __str__(self):
return "Requirements conflict: {}".format(
", ".join(repr(r) for r in self.criterion.iter_requirement()),
)
class Resolution(Generic[RT, CT, KT]):
class InconsistentCandidate(ResolverException):
def __init__(self, candidate, criterion):
super(InconsistentCandidate, self).__init__(candidate, criterion)
self.candidate = candidate
self.criterion = criterion
def __str__(self):
return "Provided candidate {!r} does not satisfy {}".format(
self.candidate,
", ".join(repr(r) for r in self.criterion.iter_requirement()),
)
class Criterion(object):
"""Representation of possible resolution results of a package.
This holds three attributes:
* `information` is a collection of `RequirementInformation` pairs.
Each pair is a requirement contributing to this criterion, and the
candidate that provides the requirement.
* `incompatibilities` is a collection of all known not-to-work candidates
to exclude from consideration.
* `candidates` is a collection containing all possible candidates deducted
from the union of contributing requirements and known incompatibilities.
It should never be empty, except when the criterion is an attribute of a
raised `RequirementsConflicted` (in which case it is always empty).
.. note::
This class is intended to be externally immutable. **Do not** mutate
any of its attribute containers.
"""
def __init__(self, candidates, information, incompatibilities):
self.candidates = candidates
self.information = information
self.incompatibilities = incompatibilities
def __repr__(self):
requirements = ", ".join(
"({!r}, via={!r})".format(req, parent)
for req, parent in self.information
)
return "Criterion({})".format(requirements)
def iter_requirement(self):
return (i.requirement for i in self.information)
def iter_parent(self):
return (i.parent for i in self.information)
class ResolutionError(ResolverException):
pass
class ResolutionImpossible(ResolutionError):
def __init__(self, causes):
super(ResolutionImpossible, self).__init__(causes)
# causes is a list of RequirementInformation objects
self.causes = causes
class ResolutionTooDeep(ResolutionError):
def __init__(self, round_count):
super(ResolutionTooDeep, self).__init__(round_count)
self.round_count = round_count
# Resolution state in a round.
State = collections.namedtuple("State", "mapping criteria backtrack_causes")
class Resolution(object):
"""Stateful resolution object.
This is designed as a one-off object that holds information to kick start
the resolution process, and holds the results afterwards.
"""
def __init__(
self,
provider: AbstractProvider[RT, CT, KT],
reporter: BaseReporter[RT, CT, KT],
) -> None:
def __init__(self, provider, reporter):
self._p = provider
self._r = reporter
self._states: list[State[RT, CT, KT]] = []
# Optimistic backjumping variables
self._optimistic_backjumping_ratio = _OPTIMISTIC_BACKJUMPING_RATIO
self._save_states: list[State[RT, CT, KT]] | None = None
self._optimistic_start_round: int | None = None
self._states = []
@property
def state(self) -> State[RT, CT, KT]:
def state(self):
try:
return self._states[-1]
except IndexError as e:
raise AttributeError("state") from e
except IndexError:
raise AttributeError("state")
def _push_new_state(self) -> None:
def _push_new_state(self):
"""Push a new state into history.
This new state will be used to hold resolution results of the next
@ -107,12 +135,7 @@ class Resolution(Generic[RT, CT, KT]):
)
self._states.append(state)
def _add_to_criteria(
self,
criteria: dict[KT, Criterion[RT, CT]],
requirement: RT,
parent: CT | None,
) -> None:
def _add_to_criteria(self, criteria, requirement, parent):
self._r.adding_requirement(requirement=requirement, parent=parent)
identifier = self._p.identify(requirement_or_candidate=requirement)
@ -151,9 +174,7 @@ class Resolution(Generic[RT, CT, KT]):
raise RequirementsConflicted(criterion)
criteria[identifier] = criterion
def _remove_information_from_criteria(
self, criteria: dict[KT, Criterion[RT, CT]], parents: Collection[KT]
) -> None:
def _remove_information_from_criteria(self, criteria, parents):
"""Remove information from parents of criteria.
Concretely, removes all values from each criterion's ``information``
@ -178,7 +199,7 @@ class Resolution(Generic[RT, CT, KT]):
criterion.incompatibilities,
)
def _get_preference(self, name: KT) -> Preference:
def _get_preference(self, name):
return self._p.get_preference(
identifier=name,
resolutions=self.state.mapping,
@ -193,9 +214,7 @@ class Resolution(Generic[RT, CT, KT]):
backtrack_causes=self.state.backtrack_causes,
)
def _is_current_pin_satisfying(
self, name: KT, criterion: Criterion[RT, CT]
) -> bool:
def _is_current_pin_satisfying(self, name, criterion):
try:
current_pin = self.state.mapping[name]
except KeyError:
@ -205,16 +224,16 @@ class Resolution(Generic[RT, CT, KT]):
for r in criterion.iter_requirement()
)
def _get_updated_criteria(self, candidate: CT) -> dict[KT, Criterion[RT, CT]]:
def _get_updated_criteria(self, candidate):
criteria = self.state.criteria.copy()
for requirement in self._p.get_dependencies(candidate=candidate):
self._add_to_criteria(criteria, requirement, parent=candidate)
return criteria
def _attempt_to_pin_criterion(self, name: KT) -> list[Criterion[RT, CT]]:
def _attempt_to_pin_criterion(self, name):
criterion = self.state.criteria[name]
causes: list[Criterion[RT, CT]] = []
causes = []
for candidate in criterion.candidates:
try:
criteria = self._get_updated_criteria(candidate)
@ -248,61 +267,7 @@ class Resolution(Generic[RT, CT, KT]):
# end, signal for backtracking.
return causes
def _patch_criteria(
self, incompatibilities_from_broken: list[tuple[KT, list[CT]]]
) -> bool:
# Create a new state from the last known-to-work one, and apply
# the previously gathered incompatibility information.
for k, incompatibilities in incompatibilities_from_broken:
if not incompatibilities:
continue
try:
criterion = self.state.criteria[k]
except KeyError:
continue
matches = self._p.find_matches(
identifier=k,
requirements=IteratorMapping(
self.state.criteria,
operator.methodcaller("iter_requirement"),
),
incompatibilities=IteratorMapping(
self.state.criteria,
operator.attrgetter("incompatibilities"),
{k: incompatibilities},
),
)
candidates: IterableView[CT] = build_iter_view(matches)
if not candidates:
return False
incompatibilities.extend(criterion.incompatibilities)
self.state.criteria[k] = Criterion(
candidates=candidates,
information=list(criterion.information),
incompatibilities=incompatibilities,
)
return True
def _save_state(self) -> None:
"""Save states for potential rollback if optimistic backjumping fails."""
if self._save_states is None:
self._save_states = [
State(
mapping=s.mapping.copy(),
criteria=s.criteria.copy(),
backtrack_causes=s.backtrack_causes[:],
)
for s in self._states
]
def _rollback_states(self) -> None:
"""Rollback states and disable optimistic backjumping."""
self._optimistic_backjumping_ratio = 0.0
if self._save_states:
self._states = self._save_states
self._save_states = None
def _backjump(self, causes: list[RequirementInformation[RT, CT]]) -> bool:
def _backjump(self, causes):
"""Perform backjumping.
When we enter here, the stack is like this::
@ -333,7 +298,7 @@ class Resolution(Generic[RT, CT, KT]):
the new Z and go back to step 2.
5b. If the incompatibilities apply cleanly, end backtracking.
"""
incompatible_reqs: Iterable[CT | RT] = itertools.chain(
incompatible_reqs = itertools.chain(
(c.parent for c in causes if c.parent is not None),
(c.requirement for c in causes),
)
@ -342,62 +307,66 @@ class Resolution(Generic[RT, CT, KT]):
# Remove the state that triggered backtracking.
del self._states[-1]
# Optimistically backtrack to a state that caused the incompatibility
broken_state = self.state
while True:
# Ensure to backtrack to a state that caused the incompatibility
incompatible_state = False
while not incompatible_state:
# Retrieve the last candidate pin and known incompatibilities.
try:
broken_state = self._states.pop()
name, candidate = broken_state.mapping.popitem()
except (IndexError, KeyError):
raise ResolutionImpossible(causes) from None
if (
not self._optimistic_backjumping_ratio
and name not in incompatible_deps
):
# For safe backjumping only backjump if the current dependency
# is not the same as the incompatible dependency
break
# On the first time a non-safe backjump is done the state
# is saved so we can restore it later if the resolution fails
if (
self._optimistic_backjumping_ratio
and self._save_states is None
and name not in incompatible_deps
):
self._save_state()
# If the current dependencies and the incompatible dependencies
# are overlapping then we have likely found a cause of the
# incompatibility
current_dependencies = {
self._p.identify(d) for d in self._p.get_dependencies(candidate)
}
if not current_dependencies.isdisjoint(incompatible_deps):
break
# Fallback: We should not backtrack to the point where
# broken_state.mapping is empty, so stop backtracking for
# a chance for the resolution to recover
if not broken_state.mapping:
break
# Guard: We need at least two state to remain to both
# backtrack and push a new state
if len(self._states) <= 1:
raise ResolutionImpossible(causes)
current_dependencies = {
self._p.identify(d)
for d in self._p.get_dependencies(candidate)
}
incompatible_state = not current_dependencies.isdisjoint(
incompatible_deps
)
incompatibilities_from_broken = [
(k, list(v.incompatibilities)) for k, v in broken_state.criteria.items()
(k, list(v.incompatibilities))
for k, v in broken_state.criteria.items()
]
# Also mark the newly known incompatibility.
incompatibilities_from_broken.append((name, [candidate]))
# Create a new state from the last known-to-work one, and apply
# the previously gathered incompatibility information.
def _patch_criteria():
for k, incompatibilities in incompatibilities_from_broken:
if not incompatibilities:
continue
try:
criterion = self.state.criteria[k]
except KeyError:
continue
matches = self._p.find_matches(
identifier=k,
requirements=IteratorMapping(
self.state.criteria,
operator.methodcaller("iter_requirement"),
),
incompatibilities=IteratorMapping(
self.state.criteria,
operator.attrgetter("incompatibilities"),
{k: incompatibilities},
),
)
candidates = build_iter_view(matches)
if not candidates:
return False
incompatibilities.extend(criterion.incompatibilities)
self.state.criteria[k] = Criterion(
candidates=candidates,
information=list(criterion.information),
incompatibilities=incompatibilities,
)
return True
self._push_new_state()
success = self._patch_criteria(incompatibilities_from_broken)
success = _patch_criteria()
# It works! Let's work on this new state.
if success:
@ -409,13 +378,7 @@ class Resolution(Generic[RT, CT, KT]):
# No way to backtrack anymore.
return False
def _extract_causes(
self, criteron: list[Criterion[RT, CT]]
) -> list[RequirementInformation[RT, CT]]:
"""Extract causes from list of criterion and deduplicate"""
return list({id(i): i for c in criteron for i in c.information}.values())
def resolve(self, requirements: Iterable[RT], max_rounds: int) -> State[RT, CT, KT]:
def resolve(self, requirements, max_rounds):
if self._states:
raise RuntimeError("already resolved")
@ -433,39 +396,16 @@ class Resolution(Generic[RT, CT, KT]):
try:
self._add_to_criteria(self.state.criteria, r, parent=None)
except RequirementsConflicted as e:
raise ResolutionImpossible(e.criterion.information) from e
raise ResolutionImpossible(e.criterion.information)
# The root state is saved as a sentinel so the first ever pin can have
# something to backtrack to if it fails. The root state is basically
# pinning the virtual "root" package in the graph.
self._push_new_state()
# Variables for optimistic backjumping
optimistic_rounds_cutoff: int | None = None
optimistic_backjumping_start_round: int | None = None
for round_index in range(max_rounds):
self._r.starting_round(index=round_index)
# Handle if optimistic backjumping has been running for too long
if self._optimistic_backjumping_ratio and self._save_states is not None:
if optimistic_backjumping_start_round is None:
optimistic_backjumping_start_round = round_index
optimistic_rounds_cutoff = int(
(max_rounds - round_index) * self._optimistic_backjumping_ratio
)
if optimistic_rounds_cutoff <= 0:
self._rollback_states()
continue
elif optimistic_rounds_cutoff is not None:
if (
round_index - optimistic_backjumping_start_round
>= optimistic_rounds_cutoff
):
self._rollback_states()
continue
unsatisfied_names = [
key
for key, criterion in self.state.criteria.items()
@ -478,68 +418,25 @@ class Resolution(Generic[RT, CT, KT]):
return self.state
# keep track of satisfied names to calculate diff after pinning
satisfied_names = set(self.state.criteria.keys()) - set(unsatisfied_names)
satisfied_names = set(self.state.criteria.keys()) - set(
unsatisfied_names
)
if len(unsatisfied_names) > 1:
narrowed_unstatisfied_names = list(
self._p.narrow_requirement_selection(
identifiers=unsatisfied_names,
resolutions=self.state.mapping,
candidates=IteratorMapping(
self.state.criteria,
operator.attrgetter("candidates"),
),
information=IteratorMapping(
self.state.criteria,
operator.attrgetter("information"),
),
backtrack_causes=self.state.backtrack_causes,
)
)
else:
narrowed_unstatisfied_names = unsatisfied_names
# Choose the most preferred unpinned criterion to try.
name = min(unsatisfied_names, key=self._get_preference)
failure_causes = self._attempt_to_pin_criterion(name)
# If there are no unsatisfied names use unsatisfied names
if not narrowed_unstatisfied_names:
raise RuntimeError("narrow_requirement_selection returned 0 names")
# If there is only 1 unsatisfied name skip calling self._get_preference
if len(narrowed_unstatisfied_names) > 1:
# Choose the most preferred unpinned criterion to try.
name = min(narrowed_unstatisfied_names, key=self._get_preference)
else:
name = narrowed_unstatisfied_names[0]
failure_criterion = self._attempt_to_pin_criterion(name)
if failure_criterion:
causes = self._extract_causes(failure_criterion)
if failure_causes:
causes = [i for c in failure_causes for i in c.information]
# Backjump if pinning fails. The backjump process puts us in
# an unpinned state, so we can work on it in the next round.
self._r.resolving_conflicts(causes=causes)
success = self._backjump(causes)
self.state.backtrack_causes[:] = causes
try:
success = self._backjump(causes)
except ResolutionImpossible:
if self._optimistic_backjumping_ratio and self._save_states:
failed_optimistic_backjumping = True
else:
raise
else:
failed_optimistic_backjumping = bool(
not success
and self._optimistic_backjumping_ratio
and self._save_states
)
if failed_optimistic_backjumping and self._save_states:
self._rollback_states()
else:
self.state.backtrack_causes[:] = causes
# Dead ends everywhere. Give up.
if not success:
raise ResolutionImpossible(self.state.backtrack_causes)
# Dead ends everywhere. Give up.
if not success:
raise ResolutionImpossible(self.state.backtrack_causes)
else:
# discard as information sources any invalidated names
# (unsatisfied names that were previously satisfied)
@ -560,16 +457,64 @@ class Resolution(Generic[RT, CT, KT]):
raise ResolutionTooDeep(max_rounds)
class Resolver(AbstractResolver[RT, CT, KT]):
def _has_route_to_root(criteria, key, all_keys, connected):
if key in connected:
return True
if key not in criteria:
return False
for p in criteria[key].iter_parent():
try:
pkey = all_keys[id(p)]
except KeyError:
continue
if pkey in connected:
connected.add(key)
return True
if _has_route_to_root(criteria, pkey, all_keys, connected):
connected.add(key)
return True
return False
Result = collections.namedtuple("Result", "mapping graph criteria")
def _build_result(state):
mapping = state.mapping
all_keys = {id(v): k for k, v in mapping.items()}
all_keys[id(None)] = None
graph = DirectedGraph()
graph.add(None) # Sentinel as root dependencies' parent.
connected = {None}
for key, criterion in state.criteria.items():
if not _has_route_to_root(state.criteria, key, all_keys, connected):
continue
if key not in graph:
graph.add(key)
for p in criterion.iter_parent():
try:
pkey = all_keys[id(p)]
except KeyError:
continue
if pkey not in graph:
graph.add(pkey)
graph.connect(pkey, key)
return Result(
mapping={k: v for k, v in mapping.items() if k in connected},
graph=graph,
criteria=state.criteria,
)
class Resolver(AbstractResolver):
"""The thing that performs the actual resolution work."""
base_exception = ResolverException
def resolve( # type: ignore[override]
self,
requirements: Iterable[RT],
max_rounds: int = 100,
) -> Result[RT, CT, KT]:
def resolve(self, requirements, max_rounds=100):
"""Take a collection of constraints, spit out the resolution result.
The return value is a representation to the final resolution result. It
@ -600,28 +545,3 @@ class Resolver(AbstractResolver[RT, CT, KT]):
resolution = Resolution(self.provider, self.reporter)
state = resolution.resolve(requirements, max_rounds=max_rounds)
return _build_result(state)
def _has_route_to_root(
criteria: Mapping[KT, Criterion[RT, CT]],
key: KT | None,
all_keys: dict[int, KT | None],
connected: set[KT | None],
) -> bool:
if key in connected:
return True
if key not in criteria:
return False
assert key is not None
for p in criteria[key].iter_parent():
try:
pkey = all_keys[id(p)]
except KeyError:
continue
if pkey in connected:
connected.add(key)
return True
if _has_route_to_root(criteria, pkey, all_keys, connected):
connected.add(key)
return True
return False

View file

@ -1,27 +0,0 @@
from ..structs import RequirementInformation
from .abstract import AbstractResolver, Result
from .criterion import Criterion
from .exceptions import (
InconsistentCandidate,
RequirementsConflicted,
ResolutionError,
ResolutionImpossible,
ResolutionTooDeep,
ResolverException,
)
from .resolution import Resolution, Resolver
__all__ = [
"AbstractResolver",
"Criterion",
"InconsistentCandidate",
"RequirementInformation",
"RequirementsConflicted",
"Resolution",
"ResolutionError",
"ResolutionImpossible",
"ResolutionTooDeep",
"Resolver",
"ResolverException",
"Result",
]

View file

@ -1,47 +0,0 @@
from __future__ import annotations
import collections
from typing import TYPE_CHECKING, Any, Generic, Iterable, NamedTuple
from ..structs import CT, KT, RT, DirectedGraph
if TYPE_CHECKING:
from ..providers import AbstractProvider
from ..reporters import BaseReporter
from .criterion import Criterion
class Result(NamedTuple, Generic[RT, CT, KT]):
mapping: dict[KT, CT]
graph: DirectedGraph[KT | None]
criteria: dict[KT, Criterion[RT, CT]]
else:
Result = collections.namedtuple("Result", ["mapping", "graph", "criteria"])
class AbstractResolver(Generic[RT, CT, KT]):
"""The thing that performs the actual resolution work."""
base_exception = Exception
def __init__(
self,
provider: AbstractProvider[RT, CT, KT],
reporter: BaseReporter[RT, CT, KT],
) -> None:
self.provider = provider
self.reporter = reporter
def resolve(self, requirements: Iterable[RT], **kwargs: Any) -> Result[RT, CT, KT]:
"""Take a collection of constraints, spit out the resolution result.
This returns a representation of the final resolution state, with one
guarenteed attribute ``mapping`` that contains resolved candidates as
values. The keys are their respective identifiers.
:param requirements: A collection of constraints.
:param kwargs: Additional keyword arguments that subclasses may accept.
:raises: ``self.base_exception`` or its subclass.
"""
raise NotImplementedError

View file

@ -1,48 +0,0 @@
from __future__ import annotations
from typing import Collection, Generic, Iterable, Iterator
from ..structs import CT, RT, RequirementInformation
class Criterion(Generic[RT, CT]):
"""Representation of possible resolution results of a package.
This holds three attributes:
* `information` is a collection of `RequirementInformation` pairs.
Each pair is a requirement contributing to this criterion, and the
candidate that provides the requirement.
* `incompatibilities` is a collection of all known not-to-work candidates
to exclude from consideration.
* `candidates` is a collection containing all possible candidates deducted
from the union of contributing requirements and known incompatibilities.
It should never be empty, except when the criterion is an attribute of a
raised `RequirementsConflicted` (in which case it is always empty).
.. note::
This class is intended to be externally immutable. **Do not** mutate
any of its attribute containers.
"""
def __init__(
self,
candidates: Iterable[CT],
information: Collection[RequirementInformation[RT, CT]],
incompatibilities: Collection[CT],
) -> None:
self.candidates = candidates
self.information = information
self.incompatibilities = incompatibilities
def __repr__(self) -> str:
requirements = ", ".join(
f"({req!r}, via={parent!r})" for req, parent in self.information
)
return f"Criterion({requirements})"
def iter_requirement(self) -> Iterator[RT]:
return (i.requirement for i in self.information)
def iter_parent(self) -> Iterator[CT | None]:
return (i.parent for i in self.information)

View file

@ -1,57 +0,0 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Collection, Generic
from ..structs import CT, RT, RequirementInformation
if TYPE_CHECKING:
from .criterion import Criterion
class ResolverException(Exception):
"""A base class for all exceptions raised by this module.
Exceptions derived by this class should all be handled in this module. Any
bubbling pass the resolver should be treated as a bug.
"""
class RequirementsConflicted(ResolverException, Generic[RT, CT]):
def __init__(self, criterion: Criterion[RT, CT]) -> None:
super().__init__(criterion)
self.criterion = criterion
def __str__(self) -> str:
return "Requirements conflict: {}".format(
", ".join(repr(r) for r in self.criterion.iter_requirement()),
)
class InconsistentCandidate(ResolverException, Generic[RT, CT]):
def __init__(self, candidate: CT, criterion: Criterion[RT, CT]):
super().__init__(candidate, criterion)
self.candidate = candidate
self.criterion = criterion
def __str__(self) -> str:
return "Provided candidate {!r} does not satisfy {}".format(
self.candidate,
", ".join(repr(r) for r in self.criterion.iter_requirement()),
)
class ResolutionError(ResolverException):
pass
class ResolutionImpossible(ResolutionError, Generic[RT, CT]):
def __init__(self, causes: Collection[RequirementInformation[RT, CT]]):
super().__init__(causes)
# causes is a list of RequirementInformation objects
self.causes = causes
class ResolutionTooDeep(ResolutionError):
def __init__(self, round_count: int) -> None:
super().__init__(round_count)
self.round_count = round_count

View file

@ -1,73 +1,34 @@
from __future__ import annotations
import itertools
from collections import namedtuple
from typing import (
TYPE_CHECKING,
Callable,
Generic,
Iterable,
Iterator,
Mapping,
NamedTuple,
Sequence,
TypeVar,
Union,
)
KT = TypeVar("KT") # Identifier.
RT = TypeVar("RT") # Requirement.
CT = TypeVar("CT") # Candidate.
Matches = Union[Iterable[CT], Callable[[], Iterable[CT]]]
if TYPE_CHECKING:
from .resolvers.criterion import Criterion
class RequirementInformation(NamedTuple, Generic[RT, CT]):
requirement: RT
parent: CT | None
class State(NamedTuple, Generic[RT, CT, KT]):
"""Resolution state in a round."""
mapping: dict[KT, CT]
criteria: dict[KT, Criterion[RT, CT]]
backtrack_causes: list[RequirementInformation[RT, CT]]
else:
RequirementInformation = namedtuple(
"RequirementInformation", ["requirement", "parent"]
)
State = namedtuple("State", ["mapping", "criteria", "backtrack_causes"])
from .compat import collections_abc
class DirectedGraph(Generic[KT]):
class DirectedGraph(object):
"""A graph structure with directed edges."""
def __init__(self) -> None:
self._vertices: set[KT] = set()
self._forwards: dict[KT, set[KT]] = {} # <key> -> Set[<key>]
self._backwards: dict[KT, set[KT]] = {} # <key> -> Set[<key>]
def __init__(self):
self._vertices = set()
self._forwards = {} # <key> -> Set[<key>]
self._backwards = {} # <key> -> Set[<key>]
def __iter__(self) -> Iterator[KT]:
def __iter__(self):
return iter(self._vertices)
def __len__(self) -> int:
def __len__(self):
return len(self._vertices)
def __contains__(self, key: KT) -> bool:
def __contains__(self, key):
return key in self._vertices
def copy(self) -> DirectedGraph[KT]:
def copy(self):
"""Return a shallow copy of this graph."""
other = type(self)()
other = DirectedGraph()
other._vertices = set(self._vertices)
other._forwards = {k: set(v) for k, v in self._forwards.items()}
other._backwards = {k: set(v) for k, v in self._backwards.items()}
return other
def add(self, key: KT) -> None:
def add(self, key):
"""Add a new vertex to the graph."""
if key in self._vertices:
raise ValueError("vertex exists")
@ -75,7 +36,7 @@ class DirectedGraph(Generic[KT]):
self._forwards[key] = set()
self._backwards[key] = set()
def remove(self, key: KT) -> None:
def remove(self, key):
"""Remove a vertex from the graph, disconnecting all edges from/to it."""
self._vertices.remove(key)
for f in self._forwards.pop(key):
@ -83,10 +44,10 @@ class DirectedGraph(Generic[KT]):
for t in self._backwards.pop(key):
self._forwards[t].remove(key)
def connected(self, f: KT, t: KT) -> bool:
def connected(self, f, t):
return f in self._backwards[t] and t in self._forwards[f]
def connect(self, f: KT, t: KT) -> None:
def connect(self, f, t):
"""Connect two existing vertices.
Nothing happens if the vertices are already connected.
@ -96,59 +57,56 @@ class DirectedGraph(Generic[KT]):
self._forwards[f].add(t)
self._backwards[t].add(f)
def iter_edges(self) -> Iterator[tuple[KT, KT]]:
def iter_edges(self):
for f, children in self._forwards.items():
for t in children:
yield f, t
def iter_children(self, key: KT) -> Iterator[KT]:
def iter_children(self, key):
return iter(self._forwards[key])
def iter_parents(self, key: KT) -> Iterator[KT]:
def iter_parents(self, key):
return iter(self._backwards[key])
class IteratorMapping(Mapping[KT, Iterator[CT]], Generic[RT, CT, KT]):
def __init__(
self,
mapping: Mapping[KT, RT],
accessor: Callable[[RT], Iterable[CT]],
appends: Mapping[KT, Iterable[CT]] | None = None,
) -> None:
class IteratorMapping(collections_abc.Mapping):
def __init__(self, mapping, accessor, appends=None):
self._mapping = mapping
self._accessor = accessor
self._appends: Mapping[KT, Iterable[CT]] = appends or {}
self._appends = appends or {}
def __repr__(self) -> str:
def __repr__(self):
return "IteratorMapping({!r}, {!r}, {!r})".format(
self._mapping,
self._accessor,
self._appends,
)
def __bool__(self) -> bool:
def __bool__(self):
return bool(self._mapping or self._appends)
def __contains__(self, key: object) -> bool:
__nonzero__ = __bool__ # XXX: Python 2.
def __contains__(self, key):
return key in self._mapping or key in self._appends
def __getitem__(self, k: KT) -> Iterator[CT]:
def __getitem__(self, k):
try:
v = self._mapping[k]
except KeyError:
return iter(self._appends[k])
return itertools.chain(self._accessor(v), self._appends.get(k, ()))
def __iter__(self) -> Iterator[KT]:
def __iter__(self):
more = (k for k in self._appends if k not in self._mapping)
return itertools.chain(self._mapping, more)
def __len__(self) -> int:
def __len__(self):
more = sum(1 for k in self._appends if k not in self._mapping)
return len(self._mapping) + more
class _FactoryIterableView(Iterable[RT]):
class _FactoryIterableView(object):
"""Wrap an iterator factory returned by `find_matches()`.
Calling `iter()` on this class would invoke the underlying iterator
@ -157,53 +115,56 @@ class _FactoryIterableView(Iterable[RT]):
built-in Python sequence types.
"""
def __init__(self, factory: Callable[[], Iterable[RT]]) -> None:
def __init__(self, factory):
self._factory = factory
self._iterable: Iterable[RT] | None = None
self._iterable = None
def __repr__(self) -> str:
return f"{type(self).__name__}({list(self)})"
def __repr__(self):
return "{}({})".format(type(self).__name__, list(self))
def __bool__(self) -> bool:
def __bool__(self):
try:
next(iter(self))
except StopIteration:
return False
return True
def __iter__(self) -> Iterator[RT]:
iterable = self._factory() if self._iterable is None else self._iterable
__nonzero__ = __bool__ # XXX: Python 2.
def __iter__(self):
iterable = (
self._factory() if self._iterable is None else self._iterable
)
self._iterable, current = itertools.tee(iterable)
return current
class _SequenceIterableView(Iterable[RT]):
class _SequenceIterableView(object):
"""Wrap an iterable returned by find_matches().
This is essentially just a proxy to the underlying sequence that provides
the same interface as `_FactoryIterableView`.
"""
def __init__(self, sequence: Sequence[RT]):
def __init__(self, sequence):
self._sequence = sequence
def __repr__(self) -> str:
return f"{type(self).__name__}({self._sequence})"
def __repr__(self):
return "{}({})".format(type(self).__name__, self._sequence)
def __bool__(self) -> bool:
def __bool__(self):
return bool(self._sequence)
def __iter__(self) -> Iterator[RT]:
__nonzero__ = __bool__ # XXX: Python 2.
def __iter__(self):
return iter(self._sequence)
def build_iter_view(matches: Matches[CT]) -> Iterable[CT]:
def build_iter_view(matches):
"""Build an iterable view from the value returned by `find_matches()`."""
if callable(matches):
return _FactoryIterableView(matches)
if not isinstance(matches, Sequence):
if not isinstance(matches, collections_abc.Sequence):
matches = list(matches)
return _SequenceIterableView(matches)
IterableView = Iterable