apt 2.9.33 commandline package manager

solver3.h
1/*
2 * solver3.h - The APT 3.0 solver
3 *
4 * Copyright (c) 2023 Julian Andres Klode
5 * Copyright (c) 2023 Canonical Ltd
6 *
7 * SPDX-License-Identifier: GPL-2.0+
8 */
9
10#include <cassert>
11#include <memory>
12#include <optional>
13#include <queue>
14#include <vector>
15
16#include <apt-pkg/configuration.h>
17#include <apt-pkg/depcache.h>
18#include <apt-pkg/edsp.h>
19#include <apt-pkg/pkgcache.h>
20#include <apt-pkg/policy.h>
21
22 namespace APT
23{
24
31 template <typename K, typename V, bool fast = false>
32 class ContiguousCacheMap
33{
34 V *data_; // Avoid std::unique_ptr() as it may check that it's non-null.
35
36 public:
37 ContiguousCacheMap(pkgCache &cache)
38 {
39 static_assert(std::is_constructible_v<V>);
40 if constexpr (fast)
41 {
42 static_assert(std::is_trivially_constructible_v<V>);
43 static_assert(std::is_trivially_destructible_v<V>);
44 }
45
46 size_t size;
47 if constexpr (std::is_same_v<K, pkgCache::Version>)
48 size = cache.Head().VersionCount;
49 else if constexpr (std::is_same_v<K, pkgCache::Package>)
50 size = cache.Head().PackageCount;
51 else
52 static_assert(false, "Cannot construct map for key type");
53
54 data_ = new V[size]{};
55 }
56 V &operator[](const K *key) { return data_[key->ID]; }
57 const V &operator[](const K *key) const { return data_[key->ID]; }
58 ~ContiguousCacheMap() { delete[] data_; }
59};
60
64 template <typename K, typename V>
65 using FastContiguousCacheMap = ContiguousCacheMap<K, V, true>;
66
67/*
68 * \brief APT 3.0 solver
69 *
70 * This is a simple solver focused on understandability and sensible results, it
71 * will not generally find all solutions to the problem but will try to find the best
72 * ones.
73 *
74 * It is a brute force solver with heuristics, conflicts learning, and 2**32 levels
75 * of backtracking.
76 */
77 class Solver
78{
79 enum class Decision : uint16_t;
80 enum class Hint : uint16_t;
81 struct Var;
82 struct CompareProviders3;
83 struct State;
84 struct Clause;
85 struct Work;
86 struct Solved;
87 friend struct std::hash<APT::Solver::Var>;
88
89 // \brief Groups of works, these are ordered.
90 //
91 // Later items will be skipped if they are optional, or we will when backtracking,
92 // try a different choice for them.
93 enum class Group : uint8_t
94 {
95 HoldOrDelete,
96
97 // Satisfying dependencies on entirely new packages first is a good idea because
98 // it may contain replacement packages like libfoo1t64 whereas we later will see
99 // Depends: libfoo1 where libfoo1t64 Provides libfoo1 and we'd have to choose.
100 SatisfyNew,
101 Satisfy,
102 // On a similar note as for SatisfyNew, if the dependency contains obsolete packages
103 // try it last.
104 SatisfyObsolete,
105
106 // Select a version of a package chosen for install.
107 SelectVersion,
108
109 // My intuition tells me that we should try to schedule upgrades first, then
110 // any non-obsolete installed packages, and only finally obsolete ones, such
111 // that newer packages guide resolution of dependencies for older ones, they
112 // may have more stringent dependencies, like a (>> 2) whereas an obsolete
113 // package may have a (>> 1), for example.
114 UpgradeManual,
115 InstallManual,
116 ObsoleteManual,
117
118 // Automatically installed packages must come last in the group, this allows
119 // us to see if they were installed as a dependency of a manually installed package,
120 // allowing a simple implementation of an autoremoval code.
121 UpgradeAuto,
122 KeepAuto,
123 ObsoleteAuto
124 };
125
126 // \brief Type to record depth at. This may very well be a 16-bit
127 // unsigned integer, then change Solver::State::Decision to be a
128 // uint16_t class enum as well to get a more compact space.
129 using depth_type = unsigned int;
130
131 // Documentation
132 template <typename T>
133 using heap = std::vector<T>;
134
135 static_assert(sizeof(depth_type) >= sizeof(map_id_t));
136
137 // Cache is needed to construct Iterators from Version objects we see
138 pkgCache &cache;
139 // Policy is needed for determining candidate version.
140 pkgDepCache::Policy &policy;
141 // Root state
142 std::unique_ptr<State> rootState;
143 // States for packages
144 ContiguousCacheMap<pkgCache::Package, State> pkgStates;
145 // States for versions
146 ContiguousCacheMap<pkgCache::Version, State> verStates;
147
148 // \brief Helper function for safe access to package state.
149 inline State &operator[](const pkgCache::Package *P)
150 {
151 return pkgStates[P];
152 }
153 inline const State &operator[](const pkgCache::Package *P) const
154 {
155 return pkgStates[P];
156 }
157
158 // \brief Helper function for safe access to version state.
159 inline State &operator[](const pkgCache::Version *V)
160 {
161 return verStates[V];
162 }
163 inline const State &operator[](const pkgCache::Version *V) const
164 {
165 return verStates[V];
166 }
167 // \brief Helper function for safe access to either state.
168 inline State &operator[](Var r);
169 inline const State &operator[](Var r) const;
170
171 mutable FastContiguousCacheMap<pkgCache::Package, char> pkgObsolete;
172 // \brief Check if package is obsolete.
173 // \param AllowManual controls whether manual packages can be obsolete
174 bool Obsolete(pkgCache::PkgIterator pkg, bool AllowManual=false) const;
175 bool ObsoletedByNewerSourceVersion(pkgCache::VerIterator cand) const;
176
177 mutable FastContiguousCacheMap<pkgCache::Version, short> priorities;
178 short GetPriority(pkgCache::VerIterator ver) const
179 {
180 if (priorities[ver] == 0)
181 priorities[ver] = policy.GetPriority(ver);
182 return priorities[ver];
183 }
184
185 mutable ContiguousCacheMap<pkgCache::Package, pkgCache::VerIterator> candidates;
186 pkgCache::VerIterator GetCandidateVer(pkgCache::PkgIterator pkg) const
187 {
188 if (candidates[pkg].end())
189 candidates[pkg] = policy.GetCandidateVer(pkg);
190 return candidates[pkg];
191 }
192
193 // \brief Heap of the remaining work.
194 //
195 // We are using an std::vector with std::make_heap(), std::push_heap(),
196 // and std::pop_heap() rather than a priority_queue because we need to
197 // be able to iterate over the queued work and see if a choice would
198 // invalidate any work.
199 heap<Work> work{};
200
201 // \brief Backlog of solved work.
202 //
203 // Solved work may become invalidated when backtracking, so store it
204 // here to revisit it later. This is similar to what MiniSAT calls the
205 // trail; one distinction is that we have both literals and our work
206 // queue to be concerned about
207 std::vector<Solved> solved{};
208
209 // \brief Propagation queue
210 std::queue<Var> propQ;
211 // \brief Discover variables
212 std::queue<Var> discoverQ;
213
214 // \brief Current decision level.
215 //
216 // This is an index into the solved vector.
217 std::vector<depth_type> choices{};
218
219 // \brief The time we called Solve()
220 time_t startTime;
221
222 EDSP::Request::Flags requestFlags;
224 std::string version{_config->Find("APT::Solver", "3.0")};
225 // \brief Debug level
226 int debug{_config->FindI("Debug::APT::Solver")};
227 // \brief If set, we try to keep automatically installed packages installed.
228 bool KeepAuto{version == "3.0" || not _config->FindB("APT::Get::AutomaticRemove")};
229 // \brief Determines if we are in upgrade mode.
230 bool IsUpgrade{_config->FindB("APT::Solver::Upgrade", requestFlags &EDSP::Request::UPGRADE_ALL)};
231 // \brief If set, removals are allowed.
232 bool AllowRemove{_config->FindB("APT::Solver::Remove", not(requestFlags & EDSP::Request::FORBID_REMOVE))};
233 // \brief If set, removal of manual packages is allowed.
234 bool AllowRemoveManual{AllowRemove && _config->FindB("APT::Solver::RemoveManual", false)};
235 // \brief If set, installs are allowed.
236 bool AllowInstall{_config->FindB("APT::Solver::Install", not(requestFlags & EDSP::Request::FORBID_NEW_INSTALL))};
237 // \brief If set, we use strict pinning.
238 bool StrictPinning{_config->FindB("APT::Solver::Strict-Pinning", true)};
239 // \brief If set, we install missing recommends and pick new best packages.
240 bool FixPolicyBroken{_config->FindB("APT::Get::Fix-Policy-Broken")};
241 // \brief If set, we use strict pinning.
242 bool DeferVersionSelection{_config->FindB("APT::Solver::Defer-Version-Selection", true)};
243 // \brief If set, we use strict pinning.
244 int Timeout{_config->FindI("APT::Solver::Timeout", 10)};
245
246 // \brief Keep recommends installed
247 bool KeepRecommends{_config->FindB("APT::AutoRemove::RecommendsImportant", true)};
248 // \brief Keep suggests installed
249 bool KeepSuggests{_config->FindB("APT::AutoRemove::SuggestsImportant", true)};
250
251 // \brief Discover a variable, translating the underlying dependencies to the SAT presentation
252 //
253 // This does a breadth-first search of the entire dependency tree of var,
254 // utilizing the discoverQ above.
255 void Discover(Var var);
256 // \brief Link a clause into the watchers
257 const Clause *RegisterClause(Clause &&clause);
258 // \brief Enqueue dependencies shared by all versions of the package.
259 void RegisterCommonDependencies(pkgCache::PkgIterator Pkg);
260
261 // \brief Translate an or group into a clause object
262 [[nodiscard]] Clause TranslateOrGroup(pkgCache::DepIterator start, pkgCache::DepIterator end, Var reason);
263 // \brief Propagate all pending propagations
264 [[nodiscard]] bool Propagate();
265
266 // \brief Return the current depth (choices.size() with casting)
267 depth_type depth()
268 {
269 return static_cast<depth_type>(choices.size());
270 }
271 inline Var bestReason(Clause const *clause, Var var) const;
272
273 public:
274 // \brief Create a new decision level.
275 void Push(Work work);
276 // \brief Revert to the previous decision level.
277 [[nodiscard]] bool Pop();
278 // \brief Undo a single assignment / solved work item
279 void UndoOne();
280 // \brief Add work to our work queue.
281 [[nodiscard]] bool AddWork(Work &&work);
282
283 // \brief Basic solver initializer. This cannot fail.
284 Solver(pkgCache &Cache, pkgDepCache::Policy &Policy, EDSP::Request::Flags requestFlags);
285
286 // Assume that the variable is decided as specified.
287 [[nodiscard]] bool Assume(Var var, bool decision, const Clause *reason = nullptr);
288 // Enqueue a decision fact
289 [[nodiscard]] bool Enqueue(Var var, bool decision, const Clause *reason = nullptr);
290
291 // \brief Apply the selections from the dep cache to the solver
292 [[nodiscard]] bool FromDepCache(pkgDepCache &depcache);
293 // \brief Apply the solver result to the depCache
294 [[nodiscard]] bool ToDepCache(pkgDepCache &depcache) const;
295
296 // \brief Solve the dependencies
297 [[nodiscard]] bool Solve();
298
299 // Print dependency chain
300 std::string WhyStr(Var reason) const;
301
313 std::string LongWhyStr(Var var, bool decision, const Clause *rclause, std::string prefix, std::unordered_set<Var> &seen) const;
314};
315
316}; // namespace APT
317
326 struct APT::Solver::Var
327{
328 uint32_t value;
329
330 explicit constexpr Var(uint32_t value = 0) : value{value} {}
331 explicit Var(pkgCache::PkgIterator const &Pkg) : value(uint32_t(Pkg.MapPointer()) << 1) {}
332 explicit Var(pkgCache::VerIterator const &Ver) : value(uint32_t(Ver.MapPointer()) << 1 | 1) {}
333
334 inline constexpr bool isVersion() const { return value & 1; }
335 inline constexpr uint32_t mapPtr() const { return value >> 1; }
336
337 // \brief Return the package, if any, otherwise 0.
338 map_pointer<pkgCache::Package> Pkg() const
339 {
340 return isVersion() ? 0 : map_pointer<pkgCache::Package>{mapPtr()};
341 }
342 // \brief Return the version, if any, otherwise 0.
343 map_pointer<pkgCache::Version> Ver() const
344 {
345 return isVersion() ? map_pointer<pkgCache::Version>{mapPtr()} : 0;
346 }
347 // \brief Return the package iterator if storing a package, or an empty one
348 pkgCache::PkgIterator Pkg(pkgCache &cache) const
349 {
350 return isVersion() ? pkgCache::PkgIterator() : pkgCache::PkgIterator(cache, cache.PkgP + Pkg());
351 }
352 // \brief Return the version iterator if storing a package, or an empty end.
353 pkgCache::VerIterator Ver(pkgCache &cache) const
354 {
355 return isVersion() ? pkgCache::VerIterator(cache, cache.VerP + Ver()) : pkgCache::VerIterator();
356 }
357 // \brief Return a package, cast from version if needed
358 pkgCache::PkgIterator CastPkg(pkgCache &cache) const
359 {
360 return isVersion() ? Ver(cache).ParentPkg() : Pkg(cache);
361 }
362 // \brief Check if there is no reason.
363 constexpr bool empty() const { return value == 0; }
364 constexpr bool operator!=(Var const other) const { return value != other.value; }
365 constexpr bool operator==(Var const other) const { return value == other.value; }
366
367 std::string toString(pkgCache &cache) const
368 {
369 if (auto P = Pkg(cache); not P.end())
370 return P.FullName();
371 if (auto V = Ver(cache); not V.end())
372 return V.ParentPkg().FullName() + "=" + V.VerStr();
373 return "(root)";
374 }
375};
376
383 struct APT::Solver::Clause
384{
385 // \brief Underyling dependency
386 pkgCache::Dependency *dep = nullptr;
387 // \brief Var for the work
388 Var reason;
389 // \brief The group we are in
390 Group group;
391 // \brief Possible solutions to this task, ordered in order of preference.
392 std::vector<Var> solutions{};
393 // \brief An optional clause does not need to be satisfied
394 bool optional;
395
396 // \brief A negative clause negates the solutions, that is X->A|B you get X->!(A|B), aka X->!A&!B
397 bool negative;
398
399 inline Clause(Var reason, Group group, bool optional = false, bool negative = false) : reason(reason), group(group), optional(optional), negative(negative) {}
400
401 std::string toString(pkgCache &cache, bool pretty = false) const;
402};
403
414 struct APT::Solver::Work
415{
416 const Clause *clause;
417
418 // \brief The depth at which the item has been added
419 depth_type depth;
420
421 // This is a union because we only need to store the choice we made when adding
422 // to the choice vector, and we don't need the size of valid choices in there.
423 union
424 {
425 // The choice we took
426 Var choice;
427 // Number of valid choices
428 size_t size{0};
429 };
430
431 // \brief This item should be removed from the queue.
432 bool erased{false};
433
434 bool operator<(APT::Solver::Work const &b) const;
435 std::string toString(pkgCache &cache) const;
436 inline Work(const Clause *clause, depth_type depth) : clause(clause), depth(depth) {}
437};
438
439// \brief This essentially describes the install state in RFC2119 terms.
440 enum class APT::Solver::Decision : uint16_t
441{
442 // \brief We have not made a choice about the package yet
443 NONE,
444 // \brief We need to install this package
445 MUST,
446 // \brief We cannot install this package (need conflicts with it)
447 MUSTNOT,
448};
449
456 struct APT::Solver::State
457{
458 // \brief The reason for causing this state (invalid for NONE).
459 //
460 // Rejects may have been caused by a later state. Consider we select
461 // between x1 and x2 in depth = N. If we now find dependencies of x1
462 // leading to a conflict with a package in K < N, we will record all
463 // of them as REJECT in depth = K.
464 //
465 // You can follow the reason chain upwards as long as the depth
466 // doesn't increase to unwind.
467 //
468 // Vars < 0 are package ID, reasons > 0 are version IDs.
469 const Clause *reason{};
470
471 // \brief The depth at which the decision has been taken
472 depth_type depth{0};
473
474 // \brief This essentially describes the install state in RFC2119 terms.
475 Decision decision{Decision::NONE};
476
477 // \brief Flags.
478 struct
479 {
480 bool discovered{};
481 bool manual{};
482 } flags;
483
484 static_assert(sizeof(flags) <= sizeof(int));
485
486 // \brief Clauses owned by this package/version
487 std::vector<std::unique_ptr<Clause>> clauses;
488 // \brief Reverse clauses, that is dependencies (or conflicts) from other packages on this one
489 std::vector<const Clause *> rclauses;
490};
491
498 struct APT::Solver::Solved
499{
500 // \brief A variable that has been assigned. We store this as a reason (FIXME: Rename Var to Var)
501 Var assigned;
502 // \brief A work item that has been solved. This needs to be put back on the queue.
503 std::optional<Work> work;
504};
505
506 inline APT::Solver::State &APT::Solver::operator[](Var r)
507{
508 if (auto P = r.Pkg())
509 return (*this)[cache.PkgP + P];
510 if (auto V = r.Ver())
511 return (*this)[cache.VerP + V];
512 return *rootState.get();
513}
514
515 inline const APT::Solver::State &APT::Solver::operator[](Var r) const
516{
517 return const_cast<Solver &>(*this)[r];
518}
519
520// Custom specialization of std::hash can be injected in namespace std.
521 template <>
522 struct std::hash<APT::Solver::Var>
523{
524 std::hash<decltype(APT::Solver::Var::value)> hash_value;
525 std::size_t operator()(const APT::Solver::Var &v) const noexcept { return hash_value(v.value); }
526};
APT::ContiguousCacheMap
A simple mapping from objects in the cache to user-defined types.
Definition solver3.h:33
APT::Solver
Definition solver3.h:78
APT::Solver::UndoOne
void UndoOne()
Definition solver3.cc:897
APT::Solver::Solver
Solver(pkgCache &Cache, pkgDepCache::Policy &Policy, EDSP::Request::Flags requestFlags)
Definition solver3.cc:199
APT::Solver::Pop
bool Pop()
Definition solver3.cc:928
APT::Solver::LongWhyStr
std::string LongWhyStr(Var var, bool decision, const Clause *rclause, std::string prefix, std::unordered_set< Var > &seen) const
Print a long reason string.
Definition solver3.cc:311
map_pointer
Definition pkgcache.h:98
pkgCache::DepIterator
Definition cacheiterators.h:327
pkgCache::PkgIterator
Definition cacheiterators.h:147
pkgCache::VerIterator
Definition cacheiterators.h:218
pkgCache
Definition pkgcache.h:126
pkgDepCache::Policy
Definition depcache.h:250
pkgDepCache
Definition depcache.h:63
edsp.h
EDSP::Request::Flags
Flags
Definition edsp.h:31
EDSP::Request::FORBID_REMOVE
@ FORBID_REMOVE
Definition edsp.h:35
EDSP::Request::FORBID_NEW_INSTALL
@ FORBID_NEW_INSTALL
Definition edsp.h:34
EDSP::Request::UPGRADE_ALL
@ UPGRADE_ALL
Definition edsp.h:33
pkgcache.h
pkgCache - Structure definitions for the cache file
APT::Solver::Clause
A single clause.
Definition solver3.h:384
APT::Solver::CompareProviders3
Definition solver3.cc:43
APT::Solver::Solved
A solved item.
Definition solver3.h:499
APT::Solver::State
The solver state.
Definition solver3.h:457
APT::Solver::Var
Tagged union holding either a package, version, or nothing; representing the reason for installing so...
Definition solver3.h:327
APT::Solver::Work
A single work item.
Definition solver3.h:415
pkgCache::Dependency
Definition pkgcache.h:783
pkgCache::Package
contains information for a single unique package
Definition pkgcache.h:460
pkgCache::Version
information for a single version of a package
Definition pkgcache.h:652