-
Notifications
You must be signed in to change notification settings - Fork 13
/
mod.rs
1382 lines (1220 loc) · 56.1 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub use cache::SolverCache;
use clause::{Clause, ClauseState, Literal};
use decision::Decision;
use decision_tracker::DecisionTracker;
use futures::{stream::FuturesUnordered, FutureExt, StreamExt};
use itertools::{chain, Itertools};
use std::fmt::Display;
use std::{any::Any, cell::RefCell, collections::HashSet, future::ready, ops::ControlFlow};
use watch_map::WatchMap;
use crate::{
internal::{
arena::Arena,
id::{ClauseId, InternalSolvableId, LearntClauseId, NameId, SolvableId},
mapping::Mapping,
},
problem::Problem,
runtime::{AsyncRuntime, NowOrNeverRuntime},
Candidates, Dependencies, DependencyProvider, KnownDependencies, VersionSetId,
};
mod cache;
pub(crate) mod clause;
mod decision;
mod decision_map;
mod decision_tracker;
mod watch_map;
#[derive(Default)]
struct AddClauseOutput {
new_requires_clauses: Vec<(InternalSolvableId, VersionSetId, ClauseId)>,
conflicting_clauses: Vec<ClauseId>,
negative_assertions: Vec<(InternalSolvableId, ClauseId)>,
clauses_to_watch: Vec<ClauseId>,
}
/// Drives the SAT solving process
pub struct Solver<D: DependencyProvider, RT: AsyncRuntime = NowOrNeverRuntime> {
pub(crate) async_runtime: RT,
pub(crate) cache: SolverCache<D>,
pub(crate) clauses: RefCell<Arena<ClauseId, ClauseState>>,
requires_clauses: Vec<(InternalSolvableId, VersionSetId, ClauseId)>,
watches: WatchMap,
negative_assertions: Vec<(InternalSolvableId, ClauseId)>,
learnt_clauses: Arena<LearntClauseId, Vec<Literal>>,
learnt_why: Mapping<LearntClauseId, Vec<ClauseId>>,
learnt_clause_ids: Vec<ClauseId>,
clauses_added_for_package: RefCell<HashSet<NameId>>,
clauses_added_for_solvable: RefCell<HashSet<InternalSolvableId>>,
decision_tracker: DecisionTracker,
/// The version sets that must be installed as part of the solution.
root_requirements: Vec<VersionSetId>,
/// Additional constraints imposed by the root.
root_constraints: Vec<VersionSetId>,
}
impl<D: DependencyProvider> Solver<D, NowOrNeverRuntime> {
/// Creates a single threaded block solver, using the provided
/// [`DependencyProvider`].
pub fn new(provider: D) -> Self {
Self {
cache: SolverCache::new(provider),
async_runtime: NowOrNeverRuntime,
clauses: RefCell::new(Arena::new()),
requires_clauses: Default::default(),
watches: WatchMap::new(),
negative_assertions: Default::default(),
learnt_clauses: Arena::new(),
learnt_why: Mapping::new(),
learnt_clause_ids: Vec::new(),
decision_tracker: DecisionTracker::new(),
root_requirements: Default::default(),
root_constraints: Default::default(),
clauses_added_for_package: Default::default(),
clauses_added_for_solvable: Default::default(),
}
}
}
/// The root cause of a solver error.
#[derive(Debug)]
pub enum UnsolvableOrCancelled {
/// The problem was unsolvable.
Unsolvable(Problem),
/// The solving process was cancelled.
Cancelled(Box<dyn Any>),
}
impl From<Problem> for UnsolvableOrCancelled {
fn from(value: Problem) -> Self {
UnsolvableOrCancelled::Unsolvable(value)
}
}
impl From<Box<dyn Any>> for UnsolvableOrCancelled {
fn from(value: Box<dyn Any>) -> Self {
UnsolvableOrCancelled::Cancelled(value)
}
}
/// An error during the propagation step
#[derive(Debug)]
pub(crate) enum PropagationError {
Conflict(InternalSolvableId, bool, ClauseId),
Cancelled(Box<dyn Any>),
}
impl Display for PropagationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PropagationError::Conflict(solvable, value, clause) => {
write!(
f,
"conflict while propagating solvable {:?}, value {} caused by clause {:?}",
solvable, value, clause
)
}
PropagationError::Cancelled(_) => {
write!(f, "propagation was cancelled")
}
}
}
}
impl<D: DependencyProvider, RT: AsyncRuntime> Solver<D, RT> {
/// Returns the dependency provider used by this instance.
pub fn provider(&self) -> &D {
self.cache.provider()
}
/// Set the runtime of the solver to `runtime`.
pub fn with_runtime<RT2: AsyncRuntime>(self, runtime: RT2) -> Solver<D, RT2> {
Solver {
async_runtime: runtime,
cache: self.cache,
clauses: self.clauses,
requires_clauses: self.requires_clauses,
watches: self.watches,
negative_assertions: self.negative_assertions,
learnt_clauses: self.learnt_clauses,
learnt_why: self.learnt_why,
learnt_clause_ids: self.learnt_clause_ids,
clauses_added_for_package: self.clauses_added_for_package,
clauses_added_for_solvable: self.clauses_added_for_solvable,
decision_tracker: self.decision_tracker,
root_requirements: self.root_requirements,
root_constraints: self.root_constraints,
}
}
/// Solves for the provided `root_requirements` and `root_constraints`. The
/// `root_requirements` are package that will be included in the
/// solution. `root_constraints` are additional constrains which do not
/// necesarily need to be included in the solution.
///
/// Returns a [`Problem`] if no solution was found, which provides ways to
/// inspect the causes and report them to the user.
pub fn solve(
&mut self,
root_requirements: Vec<VersionSetId>,
root_constraints: Vec<VersionSetId>,
) -> Result<Vec<SolvableId>, UnsolvableOrCancelled> {
// Clear state
self.decision_tracker.clear();
self.negative_assertions.clear();
self.learnt_clauses.clear();
self.learnt_why = Mapping::new();
self.clauses = Default::default();
self.root_requirements = root_requirements;
self.root_constraints = root_constraints;
// The first clause will always be the install root clause. Here we verify that
// this is indeed the case.
let root_clause = self.clauses.borrow_mut().alloc(ClauseState::root());
assert_eq!(root_clause, ClauseId::install_root());
// Run SAT
self.run_sat()?;
let steps: Vec<SolvableId> = self
.decision_tracker
.stack()
.filter_map(|d| {
if d.value {
d.solvable_id.as_solvable()
} else {
// Ignore things that are set to false
None
}
})
.collect();
tracing::trace!("Solvables found:");
for step in &steps {
tracing::trace!(
" - {}",
InternalSolvableId::from(*step).display(self.provider())
);
}
Ok(steps)
}
/// Adds clauses for a solvable. These clauses include requirements and
/// constrains on other solvables.
///
/// Returns the added clauses, and an additional list with conflicting
/// clauses (if any).
///
/// If the provider has requested the solving process to be cancelled, the
/// cancellation value will be returned as an `Err(...)`.
async fn add_clauses_for_solvables(
&self,
solvable_ids: impl IntoIterator<Item = InternalSolvableId>,
) -> Result<AddClauseOutput, Box<dyn Any>> {
let mut output = AddClauseOutput::default();
tracing::trace!("Add clauses for solvables");
pub enum TaskResult<'i> {
Dependencies {
solvable_id: InternalSolvableId,
dependencies: Dependencies,
},
SortedCandidates {
solvable_id: InternalSolvableId,
version_set_id: VersionSetId,
candidates: &'i [SolvableId],
},
NonMatchingCandidates {
solvable_id: InternalSolvableId,
version_set_id: VersionSetId,
non_matching_candidates: &'i [SolvableId],
},
Candidates {
name_id: NameId,
package_candidates: &'i Candidates,
},
}
// Mark the initial seen solvables as seen
let mut pending_solvables = vec![];
{
let mut clauses_added_for_solvable = self.clauses_added_for_solvable.borrow_mut();
for solvable_id in solvable_ids {
if clauses_added_for_solvable.insert(solvable_id) {
pending_solvables.push(solvable_id);
}
}
}
let mut seen = pending_solvables.iter().copied().collect::<HashSet<_>>();
let mut pending_futures = FuturesUnordered::new();
loop {
// Iterate over all pending solvables and request their dependencies.
for internal_solvable_id in pending_solvables.drain(..) {
// Get the solvable information and request its requirements and constraints
tracing::trace!(
"┝━ adding clauses for dependencies of {}",
internal_solvable_id.display(self.provider()),
);
// If the solvable is the root solvable, we can skip the dependency provider
// and use the root requirements and constraints directly.
let get_dependencies_fut =
if let Some(solvable_id) = internal_solvable_id.as_solvable() {
async move {
let deps = self.cache.get_or_cache_dependencies(solvable_id).await?;
Ok(TaskResult::Dependencies {
solvable_id: internal_solvable_id,
dependencies: deps.clone(),
})
}
.left_future()
} else {
ready(Ok(TaskResult::Dependencies {
solvable_id: internal_solvable_id,
dependencies: Dependencies::Known(KnownDependencies {
requirements: self.root_requirements.clone(),
constrains: self.root_constraints.clone(),
}),
}))
.right_future()
};
pending_futures.push(get_dependencies_fut.boxed_local());
}
let Some(result) = pending_futures.next().await else {
// No more pending results
break;
};
let mut clauses_added_for_solvable = self.clauses_added_for_solvable.borrow_mut();
let mut clauses_added_for_package = self.clauses_added_for_package.borrow_mut();
match result? {
TaskResult::Dependencies {
solvable_id,
dependencies,
} => {
// Get the solvable information and request its requirements and constraints
tracing::trace!(
"dependencies available for {}",
solvable_id.display(self.provider()),
);
let (requirements, constrains) = match dependencies {
Dependencies::Known(deps) => (deps.requirements, deps.constrains),
Dependencies::Unknown(reason) => {
// There is no information about the solvable's dependencies, so we add
// an exclusion clause for it
let clause_id = self
.clauses
.borrow_mut()
.alloc(ClauseState::exclude(solvable_id, reason));
// Exclusions are negative assertions, tracked outside of the watcher
// system
output.negative_assertions.push((solvable_id, clause_id));
// There might be a conflict now
if self.decision_tracker.assigned_value(solvable_id) == Some(true) {
output.conflicting_clauses.push(clause_id);
}
continue;
}
};
for version_set_id in chain(requirements.iter(), constrains.iter()).copied() {
let dependency_name = self.provider().version_set_name(version_set_id);
if clauses_added_for_package.insert(dependency_name) {
tracing::trace!(
"┝━ Adding clauses for package '{}'",
self.provider().display_name(dependency_name),
);
pending_futures.push(
async move {
let package_candidates =
self.cache.get_or_cache_candidates(dependency_name).await?;
Ok(TaskResult::Candidates {
name_id: dependency_name,
package_candidates,
})
}
.boxed_local(),
);
}
}
for version_set_id in requirements {
// Find all the solvable that match for the given version set
pending_futures.push(
async move {
let candidates = self
.cache
.get_or_cache_sorted_candidates(version_set_id)
.await?;
Ok(TaskResult::SortedCandidates {
solvable_id,
version_set_id,
candidates,
})
}
.boxed_local(),
);
}
for version_set_id in constrains {
// Find all the solvables that match for the given version set
pending_futures.push(
async move {
let non_matching_candidates = self
.cache
.get_or_cache_non_matching_candidates(version_set_id)
.await?;
Ok(TaskResult::NonMatchingCandidates {
solvable_id,
version_set_id,
non_matching_candidates,
})
}
.boxed_local(),
)
}
}
TaskResult::Candidates {
name_id,
package_candidates,
} => {
// Get the solvable information and request its requirements and constraints
tracing::trace!(
"Package candidates available for {}",
self.provider().display_name(name_id)
);
let locked_solvable_id = package_candidates.locked;
let candidates = &package_candidates.candidates;
// Check the assumption that no decision has been made about any of the
// solvables.
for &candidate in candidates {
debug_assert!(
self.decision_tracker.assigned_value(candidate.into()).is_none(),
"a decision has been made about a candidate of a package that was not properly added yet."
);
}
// Each candidate gets a clause to disallow other candidates.
for (i, &candidate) in candidates.iter().enumerate() {
for &other_candidate in &candidates[i + 1..] {
let clause_id =
self.clauses
.borrow_mut()
.alloc(ClauseState::forbid_multiple(
candidate.into(),
other_candidate.into(),
name_id,
));
debug_assert!(self.clauses.borrow_mut()[clause_id].has_watches());
output.clauses_to_watch.push(clause_id);
}
}
// If there is a locked solvable, forbid other solvables.
if let Some(locked_solvable_id) = locked_solvable_id {
for &other_candidate in candidates {
if other_candidate != locked_solvable_id {
let clause_id = self.clauses.borrow_mut().alloc(ClauseState::lock(
locked_solvable_id.into(),
other_candidate.into(),
));
debug_assert!(self.clauses.borrow_mut()[clause_id].has_watches());
output.clauses_to_watch.push(clause_id);
}
}
}
// Add a clause for solvables that are externally excluded.
for (solvable, reason) in package_candidates.excluded.iter().copied() {
let clause_id = self
.clauses
.borrow_mut()
.alloc(ClauseState::exclude(solvable.into(), reason));
// Exclusions are negative assertions, tracked outside of the watcher system
output
.negative_assertions
.push((solvable.into(), clause_id));
// Conflicts should be impossible here
debug_assert!(
self.decision_tracker.assigned_value(solvable.into()) != Some(true)
);
}
}
TaskResult::SortedCandidates {
solvable_id,
version_set_id,
candidates,
} => {
tracing::trace!(
"Sorted candidates available for {} {}",
self.provider()
.display_name(self.provider().version_set_name(version_set_id)),
self.provider().display_version_set(version_set_id),
);
// Queue requesting the dependencies of the candidates as well if they are
// cheaply available from the dependency provider.
for &candidate in candidates {
if seen.insert(candidate.into())
&& self.cache.are_dependencies_available_for(candidate)
&& clauses_added_for_solvable.insert(candidate.into())
{
pending_solvables.push(candidate.into());
}
}
// Add the requirements clause
let no_candidates = candidates.is_empty();
let (clause, conflict) = ClauseState::requires(
solvable_id,
version_set_id,
candidates,
&self.decision_tracker,
);
let clause_id = self.clauses.borrow_mut().alloc(clause);
let clause = &self.clauses.borrow()[clause_id];
let &Clause::Requires(solvable_id, version_set_id) = &clause.kind else {
unreachable!();
};
if clause.has_watches() {
output.clauses_to_watch.push(clause_id);
}
output
.new_requires_clauses
.push((solvable_id, version_set_id, clause_id));
if conflict {
output.conflicting_clauses.push(clause_id);
} else if no_candidates {
// Add assertions for unit clauses (i.e. those with no matching candidates)
output.negative_assertions.push((solvable_id, clause_id));
}
}
TaskResult::NonMatchingCandidates {
solvable_id,
version_set_id,
non_matching_candidates,
} => {
tracing::trace!(
"non matching candidates available for {} {}",
self.provider()
.display_name(self.provider().version_set_name(version_set_id)),
self.provider().display_version_set(version_set_id),
);
// Add forbidden clauses for the candidates
for &forbidden_candidate in non_matching_candidates {
let (clause, conflict) = ClauseState::constrains(
solvable_id,
forbidden_candidate.into(),
version_set_id,
&self.decision_tracker,
);
let clause_id = self.clauses.borrow_mut().alloc(clause);
output.clauses_to_watch.push(clause_id);
if conflict {
output.conflicting_clauses.push(clause_id);
}
}
}
}
}
tracing::trace!("Done adding clauses for solvables");
Ok(output)
}
/// Run the CDCL algorithm to solve the SAT problem
///
/// The CDCL algorithm's job is to find a valid assignment to the variables
/// involved in the provided clauses. It works in the following steps:
///
/// 1. __Set__: Assign a value to a variable that hasn't been assigned yet.
/// An assignment in this step starts a new "level" (the first one being
/// level 1). If all variables have been assigned, then we are done.
/// 2. __Propagate__: Perform [unit propagation](https://en.wikipedia.org/wiki/Unit_propagation).
/// Assignments in this step are associated to the same "level" as the
/// decision that triggered them. This "level" metadata is useful when it
/// comes to handling conflicts. See [`Solver::propagate`] for the
/// implementation of this step.
/// 3. __Learn__: If propagation finishes without conflicts, go back to 1.
/// Otherwise find the combination of assignments that caused the
/// conflict and add a new clause to the solver to forbid that
/// combination of assignments (i.e. learn from this mistake so it is not
/// repeated in the future). Then backtrack and go back to step 1 or, if
/// the learnt clause is in conflict with existing clauses, declare the
/// problem to be unsolvable. See [`Solver::analyze`] for the
/// implementation of this step.
///
/// The solver loop can be found in [`Solver::resolve_dependencies`].
fn run_sat(&mut self) -> Result<(), UnsolvableOrCancelled> {
assert!(self.decision_tracker.is_empty());
let mut level = 0;
loop {
if level == 0 {
tracing::trace!("Level 0: Resetting the decision loop");
} else {
tracing::trace!("Level {}: Starting the decision loop", level);
}
// A level of 0 means the decision loop has been completely reset because a
// partial solution was invalidated by newly added clauses.
if level == 0 {
// Level 1 is the initial decision level
level = 1;
// Assign `true` to the root solvable. This must be installed to satisfy the
// solution. The root solvable contains the dependencies that
// were injected when calling `Solver::solve`. If we can find a
// solution were the root is installable we found a
// solution that satisfies the user requirements.
tracing::trace!("╤══ Install <root> at level {level}",);
self.decision_tracker
.try_add_decision(
Decision::new(InternalSolvableId::root(), true, ClauseId::install_root()),
level,
)
.expect("already decided");
// Add the clauses for the root solvable.
let output = self
.async_runtime
.block_on(self.add_clauses_for_solvables(vec![InternalSolvableId::root()]))?;
if let Err(clause_id) = self.process_add_clause_output(output) {
tracing::trace!("Unsolvable: {:?}", clause_id);
return Err(UnsolvableOrCancelled::Unsolvable(
self.analyze_unsolvable(clause_id),
));
}
}
tracing::trace!("Level {}: Propagating", level);
// Propagate decisions from assignments above
let propagate_result = self.propagate(level);
tracing::trace!("Propagate result: {:?}", propagate_result);
// Handle propagation errors
match propagate_result {
Ok(()) => {}
Err(PropagationError::Conflict(_, _, clause_id)) => {
if level == 1 {
return Err(UnsolvableOrCancelled::Unsolvable(
self.analyze_unsolvable(clause_id),
));
} else {
// The conflict was caused because new clauses have been added dynamically.
// We need to start over.
tracing::debug!("├─ added clause {clause} introduces a conflict which invalidates the partial solution",
clause=self.clauses.borrow()[clause_id].display(self.provider()));
level = 0;
self.decision_tracker.clear();
continue;
}
}
Err(PropagationError::Cancelled(value)) => {
// Propagation was cancelled
return Err(UnsolvableOrCancelled::Cancelled(value));
}
}
// Enter the solver loop, return immediately if no new assignments have been
// made.
tracing::trace!("Level {}: Resolving dependencies", level);
level = self.resolve_dependencies(level)?;
tracing::trace!("Level {}: Done resolving dependencies", level);
// We have a partial solution. E.g. there is a solution that satisfies all the
// clauses that have been added so far.
// Determine which solvables are part of the solution for which we did not yet
// get any dependencies. If we find any such solvable it means we
// did not arrive at the full solution yet.
let new_solvables: Vec<_> = self
.decision_tracker
.stack()
// Filter only decisions that led to a positive assignment
.filter(|d| d.value)
// Select solvables for which we do not yet have dependencies
.filter(|d| {
!self
.clauses_added_for_solvable
.borrow()
.contains(&d.solvable_id)
})
.map(|d| (d.solvable_id, d.derived_from))
.collect();
if new_solvables.is_empty() {
// If no new literals were selected this solution is complete and we can return.
tracing::trace!(
"Level {}: No new solvables selected, solution is complete",
level
);
return Ok(());
}
tracing::debug!("==== Found newly selected solvables");
tracing::debug!(
" - {}",
new_solvables
.iter()
.copied()
.format_with("\n- ", |(id, derived_from), f| f(&format_args!(
"{} (derived from {})",
id.display(self.provider()),
self.clauses.borrow()[derived_from].display(self.provider()),
)))
);
tracing::debug!("====");
// Concurrently get the solvable's clauses
let output = self.async_runtime.block_on(self.add_clauses_for_solvables(
new_solvables.iter().map(|(solvable_id, _)| *solvable_id),
))?;
// Serially process the outputs, to reduce the need for synchronization
for &clause_id in &output.conflicting_clauses {
tracing::debug!("├─ Added clause {clause} introduces a conflict which invalidates the partial solution",
clause=self.clauses.borrow()[clause_id].display(self.provider()));
}
if let Err(_first_conflicting_clause_id) = self.process_add_clause_output(output) {
self.decision_tracker.clear();
level = 0;
}
}
}
fn process_add_clause_output(&mut self, mut output: AddClauseOutput) -> Result<(), ClauseId> {
let mut clauses = self.clauses.borrow_mut();
for clause_id in output.clauses_to_watch {
debug_assert!(
clauses[clause_id].has_watches(),
"attempting to watch a clause without watches!"
);
self.watches
.start_watching(&mut clauses[clause_id], clause_id);
}
self.requires_clauses
.append(&mut output.new_requires_clauses);
self.negative_assertions
.append(&mut output.negative_assertions);
if let Some(&clause_id) = output.conflicting_clauses.first() {
return Err(clause_id);
}
Ok(())
}
/// Resolves all dependencies
///
/// Repeatedly chooses the next variable to assign, and calls
/// [`Solver::set_propagate_learn`] to drive the solving process (as you
/// can see from the name, the method executes the set, propagate and
/// learn steps described in the [`Solver::run_sat`] docs).
///
/// The next variable to assign is obtained by finding the next dependency
/// for which no concrete package has been picked yet. Then we pick the
/// highest possible version for that package, or the favored version if
/// it was provided by the user, and set its value to true.
fn resolve_dependencies(&mut self, mut level: u32) -> Result<u32, UnsolvableOrCancelled> {
loop {
tracing::trace!("Loop in resolve_dependencies: Level {}: Deciding", level);
// Make a decision. If no decision could be made it means the problem is
// satisfyable.
let Some((candidate, required_by, clause_id)) = self.decide() else {
break;
};
// Propagate the decision
level = self.set_propagate_learn(level, candidate, required_by, clause_id)?;
}
// We just went through all clauses and there are no choices left to be made
Ok(level)
}
/// Pick a solvable that we are going to assign true. This function uses a
/// heuristic to determine to best decision to make. The function
/// selects the requirement that has the least amount of working
/// available candidates and selects the best candidate from that list. This
/// ensures that if there are conflicts they are delt with as early as
/// possible.
fn decide(&mut self) -> Option<(InternalSolvableId, InternalSolvableId, ClauseId)> {
let mut best_decision = None;
for &(solvable_id, deps, clause_id) in &self.requires_clauses {
// Consider only clauses in which we have decided to install the solvable
if self.decision_tracker.assigned_value(solvable_id) != Some(true) {
continue;
}
// Consider only clauses in which no candidates have been installed
let candidates = &self.cache.version_set_to_sorted_candidates[&deps];
// Either find the first assignable candidate or determine that one of the
// candidates is already assigned in which case the clause has
// already been satisfied.
let candidate = candidates.iter().try_fold(
(None, 0),
|(first_selectable_candidate, selectable_candidates), &candidate| {
let assigned_value = self.decision_tracker.assigned_value(candidate.into());
match assigned_value {
Some(true) => ControlFlow::Break(()),
Some(false) => ControlFlow::Continue((
first_selectable_candidate,
selectable_candidates,
)),
None => ControlFlow::Continue((
first_selectable_candidate.or(Some(candidate)),
selectable_candidates + 1,
)),
}
},
);
match candidate {
ControlFlow::Continue((Some(candidate), count)) => {
let possible_decision = (candidate, solvable_id, clause_id);
best_decision = Some(match best_decision {
None => (count, possible_decision),
Some((best_count, _)) if count < best_count => {
(count, possible_decision)
}
Some(best_decision) => best_decision,
})
}
ControlFlow::Break(_) => continue,
ControlFlow::Continue((None, _)) => unreachable!("when we get here it means that all candidates have been assigned false. This should not be able to happen at this point because during propagation the solvable should have been assigned false as well."),
}
}
if let Some((count, (candidate, _solvable_id, clause_id))) = best_decision {
tracing::trace!(
"deciding to assign {}, ({}, {} possible candidates)",
self.provider().display_solvable(candidate),
self.clauses.borrow()[clause_id].display(self.provider()),
count,
);
}
// Could not find a requirement that needs satisfying.
best_decision.map(|(_best_count, (candidate, required_by, via))| {
(candidate.into(), required_by, via)
})
}
/// Executes one iteration of the CDCL loop
///
/// A set-propagate-learn round is always initiated by a requirement clause
/// (i.e. [`Clause::Requires`]). The parameters include the variable
/// associated to the candidate for the dependency (`solvable`), the
/// package that originates the dependency (`required_by`), and the
/// id of the requires clause (`clause_id`).
///
/// Refer to the documentation of [`Solver::run_sat`] for details on the
/// CDCL algorithm.
///
/// Returns the new level after this set-propagate-learn round, or a
/// [`Problem`] if we discovered that the requested jobs are
/// unsatisfiable.
fn set_propagate_learn(
&mut self,
mut level: u32,
solvable: InternalSolvableId,
required_by: InternalSolvableId,
clause_id: ClauseId,
) -> Result<u32, UnsolvableOrCancelled> {
level += 1;
tracing::trace!(
"╤══ Install {} at level {level} (required by {})",
solvable.display(self.provider()),
required_by.display(self.provider())
);
// Add the decision to the tracker
self.decision_tracker
.try_add_decision(Decision::new(solvable, true, clause_id), level)
.expect("bug: solvable was already decided!");
self.propagate_and_learn(level)
}
fn propagate_and_learn(&mut self, mut level: u32) -> Result<u32, UnsolvableOrCancelled> {
loop {
match self.propagate(level) {
Ok(()) => {
// Propagation completed
tracing::debug!("╘══ Propagation completed");
return Ok(level);
}
Err(PropagationError::Cancelled(value)) => {
// Propagation cancelled
tracing::debug!("╘══ Propagation cancelled");
return Err(UnsolvableOrCancelled::Cancelled(value));
}
Err(PropagationError::Conflict(
conflicting_solvable,
attempted_value,
conflicting_clause,
)) => {
level = self.learn_from_conflict(
level,
conflicting_solvable,
attempted_value,
conflicting_clause,
)?;
}
}
}
}
fn learn_from_conflict(
&mut self,
mut level: u32,
conflicting_solvable: InternalSolvableId,
attempted_value: bool,
conflicting_clause: ClauseId,
) -> Result<u32, Problem> {
{
tracing::info!(
"├─ Propagation conflicted: could not set {solvable} to {attempted_value}",
solvable = conflicting_solvable.display(self.provider()),
);
tracing::info!(
"│ During unit propagation for clause: {}",
self.clauses.borrow()[conflicting_clause].display(self.provider())
);
tracing::info!(
"│ Previously decided value: {}. Derived from: {}",
!attempted_value,
self.clauses.borrow()[self
.decision_tracker
.find_clause_for_assignment(conflicting_solvable)
.unwrap()]
.display(self.provider()),
);
}
if level == 1 {
tracing::info!("╘══ UNSOLVABLE");
for decision in self.decision_tracker.stack() {
let clause = &self.clauses.borrow()[decision.derived_from];
let level = self.decision_tracker.level(decision.solvable_id);
let action = if decision.value { "install" } else { "forbid" };
if let Clause::ForbidMultipleInstances(..) = clause.kind {
// Skip forbids clauses, to reduce noise
continue;
}
tracing::info!(
"* ({level}) {action} {}. Reason: {}",
decision.solvable_id.display(self.provider()),
clause.display(self.provider()),
);
}
return Err(self.analyze_unsolvable(conflicting_clause));
}
let (new_level, learned_clause_id, literal) =
self.analyze(level, conflicting_solvable, conflicting_clause);
level = new_level;
tracing::debug!("├─ Backtracked to level {level}");
// Optimization: propagate right now, since we know that the clause is a unit
// clause
let decision = literal.satisfying_value();
self.decision_tracker
.try_add_decision(
Decision::new(literal.solvable_id, decision, learned_clause_id),
level,
)
.expect("bug: solvable was already decided!");
tracing::debug!(
"├─ Propagate after learn: {} = {decision}",
literal.solvable_id.display(self.provider()),
);
Ok(level)
}
/// The propagate step of the CDCL algorithm
///
/// Propagation is implemented by means of watches: each clause that has two
/// or more literals is "subscribed" to changes in the values of two
/// solvables that appear in the clause. When a value is assigned to a
/// solvable, each of the clauses tracking that solvable will be notified.
/// That way, the clause can check whether the literal that is using the
/// solvable has become false, in which case it picks a new solvable to
/// watch (if available) or triggers an assignment.
fn propagate(&mut self, level: u32) -> Result<(), PropagationError> {
if let Some(value) = self.provider().should_cancel_with_value() {
return Err(PropagationError::Cancelled(value));
};
// Negative assertions derived from other rules (assertions are clauses that
// consist of a single literal, and therefore do not have watches)
for &(solvable_id, clause_id) in &self.negative_assertions {
let value = false;