/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4431.3.8 by Jonathan Lange
Cherrypick bzr.dev r4477.
1
# Copyright (C) 2008, 2009 Canonical Ltd
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
17
"""Persistent maps from tuple_of_strings->string using CHK stores.
18
19
Overview and current status:
20
21
The CHKMap class implements a dict from tuple_of_strings->string by using a trie
22
with internal nodes of 8-bit fan out; The key tuples are mapped to strings by
23
joining them by \x00, and \x00 padding shorter keys out to the length of the
24
longest key. Leaf nodes are packed as densely as possible, and internal nodes
3735.19.1 by Ian Clatworthy
CHKMap cleanups
25
are all an additional 8-bits wide leading to a sparse upper tree.
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
26
27
Updates to a CHKMap are done preferentially via the apply_delta method, to
28
allow optimisation of the update operation; but individual map/unmap calls are
4526.9.5 by Robert Collins
Require that added ids in inventory deltas be new.
29
possible and supported. Individual changes via map/unmap are buffered in memory
30
until the _save method is called to force serialisation of the tree.
31
apply_delta records its changes immediately by performing an implicit _save.
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
32
33
TODO:
34
-----
35
36
Densely packed upper nodes.
37
38
"""
39
40
import heapq
41
42
from bzrlib import lazy_import
43
lazy_import.lazy_import(globals(), """
4526.9.5 by Robert Collins
Require that added ids in inventory deltas be new.
44
from bzrlib import (
45
    errors,
46
    versionedfile,
47
    )
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
48
""")
49
from bzrlib import (
50
    lru_cache,
51
    osutils,
52
    registry,
53
    trace,
54
    )
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
55
from bzrlib.static_tuple import StaticTuple
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
56
3735.19.1 by Ian Clatworthy
CHKMap cleanups
57
# approx 4MB
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
58
# If each line is 50 bytes, and you have 255 internal pages, with 255-way fan
59
# out, it takes 3.1MB to cache the layer.
60
_PAGE_CACHE_SIZE = 4*1024*1024
61
# We are caching bytes so len(value) is perfectly accurate
62
_page_cache = lru_cache.LRUSizeCache(_PAGE_CACHE_SIZE)
63
4543.2.2 by John Arbash Meinel
work out some tests that expose that bundles don't work w/ 2a formats.
64
def clear_cache():
65
    _page_cache.clear()
66
3735.2.123 by Ian Clatworthy
only check for remap if changes are interesting in size
67
# If a ChildNode falls below this many bytes, we check for a remap
68
_INTERESTING_NEW_SIZE = 50
69
# If a ChildNode shrinks by more than this amount, we check for a remap
70
_INTERESTING_SHRINKAGE_LIMIT = 20
71
# If we delete more than this many nodes applying a delta, we check for a remap
72
_INTERESTING_DELETES_LIMIT = 5
73
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
74
75
def _search_key_plain(key):
76
    """Map the key tuple into a search string that just uses the key bytes."""
77
    return '\x00'.join(key)
78
79
80
search_key_registry = registry.Registry()
81
search_key_registry.register('plain', _search_key_plain)
82
83
84
class CHKMap(object):
85
    """A persistent map from string to string backed by a CHK store."""
86
4759.1.2 by John Arbash Meinel
Change CHKMap to use __slots__
87
    __slots__ = ('_store', '_root_node', '_search_key_func')
88
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
89
    def __init__(self, store, root_key, search_key_func=None):
90
        """Create a CHKMap object.
91
92
        :param store: The store the CHKMap is stored in.
93
        :param root_key: The root key of the map. None to create an empty
94
            CHKMap.
95
        :param search_key_func: A function mapping a key => bytes. These bytes
96
            are then used by the internal nodes to split up leaf nodes into
97
            multiple pages.
98
        """
99
        self._store = store
100
        if search_key_func is None:
101
            search_key_func = _search_key_plain
102
        self._search_key_func = search_key_func
103
        if root_key is None:
104
            self._root_node = LeafNode(search_key_func=search_key_func)
105
        else:
106
            self._root_node = self._node_key(root_key)
107
108
    def apply_delta(self, delta):
109
        """Apply a delta to the map.
110
111
        :param delta: An iterable of old_key, new_key, new_value tuples.
112
            If new_key is not None, then new_key->new_value is inserted
113
            into the map; if old_key is not None, then the old mapping
114
            of old_key is removed.
115
        """
3735.2.123 by Ian Clatworthy
only check for remap if changes are interesting in size
116
        delete_count = 0
4526.9.5 by Robert Collins
Require that added ids in inventory deltas be new.
117
        # Check preconditions first.
118
        new_items = set([key for (old, key, value) in delta if key is not None
119
            and old is None])
120
        existing_new = list(self.iteritems(key_filter=new_items))
121
        if existing_new:
122
            raise errors.InconsistentDeltaDelta(delta,
123
                "New items are already in the map %r." % existing_new)
124
        # Now apply changes.
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
125
        for old, new, value in delta:
126
            if old is not None and old != new:
3735.2.122 by Ian Clatworthy
don't check_remap on every unmap call in CHKMap.apply_delta()
127
                self.unmap(old, check_remap=False)
3735.2.123 by Ian Clatworthy
only check for remap if changes are interesting in size
128
                delete_count += 1
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
129
        for old, new, value in delta:
130
            if new is not None:
131
                self.map(new, value)
3735.2.123 by Ian Clatworthy
only check for remap if changes are interesting in size
132
        if delete_count > _INTERESTING_DELETES_LIMIT:
133
            trace.mutter("checking remap as %d deletions", delete_count)
3735.2.122 by Ian Clatworthy
don't check_remap on every unmap call in CHKMap.apply_delta()
134
            self._check_remap()
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
135
        return self._save()
136
137
    def _ensure_root(self):
138
        """Ensure that the root node is an object not a key."""
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
139
        if type(self._root_node) is StaticTuple:
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
140
            # Demand-load the root
141
            self._root_node = self._get_node(self._root_node)
142
143
    def _get_node(self, node):
144
        """Get a node.
145
3735.19.1 by Ian Clatworthy
CHKMap cleanups
146
        Note that this does not update the _items dict in objects containing a
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
147
        reference to this node. As such it does not prevent subsequent IO being
148
        performed.
149
150
        :param node: A tuple key or node object.
151
        :return: A node object.
152
        """
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
153
        if type(node) is StaticTuple:
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
154
            bytes = self._read_bytes(node)
155
            return _deserialise(bytes, node,
156
                search_key_func=self._search_key_func)
157
        else:
158
            return node
159
160
    def _read_bytes(self, key):
3735.2.124 by Ian Clatworthy
use the page cache in CHKMap._read_bytes()
161
        try:
162
            return _page_cache[key]
163
        except KeyError:
164
            stream = self._store.get_record_stream([key], 'unordered', True)
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
165
            bytes = stream.next().get_bytes_as('fulltext')
166
            _page_cache[key] = bytes
167
            return bytes
168
169
    def _dump_tree(self, include_keys=False):
170
        """Return the tree in a string representation."""
171
        self._ensure_root()
172
        res = self._dump_tree_node(self._root_node, prefix='', indent='',
173
                                   include_keys=include_keys)
174
        res.append('') # Give a trailing '\n'
175
        return '\n'.join(res)
176
177
    def _dump_tree_node(self, node, prefix, indent, include_keys=True):
178
        """For this node and all children, generate a string representation."""
179
        result = []
180
        if not include_keys:
181
            key_str = ''
182
        else:
183
            node_key = node.key()
184
            if node_key is not None:
185
                key_str = ' %s' % (node_key[0],)
186
            else:
187
                key_str = ' None'
188
        result.append('%s%r %s%s' % (indent, prefix, node.__class__.__name__,
189
                                     key_str))
190
        if type(node) is InternalNode:
191
            # Trigger all child nodes to get loaded
192
            list(node._iter_nodes(self._store))
193
            for prefix, sub in sorted(node._items.iteritems()):
194
                result.extend(self._dump_tree_node(sub, prefix, indent + '  ',
195
                                                   include_keys=include_keys))
196
        else:
197
            for key, value in sorted(node._items.iteritems()):
198
                # Don't use prefix nor indent here to line up when used in
199
                # tests in conjunction with assertEqualDiff
4679.9.1 by John Arbash Meinel
Merge in the static-tuple-no-use branch, and bring back the chk_map use.
200
                result.append('      %r %r' % (tuple(key), value))
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
201
        return result
202
203
    @classmethod
3735.19.1 by Ian Clatworthy
CHKMap cleanups
204
    def from_dict(klass, store, initial_value, maximum_size=0, key_width=1,
205
        search_key_func=None):
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
206
        """Create a CHKMap in store with initial_value as the content.
207
208
        :param store: The store to record initial_value in, a VersionedFiles
209
            object with 1-tuple keys supporting CHK key generation.
210
        :param initial_value: A dict to store in store. Its keys and values
211
            must be bytestrings.
212
        :param maximum_size: The maximum_size rule to apply to nodes. This
213
            determines the size at which no new data is added to a single node.
214
        :param key_width: The number of elements in each key_tuple being stored
215
            in this map.
3735.19.1 by Ian Clatworthy
CHKMap cleanups
216
        :param search_key_func: A function mapping a key => bytes. These bytes
217
            are then used by the internal nodes to split up leaf nodes into
218
            multiple pages.
219
        :return: The root chk of the resulting CHKMap.
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
220
        """
4413.5.7 by John Arbash Meinel
Switch to using a single code path for from_dict().
221
        root_key = klass._create_directly(store, initial_value,
222
            maximum_size=maximum_size, key_width=key_width,
223
            search_key_func=search_key_func)
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
224
        assert type(root_key) is StaticTuple
4413.5.5 by John Arbash Meinel
Make it more obvious how the two creation methods are defined.
225
        return root_key
226
227
    @classmethod
228
    def _create_via_map(klass, store, initial_value, maximum_size=0,
229
                        key_width=1, search_key_func=None):
230
        result = klass(store, None, search_key_func=search_key_func)
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
231
        result._root_node.set_maximum_size(maximum_size)
232
        result._root_node._key_width = key_width
233
        delta = []
234
        for key, value in initial_value.items():
235
            delta.append((None, key, value))
4413.5.4 by John Arbash Meinel
Change CHKMap.from_dict to create a LeafNode and split it.
236
        root_key = result.apply_delta(delta)
4413.5.5 by John Arbash Meinel
Make it more obvious how the two creation methods are defined.
237
        return root_key
238
239
    @classmethod
240
    def _create_directly(klass, store, initial_value, maximum_size=0,
241
                         key_width=1, search_key_func=None):
4413.5.4 by John Arbash Meinel
Change CHKMap.from_dict to create a LeafNode and split it.
242
        node = LeafNode(search_key_func=search_key_func)
243
        node.set_maximum_size(maximum_size)
244
        node._key_width = key_width
245
        node._items = dict(initial_value)
246
        node._raw_size = sum([node._key_value_len(key, value)
247
                              for key,value in initial_value.iteritems()])
248
        node._len = len(node._items)
249
        node._compute_search_prefix()
250
        node._compute_serialised_prefix()
251
        if (node._len > 1
252
            and maximum_size
253
            and node._current_size() > maximum_size):
254
            prefix, node_details = node._split(store)
4413.5.8 by John Arbash Meinel
Change some asserts into raise: calls.
255
            if len(node_details) == 1:
256
                raise AssertionError('Failed to split using node._split')
4413.5.4 by John Arbash Meinel
Change CHKMap.from_dict to create a LeafNode and split it.
257
            node = InternalNode(prefix, search_key_func=search_key_func)
258
            node.set_maximum_size(maximum_size)
259
            node._key_width = key_width
260
            for split, subnode in node_details:
261
                node.add_node(split, subnode)
262
        keys = list(node.serialise(store))
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
263
        root_node = keys[-1]
264
        assert (type(root_node) is StaticTuple
265
                and len(root_node) == 1 and
266
                type(root_node[0]) is str)
267
        return root_node
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
268
269
    def iter_changes(self, basis):
270
        """Iterate over the changes between basis and self.
271
272
        :return: An iterator of tuples: (key, old_value, new_value). Old_value
273
            is None for keys only in self; new_value is None for keys only in
274
            basis.
275
        """
276
        # Overview:
277
        # Read both trees in lexographic, highest-first order.
278
        # Any identical nodes we skip
279
        # Any unique prefixes we output immediately.
280
        # values in a leaf node are treated as single-value nodes in the tree
281
        # which allows them to be not-special-cased. We know to output them
282
        # because their value is a string, not a key(tuple) or node.
283
        #
284
        # corner cases to beware of when considering this function:
285
        # *) common references are at different heights.
286
        #    consider two trees:
287
        #    {'a': LeafNode={'aaa':'foo', 'aab':'bar'}, 'b': LeafNode={'b'}}
288
        #    {'a': InternalNode={'aa':LeafNode={'aaa':'foo', 'aab':'bar'},
289
        #                        'ab':LeafNode={'ab':'bar'}}
290
        #     'b': LeafNode={'b'}}
291
        #    the node with aaa/aab will only be encountered in the second tree
292
        #    after reading the 'a' subtree, but it is encountered in the first
293
        #    tree immediately. Variations on this may have read internal nodes
294
        #    like this.  we want to cut the entire pending subtree when we
295
        #    realise we have a common node.  For this we use a list of keys -
296
        #    the path to a node - and check the entire path is clean as we
297
        #    process each item.
298
        if self._node_key(self._root_node) == self._node_key(basis._root_node):
299
            return
300
        self._ensure_root()
301
        basis._ensure_root()
302
        excluded_keys = set()
303
        self_node = self._root_node
304
        basis_node = basis._root_node
305
        # A heap, each element is prefix, node(tuple/NodeObject/string),
306
        # key_path (a list of tuples, tail-sharing down the tree.)
307
        self_pending = []
308
        basis_pending = []
309
        def process_node(node, path, a_map, pending):
310
            # take a node and expand it
311
            node = a_map._get_node(node)
312
            if type(node) == LeafNode:
313
                path = (node._key, path)
314
                for key, value in node._items.items():
315
                    # For a LeafNode, the key is a serialized_key, rather than
316
                    # a search_key, but the heap is using search_keys
317
                    search_key = node._search_key_func(key)
318
                    heapq.heappush(pending, (search_key, key, value, path))
319
            else:
320
                # type(node) == InternalNode
321
                path = (node._key, path)
322
                for prefix, child in node._items.items():
323
                    heapq.heappush(pending, (prefix, None, child, path))
324
        def process_common_internal_nodes(self_node, basis_node):
325
            self_items = set(self_node._items.items())
326
            basis_items = set(basis_node._items.items())
327
            path = (self_node._key, None)
328
            for prefix, child in self_items - basis_items:
329
                heapq.heappush(self_pending, (prefix, None, child, path))
330
            path = (basis_node._key, None)
331
            for prefix, child in basis_items - self_items:
332
                heapq.heappush(basis_pending, (prefix, None, child, path))
333
        def process_common_leaf_nodes(self_node, basis_node):
334
            self_items = set(self_node._items.items())
335
            basis_items = set(basis_node._items.items())
336
            path = (self_node._key, None)
337
            for key, value in self_items - basis_items:
338
                prefix = self._search_key_func(key)
339
                heapq.heappush(self_pending, (prefix, key, value, path))
340
            path = (basis_node._key, None)
341
            for key, value in basis_items - self_items:
342
                prefix = basis._search_key_func(key)
343
                heapq.heappush(basis_pending, (prefix, key, value, path))
344
        def process_common_prefix_nodes(self_node, self_path,
345
                                        basis_node, basis_path):
346
            # Would it be more efficient if we could request both at the same
347
            # time?
348
            self_node = self._get_node(self_node)
349
            basis_node = basis._get_node(basis_node)
350
            if (type(self_node) == InternalNode
351
                and type(basis_node) == InternalNode):
352
                # Matching internal nodes
353
                process_common_internal_nodes(self_node, basis_node)
354
            elif (type(self_node) == LeafNode
355
                  and type(basis_node) == LeafNode):
356
                process_common_leaf_nodes(self_node, basis_node)
357
            else:
358
                process_node(self_node, self_path, self, self_pending)
359
                process_node(basis_node, basis_path, basis, basis_pending)
360
        process_common_prefix_nodes(self_node, None, basis_node, None)
361
        self_seen = set()
362
        basis_seen = set()
363
        excluded_keys = set()
364
        def check_excluded(key_path):
365
            # Note that this is N^2, it depends on us trimming trees
366
            # aggressively to not become slow.
367
            # A better implementation would probably have a reverse map
368
            # back to the children of a node, and jump straight to it when
369
            # a common node is detected, the proceed to remove the already
370
            # pending children. bzrlib.graph has a searcher module with a
371
            # similar problem.
372
            while key_path is not None:
373
                key, key_path = key_path
374
                if key in excluded_keys:
375
                    return True
376
            return False
377
378
        loop_counter = 0
379
        while self_pending or basis_pending:
380
            loop_counter += 1
381
            if not self_pending:
382
                # self is exhausted: output remainder of basis
383
                for prefix, key, node, path in basis_pending:
384
                    if check_excluded(path):
385
                        continue
386
                    node = basis._get_node(node)
387
                    if key is not None:
388
                        # a value
389
                        yield (key, node, None)
390
                    else:
391
                        # subtree - fastpath the entire thing.
392
                        for key, value in node.iteritems(basis._store):
393
                            yield (key, value, None)
394
                return
395
            elif not basis_pending:
396
                # basis is exhausted: output remainder of self.
397
                for prefix, key, node, path in self_pending:
398
                    if check_excluded(path):
399
                        continue
400
                    node = self._get_node(node)
401
                    if key is not None:
402
                        # a value
403
                        yield (key, None, node)
404
                    else:
405
                        # subtree - fastpath the entire thing.
406
                        for key, value in node.iteritems(self._store):
407
                            yield (key, None, value)
408
                return
409
            else:
410
                # XXX: future optimisation - yield the smaller items
411
                # immediately rather than pushing everything on/off the
412
                # heaps. Applies to both internal nodes and leafnodes.
413
                if self_pending[0][0] < basis_pending[0][0]:
414
                    # expand self
415
                    prefix, key, node, path = heapq.heappop(self_pending)
416
                    if check_excluded(path):
417
                        continue
418
                    if key is not None:
419
                        # a value
420
                        yield (key, None, node)
421
                    else:
422
                        process_node(node, path, self, self_pending)
423
                        continue
424
                elif self_pending[0][0] > basis_pending[0][0]:
425
                    # expand basis
426
                    prefix, key, node, path = heapq.heappop(basis_pending)
427
                    if check_excluded(path):
428
                        continue
429
                    if key is not None:
430
                        # a value
431
                        yield (key, node, None)
432
                    else:
433
                        process_node(node, path, basis, basis_pending)
434
                        continue
435
                else:
436
                    # common prefix: possibly expand both
437
                    if self_pending[0][1] is None:
438
                        # process next self
439
                        read_self = True
440
                    else:
441
                        read_self = False
442
                    if basis_pending[0][1] is None:
443
                        # process next basis
444
                        read_basis = True
445
                    else:
446
                        read_basis = False
447
                    if not read_self and not read_basis:
448
                        # compare a common value
449
                        self_details = heapq.heappop(self_pending)
450
                        basis_details = heapq.heappop(basis_pending)
451
                        if self_details[2] != basis_details[2]:
452
                            yield (self_details[1],
453
                                basis_details[2], self_details[2])
454
                        continue
455
                    # At least one side wasn't a simple value
456
                    if (self._node_key(self_pending[0][2]) ==
457
                        self._node_key(basis_pending[0][2])):
458
                        # Identical pointers, skip (and don't bother adding to
459
                        # excluded, it won't turn up again.
460
                        heapq.heappop(self_pending)
461
                        heapq.heappop(basis_pending)
462
                        continue
463
                    # Now we need to expand this node before we can continue
464
                    if read_self and read_basis:
465
                        # Both sides start with the same prefix, so process
466
                        # them in parallel
467
                        self_prefix, _, self_node, self_path = heapq.heappop(
468
                            self_pending)
469
                        basis_prefix, _, basis_node, basis_path = heapq.heappop(
470
                            basis_pending)
471
                        if self_prefix != basis_prefix:
472
                            raise AssertionError(
473
                                '%r != %r' % (self_prefix, basis_prefix))
474
                        process_common_prefix_nodes(
475
                            self_node, self_path,
476
                            basis_node, basis_path)
477
                        continue
478
                    if read_self:
479
                        prefix, key, node, path = heapq.heappop(self_pending)
480
                        if check_excluded(path):
481
                            continue
482
                        process_node(node, path, self, self_pending)
483
                    if read_basis:
484
                        prefix, key, node, path = heapq.heappop(basis_pending)
485
                        if check_excluded(path):
486
                            continue
487
                        process_node(node, path, basis, basis_pending)
488
        # print loop_counter
489
490
    def iteritems(self, key_filter=None):
491
        """Iterate over the entire CHKMap's contents."""
492
        self._ensure_root()
493
        return self._root_node.iteritems(self._store, key_filter=key_filter)
494
495
    def key(self):
496
        """Return the key for this map."""
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
497
        if type(self._root_node) is StaticTuple:
498
            _check_key(self._root_node)
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
499
            return self._root_node
500
        else:
501
            return self._root_node._key
502
503
    def __len__(self):
504
        self._ensure_root()
505
        return len(self._root_node)
506
507
    def map(self, key, value):
4526.9.5 by Robert Collins
Require that added ids in inventory deltas be new.
508
        """Map a key tuple to value.
509
        
510
        :param key: A key to map.
511
        :param value: The value to assign to key.
512
        """
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
513
        # Need a root object.
514
        self._ensure_root()
515
        prefix, node_details = self._root_node.map(self._store, key, value)
516
        if len(node_details) == 1:
517
            self._root_node = node_details[0][1]
518
        else:
519
            self._root_node = InternalNode(prefix,
520
                                search_key_func=self._search_key_func)
521
            self._root_node.set_maximum_size(node_details[0][1].maximum_size)
522
            self._root_node._key_width = node_details[0][1]._key_width
523
            for split, node in node_details:
524
                self._root_node.add_node(split, node)
525
526
    def _node_key(self, node):
3735.19.1 by Ian Clatworthy
CHKMap cleanups
527
        """Get the key for a node whether it's a tuple or node."""
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
528
        if type(node) is StaticTuple:
529
            _check_key(node)
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
530
            return node
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
531
        elif type(node) is tuple:
532
            raise TypeError('node %r should be a StaticTuple not tuple'
533
                            % (node,))
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
534
        else:
535
            return node._key
536
3735.2.122 by Ian Clatworthy
don't check_remap on every unmap call in CHKMap.apply_delta()
537
    def unmap(self, key, check_remap=True):
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
538
        """remove key from the map."""
539
        self._ensure_root()
540
        if type(self._root_node) is InternalNode:
3735.2.122 by Ian Clatworthy
don't check_remap on every unmap call in CHKMap.apply_delta()
541
            unmapped = self._root_node.unmap(self._store, key,
542
                check_remap=check_remap)
543
        else:
544
            unmapped = self._root_node.unmap(self._store, key)
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
545
        self._root_node = unmapped
546
3735.2.122 by Ian Clatworthy
don't check_remap on every unmap call in CHKMap.apply_delta()
547
    def _check_remap(self):
548
        """Check if nodes can be collapsed."""
549
        self._ensure_root()
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
550
        if type(self._root_node) is InternalNode:
3735.2.122 by Ian Clatworthy
don't check_remap on every unmap call in CHKMap.apply_delta()
551
            self._root_node._check_remap(self._store)
552
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
553
    def _save(self):
554
        """Save the map completely.
555
556
        :return: The key of the root node.
557
        """
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
558
        if type(self._root_node) is StaticTuple:
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
559
            # Already saved.
560
            return self._root_node
561
        keys = list(self._root_node.serialise(self._store))
562
        return keys[-1]
563
564
565
class Node(object):
566
    """Base class defining the protocol for CHK Map nodes.
567
568
    :ivar _raw_size: The total size of the serialized key:value data, before
569
        adding the header bytes, and without prefix compression.
570
    """
571
4759.1.2 by John Arbash Meinel
Change CHKMap to use __slots__
572
    __slots__ = ('_key', '_len', '_maximum_size', '_key_width',
573
                 '_raw_size', '_items', '_search_prefix', '_search_key_func'
574
                )
575
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
576
    def __init__(self, key_width=1):
577
        """Create a node.
578
579
        :param key_width: The width of keys for this node.
580
        """
581
        self._key = None
582
        # Current number of elements
583
        self._len = 0
584
        self._maximum_size = 0
3735.19.1 by Ian Clatworthy
CHKMap cleanups
585
        self._key_width = key_width
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
586
        # current size in bytes
587
        self._raw_size = 0
588
        # The pointers/values this node has - meaning defined by child classes.
589
        self._items = {}
590
        # The common search prefix
591
        self._search_prefix = None
592
593
    def __repr__(self):
594
        items_str = str(sorted(self._items))
595
        if len(items_str) > 20:
3735.2.154 by Ian Clatworthy
fix chk_map Node %r formatting
596
            items_str = items_str[:16] + '...]'
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
597
        return '%s(key:%s len:%s size:%s max:%s prefix:%s items:%s)' % (
598
            self.__class__.__name__, self._key, self._len, self._raw_size,
599
            self._maximum_size, self._search_prefix, items_str)
600
601
    def key(self):
602
        return self._key
603
604
    def __len__(self):
605
        return self._len
606
607
    @property
608
    def maximum_size(self):
609
        """What is the upper limit for adding references to a node."""
610
        return self._maximum_size
611
612
    def set_maximum_size(self, new_size):
613
        """Set the size threshold for nodes.
614
615
        :param new_size: The size at which no data is added to a node. 0 for
616
            unlimited.
617
        """
618
        self._maximum_size = new_size
619
620
    @classmethod
621
    def common_prefix(cls, prefix, key):
622
        """Given 2 strings, return the longest prefix common to both.
623
624
        :param prefix: This has been the common prefix for other keys, so it is
625
            more likely to be the common prefix in this case as well.
626
        :param key: Another string to compare to
627
        """
628
        if key.startswith(prefix):
629
            return prefix
4358.1.1 by Jelmer Vernooij
Support empty keys when looking for common prefixes in CHKMap.
630
        pos = -1
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
631
        # Is there a better way to do this?
632
        for pos, (left, right) in enumerate(zip(prefix, key)):
633
            if left != right:
634
                pos -= 1
635
                break
636
        common = prefix[:pos+1]
637
        return common
638
639
    @classmethod
640
    def common_prefix_for_keys(cls, keys):
641
        """Given a list of keys, find their common prefix.
642
643
        :param keys: An iterable of strings.
644
        :return: The longest common prefix of all keys.
645
        """
646
        common_prefix = None
647
        for key in keys:
648
            if common_prefix is None:
649
                common_prefix = key
650
                continue
651
            common_prefix = cls.common_prefix(common_prefix, key)
652
            if not common_prefix:
653
                # if common_prefix is the empty string, then we know it won't
654
                # change further
655
                return ''
656
        return common_prefix
657
658
659
# Singleton indicating we have not computed _search_prefix yet
660
_unknown = object()
661
662
class LeafNode(Node):
663
    """A node containing actual key:value pairs.
664
665
    :ivar _items: A dict of key->value items. The key is in tuple form.
666
    :ivar _size: The number of bytes that would be used by serializing all of
667
        the key/value pairs.
668
    """
669
4759.1.2 by John Arbash Meinel
Change CHKMap to use __slots__
670
    __slots__ = ('_common_serialised_prefix', '_serialise_key')
671
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
672
    def __init__(self, search_key_func=None):
673
        Node.__init__(self)
674
        # All of the keys in this leaf node share this common prefix
675
        self._common_serialised_prefix = None
676
        self._serialise_key = '\x00'.join
677
        if search_key_func is None:
678
            self._search_key_func = _search_key_plain
679
        else:
680
            self._search_key_func = search_key_func
681
682
    def __repr__(self):
3735.2.154 by Ian Clatworthy
fix chk_map Node %r formatting
683
        items_str = str(sorted(self._items))
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
684
        if len(items_str) > 20:
3735.2.154 by Ian Clatworthy
fix chk_map Node %r formatting
685
            items_str = items_str[:16] + '...]'
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
686
        return \
687
            '%s(key:%s len:%s size:%s max:%s prefix:%s keywidth:%s items:%s)' \
688
            % (self.__class__.__name__, self._key, self._len, self._raw_size,
689
            self._maximum_size, self._search_prefix, self._key_width, items_str)
690
691
    def _current_size(self):
692
        """Answer the current serialised size of this node.
693
694
        This differs from self._raw_size in that it includes the bytes used for
695
        the header.
696
        """
697
        if self._common_serialised_prefix is None:
698
            bytes_for_items = 0
699
            prefix_len = 0
700
        else:
701
            # We will store a single string with the common prefix
702
            # And then that common prefix will not be stored in any of the
703
            # entry lines
704
            prefix_len = len(self._common_serialised_prefix)
705
            bytes_for_items = (self._raw_size - (prefix_len * self._len))
706
        return (9 # 'chkleaf:\n'
707
            + len(str(self._maximum_size)) + 1
708
            + len(str(self._key_width)) + 1
709
            + len(str(self._len)) + 1
710
            + prefix_len + 1
711
            + bytes_for_items)
712
713
    @classmethod
714
    def deserialise(klass, bytes, key, search_key_func=None):
715
        """Deserialise bytes, with key key, into a LeafNode.
716
717
        :param bytes: The bytes of the node.
718
        :param key: The key that the serialised node has.
719
        """
720
        return _deserialise_leaf_node(bytes, key,
721
                                      search_key_func=search_key_func)
722
723
    def iteritems(self, store, key_filter=None):
724
        """Iterate over items in the node.
725
726
        :param key_filter: A filter to apply to the node. It should be a
727
            list/set/dict or similar repeatedly iterable container.
728
        """
729
        if key_filter is not None:
730
            # Adjust the filter - short elements go to a prefix filter. All
731
            # other items are looked up directly.
732
            # XXX: perhaps defaultdict? Profiling<rinse and repeat>
733
            filters = {}
734
            for key in key_filter:
735
                if len(key) == self._key_width:
736
                    # This filter is meant to match exactly one key, yield it
737
                    # if we have it.
738
                    try:
739
                        yield key, self._items[key]
740
                    except KeyError:
741
                        # This key is not present in this map, continue
742
                        pass
743
                else:
744
                    # Short items, we need to match based on a prefix
745
                    length_filter = filters.setdefault(len(key), set())
746
                    length_filter.add(key)
747
            if filters:
748
                filters = filters.items()
749
                for item in self._items.iteritems():
750
                    for length, length_filter in filters:
751
                        if item[0][:length] in length_filter:
752
                            yield item
753
                            break
754
        else:
755
            for item in self._items.iteritems():
756
                yield item
757
758
    def _key_value_len(self, key, value):
759
        # TODO: Should probably be done without actually joining the key, but
760
        #       then that can be done via the C extension
761
        return (len(self._serialise_key(key)) + 1
762
                + len(str(value.count('\n'))) + 1
763
                + len(value) + 1)
764
765
    def _search_key(self, key):
766
        return self._search_key_func(key)
767
768
    def _map_no_split(self, key, value):
769
        """Map a key to a value.
770
771
        This assumes either the key does not already exist, or you have already
772
        removed its size and length from self.
773
774
        :return: True if adding this node should cause us to split.
775
        """
776
        self._items[key] = value
777
        self._raw_size += self._key_value_len(key, value)
778
        self._len += 1
779
        serialised_key = self._serialise_key(key)
780
        if self._common_serialised_prefix is None:
781
            self._common_serialised_prefix = serialised_key
782
        else:
783
            self._common_serialised_prefix = self.common_prefix(
784
                self._common_serialised_prefix, serialised_key)
785
        search_key = self._search_key(key)
786
        if self._search_prefix is _unknown:
787
            self._compute_search_prefix()
788
        if self._search_prefix is None:
789
            self._search_prefix = search_key
790
        else:
791
            self._search_prefix = self.common_prefix(
792
                self._search_prefix, search_key)
793
        if (self._len > 1
794
            and self._maximum_size
795
            and self._current_size() > self._maximum_size):
796
            # Check to see if all of the search_keys for this node are
797
            # identical. We allow the node to grow under that circumstance
798
            # (we could track this as common state, but it is infrequent)
799
            if (search_key != self._search_prefix
800
                or not self._are_search_keys_identical()):
801
                return True
802
        return False
803
804
    def _split(self, store):
805
        """We have overflowed.
806
807
        Split this node into multiple LeafNodes, return it up the stack so that
808
        the next layer creates a new InternalNode and references the new nodes.
809
810
        :return: (common_serialised_prefix, [(node_serialised_prefix, node)])
811
        """
812
        if self._search_prefix is _unknown:
813
            raise AssertionError('Search prefix must be known')
814
        common_prefix = self._search_prefix
815
        split_at = len(common_prefix) + 1
816
        result = {}
817
        for key, value in self._items.iteritems():
818
            search_key = self._search_key(key)
819
            prefix = search_key[:split_at]
820
            # TODO: Generally only 1 key can be exactly the right length,
821
            #       which means we can only have 1 key in the node pointed
822
            #       at by the 'prefix\0' key. We might want to consider
823
            #       folding it into the containing InternalNode rather than
824
            #       having a fixed length-1 node.
825
            #       Note this is probably not true for hash keys, as they
826
            #       may get a '\00' node anywhere, but won't have keys of
827
            #       different lengths.
828
            if len(prefix) < split_at:
829
                prefix += '\x00'*(split_at - len(prefix))
830
            if prefix not in result:
831
                node = LeafNode(search_key_func=self._search_key_func)
832
                node.set_maximum_size(self._maximum_size)
833
                node._key_width = self._key_width
834
                result[prefix] = node
835
            else:
836
                node = result[prefix]
4413.5.4 by John Arbash Meinel
Change CHKMap.from_dict to create a LeafNode and split it.
837
            sub_prefix, node_details = node.map(store, key, value)
838
            if len(node_details) > 1:
839
                if prefix != sub_prefix:
840
                    # This node has been split and is now found via a different
841
                    # path
842
                    result.pop(prefix)
843
                new_node = InternalNode(sub_prefix,
844
                    search_key_func=self._search_key_func)
845
                new_node.set_maximum_size(self._maximum_size)
846
                new_node._key_width = self._key_width
847
                for split, node in node_details:
848
                    new_node.add_node(split, node)
849
                result[prefix] = new_node
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
850
        return common_prefix, result.items()
851
852
    def map(self, store, key, value):
853
        """Map key to value."""
854
        if key in self._items:
855
            self._raw_size -= self._key_value_len(key, self._items[key])
856
            self._len -= 1
857
        self._key = None
858
        if self._map_no_split(key, value):
859
            return self._split(store)
860
        else:
861
            if self._search_prefix is _unknown:
862
                raise AssertionError('%r must be known' % self._search_prefix)
863
            return self._search_prefix, [("", self)]
864
865
    def serialise(self, store):
866
        """Serialise the LeafNode to store.
867
868
        :param store: A VersionedFiles honouring the CHK extensions.
869
        :return: An iterable of the keys inserted by this operation.
870
        """
871
        lines = ["chkleaf:\n"]
872
        lines.append("%d\n" % self._maximum_size)
873
        lines.append("%d\n" % self._key_width)
874
        lines.append("%d\n" % self._len)
875
        if self._common_serialised_prefix is None:
876
            lines.append('\n')
877
            if len(self._items) != 0:
878
                raise AssertionError('If _common_serialised_prefix is None'
879
                    ' we should have no items')
880
        else:
881
            lines.append('%s\n' % (self._common_serialised_prefix,))
882
            prefix_len = len(self._common_serialised_prefix)
883
        for key, value in sorted(self._items.items()):
884
            # Always add a final newline
885
            value_lines = osutils.chunks_to_lines([value + '\n'])
886
            serialized = "%s\x00%s\n" % (self._serialise_key(key),
887
                                         len(value_lines))
888
            if not serialized.startswith(self._common_serialised_prefix):
889
                raise AssertionError('We thought the common prefix was %r'
890
                    ' but entry %r does not have it in common'
891
                    % (self._common_serialised_prefix, serialized))
892
            lines.append(serialized[prefix_len:])
893
            lines.extend(value_lines)
894
        sha1, _, _ = store.add_lines((None,), (), lines)
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
895
        self._key = StaticTuple("sha1:" + sha1,).intern()
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
896
        bytes = ''.join(lines)
897
        if len(bytes) != self._current_size():
898
            raise AssertionError('Invalid _current_size')
899
        _page_cache.add(self._key, bytes)
900
        return [self._key]
901
902
    def refs(self):
903
        """Return the references to other CHK's held by this node."""
904
        return []
905
906
    def _compute_search_prefix(self):
907
        """Determine the common search prefix for all keys in this node.
908
909
        :return: A bytestring of the longest search key prefix that is
910
            unique within this node.
911
        """
912
        search_keys = [self._search_key_func(key) for key in self._items]
913
        self._search_prefix = self.common_prefix_for_keys(search_keys)
914
        return self._search_prefix
915
916
    def _are_search_keys_identical(self):
917
        """Check to see if the search keys for all entries are the same.
918
919
        When using a hash as the search_key it is possible for non-identical
920
        keys to collide. If that happens enough, we may try overflow a
921
        LeafNode, but as all are collisions, we must not split.
922
        """
923
        common_search_key = None
924
        for key in self._items:
925
            search_key = self._search_key(key)
926
            if common_search_key is None:
927
                common_search_key = search_key
928
            elif search_key != common_search_key:
929
                return False
930
        return True
931
932
    def _compute_serialised_prefix(self):
933
        """Determine the common prefix for serialised keys in this node.
934
935
        :return: A bytestring of the longest serialised key prefix that is
936
            unique within this node.
937
        """
938
        serialised_keys = [self._serialise_key(key) for key in self._items]
939
        self._common_serialised_prefix = self.common_prefix_for_keys(
940
            serialised_keys)
3735.19.1 by Ian Clatworthy
CHKMap cleanups
941
        return self._common_serialised_prefix
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
942
943
    def unmap(self, store, key):
944
        """Unmap key from the node."""
945
        try:
946
            self._raw_size -= self._key_value_len(key, self._items[key])
947
        except KeyError:
948
            trace.mutter("key %s not found in %r", key, self._items)
949
            raise
950
        self._len -= 1
951
        del self._items[key]
952
        self._key = None
953
        # Recompute from scratch
954
        self._compute_search_prefix()
955
        self._compute_serialised_prefix()
956
        return self
957
958
959
class InternalNode(Node):
960
    """A node that contains references to other nodes.
961
962
    An InternalNode is responsible for mapping search key prefixes to child
963
    nodes.
964
965
    :ivar _items: serialised_key => node dictionary. node may be a tuple,
966
        LeafNode or InternalNode.
967
    """
968
4759.1.2 by John Arbash Meinel
Change CHKMap to use __slots__
969
    __slots__ = ('_node_width',)
970
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
971
    def __init__(self, prefix='', search_key_func=None):
972
        Node.__init__(self)
973
        # The size of an internalnode with default values and no children.
974
        # How many octets key prefixes within this node are.
975
        self._node_width = 0
976
        self._search_prefix = prefix
977
        if search_key_func is None:
978
            self._search_key_func = _search_key_plain
979
        else:
980
            self._search_key_func = search_key_func
981
982
    def add_node(self, prefix, node):
983
        """Add a child node with prefix prefix, and node node.
984
985
        :param prefix: The search key prefix for node.
986
        :param node: The node being added.
987
        """
3735.2.126 by Ian Clatworthy
replace asserts in chk_map.py with AssertionErrors
988
        if self._search_prefix is None:
989
            raise AssertionError("_search_prefix should not be None")
990
        if not prefix.startswith(self._search_prefix):
991
            raise AssertionError("prefixes mismatch: %s must start with %s"
992
                % (prefix,self._search_prefix))
993
        if len(prefix) != len(self._search_prefix) + 1:
994
            raise AssertionError("prefix wrong length: len(%s) is not %d" %
995
                (prefix, len(self._search_prefix) + 1))
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
996
        self._len += len(node)
997
        if not len(self._items):
998
            self._node_width = len(prefix)
3735.2.126 by Ian Clatworthy
replace asserts in chk_map.py with AssertionErrors
999
        if self._node_width != len(self._search_prefix) + 1:
1000
            raise AssertionError("node width mismatch: %d is not %d" %
1001
                (self._node_width, len(self._search_prefix) + 1))
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1002
        self._items[prefix] = node
1003
        self._key = None
1004
1005
    def _current_size(self):
1006
        """Answer the current serialised size of this node."""
1007
        return (self._raw_size + len(str(self._len)) + len(str(self._key_width)) +
1008
            len(str(self._maximum_size)))
1009
1010
    @classmethod
1011
    def deserialise(klass, bytes, key, search_key_func=None):
1012
        """Deserialise bytes to an InternalNode, with key key.
1013
1014
        :param bytes: The bytes of the node.
1015
        :param key: The key that the serialised node has.
1016
        :return: An InternalNode instance.
1017
        """
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
1018
        if type(key) is not StaticTuple:
1019
            import pdb; pdb.set_trace()
1020
        key = StaticTuple.from_sequence(key).intern()
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1021
        return _deserialise_internal_node(bytes, key,
1022
                                          search_key_func=search_key_func)
1023
1024
    def iteritems(self, store, key_filter=None):
1025
        for node, node_filter in self._iter_nodes(store, key_filter=key_filter):
1026
            for item in node.iteritems(store, key_filter=node_filter):
1027
                yield item
1028
1029
    def _iter_nodes(self, store, key_filter=None, batch_size=None):
1030
        """Iterate over node objects which match key_filter.
1031
1032
        :param store: A store to use for accessing content.
1033
        :param key_filter: A key filter to filter nodes. Only nodes that might
1034
            contain a key in key_filter will be returned.
1035
        :param batch_size: If not None, then we will return the nodes that had
1036
            to be read using get_record_stream in batches, rather than reading
1037
            them all at once.
1038
        :return: An iterable of nodes. This function does not have to be fully
1039
            consumed.  (There will be no pending I/O when items are being returned.)
1040
        """
1041
        # Map from chk key ('sha1:...',) to (prefix, key_filter)
1042
        # prefix is the key in self._items to use, key_filter is the key_filter
1043
        # entries that would match this node
1044
        keys = {}
4413.4.1 by John Arbash Meinel
Add a shortcut for the case when we are searching for a single full-width key.
1045
        shortcut = False
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1046
        if key_filter is None:
4413.4.1 by John Arbash Meinel
Add a shortcut for the case when we are searching for a single full-width key.
1047
            # yielding all nodes, yield whatever we have, and queue up a read
1048
            # for whatever we are missing
1049
            shortcut = True
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1050
            for prefix, node in self._items.iteritems():
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
1051
                if node.__class__ is StaticTuple:
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1052
                    keys[node] = (prefix, None)
1053
                else:
1054
                    yield node, None
4413.4.1 by John Arbash Meinel
Add a shortcut for the case when we are searching for a single full-width key.
1055
        elif len(key_filter) == 1:
4413.4.2 by John Arbash Meinel
Rewrite the shortcuts.
1056
            # Technically, this path could also be handled by the first check
1057
            # in 'self._node_width' in length_filters. However, we can handle
1058
            # this case without spending any time building up the
1059
            # prefix_to_keys, etc state.
1060
1061
            # This is a bit ugly, but TIMEIT showed it to be by far the fastest
1062
            # 0.626us   list(key_filter)[0]
1063
            #       is a func() for list(), 2 mallocs, and a getitem
1064
            # 0.489us   [k for k in key_filter][0]
1065
            #       still has the mallocs, avoids the func() call
1066
            # 0.350us   iter(key_filter).next()
1067
            #       has a func() call, and mallocs an iterator
1068
            # 0.125us   for key in key_filter: pass
1069
            #       no func() overhead, might malloc an iterator
1070
            # 0.105us   for key in key_filter: break
1071
            #       no func() overhead, might malloc an iterator, probably
1072
            #       avoids checking an 'else' clause as part of the for
1073
            for key in key_filter:
1074
                break
1075
            search_prefix = self._search_prefix_filter(key)
1076
            if len(search_prefix) == self._node_width:
4413.4.1 by John Arbash Meinel
Add a shortcut for the case when we are searching for a single full-width key.
1077
                # This item will match exactly, so just do a dict lookup, and
1078
                # see what we can return
1079
                shortcut = True
1080
                try:
4413.4.2 by John Arbash Meinel
Rewrite the shortcuts.
1081
                    node = self._items[search_prefix]
4413.4.1 by John Arbash Meinel
Add a shortcut for the case when we are searching for a single full-width key.
1082
                except KeyError:
1083
                    # A given key can only match 1 child node, if it isn't
1084
                    # there, then we can just return nothing
1085
                    return
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
1086
                if node.__class__ is StaticTuple:
4413.4.2 by John Arbash Meinel
Rewrite the shortcuts.
1087
                    keys[node] = (search_prefix, [key])
4413.4.1 by John Arbash Meinel
Add a shortcut for the case when we are searching for a single full-width key.
1088
                else:
4413.4.2 by John Arbash Meinel
Rewrite the shortcuts.
1089
                    # This is loaded, and the only thing that can match,
1090
                    # return
1091
                    yield node, [key]
1092
                    return
4413.4.1 by John Arbash Meinel
Add a shortcut for the case when we are searching for a single full-width key.
1093
        if not shortcut:
4413.4.2 by John Arbash Meinel
Rewrite the shortcuts.
1094
            # First, convert all keys into a list of search prefixes
1095
            # Aggregate common prefixes, and track the keys they come from
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1096
            prefix_to_keys = {}
1097
            length_filters = {}
1098
            for key in key_filter:
4413.4.2 by John Arbash Meinel
Rewrite the shortcuts.
1099
                search_prefix = self._search_prefix_filter(key)
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1100
                length_filter = length_filters.setdefault(
4413.4.2 by John Arbash Meinel
Rewrite the shortcuts.
1101
                                    len(search_prefix), set())
1102
                length_filter.add(search_prefix)
1103
                prefix_to_keys.setdefault(search_prefix, []).append(key)
1104
1105
            if (self._node_width in length_filters
1106
                and len(length_filters) == 1):
1107
                # all of the search prefixes match exactly _node_width. This
1108
                # means that everything is an exact match, and we can do a
1109
                # lookup into self._items, rather than iterating over the items
1110
                # dict.
1111
                search_prefixes = length_filters[self._node_width]
1112
                for search_prefix in search_prefixes:
1113
                    try:
1114
                        node = self._items[search_prefix]
1115
                    except KeyError:
1116
                        # We can ignore this one
1117
                        continue
1118
                    node_key_filter = prefix_to_keys[search_prefix]
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
1119
                    if node.__class__ is StaticTuple:
4413.4.2 by John Arbash Meinel
Rewrite the shortcuts.
1120
                        keys[node] = (search_prefix, node_key_filter)
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1121
                    else:
1122
                        yield node, node_key_filter
4413.4.2 by John Arbash Meinel
Rewrite the shortcuts.
1123
            else:
1124
                # The slow way. We walk every item in self._items, and check to
1125
                # see if there are any matches
1126
                length_filters = length_filters.items()
1127
                for prefix, node in self._items.iteritems():
1128
                    node_key_filter = []
1129
                    for length, length_filter in length_filters:
1130
                        sub_prefix = prefix[:length]
1131
                        if sub_prefix in length_filter:
1132
                            node_key_filter.extend(prefix_to_keys[sub_prefix])
1133
                    if node_key_filter: # this key matched something, yield it
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
1134
                        if node.__class__ is StaticTuple:
4413.4.2 by John Arbash Meinel
Rewrite the shortcuts.
1135
                            keys[node] = (prefix, node_key_filter)
1136
                        else:
1137
                            yield node, node_key_filter
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1138
        if keys:
1139
            # Look in the page cache for some more bytes
1140
            found_keys = set()
1141
            for key in keys:
1142
                try:
1143
                    bytes = _page_cache[key]
1144
                except KeyError:
1145
                    continue
1146
                else:
1147
                    node = _deserialise(bytes, key,
1148
                        search_key_func=self._search_key_func)
1149
                    prefix, node_key_filter = keys[key]
1150
                    self._items[prefix] = node
1151
                    found_keys.add(key)
1152
                    yield node, node_key_filter
1153
            for key in found_keys:
1154
                del keys[key]
1155
        if keys:
1156
            # demand load some pages.
1157
            if batch_size is None:
1158
                # Read all the keys in
1159
                batch_size = len(keys)
1160
            key_order = list(keys)
1161
            for batch_start in range(0, len(key_order), batch_size):
1162
                batch = key_order[batch_start:batch_start + batch_size]
1163
                # We have to fully consume the stream so there is no pending
1164
                # I/O, so we buffer the nodes for now.
1165
                stream = store.get_record_stream(batch, 'unordered', True)
1166
                node_and_filters = []
1167
                for record in stream:
1168
                    bytes = record.get_bytes_as('fulltext')
1169
                    node = _deserialise(bytes, record.key,
1170
                        search_key_func=self._search_key_func)
1171
                    prefix, node_key_filter = keys[record.key]
1172
                    node_and_filters.append((node, node_key_filter))
1173
                    self._items[prefix] = node
1174
                    _page_cache.add(record.key, bytes)
1175
                for info in node_and_filters:
1176
                    yield info
1177
1178
    def map(self, store, key, value):
1179
        """Map key to value."""
1180
        if not len(self._items):
3735.2.122 by Ian Clatworthy
don't check_remap on every unmap call in CHKMap.apply_delta()
1181
            raise AssertionError("can't map in an empty InternalNode.")
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1182
        search_key = self._search_key(key)
3735.2.126 by Ian Clatworthy
replace asserts in chk_map.py with AssertionErrors
1183
        if self._node_width != len(self._search_prefix) + 1:
1184
            raise AssertionError("node width mismatch: %d is not %d" %
1185
                (self._node_width, len(self._search_prefix) + 1))
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1186
        if not search_key.startswith(self._search_prefix):
1187
            # This key doesn't fit in this index, so we need to split at the
1188
            # point where it would fit, insert self into that internal node,
1189
            # and then map this key into that node.
1190
            new_prefix = self.common_prefix(self._search_prefix,
1191
                                            search_key)
1192
            new_parent = InternalNode(new_prefix,
1193
                search_key_func=self._search_key_func)
1194
            new_parent.set_maximum_size(self._maximum_size)
1195
            new_parent._key_width = self._key_width
1196
            new_parent.add_node(self._search_prefix[:len(new_prefix)+1],
1197
                                self)
1198
            return new_parent.map(store, key, value)
1199
        children = [node for node, _
1200
                          in self._iter_nodes(store, key_filter=[key])]
1201
        if children:
1202
            child = children[0]
1203
        else:
1204
            # new child needed:
1205
            child = self._new_child(search_key, LeafNode)
1206
        old_len = len(child)
1207
        if type(child) is LeafNode:
1208
            old_size = child._current_size()
1209
        else:
1210
            old_size = None
1211
        prefix, node_details = child.map(store, key, value)
1212
        if len(node_details) == 1:
1213
            # child may have shrunk, or might be a new node
1214
            child = node_details[0][1]
1215
            self._len = self._len - old_len + len(child)
1216
            self._items[search_key] = child
1217
            self._key = None
1218
            new_node = self
1219
            if type(child) is LeafNode:
3735.2.123 by Ian Clatworthy
only check for remap if changes are interesting in size
1220
                if old_size is None:
1221
                    # The old node was an InternalNode which means it has now
1222
                    # collapsed, so we need to check if it will chain to a
1223
                    # collapse at this level.
1224
                    trace.mutter("checking remap as InternalNode -> LeafNode")
1225
                    new_node = self._check_remap(store)
1226
                else:
1227
                    # If the LeafNode has shrunk in size, we may want to run
1228
                    # a remap check. Checking for a remap is expensive though
1229
                    # and the frequency of a successful remap is very low.
1230
                    # Shrinkage by small amounts is common, so we only do the
1231
                    # remap check if the new_size is low or the shrinkage
1232
                    # amount is over a configurable limit.
1233
                    new_size = child._current_size()
1234
                    shrinkage = old_size - new_size
1235
                    if (shrinkage > 0 and new_size < _INTERESTING_NEW_SIZE
1236
                        or shrinkage > _INTERESTING_SHRINKAGE_LIMIT):
1237
                        trace.mutter(
1238
                            "checking remap as size shrunk by %d to be %d",
1239
                            shrinkage, new_size)
1240
                        new_node = self._check_remap(store)
3735.2.126 by Ian Clatworthy
replace asserts in chk_map.py with AssertionErrors
1241
            if new_node._search_prefix is None:
1242
                raise AssertionError("_search_prefix should not be None")
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1243
            return new_node._search_prefix, [('', new_node)]
1244
        # child has overflown - create a new intermediate node.
1245
        # XXX: This is where we might want to try and expand our depth
1246
        # to refer to more bytes of every child (which would give us
1247
        # multiple pointers to child nodes, but less intermediate nodes)
1248
        child = self._new_child(search_key, InternalNode)
1249
        child._search_prefix = prefix
1250
        for split, node in node_details:
1251
            child.add_node(split, node)
1252
        self._len = self._len - old_len + len(child)
1253
        self._key = None
1254
        return self._search_prefix, [("", self)]
1255
1256
    def _new_child(self, search_key, klass):
1257
        """Create a new child node of type klass."""
1258
        child = klass()
1259
        child.set_maximum_size(self._maximum_size)
1260
        child._key_width = self._key_width
1261
        child._search_key_func = self._search_key_func
1262
        self._items[search_key] = child
1263
        return child
1264
1265
    def serialise(self, store):
1266
        """Serialise the node to store.
1267
1268
        :param store: A VersionedFiles honouring the CHK extensions.
1269
        :return: An iterable of the keys inserted by this operation.
1270
        """
1271
        for node in self._items.itervalues():
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
1272
            if type(node) is StaticTuple:
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1273
                # Never deserialised.
1274
                continue
1275
            if node._key is not None:
1276
                # Never altered
1277
                continue
1278
            for key in node.serialise(store):
1279
                yield key
1280
        lines = ["chknode:\n"]
1281
        lines.append("%d\n" % self._maximum_size)
1282
        lines.append("%d\n" % self._key_width)
1283
        lines.append("%d\n" % self._len)
3735.2.126 by Ian Clatworthy
replace asserts in chk_map.py with AssertionErrors
1284
        if self._search_prefix is None:
1285
            raise AssertionError("_search_prefix should not be None")
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1286
        lines.append('%s\n' % (self._search_prefix,))
1287
        prefix_len = len(self._search_prefix)
1288
        for prefix, node in sorted(self._items.items()):
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
1289
            if type(node) is StaticTuple:
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1290
                key = node[0]
1291
            else:
1292
                key = node._key[0]
1293
            serialised = "%s\x00%s\n" % (prefix, key)
3735.2.126 by Ian Clatworthy
replace asserts in chk_map.py with AssertionErrors
1294
            if not serialised.startswith(self._search_prefix):
1295
                raise AssertionError("prefixes mismatch: %s must start with %s"
1296
                    % (serialised, self._search_prefix))
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1297
            lines.append(serialised[prefix_len:])
1298
        sha1, _, _ = store.add_lines((None,), (), lines)
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
1299
        self._key = StaticTuple("sha1:" + sha1,).intern()
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1300
        _page_cache.add(self._key, ''.join(lines))
1301
        yield self._key
1302
1303
    def _search_key(self, key):
1304
        """Return the serialised key for key in this node."""
1305
        # search keys are fixed width. All will be self._node_width wide, so we
1306
        # pad as necessary.
1307
        return (self._search_key_func(key) + '\x00'*self._node_width)[:self._node_width]
1308
1309
    def _search_prefix_filter(self, key):
1310
        """Serialise key for use as a prefix filter in iteritems."""
1311
        return self._search_key_func(key)[:self._node_width]
1312
1313
    def _split(self, offset):
1314
        """Split this node into smaller nodes starting at offset.
1315
1316
        :param offset: The offset to start the new child nodes at.
1317
        :return: An iterable of (prefix, node) tuples. prefix is a byte
1318
            prefix for reaching node.
1319
        """
1320
        if offset >= self._node_width:
1321
            for node in self._items.values():
1322
                for result in node._split(offset):
1323
                    yield result
1324
            return
1325
        for key, node in self._items.items():
1326
            pass
1327
1328
    def refs(self):
1329
        """Return the references to other CHK's held by this node."""
1330
        if self._key is None:
1331
            raise AssertionError("unserialised nodes have no refs.")
1332
        refs = []
1333
        for value in self._items.itervalues():
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
1334
            if type(value) is StaticTuple:
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1335
                refs.append(value)
1336
            else:
1337
                refs.append(value.key())
1338
        return refs
1339
1340
    def _compute_search_prefix(self, extra_key=None):
1341
        """Return the unique key prefix for this node.
1342
1343
        :return: A bytestring of the longest search key prefix that is
1344
            unique within this node.
1345
        """
1346
        self._search_prefix = self.common_prefix_for_keys(self._items)
1347
        return self._search_prefix
1348
3735.2.122 by Ian Clatworthy
don't check_remap on every unmap call in CHKMap.apply_delta()
1349
    def unmap(self, store, key, check_remap=True):
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1350
        """Remove key from this node and it's children."""
1351
        if not len(self._items):
3735.2.126 by Ian Clatworthy
replace asserts in chk_map.py with AssertionErrors
1352
            raise AssertionError("can't unmap in an empty InternalNode.")
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1353
        children = [node for node, _
1354
                          in self._iter_nodes(store, key_filter=[key])]
1355
        if children:
1356
            child = children[0]
1357
        else:
1358
            raise KeyError(key)
1359
        self._len -= 1
1360
        unmapped = child.unmap(store, key)
1361
        self._key = None
1362
        search_key = self._search_key(key)
1363
        if len(unmapped) == 0:
1364
            # All child nodes are gone, remove the child:
1365
            del self._items[search_key]
1366
            unmapped = None
1367
        else:
1368
            # Stash the returned node
1369
            self._items[search_key] = unmapped
1370
        if len(self._items) == 1:
1371
            # this node is no longer needed:
1372
            return self._items.values()[0]
1373
        if type(unmapped) is InternalNode:
1374
            return self
3735.2.122 by Ian Clatworthy
don't check_remap on every unmap call in CHKMap.apply_delta()
1375
        if check_remap:
1376
            return self._check_remap(store)
1377
        else:
1378
            return self
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1379
1380
    def _check_remap(self, store):
1381
        """Check if all keys contained by children fit in a single LeafNode.
1382
1383
        :param store: A store to use for reading more nodes
1384
        :return: Either self, or a new LeafNode which should replace self.
1385
        """
1386
        # Logic for how we determine when we need to rebuild
1387
        # 1) Implicitly unmap() is removing a key which means that the child
1388
        #    nodes are going to be shrinking by some extent.
1389
        # 2) If all children are LeafNodes, it is possible that they could be
1390
        #    combined into a single LeafNode, which can then completely replace
1391
        #    this internal node with a single LeafNode
1392
        # 3) If *one* child is an InternalNode, we assume it has already done
1393
        #    all the work to determine that its children cannot collapse, and
1394
        #    we can then assume that those nodes *plus* the current nodes don't
1395
        #    have a chance of collapsing either.
1396
        #    So a very cheap check is to just say if 'unmapped' is an
1397
        #    InternalNode, we don't have to check further.
1398
1399
        # TODO: Another alternative is to check the total size of all known
1400
        #       LeafNodes. If there is some formula we can use to determine the
1401
        #       final size without actually having to read in any more
1402
        #       children, it would be nice to have. However, we have to be
1403
        #       careful with stuff like nodes that pull out the common prefix
1404
        #       of each key, as adding a new key can change the common prefix
1405
        #       and cause size changes greater than the length of one key.
1406
        #       So for now, we just add everything to a new Leaf until it
1407
        #       splits, as we know that will give the right answer
1408
        new_leaf = LeafNode(search_key_func=self._search_key_func)
1409
        new_leaf.set_maximum_size(self._maximum_size)
1410
        new_leaf._key_width = self._key_width
1411
        # A batch_size of 16 was chosen because:
1412
        #   a) In testing, a 4k page held 14 times. So if we have more than 16
1413
        #      leaf nodes we are unlikely to hold them in a single new leaf
1414
        #      node. This still allows for 1 round trip
1415
        #   b) With 16-way fan out, we can still do a single round trip
1416
        #   c) With 255-way fan out, we don't want to read all 255 and destroy
1417
        #      the page cache, just to determine that we really don't need it.
1418
        for node, _ in self._iter_nodes(store, batch_size=16):
1419
            if type(node) is InternalNode:
1420
                # Without looking at any leaf nodes, we are sure
1421
                return self
1422
            for key, value in node._items.iteritems():
1423
                if new_leaf._map_no_split(key, value):
1424
                    return self
3735.2.123 by Ian Clatworthy
only check for remap if changes are interesting in size
1425
        trace.mutter("remap generated a new LeafNode")
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1426
        return new_leaf
1427
1428
1429
def _deserialise(bytes, key, search_key_func):
1430
    """Helper for repositorydetails - convert bytes to a node."""
1431
    if bytes.startswith("chkleaf:\n"):
1432
        node = LeafNode.deserialise(bytes, key, search_key_func=search_key_func)
1433
    elif bytes.startswith("chknode:\n"):
1434
        node = InternalNode.deserialise(bytes, key,
1435
            search_key_func=search_key_func)
1436
    else:
1437
        raise AssertionError("Unknown node type.")
1438
    return node
1439
1440
4476.1.38 by John Arbash Meinel
Rename InterestingNodeIterator => CHKMapDifference, update tests.
1441
class CHKMapDifference(object):
1442
    """Iterate the stored pages and key,value pairs for (new - old).
1443
1444
    This class provides a generator over the stored CHK pages and the
1445
    (key, value) pairs that are in any of the new maps and not in any of the
1446
    old maps.
1447
1448
    Note that it may yield chk pages that are common (especially root nodes),
1449
    but it won't yield (key,value) pairs that are common.
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1450
    """
1451
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1452
    def __init__(self, store, new_root_keys, old_root_keys,
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1453
                 search_key_func, pb=None):
1454
        self._store = store
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1455
        self._new_root_keys = new_root_keys
1456
        self._old_root_keys = old_root_keys
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1457
        self._pb = pb
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1458
        # All uninteresting chks that we have seen. By the time they are added
1459
        # here, they should be either fully ignored, or queued up for
1460
        # processing
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1461
        self._all_old_chks = set(self._old_root_keys)
1462
        # All items that we have seen from the old_root_keys
1463
        self._all_old_items = set()
4476.1.32 by John Arbash Meinel
A few more updates.
1464
        # These are interesting items which were either read, or already in the
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1465
        # interesting queue (so we don't need to walk them again)
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1466
        self._processed_new_refs = set()
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1467
        self._search_key_func = search_key_func
1468
4476.1.33 by John Arbash Meinel
Simpify the code a lot by ignoring the heapq stuff.
1469
        # The uninteresting and interesting nodes to be searched
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1470
        self._old_queue = []
1471
        self._new_queue = []
4476.1.34 by John Arbash Meinel
Major rework, simplify what is put into the queues.
1472
        # Holds the (key, value) items found when processing the root nodes,
1473
        # waiting for the uninteresting nodes to be walked
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1474
        self._new_item_queue = []
4476.1.17 by John Arbash Meinel
Start running all of the iter_interesting_nodes tests
1475
        self._state = None
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1476
1477
    def _read_nodes_from_store(self, keys):
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1478
        # We chose not to use _page_cache, because we think in terms of records
1479
        # to be yielded. Also, we expect to touch each page only 1 time during
1480
        # this code. (We may want to evaluate saving the raw bytes into the
1481
        # page cache, which would allow a working tree update after the fetch
1482
        # to not have to read the bytes again.)
4476.1.12 by John Arbash Meinel
Start testing the new class.
1483
        stream = self._store.get_record_stream(keys, 'unordered', True)
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1484
        for record in stream:
1485
            if self._pb is not None:
1486
                self._pb.tick()
1487
            if record.storage_kind == 'absent':
4476.1.17 by John Arbash Meinel
Start running all of the iter_interesting_nodes tests
1488
                raise errors.NoSuchRevision(self._store, record.key)
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1489
            bytes = record.get_bytes_as('fulltext')
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1490
            node = _deserialise(bytes, record.key,
1491
                                search_key_func=self._search_key_func)
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1492
            if type(node) is InternalNode:
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1493
                # Note we don't have to do node.refs() because we know that
1494
                # there are no children that have been pushed into this node
1495
                prefix_refs = node._items.items()
1496
                items = []
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1497
            else:
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1498
                prefix_refs = []
1499
                items = node._items.items()
1500
            yield record, node, prefix_refs, items
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1501
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1502
    def _read_old_roots(self):
1503
        old_chks_to_enqueue = []
1504
        all_old_chks = self._all_old_chks
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1505
        for record, node, prefix_refs, items in \
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1506
                self._read_nodes_from_store(self._old_root_keys):
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1507
            # Uninteresting node
4476.1.34 by John Arbash Meinel
Major rework, simplify what is put into the queues.
1508
            prefix_refs = [p_r for p_r in prefix_refs
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1509
                                if p_r[1] not in all_old_chks]
4476.1.34 by John Arbash Meinel
Major rework, simplify what is put into the queues.
1510
            new_refs = [p_r[1] for p_r in prefix_refs]
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1511
            all_old_chks.update(new_refs)
1512
            self._all_old_items.update(items)
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1513
            # Queue up the uninteresting references
1514
            # Don't actually put them in the 'to-read' queue until we have
1515
            # finished checking the interesting references
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1516
            old_chks_to_enqueue.extend(prefix_refs)
1517
        return old_chks_to_enqueue
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1518
4476.1.40 by John Arbash Meinel
cleanup indentation.
1519
    def _enqueue_old(self, new_prefixes, old_chks_to_enqueue):
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1520
        # At this point, we have read all the uninteresting and interesting
1521
        # items, so we can queue up the uninteresting stuff, knowing that we've
1522
        # handled the interesting ones
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1523
        for prefix, ref in old_chks_to_enqueue:
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1524
            not_interesting = True
1525
            for i in xrange(len(prefix), 0, -1):
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1526
                if prefix[:i] in new_prefixes:
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1527
                    not_interesting = False
1528
                    break
1529
            if not_interesting:
1530
                # This prefix is not part of the remaining 'interesting set'
1531
                continue
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1532
            self._old_queue.append(ref)
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1533
1534
    def _read_all_roots(self):
1535
        """Read the root pages.
1536
1537
        This is structured as a generator, so that the root records can be
1538
        yielded up to whoever needs them without any buffering.
1539
        """
1540
        # This is the bootstrap phase
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1541
        if not self._old_root_keys:
1542
            # With no old_root_keys we can just shortcut and be ready
1543
            # for _flush_new_queue
1544
            self._new_queue = list(self._new_root_keys)
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1545
            return
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1546
        old_chks_to_enqueue = self._read_old_roots()
4476.1.12 by John Arbash Meinel
Start testing the new class.
1547
        # filter out any root keys that are already known to be uninteresting
4476.1.40 by John Arbash Meinel
cleanup indentation.
1548
        new_keys = set(self._new_root_keys).difference(self._all_old_chks)
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1549
        # These are prefixes that are present in new_keys that we are
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1550
        # thinking to yield
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1551
        new_prefixes = set()
4476.1.18 by John Arbash Meinel
Tracked it down.
1552
        # We are about to yield all of these, so we don't want them getting
1553
        # added a second time
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1554
        processed_new_refs = self._processed_new_refs
1555
        processed_new_refs.update(new_keys)
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1556
        for record, node, prefix_refs, items in \
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1557
                self._read_nodes_from_store(new_keys):
4476.1.5 by John Arbash Meinel
Start working on a new InterestingNodeIterator class.
1558
            # At this level, we now know all the uninteresting references
4476.1.35 by John Arbash Meinel
Change some of the inner loop workings into list comprehensions.
1559
            # So we filter and queue up whatever is remaining
1560
            prefix_refs = [p_r for p_r in prefix_refs
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1561
                           if p_r[1] not in self._all_old_chks
1562
                              and p_r[1] not in processed_new_refs]
4476.1.35 by John Arbash Meinel
Change some of the inner loop workings into list comprehensions.
1563
            refs = [p_r[1] for p_r in prefix_refs]
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1564
            new_prefixes.update([p_r[0] for p_r in prefix_refs])
1565
            self._new_queue.extend(refs)
4476.1.34 by John Arbash Meinel
Major rework, simplify what is put into the queues.
1566
            # TODO: We can potentially get multiple items here, however the
1567
            #       current design allows for this, as callers will do the work
1568
            #       to make the results unique. We might profile whether we
1569
            #       gain anything by ensuring unique return values for items
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1570
            new_items = [item for item in items
4476.1.40 by John Arbash Meinel
cleanup indentation.
1571
                               if item not in self._all_old_items]
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1572
            self._new_item_queue.extend(new_items)
1573
            new_prefixes.update([self._search_key_func(item[0])
4476.1.40 by John Arbash Meinel
cleanup indentation.
1574
                                 for item in new_items])
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1575
            processed_new_refs.update(refs)
4476.1.13 by John Arbash Meinel
Test that _read_all_roots does what is expected
1576
            yield record
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1577
        # For new_prefixes we have the full length prefixes queued up.
4476.1.35 by John Arbash Meinel
Change some of the inner loop workings into list comprehensions.
1578
        # However, we also need possible prefixes. (If we have a known ref to
1579
        # 'ab', then we also need to include 'a'.) So expand the
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1580
        # new_prefixes to include all shorter prefixes
1581
        for prefix in list(new_prefixes):
4476.1.40 by John Arbash Meinel
cleanup indentation.
1582
            new_prefixes.update([prefix[:i] for i in xrange(1, len(prefix))])
1583
        self._enqueue_old(new_prefixes, old_chks_to_enqueue)
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1584
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1585
    def _flush_new_queue(self):
4476.1.27 by John Arbash Meinel
Rewrite of _flush_interesting_queue
1586
        # No need to maintain the heap invariant anymore, just pull things out
1587
        # and process them
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1588
        refs = set(self._new_queue)
1589
        self._new_queue = []
4476.1.31 by John Arbash Meinel
streamline the _flush_interesting_queue a bit.
1590
        # First pass, flush all interesting items and convert to using direct refs
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1591
        all_old_chks = self._all_old_chks
1592
        processed_new_refs = self._processed_new_refs
1593
        all_old_items = self._all_old_items
1594
        new_items = [item for item in self._new_item_queue
4476.1.40 by John Arbash Meinel
cleanup indentation.
1595
                           if item not in all_old_items]
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1596
        self._new_item_queue = []
1597
        if new_items:
1598
            yield None, new_items
1599
        refs = refs.difference(all_old_chks)
4476.1.31 by John Arbash Meinel
streamline the _flush_interesting_queue a bit.
1600
        while refs:
1601
            next_refs = set()
1602
            next_refs_update = next_refs.update
1603
            # Inlining _read_nodes_from_store improves 'bzr branch bzr.dev'
1604
            # from 1m54s to 1m51s. Consider it.
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1605
            for record, _, p_refs, items in self._read_nodes_from_store(refs):
4476.1.27 by John Arbash Meinel
Rewrite of _flush_interesting_queue
1606
                items = [item for item in items
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1607
                         if item not in all_old_items]
4476.1.27 by John Arbash Meinel
Rewrite of _flush_interesting_queue
1608
                yield record, items
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1609
                next_refs_update([p_r[1] for p_r in p_refs])
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1610
            next_refs = next_refs.difference(all_old_chks)
1611
            next_refs = next_refs.difference(processed_new_refs)
1612
            processed_new_refs.update(next_refs)
4476.1.31 by John Arbash Meinel
streamline the _flush_interesting_queue a bit.
1613
            refs = next_refs
4476.1.17 by John Arbash Meinel
Start running all of the iter_interesting_nodes tests
1614
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1615
    def _process_next_old(self):
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1616
        # Since we don't filter uninteresting any further than during
1617
        # _read_all_roots, process the whole queue in a single pass.
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1618
        refs = self._old_queue
1619
        self._old_queue = []
1620
        all_old_chks = self._all_old_chks
4476.1.32 by John Arbash Meinel
A few more updates.
1621
        for record, _, prefix_refs, items in self._read_nodes_from_store(refs):
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1622
            self._all_old_items.update(items)
1623
            refs = [r for _,r in prefix_refs if r not in all_old_chks]
1624
            self._old_queue.extend(refs)
1625
            all_old_chks.update(refs)
4476.1.17 by John Arbash Meinel
Start running all of the iter_interesting_nodes tests
1626
1627
    def _process_queues(self):
4476.1.39 by John Arbash Meinel
Rename interesting => new, uninteresting => old
1628
        while self._old_queue:
1629
            self._process_next_old()
1630
        return self._flush_new_queue()
4476.1.17 by John Arbash Meinel
Start running all of the iter_interesting_nodes tests
1631
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1632
    def process(self):
1633
        for record in self._read_all_roots():
1634
            yield record, []
1635
        for record, items in self._process_queues():
1636
            yield record, items
1637
4476.1.25 by John Arbash Meinel
A bit more testing.
1638
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1639
def iter_interesting_nodes(store, interesting_root_keys,
1640
                           uninteresting_root_keys, pb=None):
1641
    """Given root keys, find interesting nodes.
1642
1643
    Evaluate nodes referenced by interesting_root_keys. Ones that are also
1644
    referenced from uninteresting_root_keys are not considered interesting.
1645
1646
    :param interesting_root_keys: keys which should be part of the
1647
        "interesting" nodes (which will be yielded)
1648
    :param uninteresting_root_keys: keys which should be filtered out of the
1649
        result set.
1650
    :return: Yield
1651
        (interesting record, {interesting key:values})
1652
    """
4476.1.38 by John Arbash Meinel
Rename InterestingNodeIterator => CHKMapDifference, update tests.
1653
    iterator = CHKMapDifference(store, interesting_root_keys,
1654
                                uninteresting_root_keys,
1655
                                search_key_func=store._search_key_func,
1656
                                pb=pb)
4476.1.37 by John Arbash Meinel
Some small code cleanup passes
1657
    return iterator.process()
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1658
1659
1660
try:
1661
    from bzrlib._chk_map_pyx import (
1662
        _search_key_16,
1663
        _search_key_255,
1664
        _deserialise_leaf_node,
1665
        _deserialise_internal_node,
1666
        )
4574.3.6 by Martin Pool
More warnings when failing to load extensions
1667
except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
1668
    osutils.failed_to_load_extension(e)
4241.6.1 by Ian Clatworthy
chk_map code from brisbane-core
1669
    from bzrlib._chk_map_py import (
1670
        _search_key_16,
1671
        _search_key_255,
1672
        _deserialise_leaf_node,
1673
        _deserialise_internal_node,
1674
        )
1675
search_key_registry.register('hash-16-way', _search_key_16)
1676
search_key_registry.register('hash-255-way', _search_key_255)
4679.9.4 by John Arbash Meinel
A bit broken, but getting there.
1677
1678
def _check_key(key):
1679
    if type(key) is not StaticTuple:
1680
        raise TypeError('key %r is not StaticTuple but %s' % (key, type(key)))
1681
    if len(key) != 1:
1682
        raise ValueError('key %r should have length 1, not %d' % (key, len(key),))
1683
    if type(key[0]) is not str:
1684
        raise TypeError('key %r should hold a str, not %r'
1685
                        % (key, type(key[0])))
1686
    if not key[0].startswith('sha1:'):
1687
        raise ValueError('key %r should point to a sha1:' % (key,))
1688
1689