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 /// Pub's constraint solver. It is a back-tracking depth-first solver. | |
6 /// | |
7 /// Note that internally it uses explicit [Completer]s instead of chaining | |
8 /// futures like most async code. This is to avoid accumulating very long | |
9 /// chains of futures. Since this may iterate through many states, hanging an | |
10 /// increasing long series of `.then()` calls off each other can end up eating | |
11 /// piles of memory for both the futures and the stack traces. | |
12 library version_solver2; | |
13 | |
14 import 'dart:async'; | |
15 import 'dart:collection' show Queue; | |
16 import 'dart:json' as json; | |
17 import 'dart:math'; | |
18 import 'lock_file.dart'; | |
19 import 'log.dart' as log; | |
20 import 'package.dart'; | |
21 import 'pubspec.dart'; | |
22 import 'source.dart'; | |
23 import 'source_registry.dart'; | |
24 import 'utils.dart'; | |
25 import 'version.dart'; | |
26 import 'version_solver.dart'; | |
27 | |
28 /// How many times we allow the solver to backtrack looking for a solution | |
29 /// before giving up. | |
30 // TODO(rnystrom): What value should this have? Should it be based on graph | |
31 // size? | |
32 const _MAX_BACKTRACKING = 10000; | |
nweiz
2013/03/29 01:58:25
As discussed offline, I don't like having an itera
Bob Nystrom
2013/03/30 00:15:55
Done.
| |
33 | |
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 /// The current state being explored. Its parent links enable us to walk | |
40 /// back up the tree to other earlier states. | |
41 SolveState _state; | |
42 | |
43 /// The number of solutions we've tried so far. | |
44 int _iterations = 0; | |
45 | |
46 BacktrackingVersionSolver(SourceRegistry sources, Package root, | |
47 LockFile lockFile, List<String> useLatest) | |
48 : super(sources, root, lockFile, useLatest); | |
49 | |
50 void forceLatestVersion(String package) { | |
51 _forceLatest.add(package); | |
52 } | |
53 | |
54 Future<List<PackageId>> runSolver() { | |
55 var completer = new Completer<List<PackageId>>(); | |
56 _processState(completer); | |
57 return completer.future; | |
58 } | |
59 | |
60 /// Creates a new node in the solution space that tries [versions] for | |
61 /// package [name]. Returns the new node. | |
62 SolveState push(String name, List<Version> versions) { | |
63 _state = new SolveState(_state, name, versions); | |
64 _state.trace(); | |
65 return _state; | |
66 } | |
67 | |
68 /// Loads the pubspec for the package identified by [id]. | |
69 Future<Pubspec> getPubspec(PackageId id) { | |
70 // The root package doesn't have a source, so special case it. | |
71 if (id.isRoot) return new Future.immediate(root.pubspec); | |
72 | |
73 return cache.getPubspec(id); | |
74 } | |
75 | |
76 /// Gets the list of versions for [package]. | |
77 Future<List<PackageId>> getVersions(String package, Source source, | |
78 description) { | |
79 return cache.getVersions(package, source, description); | |
80 } | |
81 | |
82 /// Gets the version of [package] currently locked in the lock file. Returns | |
83 /// `null` if it isn't in the lockfile (or has been unlocked). | |
84 PackageId getLocked(String package) => lockFile.packages[package]; | |
85 | |
86 /// Processes the current possible solution state. If successful, completes | |
87 /// [completer] with the solution. If not, tries the next state (and so on). | |
88 /// If there are no more states, completes to the last error that occurred. | |
89 void _processState(Completer<List<PackageId>> completer) { | |
90 if (_iterations++ > _MAX_BACKTRACKING) { | |
91 completer.completeError(new CouldNotSolveException()); | |
92 } | |
93 | |
94 var state = _state; | |
95 | |
96 var propagator = new Propagator(this, state); | |
97 propagator.propagate().then((result) { | |
98 completer.complete(result); | |
99 }).catchError((error) { | |
100 if (error.error is! SolverFailure) { | |
101 completer.completeError(error); | |
102 return; | |
103 } | |
104 | |
105 // Try the next state, if there is one. | |
106 if (state != _state || _advanceState()) { | |
107 _processState(completer); | |
108 } else { | |
109 // All out of solutions, so fail. | |
110 completer.completeError(error); | |
111 } | |
112 }); | |
113 } | |
114 | |
115 /// Advances to the next node in the possible solution tree. | |
116 bool _advanceState() { | |
117 while (_state != null) { | |
118 if (_state.advance()) return true; | |
119 | |
120 // The current state is done, so pop it and try the parent. | |
121 _state = _state._parent; | |
122 } | |
123 | |
124 return false; | |
125 } | |
126 } | |
127 | |
128 /// Given a [SolveState] that selects a set of package versions, this tries to | |
129 /// traverse the dependency graph and see if a complete set of valid versions | |
130 /// has been selected. | |
131 class Propagator { | |
132 final BacktrackingVersionSolver _solver; | |
133 | |
134 /// The queue of packages left to traverse. We do a bread-first traversal | |
135 /// using an explicit queue just to avoid the code complexity of a recursive | |
136 /// asynchronous traversal. | |
137 final _packages = new Queue<PackageId>(); | |
138 | |
139 /// The packages we have already traversed. Used to avoid traversing the same | |
140 /// package multiple times, and to build the complete solution results. | |
141 final _visited = new Set<PackageId>(); | |
142 | |
143 /// The known dependencies visited so far. | |
144 final _dependencies = <String, List<Dependency>>{}; | |
145 | |
146 /// The solution being tested. | |
147 SolveState _state; | |
148 | |
149 Propagator(this._solver, this._state); | |
150 | |
151 Future<List<PackageId>> propagate() { | |
152 // Start at the root. | |
153 _packages.add(new PackageId.root(_solver.root)); | |
154 | |
155 var completer = new Completer<List<PackageId>>(); | |
156 _processPackage(completer); | |
157 return completer.future; | |
158 } | |
159 | |
160 void trace([String message]) { | |
161 if (_state == null) { | |
162 // Don't waste time building the string if it will be ignored. | |
163 if (!log.isEnabled(log.Level.SOLVER)) return; | |
164 | |
165 // No message means just describe the current state. | |
166 if (message == null) { | |
167 message = "* start at root"; | |
168 } else { | |
169 // Otherwise, indent it under the current state. | |
170 message = "| $message"; | |
171 } | |
172 | |
173 log.solver("| $message"); | |
174 } else { | |
175 _state.trace(message); | |
176 } | |
177 } | |
178 | |
179 /// Traverses the next package in the queue. Completes [completer] with a | |
180 /// list of package IDs if the traversal completely successfully and found a | |
181 /// solution. Completes to an error if the traversal failed. Otherwise, | |
182 /// recurses to the next package in the queue, etc. | |
183 void _processPackage(Completer<List<PackageId>> completer) { | |
184 if (_packages.isEmpty) { | |
185 // We traversed the whole graph. If we got here, we successfully found | |
186 // a solution. | |
187 completer.complete(_visited.toList()); | |
188 return; | |
189 } | |
190 | |
191 var id = _packages.removeFirst(); | |
192 | |
193 // Don't visit the same package twice. | |
194 if (_visited.contains(id)) { | |
195 _processPackage(completer); | |
196 return; | |
197 } | |
198 _visited.add(id); | |
199 | |
200 _solver.getPubspec(id).then((pubspec) { | |
201 var refs = pubspec.dependencies.toList(); | |
202 | |
203 // Include dev dependencies of the root package. | |
204 if (id.isRoot) refs.addAll(pubspec.devDependencies); | |
205 | |
206 // TODO(rnystrom): Sort in some best-first order to minimize backtracking. | |
207 // Bundler's model is: | |
208 // Easiest to resolve is defined by: | |
209 // 1) Is this gem already activated? | |
210 // 2) Do the version requirements include prereleased gems? | |
211 // 3) Sort by number of gems available in the source. | |
212 // Can probably do something similar, but we should profile against | |
213 // real-world package graphs that require backtracking to see which | |
214 // heuristics work best for Dart. | |
215 refs.sort((a, b) => a.name.compareTo(b.name)); | |
216 | |
217 _traverseRefs(completer, id.name, new Queue<PackageRef>.from(refs)); | |
218 }).catchError((error){ | |
219 completer.completeError(error); | |
220 }); | |
221 } | |
222 | |
223 /// Traverses the references that [depender] depends on, stored in [refs]. | |
224 /// Desctructively modifies [refs]. Completes [completer] to a list of | |
225 /// packages if the traversal is complete. Completes it to an error if a | |
226 /// failure occurred. Otherwise, recurses. | |
227 void _traverseRefs(Completer<List<PackageId>> completer, | |
228 String depender, Queue<PackageRef> refs) { | |
229 // Move onto the next package if we've traversed all of these references. | |
230 if (refs.isEmpty) { | |
231 _processPackage(completer); | |
232 return; | |
233 } | |
234 | |
235 var ref = refs.removeFirst(); | |
236 | |
237 // Note the dependency. | |
238 var dependencies = _dependencies.putIfAbsent(ref.name, | |
239 () => <Dependency>[]); | |
240 dependencies.add(new Dependency(depender, ref)); | |
241 | |
242 // Make sure the dependencies agree on source and description. | |
243 var required = _getRequired(ref.name); | |
244 if (required != null) { | |
245 // Make sure all of the existing sources match the new reference. | |
246 if (required.ref.source.name != ref.source.name) { | |
247 trace('source mismatch on ${ref.name}: ${required.ref.source} ' | |
248 '!= ${ref.source}'); | |
249 completer.completeError(new SourceMismatchException(ref.name, | |
250 required.depender, required.ref.source, depender, ref.source)); | |
251 return; | |
252 } | |
253 | |
254 // Make sure all of the existing descriptions match the new reference. | |
255 if (!ref.descriptionEquals(required.ref)) { | |
256 trace('description mismatch on ${ref.name}: ' | |
257 '${required.ref.description} != ${ref.description}'); | |
258 completer.completeError(new DescriptionMismatchException(ref.name, | |
259 required.depender, required.ref.description, | |
260 depender, ref.description)); | |
261 return; | |
262 } | |
263 } | |
264 | |
265 // Determine the overall version constraint. | |
266 var constraint = dependencies | |
267 .map((dep) => dep.ref.constraint) | |
268 .reduce(VersionConstraint.any, (a, b) => a.intersect(b)); | |
269 | |
270 // TODO(rnystrom): Currently we just backtrack to the previous state when | |
271 // a failure occurs here. Another option is back*jumping*. When we hit | |
272 // this, we could jump straight to the nearest SolveState that selects a | |
273 // depender that is causing this state to fail. Before doing that, though, | |
274 // we should: | |
275 // | |
276 // 1. Write some complex solver tests that validate which order packages | |
277 // are downgraded to reach a solution. | |
278 // 2. Get some real-world data on which package graphs go pathological. | |
279 | |
280 // See if it's possible for a package to match that constraint. We | |
281 // check this first so that this error is preferred over "no versions" | |
282 // which can be thrown if the current selection does not match the | |
283 // constraint. | |
284 if (constraint.isEmpty) { | |
285 trace('disjoint constraints on ${ref.name}'); | |
286 completer.completeError( | |
287 new DisjointConstraintException(ref.name, dependencies)); | |
288 return; | |
289 } | |
290 | |
291 var selected = _getSelected(ref.name); | |
292 if (selected != null) { | |
293 // Make sure it meets the constraint. | |
294 if (!ref.constraint.allows(selected.version)) { | |
295 trace('selection $selected does not match $constraint'); | |
296 completer.completeError( | |
297 new NoVersionException(ref.name, constraint, dependencies)); | |
298 return; | |
299 } | |
300 | |
301 // Traverse into it. | |
302 _packages.add(selected); | |
303 _traverseRefs(completer, depender, refs); | |
304 return; | |
305 } | |
306 | |
307 // We haven't selected a version. Create a substate that tries all | |
308 // versions that match the constraints we currently have for this | |
309 // package. | |
310 _solver.getVersions(ref.name, ref.source, ref.description).then((versions) { | |
311 var allowed = versions.where( | |
312 (id) => constraint.allows(id.version)).toList(); | |
313 | |
314 // See if it's in the lockfile. If so, try that version first. If the | |
315 // locked version doesn't match our constraint, just ignore it. | |
316 var locked = _getLocked(ref.name, constraint); | |
317 if (locked != null) { | |
318 allowed.removeWhere((ref) => ref.version == locked.version); | |
319 allowed.insert(0, locked); | |
320 } | |
321 | |
322 if (allowed.isEmpty) { | |
323 trace('no versions for ${ref.name} match $constraint'); | |
324 completer.completeError(new NoVersionException(ref.name, constraint, | |
325 dependencies)); | |
326 return; | |
327 } | |
328 | |
329 // If we're doing an upgrade on this package, only allow the latest | |
330 // version. | |
331 if (_solver._forceLatest.contains(ref.name)) allowed = [allowed.first]; | |
332 | |
333 // Try to continue solving with the first selected package. | |
334 _state = _solver.push(ref.name, allowed); | |
335 selected = _getSelected(ref.name); | |
336 assert(selected != null); | |
337 | |
338 _packages.add(selected); | |
339 _traverseRefs(completer, depender, refs); | |
340 }).catchError((error) { | |
341 print(error); | |
342 completer.completeError(error); | |
343 }); | |
344 } | |
345 | |
346 /// Gets the currently selected package named [package] or `null` if no | |
347 /// concrete package has been selected with that name yet. | |
348 PackageId _getSelected(String name) { | |
349 // Always prefer the root package. | |
350 if (_solver.root.name == name) return new PackageId.root(_solver.root); | |
351 | |
352 // Nothing is selected if we're in the starting state. | |
353 if (_state == null) return null; | |
354 | |
355 return _state.getSelected(name); | |
356 } | |
357 | |
358 /// Gets a "required" reference to the package [name]. This is the first | |
359 /// non-root dependency on that package. All dependencies on a package must | |
360 /// agree on source and description, except for references to the root | |
361 /// package. This will return a reference to that "canonical" source and | |
362 /// description, or `null` if there is no required reference yet. | |
363 Dependency _getRequired(String name) { | |
364 var dependencies = _dependencies[name]; | |
365 assert(dependencies != null); | |
366 | |
367 return dependencies | |
368 .firstWhere((dep) => !dep.ref.isRoot, orElse: () => null); | |
369 } | |
370 | |
371 /// Gets the package [name] that's currently contained in the lockfile if it | |
372 /// meets [constraint] and has the same source and description as other | |
373 /// references to that package. Returns `null` otherwise. | |
374 PackageId _getLocked(String name, VersionConstraint constraint) { | |
375 var package = _solver.getLocked(name); | |
376 if (package == null) return null; | |
377 | |
378 if (!constraint.allows(package.version)) return null; | |
379 | |
380 var dependencies = _dependencies[name]; | |
381 assert(dependencies != null); | |
382 | |
383 var required = _getRequired(name); | |
384 if (required != null) { | |
385 if (package.source.name != required.ref.source.name) return null; | |
386 if (!package.descriptionEquals(required.ref)) return null; | |
387 } | |
388 | |
389 return package; | |
390 } | |
391 } | |
392 | |
393 /// One node in the possible solution tree that is being traversed. Each node | |
394 /// reflects one of a set of speculative choices that may turn out to be wrong. | |
395 class SolveState { | |
396 final SolveState _parent; | |
397 | |
398 /// The name of the package this state selects. | |
399 final String _package; | |
400 | |
401 /// The list of versions that can possibly be selected. | |
402 final List<PackageId> _possible; | |
403 | |
404 /// The currently selected version in [_possible]. | |
405 int _current = 0; | |
406 | |
407 SolveState(this._parent, this._package, this._possible); | |
408 | |
409 void trace([Object message]) { | |
410 // Don't waste time building the string if it will be ignored. | |
411 if (!log.isEnabled(log.Level.SOLVER)) return; | |
412 | |
413 // No message means just describe the current state. | |
414 if (message == null) { | |
415 message = "* select ${_possible[_current]} " | |
416 "($_current/${_possible.length})"; | |
417 } else { | |
418 // Otherwise, indent it under the current state. | |
419 message = "| $message"; | |
420 } | |
421 | |
422 var buffer = new StringBuffer(); | |
423 | |
424 // Indent for the parent states. | |
425 var state = _parent; | |
426 while (state != null) { | |
427 buffer.write('| '); | |
428 state = state._parent; | |
429 } | |
430 | |
431 buffer.write(message); | |
432 log.solver(buffer); | |
433 } | |
434 | |
435 /// Tries to move to the next version in the list. Returns `false` if there | |
436 /// are no more versions. | |
437 bool advance() { | |
438 _current++; | |
439 if (_current < _possible.length) { | |
440 trace(); | |
441 return true; | |
442 } else { | |
443 return false; | |
444 } | |
445 } | |
446 | |
447 /// Gets the selected version of [package]. If no version has been selected | |
448 /// yet, returns `null`. | |
449 PackageId getSelected(String package) { | |
450 if (_package == package) return _possible[_current]; | |
451 if (_parent == null) return null; | |
452 return _parent.getSelected(package); | |
453 } | |
454 } | |
OLD | NEW |