Chromium Code Reviews| OLD | NEW |
|---|---|
| (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 | |
| 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: | |
| 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 | |
| 30 /// becomes the new current solution and it tries to solve it again. It will | |
| 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. | |
| 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 | |
| 54 /// possible versions for speculative package selections. Backtracks and | |
| 55 /// advances to the next possible solution in the case of a failure. | |
| 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 | |
| 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 | |
| 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; | |
| 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; | |
| 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 | |
| 100 /// package to the set of versions to consider for solutions. The first item | |
| 101 /// in the will be the currently selected version of that package. Subsequent | |
| 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 | |
| 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 (_backtrack(error.error)) { | |
| 146 _traverseSolution(completer); | |
| 147 } else { | |
| 148 // All out of solutions, so fail. | |
| 149 completer.completeError(error); | |
| 150 } | |
| 151 }); | |
| 152 } | |
| 153 | |
| 154 /// Backtracks from the current failed solution and determines the next | |
| 155 /// solution to try. If possible, it will backjump based on the cause of the | |
| 156 /// [failure] to minize backtracking. Otherwise, it will simply backtrack to | |
| 157 /// the next possible solution. | |
| 158 /// | |
| 159 /// Returns `true` if there is a new solution to try. | |
| 160 bool _backtrack(SolveFailure failure) { | |
| 161 // Look for the most recently selected relevant backjumping point. | |
| 162 var jumpTo; | |
| 163 var dependers = failure.dependencies.map((dep) => dep.depender).toSet(); | |
|
nweiz
2013/04/10 22:56:35
This is a somewhat different algorithm than the on
Bob Nystrom
2013/04/11 00:55:11
I didn't follow this. Can you walk me through the
nweiz
2013/04/11 22:12:04
Here, when an error is encountered, you record a s
Bob Nystrom
2013/04/16 18:34:17
I could be wrong, but I believe this solver will d
| |
| 164 for (var i = _selected.length - 1; i >= 0; i--) { | |
| 165 var name = _selected[i].first.name; | |
| 166 | |
| 167 // If we reach the package that failed, backjump to there. | |
| 168 if (failure.package == name) { | |
| 169 logSolve('jump to failing package $name'); | |
| 170 jumpTo = i; | |
| 171 break; | |
| 172 } | |
| 173 | |
| 174 // If we reach a package whose dependency led to the failing package, | |
| 175 // backjump to there. | |
| 176 if (dependers.contains(name)) { | |
| 177 logSolve('jump to depending package $name'); | |
| 178 jumpTo = i; | |
| 179 break; | |
| 180 } | |
| 181 } | |
| 182 | |
| 183 if (jumpTo != null) { | |
| 184 _selected.removeRange(jumpTo + 1, _selected.length - jumpTo - 1); | |
| 185 } | |
| 186 | |
| 187 while (!_selected.isEmpty) { | |
| 188 // Advance past the current version of the leaf-most package. | |
| 189 _selected.last.removeFirst(); | |
| 190 if (!_selected.last.isEmpty) { | |
| 191 logSolve(); | |
| 192 return true; | |
| 193 } | |
| 194 | |
| 195 // That package has no more versions, so pop it and try the next one. | |
| 196 _selected.removeLast(); | |
| 197 } | |
| 198 | |
| 199 return false; | |
| 200 } | |
| 201 | |
| 202 /// Logs [message] in the context of the current selected packages. If | |
| 203 /// [message] is omitted, just logs a description of leaf-most selection. | |
| 204 void logSolve([String message]) { | |
| 205 if (message == null) { | |
| 206 if (_selected.isEmpty) { | |
| 207 message = "* start at root"; | |
| 208 } else { | |
| 209 message = "* select ${_selected.last.first}"; | |
| 210 } | |
| 211 } else { | |
| 212 // Otherwise, indent it under the current selected package. | |
| 213 message = "| $message"; | |
| 214 } | |
| 215 | |
| 216 // Indent for the previous selections. | |
| 217 var buffer = new StringBuffer(); | |
| 218 buffer.writeAll(_selected.skip(1).map((_) => '| ')); | |
| 219 buffer.write(message); | |
| 220 log.solver(buffer); | |
| 221 } | |
| 222 } | |
| 223 | |
| 224 /// Given the solver's current set of selected package versions, this tries to | |
| 225 /// traverse the dependency graph and see if a complete set of valid versions | |
| 226 /// has been chosen. If it reaches a conflict, it will fail and stop | |
| 227 /// traversing. If it reaches a package that isn't selected it will refine the | |
| 228 /// solution by adding that package's set of allowed versions to the solver and | |
| 229 /// then select the best one and continue. | |
| 230 class Traverser { | |
| 231 final BacktrackingVersionSolver _solver; | |
| 232 | |
| 233 /// The queue of concrete packages left to traverse. We do a breadth-first | |
| 234 /// traversal using an explicit queue just to avoid the code complexity of a | |
| 235 /// recursive asynchronous traversal. | |
| 236 final _packages = new Queue<PackageId>(); | |
| 237 | |
| 238 /// The concrete packages we have already traversed. Used to avoid traversing | |
| 239 /// the same package multiple times, and to build the complete solution | |
| 240 /// results. | |
| 241 final _visited = new Set<PackageId>(); | |
| 242 | |
| 243 /// The dependencies visited so far in the traversal. For each package name | |
| 244 /// (the map key) we track the list of dependencies that other packages have | |
| 245 /// placed on it so that we can calculate the complete constraint for shared | |
| 246 /// dependencies. | |
| 247 final _dependencies = <String, List<Dependency>>{}; | |
| 248 | |
| 249 Traverser(this._solver); | |
| 250 | |
| 251 /// Walks the dependency graph starting at the root package and validates | |
| 252 /// that each reached package has a valid version selected. | |
| 253 Future<List<PackageId>> traverse() { | |
| 254 // Start at the root. | |
| 255 _packages.add(new PackageId.root(_solver.root)); | |
| 256 | |
| 257 var completer = new Completer<List<PackageId>>(); | |
| 258 _traversePackage(completer); | |
| 259 return completer.future; | |
| 260 } | |
| 261 | |
| 262 /// Traverses the next package in the queue. Completes [completer] with a | |
| 263 /// list of package IDs if the traversal completed successfully and found a | |
| 264 /// solution. Completes to an error if the traversal failed. Otherwise, | |
| 265 /// recurses to the next package in the queue, etc. | |
| 266 void _traversePackage(Completer<List<PackageId>> completer) { | |
| 267 if (_packages.isEmpty) { | |
| 268 // We traversed the whole graph. If we got here, we successfully found | |
| 269 // a solution. | |
| 270 completer.complete(_visited.toList()); | |
| 271 return; | |
| 272 } | |
| 273 | |
| 274 var id = _packages.removeFirst(); | |
| 275 | |
| 276 // Don't visit the same package twice. | |
| 277 if (_visited.contains(id)) { | |
| 278 _traversePackage(completer); | |
| 279 return; | |
| 280 } | |
| 281 _visited.add(id); | |
| 282 | |
| 283 _solver.cache.getPubspec(id).then((pubspec) { | |
| 284 var refs = pubspec.dependencies.toList(); | |
| 285 | |
| 286 // Include dev dependencies of the root package. | |
| 287 if (id.isRoot) refs.addAll(pubspec.devDependencies); | |
| 288 | |
| 289 // TODO(rnystrom): Sort in some best-first order to minimize backtracking. | |
| 290 // Bundler's model is: | |
| 291 // Easiest to resolve is defined by: | |
| 292 // 1) Is this gem already activated? | |
| 293 // 2) Do the version requirements include prereleased gems? | |
| 294 // 3) Sort by number of gems available in the source. | |
| 295 // Can probably do something similar, but we should profile against | |
| 296 // real-world package graphs that require backtracking to see which | |
| 297 // heuristics work best for Dart. | |
| 298 refs.sort((a, b) => a.name.compareTo(b.name)); | |
| 299 | |
| 300 _traverseRefs(completer, id.name, new Queue<PackageRef>.from(refs)); | |
| 301 }).catchError((error){ | |
| 302 completer.completeError(error); | |
| 303 }); | |
| 304 } | |
| 305 | |
| 306 /// Traverses the references that [depender] depends on, stored in [refs]. | |
| 307 /// Desctructively modifies [refs]. Completes [completer] to a list of | |
| 308 /// packages if the traversal is complete. Completes it to an error if a | |
| 309 /// failure occurred. Otherwise, recurses. | |
| 310 void _traverseRefs(Completer<List<PackageId>> completer, | |
| 311 String depender, Queue<PackageRef> refs) { | |
| 312 // Move onto the next package if we've traversed all of these references. | |
| 313 if (refs.isEmpty) { | |
| 314 _traversePackage(completer); | |
| 315 return; | |
| 316 } | |
| 317 | |
| 318 try { | |
| 319 var ref = refs.removeFirst(); | |
| 320 | |
| 321 _validateDependency(ref, depender); | |
| 322 var constraint = _addConstraint(ref, depender); | |
| 323 | |
| 324 var selected = _validateSelected(ref, constraint); | |
| 325 if (selected != null) { | |
| 326 // The selected package version is good, so enqueue it to traverse into | |
| 327 // it. | |
| 328 _packages.add(selected); | |
| 329 _traverseRefs(completer, depender, refs); | |
| 330 return; | |
| 331 } | |
| 332 | |
| 333 // We haven't selected a version. Get all of the versions that match the | |
| 334 // constraints we currently have for this package and add them to the | |
| 335 // set of solutions to try. | |
| 336 _selectPackage(ref, constraint).then((_) { | |
| 337 _traverseRefs(completer, depender, refs); | |
| 338 }).catchError((error) { | |
| 339 completer.completeError(error); | |
| 340 }); | |
| 341 } catch (error, stackTrace) { | |
| 342 completer.completeError(error, stackTrace); | |
| 343 } | |
| 344 } | |
| 345 | |
| 346 /// Ensures that dependency [ref] from [depender] is consistent with the | |
| 347 /// other dependencies on the same package. Throws a [SolverFailure] | |
| 348 /// exception if not. Only validates sources and descriptions, not the | |
| 349 /// version. | |
| 350 void _validateDependency(PackageRef ref, String depender) { | |
| 351 // Make sure the dependencies agree on source and description. | |
| 352 var required = _getRequired(ref.name); | |
| 353 if (required == null) return; | |
| 354 | |
| 355 // Make sure all of the existing sources match the new reference. | |
| 356 if (required.ref.source.name != ref.source.name) { | |
| 357 _solver.logSolve('source mismatch on ${ref.name}: ${required.ref.source} ' | |
| 358 '!= ${ref.source}'); | |
| 359 throw new SourceMismatchException(ref.name, | |
| 360 [required, new Dependency(depender, ref)]); | |
| 361 } | |
| 362 | |
| 363 // Make sure all of the existing descriptions match the new reference. | |
| 364 if (!ref.descriptionEquals(required.ref)) { | |
| 365 _solver.logSolve('description mismatch on ${ref.name}: ' | |
| 366 '${required.ref.description} != ${ref.description}'); | |
| 367 throw new DescriptionMismatchException(ref.name, | |
| 368 [required, new Dependency(depender, ref)]); | |
| 369 } | |
| 370 } | |
| 371 | |
| 372 /// Adds the version constraint that [depender] places on [ref] to the | |
| 373 /// overall constraint that all shared dependencies place on [ref]. Throws a | |
| 374 /// [SolverFailure] if that results in an unsolvable constraints. | |
| 375 /// | |
| 376 /// Returns the combined [VersionConstraint] that all dependers place on the | |
| 377 /// package. | |
| 378 VersionConstraint _addConstraint(PackageRef ref, String depender) { | |
| 379 // Add the dependency. | |
| 380 var dependencies = _getDependencies(ref.name); | |
| 381 dependencies.add(new Dependency(depender, ref)); | |
| 382 | |
| 383 // Determine the overall version constraint. | |
| 384 var constraint = dependencies | |
| 385 .map((dep) => dep.ref.constraint) | |
| 386 .reduce(VersionConstraint.any, (a, b) => a.intersect(b)); | |
| 387 | |
| 388 // TODO(rnystrom): Currently we just backtrack to the previous state when | |
| 389 // a failure occurs here. Another option is back*jumping*. When we hit | |
| 390 // this, we could jump straight to the nearest selection that selects a | |
| 391 // depender that is causing this state to fail. Before doing that, though, | |
| 392 // we should: | |
| 393 // | |
| 394 // 1. Write some complex solver tests that validate which order packages | |
| 395 // are downgraded to reach a solution. | |
| 396 // 2. Get some real-world data on which package graphs go pathological. | |
| 397 | |
| 398 // See if it's possible for a package to match that constraint. | |
| 399 if (constraint.isEmpty) { | |
| 400 _solver.logSolve('disjoint constraints on ${ref.name}'); | |
| 401 throw new DisjointConstraintException(ref.name, dependencies); | |
| 402 } | |
| 403 | |
| 404 return constraint; | |
| 405 } | |
| 406 | |
| 407 /// Validates the currently selected package against the new dependency that | |
| 408 /// [ref] and [constraint] place on it. Returns `null` if there is no | |
| 409 /// currently selected package, throws a [SolverFailure] if the new reference | |
| 410 /// it not does not allow the previously selected version, or returns the | |
| 411 /// selected package if successful. | |
| 412 PackageId _validateSelected(PackageRef ref, VersionConstraint constraint) { | |
| 413 var selected = _solver.getSelected(ref.name); | |
| 414 if (selected == null) return null; | |
| 415 | |
| 416 // Make sure it meets the constraint. | |
| 417 if (!ref.constraint.allows(selected.version)) { | |
| 418 _solver.logSolve('selection $selected does not match $constraint'); | |
| 419 throw new NoVersionException(ref.name, constraint, | |
| 420 _getDependencies(ref.name)); | |
| 421 } | |
| 422 | |
| 423 return selected; | |
| 424 } | |
| 425 | |
| 426 /// Tries to select a package that matches [ref] and [constraint]. Updates | |
| 427 /// the solver state so that we can backtrack from this decision if it turns | |
| 428 /// out wrong, but continues traversing with the new selection. | |
| 429 /// | |
| 430 /// Returns a future that completes with a [SolverFailure] if a version | |
| 431 /// could not be selected or that completes successfully if a package was | |
| 432 /// selected and traversing should continue. | |
| 433 Future _selectPackage(PackageRef ref, VersionConstraint constraint) { | |
| 434 return _solver.cache.getVersions(ref.name, ref.source, ref.description) | |
| 435 .then((versions) { | |
| 436 var allowed = versions.where((id) => constraint.allows(id.version)); | |
| 437 | |
| 438 // See if it's in the lockfile. If so, try that version first. If the | |
| 439 // locked version doesn't match our constraint, just ignore it. | |
| 440 var locked = _getValidLocked(ref.name, constraint); | |
| 441 if (locked != null) { | |
| 442 allowed = allowed.where((ref) => ref.version != locked.version) | |
| 443 .toList(); | |
| 444 allowed.insert(0, locked); | |
| 445 } | |
| 446 | |
| 447 if (allowed.isEmpty) { | |
| 448 _solver.logSolve('no versions for ${ref.name} match $constraint'); | |
| 449 throw new NoVersionException(ref.name, constraint, | |
| 450 _getDependencies(ref.name)); | |
| 451 } | |
| 452 | |
| 453 // If we're doing an upgrade on this package, only allow the latest | |
| 454 // version. | |
| 455 if (_solver._forceLatest.contains(ref.name)) allowed = [allowed.first]; | |
| 456 | |
| 457 // Try the first package in the allowed set and keep track of the list of | |
| 458 // other possible versions in case that fails. | |
| 459 _packages.add(_solver.select(allowed)); | |
| 460 }); | |
| 461 } | |
| 462 | |
| 463 /// Gets the list of dependencies for package [name]. Will create an empty | |
| 464 /// list if needed. | |
| 465 List<Dependency> _getDependencies(String name) { | |
| 466 return _dependencies.putIfAbsent(name, () => <Dependency>[]); | |
| 467 } | |
| 468 | |
| 469 /// Gets a "required" reference to the package [name]. This is the first | |
| 470 /// non-root dependency on that package. All dependencies on a package must | |
| 471 /// agree on source and description, except for references to the root | |
| 472 /// package. This will return a reference to that "canonical" source and | |
| 473 /// description, or `null` if there is no required reference yet. | |
| 474 /// | |
| 475 /// This is required because you may have a circular dependency back onto the | |
| 476 /// root package. That second dependency won't be a root dependency and it's | |
| 477 /// *that* one that other dependencies need to agree on. In other words, you | |
| 478 /// can have a bunch of dependencies back onto the root package as long as | |
| 479 /// they all agree with each other. | |
| 480 Dependency _getRequired(String name) { | |
| 481 return _getDependencies(name) | |
| 482 .firstWhere((dep) => !dep.ref.isRoot, orElse: () => null); | |
| 483 } | |
| 484 | |
| 485 /// Gets the package [name] that's currently contained in the lockfile if it | |
| 486 /// meets [constraint] and has the same source and description as other | |
| 487 /// references to that package. Returns `null` otherwise. | |
| 488 PackageId _getValidLocked(String name, VersionConstraint constraint) { | |
| 489 var package = _solver.getLocked(name); | |
| 490 if (package == null) return null; | |
| 491 | |
| 492 if (!constraint.allows(package.version)) return null; | |
| 493 | |
| 494 var required = _getRequired(name); | |
| 495 if (required != null) { | |
| 496 if (package.source.name != required.ref.source.name) return null; | |
| 497 if (!package.descriptionEquals(required.ref)) return null; | |
| 498 } | |
| 499 | |
| 500 return package; | |
| 501 } | |
| 502 } | |
| OLD | NEW |