Chromium Code Reviews

Side by Side Diff: utils/pub/solver/backtracking_solver.dart

Issue 13095015: Use backtracking when solving dependency constraints. (Closed) Base URL: https://dart.googlecode.com/svn/branches/bleeding_edge/dart
Patch Set: Revised. Created 7 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | | Annotate | Revision Log
« no previous file with comments | « utils/pub/pub.dart ('k') | utils/pub/solver/greedy_solver.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 /// A back-tracking depth-first solver. Attempts to find the best solution for
6 /// a root package's transitive dependency graph, where a "solution" is a set
7 /// of concrete package versions. A valid solution will select concrete
8 /// versions for every package reached from the root package's dependency graph,
9 /// and each of those packages will fit the version constraints placed on it.
10 ///
11 /// The solver builds up a solution incrementally by traversing the dependency
12 /// graph starting at the root package. When it reaches a new package, it gets
13 /// the set of versions that meet the current constraint placed on it. It
14 /// *speculatively* selects one version from that set and adds it to the
15 /// current solution and then proceeds. If it fully traverses the dependency
16 /// graph, the solution is valid and it stops.
17 ///
18 /// If it reaches an error because:
19 ///
20 /// - A new dependency is placed on a package that's already been selected in
21 /// the solution and the selected version doesn't match the new constraint.
22 ///
23 /// - There are no versions available that meet the constraint placed on a
24 /// package.
25 ///
26 /// - etc.
27 ///
28 /// then the current solution is invalid. It will then backtrack to the most
29 /// recent speculative version choice and try the next one. That becomes the
30 /// new potential solution and it tries to proceed from there. It will keep
31 /// doing this, traversing and then backtracking when it meets a failure until
32 /// a valid solution has been found or until all possible options for all
33 /// speculative choices have been exhausted.
34 library version_solver2;
35
36 import 'dart:async';
37 import 'dart:collection' show Queue;
38
39 import '../lock_file.dart';
40 import '../log.dart' as log;
41 import '../package.dart';
42 import '../source.dart';
43 import '../source_registry.dart';
44 import '../version.dart';
45 import 'version_solver.dart';
46
47 /// The top-level solver. Keeps track of the current potential solution, and
48 /// the other possible versions for speculative package selections. Backtracks
49 /// and advances to the next potential solution in the case of a failure.
50 class BacktrackingVersionSolver extends VersionSolver {
51 /// The set of packages that are being explicitly updated. The solver will
52 /// only allow the very latest version for each of these packages.
53 final _forceLatest = new Set<String>();
54
55 /// Every time a package is encountered when traversing the dependency graph,
56 /// the solver must select a version for it, sometimes when multiple versions
57 /// are valid. This keeps track of which versions have been selected so far
58 /// and which remain to be tried.
59 ///
60 /// Each entry in the list is an ordered [Queue] of versions to try for a
61 /// single package. The first item in the queue is the currently selected
62 /// version for that package. When a new dependency is encountered, a queue
63 /// of versions of that dependency is pushed onto the end of the list. A
64 /// queue is removed from the list once it's empty, indicating that none of
65 /// the versions provided a solution.
66 ///
67 /// The solver tries versions in depth-first order, so only the last queue in
68 /// the list will have items removed from it. When a new constraint is placed
69 /// on an already-selected package, and that constraint doesn't match the
70 /// selected version, that will cause the current solution to fail and
71 /// trigger backtracking.
72 final _selected = <Queue<PackageId>>[];
73
74 /// The number of possible solutions that have been attempted.
75 int get attemptedSolutions => _attemptedSolutions;
76 var _attemptedSolutions = 0;
77
78 BacktrackingVersionSolver(SourceRegistry sources, Package root,
79 LockFile lockFile, List<String> useLatest)
80 : super(sources, root, lockFile, useLatest);
81
82 void forceLatestVersion(String package) {
83 _forceLatest.add(package);
84 }
85
86 Future<List<PackageId>> runSolver() => _traverseSolution();
87
88 /// Adds [versions], which is the list of all allowed versions of a given
89 /// package, to the set of versions to consider for solutions. The first item
90 /// in the list will be the currently selected version of that package.
91 /// Subsequent items will be tried if it the current selection fails. Returns
92 /// the first selected version.
93 PackageId select(Iterable<PackageId> versions) {
94 _selected.add(new Queue<PackageId>.from(versions));
95 logSolve();
96 return versions.first;
97 }
98
99 /// Returns the the currently selected id for the package [name] or `null` if
100 /// no concrete version has been selected for that package yet.
101 PackageId getSelected(String name) {
102 // Always prefer the root package.
103 if (root.name == name) return new PackageId.root(root);
104
105 // Look through the current selections.
106 for (var i = _selected.length - 1; i >= 0; i--) {
107 if (_selected[i].first.name == name) return _selected[i].first;
108 }
109
110 return null;
111 }
112
113 /// Gets the version of [package] currently locked in the lock file. Returns
114 /// `null` if it isn't in the lockfile (or has been unlocked).
115 PackageId getLocked(String package) => lockFile.packages[package];
116
117 /// Traverses the root package's dependency graph using the current potential
118 /// solution. If successful, completes to the solution. If not, backtracks
119 /// to the most recently selected version of a package and tries the next
120 /// version of it. If there are no more versions, continues to backtrack to
121 /// previous selections, and so on. If there is nothing left to backtrack to,
122 /// completes to the last failure that occurred.
123 Future<List<PackageId>> _traverseSolution() {
124 _attemptedSolutions++;
125
126 return new Traverser(this).traverse().catchError((error) {
127 if (error.error is! SolveFailure) throw error;
128
129 if (_backtrack(error.error)) return _traverseSolution();
130
131 // All out of solutions, so fail.
132 throw error;
133 });
134 }
135
136 /// Backtracks from the current failed solution and determines the next
137 /// solution to try. If possible, it will backjump based on the cause of the
138 /// [failure] to minize backtracking. Otherwise, it will simply backtrack to
139 /// the next possible solution.
140 ///
141 /// Returns `true` if there is a new solution to try.
142 bool _backtrack(SolveFailure failure) {
143 // Look for the most recently selected relevant backjumping point.
144 var jumpTo;
145 var dependers = failure.dependencies.map((dep) => dep.depender).toSet();
146 for (var i = _selected.length - 1; i >= 0; i--) {
147 var name = _selected[i].first.name;
148
149 // If we reach the package that failed, backjump to there.
150 if (failure.package == name) {
151 logSolve('jump to failing package $name');
152 jumpTo = i;
153 break;
154 }
155
156 // If we reach a package whose dependency led to the failing package,
157 // backjump to there.
158 if (dependers.contains(name)) {
159 logSolve('jump to depending package $name');
160 jumpTo = i;
161 break;
162 }
163 }
164
165 if (jumpTo != null) {
166 _selected.removeRange(jumpTo + 1, _selected.length - jumpTo - 1);
167 }
168
169 while (!_selected.isEmpty) {
170 // Advance past the current version of the leaf-most package.
171 _selected.last.removeFirst();
172 if (!_selected.last.isEmpty) {
173 logSolve();
174 return true;
175 }
176
177 // That package has no more versions, so pop it and try the next one.
178 _selected.removeLast();
179 }
180
181 return false;
182 }
183
184 /// Logs [message] in the context of the current selected packages. If
185 /// [message] is omitted, just logs a description of leaf-most selection.
186 void logSolve([String message]) {
187 if (message == null) {
188 if (_selected.isEmpty) {
189 message = "* start at root";
190 } else {
191 message = "* select ${_selected.last.first}";
192 }
193 } else {
194 // Otherwise, indent it under the current selected package.
195 message = "| $message";
196 }
197
198 // Indent for the previous selections.
199 var buffer = new StringBuffer();
200 buffer.writeAll(_selected.skip(1).map((_) => '| '));
201 buffer.write(message);
202 log.solver(buffer);
203 }
204 }
205
206 /// Given the solver's current set of selected package versions, this tries to
207 /// traverse the dependency graph and see if a complete set of valid versions
208 /// has been chosen. If it reaches a conflict, it will fail and stop
209 /// traversing. If it reaches a package that isn't selected it will refine the
210 /// solution by adding that package's set of allowed versions to the solver and
211 /// then select the best one and continue.
212 class Traverser {
213 final BacktrackingVersionSolver _solver;
214
215 /// The queue of packages left to traverse. We do a breadth-first traversal
216 /// using an explicit queue just to avoid the code complexity of a recursive
217 /// asynchronous traversal.
218 final _packages = new Queue<PackageId>();
219
220 /// The packages we have already traversed. Used to avoid traversing the same
221 /// package multiple times, and to build the complete solution results.
222 final _visited = new Set<PackageId>();
223
224 /// The dependencies visited so far in the traversal. For each package name
225 /// (the map key) we track the list of dependencies that other packages have
226 /// placed on it so that we can calculate the complete constraint for shared
227 /// dependencies.
228 final _dependencies = <String, List<Dependency>>{};
229
230 Traverser(this._solver);
231
232 /// Walks the dependency graph starting at the root package and validates
233 /// that each reached package has a valid version selected.
234 Future<List<PackageId>> traverse() {
235 // Start at the root.
236 _packages.add(new PackageId.root(_solver.root));
237 return _traversePackage();
238 }
239
240 /// Traverses the next package in the queue. Completes to a list of package
241 /// IDs if the traversal completed successfully and found a solution.
242 /// Completes to an error if the traversal failed. Otherwise, recurses to the
243 /// next package in the queue, etc.
244 Future<List<PackageId>> _traversePackage() {
nweiz 2013/04/11 22:12:05 What do you think of wrapping the whole method in
Bob Nystrom 2013/04/16 18:34:17 If there were more .immediate() calls I would but
245 if (_packages.isEmpty) {
246 // We traversed the whole graph. If we got here, we successfully found
247 // a solution.
248 return new Future<List<PackageId>>.immediate(_visited.toList());
249 }
250
251 var id = _packages.removeFirst();
252
253 // Don't visit the same package twice.
254 if (_visited.contains(id)) {
255 return _traversePackage();
256 }
257 _visited.add(id);
258
259 return _solver.cache.getPubspec(id).then((pubspec) {
260 var refs = pubspec.dependencies.toList();
261
262 // Include dev dependencies of the root package.
263 if (id.isRoot) refs.addAll(pubspec.devDependencies);
264
265 // TODO(rnystrom): Sort in some best-first order to minimize backtracking.
266 // Bundler's model is:
267 // Easiest to resolve is defined by:
268 // 1) Is this gem already activated?
269 // 2) Do the version requirements include prereleased gems?
270 // 3) Sort by number of gems available in the source.
271 // Can probably do something similar, but we should profile against
272 // real-world package graphs that require backtracking to see which
273 // heuristics work best for Dart.
274 refs.sort((a, b) => a.name.compareTo(b.name));
275
276 return _traverseRefs(id.name, new Queue<PackageRef>.from(refs));
277 });
278 }
279
280 /// Traverses the references that [depender] depends on, stored in [refs].
281 /// Desctructively modifies [refs]. Completes to a list of packages if the
282 /// traversal is complete. Completes it to an error if a failure occurred.
283 /// Otherwise, recurses.
284 Future<List<PackageId>> _traverseRefs(String depender,
nweiz 2013/04/11 22:12:05 Shouldn't there be a call to [resetStack] somewher
Bob Nystrom 2013/04/16 18:34:17 Will the Future.of() here accomplish the same thin
nweiz 2013/04/16 23:20:38 No. Future.of (now Future.sync) is synchronous, so
Bob Nystrom 2013/04/16 23:58:45 Yes, it's using the latter now. I was using the ol
285 Queue<PackageRef> refs) {
286 // Move onto the next package if we've traversed all of these references.
287 if (refs.isEmpty) return _traversePackage();
288
289 return new Future.of(() {
290 var ref = refs.removeFirst();
291
292 _validateDependency(ref, depender);
293 var constraint = _addConstraint(ref, depender);
294
295 var selected = _validateSelected(ref, constraint);
296 if (selected != null) {
297 // The selected package version is good, so enqueue it to traverse into
298 // it.
299 _packages.add(selected);
300 return _traverseRefs(depender, refs);
301 }
302
303 // We haven't selected a version. Get all of the versions that match the
304 // constraints we currently have for this package and add them to the
305 // set of solutions to try.
306 return _selectPackage(ref, constraint).then(
307 (_) => _traverseRefs(depender, refs));
308 });
309 }
310
311 /// Ensures that dependency [ref] from [depender] is consistent with the
312 /// other dependencies on the same package. Throws a [SolverFailure]
313 /// exception if not. Only validates sources and descriptions, not the
314 /// version.
315 void _validateDependency(PackageRef ref, String depender) {
316 // Make sure the dependencies agree on source and description.
317 var required = _getRequired(ref.name);
318 if (required == null) return;
319
320 // Make sure all of the existing sources match the new reference.
321 if (required.ref.source.name != ref.source.name) {
322 _solver.logSolve('source mismatch on ${ref.name}: ${required.ref.source} '
323 '!= ${ref.source}');
324 throw new SourceMismatchException(ref.name,
325 [required, new Dependency(depender, ref)]);
326 }
327
328 // Make sure all of the existing descriptions match the new reference.
329 if (!ref.descriptionEquals(required.ref)) {
330 _solver.logSolve('description mismatch on ${ref.name}: '
331 '${required.ref.description} != ${ref.description}');
332 throw new DescriptionMismatchException(ref.name,
333 [required, new Dependency(depender, ref)]);
334 }
335 }
336
337 /// Adds the version constraint that [depender] places on [ref] to the
338 /// overall constraint that all shared dependencies place on [ref]. Throws a
339 /// [SolverFailure] if that results in an unsolvable constraints.
340 ///
341 /// Returns the combined [VersionConstraint] that all dependers place on the
342 /// package.
343 VersionConstraint _addConstraint(PackageRef ref, String depender) {
344 // Add the dependency.
345 var dependencies = _getDependencies(ref.name);
346 dependencies.add(new Dependency(depender, ref));
347
348 // Determine the overall version constraint.
349 var constraint = dependencies
350 .map((dep) => dep.ref.constraint)
351 .reduce(VersionConstraint.any, (a, b) => a.intersect(b));
352
353 // TODO(rnystrom): Currently we just backtrack to the previous state when
354 // a failure occurs here. Another option is back*jumping*. When we hit
355 // this, we could jump straight to the nearest selection that selects a
356 // depender that is causing this state to fail. Before doing that, though,
357 // we should:
358 //
359 // 1. Write some complex solver tests that validate which order packages
360 // are downgraded to reach a solution.
361 // 2. Get some real-world data on which package graphs go pathological.
362
363 // See if it's possible for a package to match that constraint.
364 if (constraint.isEmpty) {
365 _solver.logSolve('disjoint constraints on ${ref.name}');
366 throw new DisjointConstraintException(ref.name, dependencies);
367 }
368
369 return constraint;
370 }
371
372 /// Validates the currently selected package against the new dependency that
373 /// [ref] and [constraint] place on it. Returns `null` if there is no
374 /// currently selected package, throws a [SolverFailure] if the new reference
375 /// it not does not allow the previously selected version, or returns the
376 /// selected package if successful.
377 PackageId _validateSelected(PackageRef ref, VersionConstraint constraint) {
378 var selected = _solver.getSelected(ref.name);
379 if (selected == null) return null;
380
381 // Make sure it meets the constraint.
382 if (!ref.constraint.allows(selected.version)) {
383 _solver.logSolve('selection $selected does not match $constraint');
384 throw new NoVersionException(ref.name, constraint,
385 _getDependencies(ref.name));
386 }
387
388 return selected;
389 }
390
391 /// Tries to select a package that matches [ref] and [constraint]. Updates
392 /// the solver state so that we can backtrack from this decision if it turns
393 /// out wrong, but continues traversing with the new selection.
394 ///
395 /// Returns a future that completes with a [SolverFailure] if a version
396 /// could not be selected or that completes successfully if a package was
397 /// selected and traversing should continue.
398 Future _selectPackage(PackageRef ref, VersionConstraint constraint) {
399 return _solver.cache.getVersions(ref.name, ref.source, ref.description)
400 .then((versions) {
401 var allowed = versions.where((id) => constraint.allows(id.version));
402
403 // See if it's in the lockfile. If so, try that version first. If the
404 // locked version doesn't match our constraint, just ignore it.
405 var locked = _getValidLocked(ref.name, constraint);
406 if (locked != null) {
407 allowed = allowed.where((ref) => ref.version != locked.version)
408 .toList();
409 allowed.insert(0, locked);
410 }
411
412 if (allowed.isEmpty) {
413 _solver.logSolve('no versions for ${ref.name} match $constraint');
414 throw new NoVersionException(ref.name, constraint,
415 _getDependencies(ref.name));
416 }
417
418 // If we're doing an upgrade on this package, only allow the latest
419 // version.
420 if (_solver._forceLatest.contains(ref.name)) allowed = [allowed.first];
421
422 // Try the first package in the allowed set and keep track of the list of
423 // other possible versions in case that fails.
424 _packages.add(_solver.select(allowed));
425 });
426 }
427
428 /// Gets the list of dependencies for package [name]. Will create an empty
429 /// list if needed.
430 List<Dependency> _getDependencies(String name) {
431 return _dependencies.putIfAbsent(name, () => <Dependency>[]);
432 }
433
434 /// Gets a "required" reference to the package [name]. This is the first
435 /// non-root dependency on that package. All dependencies on a package must
436 /// agree on source and description, except for references to the root
437 /// package. This will return a reference to that "canonical" source and
438 /// description, or `null` if there is no required reference yet.
439 ///
440 /// This is required because you may have a circular dependency back onto the
441 /// root package. That second dependency won't be a root dependency and it's
442 /// *that* one that other dependencies need to agree on. In other words, you
443 /// can have a bunch of dependencies back onto the root package as long as
444 /// they all agree with each other.
445 Dependency _getRequired(String name) {
446 return _getDependencies(name)
447 .firstWhere((dep) => !dep.ref.isRoot, orElse: () => null);
448 }
449
450 /// Gets the package [name] that's currently contained in the lockfile if it
451 /// meets [constraint] and has the same source and description as other
452 /// references to that package. Returns `null` otherwise.
453 PackageId _getValidLocked(String name, VersionConstraint constraint) {
454 var package = _solver.getLocked(name);
455 if (package == null) return null;
456
457 if (!constraint.allows(package.version)) return null;
458
459 var required = _getRequired(name);
460 if (required != null) {
461 if (package.source.name != required.ref.source.name) return null;
462 if (!package.descriptionEquals(required.ref)) return null;
463 }
464
465 return package;
466 }
467 }
OLDNEW
« no previous file with comments | « utils/pub/pub.dart ('k') | utils/pub/solver/greedy_solver.dart » ('j') | no next file with comments »

Powered by Google App Engine