/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
1
# Copyright (C) 2007 Canonical Ltd
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
2490.2.30 by Aaron Bentley
Add functionality for tsorting graphs
17
from bzrlib import (
18
    errors,
3052.1.3 by John Arbash Meinel
deprecate revision.is_ancestor, update the callers and the tests.
19
    revision,
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
20
    symbol_versioning,
3377.3.10 by John Arbash Meinel
Tweak _BreadthFirstSearcher.find_seen_ancestors()
21
    trace,
2490.2.30 by Aaron Bentley
Add functionality for tsorting graphs
22
    tsort,
23
    )
2490.2.21 by Aaron Bentley
Rename graph to deprecated_graph
24
from bzrlib.deprecated_graph import (node_distances, select_farthest)
2490.2.1 by Aaron Bentley
Start work on GraphWalker
25
2490.2.25 by Aaron Bentley
Update from review
26
# DIAGRAM of terminology
27
#       A
28
#       /\
29
#      B  C
30
#      |  |\
31
#      D  E F
32
#      |\/| |
33
#      |/\|/
34
#      G  H
35
#
36
# In this diagram, relative to G and H:
37
# A, B, C, D, E are common ancestors.
38
# C, D and E are border ancestors, because each has a non-common descendant.
39
# D and E are least common ancestors because none of their descendants are
40
# common ancestors.
41
# C is not a least common ancestor because its descendant, E, is a common
42
# ancestor.
43
#
44
# The find_unique_lca algorithm will pick A in two steps:
45
# 1. find_lca('G', 'H') => ['D', 'E']
46
# 2. Since len(['D', 'E']) > 1, find_lca('D', 'E') => ['A']
47
48
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
49
class DictParentsProvider(object):
3172.1.2 by Robert Collins
Parent Providers should now implement ``get_parent_map`` returning a
50
    """A parents provider for Graph objects."""
2988.1.3 by Robert Collins
Add a new repositoy method _generate_text_key_index for use by reconcile/check.
51
52
    def __init__(self, ancestry):
53
        self.ancestry = ancestry
54
55
    def __repr__(self):
56
        return 'DictParentsProvider(%r)' % self.ancestry
57
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
58
    def get_parent_map(self, keys):
59
        """See _StackedParentsProvider.get_parent_map"""
60
        ancestry = self.ancestry
61
        return dict((k, ancestry[k]) for k in keys if k in ancestry)
62
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
63
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
64
class _StackedParentsProvider(object):
65
66
    def __init__(self, parent_providers):
67
        self._parent_providers = parent_providers
68
2490.2.28 by Aaron Bentley
Fix handling of null revision
69
    def __repr__(self):
70
        return "_StackedParentsProvider(%r)" % self._parent_providers
71
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
72
    def get_parent_map(self, keys):
73
        """Get a mapping of keys => parents
74
75
        A dictionary is returned with an entry for each key present in this
76
        source. If this source doesn't have information about a key, it should
77
        not include an entry.
78
79
        [NULL_REVISION] is used as the parent of the first user-committed
80
        revision.  Its parent list is empty.
81
82
        :param keys: An iterable returning keys to check (eg revision_ids)
83
        :return: A dictionary mapping each key to its parents
84
        """
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
85
        found = {}
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
86
        remaining = set(keys)
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
87
        for parents_provider in self._parent_providers:
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
88
            new_found = parents_provider.get_parent_map(remaining)
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
89
            found.update(new_found)
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
90
            remaining.difference_update(new_found)
91
            if not remaining:
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
92
                break
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
93
        return found
94
95
96
class CachingParentsProvider(object):
97
    """A parents provider which will cache the revision => parents in a dict.
98
99
    This is useful for providers that have an expensive lookup.
100
    """
101
102
    def __init__(self, parent_provider):
103
        self._real_provider = parent_provider
104
        # Theoretically we could use an LRUCache here
105
        self._cache = {}
106
107
    def __repr__(self):
108
        return "%s(%r)" % (self.__class__.__name__, self._real_provider)
109
110
    def get_parent_map(self, keys):
111
        """See _StackedParentsProvider.get_parent_map"""
112
        needed = set()
113
        # If the _real_provider doesn't have a key, we cache a value of None,
114
        # which we then later use to realize we cannot provide a value for that
115
        # key.
116
        parent_map = {}
117
        cache = self._cache
118
        for key in keys:
119
            if key in cache:
120
                value = cache[key]
121
                if value is not None:
122
                    parent_map[key] = value
123
            else:
124
                needed.add(key)
125
126
        if needed:
127
            new_parents = self._real_provider.get_parent_map(needed)
128
            cache.update(new_parents)
129
            parent_map.update(new_parents)
130
            needed.difference_update(new_parents)
131
            cache.update(dict.fromkeys(needed, None))
132
        return parent_map
133
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
134
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
135
class Graph(object):
2490.2.10 by Aaron Bentley
Clarify text, remove unused _get_ancestry method
136
    """Provide incremental access to revision graphs.
137
138
    This is the generic implementation; it is intended to be subclassed to
139
    specialize it for other repository types.
140
    """
2490.2.1 by Aaron Bentley
Start work on GraphWalker
141
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
142
    def __init__(self, parents_provider):
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
143
        """Construct a Graph that uses several graphs as its input
2490.2.10 by Aaron Bentley
Clarify text, remove unused _get_ancestry method
144
145
        This should not normally be invoked directly, because there may be
146
        specialized implementations for particular repository types.  See
3172.1.2 by Robert Collins
Parent Providers should now implement ``get_parent_map`` returning a
147
        Repository.get_graph().
2490.2.10 by Aaron Bentley
Clarify text, remove unused _get_ancestry method
148
3172.1.2 by Robert Collins
Parent Providers should now implement ``get_parent_map`` returning a
149
        :param parents_provider: An object providing a get_parent_map call
150
            conforming to the behavior of
151
            StackedParentsProvider.get_parent_map.
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
152
        """
3172.1.2 by Robert Collins
Parent Providers should now implement ``get_parent_map`` returning a
153
        if getattr(parents_provider, 'get_parents', None) is not None:
154
            self.get_parents = parents_provider.get_parents
155
        if getattr(parents_provider, 'get_parent_map', None) is not None:
156
            self.get_parent_map = parents_provider.get_parent_map
2490.2.29 by Aaron Bentley
Make parents provider private
157
        self._parents_provider = parents_provider
2490.2.28 by Aaron Bentley
Fix handling of null revision
158
159
    def __repr__(self):
2490.2.29 by Aaron Bentley
Make parents provider private
160
        return 'Graph(%r)' % self._parents_provider
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
161
162
    def find_lca(self, *revisions):
163
        """Determine the lowest common ancestors of the provided revisions
164
165
        A lowest common ancestor is a common ancestor none of whose
166
        descendants are common ancestors.  In graphs, unlike trees, there may
167
        be multiple lowest common ancestors.
2490.2.12 by Aaron Bentley
Improve documentation
168
169
        This algorithm has two phases.  Phase 1 identifies border ancestors,
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
170
        and phase 2 filters border ancestors to determine lowest common
171
        ancestors.
2490.2.12 by Aaron Bentley
Improve documentation
172
173
        In phase 1, border ancestors are identified, using a breadth-first
174
        search starting at the bottom of the graph.  Searches are stopped
175
        whenever a node or one of its descendants is determined to be common
176
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
177
        In phase 2, the border ancestors are filtered to find the least
2490.2.12 by Aaron Bentley
Improve documentation
178
        common ancestors.  This is done by searching the ancestries of each
179
        border ancestor.
180
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
181
        Phase 2 is perfomed on the principle that a border ancestor that is
182
        not an ancestor of any other border ancestor is a least common
183
        ancestor.
2490.2.12 by Aaron Bentley
Improve documentation
184
185
        Searches are stopped when they find a node that is determined to be a
186
        common ancestor of all border ancestors, because this shows that it
187
        cannot be a descendant of any border ancestor.
188
189
        The scaling of this operation should be proportional to
190
        1. The number of uncommon ancestors
191
        2. The number of border ancestors
192
        3. The length of the shortest path between a border ancestor and an
193
           ancestor of all border ancestors.
2490.2.3 by Aaron Bentley
Implement new merge base picker
194
        """
2490.2.23 by Aaron Bentley
Adapt find_borders to produce a graph difference
195
        border_common, common, sides = self._find_border_ancestors(revisions)
2776.3.1 by Robert Collins
* Deprecated method ``find_previous_heads`` on
196
        # We may have common ancestors that can be reached from each other.
197
        # - ask for the heads of them to filter it down to only ones that
198
        # cannot be reached from each other - phase 2.
199
        return self.heads(border_common)
2490.2.9 by Aaron Bentley
Fix minimal common ancestor algorithm for non-minimal perhipheral ancestors
200
2490.2.23 by Aaron Bentley
Adapt find_borders to produce a graph difference
201
    def find_difference(self, left_revision, right_revision):
2490.2.25 by Aaron Bentley
Update from review
202
        """Determine the graph difference between two revisions"""
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
203
        border, common, searchers = self._find_border_ancestors(
2490.2.23 by Aaron Bentley
Adapt find_borders to produce a graph difference
204
            [left_revision, right_revision])
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
205
        self._search_for_extra_common(common, searchers)
206
        left = searchers[0].seen
207
        right = searchers[1].seen
208
        return (left.difference(right), right.difference(left))
2490.2.23 by Aaron Bentley
Adapt find_borders to produce a graph difference
209
3172.1.2 by Robert Collins
Parent Providers should now implement ``get_parent_map`` returning a
210
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
211
    def get_parents(self, revisions):
212
        """Find revision ids of the parents of a list of revisions
213
214
        A list is returned of the same length as the input.  Each entry
215
        is a list of parent ids for the corresponding input revision.
216
217
        [NULL_REVISION] is used as the parent of the first user-committed
218
        revision.  Its parent list is empty.
219
220
        If the revision is not present (i.e. a ghost), None is used in place
221
        of the list of parents.
222
223
        Deprecated in bzr 1.2 - please see get_parent_map.
224
        """
225
        parents = self.get_parent_map(revisions)
3377.3.5 by John Arbash Meinel
Fix a latent bug in Graph.get_parents()
226
        return [parents.get(r, None) for r in revisions]
3172.1.2 by Robert Collins
Parent Providers should now implement ``get_parent_map`` returning a
227
228
    def get_parent_map(self, revisions):
229
        """Get a map of key:parent_list for revisions.
230
231
        This implementation delegates to get_parents, for old parent_providers
232
        that do not supply get_parent_map.
233
        """
234
        result = {}
235
        for rev, parents in self.get_parents(revisions):
236
            if parents is not None:
237
                result[rev] = parents
238
        return result
239
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
240
    def _make_breadth_first_searcher(self, revisions):
241
        return _BreadthFirstSearcher(revisions, self)
242
2490.2.10 by Aaron Bentley
Clarify text, remove unused _get_ancestry method
243
    def _find_border_ancestors(self, revisions):
2490.2.12 by Aaron Bentley
Improve documentation
244
        """Find common ancestors with at least one uncommon descendant.
245
246
        Border ancestors are identified using a breadth-first
247
        search starting at the bottom of the graph.  Searches are stopped
248
        whenever a node or one of its descendants is determined to be common.
249
250
        This will scale with the number of uncommon ancestors.
2490.2.25 by Aaron Bentley
Update from review
251
252
        As well as the border ancestors, a set of seen common ancestors and a
253
        list of sets of seen ancestors for each input revision is returned.
254
        This allows calculation of graph difference from the results of this
255
        operation.
2490.2.12 by Aaron Bentley
Improve documentation
256
        """
2490.2.28 by Aaron Bentley
Fix handling of null revision
257
        if None in revisions:
258
            raise errors.InvalidRevisionId(None, self)
2490.2.19 by Aaron Bentley
Implement common-ancestor-based culling
259
        common_ancestors = set()
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
260
        searchers = [self._make_breadth_first_searcher([r])
261
                     for r in revisions]
262
        active_searchers = searchers[:]
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
263
        border_ancestors = set()
2490.2.19 by Aaron Bentley
Implement common-ancestor-based culling
264
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
265
        while True:
266
            newly_seen = set()
3377.3.2 by John Arbash Meinel
find_difference is fixed by updating _find_border_ancestors.... is that reasonable?
267
            for searcher in searchers:
268
                new_ancestors = searcher.step()
269
                if new_ancestors:
270
                    newly_seen.update(new_ancestors)
271
            new_common = set()
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
272
            for revision in newly_seen:
2490.2.19 by Aaron Bentley
Implement common-ancestor-based culling
273
                if revision in common_ancestors:
3377.3.2 by John Arbash Meinel
find_difference is fixed by updating _find_border_ancestors.... is that reasonable?
274
                    # Not a border ancestor because it was seen as common
275
                    # already
276
                    new_common.add(revision)
2490.2.19 by Aaron Bentley
Implement common-ancestor-based culling
277
                    continue
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
278
                for searcher in searchers:
279
                    if revision not in searcher.seen:
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
280
                        break
281
                else:
3377.3.2 by John Arbash Meinel
find_difference is fixed by updating _find_border_ancestors.... is that reasonable?
282
                    # This is a border because it is a first common that we see
283
                    # after walking for a while.
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
284
                    border_ancestors.add(revision)
3377.3.2 by John Arbash Meinel
find_difference is fixed by updating _find_border_ancestors.... is that reasonable?
285
                    new_common.add(revision)
286
            if new_common:
287
                for searcher in searchers:
288
                    new_common.update(searcher.find_seen_ancestors(new_common))
289
                for searcher in searchers:
290
                    searcher.start_searching(new_common)
291
                common_ancestors.update(new_common)
292
293
            # Figure out what the searchers will be searching next, and if
294
            # there is only 1 set being searched, then we are done searching,
295
            # since all searchers would have to be searching the same data,
296
            # thus it *must* be in common.
297
            unique_search_sets = set()
298
            for searcher in searchers:
299
                will_search_set = frozenset(searcher._next_query)
300
                if will_search_set not in unique_search_sets:
301
                    # This searcher is searching a unique set of nodes, let it
302
                    unique_search_sets.add(will_search_set)
303
304
            if len(unique_search_sets) == 1:
305
                nodes = unique_search_sets.pop()
306
                uncommon_nodes = nodes.difference(common_ancestors)
307
                assert not uncommon_nodes, ("Somehow we ended up converging"
308
                                            " without actually marking them as"
309
                                            " in common."
310
                                            "\nStart_nodes: %s"
311
                                            "\nuncommon_nodes: %s"
312
                                            % (revisions, uncommon_nodes))
313
                break
314
        return border_ancestors, common_ancestors, searchers
2490.2.9 by Aaron Bentley
Fix minimal common ancestor algorithm for non-minimal perhipheral ancestors
315
2776.3.1 by Robert Collins
* Deprecated method ``find_previous_heads`` on
316
    def heads(self, keys):
317
        """Return the heads from amongst keys.
318
319
        This is done by searching the ancestries of each key.  Any key that is
320
        reachable from another key is not returned; all the others are.
321
322
        This operation scales with the relative depth between any two keys. If
323
        any two keys are completely disconnected all ancestry of both sides
324
        will be retrieved.
325
326
        :param keys: An iterable of keys.
2776.1.4 by Robert Collins
Trivial review feedback changes.
327
        :return: A set of the heads. Note that as a set there is no ordering
328
            information. Callers will need to filter their input to create
329
            order if they need it.
2490.2.12 by Aaron Bentley
Improve documentation
330
        """
2776.1.4 by Robert Collins
Trivial review feedback changes.
331
        candidate_heads = set(keys)
3052.5.5 by John Arbash Meinel
Special case Graph.heads() for NULL_REVISION rather than is_ancestor.
332
        if revision.NULL_REVISION in candidate_heads:
333
            # NULL_REVISION is only a head if it is the only entry
334
            candidate_heads.remove(revision.NULL_REVISION)
335
            if not candidate_heads:
336
                return set([revision.NULL_REVISION])
2850.2.1 by Robert Collins
(robertc) Special case the zero-or-no-heads case for Graph.heads(). (Robert Collins)
337
        if len(candidate_heads) < 2:
338
            return candidate_heads
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
339
        searchers = dict((c, self._make_breadth_first_searcher([c]))
2776.1.4 by Robert Collins
Trivial review feedback changes.
340
                          for c in candidate_heads)
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
341
        active_searchers = dict(searchers)
342
        # skip over the actual candidate for each searcher
343
        for searcher in active_searchers.itervalues():
1551.15.81 by Aaron Bentley
Remove testing code
344
            searcher.next()
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
345
        # The common walker finds nodes that are common to two or more of the
346
        # input keys, so that we don't access all history when a currently
347
        # uncommon search point actually meets up with something behind a
348
        # common search point. Common search points do not keep searches
349
        # active; they just allow us to make searches inactive without
350
        # accessing all history.
351
        common_walker = self._make_breadth_first_searcher([])
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
352
        while len(active_searchers) > 0:
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
353
            ancestors = set()
354
            # advance searches
355
            try:
356
                common_walker.next()
357
            except StopIteration:
2921.3.4 by Robert Collins
Review feedback.
358
                # No common points being searched at this time.
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
359
                pass
1551.15.78 by Aaron Bentley
Fix KeyError in filter_candidate_lca
360
            for candidate in active_searchers.keys():
361
                try:
362
                    searcher = active_searchers[candidate]
363
                except KeyError:
364
                    # rare case: we deleted candidate in a previous iteration
365
                    # through this for loop, because it was determined to be
366
                    # a descendant of another candidate.
367
                    continue
2490.2.9 by Aaron Bentley
Fix minimal common ancestor algorithm for non-minimal perhipheral ancestors
368
                try:
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
369
                    ancestors.update(searcher.next())
2490.2.9 by Aaron Bentley
Fix minimal common ancestor algorithm for non-minimal perhipheral ancestors
370
                except StopIteration:
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
371
                    del active_searchers[candidate]
2490.2.9 by Aaron Bentley
Fix minimal common ancestor algorithm for non-minimal perhipheral ancestors
372
                    continue
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
373
            # process found nodes
374
            new_common = set()
375
            for ancestor in ancestors:
376
                if ancestor in candidate_heads:
377
                    candidate_heads.remove(ancestor)
378
                    del searchers[ancestor]
379
                    if ancestor in active_searchers:
380
                        del active_searchers[ancestor]
381
                # it may meet up with a known common node
2921.3.4 by Robert Collins
Review feedback.
382
                if ancestor in common_walker.seen:
383
                    # some searcher has encountered our known common nodes:
384
                    # just stop it
385
                    ancestor_set = set([ancestor])
386
                    for searcher in searchers.itervalues():
387
                        searcher.stop_searching_any(ancestor_set)
388
                else:
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
389
                    # or it may have been just reached by all the searchers:
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
390
                    for searcher in searchers.itervalues():
391
                        if ancestor not in searcher.seen:
2490.2.9 by Aaron Bentley
Fix minimal common ancestor algorithm for non-minimal perhipheral ancestors
392
                            break
393
                    else:
2921.3.4 by Robert Collins
Review feedback.
394
                        # The final active searcher has just reached this node,
395
                        # making it be known as a descendant of all candidates,
396
                        # so we can stop searching it, and any seen ancestors
397
                        new_common.add(ancestor)
398
                        for searcher in searchers.itervalues():
399
                            seen_ancestors =\
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
400
                                searcher.find_seen_ancestors([ancestor])
2921.3.4 by Robert Collins
Review feedback.
401
                            searcher.stop_searching_any(seen_ancestors)
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
402
            common_walker.start_searching(new_common)
2776.1.4 by Robert Collins
Trivial review feedback changes.
403
        return candidate_heads
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
404
1551.19.10 by Aaron Bentley
Merge now warns when it encounters a criss-cross
405
    def find_unique_lca(self, left_revision, right_revision,
406
                        count_steps=False):
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
407
        """Find a unique LCA.
408
409
        Find lowest common ancestors.  If there is no unique  common
410
        ancestor, find the lowest common ancestors of those ancestors.
411
412
        Iteration stops when a unique lowest common ancestor is found.
413
        The graph origin is necessarily a unique lowest common ancestor.
2490.2.5 by Aaron Bentley
Use GraphWalker.unique_ancestor to determine merge base
414
415
        Note that None is not an acceptable substitute for NULL_REVISION.
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
416
        in the input for this method.
1551.19.12 by Aaron Bentley
Add documentation for the count_steps parameter of Graph.find_unique_lca
417
418
        :param count_steps: If True, the return value will be a tuple of
419
            (unique_lca, steps) where steps is the number of times that
420
            find_lca was run.  If False, only unique_lca is returned.
2490.2.3 by Aaron Bentley
Implement new merge base picker
421
        """
422
        revisions = [left_revision, right_revision]
1551.19.10 by Aaron Bentley
Merge now warns when it encounters a criss-cross
423
        steps = 0
2490.2.3 by Aaron Bentley
Implement new merge base picker
424
        while True:
1551.19.10 by Aaron Bentley
Merge now warns when it encounters a criss-cross
425
            steps += 1
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
426
            lca = self.find_lca(*revisions)
427
            if len(lca) == 1:
1551.19.10 by Aaron Bentley
Merge now warns when it encounters a criss-cross
428
                result = lca.pop()
429
                if count_steps:
430
                    return result, steps
431
                else:
432
                    return result
2520.4.104 by Aaron Bentley
Avoid infinite loop when there is no unique lca
433
            if len(lca) == 0:
434
                raise errors.NoCommonAncestor(left_revision, right_revision)
2490.2.13 by Aaron Bentley
Update distinct -> lowest, refactor, add ParentsProvider concept
435
            revisions = lca
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
436
3228.4.4 by John Arbash Meinel
Change iter_ancestry to take a group instead of a single node,
437
    def iter_ancestry(self, revision_ids):
3228.4.2 by John Arbash Meinel
Add a Graph.iter_ancestry()
438
        """Iterate the ancestry of this revision.
439
3228.4.4 by John Arbash Meinel
Change iter_ancestry to take a group instead of a single node,
440
        :param revision_ids: Nodes to start the search
3228.4.2 by John Arbash Meinel
Add a Graph.iter_ancestry()
441
        :return: Yield tuples mapping a revision_id to its parents for the
442
            ancestry of revision_id.
3228.4.10 by John Arbash Meinel
Respond to abentley's review comments.
443
            Ghosts will be returned with None as their parents, and nodes
3228.4.4 by John Arbash Meinel
Change iter_ancestry to take a group instead of a single node,
444
            with no parents will have NULL_REVISION as their only parent. (As
445
            defined by get_parent_map.)
3228.4.10 by John Arbash Meinel
Respond to abentley's review comments.
446
            There will also be a node for (NULL_REVISION, ())
3228.4.2 by John Arbash Meinel
Add a Graph.iter_ancestry()
447
        """
3228.4.4 by John Arbash Meinel
Change iter_ancestry to take a group instead of a single node,
448
        pending = set(revision_ids)
3228.4.2 by John Arbash Meinel
Add a Graph.iter_ancestry()
449
        processed = set()
450
        while pending:
451
            processed.update(pending)
452
            next_map = self.get_parent_map(pending)
453
            next_pending = set()
454
            for item in next_map.iteritems():
455
                yield item
456
                next_pending.update(p for p in item[1] if p not in processed)
457
            ghosts = pending.difference(next_map)
458
            for ghost in ghosts:
3228.4.10 by John Arbash Meinel
Respond to abentley's review comments.
459
                yield (ghost, None)
3228.4.2 by John Arbash Meinel
Add a Graph.iter_ancestry()
460
            pending = next_pending
461
2490.2.31 by Aaron Bentley
Fix iter_topo_order to permit un-included parents
462
    def iter_topo_order(self, revisions):
2490.2.30 by Aaron Bentley
Add functionality for tsorting graphs
463
        """Iterate through the input revisions in topological order.
464
465
        This sorting only ensures that parents come before their children.
466
        An ancestor may sort after a descendant if the relationship is not
467
        visible in the supplied list of revisions.
468
        """
3099.3.3 by John Arbash Meinel
Deprecate get_parents() in favor of get_parent_map()
469
        sorter = tsort.TopoSorter(self.get_parent_map(revisions))
2490.2.34 by Aaron Bentley
Update NEWS and change implementation to return an iterator
470
        return sorter.iter_topo_order()
2490.2.30 by Aaron Bentley
Add functionality for tsorting graphs
471
2653.2.1 by Aaron Bentley
Implement Graph.is_ancestor
472
    def is_ancestor(self, candidate_ancestor, candidate_descendant):
2653.2.5 by Aaron Bentley
Update to clarify algorithm
473
        """Determine whether a revision is an ancestor of another.
474
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
475
        We answer this using heads() as heads() has the logic to perform the
3078.2.6 by Ian Clatworthy
fix efficiency of local commit detection as recommended by jameinel's review
476
        smallest number of parent lookups to determine the ancestral
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
477
        relationship between N revisions.
2653.2.5 by Aaron Bentley
Update to clarify algorithm
478
        """
2921.3.1 by Robert Collins
* Graph ``heads()`` queries have been bugfixed to no longer access all
479
        return set([candidate_descendant]) == self.heads(
480
            [candidate_ancestor, candidate_descendant])
2653.2.1 by Aaron Bentley
Implement Graph.is_ancestor
481
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
482
    def _search_for_extra_common(self, common, searchers):
483
        """Make sure that unique nodes are genuinely unique.
484
3377.3.10 by John Arbash Meinel
Tweak _BreadthFirstSearcher.find_seen_ancestors()
485
        After _find_border_ancestors, all nodes marked "common" are indeed
486
        common. Some of the nodes considered unique are not, due to history
487
        shortcuts stopping the searches early.
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
488
489
        We know that we have searched enough when all common search tips are
490
        descended from all unique (uncommon) nodes because we know that a node
491
        cannot be an ancestor of its own ancestor.
492
493
        :param common: A set of common nodes
494
        :param searchers: The searchers returned from _find_border_ancestors
495
        :return: None
496
        """
497
        # Basic algorithm...
498
        #   A) The passed in searchers should all be on the same tips, thus
499
        #      they should be considered the "common" searchers.
500
        #   B) We find the difference between the searchers, these are the
501
        #      "unique" nodes for each side.
502
        #   C) We do a quick culling so that we only start searching from the
503
        #      more interesting unique nodes. (A unique ancestor is more
3377.3.10 by John Arbash Meinel
Tweak _BreadthFirstSearcher.find_seen_ancestors()
504
        #      interesting than any of its children.)
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
505
        #   D) We start searching for ancestors common to all unique nodes.
506
        #   E) We have the common searchers stop searching any ancestors of
507
        #      nodes found by (D)
508
        #   F) When there are no more common search tips, we stop
3377.3.10 by John Arbash Meinel
Tweak _BreadthFirstSearcher.find_seen_ancestors()
509
510
        # TODO: We need a way to remove unique_searchers when they overlap with
511
        #       other unique searchers.
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
512
        assert len(searchers) == 2, (
513
            "Algorithm not yet implemented for > 2 searchers")
514
        common_searchers = searchers
515
        left_searcher = searchers[0]
516
        right_searcher = searchers[1]
3377.3.15 by John Arbash Meinel
minor update
517
        unique = left_searcher.seen.symmetric_difference(right_searcher.seen)
3377.3.17 by John Arbash Meinel
Keep track of the intersection of unique ancestry,
518
        if not unique: # No unique nodes, nothing to do
519
            return
3377.3.10 by John Arbash Meinel
Tweak _BreadthFirstSearcher.find_seen_ancestors()
520
        total_unique = len(unique)
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
521
        unique = self._remove_simple_descendants(unique,
522
                    self.get_parent_map(unique))
3377.3.10 by John Arbash Meinel
Tweak _BreadthFirstSearcher.find_seen_ancestors()
523
        simple_unique = len(unique)
524
        trace.mutter('Starting %s unique searchers for %s unique revisions',
525
                     simple_unique, total_unique)
3377.3.14 by John Arbash Meinel
Take another tack on _search_for_extra
526
527
        unique_searchers = []
528
        for revision_id in unique:
3377.3.15 by John Arbash Meinel
minor update
529
            if revision_id in left_searcher.seen:
3377.3.14 by John Arbash Meinel
Take another tack on _search_for_extra
530
                parent_searcher = left_searcher
531
            else:
532
                parent_searcher = right_searcher
533
            revs_to_search = parent_searcher.find_seen_ancestors([revision_id])
534
            if not revs_to_search: # XXX: This shouldn't be possible
535
                revs_to_search = [revision_id]
3377.3.15 by John Arbash Meinel
minor update
536
            searcher = self._make_breadth_first_searcher(revs_to_search)
537
            # We don't care about the starting nodes.
538
            searcher.step()
539
            unique_searchers.append(searcher)
3377.3.14 by John Arbash Meinel
Take another tack on _search_for_extra
540
3377.3.16 by John Arbash Meinel
small cleanups
541
        # possible todo: aggregate the common searchers into a single common
542
        #   searcher, just make sure that we include the nodes into the .seen
543
        #   properties of the original searchers
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
544
3377.3.17 by John Arbash Meinel
Keep track of the intersection of unique ancestry,
545
        ancestor_all_unique = None
546
        for searcher in unique_searchers:
547
            if ancestor_all_unique is None:
548
                ancestor_all_unique = set(searcher.seen)
549
            else:
550
                ancestor_all_unique = ancestor_all_unique.intersection(
551
                                            searcher.seen)
552
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
553
        while True: # If we have no more nodes we have nothing to do
554
            newly_seen_common = set()
555
            for searcher in common_searchers:
556
                newly_seen_common.update(searcher.step())
557
            newly_seen_unique = set()
558
            for searcher in unique_searchers:
559
                newly_seen_unique.update(searcher.step())
560
            new_common_unique = set()
561
            for revision in newly_seen_unique:
562
                for searcher in unique_searchers:
563
                    if revision not in searcher.seen:
564
                        break
565
                else:
566
                    # This is a border because it is a first common that we see
567
                    # after walking for a while.
568
                    new_common_unique.add(revision)
569
            if newly_seen_common:
570
                # These are nodes descended from one of the 'common' searchers.
571
                # Make sure all searchers are on the same page
572
                for searcher in common_searchers:
3377.3.16 by John Arbash Meinel
small cleanups
573
                    newly_seen_common.update(
574
                        searcher.find_seen_ancestors(newly_seen_common))
3377.3.14 by John Arbash Meinel
Take another tack on _search_for_extra
575
                # We start searching the whole ancestry. It is a bit wasteful,
576
                # though. We really just want to mark all of these nodes as
577
                # 'seen' and then start just the tips. However, it requires a
578
                # get_parent_map() call to figure out the tips anyway, and all
579
                # redundant requests should be fairly fast.
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
580
                for searcher in common_searchers:
581
                    searcher.start_searching(newly_seen_common)
3377.3.13 by John Arbash Meinel
Change _search_for_extra_common slightly.
582
3377.3.17 by John Arbash Meinel
Keep track of the intersection of unique ancestry,
583
                # If a 'common' node is an ancestor of all unique searchers, we
3377.3.13 by John Arbash Meinel
Change _search_for_extra_common slightly.
584
                # can stop searching it.
3377.3.17 by John Arbash Meinel
Keep track of the intersection of unique ancestry,
585
                stop_searching_common = ancestor_all_unique.intersection(
586
                                            newly_seen_common)
3377.3.13 by John Arbash Meinel
Change _search_for_extra_common slightly.
587
                if stop_searching_common:
588
                    for searcher in common_searchers:
589
                        searcher.stop_searching_any(stop_searching_common)
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
590
            if new_common_unique:
591
                # We found some ancestors that are common, jump all the way to
592
                # their most ancestral node that we have already seen.
3377.3.10 by John Arbash Meinel
Tweak _BreadthFirstSearcher.find_seen_ancestors()
593
                for searcher in unique_searchers:
3377.3.16 by John Arbash Meinel
small cleanups
594
                    new_common_unique.update(
595
                        searcher.find_seen_ancestors(new_common_unique))
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
596
                # Since these are common, we can grab another set of ancestors
597
                # that we have seen
598
                for searcher in common_searchers:
3377.3.16 by John Arbash Meinel
small cleanups
599
                    new_common_unique.update(
600
                        searcher.find_seen_ancestors(new_common_unique))
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
601
602
                # Now we have a complete set of common nodes which are
603
                # ancestors of the unique nodes.
604
                # We can tell all of the unique searchers to start at these
605
                # nodes, and tell all of the common searchers to *stop*
606
                # searching these nodes
607
                for searcher in unique_searchers:
608
                    searcher.start_searching(new_common_unique)
609
                for searcher in common_searchers:
610
                    searcher.stop_searching_any(new_common_unique)
3377.3.17 by John Arbash Meinel
Keep track of the intersection of unique ancestry,
611
                ancestor_all_unique.update(new_common_unique)
3377.3.2 by John Arbash Meinel
find_difference is fixed by updating _find_border_ancestors.... is that reasonable?
612
            for searcher in common_searchers:
613
                if searcher._next_query:
614
                    break
615
            else:
616
                # All common searcher have stopped searching
3377.3.16 by John Arbash Meinel
small cleanups
617
                return
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
618
619
    def _remove_simple_descendants(self, revisions, parent_map):
620
        """remove revisions which are children of other ones in the set
621
622
        This doesn't do any graph searching, it just checks the immediate
623
        parent_map to find if there are any children which can be removed.
624
625
        :param revisions: A set of revision_ids
626
        :return: A set of revision_ids with the children removed
627
        """
628
        simple_ancestors = revisions.copy()
629
        # TODO: jam 20071214 we *could* restrict it to searching only the
630
        #       parent_map of revisions already present in 'revisions', but
631
        #       considering the general use case, I think this is actually
632
        #       better.
633
634
        # This is the same as the following loop. I don't know that it is any
635
        # faster.
636
        ## simple_ancestors.difference_update(r for r, p_ids in parent_map.iteritems()
637
        ##     if p_ids is not None and revisions.intersection(p_ids))
638
        ## return simple_ancestors
639
640
        # Yet Another Way, invert the parent map (which can be cached)
641
        ## descendants = {}
642
        ## for revision_id, parent_ids in parent_map.iteritems():
643
        ##   for p_id in parent_ids:
644
        ##       descendants.setdefault(p_id, []).append(revision_id)
645
        ## for revision in revisions.intersection(descendants):
646
        ##   simple_ancestors.difference_update(descendants[revision])
647
        ## return simple_ancestors
648
        for revision, parent_ids in parent_map.iteritems():
649
            if parent_ids is None:
650
                continue
651
            for parent_id in parent_ids:
652
                if parent_id in revisions:
653
                    # This node has a parent present in the set, so we can
654
                    # remove it
655
                    simple_ancestors.discard(revision)
656
                    break
657
        return simple_ancestors
658
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
659
2911.4.1 by Robert Collins
Factor out the Graph.heads() cache from _RevisionTextVersionCache for reuse, and use it in commit.
660
class HeadsCache(object):
661
    """A cache of results for graph heads calls."""
662
663
    def __init__(self, graph):
664
        self.graph = graph
665
        self._heads = {}
666
667
    def heads(self, keys):
668
        """Return the heads of keys.
669
2911.4.3 by Robert Collins
Make the contract of HeadsCache.heads() more clear.
670
        This matches the API of Graph.heads(), specifically the return value is
671
        a set which can be mutated, and ordering of the input is not preserved
672
        in the output.
673
2911.4.1 by Robert Collins
Factor out the Graph.heads() cache from _RevisionTextVersionCache for reuse, and use it in commit.
674
        :see also: Graph.heads.
675
        :param keys: The keys to calculate heads for.
676
        :return: A set containing the heads, which may be mutated without
677
            affecting future lookups.
678
        """
2911.4.2 by Robert Collins
Make HeadsCache actually work.
679
        keys = frozenset(keys)
2911.4.1 by Robert Collins
Factor out the Graph.heads() cache from _RevisionTextVersionCache for reuse, and use it in commit.
680
        try:
681
            return set(self._heads[keys])
682
        except KeyError:
683
            heads = self.graph.heads(keys)
684
            self._heads[keys] = heads
685
            return set(heads)
686
687
3224.1.20 by John Arbash Meinel
Reduce the number of cache misses by caching known heads answers
688
class FrozenHeadsCache(object):
689
    """Cache heads() calls, assuming the caller won't modify them."""
690
691
    def __init__(self, graph):
692
        self.graph = graph
693
        self._heads = {}
694
695
    def heads(self, keys):
696
        """Return the heads of keys.
697
3224.1.24 by John Arbash Meinel
Fix up docstring since FrozenHeadsCache doesn't let you mutate the result.
698
        Similar to Graph.heads(). The main difference is that the return value
699
        is a frozen set which cannot be mutated.
3224.1.20 by John Arbash Meinel
Reduce the number of cache misses by caching known heads answers
700
701
        :see also: Graph.heads.
702
        :param keys: The keys to calculate heads for.
3224.1.24 by John Arbash Meinel
Fix up docstring since FrozenHeadsCache doesn't let you mutate the result.
703
        :return: A frozenset containing the heads.
3224.1.20 by John Arbash Meinel
Reduce the number of cache misses by caching known heads answers
704
        """
705
        keys = frozenset(keys)
706
        try:
707
            return self._heads[keys]
708
        except KeyError:
709
            heads = frozenset(self.graph.heads(keys))
710
            self._heads[keys] = heads
711
            return heads
712
713
    def cache(self, keys, heads):
714
        """Store a known value."""
715
        self._heads[frozenset(keys)] = frozenset(heads)
716
717
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
718
class _BreadthFirstSearcher(object):
2921.3.4 by Robert Collins
Review feedback.
719
    """Parallel search breadth-first the ancestry of revisions.
2490.2.10 by Aaron Bentley
Clarify text, remove unused _get_ancestry method
720
721
    This class implements the iterator protocol, but additionally
722
    1. provides a set of seen ancestors, and
723
    2. allows some ancestries to be unsearched, via stop_searching_any
724
    """
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
725
2490.2.22 by Aaron Bentley
Rename GraphWalker -> Graph, _AncestryWalker -> _BreadthFirstSearcher
726
    def __init__(self, revisions, parents_provider):
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
727
        self._iterations = 0
728
        self._next_query = set(revisions)
729
        self.seen = set()
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
730
        self._started_keys = set(self._next_query)
731
        self._stopped_keys = set()
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
732
        self._parents_provider = parents_provider
3177.3.3 by Robert Collins
Review feedback.
733
        self._returning = 'next_with_ghosts'
3184.1.2 by Robert Collins
Add tests for starting and stopping searches in combination with get_recipe.
734
        self._current_present = set()
735
        self._current_ghosts = set()
736
        self._current_parents = {}
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
737
738
    def __repr__(self):
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
739
        if self._iterations:
740
            prefix = "searching"
3099.3.1 by John Arbash Meinel
Implement get_parent_map for ParentProviders
741
        else:
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
742
            prefix = "starting"
743
        search = '%s=%r' % (prefix, list(self._next_query))
744
        return ('_BreadthFirstSearcher(iterations=%d, %s,'
745
                ' seen=%r)' % (self._iterations, search, list(self.seen)))
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
746
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
747
    def get_result(self):
748
        """Get a SearchResult for the current state of this searcher.
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
749
        
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
750
        :return: A SearchResult for this search so far. The SearchResult is
751
            static - the search can be advanced and the search result will not
752
            be invalidated or altered.
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
753
        """
754
        if self._returning == 'next':
755
            # We have to know the current nodes children to be able to list the
756
            # exclude keys for them. However, while we could have a second
757
            # look-ahead result buffer and shuffle things around, this method
758
            # is typically only called once per search - when memoising the
3211.5.1 by Robert Collins
Change the smart server get_parents method to take a graph search to exclude already recieved parents from. This prevents history shortcuts causing huge numbers of duplicates.
759
            # results of the search. 
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
760
            found, ghosts, next, parents = self._do_query(self._next_query)
761
            # pretend we didn't query: perhaps we should tweak _do_query to be
762
            # entirely stateless?
763
            self.seen.difference_update(next)
3184.1.3 by Robert Collins
Automatically exclude ghosts.
764
            next_query = next.union(ghosts)
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
765
        else:
766
            next_query = self._next_query
3184.1.5 by Robert Collins
Record the number of found revisions for cross checking.
767
        excludes = self._stopped_keys.union(next_query)
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
768
        included_keys = self.seen.difference(excludes)
769
        return SearchResult(self._started_keys, excludes, len(included_keys),
770
            included_keys)
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
771
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
772
    def step(self):
773
        try:
774
            return self.next()
775
        except StopIteration:
776
            return ()
777
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
778
    def next(self):
2490.2.10 by Aaron Bentley
Clarify text, remove unused _get_ancestry method
779
        """Return the next ancestors of this revision.
780
2490.2.12 by Aaron Bentley
Improve documentation
781
        Ancestors are returned in the order they are seen in a breadth-first
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
782
        traversal.  No ancestor will be returned more than once. Ancestors are
783
        returned before their parentage is queried, so ghosts and missing
784
        revisions (including the start revisions) are included in the result.
785
        This can save a round trip in LCA style calculation by allowing
786
        convergence to be detected without reading the data for the revision
787
        the convergence occurs on.
788
789
        :return: A set of revision_ids.
2490.2.10 by Aaron Bentley
Clarify text, remove unused _get_ancestry method
790
        """
3177.3.3 by Robert Collins
Review feedback.
791
        if self._returning != 'next':
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
792
            # switch to returning the query, not the results.
3177.3.3 by Robert Collins
Review feedback.
793
            self._returning = 'next'
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
794
            self._iterations += 1
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
795
        else:
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
796
            self._advance()
797
        if len(self._next_query) == 0:
798
            raise StopIteration()
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
799
        # We have seen what we're querying at this point as we are returning
800
        # the query, not the results.
801
        self.seen.update(self._next_query)
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
802
        return self._next_query
803
804
    def next_with_ghosts(self):
805
        """Return the next found ancestors, with ghosts split out.
806
        
807
        Ancestors are returned in the order they are seen in a breadth-first
808
        traversal.  No ancestor will be returned more than once. Ancestors are
3177.3.3 by Robert Collins
Review feedback.
809
        returned only after asking for their parents, which allows us to detect
810
        which revisions are ghosts and which are not.
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
811
812
        :return: A tuple with (present ancestors, ghost ancestors) sets.
813
        """
3177.3.3 by Robert Collins
Review feedback.
814
        if self._returning != 'next_with_ghosts':
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
815
            # switch to returning the results, not the current query.
3177.3.3 by Robert Collins
Review feedback.
816
            self._returning = 'next_with_ghosts'
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
817
            self._advance()
818
        if len(self._next_query) == 0:
819
            raise StopIteration()
820
        self._advance()
821
        return self._current_present, self._current_ghosts
822
823
    def _advance(self):
824
        """Advance the search.
825
826
        Updates self.seen, self._next_query, self._current_present,
3177.3.3 by Robert Collins
Review feedback.
827
        self._current_ghosts, self._current_parents and self._iterations.
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
828
        """
829
        self._iterations += 1
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
830
        found, ghosts, next, parents = self._do_query(self._next_query)
831
        self._current_present = found
832
        self._current_ghosts = ghosts
833
        self._next_query = next
834
        self._current_parents = parents
3184.1.3 by Robert Collins
Automatically exclude ghosts.
835
        # ghosts are implicit stop points, otherwise the search cannot be
836
        # repeated when ghosts are filled.
837
        self._stopped_keys.update(ghosts)
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
838
839
    def _do_query(self, revisions):
840
        """Query for revisions.
841
3184.1.4 by Robert Collins
Correctly exclude ghosts when ghosts are started on an existing search.
842
        Adds revisions to the seen set.
843
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
844
        :param revisions: Revisions to query.
845
        :return: A tuple: (set(found_revisions), set(ghost_revisions),
846
           set(parents_of_found_revisions), dict(found_revisions:parents)).
847
        """
3377.3.9 by John Arbash Meinel
Small tweaks to _do_query
848
        found_revisions = set()
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
849
        parents_of_found = set()
3184.1.1 by Robert Collins
Add basic get_recipe to the graph breadth first searcher.
850
        # revisions may contain nodes that point to other nodes in revisions:
851
        # we want to filter them out.
852
        self.seen.update(revisions)
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
853
        parent_map = self._parents_provider.get_parent_map(revisions)
3377.3.9 by John Arbash Meinel
Small tweaks to _do_query
854
        found_revisions.update(parent_map)
3177.3.1 by Robert Collins
* New method ``next_with_ghosts`` on the Graph breadth-first-search objects
855
        for rev_id, parents in parent_map.iteritems():
3377.3.9 by John Arbash Meinel
Small tweaks to _do_query
856
            new_found_parents = [p for p in parents if p not in self.seen]
857
            if new_found_parents:
858
                # Calling set.update() with an empty generator is actually
859
                # rather expensive.
860
                parents_of_found.update(new_found_parents)
861
        ghost_revisions = revisions - found_revisions
862
        return found_revisions, ghost_revisions, parents_of_found, parent_map
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
863
2490.2.8 by Aaron Bentley
fix iteration stuff
864
    def __iter__(self):
865
        return self
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
866
3377.3.1 by John Arbash Meinel
Bring in some of the changes from graph_update and graph_optimization
867
    def find_seen_ancestors(self, revisions):
868
        """Find ancestors of these revisions that have already been seen."""
3377.3.10 by John Arbash Meinel
Tweak _BreadthFirstSearcher.find_seen_ancestors()
869
        all_seen = self.seen
870
        pending = set(revisions).intersection(all_seen)
871
        seen_ancestors = set(pending)
872
873
        if self._returning == 'next':
874
            # self.seen contains what nodes have been returned, not what nodes
875
            # have been queried. We don't want to probe for nodes that haven't
876
            # been searched yet.
877
            not_searched_yet = self._next_query
878
        else:
879
            not_searched_yet = ()
3377.3.11 by John Arbash Meinel
Committing a debug thunk that was very helpful
880
        pending.difference_update(not_searched_yet)
3377.3.10 by John Arbash Meinel
Tweak _BreadthFirstSearcher.find_seen_ancestors()
881
        get_parent_map = self._parents_provider.get_parent_map
3377.3.12 by John Arbash Meinel
Remove the helpful but ugly thunk
882
        while pending:
883
            parent_map = get_parent_map(pending)
884
            all_parents = []
885
            # We don't care if it is a ghost, since it can't be seen if it is
886
            # a ghost
887
            for parent_ids in parent_map.itervalues():
888
                all_parents.extend(parent_ids)
889
            next_pending = all_seen.intersection(all_parents).difference(seen_ancestors)
890
            seen_ancestors.update(next_pending)
891
            next_pending.difference_update(not_searched_yet)
892
            pending = next_pending
3377.3.10 by John Arbash Meinel
Tweak _BreadthFirstSearcher.find_seen_ancestors()
893
2490.2.7 by Aaron Bentley
Start implementing mca that scales with number of uncommon ancestors
894
        return seen_ancestors
895
2490.2.10 by Aaron Bentley
Clarify text, remove unused _get_ancestry method
896
    def stop_searching_any(self, revisions):
897
        """
898
        Remove any of the specified revisions from the search list.
899
900
        None of the specified revisions are required to be present in the
2490.2.12 by Aaron Bentley
Improve documentation
901
        search list.  In this case, the call is a no-op.
2490.2.10 by Aaron Bentley
Clarify text, remove unused _get_ancestry method
902
        """
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
903
        revisions = frozenset(revisions)
3177.3.3 by Robert Collins
Review feedback.
904
        if self._returning == 'next':
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
905
            stopped = self._next_query.intersection(revisions)
906
            self._next_query = self._next_query.difference(revisions)
907
        else:
3184.2.1 by Robert Collins
Handle stopping ghosts in searches properly.
908
            stopped_present = self._current_present.intersection(revisions)
909
            stopped = stopped_present.union(
910
                self._current_ghosts.intersection(revisions))
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
911
            self._current_present.difference_update(stopped)
912
            self._current_ghosts.difference_update(stopped)
913
            # stopping 'x' should stop returning parents of 'x', but 
914
            # not if 'y' always references those same parents
915
            stop_rev_references = {}
3184.2.1 by Robert Collins
Handle stopping ghosts in searches properly.
916
            for rev in stopped_present:
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
917
                for parent_id in self._current_parents[rev]:
918
                    if parent_id not in stop_rev_references:
919
                        stop_rev_references[parent_id] = 0
920
                    stop_rev_references[parent_id] += 1
921
            # if only the stopped revisions reference it, the ref count will be
922
            # 0 after this loop
3177.3.3 by Robert Collins
Review feedback.
923
            for parents in self._current_parents.itervalues():
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
924
                for parent_id in parents:
925
                    try:
926
                        stop_rev_references[parent_id] -= 1
927
                    except KeyError:
928
                        pass
929
            stop_parents = set()
930
            for rev_id, refs in stop_rev_references.iteritems():
931
                if refs == 0:
932
                    stop_parents.add(rev_id)
933
            self._next_query.difference_update(stop_parents)
3184.1.2 by Robert Collins
Add tests for starting and stopping searches in combination with get_recipe.
934
        self._stopped_keys.update(stopped)
2490.2.25 by Aaron Bentley
Update from review
935
        return stopped
2490.2.17 by Aaron Bentley
Add start_searching, tweak stop_searching_any
936
937
    def start_searching(self, revisions):
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
938
        """Add revisions to the search.
939
940
        The parents of revisions will be returned from the next call to next()
941
        or next_with_ghosts(). If next_with_ghosts was the most recently used
942
        next* call then the return value is the result of looking up the
943
        ghost/not ghost status of revisions. (A tuple (present, ghosted)).
944
        """
945
        revisions = frozenset(revisions)
3184.1.2 by Robert Collins
Add tests for starting and stopping searches in combination with get_recipe.
946
        self._started_keys.update(revisions)
3184.1.4 by Robert Collins
Correctly exclude ghosts when ghosts are started on an existing search.
947
        new_revisions = revisions.difference(self.seen)
948
        revs, ghosts, query, parents = self._do_query(revisions)
949
        self._stopped_keys.update(ghosts)
3177.3.3 by Robert Collins
Review feedback.
950
        if self._returning == 'next':
3184.1.4 by Robert Collins
Correctly exclude ghosts when ghosts are started on an existing search.
951
            self._next_query.update(new_revisions)
3177.3.2 by Robert Collins
Update graph searchers stop_searching_any and start_searching for next_with_ghosts.
952
        else:
953
            # perform a query on revisions
954
            self._current_present.update(revs)
955
            self._current_ghosts.update(ghosts)
956
            self._next_query.update(query)
957
            self._current_parents.update(parents)
958
            return revs, ghosts
3184.1.6 by Robert Collins
Create a SearchResult object which can be used as a replacement for sets.
959
960
961
class SearchResult(object):
962
    """The result of a breadth first search.
963
964
    A SearchResult provides the ability to reconstruct the search or access a
965
    set of the keys the search found.
966
    """
967
968
    def __init__(self, start_keys, exclude_keys, key_count, keys):
969
        """Create a SearchResult.
970
971
        :param start_keys: The keys the search started at.
972
        :param exclude_keys: The keys the search excludes.
973
        :param key_count: The total number of keys (from start to but not
974
            including exclude).
975
        :param keys: The keys the search found. Note that in future we may get
976
            a SearchResult from a smart server, in which case the keys list is
977
            not necessarily immediately available.
978
        """
979
        self._recipe = (start_keys, exclude_keys, key_count)
980
        self._keys = frozenset(keys)
981
982
    def get_recipe(self):
983
        """Return a recipe that can be used to replay this search.
984
        
985
        The recipe allows reconstruction of the same results at a later date
986
        without knowing all the found keys. The essential elements are a list
987
        of keys to start and and to stop at. In order to give reproducible
988
        results when ghosts are encountered by a search they are automatically
989
        added to the exclude list (or else ghost filling may alter the
990
        results).
991
992
        :return: A tuple (start_keys_set, exclude_keys_set, revision_count). To
993
            recreate the results of this search, create a breadth first
994
            searcher on the same graph starting at start_keys. Then call next()
995
            (or next_with_ghosts()) repeatedly, and on every result, call
996
            stop_searching_any on any keys from the exclude_keys set. The
997
            revision_count value acts as a trivial cross-check - the found
998
            revisions of the new search should have as many elements as
999
            revision_count. If it does not, then additional revisions have been
1000
            ghosted since the search was executed the first time and the second
1001
            time.
1002
        """
1003
        return self._recipe
1004
1005
    def get_keys(self):
1006
        """Return the keys found in this search.
1007
1008
        :return: A set of keys.
1009
        """
1010
        return self._keys
1011