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