Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(153)

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

Powered by Google App Engine
This is Rietveld 408576698