Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 123 additions & 1 deletion src/conflict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use petgraph::{

use crate::{
DenseIndex, DependencyProvider, Interner, Requirement, SolvableId, SolverId, StringId,
VersionSetId,
VariableId, VersionSetId,
internal::{id::ClauseId, solver_id::SolvableIdOrRoot},
runtime::AsyncRuntime,
solver::{Solver, clause::Clause, variable_map::VariableOrigin},
Expand Down Expand Up @@ -56,6 +56,72 @@ impl Conflict {
let unresolved_node = graph.add_node(ConflictNode::UnresolvedDependency);
let mut last_node_by_name: HashMap<D::NameId, NodeIndex> = HashMap::default();

// The shared constrains encoding splits each (parent, excluded
// candidate) pair over two clauses linked by an auxiliary variable.
// Collect both sides per auxiliary variable so the original
// `parent -> candidate` edges can be reconstructed in the loop below.
let mut constrains_aux_parents: HashMap<VariableId, Vec<SolvableIdOrRoot<D::SolvableId>>> =
HashMap::default();
let mut constrains_aux_candidates: HashMap<
VariableId,
Vec<SolvableIdOrRoot<D::SolvableId>>,
> = HashMap::default();
for clause_id in &self.clauses {
match state.clauses.kinds[clause_id.to_index()] {
Clause::ConstrainsParent(parent, aux, _) => {
let parent = parent
.as_solvable_or_root(&state.variable_map)
.expect("constrains parents are solvables or root");
constrains_aux_parents.entry(aux).or_default().push(parent);
}
Clause::ConstrainsExcluded(candidate, aux, _) => {
let candidate = candidate
.as_solvable_or_root(&state.variable_map)
.expect("excluded candidates are solvables");
constrains_aux_candidates
.entry(aux)
.or_default()
.push(candidate);
}
_ => {}
}
}

// If only one side of a chain is part of the conflict, recover the
// other side from the assignment reason of the auxiliary variable.
let reason_clause = |aux: VariableId| {
state
.decision_tracker
.find_clause_for_assignment(aux)
.map(|clause_id| state.clauses.kinds[clause_id.to_index()])
};
for &aux in constrains_aux_parents.keys() {
if constrains_aux_candidates.contains_key(&aux) {
continue;
}
if let Some(Clause::ConstrainsExcluded(candidate, _, _)) = reason_clause(aux) {
let candidate = candidate
.as_solvable_or_root(&state.variable_map)
.expect("excluded candidates are solvables");
constrains_aux_candidates.insert(aux, vec![candidate]);
}
}
for &aux in constrains_aux_candidates.keys() {
if constrains_aux_parents.contains_key(&aux) {
continue;
}
if let Some(Clause::ConstrainsParent(parent, _, _)) = reason_clause(aux) {
let parent = parent
.as_solvable_or_root(&state.variable_map)
.expect("constrains parents are solvables or root");
constrains_aux_parents.insert(aux, vec![parent]);
}
}

// Avoids adding the same edge once for each side of a chain.
type ConstrainsEdge<S> = (SolvableIdOrRoot<S>, SolvableIdOrRoot<S>, VersionSetId);
let mut constrains_edges: HashSet<ConstrainsEdge<D::SolvableId>> = HashSet::new();

for clause_id in &self.clauses {
let clause = &state.clauses.kinds[clause_id.to_index()];
match clause {
Expand Down Expand Up @@ -160,6 +226,62 @@ impl Conflict {
ConflictEdge::Conflict(ConflictCause::Constrains(version_set_id)),
);
}
&Clause::ConstrainsParent(package_id, aux, version_set_id) => {
let package_solvable = package_id
.as_solvable_or_root(&state.variable_map)
.expect("constrains parents are solvables or root");

let Some(candidates) = constrains_aux_candidates.get(&aux) else {
continue;
};

for &dependency_solvable in candidates {
if !constrains_edges.insert((
package_solvable,
dependency_solvable,
version_set_id,
)) {
continue;
}

let package_node = Self::add_node(&mut graph, &mut nodes, package_solvable);
let dep_node = Self::add_node(&mut graph, &mut nodes, dependency_solvable);

graph.add_edge(
package_node,
dep_node,
ConflictEdge::Conflict(ConflictCause::Constrains(version_set_id)),
);
}
}
&Clause::ConstrainsExcluded(dep_id, aux, version_set_id) => {
let dependency_solvable = dep_id
.as_solvable_or_root(&state.variable_map)
.expect("excluded candidates are solvables");

let Some(parents) = constrains_aux_parents.get(&aux) else {
continue;
};

for &package_solvable in parents {
if !constrains_edges.insert((
package_solvable,
dependency_solvable,
version_set_id,
)) {
continue;
}

let package_node = Self::add_node(&mut graph, &mut nodes, package_solvable);
let dep_node = Self::add_node(&mut graph, &mut nodes, dependency_solvable);

graph.add_edge(
package_node,
dep_node,
ConflictEdge::Conflict(ConflictCause::Constrains(version_set_id)),
);
}
}
Clause::AnyOf(selected, _variable) => {
// Assumption: since `AnyOf` of clause can never be false, we dont add an edge
// for it.
Expand Down
124 changes: 124 additions & 0 deletions src/solver/clause.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,30 @@ pub(crate) enum Clause<N> {
///
/// In SAT terms: (¬A ∨ ¬B)
Constrains(VariableId, VariableId, VersionSetId),
/// Makes the constraint's auxiliary variable turn true when a candidate
/// that is excluded by the constraint's version set is installed.
///
/// Usage: constraints whose version set excludes many candidates share a
/// single auxiliary variable per version set. The clauses that link the
/// excluded candidates to the auxiliary variable are emitted once per
/// version set, and each (parent, version set) pair only adds a single
/// [`Clause::ConstrainsParent`] clause. Together these encode the same
/// restriction as [`Clause::Constrains`] with O(candidates + parents)
/// instead of O(candidates * parents) clauses.
///
/// Only this implication direction is needed (the Plaisted-Greenbaum
/// one-sided form): the auxiliary variable is never decided directly, it
/// only receives a value through propagation.
///
/// In SAT terms: (¬candidate ∨ aux)
ConstrainsExcluded(VariableId, VariableId, VersionSetId),
/// Forbids a parent solvable from being installed together with the
/// constraint's auxiliary variable, i.e. together with any candidate that
/// is excluded by the constraint's version set. See
/// [`Clause::ConstrainsExcluded`] for an overview of the encoding.
///
/// In SAT terms: (¬parent ∨ ¬aux)
ConstrainsParent(VariableId, VariableId, VersionSetId),
/// Forbids the package on the right-hand side
///
/// Note that the package on the left-hand side is not part of the clause,
Expand Down Expand Up @@ -117,6 +141,8 @@ impl<N> Clause<N> {
matches!(
self,
Clause::Constrains(..)
| Clause::ConstrainsExcluded(..)
| Clause::ConstrainsParent(..)
| Clause::ForbidMultipleInstances(..)
| Clause::Lock(..)
| Clause::AnyOf(..)
Expand Down Expand Up @@ -218,6 +244,44 @@ impl<N: SolverId> Clause<N> {
)
}

/// Returns the building blocks needed for a new [WatchedLiterals] of the
/// [Clause::ConstrainsExcluded] kind.
fn constrains_excluded(
candidate: VariableId,
aux: VariableId,
via: VersionSetId,
) -> (Self, Option<[Literal; 2]>) {
(
Clause::ConstrainsExcluded(candidate, aux, via),
Some([candidate.negative(), aux.positive()]),
)
}

/// Returns the building blocks needed for a new [WatchedLiterals] of the
/// [Clause::ConstrainsParent] kind. See [`Clause::constrains`] for the
/// meaning of the returned values.
fn constrains_parent(
parent: VariableId,
aux: VariableId,
via: VersionSetId,
decision_tracker: &DecisionTracker,
) -> (Self, Option<[Literal; 2]>, bool) {
// It only makes sense to introduce a constrains clause when the parent
// solvable is undecided or going to be installed
assert_ne!(decision_tracker.assigned_value(parent), Some(false));

// If the auxiliary variable is already true, an excluded candidate is
// installed, which implies the parent solvable would be false (and we
// just asserted that it is not).
let conflict = decision_tracker.assigned_value(aux) == Some(true);

(
Clause::ConstrainsParent(parent, aux, via),
Some([parent.negative(), aux.negative()]),
conflict,
)
}

/// Returns the ids of the solvables that will be watched as well as the
/// clause itself.
fn forbid_multiple(
Expand Down Expand Up @@ -311,6 +375,12 @@ impl<N: SolverId> Clause<N> {
Clause::Constrains(s1, s2, _) => [s1.negative(), s2.negative()]
.into_iter()
.try_fold(init, visit),
Clause::ConstrainsExcluded(candidate, aux, _) => [candidate.negative(), aux.positive()]
.into_iter()
.try_fold(init, visit),
Clause::ConstrainsParent(parent, aux, _) => [parent.negative(), aux.negative()]
.into_iter()
.try_fold(init, visit),
Clause::ForbidMultipleInstances(s1, s2, _) => {
[s1.negative(), s2].into_iter().try_fold(init, visit)
}
Expand Down Expand Up @@ -437,6 +507,38 @@ impl WatchedLiterals {
)
}

/// Shorthand method to construct a [Clause::ConstrainsExcluded] without
/// requiring complicated arguments.
pub fn constrains_excluded<N: SolverId>(
candidate: VariableId,
aux: VariableId,
requirement: VersionSetId,
) -> (Option<Self>, Clause<N>) {
let (kind, watched_literals) = Clause::constrains_excluded(candidate, aux, requirement);
(Self::from_kind_and_initial_watches(watched_literals), kind)
}

/// Shorthand method to construct a [Clause::ConstrainsParent] without
/// requiring complicated arguments.
///
/// The returned boolean value is true when adding the clause resulted in a
/// conflict.
pub fn constrains_parent<N: SolverId>(
parent: VariableId,
aux: VariableId,
requirement: VersionSetId,
decision_tracker: &DecisionTracker,
) -> (Option<Self>, bool, Clause<N>) {
let (kind, watched_literals, conflict) =
Clause::constrains_parent(parent, aux, requirement, decision_tracker);

(
Self::from_kind_and_initial_watches(watched_literals),
conflict,
kind,
)
}

pub fn lock<N: SolverId>(
locked_candidate: VariableId,
other_candidate: VariableId,
Expand Down Expand Up @@ -652,6 +754,28 @@ impl<I: Interner> Display for ClauseDisplay<'_, I> {
self.interner.display_version_set(version_set_id)
)
}
Clause::ConstrainsExcluded(candidate, aux, version_set_id) => {
write!(
f,
"ConstrainsExcluded({}({:?}), {}({:?}), {})",
candidate.display(self.variable_map, self.interner),
candidate,
aux.display(self.variable_map, self.interner),
aux,
self.interner.display_version_set(version_set_id)
)
}
Clause::ConstrainsParent(parent, aux, version_set_id) => {
write!(
f,
"ConstrainsParent({}({:?}), {}({:?}), {})",
parent.display(self.variable_map, self.interner),
parent,
aux.display(self.variable_map, self.interner),
aux,
self.interner.display_version_set(version_set_id)
)
}
Clause::ForbidMultipleInstances(v1, v2, name) => {
write!(
f,
Expand Down
6 changes: 5 additions & 1 deletion src/solver/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ impl<D: DependencyProvider, RT: AsyncRuntime> Solver<D, RT> {
Clause::Learnt(..) => {
learned_clauses += 1;
}
Clause::Constrains(..) => {
Clause::Constrains(..)
| Clause::ConstrainsExcluded(..)
| Clause::ConstrainsParent(..) => {
constrains_clauses += 1;
}
Clause::AnyOf(..) => {
Expand All @@ -60,6 +62,8 @@ impl<D: DependencyProvider, RT: AsyncRuntime> Solver<D, RT> {
None => assertion_clauses += 1,
Some(_) => match clause {
Clause::Constrains(..)
| Clause::ConstrainsExcluded(..)
| Clause::ConstrainsParent(..)
| Clause::ForbidMultipleInstances(..)
| Clause::Lock(..)
| Clause::AnyOf(..) => binary_watched += 1,
Expand Down
Loading
Loading