/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/chk_map.py

  • Committer: Marius Kruger
  • Date: 2010-07-10 21:28:56 UTC
  • mto: (5384.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5385.
  • Revision ID: marius.kruger@enerweb.co.za-20100710212856-uq4ji3go0u5se7hx
* Update documentation
* add NEWS

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008-2011 Canonical Ltd
 
1
# Copyright (C) 2008, 2009, 2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
40
40
import heapq
41
41
import threading
42
42
 
43
 
from .. import (
 
43
from bzrlib import lazy_import
 
44
lazy_import.lazy_import(globals(), """
 
45
from bzrlib import (
44
46
    errors,
 
47
    versionedfile,
 
48
    )
 
49
""")
 
50
from bzrlib import (
45
51
    lru_cache,
46
52
    osutils,
47
53
    registry,
48
54
    static_tuple,
49
55
    trace,
50
56
    )
51
 
from ..static_tuple import StaticTuple
 
57
from bzrlib.static_tuple import StaticTuple
52
58
 
53
59
# approx 4MB
54
60
# If each line is 50 bytes, and you have 255 internal pages, with 255-way fan
55
61
# out, it takes 3.1MB to cache the layer.
56
 
_PAGE_CACHE_SIZE = 4 * 1024 * 1024
 
62
_PAGE_CACHE_SIZE = 4*1024*1024
57
63
# Per thread caches for 2 reasons:
58
64
# - in the server we may be serving very different content, so we get less
59
65
#   cache thrashing.
62
68
# The page cache.
63
69
_thread_caches.page_cache = None
64
70
 
65
 
 
66
71
def _get_cache():
67
72
    """Get the per-thread page cache.
68
73
 
85
90
_INTERESTING_NEW_SIZE = 50
86
91
# If a ChildNode shrinks by more than this amount, we check for a remap
87
92
_INTERESTING_SHRINKAGE_LIMIT = 20
 
93
# If we delete more than this many nodes applying a delta, we check for a remap
 
94
_INTERESTING_DELETES_LIMIT = 5
88
95
 
89
96
 
90
97
def _search_key_plain(key):
91
98
    """Map the key tuple into a search string that just uses the key bytes."""
92
 
    return b'\x00'.join(key)
 
99
    return '\x00'.join(key)
93
100
 
94
101
 
95
102
search_key_registry = registry.Registry()
96
 
search_key_registry.register(b'plain', _search_key_plain)
 
103
search_key_registry.register('plain', _search_key_plain)
97
104
 
98
105
 
99
106
class CHKMap(object):
128
135
            into the map; if old_key is not None, then the old mapping
129
136
            of old_key is removed.
130
137
        """
131
 
        has_deletes = False
 
138
        delete_count = 0
132
139
        # Check preconditions first.
133
140
        as_st = StaticTuple.from_sequence
134
 
        new_items = {as_st(key) for (old, key, value) in delta
135
 
                     if key is not None and old is None}
 
141
        new_items = set([as_st(key) for (old, key, value) in delta
 
142
                         if key is not None and old is None])
136
143
        existing_new = list(self.iteritems(key_filter=new_items))
137
144
        if existing_new:
138
145
            raise errors.InconsistentDeltaDelta(delta,
139
 
                                                "New items are already in the map %r." % existing_new)
 
146
                "New items are already in the map %r." % existing_new)
140
147
        # Now apply changes.
141
148
        for old, new, value in delta:
142
149
            if old is not None and old != new:
143
150
                self.unmap(old, check_remap=False)
144
 
                has_deletes = True
 
151
                delete_count += 1
145
152
        for old, new, value in delta:
146
153
            if new is not None:
147
154
                self.map(new, value)
148
 
        if has_deletes:
 
155
        if delete_count > _INTERESTING_DELETES_LIMIT:
 
156
            trace.mutter("checking remap as %d deletions", delete_count)
149
157
            self._check_remap()
150
158
        return self._save()
151
159
 
152
160
    def _ensure_root(self):
153
161
        """Ensure that the root node is an object not a key."""
154
 
        if isinstance(self._root_node, StaticTuple):
 
162
        if type(self._root_node) is StaticTuple:
155
163
            # Demand-load the root
156
164
            self._root_node = self._get_node(self._root_node)
157
165
 
165
173
        :param node: A tuple key or node object.
166
174
        :return: A node object.
167
175
        """
168
 
        if isinstance(node, StaticTuple):
 
176
        if type(node) is StaticTuple:
169
177
            bytes = self._read_bytes(node)
170
178
            return _deserialise(bytes, node,
171
 
                                search_key_func=self._search_key_func)
 
179
                search_key_func=self._search_key_func)
172
180
        else:
173
181
            return node
174
182
 
177
185
            return _get_cache()[key]
178
186
        except KeyError:
179
187
            stream = self._store.get_record_stream([key], 'unordered', True)
180
 
            bytes = next(stream).get_bytes_as('fulltext')
 
188
            bytes = stream.next().get_bytes_as('fulltext')
181
189
            _get_cache()[key] = bytes
182
190
            return bytes
183
191
 
184
 
    def _dump_tree(self, include_keys=False, encoding='utf-8'):
 
192
    def _dump_tree(self, include_keys=False):
185
193
        """Return the tree in a string representation."""
186
194
        self._ensure_root()
187
 
        def decode(x): return x.decode(encoding)
188
 
        res = self._dump_tree_node(self._root_node, prefix=b'', indent='',
189
 
                                   decode=decode, include_keys=include_keys)
190
 
        res.append('')  # Give a trailing '\n'
 
195
        res = self._dump_tree_node(self._root_node, prefix='', indent='',
 
196
                                   include_keys=include_keys)
 
197
        res.append('') # Give a trailing '\n'
191
198
        return '\n'.join(res)
192
199
 
193
 
    def _dump_tree_node(self, node, prefix, indent, decode, include_keys=True):
 
200
    def _dump_tree_node(self, node, prefix, indent, include_keys=True):
194
201
        """For this node and all children, generate a string representation."""
195
202
        result = []
196
203
        if not include_keys:
198
205
        else:
199
206
            node_key = node.key()
200
207
            if node_key is not None:
201
 
                key_str = ' %s' % (decode(node_key[0]),)
 
208
                key_str = ' %s' % (node_key[0],)
202
209
            else:
203
210
                key_str = ' None'
204
 
        result.append('%s%r %s%s' % (indent, decode(prefix), node.__class__.__name__,
 
211
        result.append('%s%r %s%s' % (indent, prefix, node.__class__.__name__,
205
212
                                     key_str))
206
 
        if isinstance(node, InternalNode):
 
213
        if type(node) is InternalNode:
207
214
            # Trigger all child nodes to get loaded
208
215
            list(node._iter_nodes(self._store))
209
 
            for prefix, sub in sorted(node._items.items()):
 
216
            for prefix, sub in sorted(node._items.iteritems()):
210
217
                result.extend(self._dump_tree_node(sub, prefix, indent + '  ',
211
 
                                                   decode=decode, include_keys=include_keys))
 
218
                                                   include_keys=include_keys))
212
219
        else:
213
 
            for key, value in sorted(node._items.items()):
 
220
            for key, value in sorted(node._items.iteritems()):
214
221
                # Don't use prefix nor indent here to line up when used in
215
222
                # tests in conjunction with assertEqualDiff
216
 
                result.append('      %r %r' % (
217
 
                    tuple([decode(ke) for ke in key]), decode(value)))
 
223
                result.append('      %r %r' % (tuple(key), value))
218
224
        return result
219
225
 
220
226
    @classmethod
221
227
    def from_dict(klass, store, initial_value, maximum_size=0, key_width=1,
222
 
                  search_key_func=None):
 
228
        search_key_func=None):
223
229
        """Create a CHKMap in store with initial_value as the content.
224
230
 
225
231
        :param store: The store to record initial_value in, a VersionedFiles
236
242
        :return: The root chk of the resulting CHKMap.
237
243
        """
238
244
        root_key = klass._create_directly(store, initial_value,
239
 
                                          maximum_size=maximum_size, key_width=key_width,
240
 
                                          search_key_func=search_key_func)
241
 
        if not isinstance(root_key, StaticTuple):
 
245
            maximum_size=maximum_size, key_width=key_width,
 
246
            search_key_func=search_key_func)
 
247
        if type(root_key) is not StaticTuple:
242
248
            raise AssertionError('we got a %s instead of a StaticTuple'
243
249
                                 % (type(root_key),))
244
250
        return root_key
262
268
        node.set_maximum_size(maximum_size)
263
269
        node._key_width = key_width
264
270
        as_st = StaticTuple.from_sequence
265
 
        node._items = dict((as_st(key), val)
266
 
                           for key, val in initial_value.items())
267
 
        node._raw_size = sum(node._key_value_len(key, value)
268
 
                             for key, value in node._items.items())
 
271
        node._items = dict([(as_st(key), val) for key, val
 
272
                                               in initial_value.iteritems()])
 
273
        node._raw_size = sum([node._key_value_len(key, value)
 
274
                              for key,value in node._items.iteritems()])
269
275
        node._len = len(node._items)
270
276
        node._compute_search_prefix()
271
277
        node._compute_serialised_prefix()
272
 
        if (node._len > 1 and
273
 
            maximum_size and
274
 
                node._current_size() > maximum_size):
 
278
        if (node._len > 1
 
279
            and maximum_size
 
280
            and node._current_size() > maximum_size):
275
281
            prefix, node_details = node._split(store)
276
282
            if len(node_details) == 1:
277
283
                raise AssertionError('Failed to split using node._split')
323
329
        # key_path (a list of tuples, tail-sharing down the tree.)
324
330
        self_pending = []
325
331
        basis_pending = []
326
 
 
327
332
        def process_node(node, path, a_map, pending):
328
333
            # take a node and expand it
329
334
            node = a_map._get_node(node)
330
 
            if isinstance(node, LeafNode):
 
335
            if type(node) == LeafNode:
331
336
                path = (node._key, path)
332
337
                for key, value in node._items.items():
333
338
                    # For a LeafNode, the key is a serialized_key, rather than
339
344
                path = (node._key, path)
340
345
                for prefix, child in node._items.items():
341
346
                    heapq.heappush(pending, (prefix, None, child, path))
342
 
 
343
347
        def process_common_internal_nodes(self_node, basis_node):
344
348
            self_items = set(self_node._items.items())
345
349
            basis_items = set(basis_node._items.items())
349
353
            path = (basis_node._key, None)
350
354
            for prefix, child in basis_items - self_items:
351
355
                heapq.heappush(basis_pending, (prefix, None, child, path))
352
 
 
353
356
        def process_common_leaf_nodes(self_node, basis_node):
354
357
            self_items = set(self_node._items.items())
355
358
            basis_items = set(basis_node._items.items())
361
364
            for key, value in basis_items - self_items:
362
365
                prefix = basis._search_key_func(key)
363
366
                heapq.heappush(basis_pending, (prefix, key, value, path))
364
 
 
365
367
        def process_common_prefix_nodes(self_node, self_path,
366
368
                                        basis_node, basis_path):
367
369
            # Would it be more efficient if we could request both at the same
368
370
            # time?
369
371
            self_node = self._get_node(self_node)
370
372
            basis_node = basis._get_node(basis_node)
371
 
            if (isinstance(self_node, InternalNode) and
372
 
                    isinstance(basis_node, InternalNode)):
 
373
            if (type(self_node) == InternalNode
 
374
                and type(basis_node) == InternalNode):
373
375
                # Matching internal nodes
374
376
                process_common_internal_nodes(self_node, basis_node)
375
 
            elif (isinstance(self_node, LeafNode) and
376
 
                  isinstance(basis_node, LeafNode)):
 
377
            elif (type(self_node) == LeafNode
 
378
                  and type(basis_node) == LeafNode):
377
379
                process_common_leaf_nodes(self_node, basis_node)
378
380
            else:
379
381
                process_node(self_node, self_path, self, self_pending)
382
384
        self_seen = set()
383
385
        basis_seen = set()
384
386
        excluded_keys = set()
385
 
 
386
387
        def check_excluded(key_path):
387
388
            # Note that this is N^2, it depends on us trimming trees
388
389
            # aggressively to not become slow.
389
390
            # A better implementation would probably have a reverse map
390
391
            # back to the children of a node, and jump straight to it when
391
392
            # a common node is detected, the proceed to remove the already
392
 
            # pending children. breezy.graph has a searcher module with a
 
393
            # pending children. bzrlib.graph has a searcher module with a
393
394
            # similar problem.
394
395
            while key_path is not None:
395
396
                key, key_path = key_path
472
473
                        basis_details = heapq.heappop(basis_pending)
473
474
                        if self_details[2] != basis_details[2]:
474
475
                            yield (self_details[1],
475
 
                                   basis_details[2], self_details[2])
 
476
                                basis_details[2], self_details[2])
476
477
                        continue
477
478
                    # At least one side wasn't a simple value
478
 
                    if (self._node_key(self_pending[0][2])
479
 
                            == self._node_key(basis_pending[0][2])):
 
479
                    if (self._node_key(self_pending[0][2]) ==
 
480
                        self._node_key(basis_pending[0][2])):
480
481
                        # Identical pointers, skip (and don't bother adding to
481
482
                        # excluded, it won't turn up again.
482
483
                        heapq.heappop(self_pending)
519
520
 
520
521
    def key(self):
521
522
        """Return the key for this map."""
522
 
        if isinstance(self._root_node, StaticTuple):
 
523
        if type(self._root_node) is StaticTuple:
523
524
            return self._root_node
524
525
        else:
525
526
            return self._root_node._key
530
531
 
531
532
    def map(self, key, value):
532
533
        """Map a key tuple to value.
533
 
 
 
534
        
534
535
        :param key: A key to map.
535
536
        :param value: The value to assign to key.
536
537
        """
542
543
            self._root_node = node_details[0][1]
543
544
        else:
544
545
            self._root_node = InternalNode(prefix,
545
 
                                           search_key_func=self._search_key_func)
 
546
                                search_key_func=self._search_key_func)
546
547
            self._root_node.set_maximum_size(node_details[0][1].maximum_size)
547
548
            self._root_node._key_width = node_details[0][1]._key_width
548
549
            for split, node in node_details:
550
551
 
551
552
    def _node_key(self, node):
552
553
        """Get the key for a node whether it's a tuple or node."""
553
 
        if isinstance(node, tuple):
 
554
        if type(node) is tuple:
554
555
            node = StaticTuple.from_sequence(node)
555
 
        if isinstance(node, StaticTuple):
 
556
        if type(node) is StaticTuple:
556
557
            return node
557
558
        else:
558
559
            return node._key
561
562
        """remove key from the map."""
562
563
        key = StaticTuple.from_sequence(key)
563
564
        self._ensure_root()
564
 
        if isinstance(self._root_node, InternalNode):
 
565
        if type(self._root_node) is InternalNode:
565
566
            unmapped = self._root_node.unmap(self._store, key,
566
 
                                             check_remap=check_remap)
 
567
                check_remap=check_remap)
567
568
        else:
568
569
            unmapped = self._root_node.unmap(self._store, key)
569
570
        self._root_node = unmapped
571
572
    def _check_remap(self):
572
573
        """Check if nodes can be collapsed."""
573
574
        self._ensure_root()
574
 
        if isinstance(self._root_node, InternalNode):
575
 
            self._root_node = self._root_node._check_remap(self._store)
 
575
        if type(self._root_node) is InternalNode:
 
576
            self._root_node._check_remap(self._store)
576
577
 
577
578
    def _save(self):
578
579
        """Save the map completely.
579
580
 
580
581
        :return: The key of the root node.
581
582
        """
582
 
        if isinstance(self._root_node, StaticTuple):
 
583
        if type(self._root_node) is StaticTuple:
583
584
            # Already saved.
584
585
            return self._root_node
585
586
        keys = list(self._root_node.serialise(self._store))
595
596
 
596
597
    __slots__ = ('_key', '_len', '_maximum_size', '_key_width',
597
598
                 '_raw_size', '_items', '_search_prefix', '_search_key_func'
598
 
                 )
 
599
                )
599
600
 
600
601
    def __init__(self, key_width=1):
601
602
        """Create a node.
657
658
            if left != right:
658
659
                pos -= 1
659
660
                break
660
 
        common = prefix[:pos + 1]
 
661
        common = prefix[:pos+1]
661
662
        return common
662
663
 
663
664
    @classmethod
676
677
            if not common_prefix:
677
678
                # if common_prefix is the empty string, then we know it won't
678
679
                # change further
679
 
                return b''
 
680
                return ''
680
681
        return common_prefix
681
682
 
682
683
 
683
684
# Singleton indicating we have not computed _search_prefix yet
684
685
_unknown = object()
685
686
 
686
 
 
687
687
class LeafNode(Node):
688
688
    """A node containing actual key:value pairs.
689
689
 
710
710
        return \
711
711
            '%s(key:%s len:%s size:%s max:%s prefix:%s keywidth:%s items:%s)' \
712
712
            % (self.__class__.__name__, self._key, self._len, self._raw_size,
713
 
               self._maximum_size, self._search_prefix, self._key_width, items_str)
 
713
            self._maximum_size, self._search_prefix, self._key_width, items_str)
714
714
 
715
715
    def _current_size(self):
716
716
        """Answer the current serialised size of this node.
727
727
            # entry lines
728
728
            prefix_len = len(self._common_serialised_prefix)
729
729
            bytes_for_items = (self._raw_size - (prefix_len * self._len))
730
 
        return (9 +  # 'chkleaf:\n' +
731
 
                len(str(self._maximum_size)) + 1 +
732
 
                len(str(self._key_width)) + 1 +
733
 
                len(str(self._len)) + 1 +
734
 
                prefix_len + 1 +
735
 
                bytes_for_items)
 
730
        return (9 # 'chkleaf:\n'
 
731
            + len(str(self._maximum_size)) + 1
 
732
            + len(str(self._key_width)) + 1
 
733
            + len(str(self._len)) + 1
 
734
            + prefix_len + 1
 
735
            + bytes_for_items)
736
736
 
737
737
    @classmethod
738
738
    def deserialise(klass, bytes, key, search_key_func=None):
767
767
                        pass
768
768
                else:
769
769
                    # Short items, we need to match based on a prefix
770
 
                    filters.setdefault(len(key), set()).add(key)
 
770
                    length_filter = filters.setdefault(len(key), set())
 
771
                    length_filter.add(key)
771
772
            if filters:
772
 
                filters_itemview = filters.items()
773
 
                for item in self._items.items():
774
 
                    for length, length_filter in filters_itemview:
 
773
                filters = filters.items()
 
774
                for item in self._items.iteritems():
 
775
                    for length, length_filter in filters:
775
776
                        if item[0][:length] in length_filter:
776
777
                            yield item
777
778
                            break
778
779
        else:
779
 
            yield from self._items.items()
 
780
            for item in self._items.iteritems():
 
781
                yield item
780
782
 
781
783
    def _key_value_len(self, key, value):
782
784
        # TODO: Should probably be done without actually joining the key, but
783
785
        #       then that can be done via the C extension
784
 
        return (len(self._serialise_key(key)) + 1 +
785
 
                len(b'%d' % value.count(b'\n')) + 1 +
786
 
                len(value) + 1)
 
786
        return (len(self._serialise_key(key)) + 1
 
787
                + len(str(value.count('\n'))) + 1
 
788
                + len(value) + 1)
787
789
 
788
790
    def _search_key(self, key):
789
791
        return self._search_key_func(key)
813
815
        else:
814
816
            self._search_prefix = self.common_prefix(
815
817
                self._search_prefix, search_key)
816
 
        if (self._len > 1 and
817
 
            self._maximum_size and
818
 
                self._current_size() > self._maximum_size):
 
818
        if (self._len > 1
 
819
            and self._maximum_size
 
820
            and self._current_size() > self._maximum_size):
819
821
            # Check to see if all of the search_keys for this node are
820
822
            # identical. We allow the node to grow under that circumstance
821
823
            # (we could track this as common state, but it is infrequent)
822
 
            if (search_key != self._search_prefix or
823
 
                    not self._are_search_keys_identical()):
 
824
            if (search_key != self._search_prefix
 
825
                or not self._are_search_keys_identical()):
824
826
                return True
825
827
        return False
826
828
 
837
839
        common_prefix = self._search_prefix
838
840
        split_at = len(common_prefix) + 1
839
841
        result = {}
840
 
        for key, value in self._items.items():
 
842
        for key, value in self._items.iteritems():
841
843
            search_key = self._search_key(key)
842
844
            prefix = search_key[:split_at]
843
845
            # TODO: Generally only 1 key can be exactly the right length,
849
851
            #       may get a '\00' node anywhere, but won't have keys of
850
852
            #       different lengths.
851
853
            if len(prefix) < split_at:
852
 
                prefix += b'\x00' * (split_at - len(prefix))
 
854
                prefix += '\x00'*(split_at - len(prefix))
853
855
            if prefix not in result:
854
856
                node = LeafNode(search_key_func=self._search_key_func)
855
857
                node.set_maximum_size(self._maximum_size)
864
866
                    # path
865
867
                    result.pop(prefix)
866
868
                new_node = InternalNode(sub_prefix,
867
 
                                        search_key_func=self._search_key_func)
 
869
                    search_key_func=self._search_key_func)
868
870
                new_node.set_maximum_size(self._maximum_size)
869
871
                new_node._key_width = self._key_width
870
872
                for split, node in node_details:
871
873
                    new_node.add_node(split, node)
872
874
                result[prefix] = new_node
873
 
        return common_prefix, list(result.items())
 
875
        return common_prefix, result.items()
874
876
 
875
877
    def map(self, store, key, value):
876
878
        """Map key to value."""
883
885
        else:
884
886
            if self._search_prefix is _unknown:
885
887
                raise AssertionError('%r must be known' % self._search_prefix)
886
 
            return self._search_prefix, [(b"", self)]
 
888
            return self._search_prefix, [("", self)]
887
889
 
888
 
    _serialise_key = b'\x00'.join
 
890
    _serialise_key = '\x00'.join
889
891
 
890
892
    def serialise(self, store):
891
893
        """Serialise the LeafNode to store.
893
895
        :param store: A VersionedFiles honouring the CHK extensions.
894
896
        :return: An iterable of the keys inserted by this operation.
895
897
        """
896
 
        lines = [b"chkleaf:\n"]
897
 
        lines.append(b"%d\n" % self._maximum_size)
898
 
        lines.append(b"%d\n" % self._key_width)
899
 
        lines.append(b"%d\n" % self._len)
 
898
        lines = ["chkleaf:\n"]
 
899
        lines.append("%d\n" % self._maximum_size)
 
900
        lines.append("%d\n" % self._key_width)
 
901
        lines.append("%d\n" % self._len)
900
902
        if self._common_serialised_prefix is None:
901
 
            lines.append(b'\n')
 
903
            lines.append('\n')
902
904
            if len(self._items) != 0:
903
905
                raise AssertionError('If _common_serialised_prefix is None'
904
 
                                     ' we should have no items')
 
906
                    ' we should have no items')
905
907
        else:
906
 
            lines.append(b'%s\n' % (self._common_serialised_prefix,))
 
908
            lines.append('%s\n' % (self._common_serialised_prefix,))
907
909
            prefix_len = len(self._common_serialised_prefix)
908
910
        for key, value in sorted(self._items.items()):
909
911
            # Always add a final newline
910
 
            value_lines = osutils.chunks_to_lines([value + b'\n'])
911
 
            serialized = b"%s\x00%d\n" % (self._serialise_key(key),
912
 
                                          len(value_lines))
 
912
            value_lines = osutils.chunks_to_lines([value + '\n'])
 
913
            serialized = "%s\x00%s\n" % (self._serialise_key(key),
 
914
                                         len(value_lines))
913
915
            if not serialized.startswith(self._common_serialised_prefix):
914
916
                raise AssertionError('We thought the common prefix was %r'
915
 
                                     ' but entry %r does not have it in common'
916
 
                                     % (self._common_serialised_prefix, serialized))
 
917
                    ' but entry %r does not have it in common'
 
918
                    % (self._common_serialised_prefix, serialized))
917
919
            lines.append(serialized[prefix_len:])
918
920
            lines.extend(value_lines)
919
921
        sha1, _, _ = store.add_lines((None,), (), lines)
920
 
        self._key = StaticTuple(b"sha1:" + sha1,).intern()
921
 
        data = b''.join(lines)
922
 
        if len(data) != self._current_size():
 
922
        self._key = StaticTuple("sha1:" + sha1,).intern()
 
923
        bytes = ''.join(lines)
 
924
        if len(bytes) != self._current_size():
923
925
            raise AssertionError('Invalid _current_size')
924
 
        _get_cache()[self._key] = data
 
926
        _get_cache().add(self._key, bytes)
925
927
        return [self._key]
926
928
 
927
929
    def refs(self):
993
995
 
994
996
    __slots__ = ('_node_width',)
995
997
 
996
 
    def __init__(self, prefix=b'', search_key_func=None):
 
998
    def __init__(self, prefix='', search_key_func=None):
997
999
        Node.__init__(self)
998
1000
        # The size of an internalnode with default values and no children.
999
1001
        # How many octets key prefixes within this node are.
1014
1016
            raise AssertionError("_search_prefix should not be None")
1015
1017
        if not prefix.startswith(self._search_prefix):
1016
1018
            raise AssertionError("prefixes mismatch: %s must start with %s"
1017
 
                                 % (prefix, self._search_prefix))
 
1019
                % (prefix,self._search_prefix))
1018
1020
        if len(prefix) != len(self._search_prefix) + 1:
1019
1021
            raise AssertionError("prefix wrong length: len(%s) is not %d" %
1020
 
                                 (prefix, len(self._search_prefix) + 1))
 
1022
                (prefix, len(self._search_prefix) + 1))
1021
1023
        self._len += len(node)
1022
1024
        if not len(self._items):
1023
1025
            self._node_width = len(prefix)
1024
1026
        if self._node_width != len(self._search_prefix) + 1:
1025
1027
            raise AssertionError("node width mismatch: %d is not %d" %
1026
 
                                 (self._node_width, len(self._search_prefix) + 1))
 
1028
                (self._node_width, len(self._search_prefix) + 1))
1027
1029
        self._items[prefix] = node
1028
1030
        self._key = None
1029
1031
 
1030
1032
    def _current_size(self):
1031
1033
        """Answer the current serialised size of this node."""
1032
 
        return (self._raw_size + len(str(self._len)) + len(str(self._key_width))
1033
 
                + len(str(self._maximum_size)))
 
1034
        return (self._raw_size + len(str(self._len)) + len(str(self._key_width)) +
 
1035
            len(str(self._maximum_size)))
1034
1036
 
1035
1037
    @classmethod
1036
1038
    def deserialise(klass, bytes, key, search_key_func=None):
1070
1072
            # yielding all nodes, yield whatever we have, and queue up a read
1071
1073
            # for whatever we are missing
1072
1074
            shortcut = True
1073
 
            for prefix, node in self._items.items():
 
1075
            for prefix, node in self._items.iteritems():
1074
1076
                if node.__class__ is StaticTuple:
1075
1077
                    keys[node] = (prefix, None)
1076
1078
                else:
1121
1123
            for key in key_filter:
1122
1124
                search_prefix = self._search_prefix_filter(key)
1123
1125
                length_filter = length_filters.setdefault(
1124
 
                    len(search_prefix), set())
 
1126
                                    len(search_prefix), set())
1125
1127
                length_filter.add(search_prefix)
1126
1128
                prefix_to_keys.setdefault(search_prefix, []).append(key)
1127
1129
 
1128
 
            if (self._node_width in length_filters and
1129
 
                    len(length_filters) == 1):
 
1130
            if (self._node_width in length_filters
 
1131
                and len(length_filters) == 1):
1130
1132
                # all of the search prefixes match exactly _node_width. This
1131
1133
                # means that everything is an exact match, and we can do a
1132
1134
                # lookup into self._items, rather than iterating over the items
1146
1148
            else:
1147
1149
                # The slow way. We walk every item in self._items, and check to
1148
1150
                # see if there are any matches
1149
 
                length_filters_itemview = length_filters.items()
1150
 
                for prefix, node in self._items.items():
 
1151
                length_filters = length_filters.items()
 
1152
                for prefix, node in self._items.iteritems():
1151
1153
                    node_key_filter = []
1152
 
                    for length, length_filter in length_filters_itemview:
 
1154
                    for length, length_filter in length_filters:
1153
1155
                        sub_prefix = prefix[:length]
1154
1156
                        if sub_prefix in length_filter:
1155
1157
                            node_key_filter.extend(prefix_to_keys[sub_prefix])
1156
 
                    if node_key_filter:  # this key matched something, yield it
 
1158
                    if node_key_filter: # this key matched something, yield it
1157
1159
                        if node.__class__ is StaticTuple:
1158
1160
                            keys[node] = (prefix, node_key_filter)
1159
1161
                        else:
1168
1170
                    continue
1169
1171
                else:
1170
1172
                    node = _deserialise(bytes, key,
1171
 
                                        search_key_func=self._search_key_func)
 
1173
                        search_key_func=self._search_key_func)
1172
1174
                    prefix, node_key_filter = keys[key]
1173
1175
                    self._items[prefix] = node
1174
1176
                    found_keys.add(key)
1190
1192
                for record in stream:
1191
1193
                    bytes = record.get_bytes_as('fulltext')
1192
1194
                    node = _deserialise(bytes, record.key,
1193
 
                                        search_key_func=self._search_key_func)
 
1195
                        search_key_func=self._search_key_func)
1194
1196
                    prefix, node_key_filter = keys[record.key]
1195
1197
                    node_and_filters.append((node, node_key_filter))
1196
1198
                    self._items[prefix] = node
1197
 
                    _get_cache()[record.key] = bytes
 
1199
                    _get_cache().add(record.key, bytes)
1198
1200
                for info in node_and_filters:
1199
1201
                    yield info
1200
1202
 
1205
1207
        search_key = self._search_key(key)
1206
1208
        if self._node_width != len(self._search_prefix) + 1:
1207
1209
            raise AssertionError("node width mismatch: %d is not %d" %
1208
 
                                 (self._node_width, len(self._search_prefix) + 1))
 
1210
                (self._node_width, len(self._search_prefix) + 1))
1209
1211
        if not search_key.startswith(self._search_prefix):
1210
1212
            # This key doesn't fit in this index, so we need to split at the
1211
1213
            # point where it would fit, insert self into that internal node,
1213
1215
            new_prefix = self.common_prefix(self._search_prefix,
1214
1216
                                            search_key)
1215
1217
            new_parent = InternalNode(new_prefix,
1216
 
                                      search_key_func=self._search_key_func)
 
1218
                search_key_func=self._search_key_func)
1217
1219
            new_parent.set_maximum_size(self._maximum_size)
1218
1220
            new_parent._key_width = self._key_width
1219
 
            new_parent.add_node(self._search_prefix[:len(new_prefix) + 1],
 
1221
            new_parent.add_node(self._search_prefix[:len(new_prefix)+1],
1220
1222
                                self)
1221
1223
            return new_parent.map(store, key, value)
1222
 
        children = [node for node, _ in self._iter_nodes(
1223
 
            store, key_filter=[key])]
 
1224
        children = [node for node, _
 
1225
                          in self._iter_nodes(store, key_filter=[key])]
1224
1226
        if children:
1225
1227
            child = children[0]
1226
1228
        else:
1227
1229
            # new child needed:
1228
1230
            child = self._new_child(search_key, LeafNode)
1229
1231
        old_len = len(child)
1230
 
        if isinstance(child, LeafNode):
 
1232
        if type(child) is LeafNode:
1231
1233
            old_size = child._current_size()
1232
1234
        else:
1233
1235
            old_size = None
1239
1241
            self._items[search_key] = child
1240
1242
            self._key = None
1241
1243
            new_node = self
1242
 
            if isinstance(child, LeafNode):
 
1244
            if type(child) is LeafNode:
1243
1245
                if old_size is None:
1244
1246
                    # The old node was an InternalNode which means it has now
1245
1247
                    # collapsed, so we need to check if it will chain to a
1255
1257
                    # amount is over a configurable limit.
1256
1258
                    new_size = child._current_size()
1257
1259
                    shrinkage = old_size - new_size
1258
 
                    if (shrinkage > 0 and new_size < _INTERESTING_NEW_SIZE or
1259
 
                            shrinkage > _INTERESTING_SHRINKAGE_LIMIT):
 
1260
                    if (shrinkage > 0 and new_size < _INTERESTING_NEW_SIZE
 
1261
                        or shrinkage > _INTERESTING_SHRINKAGE_LIMIT):
1260
1262
                        trace.mutter(
1261
1263
                            "checking remap as size shrunk by %d to be %d",
1262
1264
                            shrinkage, new_size)
1263
1265
                        new_node = self._check_remap(store)
1264
1266
            if new_node._search_prefix is None:
1265
1267
                raise AssertionError("_search_prefix should not be None")
1266
 
            return new_node._search_prefix, [(b'', new_node)]
 
1268
            return new_node._search_prefix, [('', new_node)]
1267
1269
        # child has overflown - create a new intermediate node.
1268
1270
        # XXX: This is where we might want to try and expand our depth
1269
1271
        # to refer to more bytes of every child (which would give us
1274
1276
            child.add_node(split, node)
1275
1277
        self._len = self._len - old_len + len(child)
1276
1278
        self._key = None
1277
 
        return self._search_prefix, [(b"", self)]
 
1279
        return self._search_prefix, [("", self)]
1278
1280
 
1279
1281
    def _new_child(self, search_key, klass):
1280
1282
        """Create a new child node of type klass."""
1291
1293
        :param store: A VersionedFiles honouring the CHK extensions.
1292
1294
        :return: An iterable of the keys inserted by this operation.
1293
1295
        """
1294
 
        for node in self._items.values():
1295
 
            if isinstance(node, StaticTuple):
 
1296
        for node in self._items.itervalues():
 
1297
            if type(node) is StaticTuple:
1296
1298
                # Never deserialised.
1297
1299
                continue
1298
1300
            if node._key is not None:
1300
1302
                continue
1301
1303
            for key in node.serialise(store):
1302
1304
                yield key
1303
 
        lines = [b"chknode:\n"]
1304
 
        lines.append(b"%d\n" % self._maximum_size)
1305
 
        lines.append(b"%d\n" % self._key_width)
1306
 
        lines.append(b"%d\n" % self._len)
 
1305
        lines = ["chknode:\n"]
 
1306
        lines.append("%d\n" % self._maximum_size)
 
1307
        lines.append("%d\n" % self._key_width)
 
1308
        lines.append("%d\n" % self._len)
1307
1309
        if self._search_prefix is None:
1308
1310
            raise AssertionError("_search_prefix should not be None")
1309
 
        lines.append(b'%s\n' % (self._search_prefix,))
 
1311
        lines.append('%s\n' % (self._search_prefix,))
1310
1312
        prefix_len = len(self._search_prefix)
1311
1313
        for prefix, node in sorted(self._items.items()):
1312
 
            if isinstance(node, StaticTuple):
 
1314
            if type(node) is StaticTuple:
1313
1315
                key = node[0]
1314
1316
            else:
1315
1317
                key = node._key[0]
1316
 
            serialised = b"%s\x00%s\n" % (prefix, key)
 
1318
            serialised = "%s\x00%s\n" % (prefix, key)
1317
1319
            if not serialised.startswith(self._search_prefix):
1318
1320
                raise AssertionError("prefixes mismatch: %s must start with %s"
1319
 
                                     % (serialised, self._search_prefix))
 
1321
                    % (serialised, self._search_prefix))
1320
1322
            lines.append(serialised[prefix_len:])
1321
1323
        sha1, _, _ = store.add_lines((None,), (), lines)
1322
 
        self._key = StaticTuple(b"sha1:" + sha1,).intern()
1323
 
        _get_cache()[self._key] = b''.join(lines)
 
1324
        self._key = StaticTuple("sha1:" + sha1,).intern()
 
1325
        _get_cache().add(self._key, ''.join(lines))
1324
1326
        yield self._key
1325
1327
 
1326
1328
    def _search_key(self, key):
1327
1329
        """Return the serialised key for key in this node."""
1328
1330
        # search keys are fixed width. All will be self._node_width wide, so we
1329
1331
        # pad as necessary.
1330
 
        return (self._search_key_func(key) + b'\x00' * self._node_width)[:self._node_width]
 
1332
        return (self._search_key_func(key) + '\x00'*self._node_width)[:self._node_width]
1331
1333
 
1332
1334
    def _search_prefix_filter(self, key):
1333
1335
        """Serialise key for use as a prefix filter in iteritems."""
1341
1343
            prefix for reaching node.
1342
1344
        """
1343
1345
        if offset >= self._node_width:
1344
 
            for node in valueview(self._items):
 
1346
            for node in self._items.values():
1345
1347
                for result in node._split(offset):
1346
1348
                    yield result
 
1349
            return
 
1350
        for key, node in self._items.items():
 
1351
            pass
1347
1352
 
1348
1353
    def refs(self):
1349
1354
        """Return the references to other CHK's held by this node."""
1350
1355
        if self._key is None:
1351
1356
            raise AssertionError("unserialised nodes have no refs.")
1352
1357
        refs = []
1353
 
        for value in self._items.values():
1354
 
            if isinstance(value, StaticTuple):
 
1358
        for value in self._items.itervalues():
 
1359
            if type(value) is StaticTuple:
1355
1360
                refs.append(value)
1356
1361
            else:
1357
1362
                refs.append(value.key())
1367
1372
        return self._search_prefix
1368
1373
 
1369
1374
    def unmap(self, store, key, check_remap=True):
1370
 
        """Remove key from this node and its children."""
 
1375
        """Remove key from this node and it's children."""
1371
1376
        if not len(self._items):
1372
1377
            raise AssertionError("can't unmap in an empty InternalNode.")
1373
1378
        children = [node for node, _
1374
 
                    in self._iter_nodes(store, key_filter=[key])]
 
1379
                          in self._iter_nodes(store, key_filter=[key])]
1375
1380
        if children:
1376
1381
            child = children[0]
1377
1382
        else:
1389
1394
            self._items[search_key] = unmapped
1390
1395
        if len(self._items) == 1:
1391
1396
            # this node is no longer needed:
1392
 
            return list(self._items.values())[0]
1393
 
        if isinstance(unmapped, InternalNode):
 
1397
            return self._items.values()[0]
 
1398
        if type(unmapped) is InternalNode:
1394
1399
            return self
1395
1400
        if check_remap:
1396
1401
            return self._check_remap(store)
1436
1441
        #   c) With 255-way fan out, we don't want to read all 255 and destroy
1437
1442
        #      the page cache, just to determine that we really don't need it.
1438
1443
        for node, _ in self._iter_nodes(store, batch_size=16):
1439
 
            if isinstance(node, InternalNode):
 
1444
            if type(node) is InternalNode:
1440
1445
                # Without looking at any leaf nodes, we are sure
1441
1446
                return self
1442
 
            for key, value in node._items.items():
 
1447
            for key, value in node._items.iteritems():
1443
1448
                if new_leaf._map_no_split(key, value):
1444
1449
                    return self
1445
1450
        trace.mutter("remap generated a new LeafNode")
1446
1451
        return new_leaf
1447
1452
 
1448
1453
 
1449
 
def _deserialise(data, key, search_key_func):
 
1454
def _deserialise(bytes, key, search_key_func):
1450
1455
    """Helper for repositorydetails - convert bytes to a node."""
1451
 
    if data.startswith(b"chkleaf:\n"):
1452
 
        node = LeafNode.deserialise(data, key, search_key_func=search_key_func)
1453
 
    elif data.startswith(b"chknode:\n"):
1454
 
        node = InternalNode.deserialise(data, key,
1455
 
                                        search_key_func=search_key_func)
 
1456
    if bytes.startswith("chkleaf:\n"):
 
1457
        node = LeafNode.deserialise(bytes, key, search_key_func=search_key_func)
 
1458
    elif bytes.startswith("chknode:\n"):
 
1459
        node = InternalNode.deserialise(bytes, key,
 
1460
            search_key_func=search_key_func)
1456
1461
    else:
1457
1462
        raise AssertionError("Unknown node type.")
1458
1463
    return node
1521
1526
            bytes = record.get_bytes_as('fulltext')
1522
1527
            node = _deserialise(bytes, record.key,
1523
1528
                                search_key_func=self._search_key_func)
1524
 
            if isinstance(node, InternalNode):
 
1529
            if type(node) is InternalNode:
1525
1530
                # Note we don't have to do node.refs() because we know that
1526
1531
                # there are no children that have been pushed into this node
1527
1532
                # Note: Using as_st() here seemed to save 1.2MB, which would
1528
1533
                #       indicate that we keep 100k prefix_refs around while
1529
1534
                #       processing. They *should* be shorter lived than that...
1530
1535
                #       It does cost us ~10s of processing time
1531
 
                prefix_refs = list(node._items.items())
 
1536
                #prefix_refs = [as_st(item) for item in node._items.iteritems()]
 
1537
                prefix_refs = node._items.items()
1532
1538
                items = []
1533
1539
            else:
1534
1540
                prefix_refs = []
1535
1541
                # Note: We don't use a StaticTuple here. Profiling showed a
1536
1542
                #       minor memory improvement (0.8MB out of 335MB peak 0.2%)
1537
1543
                #       But a significant slowdown (15s / 145s, or 10%)
1538
 
                items = list(node._items.items())
 
1544
                items = node._items.items()
1539
1545
            yield record, node, prefix_refs, items
1540
1546
 
1541
1547
    def _read_old_roots(self):
1545
1551
                self._read_nodes_from_store(self._old_root_keys):
1546
1552
            # Uninteresting node
1547
1553
            prefix_refs = [p_r for p_r in prefix_refs
1548
 
                           if p_r[1] not in all_old_chks]
 
1554
                                if p_r[1] not in all_old_chks]
1549
1555
            new_refs = [p_r[1] for p_r in prefix_refs]
1550
1556
            all_old_chks.update(new_refs)
1551
1557
            # TODO: This might be a good time to turn items into StaticTuple
1565
1571
        # handled the interesting ones
1566
1572
        for prefix, ref in old_chks_to_enqueue:
1567
1573
            not_interesting = True
1568
 
            for i in range(len(prefix), 0, -1):
 
1574
            for i in xrange(len(prefix), 0, -1):
1569
1575
                if prefix[:i] in new_prefixes:
1570
1576
                    not_interesting = False
1571
1577
                    break
1601
1607
            # At this level, we now know all the uninteresting references
1602
1608
            # So we filter and queue up whatever is remaining
1603
1609
            prefix_refs = [p_r for p_r in prefix_refs
1604
 
                           if p_r[1] not in self._all_old_chks and
1605
 
                           p_r[1] not in processed_new_refs]
 
1610
                           if p_r[1] not in self._all_old_chks
 
1611
                              and p_r[1] not in processed_new_refs]
1606
1612
            refs = [p_r[1] for p_r in prefix_refs]
1607
1613
            new_prefixes.update([p_r[0] for p_r in prefix_refs])
1608
1614
            self._new_queue.extend(refs)
1614
1620
            #       self._new_item_queue will hold the contents of multiple
1615
1621
            #       records for an extended lifetime
1616
1622
            new_items = [item for item in items
1617
 
                         if item not in self._all_old_items]
 
1623
                               if item not in self._all_old_items]
1618
1624
            self._new_item_queue.extend(new_items)
1619
1625
            new_prefixes.update([self._search_key_func(item[0])
1620
1626
                                 for item in new_items])
1625
1631
        # 'ab', then we also need to include 'a'.) So expand the
1626
1632
        # new_prefixes to include all shorter prefixes
1627
1633
        for prefix in list(new_prefixes):
1628
 
            new_prefixes.update([prefix[:i] for i in range(1, len(prefix))])
 
1634
            new_prefixes.update([prefix[:i] for i in xrange(1, len(prefix))])
1629
1635
        self._enqueue_old(new_prefixes, old_chks_to_enqueue)
1630
1636
 
1631
1637
    def _flush_new_queue(self):
1638
1644
        processed_new_refs = self._processed_new_refs
1639
1645
        all_old_items = self._all_old_items
1640
1646
        new_items = [item for item in self._new_item_queue
1641
 
                     if item not in all_old_items]
 
1647
                           if item not in all_old_items]
1642
1648
        self._new_item_queue = []
1643
1649
        if new_items:
1644
1650
            yield None, new_items
1682
1688
        for record, _, prefix_refs, items in self._read_nodes_from_store(refs):
1683
1689
            # TODO: Use StaticTuple here?
1684
1690
            self._all_old_items.update(items)
1685
 
            refs = [r for _, r in prefix_refs if r not in all_old_chks]
 
1691
            refs = [r for _,r in prefix_refs if r not in all_old_chks]
1686
1692
            self._old_queue.extend(refs)
1687
1693
            all_old_chks.update(refs)
1688
1694
 
1720
1726
 
1721
1727
 
1722
1728
try:
1723
 
    from ._chk_map_pyx import (
 
1729
    from bzrlib._chk_map_pyx import (
1724
1730
        _bytes_to_text_key,
1725
1731
        _search_key_16,
1726
1732
        _search_key_255,
1727
1733
        _deserialise_leaf_node,
1728
1734
        _deserialise_internal_node,
1729
1735
        )
1730
 
except ImportError as e:
 
1736
except ImportError, e:
1731
1737
    osutils.failed_to_load_extension(e)
1732
 
    from ._chk_map_py import (
 
1738
    from bzrlib._chk_map_py import (
1733
1739
        _bytes_to_text_key,
1734
1740
        _search_key_16,
1735
1741
        _search_key_255,
1736
1742
        _deserialise_leaf_node,
1737
1743
        _deserialise_internal_node,
1738
 
        )  # noqa: F401
1739
 
search_key_registry.register(b'hash-16-way', _search_key_16)
1740
 
search_key_registry.register(b'hash-255-way', _search_key_255)
 
1744
        )
 
1745
search_key_registry.register('hash-16-way', _search_key_16)
 
1746
search_key_registry.register('hash-255-way', _search_key_255)
1741
1747
 
1742
1748
 
1743
1749
def _check_key(key):
1746
1752
    This generally shouldn't be used in production code, but it can be helpful
1747
1753
    to debug problems.
1748
1754
    """
1749
 
    if not isinstance(key, StaticTuple):
 
1755
    if type(key) is not StaticTuple:
1750
1756
        raise TypeError('key %r is not StaticTuple but %s' % (key, type(key)))
1751
1757
    if len(key) != 1:
1752
 
        raise ValueError('key %r should have length 1, not %d' %
1753
 
                         (key, len(key),))
1754
 
    if not isinstance(key[0], str):
 
1758
        raise ValueError('key %r should have length 1, not %d' % (key, len(key),))
 
1759
    if type(key[0]) is not str:
1755
1760
        raise TypeError('key %r should hold a str, not %r'
1756
1761
                        % (key, type(key[0])))
1757
1762
    if not key[0].startswith('sha1:'):
1758
1763
        raise ValueError('key %r should point to a sha1:' % (key,))
 
1764
 
 
1765